python-voiceio 1.2.0__py3-none-any.whl → 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-voiceio
3
- Version: 1.2.0
3
+ Version: 1.3.0
4
4
  Summary: Voice dictation for Linux. Speak → text, locally, instantly.
5
5
  Author: Hugo Montenegro
6
6
  License-Expression: MIT
@@ -182,7 +182,8 @@ Most dictation errors are proper nouns and jargon: `PostgreSQL` heard as `post g
182
182
  voiceio learn import DIR --source phone # optional: add your own recordings from elsewhere
183
183
  voiceio learn label # a stronger teacher model (large-v3-turbo) transcribes your clips
184
184
  voiceio learn review # fix the teacher where it matters: your names and terms
185
- voiceio learn review --test # once: verify the held-out clips, so eval scores against the truth
185
+ voiceio learn review --test # verify the held-out clips, so eval scores against the truth: it asks only
186
+ # where the teacher and your live decode disagree, quickest clips first
186
187
  voiceio learn augment # synthesize extra examples of rare terms with local TTS
187
188
  voiceio learn build # freeze a versioned train/dev/test dataset (the test split never trains)
188
189
  voiceio learn eval # score the current model on your held-out clips: WER and term recall
@@ -191,6 +192,7 @@ voiceio learn train # LoRA fine-tune (needs the `train` extra; decoder-only
191
192
  voiceio learn promote <run> # dictate with the fine-tune; `voiceio learn rollback` undoes it
192
193
  voiceio learn maintain # later: label what's new, and once 50+ clips piled up, retrain and compare
193
194
  voiceio learn schedule on # …or let it run `maintain` every night, and notify you when a model wins
195
+ # (--auto-promote: switch to a winner by itself; `learn rollback` undoes it)
194
196
  ```
195
197
 
196
198
  Labeling, training and offline eval run in an idle-priority cgroup, so they never slow dictation down. Everything stays on your machine unless you choose `train --remote`.
@@ -301,7 +303,6 @@ Logs: `journalctl --user -u voiceio` or `~/.local/state/voiceio/voiceio.log`.
301
303
  ## Roadmap
302
304
 
303
305
  - **A landing page** — voiceio as local, open-source, private dictation that learns from you. A draft is in [`site/index.html`](site/index.html), ready for GitHub Pages.
