From 10ee627143419d6e9c9186fbb0a023a34b08948e Mon Sep 17 00:00:00 2001 From: wuhei Date: Thu, 19 Nov 2026 11:54:17 +0100 Subject: lilchinese: local streaming Chinese ASR rendered as fullscreen Takahashi slides parec mic -> sherpa-onnx streaming zipformer (zh, int8, offline) -> slide splitter -> SSE -> Firefox kiosk. No cloud, no Web Speech API. - 20ms audio reads, ~35ms capture-to-paint overhead, 320ms model lookahead - slides break on punctuation or at -chars; short tails don't blank a full slide - autofit font (Noto Sans CJK SC Black), 90ms slam transition, SSE reconnect - -record captures screen+mic via ffmpeg x11grab+pulse, finalized on Ctrl+C - -wav plays a file through the pipeline for testing --- main.go | 498 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 498 insertions(+) create mode 100644 main.go (limited to 'main.go') diff --git a/main.go b/main.go new file mode 100644 index 0000000..b7a7069 --- /dev/null +++ b/main.go @@ -0,0 +1,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() +} -- cgit v1.2.3