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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
package main

// Checking a passage by ear.
//
// A correction pass can settle everything that is quotation by fetching the
// source, and nothing that is not: the commentary between the quotations is
// unscripted, and where the recogniser misheard it there is no text to check
// against. observations-transcripts(7) says such a passage goes on a list for
// someone who can play the audio. This is that someone, when nobody is
// available: it cuts the passage out and asks a speech model what it hears.
//
// It prints three views of the same span, because no one of them is
// authoritative:
//
//   - what the model heard, which is an independent recogniser and wrong in
//     different places than the first one;
//   - what the source says, when the span falls inside a quotation, which
//     settles it outright;
//   - what the transcript currently says, which is the thing being checked and
//     is labelled as such in the output.
//
// The judgement stays with the reader: the model is a suggestion, and a
// passage it cannot settle is left alone — see observations-transcripts(7).
//
// This is the only part of observations that talks to the network or wants a
// credential. It is confined to this subcommand: add, render and list never
// reach it, and render remains a pure function of the episodes directory.

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"time"
)

// listenModel is the model passages are read by.
//
// Retired model names are refused for new callers rather than redirected, with
// the successor named in the error, which is how this one is updated. A
// failure here costs one answer and never touches a file.
const listenModel = "gemini-3.8-flash"

const listenAPI = "https://generativelanguage.googleapis.com/v1beta/models/" +
	listenModel + ":generateContent"

// passEntry is where the key lives on the author's machine, and is the last
// thing tried. Naming it in an error message instead was a way of making the
// reader run the command the program could have run itself; the two flags
// above still take a key from anywhere, so nothing is lost by trying.
const passEntry = "internet/ai.google.dev/gemini/api-keys/gemini-2.5-flash"

// listenPrompt asks for words and nothing else.
//
// It says not to censor because the recogniser does — episode 001 had
// "b*******" where the audio has a word — and a transcript that is politer
// than the recording is wrong in the direction nobody checks. It asks for
// stumbles because a spoken self-correction is what happened and the format
// keeps it. It forbids timestamps: the model will produce them to the
// millisecond and be wrong by a quarter of a second, which is worse than
// interpolating (observations-transcripts(7), REFLOWING LINES).
const listenPrompt = `Transcribe this audio clip verbatim, word for word.

This is a podcast: one person reads a blog post aloud and comments on it.

- Output ONLY the transcript text. No commentary, no timestamps, no speaker
  labels, no markdown.
- Include filler words, stumbles and repetitions exactly as spoken. If a word
  is started, broken off and restarted, write both parts.
- Do not censor profanity or slurs. Write exactly what is said; a euphemism
  here is an error.
- Spell proper nouns out in full where you can identify them.
- Mark anything genuinely unintelligible as [unclear]. Do not guess.`

// listenTimeout bounds one request. Clips are seconds long; a minute is
// already pathological.
const listenTimeout = 90 * time.Second

// clipPad is how much audio either side of the span goes into the clip.
//
// A word at the very edge of a clip is the one most likely to be misheard,
// and a clip cut wide of the passage produces a fluent reading of the wrong
// words — which looks exactly like a correct answer. Padding is reported in
// the output so the extra words are known to be context.
const clipPad = 2 * time.Second