304
- - **Hands-off promotion** — `learn schedule` already retrains nightly and tells you when a model wins; next is switching to it automatically, with one-command rollback.
305
306
  - **Unbounded vocabulary** — move to a decoder whose biasing has no token cap (see [model choice](CONTRIBUTING.md#model-choice-why-whisper-and-what-would-change-it)).
306
307
  - **One model everywhere** — sync your fine-tune to your phone server and laptops, peer to peer.
307
308
 
@@ -1,7 +1,7 @@
1
- python_voiceio-1.2.0.dist-info/licenses/LICENSE,sha256=Gz61o8jFTAvZUZyB3nWDB3DQQVuipjfPkVu9W8hBHM0,1072
2
- voiceio/__init__.py,sha256=MpAT5hgNoHnTtG1XRD_GV_A7QrHVU6vJjGSw_8qMGA4,22
1
+ python_voiceio-1.3.0.dist-info/licenses/LICENSE,sha256=Gz61o8jFTAvZUZyB3nWDB3DQQVuipjfPkVu9W8hBHM0,1072
2
+ voiceio/__init__.py,sha256=F5mW07pSyGrqDNY2Ehr-UpDzpBtN-FsYU0QGZWf6PJE,22
3
3
  voiceio/__main__.py,sha256=xT5QCGGreYMisHO7Lh_Y-xAQ2TOzG2D7npKknGNcWSY,53
4
- voiceio/app.py,sha256=_FfrMN1MFWk8H5KciGu2niJm3fZJlNR2Ju9mP9s5brk,31798
4
+ voiceio/app.py,sha256=K9vz9iZRRTavyWNYaZMYxwsvaPJBRYcQjFFyi4YOfOM,32164
5
5
  voiceio/audio_source.py,sha256=rR6NRtNzmZ8uqmNPxareBWTJmuBaOxIGI5QINR_l-qc,9102
6
6
  voiceio/backends.py,sha256=-rs1YhPblub4NjFb6qCD7Ih9FqBRXtPuvjVv9bQoQ1w,368
7
7
  voiceio/clipboard_read.py,sha256=lz75CkRGh7pyvO6xvoUmxJDl-Gwie1xlXQHK70PO84I,4261
@@ -12,13 +12,13 @@ voiceio/corrections.py,sha256=IIRViwjL9kkMy26-1dd0DtTfT0Tiedn6pmmHoaeayMQ,10047
12
12
  voiceio/demo.py,sha256=jA282e7UWDwtP1IXT2bPHH5wl6eKdBNvOJcoNDWzZlQ,8766
13
13
  voiceio/display.py,sha256=ZGBNRjuvg3chkJjduyPJs4s5ZY5vqC_mcaov94PIPzo,5313
14
14
  voiceio/feedback.py,sha256=i1Hkd_bydOOQ8p19Bz4bYougjQtozKGLjfKc5DKRDT0,5711
15
- voiceio/health.py,sha256=r0nMDozuhk1nZNpCiVhmezC_7P6ElQpaBB_IomzmXF8,22166
15
+ voiceio/health.py,sha256=PuOQ1DOtoLUbx-tU0vXRUKe_mdsgVi5up0r1jDLvCnk,22267
16
16
  voiceio/hints.py,sha256=dmoiMAJ0YGTWwFc9kIPvEs_BQJN7UEUiwYuLUD_GoQQ,1415
17
17
  voiceio/history.py,sha256=cD3Ysa39qt6uKbrcLeRQt-FOJcYCoqie4UNsUWF7DuM,5763
18
18
  voiceio/llm.py,sha256=cO2RHM2zHxTD4r5mFFNatB-pjOSl29Wx_I00f7ywYCw,9161
19
19
  voiceio/llm_api.py,sha256=4jJ5U1Dop-3uoM9RM3bjUMxB4kYNNjwKbOwIIj0ll3U,9390
20
20
  voiceio/numbers.py,sha256=CXJtlMhmV6_9Z1FtKAF4-RXycw8voV-BYHPBpdw1I6Y,13571
21
- voiceio/pidlock.py,sha256=RInlF_8H7wR0nqkdlhUfxYs7OGzHIvb5p-XDjjQSTNg,619
21
+ voiceio/pidlock.py,sha256=OZLNskUyv9_F3WgyHZWw8WmKt0W7ioxH6xgHitOwCww,1216
22
22
  voiceio/platform.py,sha256=uG_5KeYey_29GCn4nSOQJ1UpoCrBC_m2DR7IeoRnuL4,19142
23
23
  voiceio/postcorrect.py,sha256=JN5l9xnyGfYq2_owSUwkJ513QiQQKxCrT3hjU5aJCpg,17322
24
24
  voiceio/postprocess.py,sha256=rzKmf_ZCskhGnqLEbHaiQX-Sz9yutdJwcwposz7GJ4Q,4661
@@ -26,7 +26,7 @@ voiceio/privacy.py,sha256=FqnA9jx9RCqWW-i6Dh7JcT7vzz97kbUGyQEvsHLvpqc,573
26
26
  voiceio/prompt.py,sha256=9iza8KoQxvO_U9NPMJ8Ep7j-zkIs9nW8N5sacCRpsEk,2904
27
27
  voiceio/recorder.py,sha256=k51Py6av0YFkc1ENXsrXuFIL3G9bmsAijGq3X5r7pG4,15734
28
28
  voiceio/retention.py,sha256=TH_D29EUYyzEPl5FK0q32mpsSk0-0bx56JwAH83FBHI,6272
29
- voiceio/service.py,sha256=_cTb1AQ57cF8-eW3SKvDkCP46S5yJqhty1fe_eI8zbQ,14324
29
+ voiceio/service.py,sha256=N4idcPlDaarLXEMMts69Viqro5VJqmHywXmqr99UGA4,14915
30
30
  voiceio/streaming.py,sha256=hKak7ULkZbkHl5Fw0SnnZsEK3alv2s8dcuCcyBzpIQY,24700
31
31
  voiceio/suggest.py,sha256=jX4bCpnddyrteKfRBPbnUgf-Rk5145LFaSTat0_Ll2E,4836
32
32
  voiceio/tokens.py,sha256=m5tusR3zEBX7fRKaDUj4z-DSv8NcMhE-02HviAziENQ,5710
@@ -41,9 +41,9 @@ voiceio/cli/configcmd.py,sha256=YF7t-LkwEYEGH4qcO86xehWVX0LvltqxjDFpMF5ljjA,2858
41
41
  voiceio/cli/corrections.py,sha256=OBjgiOhtWlTQpQq0HLAvk5-EfKJ7NNt-hnNBHm7obEc,4247
42
42
  voiceio/cli/doctor.py,sha256=P8bOn4xedMistlKHhNeeGxRsmogV6jBVKc-CUbo0LXs,7769
43
43
  voiceio/cli/history.py,sha256=IWyFIozX5PUwtrU17JlkNea9nP_oKLsXfkxIVHjkfD0,1516
44
- voiceio/cli/learn.py,sha256=cQ3HOf0LXybRf-40QA6Jvb54gy7rpCCz_2xavPJE7wk,24859
44
+ voiceio/cli/learn.py,sha256=U6NKRQKsV6P6wxWr_Lhx_QwVio640nLZ2iggCmqT5Qo,26516
45
45
  voiceio/cli/models.py,sha256=fye_mHbsXLY11uRC1BCDlucCHPny9ftoehAeUJPMJv0,4263
46
- voiceio/cli/servicecmd.py,sha256=hcaQD1NL38fvkrHtId1307MIgyi2O2xBP6YvG8CTngc,4219
46
+ voiceio/cli/servicecmd.py,sha256=2St2WfLkt06EpC51I5i9Ykv_pvLKzu_dz01M-29O3-4,4830
47
47
  voiceio/cli/uninstall.py,sha256=Vqnq6-4hjhDrxqkU_1wtXkY5BU_Tqa-TjZA0Qpf12e4,8921
48
48
  voiceio/cli/vocab.py,sha256=lxxuSukefvIHV4fFSduCQQewXY0_Bvf5sDnG4bqLWH8,4418
49
49
  voiceio/core/__init__.py,sha256=K0b4duczohS3IrIMLp9fYhfb-GeuyQaOVH_8teYGsQM,277
@@ -75,10 +75,10 @@ voiceio/ibus/textlimit.py,sha256=4Hmn2LDEOs7h-Hb2-cT1HkvIRepDgZq4KRI9KD3xiBQ,251
75
75
  voiceio/learn/__init__.py,sha256=Q98-C809lkMqTS0OAV1xNVtqHz9NvuekivXiHiVHBWA,750
76
76
  voiceio/learn/augment.py,sha256=qyegRlg3cQF5CT0HV85Jm93Jd9xZpjWwbFVk_VzFdiI,4105
77
77
  voiceio/learn/clean.py,sha256=1ItIfIAsqxZLZ76T4oF7kSr4Poo-z_6GEzhrlt21uMo,4922
78
- voiceio/learn/evaluate.py,sha256=_a1sIum_T2f5lEVJ9-4VjgXOwmLh-B8R1PI7C7zmWH8,12600
78
+ voiceio/learn/evaluate.py,sha256=sW2lfV9jK22fpFFgxh9p6cp0pcTt5KjXV3eatsrg9sM,13233
79
79
  voiceio/learn/importer.py,sha256=uB-gHWwSewZYTx22j9h941ARtDE8BFHmf8p3HaHUC6g,3544
80
80
  voiceio/learn/metrics.py,sha256=b2xWUzPpNpXHn6zgS1upPbEcpW3ExH9SmSLIUzPhStQ,5174
81
- voiceio/learn/review.py,sha256=p11kRY-PF9YhS7aYjcYpDUJavUn8OXXz4d6S-MGfCGE,4575
81
+ voiceio/learn/review.py,sha256=X5qs5yEf20Ao3gMhsbW3Eur62hSqy9AYlv08Pcrllxo,5572
82
82
  voiceio/learn/store.py,sha256=MauWhGaI2drMbiChIZOblpPS_uVAw-1sNWGyGACHYw8,12816
83
83
  voiceio/learn/teacher.py,sha256=uF4hQkrdjv012TTBRSwrhQqqAeCFNoidABcrgzSVUoI,3696
84
84
  voiceio/learn/train.py,sha256=zTyftCsUV6hYy9WA8ftZtqjVbYJ-C7py0EoxavXWr7I,17628
@@ -125,8 +125,8 @@ voiceio/typers/pynput_type.py,sha256=Rzkixn08iaIqSCZ5vRybaHpn05lkx4FiEa_OakaiM1A
125
125
  voiceio/typers/wtype.py,sha256=d1wG-HZdYDQxXIysV_Xvk9HixDpaJgl3VEoKbP5vhIs,1786
126
126
  voiceio/typers/xdotool.py,sha256=dh1zhPqUT8ihJahJ7ZKm6PtfYY087UAzADx664DvQOM,1356
127
127
  voiceio/typers/ydotool.py,sha256=e19GvDHL9GS-jgh_hzW3PGBFPCc4IJCWsBWEzU_LqGs,5934
128
- python_voiceio-1.2.0.dist-info/METADATA,sha256=zEVw8vdKC4meGy8FxLLwba5SoZAb3LPu5OfTYlsusYo,21153
129
- python_voiceio-1.2.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
130
- python_voiceio-1.2.0.dist-info/entry_points.txt,sha256=iDIDmhvQ3xeN_CWsFne1t9STZ08I25I_wp0xmde_vMs,94
131
- python_voiceio-1.2.0.dist-info/top_level.txt,sha256=piwtn309lD6uexQyXdZ-efAVBJF9y6Wfr48Z-8zkNhg,8
132
- python_voiceio-1.2.0.dist-info/RECORD,,
128
+ python_voiceio-1.3.0.dist-info/METADATA,sha256=4h8z_g90MVVyjyWYlF4E-eFc8rYEc9ihcdM4gnPqHug,21201
129
+ python_voiceio-1.3.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
130
+ python_voiceio-1.3.0.dist-info/entry_points.txt,sha256=iDIDmhvQ3xeN_CWsFne1t9STZ08I25I_wp0xmde_vMs,94
131
+ python_voiceio-1.3.0.dist-info/top_level.txt,sha256=piwtn309lD6uexQyXdZ-efAVBJF9y6Wfr48Z-8zkNhg,8
132
+ python_voiceio-1.3.0.dist-info/RECORD,,
voiceio/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "1.2.0"
1
+ __version__ = "1.3.0"
voiceio/app.py CHANGED
@@ -43,6 +43,10 @@ class VoiceIO:
43
43
  @_state.setter
44
44
  def _state(self, value: _State) -> None:
45
45
  self.__state = value
46
+ # Only the instance holding the PID lock speaks for the daemon: a
47
+ # second launch must not overwrite the running one's state.
48
+ if not getattr(self, "_publishes_state", False):
49
+ return
46
50
  try: # best-effort: only `service restart` reads it
47
51
  tmp = config.STATE_PATH.with_suffix(".tmp")
48
52
  tmp.write_text(value.value)
@@ -660,7 +664,7 @@ class VoiceIO:
660
664
  self._typers.redetect_at_start()
661
665
 
662
666
  LOG_DIR.mkdir(parents=True, exist_ok=True)
663
- self._pid_fd = open(PID_PATH, "w")
667
+ self._pid_fd = open(PID_PATH, "a") # not "w": the running daemon's PID stays
664
668
  try:
665
669
  from voiceio.pidlock import lock_pid_file
666
670
  lock_pid_file(self._pid_fd)
@@ -669,8 +673,11 @@ class VoiceIO:
669
673
  log.error("Another voiceio instance is already running")
670
674
  print("voiceio is already running. Stop it first: voiceio service stop")
671
675
  return
676
+ self._pid_fd.truncate(0)
672
677
  self._pid_fd.write(str(os.getpid()))
673
678
  self._pid_fd.flush()
679
+ self._publishes_state = True
680
+ self._state = self._state
674
681
 
675
682
  self._typers.prepare()
676
683
 
voiceio/cli/learn.py CHANGED
@@ -84,10 +84,14 @@ def register(sub: argparse._SubParsersAction) -> None:
84
84
  help="new labeled clips needed before retraining (default 50)")
85
85
  mt.add_argument("--base", default="small")
86
86
  mt.add_argument("--epochs", type=int, default=4)
87
+ mt.add_argument("--auto-promote", action="store_true",
88
+ help="switch to the fine-tune when it wins, and restart the daemon")
87
89
  mt.set_defaults(func=cmd_maintain)
88
90
 
89
91
  sc = lsub.add_parser("schedule", help="Run `maintain` every night (systemd timer)")
90
92
  sc.add_argument("state", nargs="?", choices=("on", "off"), help="omit to show")
93
+ sc.add_argument("--auto-promote", action="store_true",
94
+ help="with on: switch to a fine-tune that wins, without asking")
91
95
  sc.set_defaults(func=cmd_schedule)
92
96
 
93
97
  pr = lsub.add_parser("promote", help="Use a trained model for dictation")
@@ -182,8 +186,7 @@ def cmd_status(args: argparse.Namespace) -> None:
182
186
  print(f"models {', '.join(runs)}")
183
187
  active = _cfg().model.name
184
188
  print(f"active {active}")
185
- from voiceio import service
186
- print(f"nightly {'on' if service.learn_timer_enabled() else 'off (voiceio learn schedule on)'}")
189
+ print(f"nightly {_schedule_state()}")
187
190
  promotable = _print_scores(ds, active, runs) if ds else None
188
191
  if promotable:
189
192
  nxt = f"promote {promotable}"
@@ -197,9 +200,9 @@ def _print_scores(ds: Path, active: str, runs: list[str]) -> str | None:
197
200
  """Scores on `ds` for the active model and each fine-tune; returns the
198
201
  run that beats the active model on everything, if any."""
199
202
  from voiceio.learn import evaluate
200
- current = evaluate.latest(active, ds.name)
203
+ current = evaluate.latest(active, ds.name, beam=_cfg().model.beam_size)
201
204
  rows = [(active + " (active)", current)] + [
202
- (run, evaluate.latest(str(_models_dir() / run / "ct2"), ds.name)) for run in runs]
205
+ (run, evaluate.latest(str(_models_dir() / run / "ct2"), ds.name, beam=_cfg().model.beam_size)) for run in runs]
203
206
  if not any(r for _, r in rows):
