summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore4
-rw-r--r--README.md97
-rw-r--r--go.mod10
-rw-r--r--go.sum8
-rw-r--r--main.go498
-rwxr-xr-xscripts/fetch-model.sh16
-rw-r--r--web/index.html122
7 files changed, 755 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..20084b3
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+/models/
+/lilchinese
+*.mp4
+*.mkv
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..39b16ff
--- /dev/null
+++ b/README.md
@@ -0,0 +1,97 @@
+# lilchinese — live 高橋メソッド subtitles for spoken Chinese
+
+Speak Chinese into your mic → huge black-on-white Chinese phrases fill the screen,
+one short phrase at a time. 100% local: no Google, no cloud, no network at runtime.
+
+```
+parec (mic) ──► sherpa-onnx streaming zipformer (zh, int8) ──► SSE ──► Firefox kiosk
+ 20 ms reads offline, on CPU, decode chunk 320 ms local Noto Sans CJK SC Black
+```
+
+## Why this shape
+
+- **ASR in Go, pixels in the browser.** The Go side owns the audio path (a long-lived
+ stream that must not hiccup); the browser owns text layout, CJK font shaping, screen
+ fitting and fullscreen — things a Go GUI toolkit makes you fight for.
+- **Server-sent events, not WebSocket.** The stream is one-way, so SSE via `net/http`
+ needs zero dependencies and reconnects by itself.
+- **Firefox is fine.** Because recognition happens in the local binary, Firefox never
+ touches a speech service; it is only a renderer. (Firefox has no Web Speech API in
+ any case — which is exactly why the ASR lives here.)
+
+## Setup
+
+```sh
+./scripts/fetch-model.sh # 133 MB, int8 streaming zipformer, Chinese
+go build -o lilchinese . # needs gcc (cgo) + prebuilt sherpa-onnx libs
+```
+
+## Run
+
+```sh
+./lilchinese # mic → Firefox kiosk, fullscreen
+./lilchinese -record talk.mp4 # same, but also record screen + mic
+./lilchinese -wav speech.wav # play a file through the pipeline instead
+./lilchinese -debug # overlay "N字 340ms" in the corner
+```
+
+Exit kiosk with `Alt+F4` (there is no chrome to click). `Ctrl+C` in the terminal stops
+everything and finalizes a recording.
+
+Then just talk. Silence holds the last phrase on screen — that is the Takahashi rhythm:
+one short thought per screen, replaced on the next one.
+
+## Flags
+
+| flag | default | meaning |
+|---|---|---|
+| `-chars` | `9` | max characters per slide (the whole point: keep it short) |
+| `-preview` | `3` | don't replace a full slide with a shorter in-progress phrase than this |
+| `-source` | system default | PulseAudio source name (`pactl list short sources`) |
+| `-model` | auto-detect `models/` | model directory |
+| `-browser` | `firefox --kiosk {url}` | how to open the display; `{url}` substituted; empty = don't launch |
+| `-record` | off | ffmpeg: `x11grab` + `pulse` → h264/aac mp4 |
+| `-threads` | `2` | onnxruntime threads |
+| `-addr` | `127.0.0.1:8787` | HTTP/SSE listen address |
+| `-wav` | off | feed an audio file (paced realtime) instead of the mic |
+
+## Latency, honestly
+
+- Model lookahead: **320 ms** (`decode_chunk_len=32` frames in this model). Recognition
+ cannot show a syllable before its chunk is complete — that is the floor for any
+ streaming ASR.
+- Plumbing (audio read → SSE → paint): **~35 ms** measured (`ts - cap` in the SSE payload).
+- So: text appears roughly a third of a second behind your voice, then grows in 320 ms
+ steps. There is no zero-latency speech recognizer; this is about as close as it gets
+ while staying offline.
+
+To trade accuracy for latency, point `-model` at a CTC streaming model instead
+(`sherpa-onnx-streaming-zipformer-small-ctc-zh-int8-2025-04-01`, 21 MB) — non-autoregressive,
+smaller chunks, noticeably faster to emit, somewhat less accurate.
+
+## Look and feel
+
+- Font stack starts at `Noto Sans CJK SC Black` (already installed here); size is
+ auto-fitted so the phrase fills 90% × 86% of the screen, whatever its length.
+- Phrase changes slam in with a 90 ms scale/fade; refinements of the same phrase are
+ updated in place so the text doesn't flicker.
+- Design preview without a mic or model: open `web/index.html?text=现在我开始` in any browser.
+
+## Notes
+
+- Slides break on `,。、;:?!…` and at `-chars`, whichever comes first.
+- The binary links the shared libs from the Go module cache
+ (`rpath` → `.../pkg/mod/github.com/k2-fsa/sherpa-onnx-go-linux@v1.13.8/lib/...`).
+ If you wipe the module cache, rebuild.
+- Screen blanking will ruin a long talk: `xset s off -dpms`.
+- Recording captures the whole screen, so start it after the kiosk window is up
+ (it auto-delays 1.5 s).
+
+## Layout
+
+```
+main.go mic → ASR → slide splitting → SSE, recorder, browser launch
+web/index.html the whole UI (autofit, pop transition, EventSource client)
+scripts/fetch-model.sh
+models/ gitignored
+```
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..b2b6c75
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,10 @@
+module lilchinese
+
+go 1.27.4
+
+require (
+ github.com/k2-fsa/sherpa-onnx-go v1.13.8 // indirect
+ github.com/k2-fsa/sherpa-onnx-go-linux v1.13.8 // indirect
+ github.com/k2-fsa/sherpa-onnx-go-macos v1.13.8 // indirect
+ github.com/k2-fsa/sherpa-onnx-go-windows v1.13.8 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..689cdb1
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,8 @@
+github.com/k2-fsa/sherpa-onnx-go v1.13.8 h1:fyX96YdrMmK/DlBrGLmBat3OqRNsnVBFsRK5djCtVSg=
+github.com/k2-fsa/sherpa-onnx-go v1.13.8/go.mod h1:Sq4gTn8pkMsxfFPPFCBjmMzuRzWA8pHQUwW8gOp2OHs=
+github.com/k2-fsa/sherpa-onnx-go-linux v1.13.8 h1:33xcR9pYuD/VZ2luCWP1PJ4uLLeYM0i5GWGgM1lZjP8=
+github.com/k2-fsa/sherpa-onnx-go-linux v1.13.8/go.mod h1:NXEH2rsBgTdqY59YpPq6CtSBlBAXy/8a9FmpLERU97I=
+github.com/k2-fsa/sherpa-onnx-go-macos v1.13.8 h1:TQFOntGvoH+L+9HpmKukq6cDag674W7YQr3680KK0Q8=
+github.com/k2-fsa/sherpa-onnx-go-macos v1.13.8/go.mod h1:ZOhUAXC62Unj0ZNfu6zxSFKcW96aXf7P3BsqiUyOBbE=
+github.com/k2-fsa/sherpa-onnx-go-windows v1.13.8 h1:PjALQ7qHH6wmGyVeHMhGESh+EAtC/24rzZIth4PXcEs=
+github.com/k2-fsa/sherpa-onnx-go-windows v1.13.8/go.mod h1:5AX7TU8+P/gInjglY1ijtWUM2b8iyR0QX4yEngzMe64=
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..b7a7069
--- /dev/null
+++ b/main.go
@@ -0,0 +1,498 @@
+// lilchinese: live Takahashi-style (高橋メソッド) subtitles.
+//
+// Mic/file audio -> sherpa-onnx streaming Chinese ASR -> SSE -> fullscreen browser.
+// Everything runs locally; no network, no cloud ASR.
+package main
+
+import (
+ _ "embed"
+ "encoding/binary"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ sherpa "github.com/k2-fsa/sherpa-onnx-go/sherpa_onnx"
+)
+
+//go:embed web/index.html
+var indexHTML []byte
+
+// ---------------------------------------------------------------- broker (SSE fan-out)
+
+// Slide is one phrase to put on screen.
+type Slide struct {
+ Text string `json:"text"`
+ Seq int `json:"seq"`
+ TS int64 `json:"ts"` // published at (unix ms)
+ Cap int64 `json:"cap"` // audio chunk captured at (unix ms)
+}
+
+type broker struct {
+ mu sync.Mutex
+ seq int
+ cur Slide
+ subs map[chan Slide]struct{}
+ pubHi int
+}
+
+func newBroker() *broker { return &broker{subs: map[chan Slide]struct{}{}} }
+
+func (b *broker) publish(text string, capTS int64) {
+ if text == "" {
+ return
+ }
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if text == b.cur.Text {
+ return
+ }
+ b.seq++
+ s := Slide{Text: text, Seq: b.seq, TS: time.Now().UnixMilli(), Cap: capTS}
+ b.cur = s
+ for ch := range b.subs {
+ select {
+ case ch <- s:
+ default: // slow client: drop, SSE will not block the audio path
+ }
+ }
+}
+
+func (b *broker) subscribe() (chan Slide, Slide, func()) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ ch := make(chan Slide, 16)
+ b.subs[ch] = struct{}{}
+ cur := b.cur
+ return ch, cur, func() {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ delete(b.subs, ch)
+ close(ch)
+ }
+}
+
+func (b *broker) serveSSE(w http.ResponseWriter, r *http.Request) {
+ fl, ok := w.(http.Flusher)
+ if !ok {
+ http.Error(w, "streaming unsupported", http.StatusInternalServerError)
+ return
+ }
+ h := w.Header()
+ h.Set("Content-Type", "text/event-stream; charset=utf-8")
+ h.Set("Cache-Control", "no-cache")
+ h.Set("X-Accel-Buffering", "no")
+ w.WriteHeader(http.StatusOK)
+
+ ch, cur, unsub := b.subscribe()
+ defer unsub()
+
+ send := func(s Slide) bool {
+ bts, _ := json.Marshal(s)
+ if _, err := fmt.Fprintf(w, "data: %s\n\n", bts); err != nil {
+ return false
+ }
+ fl.Flush()
+ return true
+ }
+
+ if cur.Text != "" && !send(cur) {
+ return
+ }
+ ka := time.NewTicker(15 * time.Second)
+ defer ka.Stop()
+ for {
+ select {
+ case <-r.Context().Done():
+ return
+ case <-ka.C:
+ if _, err := io.WriteString(w, ": keepalive\n\n"); err != nil {
+ return
+ }
+ fl.Flush()
+ case s, ok := <-ch:
+ if !ok || !send(s) {
+ return
+ }
+ }
+ }
+}
+
+// ---------------------------------------------------------------- slide splitting
+
+const puncts = ",。、;:?!…—,.!?;:"
+
+func isBoundary(c rune) bool { return strings.ContainsRune(puncts, c) }
+
+func hasLatin(s string) bool {
+ return strings.ContainsFunc(s, func(r rune) bool {
+ return r < 0x2000 && (unicode.IsLetter(r) || unicode.IsDigit(r))
+ })
+}
+
+func cleanSlide(s string) string {
+ s = strings.TrimSpace(s)
+ s = strings.TrimRight(s, puncts+"  \t")
+ if !hasLatin(s) {
+ // Chinese ASR sometimes emits spaces between chars; Takahashi wants none.
+ s = strings.ReplaceAll(s, " ", "")
+ s = strings.ReplaceAll(s, "\u3000", "")
+ }
+ return strings.TrimSpace(s)
+}
+
+// presenter decides when text becomes a slide (Takahashi = short, whole-screen).
+type presenter struct {
+ max int // max characters per slide
+ preview int // don't replace a full slide with a shorter preview than this
+ emitted int // runes of the current utterance already turned into slides
+ b *broker
+}
+
+func (p *presenter) update(u string, capTS int64, endpoint bool) {
+ r := []rune(u)
+ if len(r) < p.emitted {
+ p.emitted = len(r) // hypothesis got revised shorter
+ }
+ for {
+ rest := r[p.emitted:]
+ if len(rest) == 0 {
+ break
+ }
+ cut := -1
+ for i, c := range rest {
+ if isBoundary(c) || i+1 >= p.max {
+ cut = i + 1
+ break
+ }
+ }
+ if cut < 0 {
+ break
+ }
+ slide := cleanSlide(string(rest[:cut]))
+ p.emitted += cut
+ if slide != "" {
+ p.b.publish(slide, capTS)
+ }
+ }
+ // Live tail: grows character by character while you keep talking. A very short
+ // tail would blank a full slide, so keep the previous phrase until it grows.
+ if tail := cleanSlide(string(r[p.emitted:])); tail != "" &&
+ (endpoint || utf8.RuneCountInString(tail) >= p.preview) {
+ p.b.publish(tail, capTS)
+ }
+ if endpoint {
+ p.emitted = 0
+ }
+}
+
+// ---------------------------------------------------------------- audio in
+
+func micCmd(source string) *exec.Cmd {
+ args := []string{
+ "--raw", "--format=s16le", "--rate=16000", "--channels=1",
+ "--latency-msec=20", "--client-name=lilchinese",
+ }
+ if source != "" {
+ args = append(args, "--device="+source)
+ }
+ return exec.Command("parec", args...)
+}
+
+func fileCmd(path string) *exec.Cmd {
+ return exec.Command("ffmpeg", "-hide_banner", "-loglevel", "error",
+ "-re", "-i", path,
+ "-f", "s16le", "-acodec", "pcm_s16le", "-ac", "1", "-ar", "16000", "-")
+}
+
+func runASR(cmd *exec.Cmd, rec *sherpa.OnlineRecognizer, stream *sherpa.OnlineStream, pres *presenter) error {
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ return err
+ }
+ cmd.Stderr = os.Stderr
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ defer func() {
+ if cmd.Process != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ }
+ }()
+
+ const chunk = 320 // samples per read: 20ms @16k -> low display latency
+ buf := make([]byte, chunk*2)
+ samples := make([]float32, chunk)
+ for {
+ if _, err := io.ReadFull(stdout, buf); err != nil {
+ return err
+ }
+ capTS := time.Now().UnixMilli()
+ for i := range samples {
+ samples[i] = float32(int16(binary.LittleEndian.Uint16(buf[2*i:]))) / 32768.0
+ }
+ stream.AcceptWaveform(16000, samples)
+ for rec.IsReady(stream) {
+ rec.Decode(stream)
+ }
+ text := ""
+ if res := rec.GetResult(stream); res != nil {
+ text = res.Text
+ }
+ ep := rec.IsEndpoint(stream)
+ pres.update(text, capTS, ep)
+ if ep {
+ rec.Reset(stream)
+ }
+ }
+}
+
+// ---------------------------------------------------------------- model loading
+
+func pickModelFile(dir, kind string) string {
+ for _, n := range []string{kind + ".int8.onnx", kind + ".onnx"} {
+ p := filepath.Join(dir, n)
+ if _, err := os.Stat(p); err == nil {
+ return p
+ }
+ }
+ m, _ := filepath.Glob(filepath.Join(dir, kind+"*.onnx"))
+ if len(m) > 0 {
+ return m[0]
+ }
+ return ""
+}
+
+func isModelDir(p string) bool {
+ return pickModelFile(p, "encoder") != "" && pickModelFile(p, "joiner") != "" &&
+ fileExists(filepath.Join(p, "tokens.txt"))
+}
+
+func fileExists(p string) bool { _, err := os.Stat(p); return err == nil }
+
+func candidateRoots() []string {
+ roots := []string{"models"}
+ if x := os.Getenv("XDG_DATA_HOME"); x != "" {
+ roots = append(roots, filepath.Join(x, "lilchinese", "models"))
+ }
+ if h := os.Getenv("HOME"); h != "" {
+ roots = append(roots, filepath.Join(h, ".local/share/lilchinese/models"))
+ }
+ if exe, err := os.Executable(); err == nil {
+ roots = append(roots, filepath.Join(filepath.Dir(exe), "models"))
+ }
+ return roots
+}
+
+func findModel(explicit string) (string, error) {
+ var cands []string
+ if explicit != "" {
+ cands = append(cands, explicit)
+ }
+ for _, root := range candidateRoots() {
+ m, _ := filepath.Glob(filepath.Join(root, "sherpa-onnx-streaming-*"))
+ cands = append(cands, m...)
+ }
+ for _, c := range cands {
+ if isModelDir(c) {
+ return c, nil
+ }
+ }
+ return "", fmt.Errorf("no sherpa-onnx streaming model found (looked in %s)",
+ strings.Join(candidateRoots(), ", "))
+}
+
+// ---------------------------------------------------------------- recording / browser
+
+func startRecorder(path, source string) (*exec.Cmd, error) {
+ disp := os.Getenv("DISPLAY")
+ if disp == "" {
+ disp = ":0"
+ }
+ if !strings.Contains(disp, ".") {
+ disp += ".0"
+ }
+ mic := "default"
+ if source != "" {
+ mic = source
+ }
+ args := []string{"-hide_banner", "-loglevel", "error", "-y",
+ "-f", "x11grab", "-framerate", "30", "-i", disp,
+ "-f", "pulse", "-i", mic,
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-pix_fmt", "yuv420p",
+ "-c:a", "aac", "-b:a", "160k",
+ "-movflags", "+faststart",
+ path,
+ }
+ cmd := exec.Command("ffmpeg", args...)
+ cmd.Stderr = os.Stderr
+ if err := cmd.Start(); err != nil {
+ return nil, err
+ }
+ return cmd, nil
+}
+
+func stopRecorder(cmd *exec.Cmd) {
+ if cmd == nil || cmd.Process == nil {
+ return
+ }
+ // SIGINT makes ffmpeg finalize the container instead of leaving a broken file.
+ cmd.Process.Signal(os.Interrupt)
+ done := make(chan struct{})
+ go func() { cmd.Wait(); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ cmd.Process.Kill()
+ }
+}
+
+func launchBrowser(tmpl, url string) {
+ line := strings.ReplaceAll(tmpl, "{url}", url)
+ f := strings.Fields(line)
+ if len(f) == 0 {
+ return
+ }
+ cmd := exec.Command(f[0], f[1:]...)
+ cmd.Stdout, cmd.Stderr = io.Discard, io.Discard
+ if err := cmd.Start(); err != nil {
+ log.Printf("cannot launch browser (%v); open %s manually", err, url)
+ return
+ }
+ go cmd.Wait()
+}
+
+// ---------------------------------------------------------------- main
+
+func main() {
+ log.SetFlags(0)
+ log.SetPrefix("lilchinese: ")
+
+ var (
+ modelDir = flag.String("model", "", "model directory (default: auto-detect under ./models)")
+ addr = flag.String("addr", "127.0.0.1:8787", "http listen address")
+ source = flag.String("source", "", "pulseaudio source name (default: system default mic)")
+ wav = flag.String("wav", "", "play this audio file through the ASR instead of the mic")
+ record = flag.String("record", "", "also record screen+mic to this file (.mp4/.mkv)")
+ browser = flag.String("browser", "firefox --kiosk {url}",
+ "command that opens the display, {url} substituted (empty: don't launch)")
+ threads = flag.Int("threads", 2, "onnxruntime threads")
+ chars = flag.Int("chars", 9, "max characters per slide")
+ preview = flag.Int("preview", 3, "min characters before the next phrase replaces the current slide")
+ debug = flag.Bool("debug", false, "show latency/char-count overlay")
+ )
+ flag.Parse()
+
+ md, err := findModel(*modelDir)
+ if err != nil {
+ log.Fatal(err, " (run scripts/fetch-model.sh)")
+ }
+
+ cfg := &sherpa.OnlineRecognizerConfig{
+ FeatConfig: sherpa.FeatureConfig{SampleRate: 16000, FeatureDim: 80},
+ ModelConfig: sherpa.OnlineModelConfig{
+ Transducer: sherpa.OnlineTransducerModelConfig{
+ Encoder: pickModelFile(md, "encoder"),
+ Decoder: pickModelFile(md, "decoder"),
+ Joiner: pickModelFile(md, "joiner"),
+ },
+ Tokens: filepath.Join(md, "tokens.txt"),
+ NumThreads: *threads,
+ Provider: "cpu",
+ },
+ DecodingMethod: "greedy_search",
+ EnableEndpoint: 1,
+ Rule1MinTrailingSilence: 2.4,
+ Rule2MinTrailingSilence: 1.2,
+ Rule3MinUtteranceLength: 20,
+ }
+ if *debug {
+ cfg.ModelConfig.Debug = 1
+ }
+ rec := sherpa.NewOnlineRecognizer(cfg)
+ if rec == nil {
+ log.Fatal("failed to load model from ", md)
+ }
+ stream := sherpa.NewOnlineStream(rec)
+
+ b := newBroker()
+ pres := &presenter{max: *chars, preview: *preview, b: b}
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/" {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Write(indexHTML)
+ })
+ mux.HandleFunc("/events", b.serveSSE)
+ srv := &http.Server{Addr: *addr, Handler: mux}
+ go func() {
+ if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+ log.Fatal(err)
+ }
+ }()
+
+ url := "http://" + *addr + "/"
+ if *debug {
+ url += "?debug=1"
+ }
+ log.Printf("model %s", filepath.Base(md))
+ log.Printf("open %s", url)
+ if *browser != "" {
+ launchBrowser(*browser, url)
+ }
+
+ var recCmd *exec.Cmd
+ if *record != "" {
+ time.Sleep(1500 * time.Millisecond) // let the window come up first
+ if recCmd, err = startRecorder(*record, *source); err != nil {
+ log.Printf("recording disabled: %v", err)
+ } else {
+ log.Printf("recording to %s (Ctrl+C to stop and finalize)", *record)
+ }
+ }
+
+ var stopOnce sync.Once
+ stop := func() {
+ stopOnce.Do(func() {
+ stopRecorder(recCmd)
+ if *record != "" {
+ log.Printf("saved %s", *record)
+ }
+ })
+ }
+
+ sig := make(chan os.Signal, 1)
+ signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
+ go func() {
+ <-sig
+ log.Print("stopping")
+ stop()
+ os.Exit(0)
+ }()
+
+ in := micCmd(*source)
+ if *wav != "" {
+ in = fileCmd(*wav)
+ }
+ if err := runASR(in, rec, stream, pres); err != nil {
+ log.Printf("input ended: %v", err)
+ }
+ stop()
+}
diff --git a/scripts/fetch-model.sh b/scripts/fetch-model.sh
new file mode 100755
index 0000000..5b1b570
--- /dev/null
+++ b/scripts/fetch-model.sh
@@ -0,0 +1,16 @@
+#!/bin/sh
+# Downloads a streaming Chinese ASR model for sherpa-onnx (int8, ~133 MB).
+set -eu
+name=sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30
+dest=${1:-models}
+mkdir -p "$dest"
+if [ -d "$dest/$name" ]; then
+ echo "already have $dest/$name"
+ exit 0
+fi
+url="https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/$name.tar.bz2"
+echo "downloading $url"
+curl -L --fail -o "$dest/$name.tar.bz2" "$url"
+tar -xjf "$dest/$name.tar.bz2" -C "$dest"
+rm -f "$dest/$name.tar.bz2"
+ls "$dest/$name"
diff --git a/web/index.html b/web/index.html
new file mode 100644
index 0000000..4838047
--- /dev/null
+++ b/web/index.html
@@ -0,0 +1,122 @@
+<!doctype html>
+<html lang="zh-Hans">
+<head>
+<meta charset="utf-8">
+<title>lilchinese</title>
+<style>
+ :root { --pad-y: 7vh; --pad-x: 5vw; }
+ html, body {
+ margin: 0; padding: 0; height: 100%; overflow: hidden;
+ background: #fff; color: #000; cursor: none;
+ -webkit-user-select: none; user-select: none;
+ font-family: "Noto Sans CJK SC Black", "Noto Sans SC Black", "Source Han Sans SC",
+ "Noto Sans CJK JP Black", "PingFang SC", sans-serif;
+ }
+ #wrap {
+ position: fixed; inset: 0; box-sizing: border-box;
+ padding: var(--pad-y) var(--pad-x);
+ display: flex; align-items: center; justify-content: center;
+ }
+ #t {
+ font-weight: 900;
+ line-height: 1.04;
+ letter-spacing: .02em;
+ text-align: center;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ text-wrap: balance;
+ max-width: 100%;
+ will-change: font-size;
+ }
+ @keyframes pop {
+ from { opacity: .5; transform: scale(.955); }
+ to { opacity: 1; transform: scale(1); }
+ }
+ #t.pop { animation: pop 90ms ease-out; }
+ #d {
+ position: fixed; right: 12px; bottom: 10px; display: none;
+ font: 12px/1.4 ui-monospace, monospace; color: #bbb; letter-spacing: 0;
+ }
+</style>
+</head>
+<body>
+<div id="wrap"><div id="t"></div></div>
+<div id="d"></div>
+<script>
+(function () {
+ const wrap = document.getElementById('wrap');
+ const t = document.getElementById('t');
+ const d = document.getElementById('d');
+ const q = new URLSearchParams(location.search);
+ const debug = q.has('debug');
+ if (debug) d.style.display = 'block';
+
+ let cur = '';
+ let padW = 0, padH = 0;
+
+ function measurePad() {
+ const cs = getComputedStyle(wrap);
+ padW = parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);
+ padH = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom);
+ }
+
+ // Largest font size at which the whole phrase still fits the screen.
+ function fit() {
+ const boxW = wrap.clientWidth - padW;
+ const boxH = wrap.clientHeight - padH;
+ if (boxW <= 0 || boxH <= 0) return;
+ let lo = 8, hi = Math.max(boxW, boxH) * 1.7;
+ for (let i = 0; i < 18; i++) {
+ const mid = (lo + hi) / 2;
+ t.style.fontSize = mid + 'px';
+ const r = t.getBoundingClientRect();
+ if (r.width <= boxW && r.height <= boxH) lo = mid; else hi = mid;
+ }
+ t.style.fontSize = Math.floor(lo) + 'px';
+ }
+
+ function render(text, cap) {
+ if (!text || text === cur) return;
+ const growing = cur.length > 0 && text.startsWith(cur);
+ t.textContent = text;
+ if (!growing) {
+ // New phrase: slam it in. Refinements just update in place (no flicker).
+ t.classList.remove('pop');
+ void t.offsetWidth;
+ t.classList.add('pop');
+ }
+ cur = text;
+ fit();
+ if (debug) {
+ const lat = cap ? (Date.now() - cap) : 0;
+ d.textContent = text.length + '\u5b57 ' + (cap ? lat + 'ms' : '');
+ }
+ }
+
+ addEventListener('resize', function () { measurePad(); fit(); });
+ addEventListener('keydown', function (e) {
+ if (e.key === 'f' || e.key === 'F') {
+ if (document.fullscreenElement) document.exitFullscreen();
+ else document.documentElement.requestFullscreen();
+ }
+ });
+
+ measurePad();
+
+ if (q.has('text')) {
+ render(q.get('text'), 0); // design preview: index.html?text=你好世界
+ return;
+ }
+
+ const es = new EventSource('/events');
+ es.onmessage = function (e) {
+ try {
+ const s = JSON.parse(e.data);
+ render(s.text, s.cap);
+ } catch (_) {}
+ };
+ es.onerror = function () { /* EventSource reconnects on its own; keep the last phrase up */ };
+})();
+</script>
+</body>
+</html>