summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorwuhei <wuhei@users.noreply.github.com>2026-11-19 12:38:24 +0100
committerwuhei <wuhei@users.noreply.github.com>2026-11-19 12:38:24 +0100
commita5b77eb48974cfae45bac65ceb4880752444eb47 (patch)
treea71b85b54273a2d7893b90acfab43f52325e5db2
parent10ee627143419d6e9c9186fbb0a023a34b08948e (diff)
downloadlilchinese-a5b77eb48974cfae45bac65ceb4880752444eb47.tar.gz
english subtitles from a local translation model
Optional second line under the Chinese, translated on the machine: - -translate-model spawns llama-server (free port, /health wait, SIGTERM on exit) and uses Hy-MT2-1.8B (Tencent Hunyuan MT) — a dedicated zh→en model, 30 tok/s on CPU, so a phrase lands in 0.5-0.8s - -translate points at an already running OpenAI-compatible endpoint (ollama, LM Studio, llama-server) - the English line is sticky rather than tied to the 9 characters on screen: no LLM can keep up with a slide that lives 0.3s, so the translation lags by about one model call and never blanks between phrases - -translate-window (28 chars) trades context for latency; translations cached - phrase text is debounced 200ms and coalesced latest-wins so growth does not queue up dozens of requests - display reserves the English line only when translation is enabled, so the Chinese layout is unchanged without it; autofit now fits both lines
-rw-r--r--README.md54
-rw-r--r--main.go105
-rwxr-xr-xscripts/fetch-mt-model.sh16
-rw-r--r--translate.go284
-rw-r--r--web/index.html97
5 files changed, 526 insertions, 30 deletions
diff --git a/README.md b/README.md
index 39b16ff..694bdab 100644
--- a/README.md
+++ b/README.md
@@ -6,6 +6,8 @@ one short phrase at a time. 100% local: no Google, no cloud, no network at runti
```
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
+ │
+ └─► (optional) llama-server + Hy-MT2-1.8B ──► English line
```
## Why this shape
@@ -24,6 +26,9 @@ parec (mic) ──► sherpa-onnx streaming zipformer (zh, int8) ──► S
```sh
./scripts/fetch-model.sh # 133 MB, int8 streaming zipformer, Chinese
go build -o lilchinese . # needs gcc (cgo) + prebuilt sherpa-onnx libs
+
+./scripts/fetch-mt-model.sh # optional: 1.1 GB Hy-MT2-1.8B for English subtitles
+ # (needs llama-server from llama.cpp on PATH)
```
## Run
@@ -41,6 +46,42 @@ 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.
+## English subtitles (optional)
+
+Pass a local translation model and every phrase gets an English line underneath,
+translated on your own machine:
+
+```sh
+./lilchinese -translate-model models/mt/Hy-MT2-1.8B-Q4_K_M.gguf
+./lilchinese -translate-model models/mt/Hy-MT2-1.8B-Q4_K_M.gguf -record talk.mp4
+```
+
+`-translate-model` spawns `llama-server` itself (free port, waits for `/health`,
+killed on exit, log in `~/.cache/lilchinese/llama-server.log`). If you already run an
+OpenAI-compatible endpoint — llama-server, ollama, LM Studio — point at it instead and
+skip the spawn:
+
+```sh
+./lilchinese -translate http://127.0.0.1:11434 # ollama also speaks /v1/chat/completions
+./lilchinese -translate http://127.0.0.1:8080 -prompt '将以下文本翻译成英语:{text}'
+```
+
+How it behaves, and why:
+
+- **Hy-MT2-1.8B** is a dedicated zh→en translation model, which matters here: slides are
+ 9-character fragments, and general chat models (Qwen, GPT-class) hallucinate context
+ around fragments while claiming to translate. On this CPU it does **29–32 tok/s**, so a
+ phrase lands in **0.5–0.8 s**.
+- The English line is **sticky**: it is not tied to the 9 characters currently on screen.
+ A slide lives ~0.3 s while speaking continuously — no LLM can keep up with that, so the
+ translation lags the speaker by roughly one model call and updates as the sentence
+ grows, like an interpreter. It never blanks between phrases.
+- `-translate-window` (default 28) is how many characters of speech go to the model.
+ Larger = smoother/more context but slower; smaller = snappier, choppier fragments.
+- Translations are cached per phrase, so repeated words cost nothing.
+- Without `-translate`/`-translate-model` the page is laid out exactly as before — the
+ English line is only reserved when `?en=1` is passed to the page.
+
## Flags
| flag | default | meaning |
@@ -54,6 +95,11 @@ one short thought per screen, replaced on the next one.
| `-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 |
+| `-translate-model` | off | spawn llama-server with this `.gguf` for English subtitles |
+| `-translate` | off | use an already running OpenAI-compatible endpoint |
+| `-translate-window` | `28` | characters of speech sent to the translator |
+| `-prompt` | Hy-MT template | translation prompt, `{text}` substituted |
+| `-llama-server` / `-llama-args` / `-llama-threads` | `llama-server` / — / half the cores | spawned backend tuning |
## Latency, honestly
@@ -64,6 +110,8 @@ one short thought per screen, replaced on the next one.
- 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.
+- English is a second, slower lane: +0.5–0.8 s per phrase with Hy-MT2-1.8B on CPU
+ (`prompt_ms` ~300 ms warm, 30 tok/s decode). It rides along with each slide update.
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,
@@ -75,7 +123,8 @@ smaller chunks, noticeably faster to emit, somewhat less accurate.
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.
+- Design preview without a mic or model: open `web/index.html?text=现在我开始` in any
+ browser, and `web/index.html?en=1&text=现在我开始&t=Now I begin` to preview both lines.
## Notes
@@ -91,7 +140,8 @@ smaller chunks, noticeably faster to emit, somewhat less accurate.
```
main.go mic → ASR → slide splitting → SSE, recorder, browser launch
+translate.go optional local MT: llama-server supervision, debounce, sticky EN line
web/index.html the whole UI (autofit, pop transition, EventSource client)
-scripts/fetch-model.sh
+scripts/ fetch-model.sh (ASR), fetch-mt-model.sh (translation)
models/ gitignored
```
diff --git a/main.go b/main.go
index b7a7069..ab20108 100644
--- a/main.go
+++ b/main.go
@@ -17,6 +17,7 @@ import (
"os/exec"
"os/signal"
"path/filepath"
+ "runtime"
"strings"
"sync"
"syscall"
@@ -35,6 +36,7 @@ var indexHTML []byte
// Slide is one phrase to put on screen.
type Slide struct {
Text string `json:"text"`
+ EN string `json:"en,omitempty"`
Seq int `json:"seq"`
TS int64 `json:"ts"` // published at (unix ms)
Cap int64 `json:"cap"` // audio chunk captured at (unix ms)
@@ -46,6 +48,11 @@ type broker struct {
cur Slide
subs map[chan Slide]struct{}
pubHi int
+
+ // curEN is the English subtitle currently shown. It is sticky: a translation
+ // survives the slides that happen while the next one is being produced, so the
+ // English line lags the speaker by roughly one model call instead of blinking.
+ curEN string
}
func newBroker() *broker { return &broker{subs: map[chan Slide]struct{}{}} }
@@ -55,12 +62,13 @@ func (b *broker) publish(text string, capTS int64) {
return
}
b.mu.Lock()
- defer b.mu.Unlock()
if text == b.cur.Text {
+ // Same phrase, but a translation may now be stale-free: keep as is.
+ b.mu.Unlock()
return
}
b.seq++
- s := Slide{Text: text, Seq: b.seq, TS: time.Now().UnixMilli(), Cap: capTS}
+ s := Slide{Text: text, EN: b.curEN, Seq: b.seq, TS: time.Now().UnixMilli(), Cap: capTS}
b.cur = s
for ch := range b.subs {
select {
@@ -68,6 +76,37 @@ func (b *broker) publish(text string, capTS int64) {
default: // slow client: drop, SSE will not block the audio path
}
}
+ b.mu.Unlock()
+}
+
+// publishEN replaces the English subtitle under the current Chinese phrase.
+func (b *broker) publishEN(en string) {
+ if en == "" {
+ return
+ }
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if b.curEN == en {
+ return
+ }
+ b.curEN = en
+ b.seq++
+ s := b.cur
+ s.EN = en
+ s.Seq = b.seq
+ b.cur = s
+ for ch := range b.subs {
+ select {
+ case ch <- s:
+ default:
+ }
+ }
+}
+
+func (b *broker) currentText() string {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.cur.Text
}
func (b *broker) subscribe() (chan Slide, Slide, func()) {
@@ -159,6 +198,11 @@ type presenter struct {
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
+
+ // onUtterance receives the whole phrase being spoken (not just the slide), which
+ // is what gets translated: a 9-character window is not enough context for MT.
+ onUtterance func(string)
+ lastU string
}
func (p *presenter) update(u string, capTS int64, endpoint bool) {
@@ -193,8 +237,13 @@ func (p *presenter) update(u string, capTS int64, endpoint bool) {
(endpoint || utf8.RuneCountInString(tail) >= p.preview) {
p.b.publish(tail, capTS)
}
+ if p.onUtterance != nil && u != p.lastU && strings.TrimSpace(u) != "" {
+ p.lastU = u
+ p.onUtterance(strings.TrimSpace(u))
+ }
if endpoint {
p.emitted = 0
+ p.lastU = ""
}
}
@@ -393,6 +442,14 @@ func main() {
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")
+
+ trModel = flag.String("translate-model", "", "spawn llama-server with this .gguf and translate every slide into English")
+ trURL = flag.String("translate", "", "use an already running OpenAI-compatible endpoint for English (e.g. http://127.0.0.1:8080)")
+ trPrompt = flag.String("prompt", defaultPrompt, "translation prompt; {text} is substituted")
+ trWindow = flag.Int("translate-window", 28, "characters of speech sent to the translator (bigger = smoother, slower)")
+ llamaBin = flag.String("llama-server", "llama-server", "llama-server binary")
+ llamaArgs = flag.String("llama-args", "", "extra arguments for llama-server")
+ llamaThr = flag.Int("llama-threads", 0, "threads for the translation model (0 = half the cores)")
)
flag.Parse()
@@ -431,6 +488,31 @@ func main() {
b := newBroker()
pres := &presenter{max: *chars, preview: *preview, b: b}
+ // Optional English subtitles from a local model.
+ var llamaCmd *exec.Cmd
+ endpoint := ""
+ if *trURL != "" {
+ endpoint = normalizeEndpoint(*trURL)
+ } else if *trModel != "" {
+ var err error
+ mtThreads := *llamaThr
+ if mtThreads <= 0 {
+ mtThreads = max(4, runtime.NumCPU()/2)
+ }
+ if endpoint, llamaCmd, err = startLlamaServer(*llamaBin, *trModel, *llamaArgs, mtThreads); err != nil {
+ log.Printf("translations disabled: %v", err)
+ endpoint = ""
+ } else {
+ log.Printf("translating with %s", filepath.Base(*trModel))
+ }
+ }
+ var tr *translator
+ if endpoint != "" {
+ tr = newTranslator(endpoint, *trPrompt, b, *debug)
+ pres.onUtterance = func(u string) { tr.request(contextWindow(u, *trWindow)) }
+ go tr.run()
+ }
+
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
@@ -449,8 +531,15 @@ func main() {
}()
url := "http://" + *addr + "/"
+ var qs []string
if *debug {
- url += "?debug=1"
+ qs = append(qs, "debug=1")
+ }
+ if tr != nil {
+ qs = append(qs, "en=1")
+ }
+ if len(qs) > 0 {
+ url += "?" + strings.Join(qs, "&")
}
log.Printf("model %s", filepath.Base(md))
log.Printf("open %s", url)
@@ -472,6 +561,16 @@ func main() {
stop := func() {
stopOnce.Do(func() {
stopRecorder(recCmd)
+ if llamaCmd != nil && llamaCmd.Process != nil {
+ llamaCmd.Process.Signal(syscall.SIGTERM)
+ done := make(chan struct{})
+ go func() { llamaCmd.Wait(); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ llamaCmd.Process.Kill()
+ }
+ }
if *record != "" {
log.Printf("saved %s", *record)
}
diff --git a/scripts/fetch-mt-model.sh b/scripts/fetch-mt-model.sh
new file mode 100755
index 0000000..674899e
--- /dev/null
+++ b/scripts/fetch-mt-model.sh
@@ -0,0 +1,16 @@
+#!/bin/sh
+# Optional: local English subtitles. Hy-MT2-1.8B (Tencent Hunyuan MT, Q4_K_M, ~1.1 GB)
+# is a dedicated translation model — small, fast, and much better on short fragments
+# than a general chat model. Needs llama-server (llama.cpp) on PATH.
+set -eu
+dest=${1:-models/mt}
+name=Hy-MT2-1.8B-Q4_K_M.gguf
+base=https://huggingface.co/tencent/Hy-MT2-1.8B-GGUF/resolve/main
+mkdir -p "$dest"
+if [ -f "$dest/$name" ]; then
+ echo "already have $dest/$name"
+ exit 0
+fi
+echo "downloading $name (~1.1 GB)"
+curl -L --fail -C - -o "$dest/$name" "$base/$name"
+ls -la "$dest/$name"
diff --git a/translate.go b/translate.go
new file mode 100644
index 0000000..66cee26
--- /dev/null
+++ b/translate.go
@@ -0,0 +1,284 @@
+package main
+
+// Optional English subtitles: the Chinese slide is sent to a local,
+// OpenAI-compatible chat endpoint (llama-server / ollama / anything else) and the
+// translation is pushed to the display under the Chinese. Off by default; nothing
+// leaves the machine either way.
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "os"
+ "os/exec"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Prompt tuned for Hy-MT (Tencent Hunyuan MT) — the recommended local model.
+const defaultPrompt = "将以下文本翻译成英语,注意只需要输出翻译后的结果,不要额外解释:\n\n{text}"
+
+type translator struct {
+ endpoint string // full .../v1/chat/completions URL
+ prompt string
+ client *http.Client
+ b *broker
+
+ debounce time.Duration
+ kick chan string
+
+ mu sync.Mutex
+ cache map[string]string
+
+ debug bool
+}
+
+func newTranslator(endpoint, prompt string, b *broker, debug bool) *translator {
+ if prompt == "" {
+ prompt = defaultPrompt
+ }
+ return &translator{
+ endpoint: endpoint,
+ prompt: prompt,
+ client: &http.Client{Timeout: 15 * time.Second},
+ b: b,
+ debounce: 200 * time.Millisecond,
+ kick: make(chan string, 1),
+ cache: map[string]string{},
+ debug: debug,
+ }
+}
+
+// request is called from the audio path; it must never block.
+func (t *translator) request(text string) {
+ if text == "" {
+ return
+ }
+ t.mu.Lock()
+ en, ok := t.cache[text]
+ t.mu.Unlock()
+ if ok {
+ t.b.publishEN(en)
+ return
+ }
+ // latest wins: replace whatever is queued
+ for {
+ select {
+ case t.kick <- text:
+ return
+ default:
+ }
+ select {
+ case <-t.kick:
+ default:
+ }
+ }
+}
+
+func (t *translator) run() {
+ for {
+ text, ok := <-t.kick
+ if !ok {
+ return
+ }
+ // Coalesce the char-by-char slide growth: translate once the text has been
+ // stable for a moment, so we translate what is actually on screen.
+ debounce:
+ for {
+ select {
+ case text = <-t.kick:
+ case <-time.After(t.debounce):
+ break debounce
+ }
+ }
+ en, err := t.translate(text)
+ if err != nil {
+ if t.debug {
+ log.Printf("translate %q: %v", text, err)
+ }
+ continue
+ }
+ if en == "" {
+ continue
+ }
+ t.mu.Lock()
+ t.cache[text] = en
+ t.mu.Unlock()
+ t.b.publishEN(en)
+ }
+}
+
+func (t *translator) translate(text string) (string, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+ defer cancel()
+
+ payload := map[string]any{
+ "temperature": 0,
+ "max_tokens": 96,
+ "stream": false,
+ "messages": []map[string]string{
+ {"role": "user", "content": strings.ReplaceAll(t.prompt, "{text}", text)},
+ },
+ }
+ body, _ := json.Marshal(payload)
+ start := time.Now()
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.endpoint, bytes.NewReader(body))
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := t.client.Do(req)
+ if err != nil {
+ return "", err
+ }
+ defer resp.Body.Close()
+ raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ if resp.StatusCode != http.StatusOK {
+ return "", fmt.Errorf("%s: %s", resp.Status, strings.TrimSpace(string(raw[:min(len(raw), 200)])))
+ }
+ var out struct {
+ Choices []struct {
+ Message struct {
+ Content string `json:"content"`
+ } `json:"message"`
+ } `json:"choices"`
+ }
+ if err := json.Unmarshal(raw, &out); err != nil {
+ return "", err
+ }
+ if len(out.Choices) == 0 {
+ return "", fmt.Errorf("empty completion")
+ }
+ en := cleanTranslation(out.Choices[0].Message.Content)
+ if t.debug {
+ log.Printf("translate %q -> %q (%dms)", text, en, time.Since(start).Milliseconds())
+ }
+ return en, nil
+}
+
+// contextWindow bounds how much text goes to the model: the last clause or two,
+// so a long monologue does not turn into a paragraph of English under 9 characters
+// of Chinese. Splitting on punctuation keeps the input linguistically sensible.
+func contextWindow(u string, maxRunes int) string {
+ r := []rune(strings.TrimSpace(u))
+ if len(r) > maxRunes {
+ cut := len(r) - maxRunes
+ // prefer to start at a clause boundary inside the window
+ for i := cut; i < len(r) && i < cut+12; i++ {
+ if strings.ContainsRune(puncts, r[i]) {
+ cut = i + 1
+ break
+ }
+ }
+ r = r[cut:]
+ }
+ return strings.TrimSpace(strings.TrimLeft(string(r), puncts+" "))
+}
+
+// cleanTranslation keeps one short line of plain text.
+func cleanTranslation(s string) string {
+ s = strings.TrimSpace(s)
+ if i := strings.IndexAny(s, "\r\n"); i >= 0 {
+ s = s[:i]
+ }
+ s = strings.TrimSpace(s)
+ s = strings.Trim(s, "\"'“”‘’")
+ // Models like to reintroduce the "Translation:" label despite instructions.
+ for _, p := range []string{"Translation:", "English:", "英文:", "翻译:", "译文:"} {
+ if strings.HasPrefix(s, p) {
+ s = strings.TrimSpace(strings.TrimPrefix(s, p))
+ }
+ }
+ return s
+}
+
+// ---------------------------------------------------------------- llama-server management
+
+func normalizeEndpoint(s string) string {
+ s = strings.TrimRight(s, "/")
+ if strings.HasSuffix(s, "/v1/chat/completions") {
+ return s
+ }
+ if strings.HasSuffix(s, "/v1") {
+ return s + "/chat/completions"
+ }
+ return s + "/v1/chat/completions"
+}
+
+func freePort() (int, error) {
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ return 0, err
+ }
+ defer l.Close()
+ return l.Addr().(*net.TCPAddr).Port, nil
+}
+
+// startLlamaServer launches a local llama-server for `model` and waits until it is
+// healthy. It returns the chat endpoint and the process for shutdown.
+func startLlamaServer(bin, model, extraArgs string, threads int) (string, *exec.Cmd, error) {
+ port, err := freePort()
+ if err != nil {
+ return "", nil, err
+ }
+ if !fileExists(model) {
+ return "", nil, fmt.Errorf("model not found: %s", model)
+ }
+ args := []string{
+ "-m", model,
+ "--host", "127.0.0.1",
+ "--port", strconv.Itoa(port),
+ "--ctx-size", "1024",
+ "--no-webui",
+ "-t", strconv.Itoa(threads),
+ }
+ if extraArgs != "" {
+ args = append(args, strings.Fields(extraArgs)...)
+ }
+ cmd := exec.Command(bin, args...)
+ logPath := ""
+ if dir, err := os.UserCacheDir(); err == nil {
+ dir = dir + "/lilchinese"
+ if os.MkdirAll(dir, 0o755) == nil {
+ logPath = dir + "/llama-server.log"
+ }
+ }
+ if logPath != "" {
+ if f, err := os.Create(logPath); err == nil {
+ defer f.Close()
+ cmd.Stdout, cmd.Stderr = f, f
+ log.Printf("llama-server log: %s", logPath)
+ }
+ }
+ if err := cmd.Start(); err != nil {
+ return "", nil, err
+ }
+
+ base := fmt.Sprintf("http://127.0.0.1:%d", port)
+ deadline := time.Now().Add(3 * time.Minute)
+ for time.Now().Before(deadline) {
+ if cmd.ProcessState != nil && cmd.ProcessState.Exited() {
+ return "", cmd, fmt.Errorf("llama-server exited during load (see %s)", logPath)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, base+"/health", nil)
+ resp, err := http.DefaultClient.Do(req)
+ if err == nil {
+ resp.Body.Close()
+ if resp.StatusCode == http.StatusOK {
+ cancel()
+ return base + "/v1/chat/completions", cmd, nil
+ }
+ }
+ cancel()
+ time.Sleep(300 * time.Millisecond)
+ }
+ return "", cmd, fmt.Errorf("llama-server did not become ready (see %s)", logPath)
+}
diff --git a/web/index.html b/web/index.html
index 4838047..5179370 100644
--- a/web/index.html
+++ b/web/index.html
@@ -4,7 +4,7 @@
<meta charset="utf-8">
<title>lilchinese</title>
<style>
- :root { --pad-y: 7vh; --pad-x: 5vw; }
+ :root { --pad-y: 6vh; --pad-x: 5vw; }
html, body {
margin: 0; padding: 0; height: 100%; overflow: hidden;
background: #fff; color: #000; cursor: none;
@@ -17,7 +17,8 @@
padding: var(--pad-y) var(--pad-x);
display: flex; align-items: center; justify-content: center;
}
- #t {
+ #stack { display: flex; flex-direction: column; align-items: center; max-width: 100%; }
+ #zh {
font-weight: 900;
line-height: 1.04;
letter-spacing: .02em;
@@ -28,11 +29,24 @@
max-width: 100%;
will-change: font-size;
}
+ #en {
+ font-family: "Noto Sans", "Inter", "DejaVu Sans", sans-serif;
+ font-weight: 500;
+ line-height: 1.18;
+ text-align: center;
+ white-space: pre-wrap;
+ overflow-wrap: break-word;
+ max-width: 100%;
+ margin-top: .28em;
+ opacity: .88;
+ display: none;
+ }
+ body.en #en { display: block; }
@keyframes pop {
from { opacity: .5; transform: scale(.955); }
to { opacity: 1; transform: scale(1); }
}
- #t.pop { animation: pop 90ms ease-out; }
+ .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;
@@ -40,19 +54,25 @@
</style>
</head>
<body>
-<div id="wrap"><div id="t"></div></div>
+<div id="wrap"><div id="stack"><div id="zh"></div><div id="en"></div></div></div>
<div id="d"></div>
<script>
(function () {
const wrap = document.getElementById('wrap');
- const t = document.getElementById('t');
+ const stack = document.getElementById('stack');
+ const zh = document.getElementById('zh');
+ const en = document.getElementById('en');
const d = document.getElementById('d');
const q = new URLSearchParams(location.search);
const debug = q.has('debug');
+ const wantEN = q.has('en');
if (debug) d.style.display = 'block';
+ if (wantEN) document.body.classList.add('en');
- let cur = '';
+ let curZh = '', curEn = '';
let padW = 0, padH = 0;
+ const EN_RATIO = 0.30;
+ const EN_MAX = 120; // keep the English line from crowding out the Chinese
function measurePad() {
const cs = getComputedStyle(wrap);
@@ -60,36 +80,63 @@
padH = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom);
}
- // Largest font size at which the whole phrase still fits the screen.
+ function setSizes(s) {
+ zh.style.fontSize = s + 'px';
+ en.style.fontSize = Math.max(11, Math.round(s * EN_RATIO)) + 'px';
+ }
+
+ // Largest Chinese font size at which Chinese + English still fit the screen.
function fit() {
const boxW = wrap.clientWidth - padW;
const boxH = wrap.clientHeight - padH;
if (boxW <= 0 || boxH <= 0) return;
+ // Reserve the English line even before its translation lands, so the Chinese
+ // text does not jump in size when the translation appears.
+ const reserve = wantEN && !curEn;
+ if (reserve) en.textContent = '\u00a0';
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();
+ setSizes(mid);
+ const r = stack.getBoundingClientRect();
if (r.width <= boxW && r.height <= boxH) lo = mid; else hi = mid;
}
- t.style.fontSize = Math.floor(lo) + 'px';
+ setSizes(Math.floor(lo));
+ if (reserve) en.textContent = '';
}
- 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');
+ function render(text, translation, cap) {
+ if (!text) return;
+ const newPhrase = text !== curZh;
+ const growing = !newPhrase ? false
+ : (curZh.length > 0 && text.startsWith(curZh));
+
+ if (newPhrase) {
+ curZh = text;
+ zh.textContent = text;
+ if (!growing) {
+ // New phrase: slam it in. Refinements just update in place (no flicker).
+ zh.classList.remove('pop');
+ void zh.offsetWidth;
+ zh.classList.add('pop');
+ }
+ }
+ let tr = translation || '';
+ if (tr.length > EN_MAX) tr = tr.slice(0, EN_MAX - 1).trimEnd() + '\u2026';
+ if (tr !== curEn) {
+ curEn = tr;
+ en.textContent = tr;
+ if (tr && newPhrase) {
+ en.classList.remove('pop');
+ void en.offsetWidth;
+ en.classList.add('pop');
+ }
}
- cur = text;
fit();
if (debug) {
const lat = cap ? (Date.now() - cap) : 0;
- d.textContent = text.length + '\u5b57 ' + (cap ? lat + 'ms' : '');
+ d.textContent = text.length + '\u5b57 ' + (cap ? lat + 'ms' : '') +
+ (tr ? ' en:' + tr.length : '');
}
}
@@ -103,8 +150,8 @@
measurePad();
- if (q.has('text')) {
- render(q.get('text'), 0); // design preview: index.html?text=你好世界
+ if (q.has('text')) { // design preview: index.html?en=1&text=你好&t=hello
+ render(q.get('text'), q.get('t') || '', 0);
return;
}
@@ -112,10 +159,10 @@
es.onmessage = function (e) {
try {
const s = JSON.parse(e.data);
- render(s.text, s.cap);
+ render(s.text, s.en, s.cap);
} catch (_) {}
};
- es.onerror = function () { /* EventSource reconnects on its own; keep the last phrase up */ };
+ es.onerror = function () { /* EventSource reconnects on its own; keep the phrase up */ };
})();
</script>
</body>