-
Notifications
You must be signed in to change notification settings - Fork 588
Expand file tree
/
Copy pathagent_flow.py
More file actions
2552 lines (2216 loc) · 96.7 KB
/
Copy pathagent_flow.py
File metadata and controls
2552 lines (2216 loc) · 96.7 KB
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Generator-based agent flow runner for Moonshine Voice.
A *flow* is an ordinary Python generator function that yields prompts to the
runner and resumes with the user's answer:
from moonshine_voice import agent_flow as df
def setup_wifi(d):
ssid = yield d.ask("What's the name of your wifi network?")
if not (yield d.confirm(f"I heard, {ssid}. Is that right?")):
yield d.say("No problem, let's start over.")
return
password = yield d.ask(
"Please spell the wifi password.",
mode=df.SPELLED,
)
if (yield d.confirm("Would you like to hear it read back?")):
yield d.say(f"I heard: {df.spell_out(password)}")
if (yield d.confirm("Apply these changes?")):
apply_wifi_config(ssid, password)
yield d.say("Done. Your wifi is set up.")
else:
yield d.say("Okay, nothing changed.")
Register the flow against a trigger phrase and let the runner do the rest:
agent = (
AgentFlow()
.language("en")
.listen_for("set up wifi", setup_wifi)
)
agent.load()
agent.start_listening()
"cancel" and "start over" need no registration: they work at any point
inside a flow, and outside one they are treated as ordinary speech so a
dictation interface doesn't lose them. :meth:`AgentFlow.always` adds a
phrase of your own that stays live at every moment.
:meth:`AgentFlow.load` downloads and opens the speech recognition,
speech synthesis and phrase-matching models, and
:meth:`AgentFlow.start_listening` opens the microphone, so a voice
interface needs no other objects. Supply your own with
:meth:`AgentFlow.use_mic_transcriber` / :meth:`AgentFlow.use_text_to_speech`
when you already have them, or drive the runner from text with
:meth:`AgentFlow.handle_utterance`.
There is no asyncio dependency – flows are driven synchronously from
whatever thread delivers transcript events, so flows can be unit-tested
without any audio, TTS, or event loop.
"""
from __future__ import annotations
import argparse
import sys
import threading
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
Iterator,
List,
Mapping,
NoReturn,
Optional,
Protocol,
Sequence,
Set,
Tuple,
Union,
)
from moonshine_voice.alphanumeric_listener import (
AlphanumericEventType,
AlphanumericMatcher,
digits_only_matcher,
spoken_form,
)
from moonshine_voice.cached_embeddings import CachedEmbeddings
from moonshine_voice.download import (
get_embedding_model,
get_model_for_language,
get_spelling_model_path,
)
from moonshine_voice.errors import MoonshineError
from moonshine_voice.mic_transcriber import MicTranscriber
from moonshine_voice.transcriber import (
MOONSHINE_FLAG_SPELLING_MODE,
Error,
LineCompleted,
LineStarted,
ModelArch,
TranscriptEventListener,
)
from moonshine_voice.tts import TextToSpeech, _parse_options_cli
# ---------------------------------------------------------------------------
# Input modes
# ---------------------------------------------------------------------------
FREE = "free"
SPELLED = "spelled"
DIGITS = "digits"
PHRASE = "phrase"
# ---------------------------------------------------------------------------
# Prompt objects – what a flow yields to the runner
# ---------------------------------------------------------------------------
@dataclass
class Prompt:
"""Base class for values a flow function may yield to the runner."""
@dataclass
class Say(Prompt):
"""Speak ``text`` and resume the generator once playback has finished."""
text: str
barge_in: bool = False
@dataclass
class Ask(Prompt):
"""Speak ``prompt`` and resume with the user's next utterance as a string."""
prompt: str
mode: str = FREE
bias_terms: Optional[List[str]] = None
timeout: Optional[float] = 8.0
no_input_reprompt: Optional[str] = "Sorry, I didn't catch that. {prompt}"
max_retries: int = 2
_DEFAULT_YES_PHRASES: Tuple[str, ...] = (
"yes",
"yeah",
"yep",
"correct",
"that's right",
"sure",
"affirmative",
"okay",
"please do",
"do it",
)
_DEFAULT_NO_PHRASES: Tuple[str, ...] = (
"no",
"nope",
"incorrect",
"that's wrong",
"negative",
"cancel",
"don't do it",
"stop",
)
@dataclass
class Confirm(Prompt):
"""Speak ``prompt`` and resume with a bool (yes / no)."""
prompt: str
timeout: Optional[float] = 6.0
max_retries: int = 1
threshold: float = 0.55
no_input_reprompt: Optional[str] = (
"Sorry, I didn't catch that. Was that a yes or a no? {prompt}"
)
yes_phrases: Sequence[str] = field(
default_factory=lambda: _DEFAULT_YES_PHRASES
)
no_phrases: Sequence[str] = field(
default_factory=lambda: _DEFAULT_NO_PHRASES
)
@dataclass
class Choose(Prompt):
"""Speak ``prompt`` and resume with the key of the matched option.
``options`` maps option keys to canonical phrases. Matching is done
against the union of the key and its phrases, using the embedding
model when available and falling back to substring matching.
"""
prompt: str
options: Mapping[str, Sequence[str]] = field(default_factory=dict)
timeout: Optional[float] = 8.0
max_retries: int = 2
threshold: float = 0.55
no_input_reprompt: Optional[str] = "Sorry, I didn't catch that. {prompt}"
# ---------------------------------------------------------------------------
# Exceptions thrown into the generator
# ---------------------------------------------------------------------------
class DialogError(Exception):
"""Base class for agent-flow exceptions."""
class DialogCancelled(DialogError):
"""Raised into / from a flow to abandon it entirely."""
class DialogRestart(DialogError):
"""Raised into / from a flow to restart it from the beginning."""
class NoInputError(DialogError):
"""No utterance was received within the prompt's retry budget."""
class NoMatchError(DialogError):
"""Received an utterance but could not interpret it for this prompt."""
# ---------------------------------------------------------------------------
# Phrase matching via embeddings
# ---------------------------------------------------------------------------
class EmbeddingBackend(Protocol):
"""Minimal interface the phrase matcher needs from an embedding source.
The internal embedding model satisfies this protocol via its
:meth:`calculate_embedding` and :meth:`distance` methods – the
latter is a thin wrapper around the native
``moonshine_calculate_embedding_distance`` C API so scoring happens
in C rather than Python.
"""
def calculate_embedding(self, sentence: str) -> Sequence[float]: ...
def distance(
self, embedding_a: Sequence[float], embedding_b: Sequence[float]
) -> float: ...
class PhraseMatcher:
"""Match an utterance to one of several key→phrases groups via embeddings.
This is a tiny wrapper around an :class:`EmbeddingBackend`. At
construction time, the backend is
used to compute an embedding for every phrase in every group; at
match time, the utterance is embedded once and compared against
every phrase using cosine similarity. The key of the best-scoring
phrase (above ``threshold``) is returned, or *None* if nothing
clears the threshold.
Use this to replace string / substring matching on user utterances
with fuzzy, semantics-aware matching.
Example::
yes_no = PhraseMatcher(
embedding_backend,
{"yes": ["yes", "sure", "please"],
"no": ["no", "nope", "cancel"]},
threshold=0.6,
)
assert yes_no.match("please go ahead") == "yes"
assert yes_no.match("don't do that") == "no"
"""
def __init__(
self,
backend: EmbeddingBackend,
phrases_by_key: Mapping[str, Sequence[str]],
*,
threshold: float = 0.55,
):
if backend is None:
raise ValueError("PhraseMatcher requires an embedding backend")
self._backend = backend
self._threshold = float(threshold)
self._phrase_embeddings: Dict[str, List[Sequence[float]]] = {}
for key, phrases in phrases_by_key.items():
embeddings: List[Sequence[float]] = []
for phrase in phrases:
if not phrase:
continue
try:
embeddings.append(backend.calculate_embedding(phrase))
except Exception as e:
print(
f"PhraseMatcher: failed to embed {phrase!r}: {e}",
file=sys.stderr,
)
self._phrase_embeddings[key] = embeddings
@property
def threshold(self) -> float:
return self._threshold
def match(self, utterance: str) -> Optional[str]:
"""Return the best-matching key, or *None* if below threshold."""
key, _score = self.match_with_score(utterance)
return key
def match_with_score(
self, utterance: str
) -> Tuple[Optional[str], float]:
"""Return ``(key, similarity)`` of the best match above threshold.
When nothing clears ``threshold`` returns ``(None, best_sim)`` –
callers can inspect the score for diagnostics / reprompts.
"""
if not utterance:
return None, 0.0
try:
u_emb = self._backend.calculate_embedding(utterance)
except Exception as e:
print(f"PhraseMatcher: failed to embed utterance: {e}", file=sys.stderr)
return None, 0.0
best_key: Optional[str] = None
best_sim: float = -1.0
for key, embeddings in self._phrase_embeddings.items():
for e in embeddings:
try:
sim = self._backend.distance(u_emb, e)
except Exception as exc:
print(
f"PhraseMatcher: distance() failed: {exc}",
file=sys.stderr,
)
return None, 0.0
if sim > best_sim:
best_sim = sim
best_key = key
if best_key is not None and best_sim >= self._threshold:
return best_key, best_sim
return None, max(best_sim, 0.0)
class SubstringMatcher:
"""Match an utterance by case-insensitive substring, with no model.
Interchangeable with :class:`PhraseMatcher`, and used in its place
when :meth:`AgentFlow.use_embeddings` is off. It only recognises
what the user literally said, so it's meant for tests and offline
smoke checks rather than for real speech, where the wording never
matches the trigger phrase exactly.
A phrase matches when it appears in the utterance or the utterance
appears in it; the longest matching phrase wins, so "turn off the
lights" beats "lights". The score is the matched phrase's share of
the utterance, which lets ``threshold`` behave roughly as it does
for embeddings.
"""
def __init__(
self,
phrases_by_key: Mapping[str, Sequence[str]],
*,
threshold: float = 0.55,
):
self._threshold = float(threshold)
self._phrases_by_key: Dict[str, List[str]] = {
key: [p.strip().lower() for p in phrases if p and p.strip()]
for key, phrases in phrases_by_key.items()
}
@property
def threshold(self) -> float:
return self._threshold
def match(self, utterance: str) -> Optional[str]:
key, _score = self.match_with_score(utterance)
return key
def match_with_score(self, utterance: str) -> Tuple[Optional[str], float]:
text = (utterance or "").strip().lower()
if not text:
return None, 0.0
best_key: Optional[str] = None
best_len = 0
for key, phrases in self._phrases_by_key.items():
for phrase in phrases:
if phrase in text or text in phrase:
if len(phrase) > best_len:
best_len = len(phrase)
best_key = key
if best_key is None:
return None, 0.0
score = min(1.0, best_len / max(len(text), 1))
return best_key, score
PhraseMatcherFactory = Callable[
[Mapping[str, Sequence[str]], float], Optional[PhraseMatcher]
]
# ---------------------------------------------------------------------------
# Dialog – the context object passed to every flow function
# ---------------------------------------------------------------------------
class Dialog:
"""Context object handed to a flow as its first argument.
Each method returns a :class:`Prompt` that the flow yields; the runner
carries out the prompt and sends the result (if any) back into the
generator. ``Dialog`` itself performs no I/O, which keeps flows easy
to unit-test: pass a ``Dialog`` to the flow, iterate the generator, and
drive it with ``.send()``.
"""
def __init__(self, trigger_phrase: str = "", *, state: Optional[Dict[str, Any]] = None):
self.trigger_phrase = trigger_phrase
self.state: Dict[str, Any] = dict(state) if state else {}
self._last_spoken_prompt: Optional[str] = None
def say(self, text: str, *, barge_in: bool = False) -> Say:
self._last_spoken_prompt = text
return Say(text=text, barge_in=barge_in)
def ask(
self,
prompt: str,
*,
mode: str = FREE,
bias_terms: Optional[Sequence[str]] = None,
timeout: Optional[float] = 8.0,
no_input_reprompt: Optional[str] = "Sorry, I didn't catch that. {prompt}",
max_retries: int = 2,
) -> Ask:
self._last_spoken_prompt = prompt
return Ask(
prompt=prompt,
mode=mode,
bias_terms=list(bias_terms) if bias_terms is not None else None,
timeout=timeout,
no_input_reprompt=no_input_reprompt,
max_retries=max_retries,
)
def confirm(
self,
prompt: str,
*,
timeout: Optional[float] = 6.0,
max_retries: int = 1,
) -> Confirm:
self._last_spoken_prompt = prompt
return Confirm(prompt=prompt, timeout=timeout, max_retries=max_retries)
def choose(
self,
prompt: str,
options: Mapping[str, Sequence[str]],
*,
timeout: Optional[float] = 8.0,
max_retries: int = 2,
) -> Choose:
self._last_spoken_prompt = prompt
return Choose(
prompt=prompt,
options={k: list(v) for k, v in options.items()},
timeout=timeout,
max_retries=max_retries,
)
# -- flow control – these raise into the generator ---------------------
def cancel(self) -> NoReturn:
raise DialogCancelled()
def restart(self) -> NoReturn:
raise DialogRestart()
def replay_last_prompt(self) -> Optional[Say]:
"""Return a :class:`Say` that re-speaks the most recent prompt.
Intended for global "repeat" handlers; returns *None* if nothing has
been spoken yet.
"""
if self._last_spoken_prompt is None:
return None
return Say(text=self._last_spoken_prompt)
# ---------------------------------------------------------------------------
# Type aliases
# ---------------------------------------------------------------------------
FlowFn = Callable[[Dialog], Iterator[Prompt]]
GlobalHandler = Callable[[Dialog], Optional[Prompt]]
# ---------------------------------------------------------------------------
# AgentFlow – the runner / listener
# ---------------------------------------------------------------------------
class _AlphaSession:
"""In-progress spelled / digit input buffered across utterances."""
def __init__(self, matcher: AlphanumericMatcher):
self.matcher = matcher
self.buffer: List[str] = []
class _TranscriptBridge(TranscriptEventListener):
"""Feeds a transcriber's events into a :class:`AgentFlow`.
Kept separate from the runner so that ``AgentFlow.on_error`` can be
the public "tell me when something went wrong" setter rather than the
transcript-event callback of the same name.
"""
def __init__(self, runner: AgentFlow):
self._runner = runner
def on_line_started(self, event: LineStarted) -> None:
self._runner._on_line_started(event)
def on_line_completed(self, event: LineCompleted) -> None:
self._runner._on_line_completed(event)
def on_error(self, event: Error) -> None:
self._runner._on_transcriber_error(event)
class _ActiveFlow:
"""Per-session state for a running flow."""
def __init__(self, flow_fn: FlowFn, trigger_phrase: str):
self.flow_fn = flow_fn
self.trigger_phrase = trigger_phrase
self.dialog = Dialog(trigger_phrase)
self.generator: Iterator[Prompt] = flow_fn(self.dialog)
self.current_prompt: Optional[Prompt] = None
self.retry_count: int = 0
self.alpha_session: Optional[_AlphaSession] = None
class AgentFlow:
"""Runner that drives generator-based conversational flows.
Configure with the chainable setters, register flows with
:meth:`listen_for` and :meth:`always`, then call :meth:`load` to open
the models and :meth:`start_listening` to go live::
agent = (
AgentFlow()
.language("en")
.listen_for("set up wifi", setup_wifi)
.always("cancel", lambda d: d.cancel())
)
agent.load()
agent.start_listening()
Completed transcript lines are routed either to a matching trigger
phrase (when no flow is active) or to the currently suspended
generator (when one is).
The runner is synchronous: when a flow yields a :class:`Say`, the
runner speaks and blocks until the utterance has been played, then
resumes the generator. When a flow yields an input-expecting prompt
(:class:`Ask` / :class:`Confirm` / :class:`Choose`), the runner speaks
the prompt and returns control to the caller; the next completed
transcript line resumes the generator.
The runner mutes its microphone while the assistant is talking and
flips the C++ spelling-CNN fusion path on for the duration of a
``SPELLED`` / ``DIGITS`` prompt, so neither needs wiring up by hand.
"""
def __init__(self) -> None:
# -- model configuration, applied by :meth:`load` -------------------
self._language = "en"
self._model_arch: Optional[ModelArch] = None
self._voice: Optional[str] = None
self._model_root: Optional[Path] = None
self._wants_microphone = True
self._wants_speech = True
self._output_device: Optional[Any] = None
self._tts_options: Optional[Dict[str, Any]] = None
# -- engines --------------------------------------------------------
self._tts: Optional[Any] = None
self._mic: Optional[Any] = None
self._owns_tts = False
self._owns_mic = False
self._listening = False
self._bridge = _TranscriptBridge(self)
self._bridged: List[Any] = []
# -- observer callbacks ---------------------------------------------
self._progress_fn: Optional[Callable[[float, str], None]] = None
self._heard_fn: Optional[Callable[[str], None]] = None
self._said_fn: Optional[Callable[[str], None]] = None
self._error_fn: Optional[Callable[[BaseException], None]] = None
self._otherwise_fn: Optional[Callable[[str], None]] = None
self._speak_fn: Optional[Callable[[str], None]] = None
self._mute_fn: Optional[Callable[[bool], None]] = None
self._spelling_mode_fn: Optional[Callable[[bool], None]] = None
self._success_beep_fn: Optional[Callable[[], None]] = None
self._error_beep_fn: Optional[Callable[[], None]] = None
self._beeps_enabled = True
self._use_embeddings = True
self._spelling_mode_active = False
self._trigger_threshold = 0.7
self._spell_feedback = True
self._log_io = False
self._ignore_stt_during_tts = True
self._speaking = False
# Transcript line IDs whose ``LineStarted`` event fired while
# the assistant was talking; populated in :meth:`on_line_started`
# and consumed in :meth:`on_line_completed` to drop self-capture
# without making the user wait for an arbitrary post-TTS grace
# window. Protected by ``_lock`` since the listener thread that
# delivers transcript events is independent of the thread driving
# the flow.
self._suspect_line_ids: set = set()
self._debug = False
self._log_start: Optional[float] = None
self._log_last: Optional[float] = None
# The default :class:`PhraseMatcher` factory runs on an
# :class:`EmbeddingBackend`. Library-level constants (e.g. the
# default yes/no phrases) have their embeddings shipped via
# ``assets/cached_embeddings.tsv`` and loaded by
# :class:`CachedEmbeddings`; cache misses (typically user
# utterances) fall through to the embedding model, which
# :meth:`_embedding_backend` loads on first use so that merely
# constructing a runner never downloads anything.
self._cached_embeddings: Optional[CachedEmbeddings] = None
self._owned_model: Optional[Any] = None
self._backend: Optional[Any] = None
self._phrase_matcher_factory: Optional[PhraseMatcherFactory] = (
self._default_phrase_matcher
)
self._flows: Dict[str, FlowFn] = {}
self._globals: Dict[str, GlobalHandler] = {}
# Globals that only mean anything while a flow is running. The
# built-in "cancel" and "start over" are in here: matching them
# when nothing is active would consume the line, do nothing with
# it, and leave a dictation interface silently missing a
# sentence.
self._flow_scoped_globals: Set[str] = set()
self._active: Optional[_ActiveFlow] = None
self._lock = threading.RLock()
self._matcher_cache: Dict[Any, Optional[PhraseMatcher]] = {}
# Keyed by the phrases it covers, because that set changes with
# the flow-scoped globals coming and going.
self._trigger_matchers: Dict[Tuple[str, ...], Optional[PhraseMatcher]] = {}
# Cached alphanumeric matchers. These are stateless (only the
# per-prompt ``_AlphaSession`` holds buffer state), so one
# instance per mode is enough. Created on demand the first
# time a ``SPELLED`` / ``DIGITS`` prompt is entered.
self._spelled_matcher: Optional[AlphanumericMatcher] = None
self._digits_matcher: Optional[AlphanumericMatcher] = None
# "cancel" and "start over" are what people actually say to a
# voice interface, so they work without every application
# registering them. Both only apply to a flow in progress, so
# they stay out of the way of whatever else the microphone is
# being used for. Registering either with :meth:`always` makes
# it live all the time, as any other global is.
self._add_flow_scoped_global("cancel", lambda d: d.cancel())
self._add_flow_scoped_global("start over", lambda d: d.restart())
def _default_phrase_matcher(
self,
phrases_by_key: Mapping[str, Sequence[str]],
threshold: float,
) -> Optional[PhraseMatcher]:
backend = self._embedding_backend()
if backend is None:
return SubstringMatcher(phrases_by_key, threshold=threshold)
return PhraseMatcher(backend, phrases_by_key, threshold=threshold)
# -- configuration -------------------------------------------------------
#
# Every setter returns ``self`` so a runner can be built in one
# expression, and all of them must be called before :meth:`load`.
def language(self, code: str) -> AgentFlow:
"""Set the language for both recognition and speech (default ``"en"``)."""
self._language = code
return self
def model_arch(self, arch: ModelArch) -> AgentFlow:
"""Pick a specific speech recognition model size."""
self._model_arch = arch
return self
def voice(self, voice_id: str) -> AgentFlow:
"""Choose the synthesis voice used to speak prompts."""
self._voice = voice_id
return self
def speech_options(self, options: Mapping[str, Any]) -> AgentFlow:
"""Pass advanced options straight through to the speech synthesizer."""
self._tts_options = dict(options)
return self
def models_from(self, directory: Union[str, Path]) -> AgentFlow:
"""Read and cache model files under ``directory`` instead of the default cache."""
self._model_root = Path(directory)
return self
def microphone(self, enabled: bool = True) -> AgentFlow:
"""Whether :meth:`load` should open a microphone (default ``True``).
Turn this off to drive the runner from text with
:meth:`handle_utterance`, or when you supply your own transcriber
via :meth:`use_mic_transcriber`.
"""
self._wants_microphone = bool(enabled)
return self
def speech(self, enabled: bool = True) -> AgentFlow:
"""Whether :meth:`load` should open a synthesizer (default ``True``).
Turn this off for a silent runner: prompts are still logged and
flows still advance, they just aren't spoken aloud.
"""
self._wants_speech = bool(enabled)
return self
def output_device(self, device: Union[int, str]) -> AgentFlow:
"""Pin speech playback to a specific audio output device.
Needed on machines where the host default isn't the speaker you
want — a Raspberry Pi that defaults to HDMI while the speakers
are on the 3.5 mm jack, for example.
"""
self._output_device = device
return self
def trigger_threshold(self, threshold: float) -> AgentFlow:
"""Set the similarity a phrase must reach to fire (default ``0.7``).
Raise it towards ``1.0`` to demand a closer match when triggers
are firing on unrelated speech; lower it when they aren't firing
on genuine attempts.
"""
self._trigger_threshold = float(threshold)
self._invalidate_trigger_matcher()
return self
def on_progress(self, callback: Callable[[float, str], None]) -> AgentFlow:
"""Report model download and load progress as ``(fraction, filename)``."""
self._progress_fn = callback
return self
def on_heard(self, callback: Callable[[str], None]) -> AgentFlow:
"""Report every utterance the runner receives from the microphone."""
self._heard_fn = callback
return self
def on_said(self, callback: Callable[[str], None]) -> AgentFlow:
"""Report every prompt the runner speaks."""
self._said_fn = callback
return self
def on_error(
self, callback: Callable[[BaseException], None]
) -> AgentFlow:
"""Report errors raised by a flow or by the audio pipeline.
Without a handler the runner prints the error to stderr and
carries on; a flow that raises is always torn down either way, so
one bad turn can't wedge the runner.
"""
self._error_fn = callback
return self
def speak_with(self, speak: Callable[[str], None]) -> AgentFlow:
"""Speak prompts with your own callable instead of the built-in synthesizer.
``speak(text)`` must block until playback has finished, since the
runner resumes the flow as soon as it returns. Setting this stops
:meth:`load` from creating a synthesizer of its own.
"""
self._speak_fn = speak
return self
def beeps(self, enabled: bool = True) -> AgentFlow:
"""Whether to play the recognition cue tones (default ``True``).
The runner plays a short "got it" tone the moment an utterance
matches a trigger or answers a prompt, and a distinct "didn't get
that" tone when nothing matched, so a misrecognition never ends in
silence.
"""
self._beeps_enabled = bool(enabled)
return self
def spell_feedback(self, enabled: bool = True) -> AgentFlow:
"""Whether to echo each character during spelled input (default ``True``).
Every character recognised during a ``SPELLED`` / ``DIGITS``
prompt is spoken back using :func:`spoken_form` (``"haitch"`` for
``"h"``, ``"capital ay"`` for ``"A"``, ``"hash"`` for ``"#"``),
and a "delete" / "scratch that" is echoed as ``"deleting
<character>"`` so the user hears that the right letter came off
the end. Turn it off when there's no audio output and the echo
would just be log spam.
"""
self._spell_feedback = bool(enabled)
return self
def log_io(self, enabled: bool = True) -> AgentFlow:
"""Log the dialogue to stderr as ``user: …`` / ``assistant: …`` lines.
This is the user-facing transcript of inputs and outputs; use
:meth:`debug` for the verbose internal trace. Off by default so
callers that already format their own transcript don't end up
with duplicate lines.
"""
self._log_io = bool(enabled)
return self
def barge_in(self, enabled: bool = True) -> AgentFlow:
"""Allow the user to interrupt the assistant mid-prompt (default off).
By default every utterance that arrives while the assistant is
talking is dropped, because it's usually the microphone hearing
the speakers. That's a software guard on top of muting the mic:
muting minimises self-capture, but on devices with weak echo
cancellation the recognizer can still latch onto audio captured
just before the mute, or onto speaker bleed the cancellation
didn't suppress. Enable barge-in only when you have reliable
echo cancellation.
"""
self._ignore_stt_during_tts = not bool(enabled)
return self
def debug(self, enabled: bool = True) -> AgentFlow:
"""Trace every internal stage transition, with timings, to stderr."""
self._debug = bool(enabled)
return self
def use_embeddings(self, enabled: bool = True) -> AgentFlow:
"""Whether to match phrases semantically (default ``True``).
With embeddings on, the runner downloads a small language model
on :meth:`load` and matches what the user said against trigger
phrases by meaning, so "set up wifi" also fires on "I need to get
online". Turn it off to fall back to case-insensitive substring
matching and load no model, which is what offline tests usually
want.
"""
self._use_embeddings = bool(enabled)
return self
def use_cached_embeddings(
self, cache: CachedEmbeddings
) -> AgentFlow:
"""Supply pre-computed phrase embeddings, bypassing the model for hits."""
self._cached_embeddings = cache
self._backend = cache
return self
def use_phrase_matcher(
self, factory: PhraseMatcherFactory
) -> AgentFlow:
"""Replace the built-in phrase matching with your own implementation."""
self._phrase_matcher_factory = factory
return self
def use_text_to_speech(self, tts: Any) -> AgentFlow:
"""Speak with an existing :class:`TextToSpeech` instead of creating one.
The runner won't close a synthesizer it didn't create.
"""
self._tts = tts
self._owns_tts = False
return self
def use_mic_transcriber(self, transcriber: Any) -> AgentFlow:
"""Listen to an existing transcriber instead of opening a microphone.
Accepts a :class:`MicTranscriber` or any object with the same
``add_listener`` / ``start`` / ``stop`` shape — a plain
:class:`Transcriber` fed from a file works, which is handy for
testing a flow against recorded audio. The runner won't close a
transcriber it didn't create.
"""
self._mic = transcriber
self._owns_mic = False
self._attach_bridge(transcriber)
return self
# -- embedding backend ---------------------------------------------------
def _embedding_backend(self) -> Optional[Any]:
"""The embedding backend, loading the phrase model on first use.
:meth:`load` normally warms this up front, but it stays lazy so a
runner driven purely by :meth:`handle_utterance` still works
without an explicit load. Returns *None* when embeddings are
turned off, which leaves matching to the substring fallback.
"""
with self._lock:
if self._backend is not None:
return self._backend
if not self._use_embeddings:
return None
from moonshine_voice.embedding_model import EmbeddingModel
self._report_progress(0.0, "embedding model")
model_path, model_arch = get_embedding_model(
cache_root=self._model_root
)
self._owned_model = EmbeddingModel(
model_path=model_path, model_arch=model_arch
)
self._backend = CachedEmbeddings(fallback=self._owned_model)
self._report_progress(1.0, "embedding model")
return self._backend
def _report_progress(self, fraction: float, name: str) -> None:
if self._progress_fn is None:
return
try:
self._progress_fn(fraction, name)
except Exception as e:
self._log(f"progress callback failed: {e!r}")
# -- lifecycle ------------------------------------------------------------
def load(self) -> AgentFlow:
"""Download and open everything the runner needs, and return self.
Opens the phrase-matching model, a speech synthesizer, and a
microphone transcriber, skipping any of them you've already
supplied or turned off. Blocking, since the first call may have
to download models; report progress with :meth:`on_progress`.
Call :meth:`start_listening` afterwards to begin listening.
"""
if self._wants_speech and self._tts is None and self._speak_fn is None:
self._report_progress(0.0, "speech synthesis")
self._tts = (
TextToSpeech()
.language(self._language)
.debug(self._debug)
.output_device(self._output_device)
)
if self._voice is not None:
self._tts.voice(self._voice)
if self._tts_options:
self._tts.options(self._tts_options)
if self._progress_fn is not None:
self._tts.on_progress(
lambda fraction, name: self._report_progress(fraction, name)
)
self._tts.load()
self._owns_tts = True
self._report_progress(1.0, "speech synthesis")
if self._wants_microphone and self._mic is None:
self._report_progress(0.0, "speech recognition")
# Resolved here rather than left to MicTranscriber.load() so the
# download lands under this runner's cache root.
model_path, model_arch = get_model_for_language(
self._language,
self._model_arch,
cache_root=self._model_root,
on_progress=(
None
if self._progress_fn is None
else lambda fraction, name: self._report_progress(fraction, name)
),
)
# The spelling CNN is what makes dictated passwords and codes
# accurate, but it isn't published for every language, and its
# absence only costs accuracy inside SPELLED / DIGITS prompts.
spelling_model_path: Optional[str] = None
try:
spelling_model_path = get_spelling_model_path(
self._language, cache_root=self._model_root
)
except Exception as e: