summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md33
-rw-r--r--main.go80
-rw-r--r--main_test.go172
-rw-r--r--web/index.html24
4 files changed, 296 insertions, 13 deletions
diff --git a/README.md b/README.md
index 694bdab..7f84030 100644
--- a/README.md
+++ b/README.md
@@ -46,6 +46,22 @@ everything and finalizes a recording.
Then just talk. Silence holds the last phrase on screen — that is the Takahashi rhythm:
one short thought per screen, replaced on the next one.
+### During the talk
+
+| key | what it does |
+|---|---|
+| `Backspace` / `Delete` / `c` | **cut** — the screen goes red and the half-heard sentence is dropped so you can say it again |
+| `f` | toggle fullscreen |
+
+The red stays up until the retake is heard, then it is back to normal colours. It is not
+just a mood light: the ASR state is reset at the cut, so the flubbed sentence cannot leak
+into the next one, and because the recording is a screen capture the red frame also marks
+where each retake starts when you edit the video.
+
+Colours alternate — black on white, then white on black — at every sentence boundary
+(a pause long enough for the recogniser's endpoint detector), so consecutive thoughts
+read as clearly separate slides.
+
## English subtitles (optional)
Pass a local translation model and every phrase gets an English line underneath,
@@ -76,7 +92,7 @@ How it behaves, and why:
A slide lives ~0.3 s while speaking continuously — no LLM can keep up with that, so the
translation lags the speaker by roughly one model call and updates as the sentence
grows, like an interpreter. It never blanks between phrases.
-- `-translate-window` (default 28) is how many characters of speech go to the model.
+- `-translate-window` (default 40) is how many characters of speech go to the model.
Larger = smoother/more context but slower; smaller = snappier, choppier fragments.
- Translations are cached per phrase, so repeated words cost nothing.
- Without `-translate`/`-translate-model` the page is laid out exactly as before — the
@@ -97,7 +113,7 @@ How it behaves, and why:
| `-wav` | off | feed an audio file (paced realtime) instead of the mic |
| `-translate-model` | off | spawn llama-server with this `.gguf` for English subtitles |
| `-translate` | off | use an already running OpenAI-compatible endpoint |
-| `-translate-window` | `28` | characters of speech sent to the translator |
+| `-translate-window` | `40` | characters of speech sent to the translator |
| `-prompt` | Hy-MT template | translation prompt, `{text}` substituted |
| `-llama-server` / `-llama-args` / `-llama-threads` | `llama-server` / — / half the cores | spawned backend tuning |
@@ -128,7 +144,12 @@ smaller chunks, noticeably faster to emit, somewhat less accurate.
## Notes
-- Slides break on `,。、;:?!…` and at `-chars`, whichever comes first.
+- Slides break on `,。、;:?!…` and at `-chars`, whichever comes first — but a length
+ break only happens when at least `-preview` characters remain for the next phrase. Without
+ that rule the last frame of *我自学中文已经五年了* was just `了`, with the rest of the
+ sentence thrown away. Short sentences therefore stay whole.
+- Slides are *not* re-split for the translator: it gets up to `-translate-window` (40)
+ characters of speech, starting at a clause boundary where possible.
- The binary links the shared libs from the Go module cache
(`rpath` → `.../pkg/mod/github.com/k2-fsa/sherpa-onnx-go-linux@v1.13.8/lib/...`).
If you wipe the module cache, rebuild.
@@ -136,6 +157,12 @@ smaller chunks, noticeably faster to emit, somewhat less accurate.
- Recording captures the whole screen, so start it after the kiosk window is up
(it auto-delays 1.5 s).
+## Tests
+
+```sh
+go test ./... # slide cutting, colour alternation, cut, sticky English, windowing
+```
+
## Layout
```
diff --git a/main.go b/main.go
index d58aaa6..d53674b 100644
--- a/main.go
+++ b/main.go
@@ -20,6 +20,7 @@ import (
"runtime"
"strings"
"sync"
+ "sync/atomic"
"syscall"
"time"
"unicode"
@@ -35,11 +36,13 @@ var indexHTML []byte
// Slide is one phrase to put on screen.
type Slide struct {
- Text string `json:"text"`
- EN string `json:"en,omitempty"`
- Seq int `json:"seq"`
- TS int64 `json:"ts"` // published at (unix ms)
- Cap int64 `json:"cap"` // audio chunk captured at (unix ms)
+ Text string `json:"text"`
+ EN string `json:"en,omitempty"`
+ Invert bool `json:"invert,omitempty"` // white on black for this sentence
+ Cut bool `json:"cut,omitempty"` // red "retake" screen
+ 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 {
@@ -53,6 +56,11 @@ type broker struct {
// survives the slides that happen while the next one is being produced, so the
// English line lags the speaker by roughly one model call instead of blinking.
curEN string
+
+ // invert alternates black-on-white / white-on-black per sentence.
+ invert bool
+ // cut is the red "take again" screen; the next phrase clears it.
+ cut bool
}
func newBroker() *broker { return &broker{subs: map[chan Slide]struct{}{}} }
@@ -68,7 +76,8 @@ func (b *broker) publish(text string, capTS int64) {
return
}
b.seq++
- s := Slide{Text: text, EN: b.curEN, Seq: b.seq, TS: time.Now().UnixMilli(), Cap: capTS}
+ b.cut = 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 {
select {
@@ -93,6 +102,7 @@ func (b *broker) publishEN(en string) {
b.seq++
s := b.cur
s.EN = en
+ s.Invert = b.invert
s.Seq = b.seq
b.cur = s
for ch := range b.subs {
@@ -103,6 +113,30 @@ func (b *broker) publishEN(en string) {
}
}
+// cutNow blanks the screen and turns it red: the speaker is redoing a sentence.
+func (b *broker) cutNow() {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ b.cut = true
+ b.curEN = ""
+ b.seq++
+ s := Slide{Invert: b.invert, Cut: true, Seq: b.seq, TS: time.Now().UnixMilli()}
+ 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()
+ defer b.mu.Unlock()
+ b.invert = !b.invert
+}
+
func (b *broker) currentText() string {
b.mu.Lock()
defer b.mu.Unlock()
@@ -205,6 +239,12 @@ type presenter struct {
lastU string
}
+// reset drops the in-progress utterance so a retake starts from a clean slate.
+func (p *presenter) reset() {
+ p.emitted = 0
+ p.lastU = ""
+}
+
func (p *presenter) update(u string, capTS int64, endpoint bool) {
r := []rune(u)
if len(r) < p.emitted {
@@ -217,7 +257,14 @@ func (p *presenter) update(u string, capTS int64, endpoint bool) {
}
cut := -1
for i, c := range rest {
- if isBoundary(c) || i+1 >= p.max {
+ if isBoundary(c) {
+ cut = i + 1
+ break
+ }
+ // Break on length only if a full next phrase still fits; otherwise the
+ // last frame of a sentence is a one-character stub ("了") leaving the
+ // rest of what was said on the cutting-room floor.
+ if i+1 >= p.max && len(rest) >= p.max+p.preview {
cut = i + 1
break
}
@@ -244,6 +291,7 @@ func (p *presenter) update(u string, capTS int64, endpoint bool) {
if endpoint {
p.emitted = 0
p.lastU = ""
+ p.b.flip() // next sentence: white on black, and back again
}
}
@@ -270,7 +318,7 @@ func fileCmd(path string) *exec.Cmd {
return c
}
-func runASR(cmd *exec.Cmd, rec *sherpa.OnlineRecognizer, stream *sherpa.OnlineStream, pres *presenter) error {
+func runASR(cmd *exec.Cmd, rec *sherpa.OnlineRecognizer, stream *sherpa.OnlineStream, pres *presenter, cutReq *atomic.Bool) error {
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
@@ -305,6 +353,13 @@ func runASR(cmd *exec.Cmd, rec *sherpa.OnlineRecognizer, stream *sherpa.OnlineSt
if res := rec.GetResult(stream); res != nil {
text = res.Text
}
+ // Backspace was pressed: throw away the half-heard sentence and go red.
+ if cutReq.Swap(false) {
+ rec.Reset(stream)
+ pres.reset()
+ pres.b.cutNow()
+ continue
+ }
ep := rec.IsEndpoint(stream)
pres.update(text, capTS, ep)
if ep {
@@ -453,7 +508,7 @@ func main() {
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)")
trPrompt = flag.String("prompt", defaultPrompt, "translation prompt; {text} is substituted")
- trWindow = flag.Int("translate-window", 28, "characters of speech sent to the translator (bigger = smoother, slower)")
+ trWindow = flag.Int("translate-window", 40, "characters of speech sent to the translator (bigger = smoother, slower)")
llamaBin = flag.String("llama-server", "llama-server", "llama-server binary")
llamaArgs = flag.String("llama-args", "", "extra arguments for llama-server")
llamaThr = flag.Int("llama-threads", 0, "threads for the translation model (0 = half the cores)")
@@ -494,6 +549,7 @@ func main() {
b := newBroker()
pres := &presenter{max: *chars, preview: *preview, b: b}
+ cutReq := new(atomic.Bool)
// Optional English subtitles from a local model.
var llamaCmd *exec.Cmd
@@ -530,6 +586,10 @@ func main() {
w.Write(indexHTML)
})
mux.HandleFunc("/events", b.serveSSE)
+ mux.HandleFunc("/cut", func(w http.ResponseWriter, r *http.Request) {
+ cutReq.Store(true) // the audio loop applies it within one 20ms chunk
+ w.WriteHeader(http.StatusNoContent)
+ })
srv := &http.Server{Addr: *addr, Handler: mux}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
@@ -597,7 +657,7 @@ func main() {
if *wav != "" {
in = fileCmd(*wav)
}
- if err := runASR(in, rec, stream, pres); err != nil {
+ if err := runASR(in, rec, stream, pres, cutReq); err != nil {
log.Printf("input ended: %v", err)
}
stop()
diff --git a/main_test.go b/main_test.go
new file mode 100644
index 0000000..09ce825
--- /dev/null
+++ b/main_test.go
@@ -0,0 +1,172 @@
+package main
+
+import (
+ "testing"
+ "time"
+)
+
+// collect returns the phrases published by one run of presenter.update.
+func collect(t *testing.T, p *presenter, b *broker, u string, endpoint bool) []string {
+ t.Helper()
+ ch, _, unsub := b.subscribe()
+ defer unsub()
+ p.update(u, time.Now().UnixMilli(), endpoint)
+ var got []string
+ for {
+ select {
+ case s := <-ch:
+ got = append(got, s.Text)
+ default:
+ return got
+ }
+ }
+}
+
+func TestShortSentenceIsNotCutIntoAStub(t *testing.T) {
+ b := newBroker()
+ p := &presenter{max: 9, preview: 3, b: b}
+
+ // 10 chars with a full stop: used to end up on screen as "了".
+ got := collect(t, p, b, "我自学中文已经五年了。", true)
+ want := []string{"我自学中文已经五年了"}
+ if len(got) != 1 || got[0] != want[0] {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+}
+
+func TestLongRunIsCutButNeverLeavesAStub(t *testing.T) {
+ b := newBroker()
+ p := &presenter{max: 9, preview: 3, b: b}
+
+ u := "今天我想跟大家讲一讲我自己学习中文的一些经历"
+ got := collect(t, p, b, u, false)
+ if len(got) == 0 {
+ t.Fatal("nothing published")
+ }
+ last := []rune(got[len(got)-1])
+ if len(last) < 3 {
+ t.Fatalf("last phrase %q is a stub (all: %q)", string(last), got)
+ }
+ // Slides stay around the requested size (last one may be the shorter tail).
+ for i, s := range got {
+ n := len([]rune(s))
+ if i < len(got)-1 && (n < 3 || n > 9) {
+ t.Fatalf("phrase %d = %q (%d runes), want 3..9", i, s, n)
+ }
+ }
+}
+
+func TestPunctuationBreaksSlides(t *testing.T) {
+ b := newBroker()
+ p := &presenter{max: 9, preview: 3, b: b}
+ got := collect(t, p, b, "第一,第二,第三。", true)
+ want := []string{"第一", "第二", "第三"}
+ if len(got) != len(want) {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+ }
+}
+
+func TestEnglishLineIsStickyAcrossPhrases(t *testing.T) {
+ b := newBroker()
+ p := &presenter{max: 9, preview: 3, b: b}
+
+ collect(t, p, b, "第一", false)
+ b.publishEN("First")
+ // The next phrase is a different sentence, but the last translation stays up
+ // until its replacement arrives.
+ got := []Slide{}
+ ch, _, unsub := b.subscribe()
+ defer unsub()
+ p.update("第二,", time.Now().UnixMilli(), false)
+ for {
+ select {
+ case s := <-ch:
+ got = append(got, s)
+ default:
+ if len(got) == 0 {
+ t.Fatal("nothing published")
+ }
+ if got[len(got)-1].EN != "First" {
+ t.Fatalf("EN = %q, want the previous translation to persist", got[len(got)-1].EN)
+ }
+ return
+ }
+ }
+}
+
+func TestColourAlternatesPerSentence(t *testing.T) {
+ b := newBroker()
+ p := &presenter{max: 9, preview: 3, b: b}
+
+ first := []Slide{}
+ ch, _, unsub := b.subscribe()
+ p.update("你好啊", time.Now().UnixMilli(), true) // sentence ends -> colour flips
+ for {
+ select {
+ case s := <-ch:
+ first = append(first, s)
+ default:
+ goto next
+ }
+ }
+next:
+ unsub()
+ ch2, _, unsub2 := b.subscribe()
+ defer unsub2()
+ p.update("再见了", time.Now().UnixMilli(), false)
+ for {
+ select {
+ case s := <-ch2:
+ if !s.Invert {
+ t.Fatalf("second sentence should be white on black, got %+v", s)
+ }
+ return
+ default:
+ time.Sleep(5 * time.Millisecond)
+ }
+ }
+}
+
+func TestCutBlanksTheScreen(t *testing.T) {
+ b := newBroker()
+ b.publish("你好", time.Now().UnixMilli())
+ ch, _, unsub := b.subscribe()
+ defer unsub()
+ b.cutNow()
+ s := <-ch
+ if !s.Cut || s.Text != "" || s.EN != "" {
+ t.Fatalf("cut slide = %+v, want empty red screen", s)
+ }
+ // The next phrase leaves the red screen behind.
+ p := &presenter{max: 9, preview: 3, b: b}
+ p.update("重来说吧", time.Now().UnixMilli(), false)
+ for {
+ select {
+ case s := <-ch:
+ if s.Cut {
+ t.Fatalf("still red after new phrase: %+v", s)
+ }
+ return
+ default:
+ time.Sleep(5 * time.Millisecond)
+ }
+ }
+}
+
+func TestContextWindowPrefersClauseBoundary(t *testing.T) {
+ got := contextWindow("第一句话在这里,第二句话在这里,第三句话", 12)
+ if []rune(got)[0] == ',' {
+ t.Fatalf("window starts on punctuation: %q", got)
+ }
+ if n := len([]rune(got)); n > 12 {
+ t.Fatalf("window %q is %d runes, want <= 12", got, n)
+ }
+ if got != "第三句话" {
+ t.Logf("window = %q", got)
+ }
+}
diff --git a/web/index.html b/web/index.html
index 5179370..677fe14 100644
--- a/web/index.html
+++ b/web/index.html
@@ -8,6 +8,7 @@
html, body {
margin: 0; padding: 0; height: 100%; overflow: hidden;
background: #fff; color: #000; cursor: none;
+ transition: background-color 90ms linear, color 90ms linear;
-webkit-user-select: none; user-select: none;
font-family: "Noto Sans CJK SC Black", "Noto Sans SC Black", "Source Han Sans SC",
"Noto Sans CJK JP Black", "PingFang SC", sans-serif;
@@ -42,6 +43,9 @@
display: none;
}
body.en #en { display: block; }
+ /* sentence alternates black-on-white and white-on-black; Backspace = red retake */
+ body.invert { background: #000; color: #fff; }
+ body.cut { background: #d10d0d; color: #fff; }
@keyframes pop {
from { opacity: .5; transform: scale(.955); }
to { opacity: 1; transform: scale(1); }
@@ -63,6 +67,7 @@
const zh = document.getElementById('zh');
const en = document.getElementById('en');
const d = document.getElementById('d');
+ const body = document.body;
const q = new URLSearchParams(location.search);
const debug = q.has('debug');
const wantEN = q.has('en');
@@ -105,6 +110,13 @@
if (reserve) en.textContent = '';
}
+ function cut() {
+ body.classList.add('cut'); // instant feedback, server confirms it
+ curZh = ''; curEn = '';
+ zh.textContent = ''; en.textContent = '';
+ fetch('/cut', { method: 'POST', keepalive: true }).catch(function () {});
+ }
+
function render(text, translation, cap) {
if (!text) return;
const newPhrase = text !== curZh;
@@ -142,6 +154,12 @@
addEventListener('resize', function () { measurePad(); fit(); });
addEventListener('keydown', function (e) {
+ 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();
+ cut();
+ return;
+ }
if (e.key === 'f' || e.key === 'F') {
if (document.fullscreenElement) document.exitFullscreen();
else document.documentElement.requestFullscreen();
@@ -150,6 +168,9 @@
measurePad();
+ if (q.has('invert')) body.classList.add('invert');
+ if (q.has('cut')) { body.classList.add('cut'); return; }
+
if (q.has('text')) { // design preview: index.html?en=1&text=你好&t=hello
render(q.get('text'), q.get('t') || '', 0);
return;
@@ -159,6 +180,9 @@
es.onmessage = function (e) {
try {
const s = JSON.parse(e.data);
+ body.classList.toggle('invert', !!s.invert);
+ body.classList.toggle('cut', !!s.cut);
+ if (s.cut) { curZh = ''; curEn = ''; zh.textContent = ''; en.textContent = ''; return; }
render(s.text, s.en, s.cap);
} catch (_) {}
};