summaryrefslogtreecommitdiff
path: root/translate.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 /translate.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 'translate.go')
-rw-r--r--translate.go284
1 files changed, 284 insertions, 0 deletions
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)
+}