func cmdListen(args []string) error {
	fs := flag.NewFlagSet("listen", flag.ExitOnError)
	var d dirs
	d.flags(fs)
	var (
		keyFile  = fs.String("gemini-key-file", "", "file holding the Gemini API key (default: $GEMINI_API_KEY, then pass(1))")
		pad      = fs.Float64("pad", clipPad.Seconds(), "seconds of context to include either side of the span")
		noGemini = fs.Bool("no-gemini-call", false, "skip the model; print the source and transcript views only")
		ffmpeg   = fs.String("ffmpeg", "ffmpeg", "path to ffmpeg")
	)
	fs.Usage = func() {
		fmt.Fprint(fs.Output(), `usage: observations listen [flags] <episode> <from> <to>

Prints what a speech model hears in one passage of an episode, beside what the
source says and what the transcript currently says.

  <episode>  episode number, e.g. 001 or 1
  <from>,<to>  HH:MM:SS.mmm, MM:SS, or seconds

It never reports a timestamp: the model answers to the millisecond and is late
by 250-450ms, which is worse than interpolating within a line. Timestamps for
splitting a line come from git history — see observations-transcripts(7).

Reads the episode and its audio; writes nothing.

`)
		fs.PrintDefaults()
	}
	if err := fs.Parse(args); err != nil {
		return err
	}
	if fs.NArg() != 3 {
		fs.Usage()
		return fmt.Errorf("expected <episode> <from> <to>, got %d argument(s)", fs.NArg())
	}

	number, err := parseEpisodeArg(fs.Arg(0))
	if err != nil {
		return err
	}
	from, err := parseSpan(fs.Arg(1))
	if err != nil {
		return fmt.Errorf("<from>: %w", err)
	}
	to, err := parseSpan(fs.Arg(2))
	if err != nil {
		return fmt.Errorf("<to>: %w", err)
	}
	if to <= from {
		return fmt.Errorf("<to> (%s) is not after <from> (%s)",
			formatTimestamp(to), formatTimestamp(from))
	}

	ep, err := readEpisode(episodePath(d.episodes, number))
	if err != nil {
		return err
	}
	audio := filepath.Join(d.audio, ep.Audio.File)
	if _, err := os.Stat(audio); err != nil {
		return fmt.Errorf("audio for episode %s: %w", ep.Slug(), err)
	}

	padMs := int64(*pad * 1000)
	fmt.Printf("episode %s   %s - %s   (%.1fs, clip padded %+.1fs)\n\n",
		ep.Slug(), formatTimestamp(from), formatTimestamp(to),
		float64(to-from)/1000, *pad)

	// The model first: it is the reason to run this, and the other two views
	// are here to be compared against it.
	if !*noGemini {
		key, err := listenKey(*keyFile)
		if err != nil {
			return err
		}
		heard, err := listenOnce(*ffmpeg, audio, from-padMs, to+padMs, key)
		if err != nil {
			return err
		}
		fmt.Printf("GEMINI  %s\n%s\n\n", listenModel, indent(heard))
	}

	printSourceView(ep, from, to)
	printTranscriptView(ep, from, to)
	return nil
}

// listenKey finds the API key: an explicit file, the environment, then the
// password store.
//
// pass(1) is last because it is the one source that can block — it wants a
// gpg-agent, and on a machine without one it prompts — so a caller that has
// already said where the key is never reaches it.
func listenKey(file string) (string, error) {
	if file != "" {
		return readSecretFile(file)
	}
	if k := strings.TrimSpace(os.Getenv("GEMINI_API_KEY")); k != "" {
		return k, nil
	}
	out, err := exec.Command("pass", passEntry).Output()
	if err != nil {
		return "", fmt.Errorf("no Gemini API key: --gemini-key-file and GEMINI_API_KEY are unset,\n"+
			"        and `pass %s` failed: %w", passEntry, err)
	}
	// pass prints the secret on the first line; anything after it is a note.
	k := strings.SplitN(strings.TrimSpace(string(out)), "\n", 2)[0]
	if k == "" {
		return "", fmt.Errorf("pass %s is empty", passEntry)
	}
	return k, nil
}

func readSecretFile(path string) (string, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return "", err
	}
	s := strings.TrimSpace(string(b))
	if s == "" {
		return "", fmt.Errorf("%s is empty", path)
	}
	// A key file with several lines is a key plus a note; the key is first.
	return strings.SplitN(s, "\n", 2)[0], nil
}

// listenOnce cuts one clip and asks for it once.
func listenOnce(ffmpegBin, audio string, start, end int64, key string) (string, error) {
	if start < 0 {
		start = 0
	}
	clip, err := cutClip(ffmpegBin, audio, start, end)
	if err != nil {
		return "", err
	}
	return askModel(clip, key)
}

// cutClip extracts a span as mono 16kHz Opus.
//
// -ss before -i seeks in the input, which is exact here — measured against a
// sample-accurate decode-seek it lands on the same sample — and does not
// decode the whole file to reach a passage half an hour in. The model
// downsamples to 16kHz anyway, so sending more is only slower.
func cutClip(ffmpegBin, audio string, start, end int64) ([]byte, error) {
	cmd := exec.Command(ffmpegBin,
		"-nostdin", "-v", "error",
		"-ss", msToFFmpeg(start),
		"-t", msToFFmpeg(end-start),
		"-i", audio,
		"-ac", "1", "-ar", "16000",
		"-c:a", "libopus", "-b:a", "24k",
		"-f", "ogg", "-",
	)
	var out, stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	if err := cmd.Run(); err != nil {
		return nil, fmt.Errorf("ffmpeg cutting %s-%s: %w: %s",
			formatTimestamp(start), formatTimestamp(end), err, strings.TrimSpace(stderr.String()))
	}
	if out.Len() == 0 {
		return nil, fmt.Errorf("ffmpeg produced no audio for %s-%s (past the end of the recording?)",
			formatTimestamp(start), formatTimestamp(end))
	}
	return out.Bytes(), nil
}

func msToFFmpeg(ms int64) string {
	return strconv.FormatFloat(float64(ms)/1000, 'f', 3, 64)
}

type listenRequest struct {
	Contents []listenContent `json:"contents"`
}

type listenContent struct {
	Role  string       `json:"role,omitempty"`
	Parts []listenPart `json:"parts"`
}

type listenPart struct {
	Text       string            `json:"text,omitempty"`
	InlineData *listenInlineData `json:"inline_data,omitempty"`
}

type listenInlineData struct {
	MimeType string `json:"mime_type"`
	Data     string `json:"data"`
}

type listenResponse struct {
	Candidates []struct {
		Content struct {
			Parts []struct {
				Text string `json:"text"`
			} `json:"parts"`
		} `json:"content"`
		FinishReason string `json:"finishReason"`
	} `json:"candidates"`
	Error *struct {
		Message string `json:"message"`
	} `json:"error"`
}

// askModel sends one clip and returns what came back.
func askModel(clip []byte, key string) (string, error) {
	body, err := json.Marshal(listenRequest{
		Contents: []listenContent{{
			Role: "user",
			Parts: []listenPart{
				{InlineData: &listenInlineData{
					MimeType: "audio/ogg",
					Data:     base64.StdEncoding.EncodeToString(clip),
				}},
				{Text: listenPrompt},
			},
		}},
	})
	if err != nil {
		return "", err
	}
	req, err := http.NewRequest("POST", listenAPI, bytes.NewReader(body))
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("x-goog-api-key", key)

	client := &http.Client{Timeout: listenTimeout}
	resp, err := client.Do(req)
	if err != nil {
		return "", fmt.Errorf("asking %s: %w", listenModel, err)
	}
	defer resp.Body.Close()

	raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
	if err != nil {
		return "", err
	}
	var result listenResponse
	if err := json.Unmarshal(raw, &result); err != nil {
		return "", fmt.Errorf("decoding response (HTTP %d): %w", resp.StatusCode, err)
	}
	if result.Error != nil {
		return "", fmt.Errorf("%s: %s", listenModel, result.Error.Message)
	}
	if len(result.Candidates) == 0 {
		return "", errors.New("no candidates in response")
	}
	c := result.Candidates[0]
	if len(c.Content.Parts) == 0 {
		if c.FinishReason != "" && c.FinishReason != "STOP" {
			return "", fmt.Errorf("generation stopped: %s", c.FinishReason)
		}
		return "", errors.New("no content in response")
	}
	text := strings.TrimSpace(c.Content.Parts[0].Text)
	if text == "" {
		return "", errors.New("empty transcript in response")
	}
	return text, nil
}

