1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
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)
}
|