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
// observations publishes an audio format: one person reading someone else's
// text out loud and thinking about it. See observations(7) for what the format
// is and why the pipeline is shaped this way, and observations(1) for the
// reference.
package main

import (
	"flag"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"sort"
	"strings"
)

const usage = `observations — publish audio readings of other people's texts

usage:
  observations add [flags] <recording.m4a>   ingest a recording
  observations render [flags]                render the site
  observations list [flags]                  list episodes
  observations transcript <recording.m4a>    print a recording's transcript
  observations listen <ep> <from> <to>       check a passage by ear
  observations convert [flags]               migrate old .transcript.json files

Run 'observations <command> -h' for the flags of a command.
See observations(1) for the full reference.
`

func main() {
	if len(os.Args) < 2 {
		fmt.Fprint(os.Stderr, usage)
		os.Exit(2)
	}
	var err error
	switch os.Args[1] {
	case "add":
		err = cmdAdd(os.Args[2:])
	case "render":
		err = cmdRender(os.Args[2:])
	case "list":
		err = cmdList(os.Args[2:])
	case "transcript":
		err = cmdTranscript(os.Args[2:])
	case "listen":
		err = cmdListen(os.Args[2:])
	case "convert":
		err = cmdConvert(os.Args[2:])
	case "-h", "--help", "help":
		fmt.Print(usage)
		return
	default:
		fmt.Fprintf(os.Stderr, "observations: unknown command %q\n\n%s", os.Args[1], usage)
		os.Exit(2)
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "observations: %v\n", err)
		os.Exit(1)
	}
}

// dirs holds the three locations the tool works with. They are flags rather
// than constants so the tool can be run against a scratch tree in tests and
// from a nix build.
type dirs struct {
	episodes string
	audio    string
	out      string
}

func (d *dirs) flags(fs *flag.FlagSet) {
	fs.StringVar(&d.episodes, "episodes", "episodes", "directory of episode metadata (in git)")
	fs.StringVar(&d.audio, "audio", "audio", "directory of audio files (NOT in git)")
	fs.StringVar(&d.out, "out", "", "directory to render the site into")
}

