Malina Claude Opus 4.7 commited on
Commit
05f095d
·
1 Parent(s): 889dbaa

NINA v0.81 — modular refactor + usage-token gate + 8-vCPU queue

Browse files

- Split monolith into app.py + pipeline/audio/auth/cache/config/models/retrieval/
synthesis/utils/visual modules.
- auth.verify_usage_token: HMAC (NINA_SIGNING_SECRET) + expiry + single-use;
pipeline.run() refuses without a valid Worker-issued token (per-account 10/5h
limit enforced server-side; the public Space can't be used directly).
- run() takes a 3rd `token` input; Interface queue tuned for ~8 vCPU
(concurrency 3, max 40); uploaded-media purge kept (delete_cache 5 min).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

Files changed (11) hide show
  1. app.py +12 -1305
  2. audio.py +109 -0
  3. auth.py +49 -0
  4. cache.py +122 -0
  5. config.py +68 -0
  6. models.py +114 -0
  7. pipeline.py +199 -0
  8. retrieval.py +278 -0
  9. synthesis.py +195 -0
  10. utils.py +33 -0
  11. visual.py +126 -0
app.py CHANGED
@@ -1,1310 +1,12 @@
1
  # ─────────────────────────────────────────────
2
  # NINA — Neural Information & Narrative Abstraction
3
- # app.py | v0.80 | Made by Malina
4
- # ─────────────────────────────────────────────
5
- #
6
- # Precision MULTIMODAL video search + summarization pipeline.
7
- # Pipeline: video → audio → ASR segments → semantic chunking
8
- # → bi-encoder (text) ⨉ CLIP (vision) fusion → cross-encoder + entity overlap
9
- # → merge → confidence-gated precise re-transcribe → streaming LLM synthesis.
10
- #
11
- # ─────────────────────────────────────────────────────────────────────────────
12
- # v0.80 — performance & modernisation pass over v0.71
13
- # ─────────────────────────────────────────────────────────────────────────────
14
- # Measured on Apple M1 (8 core / 16 GB), 39 s test clip:
15
- # cold first prompt 58.8 s → ~9 s, warm prompts ~1.5 s → sub-second to first token.
16
- #
17
- # [P1] HARDWARE ACCELERATION
18
- # Torch models now auto-target the best device (CUDA → MPS → CPU). On
19
- # Apple Silicon CLIP runs ~1.8× and the cross-encoder ~1.4× faster on the
20
- # Metal (MPS) backend. CTranslate2 (Whisper) has no MPS backend, so it
21
- # stays on CPU but is tuned: int8 + cpu_threads, greedy decoding for the
22
- # cheap pass, and Silero VAD to skip non-speech.
23
- #
24
- # [P2] NO MORE DOUBLE TRANSCRIPTION
25
- # v0.71 transcribed the whole video with `base`, then RE-transcribed every
26
- # sampled sector with the ~15× slower `large-v3-turbo` — even for a global
27
- # summary (≈24 s wasted on this clip). v0.80:
28
- # • GLOBAL summaries use the clean `base` transcript directly (no turbo).
29
- # • SPECIFIC queries re-transcribe with turbo ONLY on matched regions and
30
- # ONLY when the base pass was low-confidence (avg_logprob gate). On
31
- # clean audio turbo never runs; on hard audio it runs exactly where it
32
- # helps. Per-sector results are cached and persist across prompts.
33
- #
34
- # [P3] PARALLEL COLD START
35
- # Audio transcription (CPU) and CLIP frame analysis (MPS) are independent
36
- # and now run concurrently on first sight of a video, overlapping the two
37
- # heaviest stages instead of summing them.
38
- #
39
- # [P4] ZERO-COPY I/O
40
- # Audio is decoded straight from the container (PyAV) — no ffmpeg wav
41
- # temp file. Frames are streamed from one ffmpeg rawvideo pipe into NumPy —
42
- # no per-frame JPEG temp files.
43
- #
44
- # [P5] PERSISTENT DISK CACHE
45
- # Transcript, chunk + visual embeddings and precise sectors are persisted
46
- # under a content fingerprint, so re-opening the same video — even after a
47
- # restart — skips transcription/chunking/CLIP entirely.
48
- #
49
- # [P6] STREAMING + UX
50
- # LLM synthesis streams token-by-token; run() is a generator that shows
51
- # progress and writes the answer as it is produced.
52
- #
53
- # [Q] QUALITY FIXES
54
- # • Router no longer misreads "what does the video say about X" as a global
55
- # summary (the bare word "about"/"explain" no longer forces global mode).
56
- # • The illustrative "[2:30]" timestamp no longer leaks into answers.
57
- #
58
- # Scoring formula (SPECIFIC/HYBRID mode):
59
- # audio = 0.6 * sigmoid(cross_encoder_logit) + 0.4 * entity_overlap
60
- # final = (1 - VISUAL_WEIGHT) * audio + VISUAL_WEIGHT * clip_visual_score
61
- #
62
- # Entity extraction: regex + simple NP heuristic (no spacy dependency).
63
- # Works multilingually because it operates on surface forms, not POS tags.
64
  # ─────────────────────────────────────────────
65
 
66
  import os
67
- import re
68
- import json
69
- import math
70
- import hashlib
71
- import shutil
72
- import tempfile
73
- import threading
74
- import time
75
- from concurrent.futures import ThreadPoolExecutor
76
-
77
- import ffmpeg
78
  import gradio as gr
79
- import numpy as np
80
- from PIL import Image
81
- from faster_whisper import WhisperModel
82
- from faster_whisper.audio import decode_audio
83
- from sentence_transformers import SentenceTransformer, CrossEncoder
84
- from huggingface_hub import InferenceClient
85
- import warnings
86
- warnings.filterwarnings("ignore", message="FP16 is not supported on CPU; using FP32 instead")
87
-
88
-
89
- # ── Config ─────────────────────────────────────────────────────────────────────
90
-
91
- WHISPER_FAST = "base"
92
- WHISPER_PRECISE = "large-v3-turbo"
93
- SAMPLE_RATE = 16000
94
- WHISPER_CPU_THREADS = 6 # tuned for M1 (perf cores); CTranslate2 is CPU-only
95
-
96
- RETRANSCRIBE_MAX = 12 # per-prompt budget for NEW (uncached) sector transcriptions
97
- PRECISE_LOGPROB_GATE = -0.55 # only turbo-refine sectors whose base avg_logprob is below this
98
- # (clean audio scores high → turbo is correctly skipped)
99
-
100
- CHUNK_SPLIT_THRESHOLD = 0.45
101
- CHUNK_MIN_DURATION = 8.0
102
- CHUNK_MAX_DURATION = 90.0
103
- CHUNK_WINDOW = 5
104
-
105
- BI_ENCODER_TOP_K = 100
106
- CROSS_ENCODER_TOP_K = 10
107
- RESULTS_TOP_N = 6
108
- REGION_MIN_DURATION = 5.0
109
- MERGE_GAP_SEC = 6.0
110
-
111
- # routing thresholds
112
- BI_SCORE_GLOBAL_FLOOR = 0.10 # below this → escalate to GLOBAL regardless
113
- BI_SCORE_HYBRID_FLOOR = 0.28 # below this → HYBRID (pad with neighbours)
114
-
115
- # global mode: how many evenly-sampled chunks to retranscribe
116
- GLOBAL_MAX_CHUNKS = 12 # hard cap to keep latency sane
117
-
118
- # ── CLIP / visual config ────────────────────────────────────────────────────────
119
- CLIP_MODEL = "clip-ViT-B-32" # OpenAI CLIP ViT-B/32 (via sentence-transformers)
120
- CLIP_MAX_FRAMES = 96 # cap frames encoded per video (perf)
121
- CLIP_MIN_FPS = 0.1 # sample at least 1 frame / 10s
122
- CLIP_MAX_FPS = 0.5 # sample at most 1 frame / 2s
123
- CLIP_FRAME_SIZE = 224 # square fed to CLIP (matches ViT-B/32 input → no double resize)
124
- VISUAL_WEIGHT = 0.30 # fusion weight of visual vs audio in final score
125
- VISUAL_TAGS_TOP_K = 4 # max zero-shot tags surfaced per region
126
- VISUAL_TAG_MIN_SIM = 0.20 # min CLIP cosine for a tag to count
127
-
128
- # vocabulary for zero-shot "what is on screen" tagging
129
- VISUAL_CONCEPTS = [
130
- "a person talking to the camera", "a group of people", "a presentation with slides",
131
- "a lecture or classroom", "an interview", "a news broadcast",
132
- "a screen recording of software", "source code in a text editor",
133
- "a webpage in a browser", "a chart or graph", "text on screen",
134
- "a product demonstration", "hands demonstrating something",
135
- "a cooking or food scene", "a kitchen", "an office", "a laboratory",
136
- "a factory or machinery", "a construction site", "an outdoor nature landscape",
137
- "a forest", "mountains", "a beach or ocean", "a city street",
138
- "buildings and architecture", "a car or vehicle driving", "an airplane", "a train",
139
- "a sports event", "people exercising", "a concert or live music",
140
- "a video game gameplay", "an animation or cartoon", "a medical or hospital scene",
141
- "a doctor or patient", "an animal", "a dog", "a cat", "a crowd of people",
142
- "a map", "a whiteboard with diagrams", "a scientific diagram",
143
- "a phone or mobile device", "a computer or laptop", "money or finance",
144
- "a meeting or conference room", "a stage with a speaker",
145
- "a dark scene at night", "a daytime scene",
146
- ]
147
-
148
- LLM_MODEL = "Qwen/Qwen2.5-7B-Instruct"
149
- LLM_MAX_TOKENS = 600
150
- LLM_TIMEOUT = 60
151
-
152
- CACHE_DIR = os.path.join(tempfile.gettempdir(), "nina_cache")
153
- DISK_CACHE = True
154
-
155
- DEBUG = True
156
-
157
-
158
- # ── Device selection ─────────────────────────────────────────────────────────────
159
- # CTranslate2 (Whisper) is CPU-only here; the torch models (bi/cross/CLIP) can
160
- # use Metal (MPS) on Apple Silicon or CUDA on a GPU box.
161
-
162
- def _best_torch_device() -> str:
163
- try:
164
- import torch
165
- if torch.cuda.is_available():
166
- return "cuda"
167
- if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
168
- return "mps"
169
- except Exception:
170
- pass
171
- return "cpu"
172
-
173
- TORCH_DEVICE = _best_torch_device()
174
-
175
-
176
- # ── Model load ─────────────────────────────────────────────────────────────────
177
-
178
- print(f"[NINA] Torch device: {TORCH_DEVICE} | Whisper: CPU int8 (x{WHISPER_CPU_THREADS})")
179
-
180
- print("[NINA] Loading Whisper base (faster-whisper)...")
181
- _whisper_fast = WhisperModel(WHISPER_FAST, device="cpu", compute_type="int8",
182
- cpu_threads=WHISPER_CPU_THREADS)
183
-
184
- # Bi-encoder stays on CPU: it is tiny (sub-100 ms) and MPS transfer overhead is a
185
- # wash, and this keeps the MPS device free for CLIP during the parallel cold start.
186
- print("[NINA] Loading bi-encoder...")
187
- bi_encoder = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2", device="cpu")
188
-
189
- print(f"[NINA] Loading cross-encoder ({TORCH_DEVICE})...")
190
- cross_encoder = CrossEncoder("cross-encoder/mmarco-mMiniLMv2-L12-H384-v1", device=TORCH_DEVICE)
191
-
192
-
193
- HF_TOKEN = os.getenv("HF_TOKEN")
194
- if not HF_TOKEN:
195
- _token_file = os.path.expanduser("~/.cache/huggingface/token")
196
- if os.path.exists(_token_file):
197
- HF_TOKEN = open(_token_file).read().strip()
198
-
199
- if HF_TOKEN:
200
- print(f"[NINA] HF_TOKEN loaded — LLM calls enabled.")
201
- else:
202
- print("[NINA] HF_TOKEN not set — LLM calls will fail.")
203
-
204
- llm_client = InferenceClient(
205
- token=HF_TOKEN,
206
- timeout=LLM_TIMEOUT,
207
- )
208
-
209
-
210
- _whisper_precise = None
211
- _whisper_precise_lock = threading.Lock()
212
-
213
- def get_whisper_precise():
214
- global _whisper_precise
215
- with _whisper_precise_lock:
216
- if _whisper_precise is None:
217
- print(f"[NINA] Loading Whisper {WHISPER_PRECISE} (faster-whisper)...")
218
- _whisper_precise = WhisperModel(WHISPER_PRECISE, device="cpu",
219
- compute_type="int8",
220
- cpu_threads=WHISPER_CPU_THREADS)
221
- print(f"[NINA] Whisper {WHISPER_PRECISE} ready.")
222
- return _whisper_precise
223
-
224
-
225
- # ── CLIP (OpenAI ViT-B/32) — lazy, warmed in background ──────────────────────────
226
- _clip_model = None
227
- _clip_lock = threading.Lock()
228
- _concept_embs = None
229
- _concept_lock = threading.Lock()
230
-
231
- def get_clip():
232
- global _clip_model
233
- with _clip_lock:
234
- if _clip_model is None:
235
- print(f"[NINA] Loading CLIP ({CLIP_MODEL}, {TORCH_DEVICE})...")
236
- _clip_model = SentenceTransformer(CLIP_MODEL, device=TORCH_DEVICE)
237
- print(f"[NINA] CLIP ready.")
238
- return _clip_model
239
-
240
- def _get_concept_embs() -> np.ndarray:
241
- """Encode (once) the zero-shot vocabulary, L2-normalised."""
242
- global _concept_embs
243
- with _concept_lock:
244
- if _concept_embs is None:
245
- embs = get_clip().encode(VISUAL_CONCEPTS, convert_to_numpy=True,
246
- show_progress_bar=False)
247
- _concept_embs = embs / (np.linalg.norm(embs, axis=1, keepdims=True) + 1e-9)
248
- return _concept_embs
249
-
250
-
251
- # Warm the lazy models in the background; CLIP loads on the (free) MPS device,
252
- # turbo loads on CPU. Both finish before they are first needed in most cases.
253
- threading.Thread(target=get_whisper_precise, daemon=True).start()
254
- threading.Thread(target=get_clip, daemon=True).start()
255
- print(f"[NINA] Ready. ( {WHISPER_PRECISE} + CLIP warming up...)")
256
-
257
- # ── Transcript + visual cache (in-memory) ─────────────────────────────────────────
258
- # Stores segments, chunks (with embeddings), visual frame embeddings, the decoded
259
- # waveform, and a per-sector precise-transcription cache, keyed by video path.
260
- # Second prompt on same video skips transcription, chunking and CLIP entirely.
261
- _cache: dict = {} # { video_path: {"segments","chunks","visual","audio","precise","_atime"} }
262
-
263
- # Data lifecycle / privacy:
264
- # • The uploaded video itself is purged by Gradio's own temp cleaner
265
- # (Interface(delete_cache=...)) — see the bottom of this file — so a file is
266
- # removed shortly after the user's session goes idle. One upload still serves
267
- # MANY prompts: the decoded audio + transcript live in RAM (below), so the
268
- # file is no longer needed once processed.
269
- # • This in-memory state and the derived on-disk cache are TTL-evicted here so
270
- # nothing lingers indefinitely.
271
- CACHE_IDLE_TTL = 1200 # drop in-memory video state idle for > 20 min
272
- CACHE_DISK_TTL = 1800 # delete on-disk transcript/embedding cache > 30 min old
273
-
274
- def _evict_stale() -> None:
275
- now = time.time()
276
- for vp in [k for k, e in _cache.items() if now - e.get("_atime", now) > CACHE_IDLE_TTL]:
277
- _cache.pop(vp, None)
278
- try:
279
- if os.path.isdir(CACHE_DIR):
280
- for name in os.listdir(CACHE_DIR):
281
- d = os.path.join(CACHE_DIR, name)
282
- if os.path.isdir(d) and now - os.path.getmtime(d) > CACHE_DISK_TTL:
283
- shutil.rmtree(d, ignore_errors=True)
284
- except Exception:
285
- pass
286
-
287
-
288
- # ── Audio ──────────────────────────────────────────────────────────────────────
289
-
290
- def load_audio(media_path: str) -> np.ndarray:
291
- """Decode any container straight to a float32 mono 16k waveform (PyAV, no temp file)."""
292
- return decode_audio(media_path, sampling_rate=SAMPLE_RATE)
293
-
294
-
295
- def media_duration(media_path: str) -> float:
296
- try:
297
- info = ffmpeg.probe(media_path)
298
- return float(info["format"]["duration"])
299
- except Exception:
300
- return 0.0
301
-
302
-
303
- # ── Frames (CLIP input) — streamed from one ffmpeg pipe, no temp files ────────────
304
-
305
- def extract_frames(video_path: str, duration: float):
306
- """
307
- Sample frames evenly across the video and stream them as raw RGB straight
308
- into NumPy via a single ffmpeg pipe (no per-frame JPEG temp files).
309
- fps is chosen so total frames ≈ CLIP_MAX_FRAMES (bounded by MIN/MAX fps).
310
- Returns (frames_rgb, times) where frames_rgb is (N, S, S, 3) uint8.
311
- """
312
- fps = CLIP_MAX_FPS
313
- if duration and duration > 0:
314
- fps = min(CLIP_MAX_FPS, max(CLIP_MIN_FPS, CLIP_MAX_FRAMES / duration))
315
-
316
- S = CLIP_FRAME_SIZE
317
- try:
318
- out, _ = (
319
- ffmpeg.input(video_path)
320
- .filter("fps", fps=fps)
321
- # cover-then-centre-crop to a square so portrait/landscape both work
322
- .filter("scale", S, S, force_original_aspect_ratio="increase")
323
- .filter("crop", S, S)
324
- .output("pipe:", format="rawvideo", pix_fmt="rgb24")
325
- .run(capture_stdout=True, capture_stderr=True)
326
- )
327
- except ffmpeg.Error:
328
- return np.zeros((0, S, S, 3), dtype=np.uint8), np.zeros((0,))
329
-
330
- if not out:
331
- return np.zeros((0, S, S, 3), dtype=np.uint8), np.zeros((0,))
332
-
333
- frames = np.frombuffer(out, np.uint8).reshape(-1, S, S, 3)[:CLIP_MAX_FRAMES]
334
- times = np.array([(i + 0.5) / fps for i in range(len(frames))])
335
- return frames, times
336
-
337
-
338
- # ── Stage 2: transcription ─────────────────────────────────────────────────────
339
-
340
- def transcribe_fast(audio: np.ndarray) -> list[dict]:
341
- """
342
- Cheap full-video pass: base model, greedy decoding, Silero VAD.
343
- Keeps per-segment avg_logprob so we can later refine ONLY weak sectors.
344
- """
345
- segments_gen, _ = _whisper_fast.transcribe(
346
- audio, beam_size=1, vad_filter=True, word_timestamps=False,
347
- )
348
- return [
349
- {
350
- "text": seg.text.strip(),
351
- "start": round(seg.start, 2),
352
- "end": round(seg.end, 2),
353
- "logprob": round(float(getattr(seg, "avg_logprob", 0.0) or 0.0), 3),
354
- }
355
- for seg in segments_gen
356
- if seg.text.strip()
357
- ]
358
-
359
-
360
- # ── Stage 3a: visual analysis (CLIP) ─────────────────────────────────────────────
361
-
362
- def analyze_visual(video_path: str, duration: float) -> dict:
363
- """
364
- Sample → encode frames with CLIP. Cached per video.
365
- Returns {"emb": (N, D) float32, "time": (N,) float}.
366
- Empty arrays when the video has no usable visual stream (audio-only).
367
- """
368
- frames, times = extract_frames(video_path, duration)
369
- if len(frames) == 0:
370
- print("[NINA] No video frames (audio-only?) — visual analysis skipped.")
371
- return {"emb": np.zeros((0, 512), dtype=np.float32), "time": np.zeros((0,))}
372
-
373
- images = [Image.fromarray(f) for f in frames]
374
- embs = get_clip().encode(images, convert_to_numpy=True,
375
- batch_size=32, show_progress_bar=False)
376
-
377
- print(f"[NINA] CLIP encoded {len(images)} frames ({TORCH_DEVICE}).")
378
- return {"emb": np.asarray(embs, dtype=np.float32), "time": np.asarray(times)}
379
-
380
-
381
- # ── semantic chunking ─────────────────────────────────────────────────
382
-
383
- def semantic_chunk(segments: list[dict]) -> list[dict]:
384
- if not segments:
385
- return []
386
- texts = [s["text"] for s in segments]
387
- embeddings = bi_encoder.encode(texts, convert_to_numpy=True, batch_size=64)
388
- chunks, current, cur_emb = [], [segments[0]], [embeddings[0]]
389
-
390
- for i in range(1, len(segments)):
391
- chunk_dur = segments[i]["end"] - current[0]["start"]
392
- window_mean = np.mean(cur_emb[-CHUNK_WINDOW:], axis=0)
393
- sim = max(_cosine(embeddings[i], window_mean),
394
- _cosine(embeddings[i], cur_emb[-1]))
395
- long_enough = (current[-1]["end"] - current[0]["start"]) >= CHUNK_MIN_DURATION
396
-
397
- if (sim < CHUNK_SPLIT_THRESHOLD or chunk_dur >= CHUNK_MAX_DURATION) and long_enough:
398
- chunks.append(_build_chunk(current, cur_emb))
399
- current, cur_emb = [segments[i]], [embeddings[i]]
400
- else:
401
- current.append(segments[i])
402
- cur_emb.append(embeddings[i])
403
-
404
- if current:
405
- chunks.append(_build_chunk(current, cur_emb))
406
-
407
- print(f"[NINA] {len(segments)} segments → {len(chunks)} chunks.")
408
- return chunks
409
-
410
-
411
- # ── Entity extraction ──────────────────────────────────────────────────────────
412
-
413
- _STOPWORDS = {
414
- "the","a","an","and","or","but","in","on","at","to","for","of","is","are",
415
- "was","were","be","been","that","this","it","he","she","they","we","i",
416
- "w","z","i","że","na","do","się","nie","to","jest","są","by","przez","po",
417
- "le","la","les","un","une","des","du","et","en","à","de","est","il","elle",
418
- "ein","eine","der","die","das","und","ist","in","zu","mit","von","dem",
419
- }
420
-
421
- def extract_entities(text: str) -> set[str]:
422
- """
423
- Extract surface-form entities from text.
424
- Returns a set of normalised lowercase strings for overlap comparison.
425
- """
426
- entities: set[str] = set()
427
-
428
- # 1. quoted phrases — high precision
429
- for match in re.finditer(r'"([^"]{2,40})"', text):
430
- entities.add(match.group(1).lower().strip())
431
-
432
- # 2. capitalised multi-word sequences (proper nouns)
433
- for match in re.finditer(r'\b([A-ZÁÉÍÓÚÀÂÊÎÔÙÄËÏÖÜĄĆĘŁŃÓŚŹŻ][a-záéíóúàâêîôùäëïöüąćęłńóśźż]+(?:\s[A-ZÁÉÍÓÚÀÂÊÎÔÙÄËÏÖÜĄĆĘŁŃÓŚŹŻ][a-zÀ-žąćęłńóśźż]+)*)\b', text):
434
- token = match.group(1).lower().strip()
435
- if token not in _STOPWORDS and len(token) > 2:
436
- entities.add(token)
437
-
438
- # 3. single capitalised tokens (names, brands)
439
- for token in re.findall(r'\b[A-ZÁÉÍÓÚÀÂÊÎÔÙÄËÏÖÜĄĆĘŁŃÓŚŹŻ][a-zÀ-žąćęłńóśźż]{2,}\b', text):
440
- t = token.lower()
441
- if t not in _STOPWORDS:
442
- entities.add(t)
443
-
444
- # 4. numbers with context
445
- for match in re.finditer(r'\b([A-Za-z]+[-\s]?\d+[\w]*)\b', text):
446
- entities.add(match.group(1).lower())
447
-
448
- return entities
449
-
450
-
451
- def entity_overlap_score(prompt_entities: set[str],
452
- chunk_entities: set[str],
453
- chunk_text: str = "") -> float:
454
-
455
- if not prompt_entities:
456
- return 0.0
457
-
458
- chunk_text_lower = chunk_text.lower()
459
- matched = 0
460
- for pe in prompt_entities:
461
- # pass 1: extracted entity overlap
462
- entity_hit = any(pe in ce or ce in pe for ce in chunk_entities)
463
- # pass 2: raw text substring (handles lowercase ASR output)
464
- text_hit = len(pe) > 3 and pe in chunk_text_lower
465
- if entity_hit or text_hit:
466
- matched += 1
467
- return matched / len(prompt_entities)
468
-
469
-
470
- def add_entities_to_chunks(chunks: list[dict]) -> list[dict]:
471
- for chunk in chunks:
472
- chunk["entities"] = extract_entities(chunk["text"])
473
- return chunks
474
-
475
-
476
- # ── Query router ───────────────────────────────────────────────────────────────
477
- #
478
- # Classifies prompt into one of three modes before retrieval runs.
479
- #
480
- # GLOBAL — user wants a summary / overview of the whole video.
481
- # Retrieval is the wrong tool here because no single chunk is "about"
482
- # summarization. → skip retrieval, sample chunks evenly, synthesize.
483
- #
484
- # HYBRID — user has a topic but signal is weak (bi-score 0.10–0.28).
485
- # → run retrieval, but pad results with adjacent chunks.
486
- #
487
- # SPECIFIC — normal focused query, retrieval works well (bi-score > 0.28).
488
- # → standard pipeline unchanged.
489
- #
490
- # Router runs in two passes:
491
- # Pass 1: regex pattern match on prompt text (zero-cost, runs before encoding)
492
- # Pass 2: bi-encoder score after retrieval (upgrades SPECIFIC → GLOBAL if
493
- # retrieval actually fails)
494
-
495
- # Global ONLY when the user asks for a whole-video overview. Critically, this no
496
- # longer fires on "what does the video say ABOUT <topic>" — a bare "about" or
497
- # "explain" used to force global and swallow specific questions.
498
- _GLOBAL_PATTERNS = re.compile(
499
- r'\b('
500
- r'summari[sz]e|summary|overview|recap|tl;?dr|key\s+points?|main\s+points?|'
501
- r'key\s+takeaways?|main\s+idea|gist|'
502
- r'what(?:\'s| is| was)\s+(?:this|the|it)\s+(?:video|recording|clip|all\s+)?\s*about|'
503
- r'what(?:\'s| is| was)\s+(?:this|the)\s+(?:video|recording|clip)|'
504
- r'describe\s+(?:the|this)\s+(?:video|recording|clip)|'
505
- r'streszcz\w*|podsumuj\w*|podsumowanie|'
506
- r'o\s+czym\s+(?:jest|to|opowiada|mówi)|czego\s+dotyczy|'
507
- r'gł[oó]wn\w+\s+(?:punkt\w*|my[sś]l\w*|tez\w*)|og[oó]ln\w+\s+zarys'
508
- r')\b',
509
- re.IGNORECASE
510
- )
511
-
512
- def classify_query(prompt: str) -> str:
513
- """
514
- Pass 1 router — pattern-based, runs before any encoding.
515
- Returns "global" or "specific".
516
- Pass 2 (bi-score based upgrade) happens inside run() after retrieval.
517
- """
518
- if _GLOBAL_PATTERNS.search(prompt):
519
- return "global"
520
- return "specific"
521
-
522
-
523
- # ── Stage 4: bi-encoder retrieval (top-100) ───────────────────────────────────
524
-
525
- def bi_encode_retrieve(chunks: list[dict], prompt: str) -> tuple[list[dict], float]:
526
- # chunk embeddings were computed once at chunking time and cached on the
527
- # chunk dict ("emb"); here we only encode the prompt.
528
- prompt_emb = bi_encoder.encode([prompt], convert_to_numpy=True)[0]
529
- scores = [_cosine(prompt_emb, c["emb"]) for c in chunks]
530
-
531
- top_k = min(BI_ENCODER_TOP_K, len(chunks))
532
- top_idx = np.argsort(scores)[::-1][:top_k]
533
-
534
- if DEBUG:
535
- print(f"[DEBUG] Bi top-3 scores: " +
536
- ", ".join(f"{scores[i]:.3f}" for i in top_idx[:3]))
537
-
538
- best = scores[top_idx[0]] if len(top_idx) else 0.0
539
- return (
540
- [{**chunks[i], "bi_score": round(scores[i], 3)} for i in top_idx],
541
- best
542
- )
543
-
544
-
545
- # ── Stage 4b: visual relevance (CLIP) ─────────────────────���───────────────────
546
-
547
- def visual_scores(visual: dict, prompt: str) -> tuple[np.ndarray, np.ndarray]:
548
- """
549
- Cosine of prompt↔each frame in CLIP space, plus a min-max normalised copy.
550
- Normalisation makes CLIP sims (typically ~0.2–0.35) comparable to the
551
- audio score's 0–1 range before fusion. Returns (raw, norm); empty when
552
- there are no frames.
553
- """
554
- embs = visual.get("emb")
555
- if embs is None or len(embs) == 0:
556
- if DEBUG:
557
- print("[DEBUG] Visual: no frames (audio-only) — visual weight = 0.")
558
- return np.array([]), np.array([])
559
- q = get_clip().encode([prompt], convert_to_numpy=True, show_progress_bar=False)[0]
560
- qn = q / (np.linalg.norm(q) + 1e-9)
561
- en = embs / (np.linalg.norm(embs, axis=1, keepdims=True) + 1e-9)
562
- sims = en @ qn
563
- lo, hi = float(sims.min()), float(sims.max())
564
- norm = (sims - lo) / (hi - lo + 1e-9)
565
- if DEBUG:
566
- times = visual.get("time")
567
- order = np.argsort(sims)[::-1][:3]
568
- tops = ", ".join(f"{fmt_time(times[i])}={sims[i]:.3f}" for i in order)
569
- print(f"[DEBUG] Visual: {len(sims)} frames; raw sim "
570
- f"min/mean/max={sims.min():.3f}/{sims.mean():.3f}/{sims.max():.3f}; "
571
- f"top moments: {tops}")
572
- return sims, norm
573
-
574
-
575
- def span_visual_score(times: np.ndarray, norm: np.ndarray,
576
- start: float, end: float) -> float:
577
- """Best (normalised) visual relevance among frames inside [start, end]."""
578
- if len(times) == 0:
579
- return 0.0
580
- mask = (times >= start - 0.5) & (times <= end + 0.5)
581
- if not mask.any():
582
- idx = int(np.argmin(np.abs(times - (start + end) / 2)))
583
- return float(norm[idx])
584
- return float(norm[mask].max())
585
-
586
-
587
- def region_visual_tags(visual: dict, start: float, end: float) -> list[str]:
588
- """Zero-shot CLIP tags describing what is on screen during [start, end]."""
589
- embs = visual.get("emb")
590
- times = visual.get("time")
591
- if embs is None or len(embs) == 0:
592
- return []
593
-
594
- mask = (times >= start - 0.5) & (times <= end + 0.5)
595
- if mask.any():
596
- sel = embs[mask]
597
- else:
598
- idx = int(np.argmin(np.abs(times - (start + end) / 2)))
599
- sel = embs[idx:idx + 1]
600
-
601
- region_emb = sel.mean(axis=0)
602
- region_emb = region_emb / (np.linalg.norm(region_emb) + 1e-9)
603
- sims = _get_concept_embs() @ region_emb
604
-
605
- order = np.argsort(sims)[::-1][:VISUAL_TAGS_TOP_K]
606
- return [VISUAL_CONCEPTS[i] for i in order if sims[i] >= VISUAL_TAG_MIN_SIM]
607
-
608
-
609
- def add_visual_tags(regions: list[dict], visual: dict) -> list[dict]:
610
- for r in regions:
611
- r["visual_tags"] = region_visual_tags(visual, r["start"], r["end"])
612
- return regions
613
-
614
-
615
- # ── Stage 5: cross-encoder rerank + audio/visual fusion (top-100 → top-10) ─────
616
-
617
- def rerank_and_score(candidates: list[dict], prompt: str,
618
- times: np.ndarray, norm: np.ndarray) -> list[dict]:
619
- # cross-encoder
620
- pairs = [[prompt, c["text"]] for c in candidates]
621
- logits = cross_encoder.predict(pairs)
622
-
623
- # entity overlap
624
- prompt_entities = extract_entities(prompt)
625
- prompt_words = {w.lower() for w in re.findall(r'[\wÀ-ž]{3,}', prompt)
626
- if w.lower() not in _STOPWORDS}
627
- all_prompt_tokens = prompt_entities | prompt_words
628
-
629
- if DEBUG and all_prompt_tokens:
630
- print(f"[DEBUG] Prompt tokens for entity match: {all_prompt_tokens}")
631
-
632
- vw = VISUAL_WEIGHT if len(norm) else 0.0 # no frames → pure audio
633
-
634
- scored = []
635
- for candidate, logit in zip(candidates, logits):
636
- chunk_entities = candidate.get("entities", set())
637
- chunk_text = candidate.get("text", "")
638
- overlap = entity_overlap_score(all_prompt_tokens, chunk_entities, chunk_text)
639
 
640
- ce_conf = _sigmoid(float(logit))
641
- audio_score = 0.6 * ce_conf + 0.4 * overlap
642
- visual_score = span_visual_score(times, norm, candidate["start"], candidate["end"])
643
- final = (1.0 - vw) * audio_score + vw * visual_score
644
-
645
- scored.append({
646
- **candidate,
647
- "ce_logit": round(float(logit), 3),
648
- "entity_overlap": round(overlap, 3),
649
- "visual_score": round(visual_score, 3),
650
- "confidence": round(min(1.0, final), 3),
651
- })
652
-
653
- # sort by fused multimodal score
654
- ranked = sorted(scored, key=lambda x: x["confidence"], reverse=True)
655
-
656
- if DEBUG:
657
- print(f"[DEBUG] Top-3 after reranking (audio+visual):")
658
- for r in ranked[:3]:
659
- print(f" ce_logit={r['ce_logit']:.2f} "
660
- f"bi={r['bi_score']:.3f} "
661
- f"entity={r['entity_overlap']:.3f} "
662
- f"visual={r['visual_score']:.3f} "
663
- f"conf={r['confidence']:.3f} "
664
- f"\"{r['text'][:60]}\"")
665
-
666
- return ranked[:CROSS_ENCODER_TOP_K]
667
-
668
-
669
- # ── Hybrid padding ─────────────────────────────────────────────────────────────
670
-
671
- def pad_with_neighbours(results: list[dict], chunks: list[dict]) -> list[dict]:
672
- """
673
- HYBRID mode: for each retrieved chunk, include its immediate neighbours
674
- from the full chunk list. Helps when the relevant content slightly
675
- overflows the chunk boundary. Deduplicates by start timestamp.
676
- """
677
- result_starts = {r["start"] for r in results}
678
- padded = list(results)
679
-
680
- for r in results:
681
- for i, c in enumerate(chunks):
682
- if abs(c["start"] - r["start"]) < 0.5: # found matching chunk
683
- for neighbour_i in [i - 1, i + 1]:
684
- if 0 <= neighbour_i < len(chunks):
685
- nb = chunks[neighbour_i]
686
- if nb["start"] not in result_starts:
687
- padded.append({
688
- **nb,
689
- "bi_score": 0.0,
690
- "ce_logit": -9.0,
691
- "entity_overlap": 0.0,
692
- "visual_score": 0.0,
693
- "confidence": nb.get("confidence", 0.1),
694
- })
695
- result_starts.add(nb["start"])
696
- break
697
-
698
- return sorted(padded, key=lambda x: x["start"])
699
-
700
-
701
- # ── Global mode: even sampling ────────────────────────────────────────────────
702
-
703
- def sample_chunks_for_global(chunks: list[dict], n_target: int) -> list[dict]:
704
- """
705
- For global summarization, pick `n_target` chunks evenly distributed across
706
- the video, so the summary covers the whole thing, not just the beginning.
707
- """
708
- n_target = max(3, min(n_target, len(chunks)))
709
- if n_target >= len(chunks):
710
- return chunks
711
-
712
- # evenly spaced indices
713
- indices = [int(i * (len(chunks) - 1) / (n_target - 1)) for i in range(n_target)]
714
- return [chunks[i] for i in indices]
715
-
716
-
717
- # ── Stage 6: merge regions ─────────────────────────────────────────────────────
718
-
719
- def merge_regions(results: list[dict]) -> list[dict]:
720
- if not results:
721
- return []
722
- sorted_r = sorted(results, key=lambda x: x["start"])
723
- merged, current = [], sorted_r[0].copy()
724
- current["_frags"] = [sorted_r[0]]
725
-
726
- for nxt in sorted_r[1:]:
727
- if nxt["start"] - current["end"] <= MERGE_GAP_SEC:
728
- current["end"] = max(current["end"], nxt["end"])
729
- current["text"] += " " + nxt["text"]
730
- current["_frags"].append(nxt)
731
- else:
732
- merged.append(_finalize_region(current))
733
- current = nxt.copy()
734
- current["_frags"] = [nxt]
735
-
736
- merged.append(_finalize_region(current))
737
- return [r for r in merged if (r["end"] - r["start"]) >= REGION_MIN_DURATION]
738
-
739
-
740
- def _finalize_region(region: dict) -> dict:
741
- frags = region.pop("_frags")
742
- total_dur = sum(max(f["end"] - f["start"], 0.1) for f in frags)
743
- w_conf = sum(f["confidence"] * max(f["end"] - f["start"], 0.1)
744
- for f in frags) / total_dur
745
- duration = region["end"] - region["start"]
746
- w_conf *= min(1.0, duration / 20.0)
747
- visual = max((f.get("visual_score", 0.0) for f in frags), default=0.0)
748
- return {**region, "confidence": round(w_conf, 3), "visual_score": round(visual, 3)}
749
-
750
-
751
- # ── Stage 7: precise re-transcription (confidence-gated) ──────────────────────
752
-
753
- def retranscribe_region(audio: np.ndarray, region: dict) -> str:
754
- """Slice the in-memory waveform (no per-region ffmpeg) and run precise ASR."""
755
- s = max(0, int(region["start"] * SAMPLE_RATE))
756
- e = min(len(audio), int(region["end"] * SAMPLE_RATE))
757
- clip = audio[s:e]
758
- if len(clip) < SAMPLE_RATE * 0.2: # < 0.2s → nothing to gain
759
- return region.get("text", "")
760
- model = get_whisper_precise()
761
- segments_gen, _ = model.transcribe(clip, beam_size=1)
762
- return " ".join(seg.text.strip() for seg in segments_gen).strip()
763
-
764
-
765
- def fill_precise(audio: np.ndarray, regions: list[dict], all_chunks: list[dict],
766
- precise_cache: dict, budget: int) -> int:
767
- """
768
- Ensure every region has `precise_text`. A sector is turbo-refined ONLY when:
769
- • it is not already cached, AND
770
- • the base pass for that sector was low-confidence (avg_logprob < gate), AND
771
- • we are still within `budget` NEW transcriptions this call.
772
- Clean/high-confidence sectors keep the (already accurate) base text for free,
773
- so on clean audio the slow turbo model never runs. `precise_cache` persists
774
- per video, so later prompts reuse earlier work. Returns remaining budget.
775
- """
776
- reused = new = skipped = 0
777
- for region in regions:
778
- # the chunk sectors this region spans (chunks are non-overlapping)
779
- comp = [c for c in all_chunks
780
- if c["start"] < region["end"] - 1e-3 and c["end"] > region["start"] + 1e-3]
781
- if not comp:
782
- comp = [region]
783
-
784
- for ch in comp:
785
- key = round(ch["start"], 2)
786
- if key in precise_cache:
787
- reused += 1
788
- continue
789
- weak = ch.get("logprob", 0.0) < PRECISE_LOGPROB_GATE
790
- if not weak:
791
- skipped += 1 # base was confident → trust it
792
- continue
793
- if budget <= 0:
794
- continue # over budget → fall back to fast text
795
- print(f"[NINA] Re-transcribing weak sector "
796
- f"[{fmt_time(ch['start'])} → {fmt_time(ch['end'])}] "
797
- f"(logprob {ch.get('logprob', 0.0):.2f})")
798
- precise_cache[key] = retranscribe_region(audio, ch)
799
- if DEBUG:
800
- snip = precise_cache[key]
801
- print(f"[DEBUG] Precise sector [{fmt_time(ch['start'])}→{fmt_time(ch['end'])}]: "
802
- f"{snip[:200]}{'…' if len(snip) > 200 else ''}")
803
- new += 1
804
- budget -= 1
805
-
806
- region["precise_text"] = " ".join(
807
- (precise_cache.get(round(ch["start"], 2)) or ch.get("text", ""))
808
- for ch in comp
809
- ).strip() or region.get("text", "")
810
-
811
- print(f"[NINA] Precise sectors — {new} refined, {reused} cached, {skipped} trusted (base).")
812
- return budget
813
-
814
-
815
- # ── Stage 8: synthesis ─────────────────────────────────────────────────────────
816
-
817
- # ── Output sizing — inferred from the PROMPT (no slider) ─────────────────────────
818
-
819
- _BRIEF_CUES = (
820
- "brief", "briefly", "short", "shortly", "quick", "quickly", "concise",
821
- "in a sentence", "one sentence", "one-liner", "tl;dr", "tldr",
822
- "krótko", "w skrócie", "zwięźle", "jednym zdaniem", "w jednym zdaniu",
823
- )
824
- _DETAIL_CUES = (
825
- "in detail", "detailed", "in-depth", "in depth", "thorough", "thoroughly",
826
- "comprehensive", "exhaustive", "everything", "full summary", "elaborate",
827
- "step by step", "step-by-step", "deep dive", "as much as possible",
828
- "szczegółowo", "dokładnie", "wyczerpująco", "wszystko", "krok po kroku",
829
- "dogłębnie", "obszernie",
830
- )
831
- _FACTUAL_START = re.compile(
832
- r'^\s*(what|who|whom|whose|when|where|which|how many|how much|how long|'
833
- r'is|are|was|were|does|do|did|can|could|will|would|'
834
- r'czy|kiedy|kto|kogo|gdzie|ile|jaki|jaka|jakie|który|która|które)\b',
835
- re.IGNORECASE,
836
- )
837
-
838
- def _summary_tier(max_words: int) -> str:
839
- """Human-readable label for the chosen output length."""
840
- if max_words <= 60: return "brief / one-liner"
841
- if max_words <= 110: return "short"
842
- if max_words <= 250: return "standard"
843
- if max_words <= 400: return "detailed"
844
- return "exhaustive"
845
-
846
-
847
- def _prompt_to_words(prompt: str) -> int:
848
- """
849
- Infer the answer's word budget from the prompt itself (replaces the slider):
850
- - explicit brevity cues → ~40 words
851
- - explicit detail cues → ~450 words
852
- - factual wh-/yes-no Q → ~80 words
853
- - otherwise scale gently with prompt length (longer ask → longer answer)
854
- Clamped to [30, 500].
855
- """
856
- p = prompt.lower()
857
- if any(c in p for c in _DETAIL_CUES):
858
- base, reason = 450, "explicit detail cue"
859
- elif any(c in p for c in _BRIEF_CUES):
860
- base, reason = 40, "explicit brevity cue"
861
- elif _FACTUAL_START.match(p):
862
- base, reason = 80, "factual question"
863
- else:
864
- n_words = len(re.findall(r'\w+', p))
865
- base, reason = 120 + min(180, n_words * 8), f"length-scaled ({n_words} prompt words)"
866
-
867
- out = int(max(30, min(500, base)))
868
- if DEBUG:
869
- print(f"[DEBUG] Summary sizing: {reason} → {out} words [{_summary_tier(out)}]")
870
- return out
871
-
872
-
873
- def _words_to_global_chunks(max_words: int) -> int:
874
- """More requested words → sample more chunks for the global overview."""
875
- return max(3, min(GLOBAL_MAX_CHUNKS, round(max_words / 40)))
876
-
877
-
878
- def _fallback_summary(regions: list[dict]) -> str:
879
- snippets = [
880
- f"[{fmt_time(r['start'])}] {r.get('precise_text', r['text'])[:200]}"
881
- for r in regions[:2]
882
- ]
883
- return "(LLM unavailable — raw excerpts:)\n" + "\n".join(snippets)
884
-
885
-
886
- def _build_synth_prompt(regions: list[dict], prompt: str,
887
- max_words: int, mode: str) -> str:
888
- # Each fragment carries BOTH modalities: what is SAID (audio) and what is
889
- # SHOWN (CLIP visual cues). The LLM is asked to fuse them.
890
- blocks = []
891
- for r in regions:
892
- spoken = (r.get("precise_text", r["text"]) or "").strip()
893
- tags = r.get("visual_tags", [])
894
- block = (f"[{fmt_time(r['start'])} → {fmt_time(r['end'])}]\n"
895
- f" Spoken (audio): {spoken or '(no speech)'}")
896
- if tags:
897
- block += f"\n On screen (video): {', '.join(tags)}"
898
- blocks.append(block)
899
- fragments = "\n\n".join(blocks)
900
-
901
- if mode == "global":
902
- task_line = "Task: Give a complete overview of what this video is about."
903
- else:
904
- task_line = f'Task: Summarize what the video says/shows about "{prompt}".'
905
-
906
- return (
907
- f"You are analyzing a video. Each fragment below contains what is SPOKEN "
908
- f"(audio transcript) and what is SHOWN (visual cues detected in the frames).\n"
909
- f'The user is looking for: "{prompt}"\n\n'
910
- f"Fragments:\n\n{fragments}\n\n"
911
- f"{task_line}\n\n"
912
- f"Output format:\n"
913
- f"- Combine BOTH the spoken content and the on-screen visuals into one coherent answer\n"
914
- f"- After each statement, append the timestamp it came from, taken from the "
915
- f"bracketed start time of the relevant fragment above (use that exact value)\n"
916
- f"- Maximum {max_words} words total\n"
917
- f"- IMPORTANT: Write in the same language as the prompt given by the user\n"
918
- f"- Only use information from the fragments (audio + visual) — do not invent details\n"
919
- f"- If fragments contain no real information about the topic, say so clearly, "
920
- f"without further explanation\n"
921
- )
922
-
923
-
924
- def llm_synthesize_stream(regions: list[dict], prompt: str,
925
- max_words: int = 150, mode: str = "specific"):
926
- """
927
- Generator: yields the answer incrementally as the LLM streams tokens.
928
- On any error, yields a single fallback string.
929
- """
930
- if not regions:
931
- yield "(No relevant regions to summarize.)"
932
- return
933
-
934
- synth_prompt = _build_synth_prompt(regions, prompt, max_words, mode)
935
-
936
- if DEBUG:
937
- print(f"[DEBUG] Synthesis [{mode}] — {len(regions)} region(s), "
938
- f"max_words={max_words} [{_summary_tier(max_words)}].")
939
-
940
- try:
941
- acc = ""
942
- stream = llm_client.chat_completion(
943
- model=LLM_MODEL,
944
- messages=[{"role": "user", "content": synth_prompt}],
945
- max_tokens=LLM_MAX_TOKENS,
946
- temperature=0.3,
947
- stream=True,
948
- )
949
- for ev in stream:
950
- delta = ev.choices[0].delta.content or ""
951
- if delta:
952
- acc += delta
953
- yield acc.strip()
954
- if not acc.strip():
955
- yield _fallback_summary(regions)
956
- except Exception as e:
957
- print(f"[NINA] Synthesis error: {e}")
958
- yield _fallback_summary(regions)
959
-
960
-
961
- def llm_synthesize(regions: list[dict], prompt: str,
962
- max_words: int = 150, mode: str = "specific") -> str:
963
- """Non-streaming convenience wrapper (kept for API compatibility / testing)."""
964
- out = ""
965
- for out in llm_synthesize_stream(regions, prompt, max_words, mode):
966
- pass
967
- return out
968
-
969
-
970
- # ── Helpers ────────────────────────────────────────────────────────────────────
971
-
972
- def _build_chunk(segs: list[dict], embs: list[np.ndarray]) -> dict:
973
- total = sum(max(s["end"] - s["start"], 0.1) for s in segs)
974
- logp = sum(s.get("logprob", 0.0) * max(s["end"] - s["start"], 0.1)
975
- for s in segs) / total # duration-weighted base confidence
976
- return {"text": " ".join(s["text"] for s in segs),
977
- "start": segs[0]["start"],
978
- "end": segs[-1]["end"],
979
- "logprob": round(logp, 3),
980
- "emb": np.mean(np.stack(embs), axis=0)} # cached chunk embedding
981
-
982
- def _cosine(a: np.ndarray, b: np.ndarray) -> float:
983
- return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-9))
984
-
985
- def _sigmoid(x: float) -> float:
986
- return 1.0 / (1.0 + math.exp(-float(x)))
987
-
988
- def fmt_time(s: float) -> str:
989
- m = int(s) // 60
990
- return f"{m}:{s % 60:05.2f}"
991
-
992
- def conf_bar(c: float) -> str:
993
- f = round(c * 10)
994
- return "█" * f + "░" * (10 - f)
995
-
996
-
997
- # ── Persistent disk cache ────────────────────────────────────────────────────────
998
- # Keyed by a content fingerprint (size + head + tail bytes), so the same video
999
- # re-uploaded to a fresh temp path — or opened after a restart — is recognised
1000
- # and its transcript / embeddings / precise sectors are loaded instead of
1001
- # recomputed. Best-effort: any failure silently falls back to recomputation.
1002
-
1003
- def _fingerprint(path: str) -> str:
1004
- h = hashlib.sha1()
1005
- st = os.stat(path)
1006
- h.update(str(st.st_size).encode())
1007
- with open(path, "rb") as f:
1008
- h.update(f.read(1 << 20)) # first 1 MB
1009
- if st.st_size > (1 << 20):
1010
- f.seek(-(1 << 20), os.SEEK_END)
1011
- h.update(f.read(1 << 20)) # last 1 MB
1012
- return h.hexdigest()[:16]
1013
-
1014
-
1015
- def _disk_load(fp: str) -> dict | None:
1016
- if not DISK_CACHE:
1017
- return None
1018
- d = os.path.join(CACHE_DIR, fp)
1019
- try:
1020
- with open(os.path.join(d, "meta.json"), encoding="utf-8") as f:
1021
- meta = json.load(f)
1022
- arr = np.load(os.path.join(d, "emb.npz"))
1023
- chunk_emb = arr["chunk_emb"]
1024
- chunks = []
1025
- for i, c in enumerate(meta["chunks"]):
1026
- chunks.append({
1027
- "text": c["text"], "start": c["start"], "end": c["end"],
1028
- "logprob": c.get("logprob", 0.0),
1029
- "entities": set(c.get("entities", [])),
1030
- "emb": chunk_emb[i],
1031
- })
1032
- visual = {"emb": arr["visual_emb"], "time": arr["visual_time"]}
1033
- print(f"[NINA] Disk cache hit ({fp}) — loaded {len(chunks)} chunks.")
1034
- return {"segments": meta["segments"], "chunks": chunks,
1035
- "visual": visual, "precise": {float(k): v for k, v in meta["precise"].items()}}
1036
- except Exception:
1037
- return None
1038
-
1039
-
1040
- def _disk_save(fp: str, entry: dict) -> None:
1041
- if not DISK_CACHE:
1042
- return
1043
- d = os.path.join(CACHE_DIR, fp)
1044
- try:
1045
- os.makedirs(d, exist_ok=True)
1046
- chunks = entry["chunks"]
1047
- meta = {
1048
- "segments": entry["segments"],
1049
- "precise": entry["precise"],
1050
- "chunks": [{"text": c["text"], "start": c["start"], "end": c["end"],
1051
- "logprob": c.get("logprob", 0.0),
1052
- "entities": sorted(c.get("entities", []))}
1053
- for c in chunks],
1054
- }
1055
- chunk_emb = (np.stack([c["emb"] for c in chunks]) if chunks
1056
- else np.zeros((0, 384), dtype=np.float32))
1057
- with open(os.path.join(d, "meta.json"), "w", encoding="utf-8") as f:
1058
- json.dump(meta, f)
1059
- np.savez(os.path.join(d, "emb.npz"),
1060
- chunk_emb=chunk_emb,
1061
- visual_emb=entry["visual"]["emb"],
1062
- visual_time=entry["visual"]["time"])
1063
- except Exception as e:
1064
- if DEBUG:
1065
- print(f"[DEBUG] disk cache save failed: {e}")
1066
-
1067
-
1068
- def _disk_update_precise(fp: str, precise: dict) -> None:
1069
- """Persist newly-refined precise sectors without rewriting embeddings."""
1070
- if not DISK_CACHE:
1071
- return
1072
- p = os.path.join(CACHE_DIR, fp, "meta.json")
1073
- try:
1074
- with open(p, encoding="utf-8") as f:
1075
- meta = json.load(f)
1076
- meta["precise"] = precise
1077
- with open(p, "w", encoding="utf-8") as f:
1078
- json.dump(meta, f)
1079
- except Exception:
1080
- pass
1081
-
1082
-
1083
- # ── Formatter ──────────────────────────────────────────────────────────────────
1084
-
1085
- def format_output(regions: list[dict], prompt: str, summary: str,
1086
- mode: str = "specific") -> str:
1087
- if not regions:
1088
- return (
1089
- f' Topic not found in this video.\n\n'
1090
- f' Prompt : "{prompt}"\n\n'
1091
- f' No relevant segments found.\n'
1092
- f' Try a broader or differently worded prompt.'
1093
- )
1094
-
1095
- mode_tag = {"global": "🌐 global", "hybrid": "⚡ hybrid", "specific": "🎯 specific"}.get(mode, "")
1096
- lines = [f' {len(regions)} region(s) found for: "{prompt}" [{mode_tag} · audio+video]\n']
1097
-
1098
- if DEBUG:
1099
- for i, r in enumerate(regions, 1):
1100
- dur = round(r["end"] - r["start"], 1)
1101
- text = r.get("precise_text", r["text"])
1102
- ent = r.get("entity_overlap", 0)
1103
- bi = r.get("bi_score", 0)
1104
- vis = r.get("visual_score", 0)
1105
- tags = ", ".join(r.get("visual_tags", []))
1106
- lines += [
1107
- f'\n [{i}] {fmt_time(r["start"])} → {fmt_time(r["end"])} ({dur}s)',
1108
- f' {conf_bar(r["confidence"])} {r["confidence"]:.0%} '
1109
- f'(embed {bi:.0%} · entity {ent:.0%} · visual {vis:.0%})',
1110
- f' 👁 {tags}' if tags else ' 👁 (no visual tags)',
1111
- f' "{text[:220]}{"…" if len(text) > 220 else ""}"',
1112
- ]
1113
-
1114
- lines += [
1115
- f' 🧠 Based on uploaded video (audio + video): — "{prompt}"',
1116
- summary,
1117
- f'\n Sources: ' + ', '.join(
1118
- f'[{fmt_time(r["start"])} → {fmt_time(r["end"])}]' for r in regions
1119
- ),
1120
- ]
1121
- return "\n".join(lines)
1122
-
1123
-
1124
- # ── Cold-start ingestion (transcription + chunking + CLIP, in parallel) ───────────
1125
-
1126
- def ingest_video(video_path: str) -> dict:
1127
- """
1128
- First sight of a video: decode audio, then run the two heavy independent
1129
- stages concurrently —
1130
- • CPU thread : base transcription → semantic chunking → entities
1131
- • MPS thread : frame extraction → CLIP encoding
1132
- Returns the cache entry dict.
1133
- """
1134
- audio = load_audio(video_path)
1135
- duration = media_duration(video_path) or (len(audio) / SAMPLE_RATE)
1136
-
1137
- result = {}
1138
-
1139
- def _audio_branch():
1140
- segments = transcribe_fast(audio)
1141
- result["segments"] = segments
1142
- if segments:
1143
- result["chunks"] = add_entities_to_chunks(semantic_chunk(segments))
1144
- else:
1145
- result["chunks"] = []
1146
-
1147
- def _visual_branch():
1148
- result["visual"] = analyze_visual(video_path, duration)
1149
-
1150
- with ThreadPoolExecutor(max_workers=2) as ex:
1151
- fa = ex.submit(_audio_branch)
1152
- fv = ex.submit(_visual_branch)
1153
- fa.result()
1154
- fv.result()
1155
-
1156
- return {
1157
- "segments": result["segments"],
1158
- "chunks": result["chunks"],
1159
- "visual": result["visual"],
1160
- "audio": audio,
1161
- "precise": {},
1162
- }
1163
-
1164
-
1165
- # ── Global path (shared by GLOBAL mode + every escalation/fallback) ───────────────
1166
- # Global summaries run on the clean base transcript — no whole-video turbo pass.
1167
-
1168
- def _run_global(chunks: list[dict], visual: dict,
1169
- prompt: str, max_words: int) -> list[dict]:
1170
- sampled = sample_chunks_for_global(chunks, _words_to_global_chunks(max_words))
1171
- print(f"[NINA] Global mode — sampled {len(sampled)} chunks evenly (base transcript).")
1172
- for c in sampled:
1173
- c.setdefault("confidence", 0.5)
1174
- c.setdefault("bi_score", 0.0)
1175
- c.setdefault("entity_overlap", 0.0)
1176
- c.setdefault("visual_score", 0.0)
1177
- c["precise_text"] = c.get("text", "") # base text is enough for an overview
1178
- return add_visual_tags(sampled, visual)
1179
-
1180
-
1181
- # ── Main pipeline (generator: streams progress + answer) ─────────────────────────
1182
-
1183
- def run(video_path: str, prompt: str):
1184
- if video_path is None:
1185
- yield "Please upload a video."
1186
- return
1187
- if not prompt or not prompt.strip():
1188
- yield "Please enter a prompt."
1189
- return
1190
-
1191
- prompt = prompt.strip()
1192
- max_words = _prompt_to_words(prompt) # output size inferred from the prompt
1193
- print(f'\n[NINA] ── New request ── "{prompt}" (target ≈ {max_words} words)')
1194
- _evict_stale() # drop idle sessions / stale disk cache
1195
-
1196
- # Stage 1–3: transcription + chunking + CLIP visual (cached per video)
1197
- fp = None
1198
- if video_path in _cache:
1199
- print(f"[NINA] Cache hit (memory) — skipping transcription + CLIP.")
1200
- entry = _cache[video_path]
1201
- else:
1202
- try:
1203
- fp = _fingerprint(video_path)
1204
- except Exception:
1205
- fp = None
1206
-
1207
- disk = _disk_load(fp) if fp else None
1208
- if disk is not None:
1209
- disk["audio"] = load_audio(video_path)
1210
- entry = disk
1211
- _cache[video_path] = entry
1212
- else:
1213
- yield "🎬 Reading video — transcribing audio and scanning frames…"
1214
- entry = ingest_video(video_path)
1215
- if not entry["segments"]:
1216
- yield "No speech detected."
1217
- return
1218
- _cache[video_path] = entry
1219
- if fp:
1220
- _disk_save(fp, entry)
1221
- print(f"[NINA] Cached transcript + visuals for this video.")
1222
-
1223
- entry["_atime"] = time.time() # mark recently used (keeps many-prompt sessions alive)
1224
- segments = entry["segments"]
1225
- chunks = entry["chunks"]
1226
- visual = entry["visual"]
1227
- precise_cache = entry["precise"]
1228
- audio = entry["audio"]
1229
- if fp is None and video_path not in (None,):
1230
- try:
1231
- fp = _fingerprint(video_path)
1232
- except Exception:
1233
- fp = None
1234
-
1235
- if not chunks:
1236
- yield "No speech detected."
1237
- return
1238
-
1239
- # ── Query routing (pass 1: pattern-based) ─────────────────────────────────
1240
- mode = classify_query(prompt)
1241
- print(f"[NINA] Query mode (pass 1): {mode}")
1242
-
1243
- # ── GLOBAL mode ───────────────────────────────────────────────────────────
1244
- if mode == "global":
1245
- regions = _run_global(chunks, visual, prompt, max_words)
1246
- yield from _synthesize_streaming(regions, prompt, max_words, "global")
1247
- print(f"[NINA] Done — {len(regions)} region(s) [global].")
1248
- return
1249
-
1250
- # ── SPECIFIC / HYBRID: run retrieval (audio) + visual relevance ───────────
1251
- candidates, best_bi = bi_encode_retrieve(chunks, prompt)
1252
- _, v_norm = visual_scores(visual, prompt) # CLIP prompt↔frames
1253
-
1254
- # Pass 2 routing: upgrade based on actual bi-score
1255
- if best_bi < BI_SCORE_GLOBAL_FLOOR:
1256
- print(f"[NINA] bi-score {best_bi:.3f} below floor → escalating to global.")
1257
- regions = _run_global(chunks, visual, prompt, max_words)
1258
- yield from _synthesize_streaming(regions, prompt, max_words, "global")
1259
- print(f"[NINA] Done — {len(regions)} region(s) [escalated global].")
1260
- return
1261
- elif best_bi < BI_SCORE_HYBRID_FLOOR:
1262
- mode = "hybrid"
1263
-
1264
- print(f"[NINA] Query mode (pass 2): {mode} bi={best_bi:.3f}")
1265
-
1266
- # Stage 5: cross-encoder + entity overlap + visual fusion → top-10
1267
- results = rerank_and_score(candidates, prompt, visual["time"], v_norm)
1268
-
1269
- # hybrid: pad with neighbouring chunks for context
1270
- if mode == "hybrid":
1271
- results = pad_with_neighbours(results, chunks)
1272
-
1273
- # Stage 6: merge adjacent regions
1274
- regions = merge_regions(results)
1275
- if not regions:
1276
- print(f"[NINA] No regions after merge → falling back to global.")
1277
- regions = _run_global(chunks, visual, prompt, max_words)
1278
- yield from _synthesize_streaming(regions, prompt, max_words, "global")
1279
- return
1280
-
1281
- # Stage 7: precise re-transcription (confidence-gated, cache-aware)
1282
- before = dict(precise_cache)
1283
- fill_precise(audio, regions, chunks, precise_cache, RETRANSCRIBE_MAX)
1284
- if fp and precise_cache != before:
1285
- _disk_update_precise(fp, precise_cache)
1286
-
1287
- # Stage 7b: attach CLIP visual tags to each region
1288
- regions = add_visual_tags(regions, visual)
1289
-
1290
- # Stage 8: LLM synthesis (audio + visual) — streamed
1291
- yield from _synthesize_streaming(regions, prompt, max_words, mode)
1292
- print(f"[NINA] Done — {len(regions)} region(s) [{mode}].")
1293
-
1294
-
1295
- def _synthesize_streaming(regions: list[dict], prompt: str, max_words: int, mode: str):
1296
- """Stream the formatted answer to the UI as the LLM produces it."""
1297
- print(f"[NINA] Running synthesis [{mode}]...")
1298
- yield format_output(regions, prompt, "✍️ …", mode)
1299
- last = ""
1300
- for partial in llm_synthesize_stream(regions, prompt, max_words, mode):
1301
- last = partial
1302
- yield format_output(regions, prompt, partial, mode)
1303
- if not last:
1304
- yield format_output(regions, prompt, _fallback_summary(regions), mode)
1305
-
1306
-
1307
- # ── Gradio UI ──────────────────────────────────────────────────────────────────
1308
 
1309
  demo = gr.Interface(
1310
  fn=run,
@@ -1315,19 +17,24 @@ demo = gr.Interface(
1315
  placeholder='e.g. "What does the video say about...?" '
1316
  '(add "briefly" or "in detail" to size the answer)',
1317
  ),
 
1318
  ],
1319
  outputs=gr.Textbox(label="Results", lines=38),
1320
- title="NINA v0.80 — Multimodal Video Search (audio + video via CLIP)",
1321
  description=(
1322
  "video -> a bit of magic (speech + vision) -> summary. "
1323
- "Answer length adapts to your prompt."
 
1324
  ),
1325
  flagging_mode="never",
1326
- # Privacy: Gradio purges uploaded files older than 5 min, every 5 min. One
1327
- # upload still serves many prompts (audio/transcript are cached in RAM), and
1328
- # the file is cleaned shortly after the session goes idle.
1329
  delete_cache=(300, 300),
1330
  )
1331
 
 
 
 
 
 
1332
  if __name__ == "__main__":
1333
  demo.launch()
 
1
  # ─────────────────────────────────────────────
2
  # NINA — Neural Information & Narrative Abstraction
3
+ # app.py | v0.81 | Made by Malina
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  # ─────────────────────────────────────────────
5
 
6
  import os
 
 
 
 
 
 
 
 
 
 
 
