-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstt_speechmatics_speaker_mapper.py
More file actions
executable file
·1633 lines (1332 loc) · 54.1 KB
/
stt_speechmatics_speaker_mapper.py
File metadata and controls
executable file
·1633 lines (1332 loc) · 54.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
#!/usr/bin/env -S uv run
# /// script
# dependencies = [
# "instructor>=1.0.0",
# "pydantic>=2.0.0",
# "openai>=1.0.0",
# ]
# requires-python = ">=3.11"
# ///
"""
Speechmatics Speaker Name Mapper
Post-processing tool to replace speaker labels (S1, S2, S3) with actual names
in Speechmatics 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_speechmatics_speaker_mapper.py --detect audio.speechmatics.json
# LLM-assisted interactive (AI suggestions + audio preview)
./stt_speechmatics_speaker_mapper.py --llm-interactive gpt-4o-mini audio.speechmatics.json
# Preview audio samples for a speaker
./stt_speechmatics_speaker_mapper.py --preview-speaker S1 audio.speechmatics.json
# Map via inline comma-separated names
./stt_speechmatics_speaker_mapper.py -m "Alice,Bob" audio.speechmatics.json
# Interactive mapping (manual)
./stt_speechmatics_speaker_mapper.py --interactive audio.speechmatics.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, 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',
'o1': 'openai/o1',
'o3-mini': 'openai/o3-mini',
# Anthropic Claude
'sonnet': 'anthropic/claude-sonnet-4-5',
'claude-sonnet': 'anthropic/claude-sonnet-4-5',
'opus': 'anthropic/claude-opus-4-1',
'claude-opus': 'anthropic/claude-opus-4-1',
'haiku': 'anthropic/claude-3-5-haiku',
'claude-haiku': 'anthropic/claude-3-5-haiku',
# Google Gemini
'gemini': 'google/gemini-2.5-flash',
'gemini-flash': 'google/gemini-2.5-flash',
'gemini-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',
# DeepSeek
'deepseek': 'deepseek/deepseek-v3.2-exp',
# Ollama (local deployment)
'ollama': 'ollama/llama3.2',
'smollm2': 'ollama/smollm2:1.7b',
'smollm2:1.7b': 'ollama/smollm2:1.7b',
'smollm2:360m': 'ollama/smollm2:360m',
}
def resolve_model_shortcut(model_string: str) -> str:
"""Resolve model shortcut to full provider/model string."""
if '/' in model_string:
return model_string
model_lower = model_string.lower()
return MODEL_SHORTCUTS.get(model_lower, model_string)
# ----------------------------------------------------------------------
# META Message Helper
# ----------------------------------------------------------------------
def get_meta_message(args):
"""Get META warning message for STT transcripts."""
if getattr(args, 'no_meta_message', False) or getattr(args, 'disable_meta_message', False):
return ""
if os.environ.get('STT_META_MESSAGE_DISABLE', '').lower() in ('1', 'true', 'yes'):
return ""
custom_message = os.environ.get('STT_META_MESSAGE', '').strip()
if custom_message:
return f"---\nmeta: {custom_message}\n---\n"
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
# ----------------------------------------------------------------------
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."""
if input_json.endswith('.speechmatics.json'):
base_audio = input_json[:-len('.speechmatics.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_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 = "SPEAKER.CONTEXT.md"
def find_directory_context_file(input_json: str) -> Optional[str]:
"""Find SPEAKER.CONTEXT.md in same directory or parent directories."""
if input_json.endswith('.speechmatics.json'):
base_audio = input_json[:-len('.speechmatics.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 '.'
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:
break
current = parent
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."""
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."""
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."""
path = input_json
for suffix in ['.speechmatics.mapped.json', '.speechmatics.json', '.mapped.json']:
if path.endswith(suffix):
return path[:-len(suffix)]
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.
Speechmatics format: results array with 'speaker' field on words.
We need to group consecutive words by speaker into utterances.
"""
results = json_data.get('results', [])
utterances = []
current_utterance = None
for item in results:
if item.get('type') != 'word':
continue
speaker = item.get('speaker', 'UU')
if speaker != speaker_label:
# Flush current utterance if we were tracking one
if current_utterance:
utterances.append(current_utterance)
current_utterance = None
continue
# This word is from our target speaker
start_time = item.get('start_time', 0)
end_time = item.get('end_time', 0)
content = ''
if item.get('alternatives'):
content = item['alternatives'][0].get('content', '')
if current_utterance is None:
# Start new utterance
current_utterance = {
'start': int(start_time * 1000), # Convert to ms
'end': int(end_time * 1000),
'text': content
}
else:
# Extend current utterance
current_utterance['end'] = int(end_time * 1000)
current_utterance['text'] += ' ' + content
# Flush final utterance
if current_utterance:
utterances.append(current_utterance)
return utterances
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."""
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
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
if duration_s > max_duration_per_sample:
end_ms = start_ms + int(max_duration_per_sample * 1000)
selected.append({
'start': start_ms / 1000,
'end': end_ms / 1000,
'text': utt.get('text', '')[:50]
})
if not selected:
return False, "No samples selected"
# Build ffmpeg filter_complex
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}]")
if i < len(selected) - 1 and silence_gap > 0:
silence_label = f"s{i}"
filter_parts.append(
f"anullsrc=r=44100:cl=stereo,atrim=0:{silence_gap:.2f}[{silence_label}]"
)
concat_inputs.append(f"[{silence_label}]")
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)
cmd = [
ffmpeg,
'-i', audio_file,
'-filter_complex', filter_complex,
'-map', '[out]',
'-y',
'-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."""
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
cmd = player_cmd + [filepath]
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:
result = subprocess.run(cmd, check=False)
return result.returncode == 0
except KeyboardInterrupt:
print("", file=sys.stderr)
return True
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:
"""Preview audio samples for a speaker."""
display_name = speaker_name or f"Speaker {speaker_label}"
utterances = get_speaker_utterances(json_data, speaker_label)
if not utterances:
print(f"No utterances found for {display_name}", file=sys.stderr)
return False
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)
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
with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as tmp:
tmp_path = tmp.name
try:
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)
return play_audio_file(tmp_path, player_name, player_cmd, args)
finally:
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.
For Speechmatics, speaker labels are S1, S2, S3, etc.
UU is used for unidentified speakers.
"""
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."""
if isinstance(obj, dict):
result = {}
for key, value in obj.items():
if key == "speaker" and isinstance(value, str):
result[key] = speaker_map.get(value, value)
else:
result[key] = replace_speakers_recursive(value, speaker_map)
return result
elif isinstance(obj, list):
return [replace_speakers_recursive(item, speaker_map) for item in obj]
else:
return obj
def find_transcript_segments(json_obj):
"""
Find word results in Speechmatics JSON and group by speaker.
Speechmatics uses 'results' array with individual words.
We group consecutive words by speaker to create utterance-like segments.
"""
results = json_obj.get('results', [])
if not results:
return []
segments = []
current_segment = None
for item in results:
if item.get('type') != 'word':
continue
speaker = item.get('speaker', 'UU')
content = ''
if item.get('alternatives'):
content = item['alternatives'][0].get('content', '')
if current_segment is None or current_segment.get('speaker') != speaker:
# Flush previous segment
if current_segment and current_segment.get('text'):
segments.append(current_segment)
current_segment = {
'speaker': speaker,
'text': content
}
else:
# Append to current segment
if content:
current_segment['text'] += ' ' + content
# Flush final segment
if current_segment and current_segment.get('text'):
segments.append(current_segment)
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., 'S1', 'S2', 'UU')"
)
speaker_name: str = Field(
description="Identified name or role for this speaker"
)
context: str = Field(
description="Brief contextual information about this speaker",
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."""
segments = find_transcript_segments(json_obj)
if not segments:
return ""
# Take first N segments
sample_segments = segments[:max_utterances]
# Format as readable transcript
lines = []
for seg in sample_segments:
speaker = seg.get('speaker', 'Unknown')
text = seg.get('text', '')
lines.append(f"Speaker {speaker}: {text}")
return '\n'.join(lines)
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."""
if not INSTRUCTOR_AVAILABLE:
raise RuntimeError(
"Instructor library not available. Install with: pip install instructor openai"
)
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)}
Note: Speechmatics uses S1, S2, S3, etc. for speaker labels. UU means unidentified speaker.
Your task is to create a mapping of each detected speaker label to their actual name or professional role.
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
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
- Professional roles if names aren't mentioned (Host, Guest, Expert, Interviewer)
"""
# Add context files if available
dir_context = None
about_content = None
if input_json:
dir_context, dir_context_path = get_directory_context_content(input_json)
if dir_context:
if not getattr(args, 'quiet', False):
print(f"Using directory context from: {dir_context_path}", file=sys.stderr)
prompt += f"\nDIRECTORY CONTEXT:\n{dir_context}\n"
about_content = get_about_file_content(input_json)
if about_content:
about_path = get_about_file_path(input_json)
if not getattr(args, 'quiet', False):
print(f"Using file context from: {about_path}", file=sys.stderr)
prompt += f"\nFILE-SPECIFIC CONTEXT:\n{about_content}\n"
prompt += f"""
TRANSCRIPT SAMPLE:
{transcript_sample}
You must provide a mapping for EACH detected speaker label ({', '.join(detected_labels)}) including:
1. speaker_label: The label (S1, S2, S3, etc.)
2. speaker_name: Their identified name or role (use "Unknown" if uncertain)
3. context: Brief contextual info about this speaker
"""
try:
if endpoint:
log_info(args, f"Using custom endpoint: {endpoint}")
base_client = OpenAI(base_url=endpoint, api_key="none")
client = instructor.from_openai(base_client, mode=instructor.Mode.JSON)
model = provider_model.split("/")[1] if "/" in provider_model else provider_model
else:
log_info(args, f"Using provider: {provider_model}")
client = instructor.from_provider(provider_model, mode=instructor.Mode.TOOLS)
model = provider_model.split("/")[1] if "/" in provider_model else provider_model
log_debug(args, "Calling LLM...")
result = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
response_model=SpeakerDetection,
max_retries=3
)
log_debug(args, f"LLM response - Confidence: {result.confidence}")
log_debug(args, f"LLM response - Speakers: {result.speakers}")
# Extract contexts before converting
speaker_contexts = {mapping.speaker_label: mapping.context for mapping in result.speakers}
# Convert to dict for compatibility
result.speakers = {mapping.speaker_label: mapping.speaker_name for mapping in result.speakers}
result.speaker_contexts = speaker_contexts
return result
except Exception as e:
log_error(args, f"LLM detection failed: {e}")
raise
def handle_llm_detection(args, json_data, detected_speakers):
"""Handle LLM-assisted speaker detection."""
suggestions_path = get_suggestions_file_path(args.input_json)
if args.llm_interactive and os.path.exists(suggestions_path) and not args.force:
try:
log_info(args, "Found cached suggestions file, loading...")
_, ai_suggestions, metadata = load_suggestions_from_file(suggestions_path, args)
speaker_contexts = metadata.get('speaker_contexts', {})
return prompt_interactive_with_suggestions(
detected_speakers,
ai_suggestions,
speaker_contexts,
args.input_json,
args,
json_data=json_data
)
except (FileNotFoundError, ValueError) as e:
log_warning(args, f"Failed to load suggestions file: {e}")
provider_spec = args.llm_detect or args.llm_interactive or args.llm_detect_fallback
if not provider_spec:
provider_spec = "openai/gpt-4o-mini"
log_info(args, f"No provider specified, using default: {provider_spec}")
try:
transcript_sample = extract_transcript_sample(
json_data,
max_utterances=args.llm_sample_size
)
if not transcript_sample:
raise ValueError("No transcript segments found for LLM analysis")
log_debug(args, f"Transcript sample ({len(transcript_sample)} chars)")
log_info(args, "Analyzing transcript with LLM...")
detection_result = detect_speakers_llm(
provider_spec,
transcript_sample,
list(detected_speakers),
endpoint=args.llm_endpoint,
args=args,
input_json=args.input_json
)
log_info(args, f"LLM confidence: {detection_result.confidence}")
if detection_result.reasoning:
log_info(args, f"LLM reasoning: {detection_result.reasoning}")
# Save suggestions
try:
save_suggestions_to_file(
suggestions_path,
detected_speakers,
detection_result.speakers,
detection_result,
provider_spec,
args.input_json,
args
)
except Exception as e:
log_warning(args, f"Failed to save suggestions file: {e}")
if args.llm_interactive:
speaker_contexts = getattr(detection_result, 'speaker_contexts', {})
return prompt_interactive_with_suggestions(
detected_speakers,
detection_result.speakers,
speaker_contexts,
args.input_json,
args,
json_data=json_data
)
else:
speaker_map = detection_result.speakers
for speaker, name in speaker_map.items():
if name.lower() == "unknown":
log_warning(args, f"LLM could not identify speaker {speaker}")
return speaker_map
except Exception as e:
log_error(args, f"LLM detection failed: {e}")
if args.llm_detect_fallback:
log_warning(args, "Falling back to manual interactive mode")
return prompt_interactive_mapping(detected_speakers, args)
else:
raise
def show_command_help():
"""Show available commands and placeholders."""
help_text = """
=== Interactive Commands ===
Special commands:
skip - Abort mapping (can rerun later)
help - Show this help message
play - Play entire audio file
speak - Preview audio samples for CURRENT speaker being prompted
speak S1 - Preview audio samples for speaker S1 (or any label)
about - Edit about file with context (opens $EDITOR)
!<command> - Execute shell command with placeholders
Placeholders (use in ! commands):
{audio} {a} - Original audio file
{text} {t} - Base transcript (.txt)
{json} {j} - Base JSON (.speechmatics.json)
{mapped-text} {mt} - Mapped transcript (output)
{mapped-json} {mj} - Mapped JSON (output)
Press Enter to accept AI suggestion, or type a name to override.
"""
print(help_text, file=sys.stderr)
def expand_command_placeholders(command: str, input_json: str) -> str:
"""Expand placeholders in command with actual file paths."""
import shlex
if input_json.endswith('.speechmatics.json'):
base_audio = input_json[:-len('.speechmatics.json')]
else:
base_audio = input_json
files = {
'{audio}': base_audio,
'{a}': base_audio,
'{text}': f'{base_audio}.txt',
'{t}': f'{base_audio}.txt',
'{json}': input_json,
'{j}': input_json,
'{mapped-json}': f'{base_audio}.speechmatics.mapped.json',
'{mj}': f'{base_audio}.speechmatics.mapped.json',
'{mapped-text}': f'{base_audio}.speechmatics.mapped.txt',
'{mt}': f'{base_audio}.speechmatics.mapped.txt',
'{about}': f'{base_audio}.about.md',
'{ab}': f'{base_audio}.about.md',
}
result = command
for placeholder, filepath in files.items():
if placeholder in result:
quoted = shlex.quote(filepath)
result = result.replace(placeholder, quoted)
return result
def execute_command(command: str, input_json: str, args) -> bool:
"""Execute a shell command with placeholder expansion."""
expanded = expand_command_placeholders(command, input_json)
print(f"\n→ Executing: {expanded}", file=sys.stderr)
try:
result = subprocess.run(expanded, shell=True, check=False)
if result.returncode != 0:
log_warning(args, f"Command exited with code {result.returncode}")
return False
return True
except Exception as e:
log_error(args, f"Command execution failed: {e}")
return False
def prompt_interactive_with_suggestions(
detected_speakers: set,
ai_suggestions: dict,
speaker_contexts: dict,
input_json: str,
args,
json_data: dict = None
) -> dict:
"""Interactive prompts with AI suggestions as defaults."""
audio_file = get_audio_file_path(input_json)
# Show all AI-detected mappings upfront
print("\n=== AI-Detected Speaker Mappings ===", file=sys.stderr)
for speaker in sorted(detected_speakers):
suggestion = ai_suggestions.get(speaker, "Unknown")
context = speaker_contexts.get(speaker, "")
if context:
print(f"{speaker} => {suggestion} # {context}", file=sys.stderr)
else:
print(f"{speaker} => {suggestion}", file=sys.stderr)
print("\n=== Review and Confirm ===", file=sys.stderr)
print(" Enter=accept | name=override | skip=abort | speak=hear speaker | help=commands", file=sys.stderr)
print("", file=sys.stderr)
speaker_map = {}
for speaker in sorted(detected_speakers):
suggestion = ai_suggestions.get(speaker, "Unknown")
prompt_text = f"{speaker} => [{suggestion}]: "
while True:
try:
user_input = input(prompt_text).strip()
except (EOFError, KeyboardInterrupt):
print("\n\nInterrupted - skipping speaker mapping.", file=sys.stderr)
return None
if user_input.lower() == 'skip':
print("\nSkipping speaker mapping - no files will be created.", file=sys.stderr)
return None
elif user_input.lower() == 'help':
show_command_help()
continue
elif user_input.lower() == 'play':
try:
execute_command('play {audio}', input_json, args)
except KeyboardInterrupt:
print("", file=sys.stderr)
continue
elif user_input.lower().startswith('speak'):
if json_data is None:
print("ERROR: Audio preview not available", file=sys.stderr)
continue
parts = user_input.split(None, 1)
if len(parts) > 1:
target_speaker = parts[1].strip()
if target_speaker not in detected_speakers:
print(f"Unknown speaker: {target_speaker}", file=sys.stderr)
print(f"Available: {', '.join(sorted(detected_speakers))}", file=sys.stderr)
continue
else:
target_speaker = speaker
target_name = ai_suggestions.get(target_speaker, f"Speaker {target_speaker}")
try: