| 1 | #!/usr/bin/env python3 |
| 2 | """Apply speaker names to a session: add newly-named voices to the library and |
| 3 | re-render transcript.md — no re-transcription. |
| 4 | |
| 5 | python relabel.py <session_dir> <mapping.json> |
| 6 | |
| 7 | mapping.json maps the auto-labels to names, e.g. {"Speaker 2": "Maya"}. |
| 8 | """ |
| 9 | import json |
| 10 | import os |
| 11 | import sys |
| 12 | |
| 13 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 14 | import speaker_id as sid |
| 15 | from transcript_render import render |
| 16 | |
| 17 | session_dir, mapping_path = sys.argv[1], sys.argv[2] |
| 18 | mapping = json.load(open(mapping_path)) |
| 19 | |
| 20 | transcript = json.load(open(os.path.join(session_dir, "transcript.json"))) |
| 21 | spk_path = os.path.join(session_dir, "speakers.json") |
| 22 | speakers = json.load(open(spk_path)) if os.path.exists(spk_path) else {"speakers": []} |
| 23 | |
| 24 | # Teach the library each newly-named unknown voice. |
| 25 | for sp in speakers.get("speakers", []): |
| 26 | new = mapping.get(sp["label"]) |
| 27 | if new and new != sp["label"] and sp.get("unknown") and sp.get("centroid"): |
| 28 | sid.upsert_voice(new, sp["centroid"]) |
| 29 | |
| 30 | # Re-map labels and re-render. |
| 31 | markers = [] |
| 32 | mp = os.path.join(session_dir, "markers.json") |
| 33 | if os.path.exists(mp): |
| 34 | for mk in json.load(open(mp)).get("markers", []): |
| 35 | markers.append((float(mk.get("offsetSeconds", 0)), mk.get("text"))) |
| 36 | markers.sort(key=lambda x: x[0]) |
| 37 | |
| 38 | segments = transcript["segments"] |
| 39 | for s in segments: |
| 40 | s["label"] = mapping.get(s.get("label"), s.get("label")) |
| 41 | render(transcript.get("title", "Session"), segments, |
| 42 | [s.get("label") for s in segments], markers, |
| 43 | os.path.join(session_dir, "transcript.md")) |
| 44 | |
| 45 | json.dump(transcript, open(os.path.join(session_dir, "transcript.json"), "w")) |
| 46 | for sp in speakers.get("speakers", []): |
| 47 | sp["label"] = mapping.get(sp["label"], sp["label"]) |
| 48 | json.dump(speakers, open(spk_path, "w")) |
| 49 | print("relabeled") |