7
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ from pipeline import run
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  demo = gr.Interface(
12
  fn=run,
 
17
  placeholder='e.g. "What does the video say about...?" '
18
  '(add "briefly" or "in detail" to size the answer)',
19
  ),
20
+ gr.Textbox(label="access token (set automatically by the website)", value=""),
21
  ],
22
  outputs=gr.Textbox(label="Results", lines=38),
23
+ title="NINA v0.81 — Multimodal Video Search (audio + video via CLIP)",
24
  description=(
25
  "video -> a bit of magic (speech + vision) -> summary. "
26
+ "Answer length adapts to your prompt. "
27
+ "Use it at https://app.nnlabs.pl/nina."
28
  ),
29
  flagging_mode="never",
30
+ # Privacy: purge uploaded files older than 5 min, every 5 min.
 
 
31
  delete_cache=(300, 300),
32
  )
33
 
34
+ demo.queue(
35
+ default_concurrency_limit=int(os.getenv("NINA_CONCURRENCY", "3")),
36
+ max_size=int(os.getenv("NINA_QUEUE_MAX", "40")),
37
+ )
38
+
39
  if __name__ == "__main__":
40
  demo.launch()
audio.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import ffmpeg
3
+ from faster_whisper.audio import decode_audio
4
+
5
+ from config import (
6
+ DEBUG, PRECISE_LOGPROB_GATE, RETRANSCRIBE_MAX, SAMPLE_RATE,
7
+ )
8
+ from models import get_whisper_precise, whisper_fast
9
+ from utils import fmt_time
10
+
11
+
12
+ def load_audio(media_path: str) -> np.ndarray:
13
+ """Decode any container to float32 mono 16 kHz waveform (PyAV, no temp file)."""
14
+ return decode_audio(media_path, sampling_rate=SAMPLE_RATE)
15
+
16
+
17
+ def media_duration(media_path: str) -> float:
18
+ try:
19
+ info = ffmpeg.probe(media_path)
20
+ return float(info["format"]["duration"])
21
+ except Exception:
22
+ return 0.0
23
+
24
+
25
+ def transcribe_fast(audio: np.ndarray) -> list[dict]:
26
+ """Base-model full-video pass: greedy + Silero VAD, stores avg_logprob per segment."""
27
+ segments_gen, _ = whisper_fast.transcribe(
28
+ audio, beam_size=1, vad_filter=True, word_timestamps=False,
29
+ )
30
+ return [
31
+ {
32
+ "text": seg.text.strip(),
33
+ "start": round(seg.start, 2),
34
+ "end": round(seg.end, 2),
35
+ "logprob": round(float(getattr(seg, "avg_logprob", 0.0) or 0.0), 3),
36
+ }
37
+ for seg in segments_gen
38
+ if seg.text.strip()
39
+ ]
40
+
41
+
42
+ def retranscribe_region(audio: np.ndarray, region: dict) -> str:
43
+ """Slice waveform in-memory and run precise Whisper on the slice."""
44
+ s = max(0, int(region["start"] * SAMPLE_RATE))
45
+ e = min(len(audio), int(region["end"] * SAMPLE_RATE))
46
+ clip = audio[s:e]
47
+ if len(clip) < SAMPLE_RATE * 0.2:
48
+ return region.get("text", "")
49
+ model = get_whisper_precise()
50
+ segments_gen, _ = model.transcribe(clip, beam_size=1)
51
+ return " ".join(seg.text.strip() for seg in segments_gen).strip()
52
+
53
+
54
+ def fill_precise(
55
+ audio: np.ndarray,
56
+ regions: list[dict],
57
+ all_chunks: list[dict],
58
+ precise_cache: dict,
59
+ budget: int,
60
+ ) -> int:
61
+ """
62
+ Ensure every region has `precise_text`. A sector is turbo-refined only when:
63
+ • not already cached, AND
64
+ • base avg_logprob is below PRECISE_LOGPROB_GATE (weak ASR), AND
65
+ • still within budget.
66
+ Returns remaining budget.
67
+ """
68
+ reused = new = skipped = 0
69
+ for region in regions:
70
+ comp = [
71
+ c for c in all_chunks
72
+ if c["start"] < region["end"] - 1e-3 and c["end"] > region["start"] + 1e-3
73
+ ]
74
+ if not comp:
75
+ comp = [region]
76
+
77
+ for ch in comp:
78
+ key = round(ch["start"], 2)
79
+ if key in precise_cache:
80
+ reused += 1
81
+ continue
82
+ weak = ch.get("logprob", 0.0) < PRECISE_LOGPROB_GATE
83
+ if not weak:
84
+ skipped += 1
85
+ continue
86
+ if budget <= 0:
87
+ continue
88
+ print(
89
+ f"[NINA] Re-transcribing weak sector "
90
+ f"[{fmt_time(ch['start'])} → {fmt_time(ch['end'])}] "
91
+ f"(logprob {ch.get('logprob', 0.0):.2f})"
92
+ )
93
+ precise_cache[key] = retranscribe_region(audio, ch)
94
+ if DEBUG:
95
+ snip = precise_cache[key]
96
+ print(
97
+ f"[DEBUG] Precise sector [{fmt_time(ch['start'])}→{fmt_time(ch['end'])}]: "
98
+ f"{snip[:200]}{'…' if len(snip) > 200 else ''}"
99
+ )
100
+ new += 1
101
+ budget -= 1
102
+
103
+ region["precise_text"] = " ".join(
104
+ (precise_cache.get(round(ch["start"], 2)) or ch.get("text", ""))
105
+ for ch in comp
106
+ ).strip() or region.get("text", "")
107
+
108
+ print(f"[NINA] Precise sectors — {new} refined, {reused} cached, {skipped} trusted (base).")
109
+ return budget
auth.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import hashlib
3
+ import hmac
4
+ import json
5
+ import threading
6
+ import time
7
+
8
+ from config import SIGNING_SECRET
9
+
10
+ _used_jti: dict = {}
11
+ _jti_lock = threading.Lock()
12
+
13
+
14
+ def _b64url_decode(s: str) -> bytes:
15
+ return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
16
+
17
+
18
+ def _b64url_encode(b: bytes) -> str:
19
+ return base64.urlsafe_b64encode(b).decode().rstrip("=")
20
+
21
+
22
+ def verify_usage_token(token: str) -> bool:
23
+ if not SIGNING_SECRET:
24
+ return True
25
+ if not token or "." not in token:
26
+ return False
27
+ try:
28
+ msg, sig = token.split(".", 1)
29
+ expected = _b64url_encode(
30
+ hmac.new(SIGNING_SECRET.encode(), msg.encode(), hashlib.sha256).digest()
31
+ )
32
+ if not hmac.compare_digest(expected, sig):
33
+ return False
34
+ payload = json.loads(_b64url_decode(msg))
35
+ now = int(time.time())
36
+ if int(payload.get("e", 0)) < now:
37
+ return False
38
+ jti = payload.get("j", "")
39
+ if not jti:
40
+ return False
41
+ with _jti_lock:
42
+ for k in [k for k, e in _used_jti.items() if e < now]:
43
+ _used_jti.pop(k, None)
44
+ if jti in _used_jti:
45
+ return False
46
+ _used_jti[jti] = int(payload.get("e", now + 120))
47
+ return True
48
+ except Exception:
49
+ return False
cache.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import shutil
4
+ import time
5
+
6
+ import numpy as np
7
+
8
+ from config import CACHE_DIR, CACHE_DISK_TTL, CACHE_IDLE_TTL, DEBUG, DISK_CACHE
9
+
10
+ # { video_path: {"segments","chunks","visual","audio","precise","_atime"} }
11
+ _cache: dict = {}
12
+
13
+
14
+ def evict_stale() -> None:
15
+ now = time.time()
16
+ for vp in [k for k, e in _cache.items() if now - e.get("_atime", now) > CACHE_IDLE_TTL]:
17
+ _cache.pop(vp, None)
18
+ try:
19
+ if os.path.isdir(CACHE_DIR):
20
+ for name in os.listdir(CACHE_DIR):
21
+ d = os.path.join(CACHE_DIR, name)
22
+ if os.path.isdir(d) and now - os.path.getmtime(d) > CACHE_DISK_TTL:
23
+ shutil.rmtree(d, ignore_errors=True)
24
+ except Exception:
25
+ pass
26
+
27
+
28
+ def fingerprint(path: str) -> str:
29
+ import hashlib
30
+ h = hashlib.sha1()
31
+ st = os.stat(path)
32
+ h.update(str(st.st_size).encode())
33
+ with open(path, "rb") as f:
34
+ h.update(f.read(1 << 20))
35
+ if st.st_size > (1 << 20):
36
+ f.seek(-(1 << 20), os.SEEK_END)
37
+ h.update(f.read(1 << 20))
38
+ return h.hexdigest()[:16]
39
+
40
+
41
+ def disk_load(fp: str) -> dict | None:
42
+ if not DISK_CACHE:
43
+ return None
44
+ d = os.path.join(CACHE_DIR, fp)
45
+ try:
46
+ with open(os.path.join(d, "meta.json"), encoding="utf-8") as f:
47
+ meta = json.load(f)
48
+ arr = np.load(os.path.join(d, "emb.npz"))
49
+ chunk_emb = arr["chunk_emb"]
50
+ chunks = []
51
+ for i, c in enumerate(meta["chunks"]):
52
+ chunks.append({
53
+ "text": c["text"],
54
+ "start": c["start"],
55
+ "end": c["end"],
56
+ "logprob": c.get("logprob", 0.0),
57
+ "entities": set(c.get("entities", [])),
58
+ "emb": chunk_emb[i],
59
+ })
60
+ visual = {"emb": arr["visual_emb"], "time": arr["visual_time"]}
61
+ print(f"[NINA] Disk cache hit ({fp}) — loaded {len(chunks)} chunks.")
62
+ return {
63
+ "segments": meta["segments"],
64
+ "chunks": chunks,
65
+ "visual": visual,
66
+ "precise": {float(k): v for k, v in meta["precise"].items()},
67
+ }
68
+ except Exception:
69
+ return None
70
+
71
+
72
+ def disk_save(fp: str, entry: dict) -> None:
73
+ if not DISK_CACHE:
74
+ return
75
+ d = os.path.join(CACHE_DIR, fp)
76
+ try:
77
+ os.makedirs(d, exist_ok=True)
78
+ chunks = entry["chunks"]
79
+ meta = {
80
+ "segments": entry["segments"],
81
+ "precise": entry["precise"],
82
+ "chunks": [
83
+ {
84
+ "text": c["text"],
85
+ "start": c["start"],
86
+ "end": c["end"],
87
+ "logprob": c.get("logprob", 0.0),
88
+ "entities": sorted(c.get("entities", [])),
89
+ }
90
+ for c in chunks
91
+ ],
92
+ }
93
+ chunk_emb = (
94
+ np.stack([c["emb"] for c in chunks])
95
+ if chunks
96
+ else np.zeros((0, 384), dtype=np.float32)
97
+ )
98
+ with open(os.path.join(d, "meta.json"), "w", encoding="utf-8") as f:
99
+ json.dump(meta, f)
100
+ np.savez(
101
+ os.path.join(d, "emb.npz"),
102
+ chunk_emb=chunk_emb,
103
+ visual_emb=entry["visual"]["emb"],
104
+ visual_time=entry["visual"]["time"],
105
+ )
106
+ except Exception as e:
107
+ if DEBUG:
108
+ print(f"[DEBUG] disk cache save failed: {e}")
109
+
110
+
111
+ def disk_update_precise(fp: str, precise: dict) -> None:
112
+ if not DISK_CACHE:
113
+ return
114
+ p = os.path.join(CACHE_DIR, fp, "meta.json")
115
+ try:
116
+ with open(p, encoding="utf-8") as f:
117
+ meta = json.load(f)
118
+ meta["precise"] = precise
119
+ with open(p, "w", encoding="utf-8") as f:
120
+ json.dump(meta, f)
121
+ except Exception:
122
+ pass
config.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+
4
+ WHISPER_FAST = "base"
5
+ WHISPER_PRECISE = "large-v3-turbo"
6
+ SAMPLE_RATE = 16000
7
+ WHISPER_CPU_THREADS = int(os.getenv("WHISPER_CPU_THREADS", "3"))
8
+
9
+ RETRANSCRIBE_MAX = 12
10
+ PRECISE_LOGPROB_GATE = -0.55
11
+
12
+ CHUNK_SPLIT_THRESHOLD = 0.45
13
+ CHUNK_MIN_DURATION = 8.0
14
+ CHUNK_MAX_DURATION = 90.0
15
+ CHUNK_WINDOW = 5
16
+
17
+ BI_ENCODER_TOP_K = 100
18
+ CROSS_ENCODER_TOP_K = 10
19
+ RESULTS_TOP_N = 6
20
+ REGION_MIN_DURATION = 5.0
21
+ MERGE_GAP_SEC = 6.0
22
+
23
+ BI_SCORE_GLOBAL_FLOOR = 0.10
24
+ BI_SCORE_HYBRID_FLOOR = 0.28
25
+
26
+ GLOBAL_MAX_CHUNKS = 12
27
+
28
+ CLIP_MODEL = "clip-ViT-B-32"
29
+ CLIP_MAX_FRAMES = 96
30
+ CLIP_MIN_FPS = 0.1
31
+ CLIP_MAX_FPS = 0.5
32
+ CLIP_FRAME_SIZE = 224
33
+ VISUAL_WEIGHT = 0.30
34
+ VISUAL_TAGS_TOP_K = 4
35
+ VISUAL_TAG_MIN_SIM = 0.20
36
+
37
+ VISUAL_CONCEPTS = [
38
+ "a person talking to the camera", "a group of people", "a presentation with slides",
39
+ "a lecture or classroom", "an interview", "a news broadcast",
40
+ "a screen recording of software", "source code in a text editor",
41
+ "a webpage in a browser", "a chart or graph", "text on screen",
42
+ "a product demonstration", "hands demonstrating something",
43
+ "a cooking or food scene", "a kitchen", "an office", "a laboratory",
44
+ "a factory or machinery", "a construction site", "an outdoor nature landscape",
45
+ "a forest", "mountains", "a beach or ocean", "a city street",
46
+ "buildings and architecture", "a car or vehicle driving", "an airplane", "a train",
47
+ "a sports event", "people exercising", "a concert or live music",
48
+ "a video game gameplay", "an animation or cartoon", "a medical or hospital scene",
49
+ "a doctor or patient", "an animal", "a dog", "a cat", "a crowd of people",
50
+ "a map", "a whiteboard with diagrams", "a scientific diagram",
51
+ "a phone or mobile device", "a computer or laptop", "money or finance",
52
+ "a meeting or conference room", "a stage with a speaker",
53
+ "a dark scene at night", "a daytime scene",
54
+ ]
55
+
56
+ LLM_MODEL = "Qwen/Qwen2.5-7B-Instruct"
57
+ LLM_MAX_TOKENS = 600
58
+ LLM_TIMEOUT = 60
59
+
60
+ CACHE_DIR = os.path.join(tempfile.gettempdir(), "nina_cache")
61
+ DISK_CACHE = True
62
+
63
+ CACHE_IDLE_TTL = 1200
64
+ CACHE_DISK_TTL = 1800
65
+
66
+ DEBUG = False
67
+
68
+ SIGNING_SECRET = os.getenv("NINA_SIGNING_SECRET", "")
models.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import threading
3
+ import warnings
4
+
5
+ import numpy as np
6
+ from faster_whisper import WhisperModel
7
+ from huggingface_hub import InferenceClient
8
+ from sentence_transformers import SentenceTransformer, CrossEncoder
9
+
10
+ from config import (
11
+ CLIP_MODEL, LLM_TIMEOUT, LLM_MODEL,
12
+ VISUAL_CONCEPTS, WHISPER_CPU_THREADS, WHISPER_FAST, WHISPER_PRECISE,
13
+ )
14
+
15
+ warnings.filterwarnings("ignore", message="FP16 is not supported on CPU; using FP32 instead")
16
+
17
+
18
+ def _best_torch_device() -> str:
19
+ try:
20
+ import torch
21
+ if torch.cuda.is_available():
22
+ return "cuda"
23
+ if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
24
+ return "mps"
25
+ except Exception:
26
+ pass
27
+ return "cpu"
28
+
29
+
30
+ TORCH_DEVICE = _best_torch_device()
31
+
32
+ print(f"[NINA] Torch device: {TORCH_DEVICE} | Whisper: CPU int8 (x{WHISPER_CPU_THREADS})")
33
+
34
+ print("[NINA] Loading Whisper base (faster-whisper)...")
35
+ whisper_fast = WhisperModel(
36
+ WHISPER_FAST, device="cpu", compute_type="int8", cpu_threads=WHISPER_CPU_THREADS
37
+ )
38
+
39
+ # Bi-encoder stays on CPU: tiny (sub-100 ms), keeps MPS free for CLIP during parallel cold start.
40
+ print("[NINA] Loading bi-encoder...")
41
+ bi_encoder = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2", device="cpu")
42
+
43
+ print(f"[NINA] Loading cross-encoder ({TORCH_DEVICE})...")
44
+ cross_encoder = CrossEncoder(
45
+ "cross-encoder/mmarco-mMiniLMv2-L12-H384-v1", device=TORCH_DEVICE
46
+ )
47
+
48
+ HF_TOKEN = os.getenv("HF_TOKEN")
49
+ if not HF_TOKEN:
50
+ _token_file = os.path.expanduser("~/.cache/huggingface/token")
51
+ if os.path.exists(_token_file):
52
+ HF_TOKEN = open(_token_file).read().strip()
53
+
54
+ if HF_TOKEN:
55
+ print("[NINA] HF_TOKEN loaded — LLM calls enabled.")
56
+ else:
57
+ print("[NINA] HF_TOKEN not set — LLM calls will fail.")
58
+
59
+ llm_client = InferenceClient(token=HF_TOKEN, timeout=LLM_TIMEOUT)
60
+
61
+
62
+ # ── Lazy: precise Whisper ─────────────────────────────────────────────────────
63
+
64
+ _whisper_precise = None
65
+ _whisper_precise_lock = threading.Lock()
66
+
67
+
68
+ def get_whisper_precise() -> WhisperModel:
69
+ global _whisper_precise
70
+ with _whisper_precise_lock:
71
+ if _whisper_precise is None:
72
+ print(f"[NINA] Loading Whisper {WHISPER_PRECISE} (faster-whisper)...")
73
+ _whisper_precise = WhisperModel(
74
+ WHISPER_PRECISE, device="cpu", compute_type="int8",
75
+ cpu_threads=WHISPER_CPU_THREADS,
76
+ )
77
+ print(f"[NINA] Whisper {WHISPER_PRECISE} ready.")
78
+ return _whisper_precise
79
+
80
+
81
+ # ── Lazy: CLIP ────────────────────────────────────────────────────────────────
82
+
83
+ _clip_model = None
84
+ _clip_lock = threading.Lock()
85
+ _concept_embs = None
86
+ _concept_lock = threading.Lock()
87
+
88
+
89
+ def get_clip() -> SentenceTransformer:
90
+ global _clip_model
91
+ with _clip_lock:
92
+ if _clip_model is None:
93
+ print(f"[NINA] Loading CLIP ({CLIP_MODEL}, {TORCH_DEVICE})...")
94
+ _clip_model = SentenceTransformer(CLIP_MODEL, device=TORCH_DEVICE)
95
+ print("[NINA] CLIP ready.")
96
+ return _clip_model
97
+
98
+
99
+ def get_concept_embs() -> np.ndarray:
100
+ """Encode the zero-shot vocabulary once, L2-normalised."""
101
+ global _concept_embs
102
+ with _concept_lock:
103
+ if _concept_embs is None:
104
+ embs = get_clip().encode(
105
+ VISUAL_CONCEPTS, convert_to_numpy=True, show_progress_bar=False
106
+ )
107
+ _concept_embs = embs / (np.linalg.norm(embs, axis=1, keepdims=True) + 1e-9)
108
+ return _concept_embs
109
+
110
+
111
+ # Warm background
112
+ threading.Thread(target=get_whisper_precise, daemon=True).start()
113
+ threading.Thread(target=get_clip, daemon=True).start()
114
+ print(f"[NINA] Ready. ( {WHISPER_PRECISE} + CLIP warming up...)")
pipeline.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from concurrent.futures import ThreadPoolExecutor
3
+
4
+ from auth import verify_usage_token
5
+ from audio import fill_precise, load_audio, media_duration, transcribe_fast
6
+ from cache import _cache, disk_load, disk_save, disk_update_precise, evict_stale, fingerprint
7
+ from config import RETRANSCRIBE_MAX, BI_SCORE_GLOBAL_FLOOR, BI_SCORE_HYBRID_FLOOR, SAMPLE_RATE
8
+ from retrieval import (
9
+ add_entities_to_chunks, bi_encode_retrieve, classify_query,
10
+ merge_regions, pad_with_neighbours, rerank_and_score,
11
+ sample_chunks_for_global, semantic_chunk,
12
+ )
13
+ from synthesis import (
14
+ _fallback_summary, format_output, llm_synthesize_stream, prompt_to_words,
15
+ words_to_global_chunks,
16
+ )
17
+ from visual import add_visual_tags, analyze_visual, visual_scores
18
+
19
+
20
+ # ── Cold-start ingestion ───────────────────────────────────────────────────────
21
+
22
+ def ingest_video(video_path: str) -> dict:
23
+ """
24
+ First sight of a video: decode audio, then run audio and visual branches
25
+ concurrently (CPU: transcription+chunking, MPS/GPU: CLIP).
26
+ """
27
+ audio = load_audio(video_path)
28
+ duration = media_duration(video_path) or (len(audio) / SAMPLE_RATE)
29
+
30
+ result = {}
31
+
32
+ def _audio_branch():
33
+ segments = transcribe_fast(audio)
34
+ result["segments"] = segments
35
+ result["chunks"] = add_entities_to_chunks(semantic_chunk(segments)) if segments else []
36
+
37
+ def _visual_branch():
38
+ result["visual"] = analyze_visual(video_path, duration)
39
+
40
+ with ThreadPoolExecutor(max_workers=2) as ex:
41
+ fa = ex.submit(_audio_branch)
42
+ fv = ex.submit(_visual_branch)
43
+ fa.result()
44
+ fv.result()
45
+
46
+ return {
47
+ "segments": result["segments"],
48
+ "chunks": result["chunks"],
49
+ "visual": result["visual"],
50
+ "audio": audio,
51
+ "precise": {},
52
+ }
53
+
54
+
55
+ # ── Global path ────────────────────────────────────────────────────────────────
56
+
57
+ def _run_global(chunks: list[dict], visual: dict,
58
+ prompt: str, max_words: int) -> list[dict]:
59
+ sampled = sample_chunks_for_global(chunks, words_to_global_chunks(max_words))
60
+ print(f"[NINA] Global mode — sampled {len(sampled)} chunks evenly (base transcript).")
61
+ for c in sampled:
62
+ c.setdefault("confidence", 0.5)
63
+ c.setdefault("bi_score", 0.0)
64
+ c.setdefault("entity_overlap", 0.0)
65
+ c.setdefault("visual_score", 0.0)
66
+ c["precise_text"] = c.get("text", "")
67
+ return add_visual_tags(sampled, visual)
68
+
69
+
70
+ # ── Streaming synthesis wrapper ────────────────────────────────────────────────
71
+
72
+ def _synthesize_streaming(regions: list[dict], prompt: str,
73
+ max_words: int, mode: str):
74
+ print(f"[NINA] Running synthesis [{mode}]...")
75
+ yield format_output(regions, prompt, "✍️ …", mode)
76
+ last = ""
77
+ for partial in llm_synthesize_stream(regions, prompt, max_words, mode):
78
+ last = partial
79
+ yield format_output(regions, prompt, partial, mode)
80
+ if not last:
81
+ yield format_output(regions, prompt, _fallback_summary(regions), mode)
82
+
83
+
84
+ # ── Main pipeline ──────────────────────────────────────────────────────────────
85
+
86
+ def run(video_path: str, prompt: str, token: str = ""):
87
+ if not verify_usage_token(token):
88
+ yield (
89
+ "⛔ This request is not authorized.\n\n"
90
+ "Please use NINA at https://app.nnlabs.pl/nina (sign in first). "
91
+ "Direct API access is disabled, and each account has a usage limit."
92
+ )
93
+ return
94
+ if video_path is None:
95
+ yield "Please upload a video."
96
+ return
97
+ if not prompt or not prompt.strip():
98
+ yield "Please enter a prompt."
99
+ return
100
+
101
+ prompt = prompt.strip()
102
+ max_words = prompt_to_words(prompt)
103
+ print(f'\n[NINA] ── New request ── "{prompt}" (target ≈ {max_words} words)')
104
+ evict_stale()
105
+
106
+ # Stage 1–3: transcription + chunking + CLIP (cached)
107
+ fp = None
108
+ if video_path in _cache:
109
+ print("[NINA] Cache hit (memory) — skipping transcription + CLIP.")
110
+ entry = _cache[video_path]
111
+ else:
112
+ try:
113
+ fp = fingerprint(video_path)
114
+ except Exception:
115
+ fp = None
116
+
117
+ disk = disk_load(fp) if fp else None
118
+ if disk is not None:
119
+ disk["audio"] = load_audio(video_path)
120
+ entry = disk
121
+ _cache[video_path] = entry
122
+ else:
123
+ yield "🎬 Reading video — transcribing audio and scanning frames…"
124
+ entry = ingest_video(video_path)
125
+ if not entry["segments"]:
126
+ yield "No speech detected."
127
+ return
128
+ _cache[video_path] = entry
129
+ if fp:
130
+ disk_save(fp, entry)
131
+ print("[NINA] Cached transcript + visuals for this video.")
132
+
133
+ entry["_atime"] = time.time()
134
+ segments = entry["segments"]
135
+ chunks = entry["chunks"]
136
+ visual = entry["visual"]
137
+ precise_cache = entry["precise"]
138
+ audio = entry["audio"]
139
+
140
+ if fp is None:
141
+ try:
142
+ fp = fingerprint(video_path)
143
+ except Exception:
144
+ fp = None
145
+
146
+ if not chunks:
147
+ yield "No speech detected."
148
+ return
149
+
150
+ # Pass 1 routing
151
+ mode = classify_query(prompt)
152
+ print(f"[NINA] Query mode (pass 1): {mode}")
153
+
154
+ if mode == "global":
155
+ regions = _run_global(chunks, visual, prompt, max_words)
156
+ yield from _synthesize_streaming(regions, prompt, max_words, "global")
157
+ print(f"[NINA] Done — {len(regions)} region(s) [global].")
158
+ return
159
+
160
+ # SPECIFIC / HYBRID retrieval
161
+ candidates, best_bi = bi_encode_retrieve(chunks, prompt)
162
+ _, v_norm = visual_scores(visual, prompt)
163
+
164
+ # Pass 2 routing
165
+ if best_bi < BI_SCORE_GLOBAL_FLOOR:
166
+ print(f"[NINA] bi-score {best_bi:.3f} below floor → escalating to global.")
167
+ regions = _run_global(chunks, visual, prompt, max_words)
168
+ yield from _synthesize_streaming(regions, prompt, max_words, "global")
169
+ print(f"[NINA] Done — {len(regions)} region(s) [escalated global].")
170
+ return
171
+ elif best_bi < BI_SCORE_HYBRID_FLOOR:
172
+ mode = "hybrid"
173
+
174
+ print(f"[NINA] Query mode (pass 2): {mode} bi={best_bi:.3f}")
175
+
176
+ results = rerank_and_score(candidates, prompt, visual["time"], v_norm)
177
+
178
+ if mode == "hybrid":
179
+ results = pad_with_neighbours(results, chunks)
180
+
181
+ regions = merge_regions(results)
182
+ if not regions:
183
+ print("[NINA] No regions after merge → falling back to global.")
184
+ regions = _run_global(chunks, visual, prompt, max_words)
185
+ yield from _synthesize_streaming(regions, prompt, max_words, "global")
186
+ return
187
+
188
+ # Stage 7: precise re-transcription
189
+ before = dict(precise_cache)
190
+ fill_precise(audio, regions, chunks, precise_cache, RETRANSCRIBE_MAX)
191
+ if fp and precise_cache != before:
192
+ disk_update_precise(fp, precise_cache)
193
+
194
+ # Stage 7b: CLIP visual tags
195
+ regions = add_visual_tags(regions, visual)
196
+
197
+ # Stage 8: LLM synthesis
198
+ yield from _synthesize_streaming(regions, prompt, max_words, mode)
199
+ print(f"[NINA] Done — {len(regions)} region(s) [{mode}].")
retrieval.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import numpy as np
4
+
5
+ from config import (
6
+ BI_ENCODER_TOP_K, CHUNK_MAX_DURATION, CHUNK_MIN_DURATION,
7
+ CHUNK_SPLIT_THRESHOLD, CHUNK_WINDOW, CROSS_ENCODER_TOP_K,
8
+ DEBUG, GLOBAL_MAX_CHUNKS, MERGE_GAP_SEC, REGION_MIN_DURATION,
9
+ VISUAL_WEIGHT,
10
+ )
11
+ from models import bi_encoder, cross_encoder
12
+ from utils import _build_chunk, _cosine, _sigmoid
13
+ from visual import span_visual_score
14
+
15
+
16
+ # ── Entity extraction ──────────────────────────────────────────────────────────
17
+
18
+ _STOPWORDS = {
19
+ "the","a","an","and","or","but","in","on","at","to","for","of","is","are",
20
+ "was","were","be","been","that","this","it","he","she","they","we","i",
21
+ "w","z","że","na","do","się","nie","to","jest","są","by","przez","po",
22
+ "le","la","les","un","une","des","du","et","en","à","de","est","il","elle",
23
+ "ein","eine","der","die","das","und","ist","zu","mit","von","dem",
24
+ }
25
+
26
+
27
+ def extract_entities(text: str) -> set[str]:
28
+ entities: set[str] = set()
29
+
30
+ for match in re.finditer(r'"([^"]{2,40})"', text):
31
+ entities.add(match.group(1).lower().strip())
32
+
33
+ for match in re.finditer(
34
+ r'\b([A-ZÁÉÍÓÚÀÂÊÎÔÙÄËÏÖÜĄĆĘŁŃÓŚŹŻ][a-záéíóúàâêîôùäëïöüąćęłńóśźż]+'
35
+ r'(?:\s[A-ZÁÉÍÓÚÀÂÊÎÔÙÄËÏÖÜĄĆĘŁŃÓŚŹŻ][a-zÀ-žąćęłńóśźż]+)*)\b',
36
+ text,
37
+ ):
38
+ token = match.group(1).lower().strip()
39
+ if token not in _STOPWORDS and len(token) > 2:
40
+ entities.add(token)
41
+
42
+ for token in re.findall(
43
+ r'\b[A-ZÁÉÍÓÚÀÂÊÎÔÙÄËÏÖÜĄĆĘŁŃÓŚŹŻ][a-zÀ-žąćęłńóśźż]{2,}\b', text
44
+ ):
45
+ t = token.lower()
46
+ if t not in _STOPWORDS:
47
+ entities.add(t)
48
+
49
+ for match in re.finditer(r'\b([A-Za-z]+[-\s]?\d+[\w]*)\b', text):
50
+ entities.add(match.group(1).lower())
51
+
52
+ return entities
53
+
54
+
55
+ def entity_overlap_score(
56
+ prompt_entities: set[str], chunk_entities: set[str], chunk_text: str = ""
57
+ ) -> float:
58
+ if not prompt_entities:
59
+ return 0.0
60
+ chunk_text_lower = chunk_text.lower()
61
+ matched = 0
62
+ for pe in prompt_entities:
63
+ entity_hit = any(pe in ce or ce in pe for ce in chunk_entities)
64
+ text_hit = len(pe) > 3 and pe in chunk_text_lower
65
+ if entity_hit or text_hit:
66
+ matched += 1
67
+ return matched / len(prompt_entities)
68
+
69
+
70
+ def add_entities_to_chunks(chunks: list[dict]) -> list[dict]:
71
+ for chunk in chunks:
72
+ chunk["entities"] = extract_entities(chunk["text"])
73
+ return chunks
74
+
75
+
76
+ # ── Semantic chunking ──────────────────────────────────────────────────────────
77
+
78
+ def semantic_chunk(segments: list[dict]) -> list[dict]:
79
+ if not segments:
80
+ return []
81
+ texts = [s["text"] for s in segments]
82
+ embeddings = bi_encoder.encode(texts, convert_to_numpy=True, batch_size=64)
83
+ chunks, current, cur_emb = [], [segments[0]], [embeddings[0]]
84
+
85
+ for i in range(1, len(segments)):
86
+ chunk_dur = segments[i]["end"] - current[0]["start"]
87
+ window_mean = np.mean(cur_emb[-CHUNK_WINDOW:], axis=0)
88
+ sim = max(_cosine(embeddings[i], window_mean),
89
+ _cosine(embeddings[i], cur_emb[-1]))
90
+ long_enough = (current[-1]["end"] - current[0]["start"]) >= CHUNK_MIN_DURATION
91
+
92
+ if (sim < CHUNK_SPLIT_THRESHOLD or chunk_dur >= CHUNK_MAX_DURATION) and long_enough:
93
+ chunks.append(_build_chunk(current, cur_emb))
94
+ current, cur_emb = [segments[i]], [embeddings[i]]
95
+ else:
96
+ current.append(segments[i])
97
+ cur_emb.append(embeddings[i])
98
+
99
+ if current:
100
+ chunks.append(_build_chunk(current, cur_emb))
101
+
102
+ print(f"[NINA] {len(segments)} segments → {len(chunks)} chunks.")
103
+ return chunks
104
+
105
+
106
+ # ── Query router ───────────────────────────────────────────────────────────────
107
+
108
+ _GLOBAL_PATTERNS = re.compile(
109
+ r'\b('
110
+ r'summari[sz]e|summary|overview|recap|tl;?dr|key\s+points?|main\s+points?|'
111
+ r'key\s+takeaways?|main\s+idea|gist|'
112
+ r'what(?:\'s| is| was)\s+(?:this|the|it)\s+(?:video|recording|clip|all\s+)?\s*about|'
113
+ r'what(?:\'s| is| was)\s+(?:this|the)\s+(?:video|recording|clip)|'
114
+ r'describe\s+(?:the|this)\s+(?:video|recording|clip)|'
115
+ r'streszcz\w*|podsumuj\w*|podsumowanie|'
116
+ r'o\s+czym\s+(?:jest|to|opowiada|mówi)|czego\s+dotyczy|'
117
+ r'gł[oó]wn\w+\s+(?:punkt\w*|my[sś]l\w*|tez\w*)|og[oó]ln\w+\s+zarys'
118
+ r')\b',
119
+ re.IGNORECASE,
120
+ )
121
+
122
+
123
+ def classify_query(prompt: str) -> str:
124
+ """Pattern-based pass-1 router. Returns 'global' or 'specific'."""
125
+ if _GLOBAL_PATTERNS.search(prompt):
126
+ return "global"
127
+ return "specific"
128
+
129
+
130
+ # ── Bi-encoder retrieval ───────────────────────────────────────────────────────
131
+
132
+ def bi_encode_retrieve(chunks: list[dict], prompt: str) -> tuple[list[dict], float]:
133
+ prompt_emb = bi_encoder.encode([prompt], convert_to_numpy=True)[0]
134
+ scores = [_cosine(prompt_emb, c["emb"]) for c in chunks]
135
+
136
+ top_k = min(BI_ENCODER_TOP_K, len(chunks))
137
+ top_idx = np.argsort(scores)[::-1][:top_k]
138
+
139
+ if DEBUG:
140
+ print(f"[DEBUG] Bi top-3 scores: " +
141
+ ", ".join(f"{scores[i]:.3f}" for i in top_idx[:3]))
142
+
143
+ best = scores[top_idx[0]] if len(top_idx) else 0.0
144
+ return (
145
+ [{**chunks[i], "bi_score": round(scores[i], 3)} for i in top_idx],
146
+ best,
147
+ )
148
+
149
+
150
+ # ── Cross-encoder rerank + audio/visual fusion ────────────────────────────────
151
+
152
+ def rerank_and_score(
153
+ candidates: list[dict], prompt: str,
154
+ times: np.ndarray, norm: np.ndarray,
155
+ ) -> list[dict]:
156
+ pairs = [[prompt, c["text"]] for c in candidates]
157
+ logits = cross_encoder.predict(pairs)
158
+
159
+ prompt_entities = extract_entities(prompt)
160
+ prompt_words = {
161
+ w.lower() for w in re.findall(r'[\wÀ-ž]{3,}', prompt)
162
+ if w.lower() not in _STOPWORDS
163
+ }
164
+ all_prompt_tokens = prompt_entities | prompt_words
165
+
166
+ if DEBUG and all_prompt_tokens:
167
+ print(f"[DEBUG] Prompt tokens for entity match: {all_prompt_tokens}")
168
+
169
+ vw = VISUAL_WEIGHT if len(norm) else 0.0
170
+
171
+ scored = []
172
+ for candidate, logit in zip(candidates, logits):
173
+ chunk_entities = candidate.get("entities", set())
174
+ chunk_text = candidate.get("text", "")
175
+ overlap = entity_overlap_score(all_prompt_tokens, chunk_entities, chunk_text)
176
+
177
+ ce_conf = _sigmoid(float(logit))
178
+ audio_score = 0.6 * ce_conf + 0.4 * overlap
179
+ visual_score = span_visual_score(times, norm, candidate["start"], candidate["end"])
180
+ final = (1.0 - vw) * audio_score + vw * visual_score
181
+
182
+ scored.append({
183
+ **candidate,
184
+ "ce_logit": round(float(logit), 3),
185
+ "entity_overlap": round(overlap, 3),
186
+ "visual_score": round(visual_score, 3),
187
+ "confidence": round(min(1.0, final), 3),
188
+ })
189
+
190
+ ranked = sorted(scored, key=lambda x: x["confidence"], reverse=True)
191
+
192
+ if DEBUG:
193
+ print("[DEBUG] Top-3 after reranking (audio+visual):")
194
+ for r in ranked[:3]:
195
+ print(
196
+ f" ce_logit={r['ce_logit']:.2f} "
197
+ f"bi={r['bi_score']:.3f} "
198
+ f"entity={r['entity_overlap']:.3f} "
199
+ f"visual={r['visual_score']:.3f} "
200
+ f"conf={r['confidence']:.3f} "
201
+ f"\"{r['text'][:60]}\""
202
+ )
203
+
204
+ return ranked[:CROSS_ENCODER_TOP_K]
205
+
206
+
207
+ # ── Hybrid padding ─────────────────────────────────────────────────────────────
208
+
209
+ def pad_with_neighbours(results: list[dict], chunks: list[dict]) -> list[dict]:
210
+ """Include immediate neighbours of each retrieved chunk (HYBRID mode)."""
211
+ result_starts = {r["start"] for r in results}
212
+ padded = list(results)
213
+
214
+ for r in results:
215
+ for i, c in enumerate(chunks):
216
+ if abs(c["start"] - r["start"]) < 0.5:
217
+ for neighbour_i in [i - 1, i + 1]:
218
+ if 0 <= neighbour_i < len(chunks):
219
+ nb = chunks[neighbour_i]
220
+ if nb["start"] not in result_starts:
221
+ padded.append({
222
+ **nb,
223
+ "bi_score": 0.0,
224
+ "ce_logit": -9.0,
225
+ "entity_overlap": 0.0,
226
+ "visual_score": 0.0,
227
+ "confidence": nb.get("confidence", 0.1),
228
+ })
229
+ result_starts.add(nb["start"])
230
+ break
231
+
232
+ return sorted(padded, key=lambda x: x["start"])
233
+
234
+
235
+ # ── Global sampling ────────────────────────────────────────────────────────────
236
+
237
+ def sample_chunks_for_global(chunks: list[dict], n_target: int) -> list[dict]:
238
+ """Pick n_target chunks evenly distributed across the video."""
239
+ n_target = max(3, min(n_target, len(chunks)))
240
+ if n_target >= len(chunks):
241
+ return chunks
242
+ indices = [int(i * (len(chunks) - 1) / (n_target - 1)) for i in range(n_target)]
243
+ return [chunks[i] for i in indices]
244
+
245
+
246
+ # ── Merge regions ────────────────────────────────────────────��─────────────────
247
+
248
+ def merge_regions(results: list[dict]) -> list[dict]:
249
+ if not results:
250
+ return []
251
+ sorted_r = sorted(results, key=lambda x: x["start"])
252
+ merged, current = [], sorted_r[0].copy()
253
+ current["_frags"] = [sorted_r[0]]
254
+
255
+ for nxt in sorted_r[1:]:
256
+ if nxt["start"] - current["end"] <= MERGE_GAP_SEC:
257
+ current["end"] = max(current["end"], nxt["end"])
258
+ current["text"] += " " + nxt["text"]
259
+ current["_frags"].append(nxt)
260
+ else:
261
+ merged.append(_finalize_region(current))
262
+ current = nxt.copy()
263
+ current["_frags"] = [nxt]
264
+
265
+ merged.append(_finalize_region(current))
266
+ return [r for r in merged if (r["end"] - r["start"]) >= REGION_MIN_DURATION]
267
+
268
+
269
+ def _finalize_region(region: dict) -> dict:
270
+ frags = region.pop("_frags")
271
+ total_dur = sum(max(f["end"] - f["start"], 0.1) for f in frags)
272
+ w_conf = sum(
273
+ f["confidence"] * max(f["end"] - f["start"], 0.1) for f in frags
274
+ ) / total_dur
275
+ duration = region["end"] - region["start"]
276
+ w_conf *= min(1.0, duration / 20.0)
277
+ visual = max((f.get("visual_score", 0.0) for f in frags), default=0.0)
278
+ return {**region, "confidence": round(w_conf, 3), "visual_score": round(visual, 3)}
synthesis.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ from config import DEBUG, GLOBAL_MAX_CHUNKS, LLM_MAX_TOKENS, LLM_MODEL
4
+ from models import llm_client
5
+ from utils import conf_bar, fmt_time
6
+
7
+
8
+ # ── Output size inference ──────────────────────────────────────────────────────
9
+
10
+ _BRIEF_CUES = (
11
+ "brief", "briefly", "short", "shortly", "quick", "quickly", "concise",
12
+ "in a sentence", "one sentence", "one-liner", "tl;dr", "tldr",
13
+ "krótko", "w skrócie", "zwięźle", "jednym zdaniem", "w jednym zdaniu",
14
+ )
15
+ _DETAIL_CUES = (
16
+ "in detail", "detailed", "in-depth", "in depth", "thorough", "thoroughly",
17
+ "comprehensive", "exhaustive", "everything", "full summary", "elaborate",
18
+ "step by step", "step-by-step", "deep dive", "as much as possible",
19
+ "szczegółowo", "dokładnie", "wyczerpująco", "wszystko", "krok po kroku",
20
+ "dogłębnie", "obszernie",
21
+ )
22
+ _FACTUAL_START = re.compile(
23
+ r'^\s*(what|who|whom|whose|when|where|which|how many|how much|how long|'
24
+ r'is|are|was|were|does|do|did|can|could|will|would|'
25
+ r'czy|kiedy|kto|kogo|gdzie|ile|jaki|jaka|jakie|który|która|które)\b',
26
+ re.IGNORECASE,
27
+ )
28
+
29
+
30
+ def _summary_tier(max_words: int) -> str:
31
+ if max_words <= 60: return "brief / one-liner"
32
+ if max_words <= 110: return "short"
33
+ if max_words <= 250: return "standard"
34
+ if max_words <= 400: return "detailed"
35
+ return "exhaustive"
36
+
37
+
38
+ def prompt_to_words(prompt: str) -> int:
39
+ """Infer answer word budget from prompt cues. Clamped to [30, 500]."""
40
+ p = prompt.lower()
41
+ if any(c in p for c in _DETAIL_CUES):
42
+ base, reason = 450, "explicit detail cue"
43
+ elif any(c in p for c in _BRIEF_CUES):
44
+ base, reason = 40, "explicit brevity cue"
45
+ elif _FACTUAL_START.match(p):
46
+ base, reason = 80, "factual question"
47
+ else:
48
+ n_words = len(re.findall(r'\w+', p))
49
+ base, reason = 120 + min(180, n_words * 8), f"length-scaled ({n_words} prompt words)"
50
+
51
+ out = int(max(30, min(500, base)))
52
+ if DEBUG:
53
+ print(f"[DEBUG] Summary sizing: {reason} → {out} words [{_summary_tier(out)}]")
54
+ return out
55
+
56
+
57
+ def words_to_global_chunks(max_words: int) -> int:
58
+ return max(3, min(GLOBAL_MAX_CHUNKS, round(max_words / 40)))
59
+
60
+
61
+ # ── Synthesis ──────────────────────────────────────────────────────────────────
62
+
63
+ def _fallback_summary(regions: list[dict]) -> str:
64
+ snippets = [
65
+ f"[{fmt_time(r['start'])}] {r.get('precise_text', r['text'])[:200]}"
66
+ for r in regions[:2]
67
+ ]
68
+ return "(LLM unavailable — raw excerpts:)\n" + "\n".join(snippets)
69
+
70
+
71
+ def _build_synth_prompt(regions: list[dict], prompt: str, max_words: int, mode: str) -> str:
72
+ blocks = []
73
+ for r in regions:
74
+ spoken = (r.get("precise_text", r["text"]) or "").strip()
75
+ tags = r.get("visual_tags", [])
76
+ block = (
77
+ f"[{fmt_time(r['start'])} → {fmt_time(r['end'])}]\n"
78
+ f" Spoken (audio): {spoken or '(no speech)'}"
79
+ )
80
+ if tags:
81
+ block += f"\n On screen (video): {', '.join(tags)}"
82
+ blocks.append(block)
83
+ fragments = "\n\n".join(blocks)
84
+
85
+ if mode == "global":
86
+ task_line = "Task: Give a complete overview of what this video is about."
87
+ else:
88
+ task_line = f'Task: Summarize what the video says/shows about "{prompt}".'
89
+
90
+ return (
91
+ f"You are analyzing a video. Each fragment below contains what is SPOKEN "
92
+ f"(audio transcript) and what is SHOWN (visual cues detected in the frames).\n"
93
+ f'The user is looking for: "{prompt}"\n\n'
94
+ f"Fragments:\n\n{fragments}\n\n"
95
+ f"{task_line}\n\n"
96
+ f"Output format:\n"
97
+ f"- Combine BOTH the spoken content and the on-screen visuals into one coherent answer\n"
98
+ f"- After each statement, append the timestamp it came from, taken from the "
99
+ f"bracketed start time of the relevant fragment above (use that exact value)\n"
100
+ f"- Maximum {max_words} words total\n"
101
+ f"- IMPORTANT: Write in the same language as the prompt given by the user\n"
102
+ f"- Only use information from the fragments (audio + visual) — do not invent details\n"
103
+ f"- If fragments contain no real information about the topic, say so clearly, "
104
+ f"without further explanation\n"
105
+ )
106
+
107
+
108
+ def llm_synthesize_stream(
109
+ regions: list[dict], prompt: str, max_words: int = 150, mode: str = "specific"
110
+ ):
111
+ """Generator: yields the answer incrementally as the LLM streams tokens."""
112
+ if not regions:
113
+ yield "(No relevant regions to summarize.)"
114
+ return
115
+
116
+ synth_prompt = _build_synth_prompt(regions, prompt, max_words, mode)
117
+
118
+ if DEBUG:
119
+ print(
120
+ f"[DEBUG] Synthesis [{mode}] — {len(regions)} region(s), "
121
+ f"max_words={max_words} [{_summary_tier(max_words)}]."
122
+ )
123
+
124
+ try:
125
+ acc = ""
126
+ stream = llm_client.chat_completion(
127
+ model=LLM_MODEL,
128
+ messages=[{"role": "user", "content": synth_prompt}],
129
+ max_tokens=LLM_MAX_TOKENS,
130
+ temperature=0.3,
131
+ stream=True,
132
+ )
133
+ for ev in stream:
134
+ delta = ev.choices[0].delta.content or ""
135
+ if delta:
136
+ acc += delta
137
+ yield acc.strip()
138
+ if not acc.strip():
139
+ yield _fallback_summary(regions)
140
+ except Exception as e:
141
+ print(f"[NINA] Synthesis error: {e}")
142
+ yield _fallback_summary(regions)
143
+
144
+
145
+ def llm_synthesize(
146
+ regions: list[dict], prompt: str, max_words: int = 150, mode: str = "specific"
147
+ ) -> str:
148
+ """Non-streaming convenience wrapper (API compatibility / testing)."""
149
+ out = ""
150
+ for out in llm_synthesize_stream(regions, prompt, max_words, mode):
151
+ pass
152
+ return out
153
+
154
+
155
+ # ── Output formatter ───────────────────────────────────────────────────────────
156
+
157
+ def format_output(regions: list[dict], prompt: str, summary: str,
158
+ mode: str = "specific") -> str:
159
+ if not regions:
160
+ return (
161
+ f' Topic not found in this video.\n\n'
162
+ f' Prompt : "{prompt}"\n\n'
163
+ f' No relevant segments found.\n'
164
+ f' Try a broader or differently worded prompt.'
165
+ )
166
+
167
+ mode_tag = {
168
+ "global": "🌐 global", "hybrid": "⚡ hybrid", "specific": "🎯 specific"
169
+ }.get(mode, "")
170
+ lines = [f' {len(regions)} region(s) found for: "{prompt}" [{mode_tag} · audio+video]\n']
171
+
172
+ if DEBUG:
173
+ for i, r in enumerate(regions, 1):
174
+ dur = round(r["end"] - r["start"], 1)
175
+ text = r.get("precise_text", r["text"])
176
+ ent = r.get("entity_overlap", 0)
177
+ bi = r.get("bi_score", 0)
178
+ vis = r.get("visual_score", 0)
179
+ tags = ", ".join(r.get("visual_tags", []))
180
+ lines += [
181
+ f'\n [{i}] {fmt_time(r["start"])} → {fmt_time(r["end"])} ({dur}s)',
182
+ f' {conf_bar(r["confidence"])} {r["confidence"]:.0%} '
183
+ f'(embed {bi:.0%} · entity {ent:.0%} · visual {vis:.0%})',
184
+ f' 👁 {tags}' if tags else ' 👁 (no visual tags)',
185
+ f' "{text[:220]}{"…" if len(text) > 220 else ""}"',
186
+ ]
187
+
188
+ lines += [
189
+ f' 🧠 Based on uploaded video (audio + video): — "{prompt}"',
190
+ summary,
191
+ f'\n Sources: ' + ', '.join(
192
+ f'[{fmt_time(r["start"])} → {fmt_time(r["end"])}]' for r in regions
193
+ ),
194
+ ]
195
+ return "\n".join(lines)
utils.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+
4
+
5
+ def _build_chunk(segs: list[dict], embs: list[np.ndarray]) -> dict:
6
+ total = sum(max(s["end"] - s["start"], 0.1) for s in segs)
7
+ logp = sum(s.get("logprob", 0.0) * max(s["end"] - s["start"], 0.1)
8
+ for s in segs) / total
9
+ return {
10
+ "text": " ".join(s["text"] for s in segs),
11
+ "start": segs[0]["start"],
12
+ "end": segs[-1]["end"],
13
+ "logprob": round(logp, 3),
14
+ "emb": np.mean(np.stack(embs), axis=0),
15
+ }
16
+
17
+
18
+ def _cosine(a: np.ndarray, b: np.ndarray) -> float:
19
+ return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-9))
20
+
21
+
22
+ def _sigmoid(x: float) -> float:
23
+ return 1.0 / (1.0 + math.exp(-float(x)))
24
+
25
+
26
+ def fmt_time(s: float) -> str:
27
+ m = int(s) // 60
28
+ return f"{m}:{s % 60:05.2f}"
29
+
30
+
31
+ def conf_bar(c: float) -> str:
32
+ f = round(c * 10)
33
+ return "█" * f + "░" * (10 - f)
visual.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import ffmpeg
3
+ from PIL import Image
4
+
5
+ from config import (
6
+ CLIP_FRAME_SIZE, CLIP_MAX_FRAMES, CLIP_MAX_FPS, CLIP_MIN_FPS,
7
+ DEBUG, VISUAL_CONCEPTS, VISUAL_TAG_MIN_SIM, VISUAL_TAGS_TOP_K,
8
+ )
9
+ from models import TORCH_DEVICE, get_clip, get_concept_embs
10
+ from utils import fmt_time
11
+
12
+
13
+ def extract_frames(video_path: str, duration: float):
14
+ """
15
+ Sample frames evenly via one ffmpeg rawvideo pipe into NumPy (no temp files).
16
+ Returns (frames_rgb, times): uint8 (N, S, S, 3) and float (N,).
17
+ """
18
+ fps = CLIP_MAX_FPS
19
+ if duration and duration > 0:
20
+ fps = min(CLIP_MAX_FPS, max(CLIP_MIN_FPS, CLIP_MAX_FRAMES / duration))
21
+
22
+ S = CLIP_FRAME_SIZE
23
+ try:
24
+ out, _ = (
25
+ ffmpeg.input(video_path)
26
+ .filter("fps", fps=fps)
27
+ .filter("scale", S, S, force_original_aspect_ratio="increase")
28
+ .filter("crop", S, S)
29
+ .output("pipe:", format="rawvideo", pix_fmt="rgb24")
30
+ .run(capture_stdout=True, capture_stderr=True)
31
+ )
32
+ except ffmpeg.Error:
33
+ return np.zeros((0, S, S, 3), dtype=np.uint8), np.zeros((0,))
34
+
35
+ if not out:
36
+ return np.zeros((0, S, S, 3), dtype=np.uint8), np.zeros((0,))
37
+
38
+ frames = np.frombuffer(out, np.uint8).reshape(-1, S, S, 3)[:CLIP_MAX_FRAMES]
39
+ times = np.array([(i + 0.5) / fps for i in range(len(frames))])
40
+ return frames, times
41
+
42
+
43
+ def analyze_visual(video_path: str, duration: float) -> dict:
44
+ """
45
+ Sample + CLIP-encode frames. Returns {"emb": (N,D) float32, "time": (N,)}.
46
+ Empty arrays for audio-only input.
47
+ """
48
+ frames, times = extract_frames(video_path, duration)
49
+ if len(frames) == 0:
50
+ print("[NINA] No video frames (audio-only?) — visual analysis skipped.")
51
+ return {"emb": np.zeros((0, 512), dtype=np.float32), "time": np.zeros((0,))}
52
+
53
+ images = [Image.fromarray(f) for f in frames]
54
+ embs = get_clip().encode(images, convert_to_numpy=True, batch_size=32, show_progress_bar=False)
55
+ print(f"[NINA] CLIP encoded {len(images)} frames ({TORCH_DEVICE}).")
56
+ return {"emb": np.asarray(embs, dtype=np.float32), "time": np.asarray(times)}
57
+
58
+
59
+ def visual_scores(visual: dict, prompt: str) -> tuple[np.ndarray, np.ndarray]:
60
+ """
61
+ Per-frame cosine of prompt↔frame in CLIP space.
62
+ Returns (raw_sims, min-max-normalised_sims); empty arrays when no frames.
63
+ """
64
+ embs = visual.get("emb")
65
+ if embs is None or len(embs) == 0:
66
+ if DEBUG:
67
+ print("[DEBUG] Visual: no frames (audio-only) — visual weight = 0.")
68
+ return np.array([]), np.array([])
69
+
70
+ q = get_clip().encode([prompt], convert_to_numpy=True, show_progress_bar=False)[0]
71
+ qn = q / (np.linalg.norm(q) + 1e-9)
72
+ en = embs / (np.linalg.norm(embs, axis=1, keepdims=True) + 1e-9)
73
+ sims = en @ qn
74
+ lo, hi = float(sims.min()), float(sims.max())
75
+ norm = (sims - lo) / (hi - lo + 1e-9)
76
+
77
+ if DEBUG:
78
+ times = visual.get("time")
79
+ order = np.argsort(sims)[::-1][:3]
80
+ tops = ", ".join(f"{fmt_time(times[i])}={sims[i]:.3f}" for i in order)
81
+ print(
82
+ f"[DEBUG] Visual: {len(sims)} frames; raw sim "
83
+ f"min/mean/max={sims.min():.3f}/{sims.mean():.3f}/{sims.max():.3f}; "
84
+ f"top moments: {tops}"
85
+ )
86
+ return sims, norm
87
+
88
+
89
+ def span_visual_score(times: np.ndarray, norm: np.ndarray,
90
+ start: float, end: float) -> float:
91
+ """Best normalised visual relevance among frames inside [start, end]."""
92
+ if len(times) == 0:
93
+ return 0.0
94
+ mask = (times >= start - 0.5) & (times <= end + 0.5)
95
+ if not mask.any():
96
+ idx = int(np.argmin(np.abs(times - (start + end) / 2)))
97
+ return float(norm[idx])
98
+ return float(norm[mask].max())
99
+
100
+
101
+ def region_visual_tags(visual: dict, start: float, end: float) -> list[str]:
102
+ """Zero-shot CLIP tags for what is on screen during [start, end]."""
103
+ embs = visual.get("emb")
104
+ times = visual.get("time")
105
+ if embs is None or len(embs) == 0:
106
+ return []
107
+
108
+ mask = (times >= start - 0.5) & (times <= end + 0.5)
109
+ if mask.any():
110
+ sel = embs[mask]
111
+ else:
112
+ idx = int(np.argmin(np.abs(times - (start + end) / 2)))
113
+ sel = embs[idx:idx + 1]
114
+
115
+ region_emb = sel.mean(axis=0)
116
+ region_emb = region_emb / (np.linalg.norm(region_emb) + 1e-9)
117
+ sims = get_concept_embs() @ region_emb
118
+
119
+ order = np.argsort(sims)[::-1][:VISUAL_TAGS_TOP_K]
120
+ return [VISUAL_CONCEPTS[i] for i in order if sims[i] >= VISUAL_TAG_MIN_SIM]
121
+
122
+
123
+ def add_visual_tags(regions: list[dict], visual: dict) -> list[dict]:
124
+ for r in regions:
125
+ r["visual_tags"] = region_visual_tags(visual, r["start"], r["end"])
126
+ return regions