From a5b77eb48974cfae45bac65ceb4880752444eb47 Mon Sep 17 00:00:00 2001 From: wuhei Date: Thu, 19 Nov 2026 12:38:24 +0100 Subject: english subtitles from a local translation model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- README.md | 54 ++++++++- main.go | 105 ++++++++++++++++- scripts/fetch-mt-model.sh | 16 +++ translate.go | 284 ++++++++++++++++++++++++++++++++++++++++++++++ web/index.html | 97 ++++++++++++---- 5 files changed, 526 insertions(+), 30 deletions(-) create mode 100755 scripts/fetch-mt-model.sh create mode 100644 translate.go 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 @@ lilchinese -
+
-- cgit v1.2.3