204
207
  return None
205
208
  print(f"\nscores on {ds.name} test clips:")
@@ -442,8 +445,9 @@ def cmd_maintain(args: argparse.Namespace) -> None:
442
445
  labeled = {c.audio for c in store.clips() if c.audio in labels}
443
446
  ds = store.latest_dataset()
444
447
  new = len(labeled - store.dataset_clips(ds)) if ds else len(labeled)
445
- if ds is not None and new < args.min_new:
446
- print(f"{new} new labeled clips since {ds.name}; retraining waits for {args.min_new}.")
448
+ if new < args.min_new: # the first dataset too: a handful of clips trains nothing
449
+ since = f" since {ds.name}" if ds else ""
450
+ print(f"{new} new labeled clips{since}; retraining waits for {args.min_new}.")
447
451
  return
448
452
  ds = store.build_dataset()
449
453
  print(f"built {ds.name} ({new} new clips)")
@@ -454,13 +458,39 @@ def cmd_maintain(args: argparse.Namespace) -> None:
454
458
  print(f"\n{_cfg().model.name} → {run.name} on {ds.name}:\n{table}")
455
459
  print(f"better or equal on everything — `voiceio learn promote {run.name}`" if ok
456
460
  else "not better on everything — keeping the current model")
457
- if ok: # often runs unattended at night: say so where it will be seen
458
- from voiceio import feedback
461
+ if not ok:
462
+ return
463
+ # Often runs unattended at night: say so where it will be seen.
464
+ from voiceio import feedback
465
+ if getattr(args, "auto_promote", False):
466
+ try:
467
+ cmd_promote(argparse.Namespace(run=run.name, force=False))
468
+ except SystemExit as refused: # the gate's own re-check said no
469
+ print(f"not promoted: {refused}")
470
+ return
471
+ from voiceio import service
472
+ if service.is_installed() and not service.restart_when_idle():
473
+ feedback.notify("VoiceIO: a better model is ready",
474
+ f"Switched to {run.name}; restart voiceio to use it "
475
+ "(a dictation was in progress). Undo: voiceio learn rollback",
476
+ urgent=True)
477
+ return
478
+ feedback.notify("VoiceIO: switched to a better model",
479
+ f"Trained on your dictation: {run.name}. Undo: voiceio learn rollback",
480
+ urgent=True)
481
+ else:
459
482
  feedback.notify("VoiceIO: a better model is ready",
460
483
  f"Trained on your dictation. Use it: voiceio learn promote {run.name}",
461
484
  urgent=True)
