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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
|
// lilchinese: live Takahashi-style (高橋メソッド) subtitles.
//
// Mic/file audio -> sherpa-onnx streaming Chinese ASR -> SSE -> fullscreen browser.
// Everything runs locally; no network, no cloud ASR.
package main
import (
_ "embed"
"encoding/binary"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"unicode"
"unicode/utf8"
sherpa "github.com/k2-fsa/sherpa-onnx-go/sherpa_onnx"
)
//go:embed web/index.html
var indexHTML []byte
// ---------------------------------------------------------------- broker (SSE fan-out)
// Slide is one phrase to put on screen.
type Slide struct {
Text string `json:"text"`
Seq int `json:"seq"`
TS int64 `json:"ts"` // published at (unix ms)
Cap int64 `json:"cap"` // audio chunk captured at (unix ms)
}
type broker struct {
mu sync.Mutex
seq int
cur Slide
subs map[chan Slide]struct{}
pubHi int
}
func newBroker() *broker { return &broker{subs: map[chan Slide]struct{}{}} }
func (b *broker) publish(text string, capTS int64) {
if text == "" {
return
}
b.mu.Lock()
defer b.mu.Unlock()
if text == b.cur.Text {
return
}
b.seq++
s := Slide{Text: text, Seq: b.seq, TS: time.Now().UnixMilli(), Cap: capTS}
b.cur = s
for ch := range b.subs {
select {
case ch <- s:
default: // slow client: drop, SSE will not block the audio path
}
}
}
func (b *broker) subscribe() (chan Slide, Slide, func()) {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan Slide, 16)
b.subs[ch] = struct{}{}
cur := b.cur
return ch, cur, func() {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.subs, ch)
close(ch)
}
}
func (b *broker) serveSSE(w http.ResponseWriter, r *http.Request) {
fl, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
h := w.Header()
h.Set("Content-Type", "text/event-stream; charset=utf-8")
h.Set("Cache-Control", "no-cache")
h.Set("X-Accel-Buffering", "no")
w.WriteHeader(http.StatusOK)
ch, cur, unsub := b.subscribe()
defer unsub()
send := func(s Slide) bool {
bts, _ := json.Marshal(s)
if _, err := fmt.Fprintf(w, "data: %s\n\n", bts); err != nil {
return false
}
fl.Flush()
return true
}
if cur.Text != "" && !send(cur) {
return
}
ka := time.NewTicker(15 * time.Second)
defer ka.Stop()
for {
select {
case <-r.Context().Done():
return
case <-ka.C:
if _, err := io.WriteString(w, ": keepalive\n\n"); err != nil {
return
}
fl.Flush()
case s, ok := <-ch:
if !ok || !send(s) {
return
}
}
}
}
// ---------------------------------------------------------------- slide splitting
const puncts = ",。、;:?!…—,.!?;:"
func isBoundary(c rune) bool { return strings.ContainsRune(puncts, c) }
func hasLatin(s string) bool {
return strings.ContainsFunc(s, func(r rune) bool {
return r < 0x2000 && (unicode.IsLetter(r) || unicode.IsDigit(r))
})
}
func cleanSlide(s string) string {
s = strings.TrimSpace(s)
s = strings.TrimRight(s, puncts+" \t")
if !hasLatin(s) {
// Chinese ASR sometimes emits spaces between chars; Takahashi wants none.
s = strings.ReplaceAll(s, " ", "")
s = strings.ReplaceAll(s, "\u3000", "")
}
return strings.TrimSpace(s)
}
// presenter decides when text becomes a slide (Takahashi = short, whole-screen).
type presenter struct {
max int // max characters per slide
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
}
func (p *presenter) update(u string, capTS int64, endpoint bool) {
r := []rune(u)
if len(r) < p.emitted {
p.emitted = len(r) // hypothesis got revised shorter
}
for {
rest := r[p.emitted:]
if len(rest) == 0 {
break
}
cut := -1
for i, c := range rest {
if isBoundary(c) || i+1 >= p.max {
cut = i + 1
break
}
}
if cut < 0 {
break
}
slide := cleanSlide(string(rest[:cut]))
p.emitted += cut
if slide != "" {
p.b.publish(slide, capTS)
}
}
// Live tail: grows character by character while you keep talking. A very short
// tail would blank a full slide, so keep the previous phrase until it grows.
if tail := cleanSlide(string(r[p.emitted:])); tail != "" &&
(endpoint || utf8.RuneCountInString(tail) >= p.preview) {
p.b.publish(tail, capTS)
}
if endpoint {
p.emitted = 0
}
}
// ---------------------------------------------------------------- audio in
func micCmd(source string) *exec.Cmd {
args := []string{
"--raw", "--format=s16le", "--rate=16000", "--channels=1",
"--latency-msec=20", "--client-name=lilchinese",
}
if source != "" {
args = append(args, "--device="+source)
}
return exec.Command("parec", args...)
}
func fileCmd(path string) *exec.Cmd {
return exec.Command("ffmpeg", "-hide_banner", "-loglevel", "error",
"-re", "-i", path,
"-f", "s16le", "-acodec", "pcm_s16le", "-ac", "1", "-ar", "16000", "-")
}
func runASR(cmd *exec.Cmd, rec *sherpa.OnlineRecognizer, stream *sherpa.OnlineStream, pres *presenter) error {
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return err
}
defer func() {
if cmd.Process != nil {
cmd.Process.Kill()
cmd.Wait()
}
}()
const chunk = 320 // samples per read: 20ms @16k -> low display latency
buf := make([]byte, chunk*2)
samples := make([]float32, chunk)
for {
if _, err := io.ReadFull(stdout, buf); err != nil {
return err
}
capTS := time.Now().UnixMilli()
for i := range samples {
samples[i] = float32(int16(binary.LittleEndian.Uint16(buf[2*i:]))) / 32768.0
}
stream.AcceptWaveform(16000, samples)
for rec.IsReady(stream) {
rec.Decode(stream)
}
text := ""
if res := rec.GetResult(stream); res != nil {
text = res.Text
}
ep := rec.IsEndpoint(stream)
pres.update(text, capTS, ep)
if ep {
rec.Reset(stream)
}
}
}
// ---------------------------------------------------------------- model loading
func pickModelFile(dir, kind string) string {
for _, n := range []string{kind + ".int8.onnx", kind + ".onnx"} {
p := filepath.Join(dir, n)
if _, err := os.Stat(p); err == nil {
return p
}
}
m, _ := filepath.Glob(filepath.Join(dir, kind+"*.onnx"))
if len(m) > 0 {
return m[0]
}
return ""
}
func isModelDir(p string) bool {
return pickModelFile(p, "encoder") != "" && pickModelFile(p, "joiner") != "" &&
fileExists(filepath.Join(p, "tokens.txt"))
}
func fileExists(p string) bool { _, err := os.Stat(p); return err == nil }
func candidateRoots() []string {
roots := []string{"models"}
if x := os.Getenv("XDG_DATA_HOME"); x != "" {
roots = append(roots, filepath.Join(x, "lilchinese", "models"))
}
if h := os.Getenv("HOME"); h != "" {
roots = append(roots, filepath.Join(h, ".local/share/lilchinese/models"))
}
if exe, err := os.Executable(); err == nil {
roots = append(roots, filepath.Join(filepath.Dir(exe), "models"))
}
return roots
}
func findModel(explicit string) (string, error) {
var cands []string
if explicit != "" {
cands = append(cands, explicit)
}
for _, root := range candidateRoots() {
m, _ := filepath.Glob(filepath.Join(root, "sherpa-onnx-streaming-*"))
cands = append(cands, m...)
}
for _, c := range cands {
if isModelDir(c) {
return c, nil
}
}
return "", fmt.Errorf("no sherpa-onnx streaming model found (looked in %s)",
strings.Join(candidateRoots(), ", "))
}
// ---------------------------------------------------------------- recording / browser
func startRecorder(path, source string) (*exec.Cmd, error) {
disp := os.Getenv("DISPLAY")
if disp == "" {
disp = ":0"
}
if !strings.Contains(disp, ".") {
disp += ".0"
}
mic := "default"
if source != "" {
mic = source
}
args := []string{"-hide_banner", "-loglevel", "error", "-y",
"-f", "x11grab", "-framerate", "30", "-i", disp,
"-f", "pulse", "-i", mic,
"-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "160k",
"-movflags", "+faststart",
path,
}
cmd := exec.Command("ffmpeg", args...)
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return nil, err
}
return cmd, nil
}
func stopRecorder(cmd *exec.Cmd) {
if cmd == nil || cmd.Process == nil {
return
}
// SIGINT makes ffmpeg finalize the container instead of leaving a broken file.
cmd.Process.Signal(os.Interrupt)
done := make(chan struct{})
go func() { cmd.Wait(); close(done) }()
select {
case <-done:
case <-time.After(10 * time.Second):
cmd.Process.Kill()
}
}
func launchBrowser(tmpl, url string) {
line := strings.ReplaceAll(tmpl, "{url}", url)
f := strings.Fields(line)
if len(f) == 0 {
return
}
cmd := exec.Command(f[0], f[1:]...)
cmd.Stdout, cmd.Stderr = io.Discard, io.Discard
if err := cmd.Start(); err != nil {
log.Printf("cannot launch browser (%v); open %s manually", err, url)
return
}
go cmd.Wait()
}
// ---------------------------------------------------------------- main
func main() {
log.SetFlags(0)
log.SetPrefix("lilchinese: ")
var (
modelDir = flag.String("model", "", "model directory (default: auto-detect under ./models)")
addr = flag.String("addr", "127.0.0.1:8787", "http listen address")
source = flag.String("source", "", "pulseaudio source name (default: system default mic)")
wav = flag.String("wav", "", "play this audio file through the ASR instead of the mic")
record = flag.String("record", "", "also record screen+mic to this file (.mp4/.mkv)")
browser = flag.String("browser", "firefox --kiosk {url}",
"command that opens the display, {url} substituted (empty: don't launch)")
threads = flag.Int("threads", 2, "onnxruntime threads")
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")
)
flag.Parse()
md, err := findModel(*modelDir)
if err != nil {
log.Fatal(err, " (run scripts/fetch-model.sh)")
}
cfg := &sherpa.OnlineRecognizerConfig{
FeatConfig: sherpa.FeatureConfig{SampleRate: 16000, FeatureDim: 80},
ModelConfig: sherpa.OnlineModelConfig{
Transducer: sherpa.OnlineTransducerModelConfig{
Encoder: pickModelFile(md, "encoder"),
Decoder: pickModelFile(md, "decoder"),
Joiner: pickModelFile(md, "joiner"),
},
Tokens: filepath.Join(md, "tokens.txt"),
NumThreads: *threads,
Provider: "cpu",
},
DecodingMethod: "greedy_search",
EnableEndpoint: 1,
Rule1MinTrailingSilence: 2.4,
Rule2MinTrailingSilence: 1.2,
Rule3MinUtteranceLength: 20,
}
if *debug {
cfg.ModelConfig.Debug = 1
}
rec := sherpa.NewOnlineRecognizer(cfg)
if rec == nil {
log.Fatal("failed to load model from ", md)
}
stream := sherpa.NewOnlineStream(rec)
b := newBroker()
pres := &presenter{max: *chars, preview: *preview, b: b}
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(indexHTML)
})
mux.HandleFunc("/events", b.serveSSE)
srv := &http.Server{Addr: *addr, Handler: mux}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}()
url := "http://" + *addr + "/"
if *debug {
url += "?debug=1"
}
log.Printf("model %s", filepath.Base(md))
log.Printf("open %s", url)
if *browser != "" {
launchBrowser(*browser, url)
}
var recCmd *exec.Cmd
if *record != "" {
time.Sleep(1500 * time.Millisecond) // let the window come up first
if recCmd, err = startRecorder(*record, *source); err != nil {
log.Printf("recording disabled: %v", err)
} else {
log.Printf("recording to %s (Ctrl+C to stop and finalize)", *record)
}
}
var stopOnce sync.Once
stop := func() {
stopOnce.Do(func() {
stopRecorder(recCmd)
if *record != "" {
log.Printf("saved %s", *record)
}
})
}
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
go func() {
<-sig
log.Print("stopping")
stop()
os.Exit(0)
}()
in := micCmd(*source)
if *wav != "" {
in = fileCmd(*wav)
}
if err := runASR(in, rec, stream, pres); err != nil {
log.Printf("input ended: %v", err)
}
stop()
}
|