-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostprocess_audiov4.py
More file actions
1806 lines (1643 loc) · 75.1 KB
/
Copy pathpostprocess_audiov4.py
File metadata and controls
1806 lines (1643 loc) · 75.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 python3
from auto_ingest_config import get_fileserver_path
# -*- coding: utf-8 -*-
"""
Ingest transcripts (dashcam/bodycam/audio) into Neo4j with:
- Best-model transcript selection (prefers <model>_transcription.txt JSON)
- Robust CSV fallback
- GLiNER entity extraction (uses existing sidecars if present; else runs GLiNER)
- Subject taxonomy & classification (embeddings + regex blend)
- Speaker/utterance graph wiring when RTTM is present
- Confusion matrices (segment/utterance subjects) written to CSV + logged
- Vector indexes (Neo4j 5.11+) for Segment/Utterance/Transcription embeddings
- Sidecars for all processed data (segments, utterances, speakers, entities, subjects, edges, summary, narrative)
Usage
-----
# Ingest everything with info logs, read taxonomy, write confmats & sidecars:
./.venv/bin/python3 ingest_transcripts.py \
--taxonomy /path/to/taxonomy.yml \
--confmat-out get_fileserver_path("audio/_reports") \
--sidecar-pretty --narrative --log-level INFO
# Dry run (no writes), show decisions
./.venv/bin/python3 ingest_transcripts.py --dry-run --log-level INFO
# Force re-ingest even if graph looks complete
./.venv/bin/python3 ingest_transcripts.py --force
# Limit to 50 keys
./.venv/bin/python3 ingest_transcripts.py --limit 50
"""
import os, re, uuid, csv, json, time, hashlib, logging, math, itertools, copy
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
import numpy as np
import torch
from transformers import AutoTokenizer, AutoModel
from neo4j import GraphDatabase
from neo4j.exceptions import Neo4jError
try:
from zoneinfo import ZoneInfo # py>=3.9
except Exception:
ZoneInfo = None
# Optional YAML taxonomy
try:
import yaml # pip install pyyaml
HAVE_YAML = True
except Exception:
HAVE_YAML = False
# =========================
# Config
# =========================
LOG_LEVEL_DEFAULT = os.getenv("LOG_LEVEL", "INFO").upper()
logging.basicConfig(level=getattr(logging, LOG_LEVEL_DEFAULT, logging.INFO),
format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("ingest_transcripts")
# Stage EMA alpha
EMA_ALPHA = float(os.getenv("EMA_ALPHA", "0.2"))
# Default scan roots (env override: SCAN_ROOTS="a,b,c")
DEFAULT_SCAN_ROOTS = [
get_fileserver_path("dashcam/audio"),
get_fileserver_path("dashcam/transcriptions"),
get_fileserver_path("audio"),
get_fileserver_path("audio/transcriptions"),
get_fileserver_path("bodycam"),
]
SCAN_ROOTS = [p.strip() for p in os.getenv("SCAN_ROOTS", ",".join(DEFAULT_SCAN_ROOTS)).split(",") if p.strip()]
# Local timezone used to interpret file keys, then converted to UTC
LOCAL_TZ = os.getenv("LOCAL_TZ", "America/New_York")
# Embedding model
EMBED_MODEL_NAME = os.getenv("EMBED_MODEL_NAME", "sentence-transformers/all-MiniLM-L6-v2") # 384 dims
EMBED_DIM = int(os.getenv("EMBED_DIM", "384"))
# Neo4j
NEO4J_URI = os.getenv("NEO4J_URI", "bolt://localhost:7687")
NEO4J_USER = os.getenv("NEO4J_USER", "neo4j")
NEO4J_PASSWORD = os.getenv("NEO4J_PASSWORD", "livelongandprosper")
NEO4J_DB = os.getenv("NEO4J_DB", "neo4j")
NEO4J_ENABLED = bool(NEO4J_URI and NEO4J_USER and NEO4J_PASSWORD)
# Defaults
DEFAULT_BATCH_SIZE = int(os.getenv("EMBED_BATCH", "32"))
# Filenames and patterns (JSON lives in <model>_transcription.txt per new pipeline)
AUDIO_BASE = Path(get_fileserver_path("audio"))
PAT_TRANS_JSON_TXT = re.compile(r"_([A-Za-z0-9\-\._]+)_transcription\.txt$", re.IGNORECASE)
PAT_TRANS_CSV = re.compile(r"_transcription\.csv$", re.IGNORECASE)
PAT_ENTITIES = re.compile(r"_transcription_(entites|entities)\.csv$", re.IGNORECASE)
PAT_RTTM = re.compile(r"_speakers\.rttm$", re.IGNORECASE)
PAT_MEDIA = re.compile(r"\.(wav|mp3|m4a|flac|mp4|mov|mkv)$", re.IGNORECASE)
PAT_SUBJECTS_SIDECAR = re.compile(r"_transcription_subjects\.json$", re.IGNORECASE)
# Model quality preference (left = best). You can override via env MODEL_PREF (comma-separated).
DEFAULT_MODEL_PREF = [
"large-v3", "large-v2", "large", "turbo",
"medium.en", "medium",
"small.en", "small", "base.en", "base", "tiny.en", "tiny",
"faster-whisper:large-v3", "faster-whisper:large-v2", "faster-whisper:large",
"faster-whisper:medium", "faster-whisper:small", "faster-whisper:base", "faster-whisper:tiny",
]
MODEL_PREF = [s.strip() for s in os.getenv("MODEL_PREF", ",".join(DEFAULT_MODEL_PREF)).split(",") if s.strip()]
# ========= Subject taxonomy defaults (overridable via --taxonomy) =========
SUBJECT_LABELS: List[str] = [
"Driving", "PhoneCall", "Errand", "Meeting", "Work", "Travel", "Music",
"Vehicle", "Finance", "Insurance", "Health", "Shopping", "DevOps",
"Models", "Data", "Legal", "Personal", "Planning", "Family",
]
SUBJECT_REGEX: Dict[str, re.Pattern] = {
"Driving": re.compile(r"\b(exit|merge|turn|traffic|speed|mile|highway|lane|gps|intersection)\b", re.I),
"PhoneCall": re.compile(r"\b(call|dial|voicemail|ring|phone|speakerphone)\b", re.I),
"Errand": re.compile(r"\b(store|checkout|grocery|receipt|errand|pharmacy|pickup|drop[- ]off)\b", re.I),
"Meeting": re.compile(r"\b(meeting|agenda|minutes|action items|follow[- ]up|notes)\b", re.I),
"Work": re.compile(r"\b(project|deadline|ticket|deploy|git|kubernetes|model|dataset|pipeline)\b", re.I),
"Travel": re.compile(r"\b(flight|hotel|booking|reservation|check[- ]in|boarding|gate|airbnb)\b", re.I),
"Music": re.compile(r"\b(song|music|album|playlist|spotify|sirius|radio)\b", re.I),
"Vehicle": re.compile(r"\b(oil|tire|engine|battery|charge|maintenance|diagnostic|sensor)\b", re.I),
"Finance": re.compile(r"\b(invoice|payment|balance|account|transfer|bank|budget|expense)\b", re.I),
"Insurance": re.compile(r"\b(policy|claim|deductible|coverage|premium|copay)\b", re.I),
"Health": re.compile(r"\b(appointment|doctor|prescription|pharmacy|clinic|therap\w+)\b", re.I),
"Shopping": re.compile(r"\b(cart|checkout|order|price|discount|coupon)\b", re.I),
"DevOps": re.compile(r"\b(kubernetes|helm|ingress|pod|deployment|cluster|ci/cd|terraform)\b", re.I),
"Models": re.compile(r"\b(model|weights|embeddings|llm|quantization|checkpoint|safetensors)\b", re.I),
"Data": re.compile(r"\b(dataset|csv|sqlite|neo4j|index|query|etl|ingest)\b", re.I),
"Legal": re.compile(r"\b(nda|contract|agreement|terms|liability|warranty|compliance)\b", re.I),
"Personal": re.compile(r"\b(birthday|anniversary|family|friend|party|gift)\b", re.I),
"Planning": re.compile(r"\b(plan|schedule|timeline|milestone|roadmap|todo|task)\b", re.I),
"Family": re.compile(r"\b(mom|dad|sister|brother|kids|child|family)\b", re.I),
}
SUBJECT_SYNONYMS: Dict[str, List[str]] = {}
SUBJECT_PROMPTS: Dict[str, str] = {}
# subject scoring weights/thresholds (can be overridden by taxonomy)
SUBJ_W_EMB = float(os.getenv("SUBJ_W_EMB", "0.72")) # embedding similarity weight
SUBJ_W_RX = float(os.getenv("SUBJ_W_RX", "0.28")) # regex hit weight
SUBJ_THRESHOLD_TRANSCRIPTION = float(os.getenv("SUBJ_THRESHOLD_T", "0.25"))
SUBJ_THRESHOLD_SEGMENT = float(os.getenv("SUBJ_THRESHOLD_S", "0.30"))
SUBJ_THRESHOLD_UTTERANCE = float(os.getenv("SUBJ_THRESHOLD_U", "0.30"))
# =========================
# Stage timing helpers
# =========================
class StageStats:
def __init__(self, name: str, alpha: float = 0.2):
self.name = name
self.alpha = alpha
self.count = 0
self.total = 0.0
self.ema = None # type: Optional[float]
def update(self, dt: float):
self.count += 1
self.total += dt
self.ema = dt if self.ema is None else self.alpha * dt + (1 - self.alpha) * self.ema
@property
def avg(self) -> float:
return (self.total / self.count) if self.count else 0.0
def summary(self) -> str:
ema = f"{self.ema:.2f}s" if self.ema is not None else "n/a"
avg = f"{self.avg:.2f}s"
return f"{self.name}: n={self.count}, avg={avg}, ema={ema}, total={self.total:.2f}s"
class TimedStage:
def __init__(self, stats: StageStats, detail: str = ""):
self.stats = stats
self.detail = detail
self.start = 0.0
self.dt = 0.0
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, exc_type, exc, tb):
self.dt = time.perf_counter() - self.start
if exc is None:
self.stats.update(self.dt)
log.info(f"[stage:{self.stats.name}] {self.dt:.2f}s | {self.stats.summary()} | {self.detail}")
else:
log.error(f"[stage:{self.stats.name}] FAILED after {self.dt:.2f}s | {self.detail}")
return False
st_discover = StageStats("discover", EMA_ALPHA)
st_load = StageStats("load", EMA_ALPHA)
st_validate = StageStats("validate", EMA_ALPHA)
st_embed = StageStats("embed", EMA_ALPHA)
st_ingest = StageStats("ingest", EMA_ALPHA)
GLOBAL_START = time.perf_counter()
# =========================
# Models (loaded once)
# =========================
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
if DEVICE == "cuda":
try:
torch.backends.cuda.matmul.allow_tf32 = True
except Exception:
pass
log.info(f"Loading embedding model on {DEVICE}…")
emb_tokenizer = AutoTokenizer.from_pretrained(EMBED_MODEL_NAME)
emb_model = AutoModel.from_pretrained(EMBED_MODEL_NAME).to(DEVICE).eval()
# Lazy: only load GLiNER if we actually need it
entity_recognition_classifier = None
# =========================
# Utilities (hash/id/embeddings)
# =========================
def stable_id(*parts: str) -> str:
h = hashlib.md5()
for p in parts:
h.update((p or "").encode("utf-8", errors="ignore"))
h.update(b"|")
return h.hexdigest()
def normalize(v: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.normalize(v, p=2, dim=1)
def mean_pooling(last_hidden_state: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
mask = attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()
masked = last_hidden_state * mask
summed = torch.sum(masked, dim=1)
counts = torch.clamp(mask.sum(dim=1), min=1e-9)
return summed / counts
def embed_texts(texts: List[str], batch_size: int, max_length: int = 512) -> List[List[float]]:
if not texts:
return []
vectors = []
with torch.no_grad():
for i in range(0, len(texts), batch_size):
batch = texts[i:i+batch_size]
enc = emb_tokenizer(batch, return_tensors="pt", padding=True, truncation=True, max_length=max_length)
enc = {k: v.to(DEVICE) for k,v in enc.items()}
out = emb_model(**enc)
pooled = mean_pooling(out.last_hidden_state, enc["attention_mask"])
pooled = normalize(pooled)
vectors.extend(pooled.cpu().numpy().tolist())
return vectors
def embed_long_text_via_segments(segments: List[str], batch_size: int) -> List[float]:
if not segments:
return [0.0] * EMBED_DIM
seg_vecs = embed_texts(segments, batch_size=batch_size)
arr = np.array(seg_vecs, dtype=np.float32)
vec = arr.mean(axis=0)
n = np.linalg.norm(vec)
if n > 0:
vec = vec / n
return vec.tolist()
# ---------- Key / timestamp helpers ----------
def _to_localized(dt: datetime) -> datetime:
if ZoneInfo:
return dt.replace(tzinfo=ZoneInfo(LOCAL_TZ))
return dt.replace(tzinfo=timezone.utc)
def _to_utc(dt: datetime) -> datetime:
if dt.tzinfo is None:
dt = _to_localized(dt)
return dt.astimezone(timezone.utc)
def parse_key_datetime_utc_from_string(s: str) -> Optional[datetime]:
s = s.strip()
m = re.search(r"(?P<dt14>\d{14})", s)
if m:
try:
dt = datetime.strptime(m.group("dt14"), "%Y%m%d%H%M%S")
return _to_utc(_to_localized(dt))
except Exception:
pass
for pat, fmt in [
(r"(\d{4})_(\d{4})_(\d{6})", "%Y_%m%d_%H%M%S"),
(r"(\d{8})_(\d{6})", "%Y%m%d_%H%M%S"),
(r"(\d{8})(\d{6})", "%Y%m%d%H%M%S"),
(r"(\d{4})-(\d{2})-(\d{2})[_\-](\d{2})-(\d{2})-(\d{2})", "%Y-%m-%d_%H-%M-%S"),
(r"(\d{4})_(\d{2})_(\d{2})[_\-](\d{2})_(\d{2})_(\d{2})", "%Y_%m_%d_%H_%M_%S"),
]:
m2 = re.search(pat, s)
if m2:
try:
dt = datetime.strptime(m2.group(0), fmt)
return _to_utc(_to_localized(dt))
except Exception:
pass
m = re.search(r"/(?P<Y>\d{4})/(?P<M>\d{2})/(?P<D>\d{2})/", s)
if m:
Y, M, D = m.group("Y"), m.group("M"), m.group("D")
m2 = re.search(r"(?<!\d)(\d{6})(?!\d)", os.path.basename(s))
if m2:
hhmmss = m2.group(1)
try:
dt = datetime.strptime(f"{Y}{M}{D}{hhmmss}", "%Y%m%d%H%M%S")
return _to_utc(_to_localized(dt))
except Exception:
pass
return None
def canonicalize_key(name_without_suffix: str, full_path: str) -> str:
dt = parse_key_datetime_utc_from_string(name_without_suffix) or parse_key_datetime_utc_from_string(full_path)
if dt:
return dt.astimezone(timezone.utc).strftime("%Y_%m%d_%H%M%S")
base = re.sub(r"[^\w\-]+", "_", name_without_suffix).strip("_")
return base or stable_id(full_path)
def file_key_from_name(name: str) -> str:
base = os.path.basename(name)
base = re.sub(r"\.(json|txt|csv|rttm)$", "", base, flags=re.IGNORECASE)
base = re.sub(r"_([A-Za-z0-9\-\._]+)_transcription(_(entites|entities))?$", "", base, flags=re.IGNORECASE)
base = re.sub(r"_transcription(_(entites|entities))?$", "", base, flags=re.IGNORECASE)
base = re.sub(r"_speakers$", "", base, flags=re.IGNORECASE)
base = re.sub(r"_transcription_subjects$", "", base, flags=re.IGNORECASE)
return base
def iso(dt: Optional[datetime]) -> Optional[str]:
return dt.astimezone(timezone.utc).isoformat() if dt else None
def _parse_any_iso_or_epoch(v: Any) -> Optional[datetime]:
if v is None:
return None
try:
if isinstance(v, (int, float)):
val = int(v)
if val > 1e12:
val = int(val / 1000)
return datetime.fromtimestamp(val, tz=timezone.utc)
s = str(v).strip()
if re.fullmatch(r"\d{10,13}", s):
val = int(s)
if val > 1e12:
val = int(val / 1000)
return datetime.fromtimestamp(val, tz=timezone.utc)
return _to_utc(datetime.fromisoformat(s.replace("Z", "+00:00")))
except Exception:
return None
# =========================
# Loaders
# =========================
def load_transcription_json_txt(path: str) -> Optional[Dict[str, Any]]:
with TimedStage(st_load, detail=f"json_txt={path}"):
try:
with open(path, "r", encoding="utf-8") as f:
raw = f.read()
data = json.loads(raw)
text = (data.get("text") or data.get("transcript") or "").strip()
segments = data.get("segments") or []
candidates = [
data.get("started_at"), data.get("start_time"), data.get("start"),
(data.get("metadata") or {}).get("started_at"),
]
enders = [
data.get("ended_at"), data.get("end_time"), data.get("end"),
(data.get("metadata") or {}).get("ended_at"),
]
file_started_at = None
for c in candidates:
file_started_at = _parse_any_iso_or_epoch(c)
if file_started_at: break
file_ended_at = None
for e in enders:
file_ended_at = _parse_any_iso_or_epoch(e)
if file_ended_at: break
return {"text": text, "segments": segments, "language": data.get("language"),
"file_started_at": file_started_at, "file_ended_at": file_ended_at}
except json.JSONDecodeError as ex:
log.warning(f"JSON parse error (expected JSON in {path}): {ex}")
return None
except Exception as ex:
log.warning(f"Failed to parse JSON TXT {path}: {ex}")
return None
def load_transcription_csv(path: str) -> Optional[Dict[str, Any]]:
with TimedStage(st_load, detail=f"csv={path}"):
try:
segments, full_text = [], []
file_start_abs: Optional[datetime] = None
file_end_abs: Optional[datetime] = None
with open(path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row_idx, row in enumerate(reader):
def ffloat(k: str, default: float = 0.0) -> float:
try: return float(row.get(k, default) or default)
except Exception: return default
text = (row.get("Text") or row.get("text") or "").strip()
start = ffloat("StartTime", ffloat("start", 0.0))
end = ffloat("EndTime", ffloat("end", start))
abs_start = None
abs_end = None
for k in ("AbsoluteStart","AbsStart","absolute_start","StartISO","start_iso","StartEpochMillis","start_epoch_ms"):
if row.get(k):
abs_start = _parse_any_iso_or_epoch(row.get(k)); break
for k in ("AbsoluteEnd","AbsEnd","absolute_end","EndISO","end_iso","EndEpochMillis","end_epoch_ms"):
if row.get(k):
abs_end = _parse_any_iso_or_epoch(row.get(k)); break
seg = {
"id": row.get("SegmentId") or row.get("id") or stable_id(path, "seg", str(row_idx), text[:64]),
"seek": None,
"start": start,
"end": end,
"text": text,
"tokens": [],
"words": [],
"abs_start": iso(abs_start) if abs_start else None,
"abs_end": iso(abs_end) if abs_end else None,
}
segments.append(seg)
if text: full_text.append(text)
if abs_start:
file_start_abs = min(file_start_abs, abs_start) if file_start_abs else abs_start
if abs_end:
file_end_abs = max(file_end_abs, abs_end) if file_end_abs else abs_end
return {
"text": " ".join(full_text),
"segments": segments,
"language": "en",
"file_started_at": file_start_abs,
"file_ended_at": file_end_abs
}
except Exception as ex:
log.warning(f"Failed to parse CSV transcript {path}: {ex}")
return None
def load_entities_csv(path: str) -> List[Dict[str, Any]]:
ents = []
try:
with open(path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
def ffloat(k: str, default: float = 0.0) -> float:
try: return float(row.get(k, default) or default)
except Exception: return default
ents.append({
"text": (row.get("text") or row.get("Text") or "").strip(),
"label": (row.get("label") or row.get("Label") or "").strip(),
"score": ffloat("score", ffloat("Score", 0.0)),
"start": ffloat("start", ffloat("StartTime", 0.0)),
"end": ffloat("end", ffloat("EndTime", 0.0)),
})
except Exception as ex:
log.warning(f"Failed to parse entities CSV {path}: {ex}")
return ents
def load_subjects_sidecar(path: str) -> List[Dict[str, Any]]:
try:
with open(path, "r", encoding="utf-8") as f:
j = json.load(f)
ents = j.get("entities") or []
if isinstance(ents, list):
out = []
for e in ents:
out.append({
"id": e.get("id") or stable_id(path, e.get("text",""), e.get("label","")),
"text": e.get("text",""),
"label": e.get("label",""),
"count": int(e.get("count") or 0),
"starts": e.get("starts") or [],
"ends": e.get("ends") or [],
"avg_score": float(e.get("avg_score") or 0.0),
})
return out
except Exception as ex:
log.warning(f"Failed to parse subjects sidecar {path}: {ex}")
return []
def load_rttm(path: str) -> List[Tuple[float,float,str]]:
intervals = []
try:
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"): continue
parts = line.split()
if len(parts) < 9: continue
try:
start = float(parts[3]); dur = float(parts[4]); end = start + dur
spk = parts[7]
intervals.append((start, end, spk))
except Exception:
continue
intervals.sort(key=lambda x: x[0])
except Exception as ex:
log.warning(f"Failed to read RTTM {path}: {ex}")
return intervals
# =========================
# Model/version selection
# =========================
def extract_model_tag_from_json_txt(p: str) -> str:
m = PAT_TRANS_JSON_TXT.search(os.path.basename(p))
return m.group(1) if m else ""
def model_rank(tag: str) -> int:
if not tag: return 10_000
t = tag.lower()
try:
return MODEL_PREF.index(t)
except ValueError:
if "large" in t: return 100
if "medium" in t: return 200
if "small" in t: return 300
if "base" in t: return 400
if "tiny" in t: return 500
return 9999
def is_in_audio_base(p: str) -> bool:
try:
return str(Path(p).resolve()).startswith(str(AUDIO_BASE.resolve()))
except Exception:
return False
def select_best_json(json_paths: List[str], csv_paths: List[str]) -> Optional[str]:
if not json_paths:
return None
scored: List[Tuple[int,int,float,float,str]] = []
for p in json_paths:
tag = extract_model_tag_from_json_txt(p)
rank = model_rank(tag)
segs = -1.0
try:
with open(p, "r", encoding="utf-8") as f:
j = json.load(f)
segs = float(len(j.get("segments") or []))
except Exception:
segs = -1.0
mtime = 0.0
try:
mtime = Path(p).stat().st_mtime
except Exception:
pass
scored.append((0 if is_in_audio_base(p) else 1, rank, -segs, -mtime, p))
scored.sort()
best = scored[0][-1] if scored else None
if best:
log.info(f"[select] best JSON = {best}")
else:
log.warning("[select] no JSON candidate could be selected")
return best
# =========================
# Entity aggregation / fallback
# =========================
def gliner_extract(text: str) -> List[Dict[str, Any]]:
global entity_recognition_classifier
try:
if entity_recognition_classifier is None:
from gliner import GLiNER
log.info("Loading GLiNER (fallback only)…")
entity_recognition_classifier = GLiNER.from_pretrained("urchade/gliner_large-v2", device=DEVICE)
ents = entity_recognition_classifier.predict_entities(
text, ["Person","Place","Event","Date","Subject","Organization","Product","Location"]
)
return [{
"text": e.get("text",""),
"label": e.get("label",""),
"score": float(e.get("score", 0.0) or 0.0),
"start": float(e.get("start", -1) or -1),
"end": float(e.get("end", -1) or -1),
} for e in ents]
except Exception as ex:
log.warning(f"GLiNER fallback failed: {ex}")
return []
def aggregate_entities(ents: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
bucket: Dict[Tuple[str,str], Dict[str, Any]] = {}
for e in ents:
key = (e.get("text","").strip(), e.get("label","").strip())
if not key[0]:
continue
b = bucket.setdefault(key, {"text": key[0], "label": key[1], "count": 0, "starts": [], "ends": [], "scores": []})
b["count"] += 1
if "start" in e and e["start"] is not None: b["starts"].append(float(e["start"]))
if "end" in e and e["end"] is not None: b["ends"].append(float(e["end"]))
if "score" in e and e["score"] is not None: b["scores"].append(float(e["score"]))
out = []
for (txt, lbl), b in bucket.items():
eid = stable_id(txt, lbl)
avg = float(np.mean(b["scores"])) if b["scores"] else 0.0
out.append({"id": eid, "text": txt, "label": lbl, "count": b["count"], "starts": b["starts"], "ends": b["ends"], "avg_score": avg})
return out
# =========================
# Validation / cleaning
# =========================
def validate_and_clean_segments(key: str, segs: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], Dict[str,int]]:
fixed = []
stats = {"nonfinite":0, "neg_dur":0, "reordered":0, "empty_txt":0, "kept":0}
last_end = -math.inf
for i, s in enumerate(segs):
try:
start = float(s.get("start", 0.0))
end = float(s.get("end", start))
if not math.isfinite(start) or not math.isfinite(end):
stats["nonfinite"] += 1
continue
if end < start:
end = start
stats["neg_dur"] += 1
txt = (s.get("text") or "").strip()
if not txt:
stats["empty_txt"] += 1
sid = s.get("id") or stable_id(key, "seg", str(i), txt[:64])
if start < last_end:
stats["reordered"] += 1
last_end = max(last_end, end)
fixed.append({
"id": sid,
"idx": s.get("idx", i),
"start": start,
"end": end,
"text": txt,
"tokens": s.get("tokens", []),
"words": s.get("words", []),
"abs_start": s.get("abs_start"),
"abs_end": s.get("abs_end"),
})
except Exception:
stats["nonfinite"] += 1
continue
stats["kept"] = len(fixed)
return fixed, stats
# =========================
# Speaker/utterance utils
# =========================
def words_from_segments(segments: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
words = []
for seg in segments:
for w in seg.get("words", []) or []:
wt = (w.get("word") or "").strip()
ws = float(w.get("start", seg.get("start", 0.0)) or seg.get("start", 0.0))
we = float(w.get("end", seg.get("end", ws)) or seg.get("end", ws))
if wt:
words.append({"text": wt, "start": ws, "end": we})
words.sort(key=lambda x: x["start"])
return words
def overlap(a_start: float, a_end: float, b_start: float, b_end: float) -> float:
return max(0.0, min(a_end, b_end) - max(a_start, b_start))
def utterances_from_rttm_with_words(rttm: List[Tuple[float,float,str]], segments: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
words = words_from_segments(segments)
if not words:
return []
utterances = []
for i, (start, end, spk) in enumerate(rttm):
mid = lambda w: (w["start"] + w["end"]) / 2.0
chunk = [w for w in words if mid(w) >= start and mid(w) <= end]
if not chunk:
continue
text = " ".join(w["text"] for w in chunk).strip()
u_start = chunk[0]["start"]
u_end = chunk[-1]["end"]
u_id = stable_id("utt", spk, f"{u_start:.3f}", f"{u_end:.3f}")
utterances.append({
"id": u_id,
"speaker_label": spk,
"start": u_start,
"end": u_end,
"text": text,
"segment_id": None,
"idx": i
})
return utterances
def utterances_from_rttm_dominant_segment(rttm: List[Tuple[float,float,str]], segments: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
utterances = []
for i, seg in enumerate(segments):
s_start = float(seg.get("start", 0.0) or 0.0)
s_end = float(seg.get("end", s_start) or s_start)
best_overlap = 0.0
best_spk = None
for (a, b, spk) in rttm:
ov = overlap(s_start, s_end, a, b)
if ov > best_overlap:
best_overlap = ov
best_spk = spk
spk_label = best_spk or "UNKNOWN"
u_id = stable_id("utt", spk_label, str(seg.get("id")), f"{s_start:.3f}", f"{s_end:.3f}")
utterances.append({
"id": u_id,
"speaker_label": spk_label,
"start": s_start,
"end": s_end,
"text": seg.get("text", ""),
"segment_id": seg.get("id"),
"idx": i
})
return utterances
def _sum_overlap(seg_start: float, seg_end: float, rttm: List[Tuple[float,float,str]]) -> Dict[str, float]:
totals: Dict[str, float] = {}
for a,b,spk in rttm:
ov = overlap(seg_start, seg_end, a, b)
if ov > 0:
totals[spk] = totals.get(spk, 0.0) + ov
return totals
def compute_segment_speaker_overlaps(
rttm: List[Tuple[float,float,str]],
segments: List[Dict[str, Any]],
speaker_map: Dict[str, Dict[str,str]],
min_proportion: float = 0.05
) -> Tuple[Dict[str, Dict[str, Any]], List[Dict[str, Any]]]:
seg_best: Dict[str, Dict[str, Any]] = {}
seg_edges: List[Dict[str, Any]] = []
for s in segments:
s_start = float(s.get("start", 0.0) or 0.0)
s_end = float(s.get("end", s_start) or s_start)
sid = s["id"]
totals = _sum_overlap(s_start, s_end, rttm)
total_ov = sum(totals.values()) or 0.0
best_lbl = max(totals.items(), key=lambda kv: kv[1])[0] if totals else "UNKNOWN"
sp = speaker_map.get(best_lbl)
best_id = sp["id"] if sp else speaker_map.get("UNKNOWN", {}).get("id")
seg_best[sid] = {"speaker_label": best_lbl, "speaker_id": best_id}
if total_ov > 0.0:
for lbl, ov in totals.items():
prop = ov / total_ov
if prop >= min_proportion:
spx = speaker_map.get(lbl)
spx_id = spx["id"] if spx else speaker_map.get("UNKNOWN", {}).get("id")
seg_edges.append({"segment_id": sid, "speaker_id": spx_id, "label": lbl, "overlap": float(ov), "proportion": float(prop)})
return seg_best, seg_edges
# =========================
# Taxonomy loader & confusion matrix
# =========================
def _load_json_or_yaml(path: str) -> Dict[str, Any]:
with open(path, "r", encoding="utf-8") as f:
if path.lower().endswith((".yml", ".yaml")):
if not HAVE_YAML:
raise RuntimeError("PyYAML not installed; use JSON or `pip install pyyaml`.")
return yaml.safe_load(f)
return json.load(f)
def _compile_patterns(patterns: List[str]) -> re.Pattern:
if not patterns:
return re.compile(r"$^", re.I)
joined = "|".join(f"(?:{p})" for p in patterns)
return re.compile(joined, re.I)
def apply_taxonomy(tax: Dict[str, Any]) -> None:
global SUBJECT_LABELS, SUBJECT_REGEX, SUBJECT_SYNONYMS
global SUBJ_W_EMB, SUBJ_W_RX
global SUBJ_THRESHOLD_TRANSCRIPTION, SUBJ_THRESHOLD_SEGMENT, SUBJ_THRESHOLD_UTTERANCE
settings = (tax.get("settings") or {})
weights = (settings.get("weights") or {})
th = (settings.get("thresholds") or {})
SUBJ_W_EMB = float(weights.get("emb", SUBJ_W_EMB))
SUBJ_W_RX = float(weights.get("rx", SUBJ_W_RX))
SUBJ_THRESHOLD_TRANSCRIPTION = float(th.get("transcription", SUBJ_THRESHOLD_TRANSCRIPTION))
SUBJ_THRESHOLD_SEGMENT = float(th.get("segment", SUBJ_THRESHOLD_SEGMENT))
SUBJ_THRESHOLD_UTTERANCE = float(th.get("utterance", SUBJ_THRESHOLD_UTTERANCE))
subjects = tax.get("subjects") or []
labels: List[str] = []
regex_map: Dict[str, re.Pattern] = {}
synonyms_map: Dict[str, List[str]] = {}
for item in subjects:
lbl = str(item.get("label") or "").strip()
if not lbl:
continue
labels.append(lbl)
pats = item.get("patterns") or []
regex_map[lbl] = _compile_patterns(pats) if pats else re.compile(r"$^", re.I)
syns = item.get("synonyms") or []
synonyms_map[lbl] = [str(s).strip() for s in syns if str(s).strip()]
if labels:
SUBJECT_LABELS = labels
for k in list(SUBJECT_REGEX.keys()):
if k not in labels:
SUBJECT_REGEX.pop(k, None)
for lbl in labels:
SUBJECT_REGEX[lbl] = regex_map.get(lbl, SUBJECT_REGEX.get(lbl, re.compile(r"$^", re.I)))
SUBJECT_SYNONYMS = synonyms_map
log.info(
"[taxonomy] Loaded: labels=%s | weights={emb=%.2f, rx=%.2f} | thresholds={T=%.2f,S=%.2f,U=%.2f}",
",".join(SUBJECT_LABELS), SUBJ_W_EMB, SUBJ_W_RX,
SUBJ_THRESHOLD_TRANSCRIPTION, SUBJ_THRESHOLD_SEGMENT, SUBJ_THRESHOLD_UTTERANCE
)
class ConfusionMatrix:
def __init__(self, labels: List[str], name: str):
self.labels = labels
self.index = {lbl: i for i, lbl in enumerate(labels)}
n = len(labels)
self.mat = np.zeros((n, n), dtype=np.int64)
self.name = name
def update_from_lists(self, label_lists: List[List[str]]):
for labels in label_lists:
uniq = sorted(set(l for l in labels if l in self.index))
for a, b in itertools.combinations_with_replacement(uniq, 2):
i = self.index[a]; j = self.index[b]
self.mat[i, j] += 1
if i != j:
self.mat[j, i] += 1
def to_csv(self, out_path: str):
Path(out_path).parent.mkdir(parents=True, exist_ok=True)
with open(out_path, "w", encoding="utf-8", newline="") as f:
w = csv.writer(f)
w.writerow([""] + self.labels)
for i, lbl in enumerate(self.labels):
row = [lbl] + [int(x) for x in self.mat[i].tolist()]
w.writerow(row)
def log_top_pairs(self, top_k: int = 15):
pairs = []
n = len(self.labels)
for i in range(n):
for j in range(i, n):
c = int(self.mat[i, j])
if c > 0:
pairs.append((c, self.labels[i], self.labels[j]))
pairs.sort(reverse=True)
head = pairs[:top_k]
pretty = ", ".join([f"{a}&{b}:{c}" for (c, a, b) in head])
log.info("[confmat:%s] top co-occurrences: %s", self.name, pretty or "(none)")
# =========================
# Subject classification helpers
# =========================
_subject_label_vecs: Optional[List[List[float]]] = None
def _ensure_subject_label_vecs(batch_size: int) -> List[List[float]]:
global _subject_label_vecs
if _subject_label_vecs is not None:
return _subject_label_vecs
prompts = []
for lbl in SUBJECT_LABELS:
syns = SUBJECT_SYNONYMS.get(lbl, [])
prompt = f"Topic: {lbl}. Synonyms: {', '.join(syns)}." if syns else f"Topic: {lbl}."
prompts.append(prompt)
_subject_label_vecs = embed_texts(prompts, batch_size=batch_size)
return _subject_label_vecs
def _cosine(a: List[float], b: List[float]) -> float:
if not a or not b: return 0.0
av = np.array(a, dtype=np.float32); bv = np.array(b, dtype=np.float32)
na = np.linalg.norm(av); nb = np.linalg.norm(bv)
if na == 0 or nb == 0: return 0.0
return float(np.dot(av, bv) / (na * nb))
def classify_subjects_for_text(
unit_text: str,
unit_vec: List[float],
batch_size: int,
threshold: float
) -> List[Tuple[str, float]]:
label_vecs = _ensure_subject_label_vecs(batch_size)
results: List[Tuple[str, float]] = []
for i, lbl in enumerate(SUBJECT_LABELS):
sim = _cosine(unit_vec, label_vecs[i])
rx_hit = 1.0 if SUBJECT_REGEX.get(lbl, re.compile(r"$^")).search(unit_text or "") else 0.0
score = SUBJ_W_EMB * sim + SUBJ_W_RX * rx_hit
if score >= threshold:
results.append((lbl, score))
results.sort(key=lambda x: x[1], reverse=True)
return results
# =========================
# Neo4j plumbing
# =========================
def neo4j_driver():
if not NEO4J_ENABLED:
return None
return GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
SCHEMA_QUERIES = [
"CREATE CONSTRAINT transcription_id IF NOT EXISTS FOR (t:Transcription) REQUIRE t.id IS UNIQUE",
"CREATE CONSTRAINT segment_id IF NOT EXISTS FOR (s:Segment) REQUIRE s.id IS UNIQUE",
"CREATE CONSTRAINT entity_id IF NOT EXISTS FOR (e:Entity) REQUIRE e.id IS UNIQUE",
"CREATE CONSTRAINT utterance_id IF NOT EXISTS FOR (u:Utterance) REQUIRE u.id IS UNIQUE",
"CREATE CONSTRAINT speaker_id IF NOT EXISTS FOR (sp:Speaker) REQUIRE sp.id IS UNIQUE",
"CREATE CONSTRAINT subject_id IF NOT EXISTS FOR (sb:Subject) REQUIRE sb.id IS UNIQUE",
"CREATE INDEX transcription_key IF NOT EXISTS FOR (t:Transcription) ON (t.key)",
"CREATE INDEX frame_key IF NOT EXISTS FOR (f:Frame) ON (f.key)",
]
def _create_vector_index(sess, label: str, prop: str, name: str, dim: int):
q = f"""
CREATE VECTOR INDEX {name} IF NOT EXISTS
FOR (n:{label}) ON (n.{prop})
OPTIONS {{
indexConfig: {{
`vector.dimensions`: {dim},
`vector.similarity_function`: 'cosine'
}}
}}
"""
sess.run(q)
def ensure_schema(driver):
if not driver:
log.info("Neo4j not configured; skipping schema setup.")
return
with driver.session(database=NEO4J_DB) as sess:
for q in SCHEMA_QUERIES:
sess.run(q)
try:
_create_vector_index(sess, "Segment", "embedding", "segment_embedding_index", EMBED_DIM)
_create_vector_index(sess, "Transcription", "embedding", "transcription_embedding_index", EMBED_DIM)
_create_vector_index(sess, "Utterance", "embedding", "utterance_embedding_index", EMBED_DIM)
except Neo4jError as e:
msg = str(e)
if "Invalid input 'VECTOR'" in msg or "Unrecognized command" in msg:
raise RuntimeError("This Neo4j server does not support VECTOR indexes (need 5.11+).") from e
raise
log.info("Neo4j schema ensured (constraints + vector indexes + btree indexes).")
def already_ingested(driver, t_id: str) -> bool:
if not driver:
return False
with driver.session(database=NEO4J_DB) as sess:
rec = sess.run("MATCH (t:Transcription {id:$id}) RETURN t.id AS id LIMIT 1", id=t_id).single()
return bool(rec)
def get_ingestion_status(driver, t_id: str) -> Dict[str, Any]:
if not driver:
return {"exists": False}
cy = """
OPTIONAL MATCH (t:Transcription {id:$id})
WITH t
OPTIONAL MATCH (t)-[:HAS_SEGMENT]->(s:Segment)
WITH t, count(s) AS seg_count, sum(CASE WHEN s.embedding IS NULL THEN 1 ELSE 0 END) AS seg_no_emb
OPTIONAL MATCH (t)-[:HAS_UTTERANCE]->(u:Utterance)
RETURN
t IS NOT NULL AS exists,
seg_count,
seg_no_emb,
count(u) AS utt_count,
sum(CASE WHEN u.embedding IS NULL THEN 1 ELSE 0 END) AS utt_no_emb,
t.started_at AS started_at,
t.source_json AS source_json,
t.source_csv AS source_csv,
t.source_rttm AS source_rttm,
t.source_media AS source_media
"""
with driver.session(database=NEO4J_DB) as sess:
rec = sess.run(cy, id=t_id).single()
return rec.data() if rec else {"exists": False}
def should_reingest(status: Dict[str, Any], expected_segments: int, has_rttm: bool, paths: Dict[str, Any]) -> bool:
if not status.get("exists"):
return True
for k in ("json", "csv", "rttm", "media"):
if paths.get(k) and not status.get(f"source_{k}"):
return True
if status.get("started_at") is None:
return True
seg_count = int(status.get("seg_count") or 0)
seg_no_emb = int(status.get("seg_no_emb") or 0)
utt_count = int(status.get("utt_count") or 0)
if expected_segments > 0 and seg_count == 0:
return True
if has_rttm and utt_count == 0:
return True
if seg_count > 0 and seg_no_emb > max(1, seg_count // 2):
return True
return False
def ingest_record(
driver,
t_id: str,
key: str,
started_at_iso: Optional[str],
ended_at_iso: Optional[str],
source_paths: Dict[str,str],
text: str,
transcript_emb: List[float],
segments: List[Dict[str, Any]],
entities: List[Dict[str, Any]],
utterances: List[Dict[str, Any]],
speakers: List[Dict[str, Any]],
segment_speakers: List[Dict[str, Any]],
subjectsT: List[Tuple[str,float]],