462
485
 
463
486
 
487
+ def _schedule_state() -> str:
488
+ from voiceio import service
489
+ if not service.learn_timer_enabled():
490
+ return "off (voiceio learn schedule on)"
491
+ return "on (auto-promote)" if service.learn_timer_auto_promotes() else "on"
492
+
493
+
464
494
  def cmd_schedule(args: argparse.Namespace) -> None:
465
495
  from voiceio import config, service
466
496
  if args.state == "on":
@@ -471,16 +501,18 @@ def cmd_schedule(args: argparse.Namespace) -> None:
471
501
  if missing := train.missing_train_deps():
472
502
  print(f"note: until {', '.join(missing)} are installed it only labels new clips;\n"
473
503
  f" to also retrain: {train.TRAIN_HINT}")
474
- if not service.install_learn_timer():
504
+ if not service.install_learn_timer(auto_promote=args.auto_promote):
475
505
  raise SystemExit("could not enable the timer (needs systemd --user)")
476
506
  print("on: every night ~03:30, `voiceio learn maintain` labels new dictation at idle "
477
- "priority, retrains once 50+ clips are new, and tells you if the result is better. "
478
- "It never switches models by itself.")
507
+ "priority, retrains once 50+ clips are new, and "
508
+ + ("switches to the result when it wins on your held-out clips "
509
+ "(undo: voiceio learn rollback)." if args.auto_promote else
510
+ "tells you if the result is better. It never switches models by itself."))
479
511
  elif args.state == "off":
