diff options
| author | wuhei <wuhei@users.noreply.github.com> | 2026-11-19 18:36:43 +0100 |
|---|---|---|
| committer | wuhei <wuhei@users.noreply.github.com> | 2026-11-19 18:36:43 +0100 |
| commit | b457d19d9b2c634570300d0f73087e18b4ec4a4a (patch) | |
| tree | 36e066cbe7abb486cb215ba9ccab6ba1550bb315 | |
| parent | f5181ead5b0969fc1806fb714097b17b8d62d53b (diff) | |
| download | lilchinese-b457d19d9b2c634570300d0f73087e18b4ec4a4a.tar.gz | |
Enter keeps the sentence: green on screen, appended to a session log
- Enter (kiosk) turns the sentence green and appends it to a Markdown session log,
default sessions/session-<timestamp>.md, -log to override. Written lazily, so a
run that kept nothing leaves no file.
- logs the whole sentence rather than the 9 characters on screen; the snapshot waits
450ms so the model's lookahead has decoded the final syllables
- the English in the log is a fresh translation of that sentence, done on a single
ordered worker off the audio path, so it never delays recognition
- green clears with the next sentence, like the red cut screen
- double Enter within 2s does not duplicate a line
- tests: keep state, sentence selection, log format and dedupe
| -rw-r--r-- | .gitignore | 1 | ||||
| -rw-r--r-- | README.md | 25 | ||||
| -rw-r--r-- | log.go | 87 | ||||
| -rw-r--r-- | main.go | 113 | ||||
| -rw-r--r-- | main_test.go | 79 | ||||
| -rw-r--r-- | translate.go | 3 | ||||
| -rw-r--r-- | web/index.html | 16 |
7 files changed, 320 insertions, 4 deletions
@@ -2,3 +2,4 @@ /lilchinese *.mp4 *.mkv +/sessions/ @@ -50,6 +50,7 @@ one short thought per screen, replaced on the next one. | key | what it does | |---|---| +| `Enter` | **keep** — the sentence turns green and is appended to the session log | | `Backspace` / `Delete` / `c` | **cut** — the screen goes red and the half-heard sentence is dropped so you can say it again | | `f` | toggle fullscreen | @@ -62,6 +63,26 @@ Colours alternate — black on white, then white on black — at every sentence (a pause long enough for the recogniser's endpoint detector), so consecutive thoughts read as clearly separate slides. +## Session log (Enter) + +`Enter` turns the sentence on screen green and appends it to a Markdown file, so the +talk can be cut down into a script afterwards: + +```markdown +# lilchinese session 2026-11-19 18:34 + +- 18:34:06 重点呢想谈三个问题首先呢就是这一轮全球金融动荡的表现 — I would like to focus on three issues. First, it is about the manifestations of this round of global financial turmoil +- 18:35:41 我自学中文已经五年了 — I have been studying Chinese for five years +``` + +- Default target is `sessions/session-<YYYYMMDD-HHMMSS>.md` (gitignored); pass + `-log talk.md` for a fixed file. Nothing is created until you keep something. +- The **whole sentence** is logged, not the 9 characters on screen — including the last + syllables: the snapshot waits 450 ms for the model's lookahead to finish decoding. +- The English is a fresh translation of that exact sentence, produced off the audio path, + so a slow translator never delays recognition. Entries are written in order by one worker. +- A double `Enter` within 2 s does not duplicate the line. + ## English subtitles (optional) Pass a local translation model and every phrase gets an English line underneath, @@ -108,6 +129,7 @@ How it behaves, and why: | `-model` | auto-detect `models/` | model directory | | `-browser` | `firefox --kiosk {url}` | how to open the display; `{url}` substituted; empty = don't launch | | `-record` | off | ffmpeg: `x11grab` + `pulse` → h264/aac mp4 | +| `-log` | `sessions/` | session log target: a file, or a directory for a timestamped file | | `-threads` | `2` | onnxruntime threads | | `-addr` | `127.0.0.1:8787` | HTTP/SSE listen address | | `-wav` | off | feed an audio file (paced realtime) instead of the mic | @@ -160,13 +182,14 @@ smaller chunks, noticeably faster to emit, somewhat less accurate. ## Tests ```sh -go test ./... # slide cutting, colour alternation, cut, sticky English, windowing +go test ./... # slide cutting, colour alternation, cut, keep, log format, windowing ``` ## Layout ``` main.go mic → ASR → slide splitting → SSE, recorder, browser launch +log.go session log written by Enter translate.go optional local MT: llama-server supervision, debounce, sticky EN line web/index.html the whole UI (autofit, pop transition, EventSource client) scripts/ fetch-model.sh (ASR), fetch-mt-model.sh (translation) @@ -0,0 +1,87 @@ +package main + +// Session log: pressing Enter keeps the sentence that is on screen, turns it green, +// and appends it to a Markdown file so the talk can be edited into a script later. +// +// The file is written lazily — a run where nothing was kept leaves no file behind. + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +type sessionLog struct { + mu sync.Mutex + path string + f *os.File + lastZh string + lastEn string + lastAt time.Time +} + +func newSessionLog(path string) (*sessionLog, error) { + if path == "" { + path = "sessions" + } + if strings.HasSuffix(path, string(os.PathSeparator)) || strings.HasSuffix(path, "/") { + path += "session-" + time.Now().Format("20060102-150405") + ".md" + } else if st, err := os.Stat(path); err == nil && st.IsDir() { + path = filepath.Join(path, "session-"+time.Now().Format("20060102-150405")+".md") + } + if dir := filepath.Dir(path); dir != "." { + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, err + } + } + return &sessionLog{path: path}, nil +} + +// add appends one sentence and returns whether anything was written. +func (l *sessionLog) add(zh, en string) (bool, error) { + zh = strings.TrimSpace(zh) + en = strings.TrimSpace(en) + if zh == "" { + return false, nil + } + l.mu.Lock() + defer l.mu.Unlock() + + // A double Enter should not duplicate the same sentence. + if zh == l.lastZh && en == l.lastEn && time.Since(l.lastAt) < 2*time.Second { + return false, nil + } + + if l.f == nil { + f, err := os.OpenFile(l.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) + if err != nil { + return false, err + } + l.f = f + if st, err := f.Stat(); err == nil && st.Size() == 0 { + fmt.Fprintf(f, "# lilchinese session %s\n\n", time.Now().Format("2006-01-02 15:04")) + } + } + + line := fmt.Sprintf("- %s %s", time.Now().Format("15:04:05"), zh) + if en != "" { + line += " — " + en + } + if _, err := fmt.Fprintln(l.f, line); err != nil { + return false, err + } + l.lastZh, l.lastEn, l.lastAt = zh, en, time.Now() + return true, nil +} + +func (l *sessionLog) close() { + l.mu.Lock() + defer l.mu.Unlock() + if l.f != nil { + l.f.Close() + l.f = nil + } +} @@ -40,6 +40,7 @@ type Slide struct { EN string `json:"en,omitempty"` Invert bool `json:"invert,omitempty"` // white on black for this sentence Cut bool `json:"cut,omitempty"` // red "retake" screen + Keep bool `json:"keep,omitempty"` // green: this sentence was kept Seq int `json:"seq"` TS int64 `json:"ts"` // published at (unix ms) Cap int64 `json:"cap"` // audio chunk captured at (unix ms) @@ -61,6 +62,8 @@ type broker struct { invert bool // cut is the red "take again" screen; the next phrase clears it. cut bool + // keep is the green "this sentence was saved" state, cleared the same way. + keep bool } func newBroker() *broker { return &broker{subs: map[chan Slide]struct{}{}} } @@ -77,6 +80,7 @@ func (b *broker) publish(text string, capTS int64) { } b.seq++ b.cut = false + b.keep = false s := Slide{Text: text, EN: b.curEN, Invert: b.invert, Seq: b.seq, TS: time.Now().UnixMilli(), Cap: capTS} b.cur = s for ch := range b.subs { @@ -103,6 +107,7 @@ func (b *broker) publishEN(en string) { s := b.cur s.EN = en s.Invert = b.invert + s.Keep = b.keep s.Seq = b.seq b.cur = s for ch := range b.subs { @@ -130,6 +135,27 @@ func (b *broker) cutNow() { } } +// keepNow turns the sentence on screen green: it has been written to the log. +func (b *broker) keepNow() { + b.mu.Lock() + defer b.mu.Unlock() + if b.cur.Text == "" || b.keep { + return + } + b.keep = true + b.seq++ + s := b.cur + s.Keep = true + s.Seq = b.seq + b.cur = s + for ch := range b.subs { + select { + case ch <- s: + default: + } + } +} + // flip swaps the colour scheme; called at each sentence boundary. func (b *broker) flip() { b.mu.Lock() @@ -137,6 +163,12 @@ func (b *broker) flip() { b.invert = !b.invert } +func (b *broker) currentEN() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.curEN +} + func (b *broker) currentText() string { b.mu.Lock() defer b.mu.Unlock() @@ -237,6 +269,9 @@ type presenter struct { // is what gets translated: a 9-character window is not enough context for MT. onUtterance func(string) lastU string + + cur string // sentence being spoken + last string // last finished sentence } // reset drops the in-progress utterance so a retake starts from a clean slate. @@ -245,7 +280,18 @@ func (p *presenter) reset() { p.lastU = "" } +// sentence is what Enter saves: the sentence on screen now, else the last one heard. +func (p *presenter) sentence() string { + if s := strings.TrimSpace(p.cur); s != "" { + return s + } + return strings.TrimSpace(p.last) +} + func (p *presenter) update(u string, capTS int64, endpoint bool) { + if s := strings.TrimSpace(u); s != "" { + p.cur = s + } r := []rune(u) if len(r) < p.emitted { p.emitted = len(r) // hypothesis got revised shorter @@ -289,6 +335,8 @@ func (p *presenter) update(u string, capTS int64, endpoint bool) { p.onUtterance(strings.TrimSpace(u)) } if endpoint { + p.last = p.cur + p.cur = "" p.emitted = 0 p.lastU = "" p.b.flip() // next sentence: white on black, and back again @@ -318,7 +366,7 @@ func fileCmd(path string) *exec.Cmd { return c } -func runASR(cmd *exec.Cmd, rec *sherpa.OnlineRecognizer, stream *sherpa.OnlineStream, pres *presenter, cutReq *atomic.Bool) error { +func runASR(cmd *exec.Cmd, rec *sherpa.OnlineRecognizer, stream *sherpa.OnlineStream, pres *presenter, cutReq, keepReq *atomic.Bool, keepQ chan<- string) error { stdout, err := cmd.StdoutPipe() if err != nil { return err @@ -337,6 +385,7 @@ func runASR(cmd *exec.Cmd, rec *sherpa.OnlineRecognizer, stream *sherpa.OnlineSt const chunk = 320 // samples per read: 20ms @16k -> low display latency buf := make([]byte, chunk*2) samples := make([]float32, chunk) + var keepAt time.Time for { if _, err := io.ReadFull(stdout, buf); err != nil { return err @@ -358,6 +407,7 @@ func runASR(cmd *exec.Cmd, rec *sherpa.OnlineRecognizer, stream *sherpa.OnlineSt rec.Reset(stream) pres.reset() pres.b.cutNow() + keepAt = time.Time{} continue } ep := rec.IsEndpoint(stream) @@ -365,6 +415,23 @@ func runASR(cmd *exec.Cmd, rec *sherpa.OnlineRecognizer, stream *sherpa.OnlineSt if ep { rec.Reset(stream) } + + // Enter was pressed. Wait out the model's 320ms lookahead first, otherwise + // the last syllables of the sentence are not decoded yet. + if keepReq.Swap(false) { + keepAt = time.Now().Add(450 * time.Millisecond) + } + if !keepAt.IsZero() && !time.Now().Before(keepAt) { + keepAt = time.Time{} + if zh := pres.sentence(); zh != "" { + pres.b.keepNow() // instant feedback; the log line follows + log.Printf("kept: %s", zh) + select { + case keepQ <- zh: + default: + } + } + } } } @@ -504,6 +571,7 @@ 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") + logFile = flag.String("log", "sessions/", "session log written by Enter (a file, or a directory for a timestamped file)") 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)") @@ -549,7 +617,16 @@ func main() { b := newBroker() pres := &presenter{max: *chars, preview: *preview, b: b} - cutReq := new(atomic.Bool) + cutReq, keepReq := new(atomic.Bool), new(atomic.Bool) + + var trRef atomic.Value // *translator, may stay nil + + lg, err := newSessionLog(*logFile) + if err != nil { + log.Fatalf("session log: %v", err) + } + defer lg.close() + log.Printf("session log %s", lg.path) // Optional English subtitles from a local model. var llamaCmd *exec.Cmd @@ -569,10 +646,32 @@ func main() { log.Printf("translating with %s", filepath.Base(*trModel)) } } + // Kept sentences are translated and appended in order, off the audio path, so a + // slow translation can never delay speech recognition. + keepQ := make(chan string, 8) + go func() { + for zh := range keepQ { + en := "" + if tr := trRef.Load(); tr != nil { + if got, err := tr.(*translator).translateText(zh); err == nil { + en = got + } else if *debug { + log.Printf("translate kept sentence: %v", err) + } + } + if written, err := lg.add(zh, en); err != nil { + log.Printf("session log: %v", err) + } else if written { + log.Printf("appended to %s", lg.path) + } + } + }() + var tr *translator if endpoint != "" { tr = newTranslator(endpoint, *trPrompt, b, *debug) pres.onUtterance = func(u string) { tr.request(contextWindow(u, *trWindow)) } + trRef.Store(tr) go tr.run() } @@ -590,6 +689,10 @@ func main() { cutReq.Store(true) // the audio loop applies it within one 20ms chunk w.WriteHeader(http.StatusNoContent) }) + mux.HandleFunc("/keep", func(w http.ResponseWriter, r *http.Request) { + keepReq.Store(true) + w.WriteHeader(http.StatusNoContent) + }) srv := &http.Server{Addr: *addr, Handler: mux} go func() { if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { @@ -627,6 +730,10 @@ func main() { var stopOnce sync.Once stop := func() { stopOnce.Do(func() { + // let sentences that were just kept reach the log + for i := 0; i < 30 && len(keepQ) > 0; i++ { + time.Sleep(100 * time.Millisecond) + } stopRecorder(recCmd) if llamaCmd != nil && llamaCmd.Process != nil { llamaCmd.Process.Signal(syscall.SIGTERM) @@ -657,7 +764,7 @@ func main() { if *wav != "" { in = fileCmd(*wav) } - if err := runASR(in, rec, stream, pres, cutReq); err != nil { + if err := runASR(in, rec, stream, pres, cutReq, keepReq, keepQ); err != nil { log.Printf("input ended: %v", err) } stop() diff --git a/main_test.go b/main_test.go index 09ce825..1838cdb 100644 --- a/main_test.go +++ b/main_test.go @@ -1,6 +1,8 @@ package main import ( + "os" + "strings" "testing" "time" ) @@ -170,3 +172,80 @@ func TestContextWindowPrefersClauseBoundary(t *testing.T) { t.Logf("window = %q", got) } } + +func TestKeepTurnsSentenceGreenUntilTheNextOne(t *testing.T) { + b := newBroker() + ch, _, unsub := b.subscribe() + defer unsub() + b.publish("我自学中文已经五年了", time.Now().UnixMilli()) + <-ch // the phrase itself + + b.keepNow() + s := <-ch + if !s.Keep || s.Text != "我自学中文已经五年了" { + t.Fatalf("keep slide = %+v", s) + } + b.keepNow() // idempotent: no second broadcast, no crash + select { + case dup := <-ch: + t.Fatalf("second keep re-broadcast: %+v", dup) + default: + } + + b.publish("下一句话", time.Now().UnixMilli()) + if next := <-ch; next.Keep { + t.Fatalf("green leaked into the next sentence: %+v", next) + } +} + +func TestPresentersentencePrefersTheOneBeingSpoken(t *testing.T) { + b := newBroker() + p := &presenter{max: 9, preview: 3, b: b} + if got := p.sentence(); got != "" { + t.Fatalf("empty presenter returned %q", got) + } + p.update("第一句话结束了", time.Now().UnixMilli(), true) + if got := p.sentence(); got != "第一句话结束了" { + t.Fatalf("after endpoint sentence() = %q", got) + } + p.update("第二句还在说", time.Now().UnixMilli(), false) + if got := p.sentence(); got != "第二句还在说" { + t.Fatalf("while speaking sentence() = %q", got) + } +} + +func TestSessionLogFormat(t *testing.T) { + dir := t.TempDir() + lg, err := newSessionLog(dir + "/") + if err != nil { + t.Fatal(err) + } + defer lg.close() + + if w, err := lg.add("我自学中文已经五年了", "I have been studying Chinese for five years"); err != nil || !w { + t.Fatalf("add returned %v, %v", w, err) + } + // same sentence twice in a row is a double Enter, not two lines + if w, _ := lg.add("我自学中文已经五年了", "I have been studying Chinese for five years"); w { + t.Fatal("duplicate sentence was written") + } + if w, err := lg.add("谢谢大家", ""); err != nil || !w { + t.Fatalf("second add returned %v, %v", w, err) + } + lg.close() + + raw, err := os.ReadFile(lg.path) + if err != nil { + t.Fatal(err) + } + body := string(raw) + if !strings.HasPrefix(body, "# lilchinese session ") { + t.Fatalf("missing header: %q", body) + } + if n := strings.Count(body, "\n- "); n != 2 { + t.Fatalf("want 2 entries, got %d in:\n%s", n, body) + } + if !strings.Contains(body, "我自学中文已经五年了 — I have been studying Chinese") { + t.Fatalf("translation missing:\n%s", body) + } +} diff --git a/translate.go b/translate.go index 66cee26..508e5db 100644 --- a/translate.go +++ b/translate.go @@ -115,6 +115,9 @@ func (t *translator) run() { } } +// translateText is the synchronous form, used when a sentence is kept for the log. +func (t *translator) translateText(text string) (string, error) { return t.translate(text) } + func (t *translator) translate(text string) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) defer cancel() diff --git a/web/index.html b/web/index.html index 677fe14..404b367 100644 --- a/web/index.html +++ b/web/index.html @@ -46,6 +46,9 @@ /* sentence alternates black-on-white and white-on-black; Backspace = red retake */ body.invert { background: #000; color: #fff; } body.cut { background: #d10d0d; color: #fff; } + /* Enter: the sentence was kept and written to the session log */ + body.keep { color: #0a7d3a; } + body.invert.keep { color: #4ade80; } @keyframes pop { from { opacity: .5; transform: scale(.955); } to { opacity: 1; transform: scale(1); } @@ -110,6 +113,11 @@ if (reserve) en.textContent = ''; } + function keep() { + body.classList.add('keep'); // instant feedback, server confirms it + fetch('/keep', { method: 'POST', keepalive: true }).catch(function () {}); + } + function cut() { body.classList.add('cut'); // instant feedback, server confirms it curZh = ''; curEn = ''; @@ -154,6 +162,11 @@ addEventListener('resize', function () { measurePad(); fit(); }); addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + keep(); + return; + } if (e.key === 'Backspace' || e.key === 'Delete' || e.key === 'c') { // "that was wrong, say it again": red screen, then straight back to work e.preventDefault(); @@ -169,6 +182,7 @@ measurePad(); if (q.has('invert')) body.classList.add('invert'); + if (q.has('keep')) body.classList.add('keep'); if (q.has('cut')) { body.classList.add('cut'); return; } if (q.has('text')) { // design preview: index.html?en=1&text=你好&t=hello @@ -182,7 +196,9 @@ const s = JSON.parse(e.data); body.classList.toggle('invert', !!s.invert); body.classList.toggle('cut', !!s.cut); + body.classList.toggle('keep', !!s.keep); if (s.cut) { curZh = ''; curEn = ''; zh.textContent = ''; en.textContent = ''; return; } + if (s.keep && s.text === curZh) return; // only the colour changed render(s.text, s.en, s.cap); } catch (_) {} }; |
