-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemantic_alignment.py
More file actions
2114 lines (1812 loc) · 87.7 KB
/
Copy pathsemantic_alignment.py
File metadata and controls
2114 lines (1812 loc) · 87.7 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
"""
Semantic Alignment Engine
Maps Whisper transcript segments → slide pages using dense RAG.
Pipeline:
1. Extract text from each slide (PDF / PPTX / DOCX)
- Includes speaker notes (PPTX) and image descriptions (OCR + Claude vision)
2. Embed slides with sentence-transformers (all-mpnet-base-v2, GPU)
3. Build a FAISS index for fast cosine-similarity lookup
4. For each transcript segment query the index (optionally with a context
window of ±CONTEXT_SEC seconds for richer matching signal)
5. Apply Viterbi temporal smoothing so slides only advance forward
6. Flag segments that don't match any slide well (off_slide)
7. Collapse consecutive equal-slide segments into a compact timeline
8. Save JSON to [course_id]/alignment/[stem].json
Usage:
# align one caption↔slide pair
python semantic_alignment.py \\
--caption 85427/captions/CS3210\\ e-Lecture\\ on\\ Processes\\ and\\ Threads.json \\
--slides 85427/materials/LectureNotes/L02-Processes-Threads.pdf
# auto-discover all unaligned pairs in a course folder
python semantic_alignment.py --course 85427
"""
from __future__ import annotations
import argparse
import io
import json
import re
import sys
from collections import defaultdict
from pathlib import Path
from typing import NamedTuple
try:
import faiss
import numpy as np
_HAS_ML = True
except ImportError as _e:
_HAS_ML = False
# numpy is needed almost everywhere — try standalone import
try:
import numpy as np
except ImportError:
np = None # type: ignore[assignment]
# Don't sys.exit here — some operations (like --suggest-matches) can
# work without faiss. The functions that need it will fail at call time.
PROJECT_DIR = Path(__file__).parent
import sys as _sys
_AUTO_NOTE_DIR = Path.home() / ".auto_note"
import os as _os
if _os.environ.get("AUTONOTE_DATA_DIR"):
DATA_DIR = Path(_os.environ["AUTONOTE_DATA_DIR"])
elif getattr(_sys, "frozen", False) or PROJECT_DIR == _AUTO_NOTE_DIR / "scripts":
DATA_DIR = _AUTO_NOTE_DIR
else:
DATA_DIR = PROJECT_DIR
# Course output directory: defaults to DATA_DIR but can be overridden by
# OUTPUT_DIR in config.json so files land in the user's chosen Output Dir.
try:
_cfg_file = DATA_DIR / "config.json"
_sa_config: dict = json.loads(_cfg_file.read_text(encoding="utf-8")) if _cfg_file.exists() else {}
except Exception:
_sa_config = {}
_out_dir = _sa_config.get("OUTPUT_DIR", "").strip()
# Default to ~/AutoNote (same as the Electron app's getOutputDir())
COURSE_DATA_DIR = Path(_out_dir) if _out_dir else Path.home() / "AutoNote"
# ── Tunable knobs ─────────────────────────────────────────────────────────────
EMBED_MODEL = "all-mpnet-base-v2" # highest-quality general sentence model
CONTEXT_SEC = 30.0 # seconds of transcript to pool per query
BATCH_SIZE = 64 # embedding batch size
# Jina Embeddings v4 multimodal model — used when aligning transcript to slide
# images directly (no slide text extraction needed). Requires the jina API key
# or the local model jinaai/jina-embeddings-v4 via sentence-transformers.
JINA_EMBED_MODEL = "jinaai/jina-embeddings-v4"
JINA_API_URL = "https://api.jina.ai/v1/embeddings"
# Google Generative Language embeddings — text-only remote API. Used for
# caption↔slide file matching when GEMINI_API_KEY (or gemini_api.txt) is set.
GOOGLE_EMBED_MODEL = "text-embedding-004"
GOOGLE_API_URL = "https://generativelanguage.googleapis.com/v1beta"
# Viterbi transition log-probabilities
STAY_LOGP = 0.0 # free to stay on the same slide
FWD_LOGP_PER = -0.02 # cost per slide advanced forward (nearly free)
BWD_LOGP_PER = -1.5 # cost per slide stepped backward
# firm — allows genuine multi-minute review sections
# (e.g. slide 63 revisited) while suppressing
# single-segment noise flips
# Temporal position prior: at time t, add a Gaussian bonus centred on the
# expected slide position (t / duration) * n_slides.
# PRIOR_SIGMA controls the width in slide units; larger = softer guide.
PRIOR_SIGMA = 8.0
# Off-slide detection: segments where the best raw cosine similarity (before
# the position prior) is below this threshold are flagged as off_slide.
OFF_SLIDE_THRESHOLD = 0.28
# Image captioning: pages / slides with fewer than this many words of text
# have their visual content described via OCR + Claude vision.
IMAGE_WORD_THRESHOLD = 20
# OpenAI vision model used for slide image description.
# gpt-4o-mini is used for cost efficiency; each call is only made once per
# slide because results are cached in {slide_file}.image_cache.json.
OPENAI_VISION_MODEL = "gpt-4o-mini"
# Sparse-slide enrichment: slides below this word count borrow text from
# content-rich neighbours before embedding.
SPARSE_THRESHOLD = 30 # words
NEIGHBOR_WORDS = 60 # how many words to borrow from each neighbour
# ── OpenAI API key helper ─────────────────────────────────────────────────────
def _get_openai_key() -> str:
import os
key = os.environ.get("OPENAI_API_KEY", "")
if not key:
key_file = DATA_DIR / "openai_api.txt"
if key_file.exists():
key = key_file.read_text().strip()
return key
# ── Image description (OCR + Claude vision) ───────────────────────────────────
_VISION_PROMPT = (
"This is a slide from a university lecture. "
"Describe ALL visible content in detail: every text label, concept name, "
"diagram element, arrow, relationship, numbered step, code snippet, and "
"technical term you can see. "
"Focus on the academic topic — mention state names, algorithm steps, "
"data structure relationships, or any specific terminology shown. "
"Write a thorough plain-text description (no markdown), 3-5 sentences."
)
class ImageDescriber:
"""
Extracts textual descriptions from slide images using:
1. pytesseract OCR — free, captures printed text in diagrams
2. Claude vision API — powerful, understands academic diagrams and
technical content (used only on slides with
< IMAGE_WORD_THRESHOLD words; results cached)
The Claude API is called at most once per slide per slide file, thanks to
the image cache written to {slide_file}.image_cache.json.
"""
def __init__(self):
self._ocr_ok = None # None = unchecked, True/False after first call
self._openai = None # openai.OpenAI client, lazy-loaded
self._api_calls = 0 # count for cost reporting
# ── lazy loaders ─────────────────────────────────────────────────────────
def _ensure_ocr(self) -> bool:
# OCR is an optional enhancement layered on top of the GPT-4o-mini
# vision pass — when both are available we concatenate verbatim text
# (OCR) with structural description (vision). When pytesseract or
# the tesseract binary isn't installed we silently fall back to
# vision-only; no warning needed.
if self._ocr_ok is None:
try:
import pytesseract
pytesseract.get_tesseract_version()
self._ocr_ok = True
except Exception:
self._ocr_ok = False
return self._ocr_ok
def _ensure_openai(self) -> bool:
if self._openai is not None:
return True
key = _get_openai_key()
if not key:
print(" [img] No OpenAI API key — vision description skipped")
return False
try:
from openai import OpenAI
self._openai = OpenAI(api_key=key)
return True
except Exception as e:
print(f" [img] OpenAI client error: {e}")
return False
# ── per-image methods ────────────────────────────────────────────────────
def _ocr(self, img) -> str:
if not self._ensure_ocr():
return ""
try:
import pytesseract
return pytesseract.image_to_string(img).strip()
except Exception:
return ""
def _openai_describe(self, img) -> str:
"""Send one slide image to GPT-4o-mini vision and return description."""
if not self._ensure_openai():
return ""
import base64
try:
buf = io.BytesIO()
img.save(buf, format="PNG")
b64 = base64.standard_b64encode(buf.getvalue()).decode()
resp = self._openai.chat.completions.create(
model=OPENAI_VISION_MODEL,
max_tokens=300,
messages=[{
"role": "user",
"content": [
{"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{b64}",
"detail": "low"}}, # "low" = cheapest
{"type": "text", "text": _VISION_PROMPT},
],
}],
)
self._api_calls += 1
return resp.choices[0].message.content.strip()
except Exception as e:
print(f" [img] OpenAI vision error: {e}")
return ""
# ── public API ───────────────────────────────────────────────────────────
def describe_slide_image(self, img) -> str:
"""
Run OCR then Claude vision on a single slide image (already rendered
as a full-page pixmap). Returns combined description text.
The caller is responsible for caching so this is never called twice
for the same slide.
"""
from PIL import Image as PILImage
if not isinstance(img, PILImage.Image):
return ""
parts: list[str] = []
ocr = self._ocr(img)
if ocr:
parts.append(ocr)
vision = self._openai_describe(img)
if vision:
parts.append(vision)
return " ".join(parts)
@property
def api_calls(self) -> int:
return self._api_calls
# ── Image cache helpers ────────────────────────────────────────────────────────
def _load_image_cache(slide_path: Path) -> dict:
cache_file = slide_path.parent / f"{slide_path.name}.image_cache.json"
if cache_file.exists():
with open(cache_file) as f:
return json.load(f)
return {}
def _save_image_cache(slide_path: Path, cache: dict) -> None:
cache_file = slide_path.parent / f"{slide_path.name}.image_cache.json"
with open(cache_file, "w") as f:
json.dump(cache, f, indent=2)
# ── Slide text extraction ─────────────────────────────────────────────────────
class SlideText(NamedTuple):
index: int # 0-based slide/page index
label: str # short title (first non-empty line)
text: str # full extracted text (incl. notes + image descriptions)
def extract_pdf(path: Path,
describer: ImageDescriber | None = None,
img_cache: dict | None = None) -> list[SlideText]:
import fitz
from PIL import Image as PILImage
doc = fitz.open(str(path))
slides = []
for i, page in enumerate(doc):
text = page.get_text().strip()
label = next((ln.strip() for ln in text.splitlines() if ln.strip()),
f"Page {i+1}")
# Image enrichment for sparse pages — render the full page as a
# high-res pixmap so vector diagrams (state graphs, flowcharts, etc.)
# are captured alongside any embedded bitmaps.
if describer is not None and len(text.split()) < IMAGE_WORD_THRESHOLD:
cache_key = f"page_{i}"
if img_cache is not None and cache_key in img_cache:
img_desc = img_cache[cache_key]
else:
pxmap = page.get_pixmap(matrix=fitz.Matrix(2, 2))
pil = PILImage.frombytes(
"RGB", [pxmap.width, pxmap.height], pxmap.samples)
img_desc = describer.describe_slide_image(pil)
if img_cache is not None:
img_cache[cache_key] = img_desc
if img_desc:
text = (text + "\n" + img_desc).strip()
slides.append(SlideText(i, label[:80], text))
doc.close()
return slides
def extract_pptx(path: Path,
describer: ImageDescriber | None = None,
img_cache: dict | None = None) -> list[SlideText]:
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
from PIL import Image as PILImage
prs = Presentation(str(path))
slides = []
for i, slide in enumerate(prs.slides):
parts: list[str] = []
# Shape text
for shape in slide.shapes:
if shape.has_text_frame:
for para in shape.text_frame.paragraphs:
line = para.text.strip()
if line:
parts.append(line)
# Speaker notes
try:
notes_text = slide.notes_slide.notes_text_frame.text.strip()
if notes_text:
parts.append(notes_text)
except Exception:
pass
text = "\n".join(parts)
label = parts[0][:80] if parts else f"Slide {i+1}"
# Image enrichment for sparse slides: use the first picture shape.
# For PPTX we extract the embedded image blob directly (no rendering).
if describer is not None and len(text.split()) < IMAGE_WORD_THRESHOLD:
cache_key = f"slide_{i}"
if img_cache is not None and cache_key in img_cache:
img_desc = img_cache[cache_key]
else:
img_desc = ""
for shape in slide.shapes:
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
try:
pil = PILImage.open(
io.BytesIO(shape.image.blob)).convert("RGB")
img_desc = describer.describe_slide_image(pil)
break # one image per slide is enough
except Exception:
pass
if img_cache is not None:
img_cache[cache_key] = img_desc
if img_desc:
text = (text + "\n" + img_desc).strip()
slides.append(SlideText(i, label, text))
return slides
def extract_docx(path: Path) -> list[SlideText]:
"""
Word documents lack explicit page breaks; we treat each paragraph as one
logical unit and group them into synthetic 'pages' of ≈ PAGE_PARA paragraphs.
"""
from docx import Document
PAGE_PARA = 15
doc = Document(str(path))
paras = [p.text.strip() for p in doc.paragraphs if p.text.strip()]
pages: list[SlideText] = []
for pi, start in enumerate(range(0, max(len(paras), 1), PAGE_PARA)):
chunk = paras[start:start + PAGE_PARA]
text = "\n".join(chunk)
label = chunk[0][:80] if chunk else f"Page {pi+1}"
pages.append(SlideText(pi, label, text))
return pages
def load_slides(path: Path,
describer: ImageDescriber | None = None,
img_cache: dict | None = None) -> list[SlideText]:
ext = path.suffix.lower()
if ext == ".pdf":
return extract_pdf(path, describer, img_cache)
if ext in (".pptx", ".ppt"):
return extract_pptx(path, describer, img_cache)
if ext in (".docx", ".doc"):
return extract_docx(path)
raise ValueError(f"Unsupported slide format: {ext}")
# ── Embedding & FAISS index ───────────────────────────────────────────────────
class _RemoteEmbedder:
"""Drop-in replacement for SentenceTransformer backed by a remote API.
Implements only the subset of the SentenceTransformer interface used by
embed_texts()/align_multi_slides()/_content_match_slide_group(), so the
rest of the pipeline keeps working when the local ML environment is not
installed.
"""
def __init__(self, backend: str):
self.backend = backend # "google" or "jina"
def encode(self, texts, batch_size=64, show_progress_bar=False,
normalize_embeddings=True, convert_to_numpy=True):
if isinstance(texts, str):
texts = [texts]
# Replace empty strings with a single space — Google's API rejects them.
texts = [t if t and t.strip() else " " for t in texts]
if self.backend == "google":
vecs = embed_texts_google(texts, desc=" [embed:google]",
task_type="RETRIEVAL_DOCUMENT")
else:
vecs = embed_texts_jina(texts, desc=" [embed:jina]")
if vecs is None:
raise RuntimeError(f"Remote embedder '{self.backend}' failed — "
f"check API key and network connectivity.")
return vecs # already L2-normalised, float32
def _remote_embedder_if_available():
"""Return a _RemoteEmbedder when an API key is configured, else None."""
if _get_google_key():
print(" [embed] Using Google text-embedding-004 (remote)", flush=True)
return _RemoteEmbedder("google")
if _get_jina_key():
print(" [embed] Using Jina embeddings v4 (remote)", flush=True)
return _RemoteEmbedder("jina")
return None
def get_embedder():
"""Load a sentence-transformer model; fall back to a remote API embedder
when the local ML environment is missing. Raises RuntimeError only when
neither local nor remote is available."""
try:
from sentence_transformers import SentenceTransformer
import torch
except ImportError:
remote = _remote_embedder_if_available()
if remote is not None:
return remote
raise RuntimeError(
"sentence_transformers is not installed and no remote embedding "
"API key (GEMINI_API_KEY / JINA_API_KEY) is configured. "
"Install the ML environment OR add a Gemini/Jina API key in "
"Settings to enable alignment.")
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f" [embed] Loading {EMBED_MODEL} on {device} ...", flush=True)
try:
# Suppress the safetensors LOAD REPORT (position_ids UNEXPECTED).
# It writes directly to fd 1/2, so we must redirect at the OS level.
import os as _os
_devnull = _os.open(_os.devnull, _os.O_WRONLY)
_saved_stdout = _os.dup(1)
_saved_stderr = _os.dup(2)
_os.dup2(_devnull, 1)
_os.dup2(_devnull, 2)
try:
model = SentenceTransformer(EMBED_MODEL, device=device)
finally:
_os.dup2(_saved_stdout, 1)
_os.dup2(_saved_stderr, 2)
_os.close(_devnull)
_os.close(_saved_stdout)
_os.close(_saved_stderr)
except Exception as e:
print(f" [embed] Local model load failed ({e}) — trying remote API", flush=True)
remote = _remote_embedder_if_available()
if remote is not None:
return remote
raise
print(f" [embed] Model loaded.", flush=True)
return model
def embed_texts(model, texts: list[str], desc: str = " embedding") -> np.ndarray:
"""Return L2-normalised float32 embeddings, shape (N, D)."""
print(f"{desc} ({len(texts)} texts)...", flush=True)
vecs = model.encode(
texts,
batch_size=BATCH_SIZE,
show_progress_bar=False, # avoid tqdm issues in Windows pipe-mode subprocesses
normalize_embeddings=True, # cosine sim → inner product on unit sphere
convert_to_numpy=True,
)
print(f"{desc} done.", flush=True)
return vecs.astype(np.float32)
def build_faiss_index(embeddings: np.ndarray) -> faiss.IndexFlatIP:
"""Inner-product index (= cosine similarity on normalised vectors)."""
dim = embeddings.shape[1]
index = faiss.IndexFlatIP(dim)
index.add(embeddings)
return index
# ── Jina Embeddings v4 multimodal ────────────────────────────────────────────
def _get_jina_key() -> str:
import os
key = os.environ.get("JINA_API_KEY", "")
if not key:
key_file = DATA_DIR / "jina_api.txt"
if key_file.exists():
key = key_file.read_text().strip()
return key
def embed_images_jina(image_paths: list[Path], desc: str = " embedding images") -> np.ndarray | None:
"""Embed slide images using Jina Embeddings v4 API.
Returns L2-normalised float32 embeddings, shape (N, D), or None on failure.
"""
import base64
import requests as _req
key = _get_jina_key()
if not key:
print(" [jina] No Jina API key — cannot embed images")
return None
print(f"{desc} ({len(image_paths)} images via Jina API)...", flush=True)
# Encode images as base64
inputs = []
for p in image_paths:
if not p.exists():
continue
b64 = base64.b64encode(p.read_bytes()).decode("ascii")
inputs.append({"image": f"data:image/png;base64,{b64}"})
if not inputs:
return None
# Call Jina API in batches
all_embeddings = []
batch_size = 16
for i in range(0, len(inputs), batch_size):
batch = inputs[i:i + batch_size]
try:
resp = _req.post(
JINA_API_URL,
headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
json={"model": "jina-embeddings-v4", "input": batch,
"dimensions": 768, "normalized": True,
"embedding_type": "float", "task": "retrieval.passage"},
timeout=120,
)
if resp.status_code != 200:
print(f" [jina] API error {resp.status_code}: {resp.text[:200]}")
return None
data = resp.json()
for item in data.get("data", []):
all_embeddings.append(item["embedding"])
except Exception as e:
print(f" [jina] Request failed: {e}")
return None
print(f"{desc} done.", flush=True)
return np.array(all_embeddings, dtype=np.float32)
def embed_texts_jina(texts: list[str], desc: str = " embedding texts") -> np.ndarray | None:
"""Embed texts using Jina Embeddings v4 API.
Returns L2-normalised float32 embeddings, shape (N, D), or None on failure.
"""
import requests as _req
key = _get_jina_key()
if not key:
print(" [jina] No Jina API key — cannot embed texts")
return None
print(f"{desc} ({len(texts)} texts via Jina API)...", flush=True)
all_embeddings = []
batch_size = 64
for i in range(0, len(texts), batch_size):
batch = [{"text": t} for t in texts[i:i + batch_size]]
try:
resp = _req.post(
JINA_API_URL,
headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
json={"model": "jina-embeddings-v4", "input": batch,
"dimensions": 768, "normalized": True,
"embedding_type": "float", "task": "retrieval.query"},
timeout=120,
)
if resp.status_code != 200:
print(f" [jina] API error {resp.status_code}: {resp.text[:200]}")
return None
data = resp.json()
for item in data.get("data", []):
all_embeddings.append(item["embedding"])
except Exception as e:
print(f" [jina] Request failed: {e}")
return None
print(f"{desc} done.", flush=True)
return np.array(all_embeddings, dtype=np.float32)
# ── Google Generative Language embeddings ────────────────────────────────────
def _get_google_key() -> str:
import os
key = os.environ.get("GEMINI_API_KEY", "") or os.environ.get("GOOGLE_API_KEY", "")
if not key:
for name in ("gemini_api.txt", "google_api.txt"):
key_file = DATA_DIR / name
if key_file.exists():
key = key_file.read_text().strip()
if key:
break
return key
def embed_texts_google(texts: list[str], desc: str = " embedding texts",
task_type: str = "RETRIEVAL_DOCUMENT") -> np.ndarray | None:
"""Embed texts using Google's Generative Language API (text-embedding-004).
Returns L2-normalised float32 embeddings, shape (N, 768), or None on failure.
"""
import requests as _req
key = _get_google_key()
if not key:
print(" [google] No Gemini API key — cannot embed texts")
return None
print(f"{desc} ({len(texts)} texts via Google API)...", flush=True)
url = (f"{GOOGLE_API_URL}/models/{GOOGLE_EMBED_MODEL}:batchEmbedContents"
f"?key={key}")
all_embeddings: list[list[float]] = []
batch_size = 100 # API limit
for i in range(0, len(texts), batch_size):
batch = texts[i:i + batch_size]
payload = {
"requests": [
{
"model": f"models/{GOOGLE_EMBED_MODEL}",
"content": {"parts": [{"text": t}]},
"taskType": task_type,
}
for t in batch
]
}
try:
resp = _req.post(
url,
headers={"Content-Type": "application/json"},
json=payload,
timeout=120,
)
if resp.status_code != 200:
print(f" [google] API error {resp.status_code}: {resp.text[:200]}")
return None
data = resp.json()
for item in data.get("embeddings", []):
all_embeddings.append(item.get("values", []))
except Exception as e:
print(f" [google] Request failed: {e}")
return None
if not all_embeddings:
return None
arr = np.array(all_embeddings, dtype=np.float32)
# L2-normalise so cosine similarity == inner product
norms = np.linalg.norm(arr, axis=1, keepdims=True)
norms[norms == 0] = 1.0
arr = arr / norms
print(f"{desc} done.", flush=True)
return arr
# ── Transcript windowing ──────────────────────────────────────────────────────
def build_window_texts(segments: list[dict], context_sec: float) -> list[str]:
"""
For each segment build a richer query string by pooling the text of all
segments whose midpoint falls within ±context_sec of this segment's midpoint.
This prevents very short segments (e.g. "Yes" or "Okay") from misleading
the matcher.
"""
mids = [(s["start"] + s["end"]) / 2.0 for s in segments]
n = len(segments)
texts: list[str] = []
for i, mid in enumerate(mids):
parts = []
# scan backwards
j = i
while j >= 0 and mids[j] >= mid - context_sec:
j -= 1
# scan forwards
k = i
while k < n and mids[k] <= mid + context_sec:
k += 1
for s in segments[j+1 : k]:
if s["text"].strip():
parts.append(s["text"].strip())
texts.append(" ".join(parts) if parts else (segments[i]["text"] or " "))
return texts
# ── Viterbi temporal smoothing ────────────────────────────────────────────────
def viterbi_smooth(
log_likelihoods: np.ndarray, # shape (T, N_slides)
) -> list[int]:
"""
Viterbi decoding that prefers forward progression.
log_likelihoods[t, s] = log P(observation_t | slide s)
= cosine_similarity score (already log-scale proxy)
Returns: list of best slide indices, length T.
"""
T, N = log_likelihoods.shape
# dp[t, s] = best total log-score ending at slide s at step t
dp = np.full((T, N), -np.inf, dtype=np.float64)
back = np.zeros((T, N), dtype=np.int32)
dp[0] = log_likelihoods[0]
for t in range(1, T):
for s in range(N):
# consider all previous states s_prev
trans = np.zeros(N, dtype=np.float64)
for sp in range(N):
delta = s - sp
if delta == 0:
trans[sp] = STAY_LOGP
elif delta > 0:
trans[sp] = FWD_LOGP_PER * delta
else:
trans[sp] = BWD_LOGP_PER * abs(delta)
scores = dp[t-1] + trans
best_prev = int(np.argmax(scores))
dp[t, s] = scores[best_prev] + log_likelihoods[t, s]
back[t, s] = best_prev
# Traceback
path = [0] * T
path[-1] = int(np.argmax(dp[-1]))
for t in range(T - 2, -1, -1):
path[t] = int(back[t + 1, path[t + 1]])
return path
def viterbi_smooth_fast(log_likelihoods: np.ndarray) -> list[int]:
"""
Vectorised Viterbi — O(T × N) instead of O(T × N²).
Equivalent to the loop version but ~100× faster.
"""
T, N = log_likelihoods.shape
dp = np.full((T, N), -np.inf, dtype=np.float64)
back = np.zeros((T, N), dtype=np.int32)
dp[0] = log_likelihoods[0]
# Precompute transition matrix trans[s_prev, s]
idx = np.arange(N)
delta = idx[None, :] - idx[:, None] # (N, N) delta[sp, s] = s - sp
trans = np.where(delta == 0, STAY_LOGP,
np.where(delta > 0, FWD_LOGP_PER * delta,
BWD_LOGP_PER * np.abs(delta)))
for t in range(1, T):
# scores[sp, s] = dp[t-1, sp] + trans[sp, s]
scores = dp[t-1, :, None] + trans # (N, N)
best_prev = np.argmax(scores, axis=0) # (N,)
dp[t] = scores[best_prev, np.arange(N)] + log_likelihoods[t]
back[t] = best_prev
path = [0] * T
path[-1] = int(np.argmax(dp[-1]))
for t in range(T - 2, -1, -1):
path[t] = int(back[t + 1, path[t + 1]])
return path
# ── Timeline collapse ─────────────────────────────────────────────────────────
def build_timeline(segments: list[dict], slide_path: list[int],
slides: list[SlideText],
off_slide_mask: list[bool] | None = None) -> list[dict]:
"""
Merge consecutive segments assigned to the same slide into one interval.
Off-slide segments are excluded from the timeline.
Returns list of {slide_1based, start, end, label}.
"""
if not segments:
return []
if off_slide_mask is None:
off_slide_mask = [False] * len(segments)
timeline: list[dict] = []
cur_slide: int | None = None
cur_start = 0.0
cur_end = 0.0
for i in range(len(segments)):
s = segments[i]
si = slide_path[i]
if off_slide_mask[i]:
# Flush current span before the gap
if cur_slide is not None:
timeline.append({
"slide": cur_slide + 1,
"start": round(cur_start, 3),
"end": round(cur_end, 3),
"label": slides[cur_slide].label,
})
cur_slide = None
continue
if cur_slide is None:
cur_slide = si
cur_start = s["start"]
cur_end = s["end"]
elif si == cur_slide:
cur_end = s["end"]
else:
timeline.append({
"slide": cur_slide + 1,
"start": round(cur_start, 3),
"end": round(cur_end, 3),
"label": slides[cur_slide].label,
})
cur_slide = si
cur_start = s["start"]
cur_end = s["end"]
if cur_slide is not None:
timeline.append({
"slide": cur_slide + 1,
"start": round(cur_start, 3),
"end": round(cur_end, 3),
"label": slides[cur_slide].label,
})
return timeline
# ── Sparse-slide enrichment ───────────────────────────────────────────────────
def _enrich_sparse_slides(texts: list[str]) -> list[str]:
"""
Slides that are nearly empty (section headers, diagram-only, code-only)
get almost no embedding signal. Enrich them by appending up to
NEIGHBOR_WORDS from the nearest content-rich neighbours so the embedder
has something to work with. The original label text is kept at the front
so the slide's own identity still dominates.
"""
word_counts = [len(t.split()) for t in texts]
enriched = list(texts)
for i, (text, wc) in enumerate(zip(texts, word_counts)):
if wc >= SPARSE_THRESHOLD:
continue
extra: list[str] = []
for delta in (1, -1, 2, -2, 3, -3):
j = i + delta
if 0 <= j < len(texts) and word_counts[j] >= SPARSE_THRESHOLD:
words = texts[j].split()[:NEIGHBOR_WORDS]
extra.extend(words)
if len(extra) >= NEIGHBOR_WORDS * 2:
break
if extra:
enriched[i] = text + " " + " ".join(extra)
return enriched
# ── Main alignment routine ────────────────────────────────────────────────────
def align(caption_path: Path, slide_path: Path,
out_dir: Path, embedder=None) -> Path:
"""
Full alignment pipeline for one (caption, slide) pair.
Returns path of the saved JSON.
"""
print(f"\n{'='*70}")
print(f"Caption : {caption_path.name}")
print(f"Slides : {slide_path.name}")
print(f"{'='*70}")
# ── Load inputs ──────────────────────────────────────────────────────────
with open(caption_path, encoding="utf-8") as f:
caption = json.load(f)
segments: list[dict] = caption["segments"]
if not segments:
print(" [skip] Caption has no segments.")
return out_dir
print(f" Transcript: {len(segments)} segments, {caption['duration']:.0f}s")
# ── Load slides (with image captioning + speaker notes) ───────────────────
describer = ImageDescriber()
img_cache = _load_image_cache(slide_path)
cache_size_before = len(img_cache)
print(" Extracting slide text (+ images + speaker notes)...")
slides = load_slides(slide_path, describer, img_cache)
print(f" Slides: {len(slides)} pages/slides")
# Save image cache if any new descriptions were generated
new_descriptions = len(img_cache) - cache_size_before
if new_descriptions > 0:
_save_image_cache(slide_path, img_cache)
print(f" [img] {describer.api_calls} GPT-4o-mini vision API call(s) made "
f"({new_descriptions} new slide(s) described, cached for future runs)")
# ── Embed slides ──────────────────────────────────────────────────────────
if embedder is None:
embedder = get_embedder()
slide_texts = _enrich_sparse_slides([s.text if s.text.strip() else s.label for s in slides])
print(f" Embedding {len(slides)} slides...")
slide_embs = embed_texts(embedder, slide_texts, desc=" slides")
index = build_faiss_index(slide_embs)
# ── Embed transcript segments (with context window) ───────────────────────
print(f" Building context windows (±{CONTEXT_SEC:.0f}s)...")
window_texts = build_window_texts(segments, CONTEXT_SEC)
print(f" Embedding {len(window_texts)} transcript windows...")
seg_embs = embed_texts(embedder, window_texts, desc=" transcript") # (T, D)
# ── Raw similarity scores: each segment vs all slides ─────────────────────
# faiss.search returns (scores, indices); with IndexFlatIP + normalised
# vectors scores are cosine similarities in [-1, 1].
print(" Querying FAISS index...")
k = len(slides)
sims, idxs = index.search(seg_embs, k) # both (T, N_slides)
# Build log-likelihood matrix: reorder sims by slide index
T = len(segments)
N = len(slides)
log_ll = np.zeros((T, N), dtype=np.float64)
for t in range(T):
for rank in range(k):
log_ll[t, idxs[t, rank]] = float(sims[t, rank])
# Save raw log-likelihoods for off-slide detection (before the prior)
log_ll_raw = log_ll.copy()
# ── Temporal position prior ───────────────────────────────────────────────
# At segment t, the professor is expected to be near slide
# expected_s = (t_mid / total_duration) * (N - 1).
# A Gaussian prior around this expected position gently pushes the
# Viterbi toward the correct slide when raw similarities are ambiguous
# (e.g., consecutive slides with nearly identical content).
total_duration = caption["duration"] or 1.0
slide_idx = np.arange(N, dtype=np.float64)
for t, seg in enumerate(segments):
t_mid = (seg["start"] + seg["end"]) / 2.0
expected_s = (t_mid / total_duration) * (N - 1)
prior = -0.5 * ((slide_idx - expected_s) / PRIOR_SIGMA) ** 2
log_ll[t] += prior
# ── Off-slide detection ───────────────────────────────────────────────────
# Segments where the best raw cosine is below threshold are flagged.
# The professor may be speaking off-topic, answering questions, or doing
# live demos that don't correspond to any slide.
raw_max_sim = log_ll_raw.max(axis=1) # (T,)
off_slide_mask = (raw_max_sim < OFF_SLIDE_THRESHOLD).tolist()
n_off = sum(off_slide_mask)
if n_off:
print(f" Off-slide segments: {n_off}/{T} "
f"(raw cosine < {OFF_SLIDE_THRESHOLD})")