-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstt_assemblyai_speaker_mapper.py
More file actions
executable file
·2579 lines (2120 loc) · 89.2 KB
/
stt_assemblyai_speaker_mapper.py
File metadata and controls
executable file
·2579 lines (2120 loc) · 89.2 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
#!/usr/bin/env -S uv run
# /// script
# dependencies = [
# "instructor>=1.0.0",
# "pydantic>=2.0.0",
# "openai>=1.0.0",
# ]
# requires-python = ">=3.11"
# ///
"""
AssemblyAI Speaker Name Mapper
Post-processing tool to replace speaker labels (A, B, C) with actual names
in AssemblyAI transcription JSON files. Uses recursive traversal to handle
any JSON structure, making it future-proof and format-agnostic.
Features:
- LLM-assisted speaker detection with multiple provider support
- Interactive mapping with AI suggestions as defaults
- Audio preview: hear samples of each speaker during mapping
- Verification mode: review and correct existing mappings with audio
- Speaker audio extraction: save speaker segments to separate files
Usage:
# Detect speakers
./stt_assemblyai_speaker_mapper.py --detect audio.assemblyai.json
# LLM-assisted interactive (AI suggestions + audio preview)
./stt_assemblyai_speaker_mapper.py --llm-interactive gpt-4o-mini audio.assemblyai.json
# Preview audio samples for a speaker
./stt_assemblyai_speaker_mapper.py --preview-speaker A audio.assemblyai.json
# Verify/review existing mappings with audio
./stt_assemblyai_speaker_mapper.py --verify audio.assemblyai.mapped.json
# Extract speaker audio to file
./stt_assemblyai_speaker_mapper.py --extract-speaker A -o speaker_a.mp3 audio.assemblyai.json
# Map via inline comma-separated names
./stt_assemblyai_speaker_mapper.py -m "Alice,Bob" audio.assemblyai.json
# Interactive mapping (manual)
./stt_assemblyai_speaker_mapper.py --interactive audio.assemblyai.json
Requirements for audio features:
- ffmpeg (for audio extraction)
- mpv, ffplay, or mplayer (for playback with seeking)
"""
import argparse
import sys
import json
import os
import re
import shutil
import tempfile
import subprocess
from typing import Dict, List, Optional, Union, Tuple
# Optional LLM detection support
try:
import instructor
from pydantic import BaseModel, Field, ConfigDict
from openai import OpenAI
INSTRUCTOR_AVAILABLE = True
except ImportError:
INSTRUCTOR_AVAILABLE = False
instructor = None
BaseModel = None
Field = None
ConfigDict = None
OpenAI = None
# ----------------------------------------------------------------------
# Model Shortcuts - Map common names to full provider/model strings
# ----------------------------------------------------------------------
MODEL_SHORTCUTS = {
# OpenAI models (best structured output support)
'4o-mini': 'openai/gpt-4o-mini',
'gpt-4o-mini': 'openai/gpt-4o-mini',
'4o': 'openai/gpt-4o',
'gpt-4o': 'openai/gpt-4o',
'4.1': 'openai/gpt-4.1',
'gpt-4.1': 'openai/gpt-4.1',
'4.1-mini': 'openai/gpt-4.1-mini',
'gpt-4.1-mini': 'openai/gpt-4.1-mini',
'4.1-nano': 'openai/gpt-4.1-nano',
'gpt-4.1-nano': 'openai/gpt-4.1-nano',
'o1': 'openai/o1',
'o3-mini': 'openai/o3-mini',
# Anthropic Claude (best accuracy for speaker detection)
'sonnet': 'anthropic/claude-sonnet-4-5',
'claude-sonnet': 'anthropic/claude-sonnet-4-5',
'sonnet-4-5': 'anthropic/claude-sonnet-4-5',
'claude-sonnet-4-5': 'anthropic/claude-sonnet-4-5',
'opus': 'anthropic/claude-opus-4-1',
'claude-opus': 'anthropic/claude-opus-4-1',
'opus-4-1': 'anthropic/claude-opus-4-1',
'claude-opus-4-1': 'anthropic/claude-opus-4-1',
'haiku': 'anthropic/claude-3-5-haiku',
'claude-haiku': 'anthropic/claude-3-5-haiku',
'haiku-3-5': 'anthropic/claude-3-5-haiku',
'claude-3-5-haiku': 'anthropic/claude-3-5-haiku',
'sonnet-3-7': 'anthropic/claude-3-7-sonnet',
'claude-3-7-sonnet': 'anthropic/claude-3-7-sonnet',
# Google Gemini (cost leader)
'gemini': 'google/gemini-2.5-flash',
'gemini-flash': 'google/gemini-2.5-flash',
'gemini-2.5': 'google/gemini-2.5-flash',
'gemini-2.5-flash': 'google/gemini-2.5-flash',
'gemini-2.0': 'google/gemini-2.0-flash',
'gemini-2.0-flash': 'google/gemini-2.0-flash',
'gemini-pro': 'google/gemini-2.0-pro-experimental',
'gemini-2.0-pro': 'google/gemini-2.0-pro-experimental',
# Groq (ultra-fast inference)
'llama': 'groq/llama-3.3-70b-versatile',
'llama3.3': 'groq/llama-3.3-70b-versatile',
'llama-3.3': 'groq/llama-3.3-70b-versatile',
'llama3.2': 'groq/llama-3.2-3b-preview',
'llama-3.2': 'groq/llama-3.2-3b-preview',
'llama3.1': 'groq/llama-3.1-8b-instant',
'llama-3.1': 'groq/llama-3.1-8b-instant',
# DeepSeek (cost effective with caching)
'deepseek': 'deepseek/deepseek-v3.2-exp',
'deepseek-v3': 'deepseek/deepseek-v3.2-exp',
'deepseek-v3.2': 'deepseek/deepseek-v3.2-exp',
'deepseek-r1': 'deepseek/deepseek-r1',
# Mistral
'mistral': 'mistral/mistral-large-latest',
'mistral-large': 'mistral/mistral-large-latest',
'mistral-medium': 'mistral/mistral-medium-3',
'mistral-small': 'mistral/mistral-small',
'codestral': 'mistral/codestral',
# Ollama (local deployment) - Small CPU-optimized models
'ollama': 'ollama/llama3.2',
'ollama-llama': 'ollama/llama3.2',
'ollama-mistral': 'ollama/mistral',
# SmolLM2 series (best small models for CPU, 16GB RAM friendly)
'smollm2': 'ollama/smollm2:1.7b',
'smollm2:1.7b': 'ollama/smollm2:1.7b',
'smollm2-1.7b': 'ollama/smollm2:1.7b',
'smollm2:360m': 'ollama/smollm2:360m',
'smollm2-360m': 'ollama/smollm2:360m',
'smollm2:135m': 'ollama/smollm2:135m',
'smollm2-135m': 'ollama/smollm2:135m',
# Qwen2.5 small variants (excellent small coders)
'qwen2.5:0.5b': 'ollama/qwen2.5:0.5b',
'qwen2.5-0.5b': 'ollama/qwen2.5:0.5b',
'qwen2.5:1.5b': 'ollama/qwen2.5:1.5b',
'qwen2.5-1.5b': 'ollama/qwen2.5:1.5b',
'qwen2.5:3b': 'ollama/qwen2.5:3b',
'qwen2.5-3b': 'ollama/qwen2.5:3b',
'qwen2.5-coder:0.5b': 'ollama/qwen2.5-coder:0.5b',
'qwen2.5-coder-0.5b': 'ollama/qwen2.5-coder:0.5b',
'qwen2.5-coder:1.5b': 'ollama/qwen2.5-coder:1.5b',
'qwen2.5-coder-1.5b': 'ollama/qwen2.5-coder:1.5b',
'qwen2.5-coder:3b': 'ollama/qwen2.5-coder:3b',
'qwen2.5-coder-3b': 'ollama/qwen2.5-coder:3b',
# Llama 3.2 small variants (fast on CPU)
'llama3.2:1b': 'ollama/llama3.2:1b',
'llama3.2-1b': 'ollama/llama3.2:1b',
'llama3.2:3b': 'ollama/llama3.2:3b',
'llama3.2-3b': 'ollama/llama3.2:3b',
# Phi models (punches above weight)
'phi3': 'ollama/phi3:mini',
'phi3:mini': 'ollama/phi3:mini',
'phi3-mini': 'ollama/phi3:mini',
'phi3:3.8b': 'ollama/phi3:3.8b',
'phi4': 'ollama/phi4:14b',
# DeepSeek Coder (coding specialist)
'deepseek-coder': 'ollama/deepseek-coder:1.3b',
'deepseek-coder:1.3b': 'ollama/deepseek-coder:1.3b',
'deepseek-coder-1.3b': 'ollama/deepseek-coder:1.3b',
# Other popular small models
'tinyllama': 'ollama/tinyllama:1.1b',
'tinyllama:1.1b': 'ollama/tinyllama:1.1b',
'stablelm-zephyr': 'ollama/stablelm-zephyr:3b',
'stablelm-zephyr:3b': 'ollama/stablelm-zephyr:3b',
'orca-mini': 'ollama/orca-mini:3b',
'orca-mini:3b': 'ollama/orca-mini:3b',
}
def resolve_model_shortcut(model_string: str) -> str:
"""
Resolve model shortcut to full provider/model string.
Args:
model_string: Model name or shortcut (e.g., "4o-mini", "sonnet", "openai/gpt-4o")
Returns:
Full provider/model string (e.g., "openai/gpt-4o-mini")
Examples:
>>> resolve_model_shortcut("4o-mini")
'openai/gpt-4o-mini'
>>> resolve_model_shortcut("sonnet")
'anthropic/claude-sonnet-4-5'
>>> resolve_model_shortcut("openai/gpt-4o")
'openai/gpt-4o'
"""
# If already in provider/model format, return as-is
if '/' in model_string:
return model_string
# Case-insensitive lookup
model_lower = model_string.lower()
return MODEL_SHORTCUTS.get(model_lower, model_string)
# ----------------------------------------------------------------------
# META Message Helper (for transcript warnings)
# ----------------------------------------------------------------------
def get_meta_message(args):
"""
Get META warning message for STT transcripts.
Returns empty string if disabled via flag or environment variable.
Returns custom message if STT_META_MESSAGE env var is set.
Returns default message otherwise.
"""
# Check command-line flag
if getattr(args, 'no_meta_message', False) or getattr(args, 'disable_meta_message', False):
return ""
# Check environment variable for disabling
if os.environ.get('STT_META_MESSAGE_DISABLE', '').lower() in ('1', 'true', 'yes'):
return ""
# Check for custom message
custom_message = os.environ.get('STT_META_MESSAGE', '').strip()
if custom_message:
return f"---\nmeta: {custom_message}\n---\n"
# Default META message
default_message = (
"THIS IS AN AUTOMATED SPEECH-TO-TEXT (STT) TRANSCRIPT AND MAY CONTAIN TRANSCRIPTION ERRORS. "
"This transcript was generated by automated speech recognition technology and should be treated "
"as a rough transcription for reference purposes. Common types of errors include: incorrect word "
"recognition (especially homophones, proper nouns, technical terminology, or words in noisy audio "
"conditions), missing or incorrect punctuation, speaker misidentification in multi-speaker scenarios, "
"and timing inaccuracies. For best comprehension and to mentally correct potential errors, please consider: "
"the broader conversational context, relevant domain knowledge, technical background of the subject matter, "
"and any supplementary information about the speakers or topic. This transcript is intended to convey "
"the general content and flow of the conversation rather than serving as a verbatim, word-perfect record. "
"When critical accuracy is required, please verify important details against the original audio source."
)
return f"---\nmeta: {default_message}\n---\n"
# ----------------------------------------------------------------------
# Verbosity-aware logger (matches stt_assemblyai.py pattern)
# ----------------------------------------------------------------------
def _should_log(args, level_threshold):
return getattr(args, "verbose", 0) >= level_threshold and not getattr(args, "quiet", False)
def log_error(args, message):
print(f"ERROR: {message}", file=sys.stderr)
def log_warning(args, message):
if _should_log(args, 0):
print(f"WARNING: {message}", file=sys.stderr)
def log_info(args, message):
if _should_log(args, 1):
print(f"INFO: {message}", file=sys.stderr)
def log_debug(args, message):
if _should_log(args, 5):
print(f"DEBUG: {message}", file=sys.stderr)
# ----------------------------------------------------------------------
# About File Helper
# ----------------------------------------------------------------------
def get_about_file_path(input_json: str) -> str:
"""
Generate about file path from input JSON path.
Examples:
audio.mp3.assemblyai.json → audio.mp3.about.md
Args:
input_json: Path to input JSON file
Returns:
Path to about file
"""
if input_json.endswith('.assemblyai.json'):
base_audio = input_json[:-len('.assemblyai.json')]
else:
base_audio = input_json
return f"{base_audio}.about.md"
def get_about_file_content(input_json: str) -> Optional[str]:
"""
Load .about.md file content if it exists.
About files provide context about the audio (speaker names, roles, topics)
to help improve LLM speaker detection accuracy.
Args:
input_json: Path to input JSON file
Returns:
Content of about file, or None if file doesn't exist
"""
about_path = get_about_file_path(input_json)
if os.path.exists(about_path):
try:
with open(about_path, 'r') as f:
return f.read().strip()
except Exception:
return None
return None
# Directory context filename (searched in parent directories)
DIRECTORY_CONTEXT_FILENAME = "SPEAKER.CONTEXT.md"
def find_directory_context_file(input_json: str) -> Optional[str]:
"""
Find SPEAKER.CONTEXT.md in same directory or parent directories.
Searches both original path and resolved path (via realpath).
Similar to how .gitignore or .editorconfig files work.
Args:
input_json: Path to input JSON file
Returns:
Path to found context file, or None if not found
"""
# Get base audio path
if input_json.endswith('.assemblyai.json'):
base_audio = input_json[:-len('.assemblyai.json')]
else:
base_audio = input_json
original_dir = os.path.dirname(os.path.abspath(base_audio)) or '.'
resolved_dir = os.path.dirname(os.path.realpath(base_audio)) or '.'
# Walk up both paths, collect unique directories
dirs_to_check = []
for start_dir in [original_dir, resolved_dir]:
current = start_dir
while current:
if current not in dirs_to_check:
dirs_to_check.append(current)
parent = os.path.dirname(current)
if parent == current: # Reached root
break
current = parent
# Return first found
for dir_path in dirs_to_check:
context_path = os.path.join(dir_path, DIRECTORY_CONTEXT_FILENAME)
if os.path.exists(context_path):
return context_path
return None
def get_directory_context_content(input_json: str) -> tuple[Optional[str], Optional[str]]:
"""
Load directory context file content if it exists.
Args:
input_json: Path to input JSON file
Returns:
Tuple of (content, path) or (None, None) if not found
"""
context_path = find_directory_context_file(input_json)
if context_path:
try:
with open(context_path, 'r') as f:
return f.read().strip(), context_path
except Exception:
return None, None
return None, None
# ----------------------------------------------------------------------
# Audio Preview Functions
# ----------------------------------------------------------------------
def find_audio_player() -> Tuple[Optional[str], List[str]]:
"""
Find available audio player with seeking support.
Checks for players in order of preference:
1. mpv - Best choice, excellent seeking, terminal-friendly
2. ffplay - Good fallback, comes with ffmpeg
3. mplayer - Older but capable
Returns:
Tuple of (player_name, base_command_args) or (None, []) if none found
"""
players = [
('mpv', ['mpv', '--no-video', '--term-osd-bar']),
('ffplay', ['ffplay', '-nodisp', '-autoexit']),
('mplayer', ['mplayer', '-vo', 'null']),
]
for name, cmd in players:
if shutil.which(cmd[0]):
return name, cmd
return None, []
def find_ffmpeg() -> Optional[str]:
"""Check if ffmpeg is available."""
return shutil.which('ffmpeg')
def get_audio_file_path(input_json: str) -> str:
"""
Derive audio file path from JSON path.
Examples:
audio.mp3.assemblyai.json → audio.mp3
audio.mp3.assemblyai.mapped.json → audio.mp3
Args:
input_json: Path to JSON file
Returns:
Path to original audio file
"""
path = input_json
# Remove known suffixes
for suffix in ['.assemblyai.mapped.json', '.assemblyai.json', '.mapped.json']:
if path.endswith(suffix):
return path[:-len(suffix)]
# Fallback: just remove .json
if path.endswith('.json'):
return path[:-5]
return path
def get_speaker_utterances(
json_data: dict,
speaker_label: str
) -> List[dict]:
"""
Get all utterances for a specific speaker with timing info.
Args:
json_data: Full AssemblyAI JSON data
speaker_label: Speaker label to filter (e.g., 'A', 'B')
Returns:
List of utterance dicts with 'start', 'end', 'text' keys
"""
utterances = json_data.get('utterances', [])
return [u for u in utterances if u.get('speaker') == speaker_label]
def format_duration(ms: int) -> str:
"""Format milliseconds as human-readable duration."""
seconds = ms / 1000
if seconds < 60:
return f"{seconds:.1f}s"
minutes = int(seconds // 60)
secs = seconds % 60
return f"{minutes}m {secs:.0f}s"
def extract_speaker_audio(
audio_file: str,
utterances: List[dict],
output_file: str,
max_samples: int = 10,
max_duration_per_sample: float = 8.0,
silence_gap: float = 0.3,
args=None
) -> Tuple[bool, str]:
"""
Extract and concatenate speaker audio samples using ffmpeg.
Uses ffmpeg's filter_complex for efficient single-pass extraction.
Adds short silence between samples for clarity.
Args:
audio_file: Path to source audio file
utterances: List of utterance dicts with 'start' and 'end' (in ms)
output_file: Path to output concatenated audio
max_samples: Maximum number of samples to extract
max_duration_per_sample: Max duration per sample in seconds
silence_gap: Silence duration between samples in seconds
args: Arguments namespace for logging
Returns:
Tuple of (success: bool, message: str)
"""
if not utterances:
return False, "No utterances found for speaker"
ffmpeg = find_ffmpeg()
if not ffmpeg:
return False, "ffmpeg not found. Install with: sudo pacman -S ffmpeg"
if not os.path.exists(audio_file):
return False, f"Audio file not found: {audio_file}"
# Select samples (first N, capped by max_duration_per_sample)
selected = []
for utt in utterances[:max_samples]:
start_ms = utt.get('start', 0)
end_ms = utt.get('end', 0)
duration_s = (end_ms - start_ms) / 1000
# Cap duration
if duration_s > max_duration_per_sample:
end_ms = start_ms + int(max_duration_per_sample * 1000)
selected.append({
'start': start_ms / 1000, # Convert to seconds
'end': end_ms / 1000,
'text': utt.get('text', '')[:50] # Preview text
})
if not selected:
return False, "No samples selected"
# Build ffmpeg filter_complex
# Format: [0]atrim=start=X:end=Y,asetpts=PTS-STARTPTS[aN];...
# Then: [a1][silence][a2][silence]...concat
filter_parts = []
concat_inputs = []
for i, sample in enumerate(selected):
label = f"a{i}"
filter_parts.append(
f"[0]atrim=start={sample['start']:.3f}:end={sample['end']:.3f},"
f"asetpts=PTS-STARTPTS[{label}]"
)
concat_inputs.append(f"[{label}]")
# Add silence between samples (except after last)
if i < len(selected) - 1 and silence_gap > 0:
silence_label = f"s{i}"
# Generate silence using anullsrc
filter_parts.append(
f"anullsrc=r=44100:cl=stereo,atrim=0:{silence_gap:.2f}[{silence_label}]"
)
concat_inputs.append(f"[{silence_label}]")
# Concat all segments
n_segments = len(concat_inputs)
filter_parts.append(
f"{''.join(concat_inputs)}concat=n={n_segments}:v=0:a=1[out]"
)
filter_complex = ';'.join(filter_parts)
# Build ffmpeg command
cmd = [
ffmpeg,
'-i', audio_file,
'-filter_complex', filter_complex,
'-map', '[out]',
'-y', # Overwrite output
'-loglevel', 'error',
output_file
]
try:
log_debug(args, f"Running ffmpeg with {len(selected)} samples")
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
if result.returncode != 0:
error_msg = result.stderr.strip() if result.stderr else "Unknown error"
return False, f"ffmpeg failed: {error_msg}"
total_duration = sum(s['end'] - s['start'] for s in selected)
return True, f"Extracted {len(selected)} samples ({format_duration(int(total_duration * 1000))})"
except subprocess.TimeoutExpired:
return False, "ffmpeg timed out"
except Exception as e:
return False, f"ffmpeg error: {e}"
def play_audio_file(
filepath: str,
player_name: str = None,
player_cmd: List[str] = None,
args=None
) -> bool:
"""
Play audio file with seeking-capable terminal player.
Args:
filepath: Path to audio file to play
player_name: Name of player (for display)
player_cmd: Command and args to run player
args: Arguments namespace for logging
Returns:
True if playback completed, False on error
"""
if player_cmd is None:
player_name, player_cmd = find_audio_player()
if not player_cmd:
log_error(args, "No audio player found. Install mpv: sudo pacman -S mpv")
return False
# Build full command
cmd = player_cmd + [filepath]
# Show controls hint
if player_name == 'mpv':
hint = "mpv: ←/→ seek 5s, ↑/↓ seek 1m, space=pause, q=quit"
elif player_name == 'ffplay':
hint = "ffplay: ←/→ seek 10s, space=pause, q=quit"
else:
hint = f"{player_name}: use arrow keys to seek, q=quit"
print(f"→ Playing ({hint})", file=sys.stderr)
try:
# Run player, letting it take over terminal
result = subprocess.run(cmd, check=False)
return result.returncode == 0
except KeyboardInterrupt:
print("", file=sys.stderr) # Clean line after Ctrl+C
return True # User interrupted, not an error
except Exception as e:
log_error(args, f"Playback failed: {e}")
return False
def preview_speaker_audio(
audio_file: str,
json_data: dict,
speaker_label: str,
speaker_name: str = None,
max_samples: int = 10,
args=None
) -> bool:
"""
High-level function to preview audio samples for a speaker.
Extracts samples to temp file, plays them, then cleans up.
Args:
audio_file: Path to source audio file
json_data: Full AssemblyAI JSON data
speaker_label: Speaker label (e.g., 'A', 'B')
speaker_name: Display name for speaker (optional)
max_samples: Maximum samples to extract
args: Arguments namespace
Returns:
True if preview completed successfully
"""
display_name = speaker_name or f"Speaker {speaker_label}"
# Get utterances for this speaker
utterances = get_speaker_utterances(json_data, speaker_label)
if not utterances:
print(f"No utterances found for {display_name}", file=sys.stderr)
return False
# Calculate stats
total_duration = sum(u.get('end', 0) - u.get('start', 0) for u in utterances)
print(f"\nExtracting samples for {display_name}...", file=sys.stderr)
print(f" Found {len(utterances)} utterances ({format_duration(total_duration)})", file=sys.stderr)
# Find audio player first
player_name, player_cmd = find_audio_player()
if not player_cmd:
print("ERROR: No audio player found. Install mpv: sudo pacman -S mpv", file=sys.stderr)
return False
# Create temp file for extracted audio
with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as tmp:
tmp_path = tmp.name
try:
# Extract audio samples
success, message = extract_speaker_audio(
audio_file,
utterances,
tmp_path,
max_samples=max_samples,
args=args
)
if not success:
print(f"ERROR: {message}", file=sys.stderr)
return False
print(f" {message}", file=sys.stderr)
# Play the extracted audio
return play_audio_file(tmp_path, player_name, player_cmd, args)
finally:
# Clean up temp file
try:
os.unlink(tmp_path)
except OSError:
pass
# ----------------------------------------------------------------------
# Core JSON Traversal Functions
# ----------------------------------------------------------------------
def detect_speakers_in_json(json_obj, found=None):
"""
Recursively find all unique values associated with "speaker" keys.
Args:
json_obj: JSON object (dict/list/primitive)
found: Set to accumulate speaker labels (internal use)
Returns:
Set of speaker labels (e.g., {'A', 'B', 'C'})
"""
if found is None:
found = set()
if isinstance(json_obj, dict):
for key, value in json_obj.items():
if key == "speaker" and isinstance(value, str):
found.add(value)
else:
detect_speakers_in_json(value, found)
elif isinstance(json_obj, list):
for item in json_obj:
detect_speakers_in_json(item, found)
return found
def replace_speakers_recursive(obj, speaker_map):
"""
Recursively traverse JSON and replace all "speaker" key values.
Args:
obj: JSON object (dict/list/primitive)
speaker_map: Dict mapping speaker labels (e.g., {'A': 'Alice Anderson'})
Returns:
Modified copy with speaker replacements applied
"""
if isinstance(obj, dict):
result = {}
for key, value in obj.items():
if key == "speaker" and isinstance(value, str):
# Found a speaker field - apply mapping if available
result[key] = speaker_map.get(value, value)
else:
# Recurse into nested structures
result[key] = replace_speakers_recursive(value, speaker_map)
return result
elif isinstance(obj, list):
# Recurse into list items
return [replace_speakers_recursive(item, speaker_map) for item in obj]
else:
# Primitive value - return as-is
return obj
def find_transcript_segments(json_obj):
"""
Find lists of transcript segments in JSON.
Heuristic: Look for lists of dicts containing 'speaker' and 'text' keys.
Tries common paths first ('utterances'), then searches recursively.
Args:
json_obj: JSON object to search
Returns:
List of segment dicts with 'speaker' and 'text' keys
"""
# Fast path: check common AssemblyAI location
if isinstance(json_obj, dict) and 'utterances' in json_obj:
return json_obj['utterances']
# Recursive search
segments = []
if isinstance(json_obj, dict):
for value in json_obj.values():
segments.extend(find_transcript_segments(value))
elif isinstance(json_obj, list):
# Check if this list looks like transcript segments
if json_obj and isinstance(json_obj[0], dict):
if 'speaker' in json_obj[0] and 'text' in json_obj[0]:
return json_obj
# Otherwise recurse into list items
for item in json_obj:
segments.extend(find_transcript_segments(item))
return segments
# ----------------------------------------------------------------------
# LLM-Assisted Speaker Detection (Optional)
# ----------------------------------------------------------------------
if INSTRUCTOR_AVAILABLE:
class SpeakerMapping(BaseModel):
"""Individual speaker label to name mapping."""
speaker_label: str = Field(
description="Speaker label from transcript (e.g., 'A', 'B', 'SPEAKER_00')"
)
speaker_name: str = Field(
description="Identified name or role for this speaker"
)
context: str = Field(
description="Brief contextual information about this speaker: topics discussed, role in conversation, keywords, adjectives, or identifying characteristics to help identify them even if name is uncertain",
default=""
)
class SpeakerDetection(BaseModel):
"""Pydantic model for LLM speaker detection response."""
model_config = ConfigDict(extra='allow')
speakers: List[SpeakerMapping] = Field(
description='List of speaker mappings. Must include one mapping for EACH detected speaker label.'
)
confidence: str = Field(
description="Confidence level: low, medium, or high",
default="medium"
)
reasoning: str = Field(
description="Brief explanation of how speakers were identified",
default=""
)
def extract_transcript_sample(json_obj: dict, max_utterances: int = 20) -> str:
"""
Extract strategic sample of transcript for LLM analysis.
Strategy:
1. Include first few utterances (introductions often here)
2. Include utterances with potential name mentions (proper nouns)
3. Include utterances from each speaker
4. Limit total to avoid token limits
Args:
json_obj: Full AssemblyAI JSON
max_utterances: Maximum utterances to include
Returns:
Formatted transcript sample string
"""
utterances = json_obj.get('utterances', [])
if not utterances:
return ""
# Strategy 1: First N utterances (catch introductions)
first_n = min(10, len(utterances))
sample_utterances = utterances[:first_n]
# Strategy 2: Add utterances with potential names (proper nouns)
if len(utterances) > first_n:
for utt in utterances[first_n:]:
text = utt.get('text', '')
# Simple heuristic: contains capitalized words (potential names)
if has_proper_nouns(text) and len(sample_utterances) < max_utterances:
sample_utterances.append(utt)
# Strategy 3: Ensure all speakers represented
represented_speakers = {u.get('speaker') for u in sample_utterances}
all_speakers = {u.get('speaker') for u in utterances}
missing_speakers = all_speakers - represented_speakers
if missing_speakers and len(sample_utterances) < max_utterances:
for utt in utterances:
if utt.get('speaker') in missing_speakers:
sample_utterances.append(utt)
missing_speakers.remove(utt.get('speaker'))
if not missing_speakers or len(sample_utterances) >= max_utterances:
break
# Format as readable transcript
lines = []
for utt in sample_utterances:
speaker = utt.get('speaker', 'Unknown')
text = utt.get('text', '')
lines.append(f"Speaker {speaker}: {text}")
return '\n'.join(lines)
def has_proper_nouns(text: str) -> bool:
"""
Check if text contains capitalized words (potential names).
Args:
text: Input text to check
Returns:
True if proper nouns detected
"""
# Match capitalized words that aren't sentence starts
pattern = r'(?<![.!?]\s)(?<!\A)\b[A-Z][a-z]+'
return bool(re.search(pattern, text))
def detect_speakers_llm(
provider_model: str,
transcript_sample: str,
detected_labels: List[str],
endpoint: Optional[str] = None,
args=None,
input_json: Optional[str] = None
):
"""
Detect speaker names using LLM via Instructor.
Args:
provider_model: Provider and model string or shortcut (e.g., "4o-mini", "sonnet", "openai/gpt-4o-mini")
transcript_sample: Sample of transcript text
detected_labels: List of detected speaker labels (e.g., ['A', 'B'])
endpoint: Optional custom endpoint URL
args: Arguments namespace (for logging)
input_json: Path to input JSON file (for loading .about.md context)
Returns:
SpeakerDetection object with suggested speaker names
Raises:
RuntimeError: If Instructor is not available
Exception: If LLM detection fails
"""
if not INSTRUCTOR_AVAILABLE:
raise RuntimeError(
"Instructor library not available. Install with: pip install instructor openai"
)
# Resolve model shortcuts to full provider/model strings
original_model = provider_model
provider_model = resolve_model_shortcut(provider_model)
if original_model != provider_model:
log_debug(args, f"Resolved shortcut '{original_model}' → '{provider_model}'")
log_debug(args, f"LLM provider: {provider_model}")
log_debug(args, f"Detected labels: {detected_labels}")
# Build prompt
prompt = f"""Analyze this conversation transcript and identify the speakers.
DETECTED SPEAKERS: {', '.join(detected_labels)}
Your task is to create a mapping of each detected speaker label to their actual name or professional role, along with contextual information to help identify them.
CRITICAL WARNING - Avoid Address Confusion:
When someone says a name in their utterance, they are usually ADDRESSING that person, NOT identifying themselves.
- "Alice, what do you think?" → Speaker is NOT Alice, they are talking TO Alice
- "Bob, I agree with you" → Speaker is NOT Bob, they are responding TO Bob
- "Thanks John for joining us" → Speaker is NOT John, they are welcoming John
Pay careful attention to WHO is being addressed vs WHO is speaking. The name mentioned is typically the listener, not the speaker.
Look for:
- Direct name mentions - but remember: the name mentioned is usually the ADDRESSEE, not the speaker
- Introductions ("I'm...", "My name is...") - these DO identify the speaker
- Self-references using third person ("Alice is happy", "Bob appreciates")
- Professional roles if names aren't mentioned (Host, Guest, Expert, Interviewer)
- Topics they discussed (AI, research, product features, etc.)
- Their role in the conversation (asking questions, explaining, presenting, etc.)
- Keywords, adjectives, or characteristics that identify them
"""
# Initialize context variables