480
512
  service.uninstall_learn_timer()
481
513
  print("off")
482
514
  else:
483
- print("on" if service.learn_timer_enabled() else "off — enable: voiceio learn schedule on")
515
+ print(_schedule_state())
484
516
 
485
517
 
486
518
  def _scores(result) -> dict:
@@ -506,16 +538,16 @@ def _check_beats_current(ct2: Path) -> None:
506
538
  """Refuse a promotion the evals don't support (a fine-tune can regress)."""
507
539
  from voiceio.learn import evaluate
508
540
  ds = store.latest_dataset()
509
- current = _cfg().model.name
541
+ current, beam = _cfg().model.name, _cfg().model.beam_size
510
542
  if ds is None:
511
543
  raise SystemExit("no dataset to compare on — `voiceio learn build`, or --force")
512
- missing = [m for m in (current, str(ct2)) if evaluate.latest(m, ds.name) is None]
544
+ missing = [m for m in (current, str(ct2)) if evaluate.latest(m, ds.name, beam=beam) is None]
513
545
  if missing:
514
546
  raise SystemExit("evaluate both models on the same clips first:\n"
515
547
  + "".join(f" voiceio learn eval --model {m}\n" for m in missing)
516
548
  + "(or promote anyway with --force)")
517
- ok, table = evaluate.promotion_verdict(evaluate.latest(str(ct2), ds.name),
518
- evaluate.latest(current, ds.name))
549
+ ok, table = evaluate.promotion_verdict(evaluate.latest(str(ct2), ds.name, beam=beam),
550
+ evaluate.latest(current, ds.name, beam=beam))
519
551
  print(f"on {ds.name} test clips, {current} → fine-tune:\n{table}")
