summaryrefslogtreecommitdiff
path: root/main.go
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 /main.go
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
Diffstat (limited to 'main.go')
-rw-r--r--main.go105
1 files changed, 102 insertions, 3 deletions
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)
}