// printSourceView shows the source's own wording where the span is quotation.
//
// Inside a .quote the source settles the passage outright and the model is not
// needed; this view is what makes that visible. Fetching is best-effort: the
// other two views are still worth having when a site is down.
func printSourceView(ep *Episode, from, to int64) {
	ids := quotedSourcesIn(ep.Transcript, from, to)
	if len(ids) == 0 {
		fmt.Print("SOURCE\n  (span is commentary; no quotation is marked here)\n\n")
		return
	}
	for _, id := range ids {
		var src *DocSource
		for i := range ep.Transcript.Sources {
			if ep.Transcript.Sources[i].ID == id {
				src = &ep.Transcript.Sources[i]
				break
			}
		}
		if src == nil {
			continue
		}
		fmt.Printf("SOURCE  %s - %s, %q\n", src.ID, src.Author, src.Title)
		if src.URL == "" {
			fmt.Print("  (no URL in the transcript header)\n\n")
			continue
		}
		text, err := fetchSourceText(src.URL)
		if err != nil {
			fmt.Printf("  (unavailable: %v)\n  %s\n\n", err, src.URL)
			continue
		}
		spoken := spokenWords(ep.Transcript, from, to)
		if m := locateInSource(text, spoken); m != "" {
			fmt.Printf("%s\n\n", indent(m))
		} else {
			fmt.Printf("  (could not locate this passage in the source)\n  %s\n\n", src.URL)
		}
	}
}

// printTranscriptView shows what is in the file now.
//
// Last, and labelled, because it is the thing under test: an agent that reads
// it first has already been told what to hear.
func printTranscriptView(ep *Episode, from, to int64) {
	fmt.Print("TRANSCRIPT  recogniser output, for reference - this is what is being checked\n")
	n := 0
	for _, e := range ep.Transcript.Entries {
		if e.Kind != EntrySpeech || e.End < from || e.Start > to {
			continue
		}
		fmt.Printf("  %s  %s\n", formatTimestamp(e.Start), e.Text)
		n++
	}
	if n == 0 {
		fmt.Print("  (no lines in this span)\n")
	}
}

// quotedSourcesIn returns the sources quoted anywhere in the span, in the
// order they appear.
func quotedSourcesIn(d *Document, from, to int64) []string {
	if d == nil {
		return nil
	}
	var out []string
	seen := map[string]bool{}
	cur := ""
	for _, e := range d.Entries {
		switch e.Kind {
		case EntryQuoteStart:
			cur = e.Source
		case EntryQuoteEnd:
			cur = ""
		case EntrySpeech:
			if cur != "" && e.End >= from && e.Start <= to && !seen[cur] {
				seen[cur] = true
				out = append(out, cur)
			}
		}
	}
	return out
}

// spokenWords is the transcript's own text for the span, used to find the
// passage in the source.
func spokenWords(d *Document, from, to int64) []string {
	if d == nil {
		return nil
	}
	var ws []string
	for _, e := range d.Entries {
		if e.Kind == EntrySpeech && e.End >= from && e.Start <= to {
			ws = append(ws, strings.Fields(e.Text)...)
		}
	}
	return ws
}

// Go's regexp has no backreferences, so the paired tags whose contents must go
// are stripped one element at a time before the general tag strip.
var dropElemRe = []*regexp.Regexp{
	regexp.MustCompile(`(?is)<script[^>]*>.*?</script>`),
	regexp.MustCompile(`(?is)<style[^>]*>.*?</style>`),
	regexp.MustCompile(`(?is)<nav[^>]*>.*?</nav>`),
	regexp.MustCompile(`(?is)<header[^>]*>.*?</header>`),
	regexp.MustCompile(`(?is)<footer[^>]*>.*?</footer>`),
}

var tagRe = regexp.MustCompile(`(?s)<[^>]+>`)
var wsRe = regexp.MustCompile(`\s+`)
var wordRe = regexp.MustCompile(`[a-z0-9]+`)

// fetchSourceText strips a page to text. Crude on purpose: it only has to be
// good enough to find a paragraph that is being read aloud.
func fetchSourceText(url string) (string, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", err
	}
	req.Header.Set("User-Agent", "observations-listen/1 (+https://profpatsch.de)")
	resp, err := (&http.Client{Timeout: 60 * time.Second}).Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("HTTP %d", resp.StatusCode)
	}
	b, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
	if err != nil {
		return "", err
	}
	t := string(b)
	for _, re := range dropElemRe {
		t = re.ReplaceAllString(t, " ")
	}
	t = tagRe.ReplaceAllString(t, " ")
	t = strings.NewReplacer("&amp;", "&", "&lt;", "<", "&gt;", ">",
		"&quot;", `"`, "&#39;", "'", "&nbsp;", " ", "&#8217;", "'",
		"&rsquo;", "'", "&ldquo;", `"`, "&rdquo;", `"`).Replace(t)
	return wsRe.ReplaceAllString(t, " "), nil
}

// locateInSource finds the stretch of source text the spoken words come from,
// by matching the longest run of consecutive words it can.
//
// The spoken version has stumbles and mishearings in it, so an exact match is
// not available; anchoring on a run of words that does match and then showing
// the source's own sentences around it is what makes the difference visible.
func locateInSource(text string, spoken []string) string {
	if len(spoken) < 4 {
		return ""
	}
	srcWords := wordRe.FindAllString(strings.ToLower(text), -1)
	srcIdx := wordRe.FindAllStringIndex(strings.ToLower(text), -1)
	var norm []string
	for _, w := range spoken {
		if m := wordRe.FindString(strings.ToLower(w)); m != "" {
			norm = append(norm, m)
		}
	}
	if len(norm) < 4 {
		return ""
	}
	// Anchor on the longest matching run, trying progressively shorter needles
	// from the start of the passage.
	for n := min(8, len(norm)); n >= 4; n-- {
		needle := norm[:n]
		for i := 0; i+n <= len(srcWords); i++ {
			if !equalWords(srcWords[i:i+n], needle) {
				continue
			}
			// Show from here to roughly as many words as were spoken.
			end := i + len(norm)
			if end > len(srcWords) {
				end = len(srcWords)
			}
			lo := srcIdx[i][0]
			hi := srcIdx[end-1][1]
			return strings.TrimSpace(text[lo:hi])
		}
	}
	return ""
}

func equalWords(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	for i := range a {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}

// sameWords compares two readings ignoring case, punctuation and spacing,
// which is the level at which a disagreement matters.
func sameWords(a, b string) bool {
	return strings.Join(wordRe.FindAllString(strings.ToLower(a), -1), " ") ==
		strings.Join(wordRe.FindAllString(strings.ToLower(b), -1), " ")
}

func indent(s string) string {
	lines := strings.Split(strings.TrimSpace(s), "\n")
	for i, l := range lines {
		lines[i] = "  " + strings.TrimSpace(l)
	}
	return strings.Join(lines, "\n")
}

// parseEpisodeArg accepts 001 and 1 alike.
func parseEpisodeArg(s string) (int, error) {
	n, err := strconv.Atoi(strings.TrimSpace(s))
	if err != nil || n <= 0 {
		return 0, fmt.Errorf("episode %q is not a number", s)
	}
	return n, nil
}

// parseSpan accepts the transcript's own HH:MM:SS.mmm, the MM:SS a person
// reads off a player, and bare seconds.
func parseSpan(s string) (int64, error) {
	s = strings.TrimSpace(s)
	if s == "" {
		return 0, errors.New("empty timestamp")
	}
	if !strings.Contains(s, ":") {
		f, err := strconv.ParseFloat(s, 64)
		if err != nil || f < 0 {
			return 0, fmt.Errorf("%q is not seconds or HH:MM:SS.mmm", s)
		}
		return int64(f * 1000), nil
	}
	parts := strings.Split(s, ":")
	if len(parts) > 3 {
		return 0, fmt.Errorf("%q has too many colons", s)
	}
	var total float64
	for _, p := range parts {
		v, err := strconv.ParseFloat(p, 64)
		if err != nil || v < 0 {
			return 0, fmt.Errorf("%q is not seconds or HH:MM:SS.mmm", s)
		}
		total = total*60 + v
	}
	return int64(total * 1000), nil
}