Spaces:
Paused
Paused
Malina Claude Opus 4.8 commited on
Commit ·
0695bec
1
Parent(s): 165807e
NINA v0.82 — upload compression, natural multilingual answers, robust precise
Browse files- compress.py + pipeline guard: reject uploads >200 MB, ffmpeg-downscale
anything >20 MB to 720p before decode (faster, smaller)
- synthesis: detect the prompt language (langdetect + diacritic fallback) and
answer in it; natural prose + a final "Sources:" line; auto-sized length
- precise re-transcription: loosen logprob gate -0.55 → -0.40 so it actually
fires on weak audio; never crash (graceful fallback if the model can't load)
- app.py: drop benign ClientDisconnect tracebacks from upload aborts
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- app.py +21 -0
- audio.py +17 -4
- compress.py +86 -0
- config.py +18 -1
- models.py +20 -8
- pipeline.py +15 -1
- requirements.txt +1 -0
- synthesis.py +65 -38
app.py
CHANGED
|
@@ -3,11 +3,32 @@
|
|
| 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,
|
| 13 |
inputs=[
|
|
|
|
| 3 |
# app.py | v0.81 | Made by Malina
|
| 4 |
# ─────────────────────────────────────────────
|
| 5 |
|
| 6 |
+
import logging
|
| 7 |
import os
|
| 8 |
+
|
| 9 |
import gradio as gr
|
| 10 |
|
| 11 |
from pipeline import run
|
| 12 |
|
| 13 |
+
|
| 14 |
+
# ── Quiet benign upload aborts ─────────────────────────────────────────────────
|
| 15 |
+
# When a browser cancels a multipart upload mid-stream (slow/mobile connection,
|
| 16 |
+
# tab switch, or our own client rejecting an oversized file), Starlette raises
|
| 17 |
+
# `ClientDisconnect` and uvicorn logs a full "Exception in ASGI application"
|
| 18 |
+
# traceback. It's harmless — there's nothing to handle, the request is just gone —
|
| 19 |
+
# but it floods the Space logs. Drop only those records; everything else logs as
|
| 20 |
+
# normal. (The new size cap + pre-upload compression also make it far rarer.)
|
| 21 |
+
class _DropClientDisconnect(logging.Filter):
|
| 22 |
+
def filter(self, record: logging.LogRecord) -> bool:
|
| 23 |
+
exc = record.exc_info[1] if record.exc_info else None
|
| 24 |
+
if exc is not None and type(exc).__name__ == "ClientDisconnect":
|
| 25 |
+
return False
|
| 26 |
+
return "ClientDisconnect" not in record.getMessage()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
for _name in ("uvicorn.error", "uvicorn"):
|
| 30 |
+
logging.getLogger(_name).addFilter(_DropClientDisconnect())
|
| 31 |
+
|
| 32 |
demo = gr.Interface(
|
| 33 |
fn=run,
|
| 34 |
inputs=[
|
audio.py
CHANGED
|
@@ -40,15 +40,28 @@ def transcribe_fast(audio: np.ndarray) -> list[dict]:
|
|
| 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
|
| 49 |
model = get_whisper_precise()
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
def fill_precise(
|
|
|
|
| 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 |
+
|
| 45 |
+
Always returns usable text: if the precise model is unavailable or errors out,
|
| 46 |
+
we fall back to the region's base-model text rather than crashing the request.
|
| 47 |
+
"""
|
| 48 |
+
base = region.get("text", "")
|
| 49 |
s = max(0, int(region["start"] * SAMPLE_RATE))
|
| 50 |
e = min(len(audio), int(region["end"] * SAMPLE_RATE))
|
| 51 |
clip = audio[s:e]
|
| 52 |
if len(clip) < SAMPLE_RATE * 0.2:
|
| 53 |
+
return base
|
| 54 |
model = get_whisper_precise()
|
| 55 |
+
if model is None:
|
| 56 |
+
return base
|
| 57 |
+
try:
|
| 58 |
+
segments_gen, _ = model.transcribe(clip, beam_size=1)
|
| 59 |
+
out = " ".join(seg.text.strip() for seg in segments_gen).strip()
|
| 60 |
+
return out or base
|
| 61 |
+
except Exception as exc:
|
| 62 |
+
print(f"[NINA] Precise re-transcription failed for "
|
| 63 |
+
f"[{fmt_time(region['start'])} → {fmt_time(region['end'])}]: {exc}")
|
| 64 |
+
return base
|
| 65 |
|
| 66 |
|
| 67 |
def fill_precise(
|
compress.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ─────────────────────────────────────────────
|
| 2 |
+
# NINA — server-side upload guard + compression
|
| 3 |
+
# ─────────────────────────────────────────────
|
| 4 |
+
# The website already rejects > MAX_UPLOAD_MB and best-effort compresses before
|
| 5 |
+
# upload, but the client check is bypassable (direct API calls) and browser
|
| 6 |
+
# compression is skipped for long clips. So we re-check the size here and, for
|
| 7 |
+
# anything still large, transcode it down with ffmpeg before the heavy pipeline
|
| 8 |
+
# touches it. NINA only needs the audio plus a handful of sampled frames, so an
|
| 9 |
+
# aggressive 720p / low-bitrate re-encode costs nothing in quality and speeds up
|
| 10 |
+
# decode + CLIP frame extraction on big files.
|
| 11 |
+
#
|
| 12 |
+
# Everything here is best-effort: on any failure (no ffmpeg, odd container,
|
| 13 |
+
# timeout) we return the original path and let the pipeline carry on.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import shutil
|
| 17 |
+
import subprocess
|
| 18 |
+
import tempfile
|
| 19 |
+
|
| 20 |
+
from config import (
|
| 21 |
+
COMPRESS_AUDIO_BITRATE, COMPRESS_TARGET_HEIGHT, COMPRESS_TRIGGER_MB,
|
| 22 |
+
COMPRESS_VIDEO_BITRATE, MAX_UPLOAD_MB,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def file_mb(path: str) -> float:
|
| 27 |
+
"""Size of a file in MB, or 0.0 if it doesn't exist."""
|
| 28 |
+
try:
|
| 29 |
+
return os.path.getsize(path) / (1024 * 1024)
|
| 30 |
+
except OSError:
|
| 31 |
+
return 0.0
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def too_large(path: str) -> bool:
|
| 35 |
+
"""True if the upload exceeds the hard cap and must be rejected."""
|
| 36 |
+
return file_mb(path) > MAX_UPLOAD_MB
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def ensure_compressed(path: str) -> str:
|
| 40 |
+
"""Return a path to a download-sized version of `path`.
|
| 41 |
+
|
| 42 |
+
If the file is under the trigger size (or ffmpeg is unavailable, or the
|
| 43 |
+
re-encode fails or doesn't actually shrink it), the original path is returned
|
| 44 |
+
unchanged. Otherwise a new temp MP4 (≤720p, H.264 + AAC) is written and its
|
| 45 |
+
path returned.
|
| 46 |
+
"""
|
| 47 |
+
try:
|
| 48 |
+
size = file_mb(path)
|
| 49 |
+
if size <= COMPRESS_TRIGGER_MB:
|
| 50 |
+
return path
|
| 51 |
+
if not shutil.which("ffmpeg"):
|
| 52 |
+
print("[NINA] ffmpeg not found — skipping server-side compression.")
|
| 53 |
+
return path
|
| 54 |
+
|
| 55 |
+
fd, out = tempfile.mkstemp(prefix="nina_compressed_", suffix=".mp4")
|
| 56 |
+
os.close(fd)
|
| 57 |
+
|
| 58 |
+
# scale=-2:min(720,ih) → cap height at 720, keep aspect ratio, even dims.
|
| 59 |
+
# The comma inside min() must be escaped so the filtergraph parser doesn't
|
| 60 |
+
# read it as a filter separator.
|
| 61 |
+
vf = f"scale=-2:'min({COMPRESS_TARGET_HEIGHT}\\,ih)'"
|
| 62 |
+
cmd = [
|
| 63 |
+
"ffmpeg", "-y", "-i", path,
|
| 64 |
+
"-vf", vf,
|
| 65 |
+
"-c:v", "libx264", "-preset", "veryfast", "-b:v", COMPRESS_VIDEO_BITRATE,
|
| 66 |
+
"-c:a", "aac", "-b:a", COMPRESS_AUDIO_BITRATE,
|
| 67 |
+
"-movflags", "+faststart",
|
| 68 |
+
"-loglevel", "error",
|
| 69 |
+
out,
|
| 70 |
+
]
|
| 71 |
+
subprocess.run(cmd, check=True, timeout=600)
|
| 72 |
+
|
| 73 |
+
new_size = file_mb(out)
|
| 74 |
+
if 0 < new_size < size:
|
| 75 |
+
print(f"[NINA] Server-side compression: {size:.1f} MB → {new_size:.1f} MB.")
|
| 76 |
+
return out
|
| 77 |
+
|
| 78 |
+
# Didn't help (already small / re-encode grew it) — discard and keep original.
|
| 79 |
+
try:
|
| 80 |
+
os.remove(out)
|
| 81 |
+
except OSError:
|
| 82 |
+
pass
|
| 83 |
+
return path
|
| 84 |
+
except Exception as exc:
|
| 85 |
+
print(f"[NINA] Server-side compression skipped: {exc}")
|
| 86 |
+
return path
|
config.py
CHANGED
|
@@ -7,7 +7,12 @@ SAMPLE_RATE = 16000
|
|
| 7 |
WHISPER_CPU_THREADS = int(os.getenv("WHISPER_CPU_THREADS", "3"))
|
| 8 |
|
| 9 |
RETRANSCRIBE_MAX = 12
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
CHUNK_SPLIT_THRESHOLD = 0.45
|
| 13 |
CHUNK_MIN_DURATION = 8.0
|
|
@@ -58,6 +63,18 @@ LLM_MAX_TOKENS = 1800
|
|
| 58 |
LLM_TEMPERATURE = 0.05
|
| 59 |
LLM_TIMEOUT = 120
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
CACHE_DIR = os.path.join(tempfile.gettempdir(), "nina_cache")
|
| 62 |
DISK_CACHE = True
|
| 63 |
|
|
|
|
| 7 |
WHISPER_CPU_THREADS = int(os.getenv("WHISPER_CPU_THREADS", "3"))
|
| 8 |
|
| 9 |
RETRANSCRIBE_MAX = 12
|
| 10 |
+
# Re-transcribe a sector with the precise model when the base model's confidence
|
| 11 |
+
# (avg_logprob) drops below this. Loosened from -0.55 → -0.40 so it actually fires
|
| 12 |
+
# on weak audio: the base model sits around -0.2…-0.5 on normal speech, so the old
|
| 13 |
+
# gate almost never triggered. -0.40 catches genuinely-shaky sectors; the budget
|
| 14 |
+
# (RETRANSCRIBE_MAX) and the per-sector cache keep it from running on everything.
|
| 15 |
+
PRECISE_LOGPROB_GATE = -0.40
|
| 16 |
|
| 17 |
CHUNK_SPLIT_THRESHOLD = 0.45
|
| 18 |
CHUNK_MIN_DURATION = 8.0
|
|
|
|
| 63 |
LLM_TEMPERATURE = 0.05
|
| 64 |
LLM_TIMEOUT = 120
|
| 65 |
|
| 66 |
+
# ── Upload limits & server-side compression ───────────────────────────────────
|
| 67 |
+
# The website rejects > MAX_UPLOAD_MB before upload; we re-check here because the
|
| 68 |
+
# client check is bypassable. Files over COMPRESS_TRIGGER_MB are transcoded down
|
| 69 |
+
# to an aggressive 720p / low-bitrate MP4 before decoding — NINA only needs the
|
| 70 |
+
# audio plus a handful of sampled frames, so quality loss is irrelevant and it
|
| 71 |
+
# makes frame extraction + decode noticeably faster on big uploads.
|
| 72 |
+
MAX_UPLOAD_MB = 200
|
| 73 |
+
COMPRESS_TRIGGER_MB = 20
|
| 74 |
+
COMPRESS_TARGET_HEIGHT = 720
|
| 75 |
+
COMPRESS_VIDEO_BITRATE = "1200k"
|
| 76 |
+
COMPRESS_AUDIO_BITRATE = "96k"
|
| 77 |
+
|
| 78 |
CACHE_DIR = os.path.join(tempfile.gettempdir(), "nina_cache")
|
| 79 |
DISK_CACHE = True
|
| 80 |
|
models.py
CHANGED
|
@@ -63,18 +63,30 @@ llm_client = InferenceClient(token=HF_TOKEN, timeout=LLM_TIMEOUT)
|
|
| 63 |
|
| 64 |
_whisper_precise = None
|
| 65 |
_whisper_precise_lock = threading.Lock()
|
|
|
|
| 66 |
|
| 67 |
|
| 68 |
-
def get_whisper_precise()
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
| 70 |
with _whisper_precise_lock:
|
|
|
|
|
|
|
| 71 |
if _whisper_precise is None:
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
return _whisper_precise
|
| 79 |
|
| 80 |
|
|
|
|
| 63 |
|
| 64 |
_whisper_precise = None
|
| 65 |
_whisper_precise_lock = threading.Lock()
|
| 66 |
+
_whisper_precise_failed = False
|
| 67 |
|
| 68 |
|
| 69 |
+
def get_whisper_precise():
|
| 70 |
+
"""Lazy-load the precise Whisper model. Returns None (never raises) if it can't
|
| 71 |
+
load — e.g. the model isn't downloadable or the Space is out of memory — so the
|
| 72 |
+
pipeline degrades to base-model text instead of crashing the request."""
|
| 73 |
+
global _whisper_precise, _whisper_precise_failed
|
| 74 |
with _whisper_precise_lock:
|
| 75 |
+
if _whisper_precise_failed:
|
| 76 |
+
return None
|
| 77 |
if _whisper_precise is None:
|
| 78 |
+
try:
|
| 79 |
+
print(f"[NINA] Loading Whisper {WHISPER_PRECISE} (faster-whisper)...")
|
| 80 |
+
_whisper_precise = WhisperModel(
|
| 81 |
+
WHISPER_PRECISE, device="cpu", compute_type="int8",
|
| 82 |
+
cpu_threads=WHISPER_CPU_THREADS,
|
| 83 |
+
)
|
| 84 |
+
print(f"[NINA] Whisper {WHISPER_PRECISE} ready.")
|
| 85 |
+
except Exception as e:
|
| 86 |
+
_whisper_precise_failed = True
|
| 87 |
+
print(f"[NINA] Whisper {WHISPER_PRECISE} failed to load: {e} "
|
| 88 |
+
f"— precise re-transcription disabled (using base text).")
|
| 89 |
+
return None
|
| 90 |
return _whisper_precise
|
| 91 |
|
| 92 |
|
pipeline.py
CHANGED
|
@@ -5,7 +5,11 @@ from concurrent.futures import ThreadPoolExecutor
|
|
| 5 |
from auth import verify_usage_token
|
| 6 |
from audio import fill_precise, load_audio, media_duration, transcribe_fast
|
| 7 |
from cache import _cache, disk_load, disk_save, disk_update_precise, evict_stale, fingerprint
|
| 8 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from retrieval import (
|
| 10 |
add_entities_to_chunks, bi_encode_retrieve, classify_query,
|
| 11 |
merge_regions, pad_with_neighbours, rerank_and_score,
|
|
@@ -25,6 +29,9 @@ def ingest_video(video_path: str) -> dict:
|
|
| 25 |
First sight of a video: decode audio, then run audio and visual branches
|
| 26 |
concurrently (CPU: transcription+chunking, MPS/GPU: CLIP).
|
| 27 |
"""
|
|
|
|
|
|
|
|
|
|
| 28 |
audio = load_audio(video_path)
|
| 29 |
duration = media_duration(video_path) or (len(audio) / SAMPLE_RATE)
|
| 30 |
|
|
@@ -98,6 +105,13 @@ def run(video_path: str, prompt: str, token: str = ""):
|
|
| 98 |
if not prompt or not prompt.strip():
|
| 99 |
yield "Please enter a prompt."
|
| 100 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
prompt = prompt.strip()
|
| 103 |
max_words = prompt_to_words(prompt)
|
|
|
|
| 5 |
from auth import verify_usage_token
|
| 6 |
from audio import fill_precise, load_audio, media_duration, transcribe_fast
|
| 7 |
from cache import _cache, disk_load, disk_save, disk_update_precise, evict_stale, fingerprint
|
| 8 |
+
from compress import ensure_compressed, file_mb, too_large
|
| 9 |
+
from config import (
|
| 10 |
+
RETRANSCRIBE_MAX, BI_SCORE_GLOBAL_FLOOR, BI_SCORE_HYBRID_FLOOR,
|
| 11 |
+
MAX_UPLOAD_MB, SAMPLE_RATE,
|
| 12 |
+
)
|
| 13 |
from retrieval import (
|
| 14 |
add_entities_to_chunks, bi_encode_retrieve, classify_query,
|
| 15 |
merge_regions, pad_with_neighbours, rerank_and_score,
|
|
|
|
| 29 |
First sight of a video: decode audio, then run audio and visual branches
|
| 30 |
concurrently (CPU: transcription+chunking, MPS/GPU: CLIP).
|
| 31 |
"""
|
| 32 |
+
# Big uploads get an aggressive 720p re-encode first (best-effort, no-op when
|
| 33 |
+
# already small) so audio decode + frame sampling run on a lean file.
|
| 34 |
+
video_path = ensure_compressed(video_path)
|
| 35 |
audio = load_audio(video_path)
|
| 36 |
duration = media_duration(video_path) or (len(audio) / SAMPLE_RATE)
|
| 37 |
|
|
|
|
| 105 |
if not prompt or not prompt.strip():
|
| 106 |
yield "Please enter a prompt."
|
| 107 |
return
|
| 108 |
+
if too_large(video_path):
|
| 109 |
+
yield (
|
| 110 |
+
f"⛔ This video is too large ({file_mb(video_path):.0f} MB).\n\n"
|
| 111 |
+
f"The maximum is {MAX_UPLOAD_MB} MB. Please upload a shorter clip, or compress "
|
| 112 |
+
f"it first (the app at https://app.nnlabs.pl/nina shrinks large videos for you)."
|
| 113 |
+
)
|
| 114 |
+
return
|
| 115 |
|
| 116 |
prompt = prompt.strip()
|
| 117 |
max_words = prompt_to_words(prompt)
|
requirements.txt
CHANGED
|
@@ -9,6 +9,7 @@ gradio==6.14.0
|
|
| 9 |
ffmpeg-python==0.2.0
|
| 10 |
numpy==2.4.6
|
| 11 |
Pillow==12.2.0
|
|
|
|
| 12 |
|
| 13 |
# ── ML / inference ──
|
| 14 |
torch==2.12.0
|
|
|
|
| 9 |
ffmpeg-python==0.2.0
|
| 10 |
numpy==2.4.6
|
| 11 |
Pillow==12.2.0
|
| 12 |
+
langdetect==1.0.9 # robust prompt-language detection (answer in user's language)
|
| 13 |
|
| 14 |
# ── ML / inference ──
|
| 15 |
torch==2.12.0
|
synthesis.py
CHANGED
|
@@ -73,8 +73,40 @@ _GERMAN_CHARS = frozenset("äöüÄÖÜß")
|
|
| 73 |
_FRENCH_CHARS = frozenset("àâæçéèêëîïôœùûüÿÀÂÆÇÉÈÊËÎÏÔŒÙÛÜŸ")
|
| 74 |
_SPANISH_CHARS = frozenset("áéíóúüñ¡¿ÁÉÍÓÚÜÑ")
|
| 75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
def _detect_language(text: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
if any(c in text for c in _POLISH_CHARS):
|
| 79 |
return "Polish"
|
| 80 |
if any(c in text for c in _GERMAN_CHARS):
|
|
@@ -86,23 +118,30 @@ def _detect_language(text: str) -> str:
|
|
| 86 |
return "English"
|
| 87 |
|
| 88 |
|
| 89 |
-
def _make_system_msg(language: str) -> str:
|
| 90 |
return (
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
f"
|
| 94 |
-
"
|
| 95 |
-
"
|
| 96 |
-
"
|
| 97 |
-
"
|
| 98 |
-
"
|
| 99 |
-
"
|
| 100 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
)
|
| 102 |
|
| 103 |
|
| 104 |
_STRONG_CONF = 0.45
|
| 105 |
-
_TS_LINE = re.compile(r'^\[(\d+:\d{2}(?:\.\d+)?(?:\s*[→\-]\s*\d+:\d{2}(?:\.\d+)?)?)\]')
|
| 106 |
|
| 107 |
|
| 108 |
def _render_region(r: dict) -> str:
|
|
@@ -117,13 +156,6 @@ def _render_region(r: dict) -> str:
|
|
| 117 |
return block
|
| 118 |
|
| 119 |
|
| 120 |
-
def _enforce_citations(text: str) -> str:
|
| 121 |
-
"""Keep only lines that begin with a [M:SS] timestamp. Returns original if all stripped."""
|
| 122 |
-
lines = text.splitlines()
|
| 123 |
-
cited = [ln.strip() for ln in lines if ln.strip() and _TS_LINE.match(ln.strip())]
|
| 124 |
-
return "\n".join(cited) if cited else text
|
| 125 |
-
|
| 126 |
-
|
| 127 |
def _build_synth_prompt(regions: list[dict], prompt: str, max_words: int, mode: str) -> str:
|
| 128 |
strong = [r for r in regions if r.get("confidence", 1.0) >= _STRONG_CONF]
|
| 129 |
context = [r for r in regions if r.get("confidence", 1.0) < _STRONG_CONF]
|
|
@@ -141,7 +173,7 @@ def _build_synth_prompt(regions: list[dict], prompt: str, max_words: int, mode:
|
|
| 141 |
|
| 142 |
if mode == "global":
|
| 143 |
task_line = (
|
| 144 |
-
"Task: Give a factual overview of what this video covers, "
|
| 145 |
"drawing only from the fragments below."
|
| 146 |
)
|
| 147 |
else:
|
|
@@ -151,17 +183,17 @@ def _build_synth_prompt(regions: list[dict], prompt: str, max_words: int, mode:
|
|
| 151 |
|
| 152 |
return (
|
| 153 |
f'User question: "{prompt}"\n\n'
|
| 154 |
-
f"Video
|
|
|
|
| 155 |
f"{task_line}\n\n"
|
| 156 |
-
f"
|
| 157 |
-
f"-
|
| 158 |
-
f"
|
| 159 |
-
f"-
|
| 160 |
-
f"
|
| 161 |
-
f"-
|
| 162 |
-
f"
|
| 163 |
-
f"-
|
| 164 |
-
f"- If nothing is relevant: write exactly: [0:00.00] No relevant content found.\n"
|
| 165 |
)
|
| 166 |
|
| 167 |
|
|
@@ -189,8 +221,9 @@ def llm_synthesize_stream(
|
|
| 189 |
stream = llm_client.chat_completion(
|
| 190 |
model=LLM_MODEL,
|
| 191 |
messages=[
|
| 192 |
-
{"role": "system",
|
| 193 |
-
|
|
|
|
| 194 |
],
|
| 195 |
max_tokens=LLM_MAX_TOKENS,
|
| 196 |
temperature=LLM_TEMPERATURE,
|
|
@@ -206,12 +239,6 @@ def llm_synthesize_stream(
|
|
| 206 |
if not acc.strip():
|
| 207 |
yield _fallback_summary(regions)
|
| 208 |
return
|
| 209 |
-
# Post-stream: strip any uncited lines (structural hallucination guard)
|
| 210 |
-
clean = _enforce_citations(acc.strip())
|
| 211 |
-
if clean != acc.strip():
|
| 212 |
-
if DEBUG:
|
| 213 |
-
print(f"[DEBUG] Citation enforcement removed uncited lines.")
|
| 214 |
-
yield clean
|
| 215 |
except Exception as e:
|
| 216 |
print(f"[NINA] Synthesis error: {e}")
|
| 217 |
yield _fallback_summary(regions)
|
|
|
|
| 73 |
_FRENCH_CHARS = frozenset("àâæçéèêëîïôœùûüÿÀÂÆÇÉÈÊËÎÏÔŒÙÛÜŸ")
|
| 74 |
_SPANISH_CHARS = frozenset("áéíóúüñ¡¿ÁÉÍÓÚÜÑ")
|
| 75 |
|
| 76 |
+
# ISO-639-1 → English name, for the languages langdetect distinguishes that matter
|
| 77 |
+
# to NINA's users. Anything else falls back to the system prompt's "same language
|
| 78 |
+
# as the question" instruction, which Qwen handles well on its own.
|
| 79 |
+
_LANG_NAMES = {
|
| 80 |
+
"en": "English", "pl": "Polish", "de": "German", "fr": "French",
|
| 81 |
+
"es": "Spanish", "it": "Italian", "pt": "Portuguese", "nl": "Dutch",
|
| 82 |
+
"ru": "Russian", "uk": "Ukrainian", "cs": "Czech", "sk": "Slovak",
|
| 83 |
+
"sv": "Swedish", "no": "Norwegian", "da": "Danish", "fi": "Finnish",
|
| 84 |
+
"tr": "Turkish", "ro": "Romanian", "hu": "Hungarian", "el": "Greek",
|
| 85 |
+
"bg": "Bulgarian", "hr": "Croatian", "lt": "Lithuanian", "lv": "Latvian",
|
| 86 |
+
"et": "Estonian", "sl": "Slovenian", "ja": "Japanese", "ko": "Korean",
|
| 87 |
+
"zh": "Chinese", "zh-cn": "Chinese", "zh-tw": "Chinese", "ar": "Arabic",
|
| 88 |
+
"he": "Hebrew", "hi": "Hindi", "id": "Indonesian", "vi": "Vietnamese",
|
| 89 |
+
"th": "Thai", "ca": "Catalan",
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
|
| 93 |
def _detect_language(text: str) -> str:
|
| 94 |
+
"""Best-effort language of the user's prompt. Tries langdetect (robust on prompts
|
| 95 |
+
with no diacritics, e.g. Polish typed without accents), then a diacritic
|
| 96 |
+
heuristic, then English. The result is only a *hint*; the system prompt also
|
| 97 |
+
tells the model to mirror the question's language, so a wrong guess self-corrects."""
|
| 98 |
+
stripped = (text or "").strip()
|
| 99 |
+
if stripped:
|
| 100 |
+
try:
|
| 101 |
+
from langdetect import detect, DetectorFactory
|
| 102 |
+
DetectorFactory.seed = 0
|
| 103 |
+
code = detect(stripped).lower()
|
| 104 |
+
name = _LANG_NAMES.get(code) or _LANG_NAMES.get(code.split("-")[0])
|
| 105 |
+
if name:
|
| 106 |
+
return name
|
| 107 |
+
except Exception:
|
| 108 |
+
pass # langdetect missing or undecidable → fall through to heuristics
|
| 109 |
+
|
| 110 |
if any(c in text for c in _POLISH_CHARS):
|
| 111 |
return "Polish"
|
| 112 |
if any(c in text for c in _GERMAN_CHARS):
|
|
|
|
| 118 |
return "English"
|
| 119 |
|
| 120 |
|
| 121 |
+
def _make_system_msg(language: str, max_words: int, tier: str) -> str:
|
| 122 |
return (
|
| 123 |
+
"You are NINA, a sharp assistant that answers questions about a video using ONLY "
|
| 124 |
+
"the transcript fragments and on-screen cues you are given.\n\n"
|
| 125 |
+
f"LANGUAGE — Write your ENTIRE answer in the same language as the user's question "
|
| 126 |
+
f"(it looks like {language}). Never switch languages, even if the transcript is in "
|
| 127 |
+
f"another language: report its content in the user's language. Keep names, numbers, "
|
| 128 |
+
f"brands, titles and direct quotes exactly as they appear — do not translate, "
|
| 129 |
+
f"re-spell or reinterpret those.\n\n"
|
| 130 |
+
f"LENGTH — Fit the answer to the question. Aim for about {max_words} words at most "
|
| 131 |
+
f"({tier}); be shorter when the video covers little. Never pad. Answer the question "
|
| 132 |
+
f"directly, with no preamble like \"The video says…\".\n\n"
|
| 133 |
+
"GROUNDING — Use only what the fragments state. Never invent, infer, guess, or "
|
| 134 |
+
"complete partial words, names or numbers. If the fragments don't address the "
|
| 135 |
+
"question, say so plainly (in the user's language) instead of speculating. Don't "
|
| 136 |
+
"fix grammar inside quoted speech.\n\n"
|
| 137 |
+
"FORMAT — Write a natural, flowing answer in prose (sentences or short paragraphs). "
|
| 138 |
+
"Do NOT begin lines with timestamps. After the answer, add exactly one final line "
|
| 139 |
+
"listing the moments you drew from, in this form:\n"
|
| 140 |
+
"Sources: [m:ss], [m:ss]"
|
| 141 |
)
|
| 142 |
|
| 143 |
|
| 144 |
_STRONG_CONF = 0.45
|
|
|
|
| 145 |
|
| 146 |
|
| 147 |
def _render_region(r: dict) -> str:
|
|
|
|
| 156 |
return block
|
| 157 |
|
| 158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
def _build_synth_prompt(regions: list[dict], prompt: str, max_words: int, mode: str) -> str:
|
| 160 |
strong = [r for r in regions if r.get("confidence", 1.0) >= _STRONG_CONF]
|
| 161 |
context = [r for r in regions if r.get("confidence", 1.0) < _STRONG_CONF]
|
|
|
|
| 173 |
|
| 174 |
if mode == "global":
|
| 175 |
task_line = (
|
| 176 |
+
"Task: Give a natural, factual overview of what this video covers, "
|
| 177 |
"drawing only from the fragments below."
|
| 178 |
)
|
| 179 |
else:
|
|
|
|
| 183 |
|
| 184 |
return (
|
| 185 |
f'User question: "{prompt}"\n\n'
|
| 186 |
+
f"Video fragments (each headed by its [m:ss → m:ss] timestamp):\n\n"
|
| 187 |
+
f"{fragments}{context_section}\n\n"
|
| 188 |
f"{task_line}\n\n"
|
| 189 |
+
f"How to write the answer:\n"
|
| 190 |
+
f"- Reply in the SAME language as the user's question above.\n"
|
| 191 |
+
f"- Write naturally, in prose — do NOT prefix lines with timestamps.\n"
|
| 192 |
+
f"- Ground every statement only in the fragments; never merge two fragments into a "
|
| 193 |
+
f"single claim, and don't derive new claims from the supporting-context blocks alone.\n"
|
| 194 |
+
f"- Keep it to about {max_words} words at most; be shorter if the material is thin.\n"
|
| 195 |
+
f"- If nothing above is relevant, say that plainly in the user's language.\n"
|
| 196 |
+
f"- End with one line: Sources: followed by the [m:ss] start-times you actually used."
|
|
|
|
| 197 |
)
|
| 198 |
|
| 199 |
|
|
|
|
| 221 |
stream = llm_client.chat_completion(
|
| 222 |
model=LLM_MODEL,
|
| 223 |
messages=[
|
| 224 |
+
{"role": "system",
|
| 225 |
+
"content": _make_system_msg(language, max_words, _summary_tier(max_words))},
|
| 226 |
+
{"role": "user", "content": synth_prompt},
|
| 227 |
],
|
| 228 |
max_tokens=LLM_MAX_TOKENS,
|
| 229 |
temperature=LLM_TEMPERATURE,
|
|
|
|
| 239 |
if not acc.strip():
|
| 240 |
yield _fallback_summary(regions)
|
| 241 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
except Exception as e:
|
| 243 |
print(f"[NINA] Synthesis error: {e}")
|
| 244 |
yield _fallback_summary(regions)
|