520
552
  if not ok:
521
553
  raise SystemExit("the fine-tune is worse on something — not promoting (--force overrides)")
voiceio/cli/servicecmd.py CHANGED
@@ -85,23 +85,35 @@ def _cmd_service(args: argparse.Namespace) -> None:
85
85
  pass
86
86
 
87
87
 
88
- def wait_until_idle(timeout: float = 300.0, poll: float = 0.25) -> bool:
88
+ def wait_until_idle(timeout: float = 300.0, poll: float = 0.25,
89
+ finalizing_timeout: float = 60.0) -> bool:
89
90
  """Wait for the daemon to finish any dictation in progress (stopping it
90
- mid-recording loses what was said). True once idle or not running."""
91
+ mid-recording loses what was said). True once idle or not running; False
92
+ when it stayed busy. A decode stuck finalizing gets a shorter wait: a
93
+ restart is how that is recovered."""
91
94
  import time
92
95
 
93
- from voiceio.config import STATE_PATH
94
- deadline, told = time.monotonic() + timeout, False
95
- while time.monotonic() < deadline:
96
- try:
97
- state = STATE_PATH.read_text().strip()
98
- except OSError:
99
- return True # not running (or pre-1.1): nothing to wait for
100
- if state in ("idle", "error"):
101
- return True
102
- if not told:
103
- print(f"Waiting for the dictation in progress to finish ({state})…", flush=True)
104
- told = True
105
- time.sleep(poll)
106
- print("Still busy; going ahead. (--now skips the wait.)", file=sys.stderr)
107
- return False
96
+ from voiceio.config import PID_PATH, STATE_PATH
97
+ from voiceio.pidlock import daemon_alive
98
+ start, told = time.monotonic(), False
99
+ try:
100
+ while True:
101
+ if not daemon_alive(PID_PATH):
102
+ return True # crashed or stopped: its state file is stale
103
+ try:
104
+ state = STATE_PATH.read_text().strip()
105
+ except OSError:
106
+ return True # pre-1.1 daemon: nothing to wait for
107
+ if state in ("idle", "error"):
108
+ return True
109
+ waited = time.monotonic() - start
110
+ if waited > (finalizing_timeout if state == "finalizing" else timeout):
111
+ print(f"Still {state}; going ahead. (--now skips the wait.)", file=sys.stderr)
112
+ return False
113
+ if not told:
114
+ print(f"Waiting for the dictation in progress to finish ({state})…", flush=True)
115
+ told = True
116
+ time.sleep(poll)
117
+ except KeyboardInterrupt:
118
+ print("\nNot waiting.", file=sys.stderr)
119
+ sys.exit(130)
voiceio/health.py CHANGED
@@ -247,7 +247,8 @@ def _learning_status(cfg) -> dict[str, str]:
247
247
  out["Recordings"] = f"on ({n} kept to learn from)"
248
248
  else:
249
249
  out["Recordings"] = "off (nothing to learn from)"
250
- out["Nightly learning"] = "on" if service.learn_timer_enabled() else "off"
250
+ out["Nightly learning"] = ("off" if not service.learn_timer_enabled() else
251
+ "on (auto-promote)" if service.learn_timer_auto_promotes() else "on")
251
252
  return out
252
253
 
253
254
 
voiceio/learn/evaluate.py CHANGED
@@ -156,11 +156,11 @@ def save(result: EvalResult) -> Path:
156
156
  return path
157
157
 
158
158
 
159
- def latest(model: str, dataset: str, mode: str = "offline") -> dict | None:
160
- """The newest saved run of `model` (a faster-whisper name or path) on
161
- `dataset` scored by the current metrics, or None."""
159
+ def latest(model: str, dataset: str, mode: str = "offline", beam: int = 5) -> dict | None:
160
+ """The newest saved run of `model` (a faster-whisper name or path) at
161
+ beam width `beam` on `dataset` scored by the current metrics, or None."""
162
162
  runs = learn_dir() / "runs"
163
- want = f"faster-whisper:{model}"
163
+ want = f"faster-whisper:{model}" + (f"@beam{beam}" if beam != 5 else "")
164
164
  for path in sorted(runs.glob("eval-*.json"), reverse=True) if runs.exists() else []:
165
165
  try:
166
166
  data = json.loads(path.read_text())
@@ -173,6 +173,9 @@ def latest(model: str, dataset: str, mode: str = "offline") -> dict | None:
173
173
  return None
174
174
 
175
175
 
176
+ # Fewer held-out clips than this can't tell a better model from luck.
177
+ MIN_EVAL_CLIPS = 5
178
+
176
179
  # A fine-tune may trade a hair of WER for vocabulary; it may not regress either.
177
180
  WER_SLACK = 0.002
178
181
 
@@ -196,7 +199,10 @@ def paired(candidate: dict, current: dict, *, n_boot: int = 2000) -> dict | None
196
199
 
197
200
 
198
201
  def promotion_verdict(candidate: dict, current: dict) -> tuple[bool, str]:
199
- """Is `candidate` at least as good as `current` on the same clips?"""
202
+ """Is `candidate` at least as good as `current` on the same clips?
203
+
204
+ No verdict without evidence: too few clips, different clips, or a clip
205
+ the candidate failed to decode at all (a crashed decode scores 0% WER)."""
200
206
  rows = [("WER", current["wer"], candidate["wer"], "{:.1%}"),
201
207
  ("vocab recall", current["term_recall"], candidate["term_recall"], "{:.1%}"),
202
208
  ("loops", current["repetitions"], candidate["repetitions"], "{}")]
@@ -208,6 +214,10 @@ def promotion_verdict(candidate: dict, current: dict) -> tuple[bool, str]:
208
214
  f"WER change {p['mean']:+.1%} (90% interval {p['lo']:+.1%} … {p['hi']:+.1%})")
209
215
  if p["lo"] < 0 < p["hi"]:
210
216
  table += "\n (the interval spans zero: the WER difference may be luck)"
217
+ clips = candidate.get("clips", 0)
218
+ if candidate.get("failures", 0) or clips != current.get("clips", 0) or clips < MIN_EVAL_CLIPS:
219
+ return False, table + (f"\n not enough evidence: {clips} clips "
220
+ f"({candidate.get('failures', 0)} failed) vs {current.get('clips', 0)}")
211
221
  ok = (candidate["wer"] <= current["wer"] + WER_SLACK
212
222
  and candidate["term_recall"] >= current["term_recall"]
213
223
  and candidate["repetitions"] <= current["repetitions"])
voiceio/learn/review.py CHANGED
@@ -26,8 +26,10 @@ class Item:
26
26
  reason: str
27
27
 
28
28
 
29
- def _contains(seg_words: list[str], live_words: list[str]) -> bool:
30
- """Whether the segment's words occur (nearly) contiguously in the live text."""
29
+ def _contains(seg_words: list[str], live_words: list[str],
30
+ tolerance: float = _DISAGREE_WER) -> bool:
31
+ """Whether the segment's words occur (nearly, within `tolerance` of its
32
+ words) contiguously in the live text."""
31
33
  n = len(seg_words)