func cmdAdd(args []string) error {
	fs := flag.NewFlagSet("add", flag.ExitOnError)
	var d dirs
	d.flags(fs)
	var (
		title        = fs.String("source-title", "", "title of the text being read (required)")
		url          = fs.String("source-url", "", "URL of the text being read (required)")
		author       = fs.String("source-author", "", "author of the text (required)")
		published    = fs.String("source-published", "", "publication date of the text, YYYY-MM-DD (required)")
		site         = fs.String("source-site", "", "publication the text appeared in")
		note         = fs.String("source-note", "", "what this text is doing in the episode (\"intro only\")")
		episodeTitle = fs.String("title", "", "title of the episode (default: the source's title)")
		recorded     = fs.String("recorded", "", "date of the recording, YYYY-MM-DD (default: the file's mtime)")
		notes        = fs.String("notes", "", "prose shown on the episode page")
		number       = fs.Int("number", 0, "episode number (default: next free)")
		ffprobeBin   = fs.String("ffprobe", "ffprobe", "path to ffprobe")
		ffmpegBin    = fs.String("ffmpeg", "ffmpeg", "path to ffmpeg")
	)
	fs.Usage = func() {
		fmt.Fprint(fs.Output(), "usage: observations add [flags] <recording.m4a>\n\n")
		fs.PrintDefaults()
	}
	if err := fs.Parse(args); err != nil {
		return err
	}
	if fs.NArg() != 1 {
		fs.Usage()
		return fmt.Errorf("expected exactly one recording, got %d", fs.NArg())
	}
	src := fs.Arg(0)

	info, err := os.Stat(src)
	if err != nil {
		return err
	}
	if *recorded == "" {
		*recorded = info.ModTime().Format("2006-01-02")
	}

	pr, err := probe(*ffprobeBin, src)
	if err != nil {
		return err
	}

	n := *number
	if n == 0 {
		if n, err = nextNumber(d.episodes); err != nil {
			return err
		}
	}

	ep := &Episode{
		Number:       n,
		Recorded:     *recorded,
		Notes:        *notes,
		EpisodeTitle: *episodeTitle,
		// add takes one source, which is the common case. An episode built
		// around several texts gets the rest added to its JSON by hand — see
		// observations(1). Zipping repeated flags into a list positionally
		// would silently misalign the moment one source has a --source-site
		// and another does not.
		Sources: []Source{{
			Title:     *title,
			URL:       *url,
			Author:    *author,
			Published: *published,
			Site:      *site,
			Note:      *note,
		}},
		Audio: Audio{
			File:     fmt.Sprintf("%03d%s", n, strings.ToLower(filepath.Ext(src))),
			Bytes:    pr.Bytes,
			Duration: pr.DurationMs,
			MIME:     mimeForExt(filepath.Ext(src)),
		},
	}
	if err := ep.validate(); err != nil {
		return err
	}
	if _, err := os.Stat(episodePath(d.episodes, n)); err == nil {
		return fmt.Errorf("episode %03d already exists (pass -number to override)", n)
	}

	// The transcript exists only inside this file, and every ordinary audio
	// operation drops it silently. A missing track is worth saying out loud —
	// it usually means the file has already been through such a tool — but it
	// is not a reason to refuse the episode: plenty of recordings never had
	// one, and an episode without a transcript is still an episode. See
	// observations(7).
	if pr.TranscriptStream >= 0 {
		raw, err := extractStream(*ffmpegBin, src, pr.TranscriptStream)
		if err != nil {
			return err
		}
		tr, err := DecodeTranscript(raw)
		if err != nil {
			return fmt.Errorf("decoding transcript: %w", err)
		}
		// The recogniser's flat word list is turned into subtitle-shaped
		// lines here, at the edge: everything downstream of this point deals
		// in the stored format, which is the one people edit.
		doc := NewDocument(tr)
		doc.Episode = ep.Slug()
		doc.Recorded = ep.Recorded
		for i, s := range ep.Sources {
			doc.Sources = append(doc.Sources, DocSource{
				ID:     sourceID(s, i),
				Author: s.Author,
				Title:  s.Title,
				URL:    s.URL,
			})
		}
		ep.Transcript = doc
		fmt.Fprintf(os.Stderr, "transcript: %d words in %d lines (stream %d)\n",
			doc.WordCount(), len(doc.Entries), pr.TranscriptStream)
	} else {
		var found string
		if len(pr.DataMIMEs) > 0 {
			ms := make([]string, 0, len(pr.DataMIMEs))
			for _, m := range pr.DataMIMEs {
				ms = append(ms, m)
			}
			sort.Strings(ms)
			found = "; data tracks present: " + strings.Join(ms, ", ")
		}
		fmt.Fprintf(os.Stderr,
			"transcript: none%s\n"+
				"        If this recording had one, it has been lost to a transcode, remux or\n"+
				"        edit, and cannot be recovered; use the original file from the recorder.\n",
			found)
	}

	if err := copyFile(src, filepath.Join(d.audio, ep.Audio.File)); err != nil {
		return err
	}
	if err := writeEpisode(d.episodes, ep); err != nil {
		return err
	}

	fmt.Printf("%s  %s\n", ep.Slug(), ep.Title())
	fmt.Printf("  audio      %s (%s, %s)\n", filepath.Join(d.audio, ep.Audio.File), ep.DurationHMS(), humanBytes(ep.Audio.Bytes))
	fmt.Printf("  metadata   %s\n", episodePath(d.episodes, ep.Number))
	if d.out != "" {
		return render(&d)
	}
	fmt.Println("\nNext: observations render -out …, then commit and push.")
	return nil
}

func cmdRender(args []string) error {
	fs := flag.NewFlagSet("render", flag.ExitOnError)
	var d dirs
	d.flags(fs)
	if err := fs.Parse(args); err != nil {
		return err
	}
	if d.out == "" {
		return fmt.Errorf("-out is required")
	}
	return render(&d)
}

func cmdList(args []string) error {
	fs := flag.NewFlagSet("list", flag.ExitOnError)
	var d dirs
	d.flags(fs)
	if err := fs.Parse(args); err != nil {
		return err
	}
	eps, err := loadEpisodes(d.episodes)
	if err != nil {
		return err
	}
	if len(eps) == 0 {
		fmt.Fprintln(os.Stderr, "no episodes yet")
		return nil
	}
	for _, e := range eps {
		words := 0
		if e.Transcript != nil {
			words = e.Transcript.WordCount()
		}
		fmt.Printf("%s  %-10s %8s  %6d words  %s\n",
			e.Slug(), e.Recorded, e.DurationHMS(), words, e.Subject())
	}
	return nil
}

// cmdTranscript prints the transcript embedded in a recording, without
// ingesting it.
//
// Everything this does was already reachable through `add`, but only as part
// of ingesting: add copies the audio, writes episode metadata and allocates a
// number. That is the wrong tool for the two things people actually want here
// — checking whether a file still carries its transcript before doing anything
// irreversible to it, and reading the transcript of a recording that is not an
// episode and never will be.
//
// It is read-only. It writes nothing, touches nothing, and takes no episode
// directory, so it is safe to point at any file including one already
// published.
func cmdTranscript(args []string) error {
	fs := flag.NewFlagSet("transcript", flag.ExitOnError)
	ffprobeBin := fs.String("ffprobe", "ffprobe", "path to ffprobe")
	ffmpegBin := fs.String("ffmpeg", "ffmpeg", "path to ffmpeg")
	format := fs.String("format", "transcript", "output: transcript, text or streams")
	fs.Usage = func() {
		fmt.Fprint(fs.Output(), "usage: observations transcript [flags] <recording.m4a>\n\n")
		fmt.Fprint(fs.Output(), "Prints the transcript Google Recorder embedded in a recording.\n")
		fmt.Fprint(fs.Output(), "Reads the file and writes nothing.\n\n")
		fs.PrintDefaults()
	}
	if err := fs.Parse(args); err != nil {
		return err
	}
	if fs.NArg() != 1 {
		fs.Usage()
		return fmt.Errorf("need exactly one recording")
	}
	src := fs.Arg(0)

	pr, err := probe(*ffprobeBin, src)
	if err != nil {
		return err
	}

	// `streams` answers "what is in this file", which is the question worth
	// asking when the transcript is missing and the reason is not obvious.
	if *format == "streams" {
		fmt.Printf("%s\n", src)
		fmt.Printf("  duration   %s\n", (&Episode{Audio: Audio{Duration: pr.DurationMs}}).DurationHMS())
		fmt.Printf("  audio      %s\n", pr.AudioCodec)
		if len(pr.DataMIMEs) == 0 {
			fmt.Printf("  data       none\n")
		}
		idx := make([]int, 0, len(pr.DataMIMEs))
		for i := range pr.DataMIMEs {
			idx = append(idx, i)
		}
		sort.Ints(idx)
		for _, i := range idx {
			mark := ""
			if i == pr.TranscriptStream {
				mark = "  <- transcript"
			}
			fmt.Printf("  stream %d   %s%s\n", i, pr.DataMIMEs[i], mark)
		}
		return nil
	}

	if pr.TranscriptStream < 0 {
		// The same diagnosis add gives, because the question being asked is
		// the same one: has this file been through something that stripped it?
		var found string
		if len(pr.DataMIMEs) > 0 {
			ms := make([]string, 0, len(pr.DataMIMEs))
			for _, m := range pr.DataMIMEs {
				ms = append(ms, m)
			}
			sort.Strings(ms)
			found = "; data tracks present: " + strings.Join(ms, ", ")
		}
		return fmt.Errorf(
			"%s carries no transcript track%s\n"+
				"        A recording that has been transcoded, remuxed or edited has lost it,\n"+
				"        and it cannot be recovered. Use the original file from the recorder.", src, found)
	}

	raw, err := extractStream(*ffmpegBin, src, pr.TranscriptStream)
	if err != nil {
		return err
	}
	tr, err := DecodeTranscript(raw)
	if err != nil {
		return fmt.Errorf("decoding transcript: %w", err)
	}
	doc := NewDocument(tr)

	switch *format {
	case "transcript":
		return WriteTranscript(os.Stdout, doc)
	case "text":
		_, err := fmt.Println(doc.Text())
		return err
	default:
		return fmt.Errorf("unknown -format %q: want transcript, text or streams", *format)
	}
}

// cmdConvert migrates NNN.transcript.json, the shape the recogniser's
// protobuf decoded into, to NNN.transcript, the shape people edit.
//
// It exists for the two episodes that were ingested before the stored format
// changed, and is kept afterwards because it is the only way back if the
// conversion ever has to be redone from the JSON in git history.
func cmdConvert(args []string) error {
	fs := flag.NewFlagSet("convert", flag.ExitOnError)
	var d dirs
	d.flags(fs)
	force := fs.Bool("force", false, "overwrite an existing .transcript")
	if err := fs.Parse(args); err != nil {
		return err
	}

	names, err := filepath.Glob(filepath.Join(d.episodes, "*.transcript.json"))
	if err != nil {
		return err
	}
	if len(names) == 0 {
		fmt.Fprintln(os.Stderr, "no .transcript.json files to convert")
		return nil
	}
	sort.Strings(names)

	for _, src := range names {
		var tr Transcript
		if err := readJSONFile(src, &tr); err != nil {
			return err
		}
		base := strings.TrimSuffix(src, ".transcript.json")
		ep, err := readEpisodeMeta(base + ".json")
		if err != nil {
			return err
		}
		doc := NewDocument(&tr)
		doc.Episode = ep.Slug()
		doc.Recorded = ep.Recorded
		for i, s := range ep.Sources {
			doc.Sources = append(doc.Sources, DocSource{
				ID: sourceID(s, i), Author: s.Author, Title: s.Title, URL: s.URL,
			})
		}

		dst := base + ".transcript"
		if _, err := os.Stat(dst); err == nil && !*force {
			return fmt.Errorf("%s exists; pass -force to overwrite", dst)
		}
		if err := writeTranscriptFile(dst, doc); err != nil {
			return err
		}
		fmt.Printf("%s -> %s  (%d words, %d lines)\n",
			filepath.Base(src), filepath.Base(dst), doc.WordCount(), len(doc.Entries))
	}
	fmt.Fprintln(os.Stderr, "\nThe .transcript.json files are now unused; remove them in the same commit.")
	return nil
}

func mimeForExt(ext string) string {
	switch strings.ToLower(ext) {
	case ".m4a", ".mp4", ".m4b":
		// audio/mp4 rather than the legacy audio/x-m4a: it is the registered
		// type, and podcast clients match on it.
		return "audio/mp4"
	case ".mp3":
		return "audio/mpeg"
	case ".ogg", ".opus":
		return "audio/ogg"
	case ".wav":
		return "audio/wav"
	default:
		return "application/octet-stream"
	}
}

func humanBytes(n int64) string {
	switch {
	case n >= 1<<20:
		return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
	case n >= 1<<10:
		return fmt.Sprintf("%.1f kB", float64(n)/(1<<10))
	default:
		return fmt.Sprintf("%d B", n)
	}
}

func copyFile(src, dst string) error {
	if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
		return err
	}
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()

	tmp := dst + ".tmp"
	out, err := os.Create(tmp)
	if err != nil {
		return err
	}
	if _, err := io.Copy(out, in); err != nil {
		out.Close()
		os.Remove(tmp)
		return err
	}
	if err := out.Close(); err != nil {
		os.Remove(tmp)
		return err
	}
	return os.Rename(tmp, dst)
}