-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprint_transcript.py
More file actions
1777 lines (1501 loc) · 61.1 KB
/
Copy pathprint_transcript.py
File metadata and controls
1777 lines (1501 loc) · 61.1 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
from typing import Optional, TypedDict, TypeVar
import json
import datetime
from dataclasses import dataclass
import click
from colorama import Style
from pydantic import BaseModel
T = TypeVar("T")
# ============================================================================
# Configuration Models
# ============================================================================
class DisplayConfig(BaseModel):
"""Configuration for display options"""
print_channels: bool = False
print_speakers: bool = False
print_interim: bool = False
print_received: bool = False
print_entities: bool = False
print_latency: bool = False
colorize: bool = False
only_transcript: bool = False
class WordData(BaseModel):
"""Model for word data in transcripts"""
word: str
start: float
end: float
confidence: float = 1.0
channel: int = 0
speaker: Optional[int] = None
punctuated_word: Optional[str] = None
entity: Optional[dict] = None
class Config:
extra = "allow" # Allow extra fields from the API
# ============================================================================
# Color Formatting Functions
# ============================================================================
def confidence_color(confidence):
"""
Convert a number between 0 and 1 to an RGB color where:
0 maps to red (255, 0, 0) and
1 maps to white (255, 255, 255)
"""
confidence = confidence**2
red = 255
green = int(255 * confidence)
blue = int(255 * confidence)
return red, green, blue
def colorize_latency(
latency: float,
min_latency: float,
max_latency: float,
use_rich_markup: bool = False,
) -> str:
"""
Colorize a latency value string based on min/max range.
Args:
latency: The latency value in seconds
min_latency: Minimum latency (maps to white/good)
max_latency: Maximum latency (maps to red/bad)
use_rich_markup: If True, use Rich markup format. If False, use ANSI codes.
"""
text = f"{latency:.3f}s"
# Convert a latency value to an RGB color where:
# min_latency maps to white (255, 255, 255) - good
# max_latency maps to red (255, 0, 0) - bad
if max_latency <= min_latency:
# Avoid division by zero; treat as best case
normalized = 1.0
else:
# Normalize: 0 = max (bad), 1 = min (good)
normalized = 1.0 - (latency - min_latency) / (max_latency - min_latency)
normalized = max(0.0, min(1.0, normalized)) # Clamp to [0, 1]
# Use same color mapping as confidence
normalized = normalized**2
red = 255
green = int(255 * normalized)
blue = int(255 * normalized)
if use_rich_markup:
return f"[rgb({red},{green},{blue})]{text}[/]"
else:
ansi_color = rgb_to_ansi(red, green, blue)
return f"{ansi_color}{text}{Style.RESET_ALL}"
def rgb_to_ansi(r, g, b):
return f"\033[38;2;{r};{g};{b}m"
def colorize_word(text, confidence, use_rich_markup=False):
"""
Colorize a word based on confidence.
Args:
text: The word to colorize
confidence: Confidence score (0-1)
use_rich_markup: If True, use Rich markup format. If False, use ANSI codes.
"""
r, g, b = confidence_color(confidence)
if use_rich_markup:
# Rich markup format for Textual
return f"[rgb({r},{g},{b})]{text}[/]"
else:
# ANSI escape codes for terminal
ansi_color = rgb_to_ansi(r, g, b)
return f"{ansi_color}{text}{Style.RESET_ALL}"
# ============================================================================
# Time Formatting
# ============================================================================
def format_time(seconds: float) -> str:
if seconds < 0:
return f"-{format_time(-seconds)}"
hours = seconds // 3600
seconds = seconds - (hours * 3600)
minutes = seconds // 60
seconds = seconds - (minutes * 60)
milliseconds = (seconds - int(seconds)) * 1000
# Make sure the milliseconds string is 2 digits
milliseconds_str = f"{int(milliseconds / 10)}"
if len(milliseconds_str) == 1:
milliseconds_str += "0"
return f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}.{milliseconds_str}"
# ============================================================================
# Word Processing Functions
# ============================================================================
class WordType(TypedDict):
word: str
start: float
end: float
confidence: float
channel: int
speaker: Optional[int]
punctuated_word: Optional[str]
entity: Optional[dict]
def add_channel_to_word_objects(dg_response: dict):
if dg_response.get("type") == "TurnInfo": # Flux
# For Flux, we don't have explicit channels, so assume channel 0
for word in dg_response.get("words", []):
word["channel"] = 0
elif "results" in dg_response: # batch
# Augment the word objects with a "channel" field
for channel_index, channel in enumerate(dg_response["results"]["channels"]):
# Always use the first alternative and ignore any others.
for word in channel["alternatives"][0]["words"]:
word["channel"] = channel_index
elif "channel" in dg_response: # streaming
channel = dg_response["channel_index"][0]
for word in dg_response["channel"]["alternatives"][0]["words"]:
word["channel"] = channel
else:
raise ValueError("impossible")
return dg_response
def remove_empty_sublists(list_of_lists: list[list[T]]) -> list[list[T]]:
return [sublist for sublist in list_of_lists if len(sublist) > 0]
def split_words_by_speaker(words: list[WordType]) -> list[list[WordType]]:
"""
Looks at both the speaker and the channel to determine when a speaker change occurs.
The list of words is split into sublists whenever the speaker or channel changes.
"""
# Split the word array into subarrays by speaker
split_by_speaker: list[list[WordType]] = []
speaker = None
channel = None
for word in words:
word_speaker = word.get("speaker", None)
word_channel = word["channel"]
if word_speaker != speaker or word_channel != channel:
split_by_speaker.append([])
split_by_speaker[-1].append(word)
speaker = word_speaker
channel = word_channel
# Remove empty word arrays from speaker array
split_by_speaker = remove_empty_sublists(split_by_speaker)
return split_by_speaker
def split_words_into_sentences(words: list[WordType]) -> list[list[WordType]]:
split: list[list[WordType]] = [[]]
# Split at a period, question mark, or exclamation point.
for word in words:
split[-1].append(word)
_word = word.get("punctuated_word") or word["word"]
if any(p in _word for p in [".", "?", "!"]):
split.append([])
del words
split = remove_empty_sublists(split)
return split
def add_entities_to_word_objects(
words: list[WordType], entities: list[dict]
) -> list[WordType]:
"""
Add the entity information to the words.
"""
for entity in entities:
for i in range(entity["start_word"], entity["end_word"]):
words[i]["entity"] = entity
return words
def apply_entity_brackets(word_array: list[WordType]) -> None:
"""
Modifies word_array in place to add [ENTITY: text] formatting.
Handles nested entities and fixes punctuation placement.
"""
# Track active entities to handle nesting
active_entities = {}
for i, word in enumerate(word_array):
if word is None:
continue
# Get current word text
word_text: str = word.get("punctuated_word") or word["word"]
# Check if this word has an entity
current_entity = word.get("entity", None)
current_entity_key = current_entity["label"] if current_entity else None
# Check next word to see if entity continues
next_entity = None
if i + 1 < len(word_array) and word_array[i + 1] is not None:
next_entity = word_array[i + 1].get("entity", None)
# Check if this is the start of a new entity
if current_entity and current_entity_key not in active_entities:
# Add opening bracket
word_text = f"[{current_entity_key}: {word_text}"
active_entities[current_entity_key] = True
# Check if this is the end of the current entity
if current_entity and (
next_entity is None or next_entity["label"] != current_entity["label"]
):
# Add closing bracket
word_text = f"{word_text}]"
if current_entity_key in active_entities:
del active_entities[current_entity_key]
# Update the word
word["punctuated_word"] = word_text
# Close any remaining open entities at the end
if len(word_array) > 0 and word_array[-1] is not None:
last_word = word_array[-1]
last_word_text = last_word.get("punctuated_word") or last_word["word"]
for _ in active_entities:
last_word_text += "]"
last_word["punctuated_word"] = last_word_text
# Fix any .] or ,] punctuation issues.
punctuation = [".", ",", "!", "?", ":", ";"]
for word in word_array:
word_text = word.get("punctuated_word") or word["word"]
for p in punctuation:
if word_text.endswith(f"{p}]"):
word_text = word_text[:-2] + "]" + p
word["punctuated_word"] = word_text
# ============================================================================
# Speaker Management
# ============================================================================
class SpeakerAggregator:
def __init__(self) -> None:
self.speaker_labels: dict[tuple[int, int | None], int] = {}
def same_speaker_in_word_array(
self,
word_array: list[WordType],
different_channels_are_different_speakers: bool,
) -> bool:
"""Returns "True" if all word-level speaker tags are the same."""
labels = set()
for word in word_array:
labels.add(
self.get_speaker_label(word, different_channels_are_different_speakers)
)
return len(labels) == 1
def get_speaker_labels(
self,
word_array: list[WordType],
different_channels_are_different_speakers: bool,
) -> str:
"""
Get the speaker labels for the given word array.
Multiple speaker labels are returned if the speaker changes within the word array.
"""
if len(word_array) == 0:
return "-"
labels = sorted(
set(
self.get_speaker_label(word, different_channels_are_different_speakers)
for word in word_array
)
)
return "+".join(str(label) for label in labels)
def get_speaker_label(
self, word: WordType, different_channels_are_different_speakers: bool
) -> str:
"""
Get the speaker label for the given word. Unique speaker labels are generated on-demand.
The mapping is created on-the-fly as the words are processed using the channel and speaker.
"""
if different_channels_are_different_speakers:
# Use the channel and speaker to create a unique speaker label
speaker_id = (word["channel"], word.get("speaker", None))
else:
speaker_id = (0, word.get("speaker", None))
if speaker_id not in self.speaker_labels:
self.speaker_labels[speaker_id] = len(self.speaker_labels)
return str(self.speaker_labels[speaker_id])
# ============================================================================
# Transcript Line Building
# ============================================================================
@dataclass
class TranscriptLine:
"""Helper class to build formatted transcript lines"""
config: DisplayConfig
words_str: str
start: float
end: float
events: tuple[str, ...]
speaker_label: str = ""
channel: Optional[int | tuple[int, ...]] = None
received: Optional[datetime.datetime] = None
latency: Optional[float] = None
eot_latency: Optional[float] = None
def format(self) -> str:
"""Build the final formatted line"""
parts = []
# Add received timestamp if configured
if self.config.print_received and self.received is not None:
received_str = f"[{self.received.strftime('%H:%M:%S.%f')}]"
parts.append(received_str)
# Add interim latency if configured and available
if self.config.print_latency and self.latency is not None:
parts.append(f"[latency={self.latency:.3f}s]")
# Add EOT latency if configured and available
if self.config.print_latency and self.eot_latency is not None:
parts.append(f"[eot_latency={self.eot_latency:.3f}s]")
# Add duration
duration = f"[{format_time(self.start)} - {format_time(self.end)}]"
parts.append(duration)
# Add speaker if configured
if self.config.print_speakers and self.speaker_label:
parts.append(f"[Speaker {self.speaker_label}]")
# Add channel if configured
if self.config.print_channels and self.channel is not None:
parts.append(f"[Channel {self.channel}]")
# Add events
for event in self.events:
parts.append(f"[{event}]")
# Combine all parts
line = " ".join(parts) + f": {self.words_str}"
# Clean up spacing
while " " in line:
line = line.replace(" ", " ")
while " :" in line:
line = line.replace(" :", ":")
return line.strip()
def str_from_word_array(
streaming: bool,
received: datetime.datetime | None,
latency: float | None,
eot_latency: float | None,
word_array: list[WordType],
channel: int | tuple[int, ...],
start: float,
end: float,
events: tuple[str, ...],
allow_multiple_speakers: bool,
speaker_aggregator: SpeakerAggregator,
config: DisplayConfig,
use_rich_markup: bool = False,
) -> str | None:
"""
Convert the word array and associated metadata into a formatted string.
"""
# Return without printing if we are not printing interim results and is_final=false .
if streaming and not config.print_interim:
if "InterimResult" in events or "Update" in events or "StartOfTurn" in events:
return None
# Apply entity brackets if configured
if config.print_entities:
apply_entity_brackets(word_array)
# Build the words string with optional colorization
if config.colorize:
words_str = " ".join(
[
colorize_word(
word.get("punctuated_word", word["word"]),
word["confidence"],
use_rich_markup=use_rich_markup,
)
for word in word_array
]
)
else:
words_str = " ".join(
[word.get("punctuated_word") or word["word"] for word in word_array]
)
# Determine speaker configuration
# If print_speaker is true and print_channels is true, then don't treat channels are different speakers.
if config.print_speakers and config.print_channels:
different_channels_are_different_speakers = False
# If print_speakers is true and print_channels is false, then treat channels as different speakers.
elif config.print_speakers and not config.print_channels:
different_channels_are_different_speakers = True
# If print_speakers is false and print_channels is true, then don't treat channels as different speakers.
elif not config.print_speakers and config.print_channels:
different_channels_are_different_speakers = False
# If print_speakers is false and print_channels is false, then don't treat channels as different speakers.
elif not config.print_speakers and not config.print_channels:
different_channels_are_different_speakers = False
else:
raise ValueError("impossible")
# Get speaker label(s)
if not allow_multiple_speakers:
if len(word_array) > 0:
# Ensure all words are from the same speaker.
assert speaker_aggregator.same_speaker_in_word_array(
word_array, different_channels_are_different_speakers
)
# Get the single speaker label.
speaker_label = speaker_aggregator.get_speaker_label(
word_array[0], different_channels_are_different_speakers
)
else: # no words!
speaker_label = "0" # Default for empty arrays
else:
speaker_label = speaker_aggregator.get_speaker_labels(
word_array, different_channels_are_different_speakers
)
# Build and format the transcript line
line_builder = TranscriptLine(
words_str=words_str,
start=start,
end=end,
speaker_label=speaker_label if config.print_speakers else "",
channel=channel,
events=events,
received=received,
latency=latency,
eot_latency=eot_latency,
config=config,
)
return line_builder.format()
# ============================================================================
# EOT Latency Tracking (End-of-Turn Latency)
# ============================================================================
class EOTLatencyAggregator:
"""
Calculates End-of-Turn (EOT) latency for streaming transcription.
EOT latency measures the time from when the user finished speaking to when
we receive the finalizing transcript event. Requires VAD data (--vad flag)
to determine when speech actually ended.
The calculation is:
eot_latency = received_time_of_finalizing_event
- wall_clock_time_when_vad_segment_end_audio_was_sent
Supported EOT events:
- Nova: speech_final, UtteranceEnd (is_final without speech_final is NOT an EOT event)
- Flux: EndOfTurn, EagerEndOfTurn
"""
def __init__(
self,
vad_segments: list[dict] | None = None,
audio_send_times: list[dict] | None = None,
) -> None:
# VAD data for EOT latency calculation
self.vad_segments: list[dict] = vad_segments or []
self.audio_send_times: list[dict] = audio_send_times or []
# Nova: track Results messages for UtteranceEnd last_word_end lookup
self.results_history: list[dict] = []
# Store measurements as (event_type, latency_seconds)
self.measurements: list[tuple[str, float]] = []
@property
def has_vad_data(self) -> bool:
return bool(self.vad_segments) and bool(self.audio_send_times)
def record_message(self, message: dict) -> None:
"""Record a Results message for later UtteranceEnd lookup."""
if message.get("type") == "Results":
self.results_history.append(message)
def calculate_eot_latency(
self, message: dict, received: datetime.datetime
) -> tuple[str, float] | None:
"""
Calculate EOT latency for end-of-turn events.
Returns (event_type, latency_seconds) or None if not an EOT event
or if VAD data is unavailable.
"""
if not self.has_vad_data:
return None
# Nova: speech_final
if message.get("type") == "Results" and message.get("speech_final", False):
start = message.get("start", 0)
duration = message.get("duration", 0)
return self._vad_latency(start, start + duration, received, "speech_final")
# Nova: UtteranceEnd
if message.get("type") == "UtteranceEnd":
return self._utterance_end_latency(message, received)
# Flux: EndOfTurn or EagerEndOfTurn
if message.get("type") == "TurnInfo":
event = message.get("event")
if event in ("EndOfTurn", "EagerEndOfTurn"):
start = message.get("audio_window_start", 0)
end = message.get("audio_window_end", 0)
return self._vad_latency(start, end, received, event)
return None
def _vad_latency(
self,
window_start: float,
window_end: float,
received: datetime.datetime,
event_type: str,
) -> tuple[str, float] | None:
"""Compute VAD-based EOT latency for a finalizing event.
Finds the VAD segment whose end falls within the audio window, then
looks up the wall-clock time when that audio was sent.
"""
vad_seg = self._find_vad_segment_ending_in(window_start, window_end)
if vad_seg is None:
return None
sent_at = self._wall_clock_for_audio_time(vad_seg["end"])
if sent_at is None:
return None
eot_latency = (received - sent_at).total_seconds()
if eot_latency >= 0:
self.measurements.append((event_type, eot_latency))
return (event_type, eot_latency)
def _utterance_end_latency(
self, message: dict, received: datetime.datetime
) -> tuple[str, float] | None:
"""Compute VAD-based EOT latency for a Nova UtteranceEnd message.
Uses last_word_end to find the Results message containing a word with
a matching end timestamp, then uses that message's audio window to
locate the VAD segment.
"""
last_word_end = message.get("last_word_end", 0)
if last_word_end <= 0:
return None
channel = message.get("channel", [0])[0]
# Find the most recent Results message on this channel that contains
# a word whose end timestamp matches last_word_end.
target_message: dict | None = None
for msg in reversed(self.results_history):
if msg.get("channel_index", [0])[0] != channel:
continue
words = msg.get("channel", {}).get("alternatives", [{}])[0].get("words", [])
if any(w.get("end") == last_word_end for w in words):
target_message = msg
break
if target_message is None:
return None
start = target_message.get("start", 0)
duration = target_message.get("duration", 0)
return self._vad_latency(start, start + duration, received, "UtteranceEnd")
def _find_vad_segment_ending_in(
self, window_start: float, window_end: float
) -> dict | None:
"""Find the last VAD segment whose end falls within the given audio window."""
result = None
for seg in self.vad_segments:
if window_start <= seg["end"] <= window_end:
result = seg
return result
def _wall_clock_for_audio_time(
self, audio_time: float
) -> datetime.datetime | None:
"""Find the wall-clock time when the chunk containing audio_time was sent.
audio_send_times entries have audio_cursor (cumulative seconds sent after
this chunk) and sent_at (ISO timestamp). The first entry where
audio_cursor >= audio_time is the chunk that contained that audio.
"""
for entry in self.audio_send_times:
if entry["audio_cursor"] >= audio_time:
return datetime.datetime.fromisoformat(entry["sent_at"])
return None
def get_stats(self) -> dict:
"""Return EOT latency statistics."""
if not self.measurements:
return {"count": 0}
latencies = [m[1] for m in self.measurements]
sorted_latencies = sorted(latencies)
def percentile(p: float) -> float:
idx = int(len(sorted_latencies) * p)
return sorted_latencies[min(idx, len(sorted_latencies) - 1)]
return {
"min": min(latencies),
"p50": percentile(0.50),
"p95": percentile(0.95),
"p99": percentile(0.99),
"max": max(latencies),
"count": len(self.measurements),
"by_event": self._stats_by_event(),
}
def _stats_by_event(self) -> dict[str, dict]:
"""Get stats broken down by event type."""
from collections import defaultdict
by_event: dict[str, list[float]] = defaultdict(list)
for event_type, latency in self.measurements:
by_event[event_type].append(latency)
def percentile(sorted_vals: list[float], p: float) -> float:
idx = int(len(sorted_vals) * p)
return sorted_vals[min(idx, len(sorted_vals) - 1)]
result = {}
for event_type, latencies in by_event.items():
sorted_latencies = sorted(latencies)
result[event_type] = {
"min": min(latencies),
"p50": percentile(sorted_latencies, 0.50),
"p95": percentile(sorted_latencies, 0.95),
"p99": percentile(sorted_latencies, 0.99),
"max": max(latencies),
"count": len(latencies),
}
return result
def format_summary(self) -> str:
"""Return formatted summary string."""
stats = self.get_stats()
if stats["count"] == 0:
return "No EOT latency measurements (requires --vad flag during audio streaming)"
lines = [
f"EOT Latency: min={stats['min']:.3f}s, p50={stats['p50']:.3f}s, "
f"p95={stats['p95']:.3f}s, p99={stats['p99']:.3f}s, "
f"max={stats['max']:.3f}s ({stats['count']} events)"
]
for event_type, event_stats in stats["by_event"].items():
lines.append(
f" {event_type}: min={event_stats['min']:.3f}s, p50={event_stats['p50']:.3f}s, "
f"p95={event_stats['p95']:.3f}s, p99={event_stats['p99']:.3f}s, "
f"max={event_stats['max']:.3f}s ({event_stats['count']} events)"
)
return "\n".join(lines)
def colorize_lines(
self, lines: list[str], use_rich_markup: bool = False
) -> list[str]:
"""
Post-process transcript lines to colorize EOT latency values.
Replaces [eot_latency=X.XXXs] with colorized version based on min/max.
"""
import re
stats = self.get_stats()
if stats["count"] == 0:
return lines
min_lat = stats["min"]
max_lat = stats["max"]
# If the worst latency is less than 400ms, that's still really good.
# We will manually increase the worst case latency to 400ms in these cases.
if max_lat <= 0.4:
max_lat = 0.4
# Pattern to match [eot_latency=0.123s]
pattern = re.compile(r"\[eot_latency=(\d+\.\d+)s\]")
colorized_lines = []
for line in lines:
def replace_latency(match):
latency_val = float(match.group(1))
colored = colorize_latency(
latency_val, min_lat, max_lat, use_rich_markup
)
return f"[eot_latency={colored}]"
colorized_lines.append(pattern.sub(replace_latency, line))
return colorized_lines
# ============================================================================
# Interim Latency Tracking (Message Latency per Deepgram methodology)
# ============================================================================
class LatencyAggregator:
"""
Calculates message latency following Deepgram's methodology.
Latency = audio_cursor - transcript_cursor
Where:
audio_cursor = seconds of audio sent to Deepgram (from message)
transcript_cursor = start + duration from the response
Per Deepgram docs, latency is measured using INTERIM results because
they arrive faster and reflect actual real-time latency.
Supported interim message types:
- Nova: Results with is_final=false
- Flux: TurnInfo with event=Update or event=TurnResumed
Reference: https://developers.deepgram.com/docs/measuring-streaming-latency
"""
def __init__(self) -> None:
self.measurements: list[float] = []
def calculate_latency(self, message: dict) -> float | None:
"""
Calculate latency for an interim result message (Nova or Flux).
Returns latency in seconds, or None if not applicable.
"""
audio_cursor: float | None = None
transcript_cursor: float | None = None
# Nova: Results messages
if message.get("type") == "Results":
# Only measure interim results
if message.get("is_final", True):
return None
audio_cursor = message.get("audio_cursor")
start = message.get("start", 0)
duration = message.get("duration", 0)
if duration <= 0:
return None
transcript_cursor = start + duration
# Flux: TurnInfo messages with Update or TurnResumed events
elif message.get("type") == "TurnInfo":
event = message.get("event")
if event not in ("Update", "TurnResumed"):
return None
audio_cursor = message.get("audio_cursor")
audio_window_end = message.get("audio_window_end", 0)
if audio_window_end <= 0:
return None
transcript_cursor = audio_window_end
else:
return None
# Need audio_cursor to calculate latency
if audio_cursor is None:
return None
if transcript_cursor is None:
return None
cur_latency = audio_cursor - transcript_cursor
# Record measurement
self.measurements.append(cur_latency)
return cur_latency
def get_p50(self) -> float | None:
"""Calculate p50 latency."""
if not self.measurements:
return None
sorted_measurements = sorted(self.measurements)
idx = int(len(sorted_measurements) * 0.50)
idx = min(idx, len(sorted_measurements) - 1)
return sorted_measurements[idx]
def get_p95(self) -> float | None:
"""Calculate p95 latency."""
if not self.measurements:
return None
sorted_measurements = sorted(self.measurements)
idx = int(len(sorted_measurements) * 0.95)
idx = min(idx, len(sorted_measurements) - 1)
return sorted_measurements[idx]
def get_p99(self) -> float | None:
"""Calculate p99 latency."""
if not self.measurements:
return None
sorted_measurements = sorted(self.measurements)
idx = int(len(sorted_measurements) * 0.99)
idx = min(idx, len(sorted_measurements) - 1)
return sorted_measurements[idx]
def get_stats(self) -> dict:
"""Return latency statistics."""
if not self.measurements:
return {
"min": None,
"p50": None,
"p95": None,
"p99": None,
"max": None,
"count": 0,
}
p50 = self.get_p50()
p95 = self.get_p95()
p99 = self.get_p99()
return {
"min": min(self.measurements) if self.measurements else None,
"p50": p50,
"p95": p95,
"p99": p99,
"max": max(self.measurements) if self.measurements else None,
"count": len(self.measurements),
}
def format_summary(self) -> str:
"""Return formatted summary string."""
stats = self.get_stats()
if stats["count"] == 0:
return "No latency measurements (requires interim_results=true and audio_cursor in messages)"
return (
f"Message Latency: min={round(stats['min'], 3):.3f}s, p50={round(stats['p50'], 3):.3f}s, p95={round(stats['p95'], 3):.3f}s, p99={round(stats['p99'], 3):.3f}s, "
f"max={round(stats['max'], 3):.3f}s ({stats['count']} measurements)"
)
def colorize_lines(
self, lines: list[str], use_rich_markup: bool = False
) -> list[str]:
"""
Post-process transcript lines to colorize latency values.
Replaces [latency=X.XXXs] with colorized version based on min/max.
"""
import re
stats = self.get_stats()
min_latency = stats["min"]
max_latency = stats["max"]
if not self.measurements or min_latency is None or max_latency is None:
return lines
min_lat = min_latency
max_lat = max_latency
# If the worst latency is less than 400ms, that's still really good.
# We will manually increase the worst case latency to 400ms in these cases.
if max_lat <= 0.4:
max_lat = 0.4
# Pattern to match [latency=0.123s]
pattern = re.compile(r"\[latency=(\d+\.\d+)s\]")
colorized_lines = []
for line in lines:
def replace_latency(match):
latency_val = float(match.group(1))
colored = colorize_latency(
latency_val, min_lat, max_lat, use_rich_markup
)
return f"[latency={colored}]"
colorized_lines.append(pattern.sub(replace_latency, line))
return colorized_lines
# ============================================================================
# Response Metrics (TTFT and Update Frequency)
# ============================================================================
class ResponseMetricsAggregator:
"""
Tracks Time-to-First-Transcript (TTFT) and Update Frequency metrics.
TTFT: Wall-clock time from first audio sent (OpenStream) to first
transcript message received (Results or TurnInfo). This includes empty
transcripts, as they still indicate Deepgram has processed audio.
Update Frequency: Number of interim/update messages per second of audio.
This captures how "responsive" the transcription feels to users, as more
frequent updates create a more fluid real-time experience.
"""
def __init__(self) -> None:
# TTFT tracking
self.first_audio_sent_time: datetime.datetime | None = None
self.first_transcript_received_time: datetime.datetime | None = None
# Update frequency tracking
self.interim_message_count: int = 0
self.total_audio_duration: float = 0.0
def record_stream_start(self, received: datetime.datetime) -> None:
"""Record when audio streaming begins (OpenStream message)."""