32
34
  if not n:
33
35
  return True
@@ -36,7 +38,7 @@ def _contains(seg_words: list[str], live_words: list[str]) -> bool:
36
38
  window = live_words[i:i + n]
37
39
  match = sum(a == b for a, b in zip(seg_words, window)) / n
38
40
  best = max(best, match)
39
- if best >= 1 - _DISAGREE_WER:
41
+ if best >= 1 - tolerance:
40
42
  return True
41
43
  return False
42
44
 
@@ -84,12 +86,31 @@ def live_span(segment_text: str, live: str) -> str | None:
84
86
 
85
87
 
86
88
  def queue_all(clips: list[Clip], labels: dict[str, Label]) -> list[Item]:
87
- """Every segment of every unreviewed clip — for building a gold test set,
88
- where a reference is only trustworthy if all of it was checked."""
89
- return [Item(clip, labels[clip.audio], i, "test set")
90
- for clip in clips
91
- if clip.audio in labels and not labels[clip.audio].reviewed
92
- for i in range(len(labels[clip.audio].segments))]
89
+ """Segments to check for a gold test set, cheapest clips first.
90
+
91
+ A reference is only trustworthy if all of it was checked — but where the
92
+ teacher and the live decode agree word for word, two independent models
93
+ already did; those segments are kept as they are, and only the rest are
94
+ asked. Clips needing the fewest answers come first, so each minute of
95
+ review completes as many gold clips as possible. A clip with no live
96
+ decode (an import) has every segment asked; one where everything agrees
97
+ asks nothing and stays a teacher label.
98
+ """
99
+ per_clip: list[list[Item]] = []
100
+ for clip in clips:
101
+ lab = labels.get(clip.audio)
102
+ if lab is None or lab.reviewed:
103
+ continue
104
+ live = metrics.words(clip.raw)
105
+ items = [Item(clip, lab, i, "test set: teacher and live disagree" if live else "test set")
106
+ for i, seg in enumerate(lab.segments)
107
+ # Word for word: a gold reference can't skip "kalchi" vs
108
+ # "Kalshi" in an otherwise matching sentence.
109
+ if not live or not _contains(metrics.words(seg.text), live, tolerance=0.0)]
110
+ if items:
111
+ per_clip.append(items)
112
+ per_clip.sort(key=len)
113
+ return [it for items in per_clip for it in items]
93
114
 
94
115
 
95
116
  def run(items: list[Item], *, ask: Callable[[Item], str | None],
voiceio/pidlock.py CHANGED
@@ -20,3 +20,21 @@ def lock_pid_file(fd) -> None:
20
20
  import fcntl
21
21
  fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
22
22
  log.debug("PID lock acquired (fcntl)")
23
+
24
+
25
+ def daemon_alive(path) -> bool:
26
+ """Whether a voiceio daemon holds the PID lock at `path` (probes without
27
+ keeping the lock, and without truncating the file)."""
28
+ if sys.platform == "win32":
29
+ return True # no cheap probe; callers then trust their other signal
30
+ import fcntl
31
+ try:
32
+ with open(path, "a") as fd:
33
+ try:
34
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
35
+ except BlockingIOError:
36
+ return True
37
+ fcntl.flock(fd, fcntl.LOCK_UN)
38
+ return False
39
+ except OSError:
40
+ return False
voiceio/service.py CHANGED
@@ -86,8 +86,9 @@ WantedBy=graphical-session.target
86
86
  """
87
87
 
88
88
 
89
- def _learn_units(bin_path: str) -> tuple[str, str]:
89
+ def _learn_units(bin_path: str, auto_promote: bool = False) -> tuple[str, str]:
90
90
  """(service, timer) for nightly learning on this machine."""
91
+ flags = " --auto-promote" if auto_promote else ""
91
92
  service = f"""\
92
93
  [Unit]
93
94
  Description=VoiceIO - learn from today's dictation (label, retrain when enough is new)
@@ -95,7 +96,7 @@ Documentation=https://github.com/Hugo0/voiceio#make-it-yours
95
96
 
96
97
  [Service]
97
98
  Type=oneshot
98
- ExecStart={bin_path} learn maintain
99
+ ExecStart={bin_path} learn maintain{flags}
99
100
  # Background work: it gets the CPU only when nothing else wants it, so
100
101
  # dictation and everything else stay fast. The unit's own cgroup already
101
102
  # does what `learn` would otherwise re-exec into a scope for.
@@ -128,11 +129,11 @@ def _systemctl(*args: str) -> bool:
128
129
  return False
129
130
 
130
131
 
131
- def install_learn_timer() -> bool:
132
+ def install_learn_timer(auto_promote: bool = False) -> bool:
132
133
  """Run `voiceio learn maintain` nightly. True when the timer is enabled."""
133
134
  if _IS_WINDOWS or not has_systemd():
134
135
  return False
135
- service, timer = _learn_units(_find_voiceio_bin())
136
+ service, timer = _learn_units(_find_voiceio_bin(), auto_promote)
136
137
  SERVICE_DIR.mkdir(parents=True, exist_ok=True)
137
138
  LEARN_SERVICE_PATH.write_text(service)
138
139
  LEARN_TIMER_PATH.write_text(timer)
@@ -151,6 +152,20 @@ def learn_timer_enabled() -> bool:
151
152
  return LEARN_TIMER_PATH.exists() and _systemctl("is-enabled", "--quiet", LEARN_TIMER_NAME)
152
153
 
153
154
 
155
+ def learn_timer_auto_promotes() -> bool:
156
+ try:
157
+ return "--auto-promote" in LEARN_SERVICE_PATH.read_text()
158
+ except OSError:
159
+ return False
160
+
161
+
162
+ def restart_when_idle() -> bool:
163
+ """Restart the daemon once no dictation is in progress. False when it
164
+ stayed busy (never cut a dictation off) or the restart failed."""
165
+ from voiceio.cli.servicecmd import wait_until_idle
166
+ return wait_until_idle() and _systemctl("restart", SERVICE_NAME)
167
+
168
+
154
169
  def uninstall_correct_timer() -> None:
155
170
  """Remove the pre-1.0 weekly cloud-mining timer (`correct --auto --batch`).
156
171
  It is gone in 1.0: mining moved to the local, opt-in `voiceio learn`."""