Spaces:
Paused
Paused
Malina Claude Opus 4.8 commited on
Commit Β·
729fbc4
1
Parent(s): f1e4c89
NINA Phase 3b: OCR burned-in captions (RapidOCR) as the last fallback rung
Browse filesFinal rung of the transcript ladder: when the audio stays unreliable, there's no
embedded subtitle track, AND CLIP detects on-screen text, OCR the bottom strip of
sampled frames and collapse repeated cues into timed segments.
- ocr.py: RapidOCR (onnxruntime) over ffmpeg-sampled frames, best-effort.
- visual.has_on_screen_text(): CLIP gate so OCR stays off for most videos.
- pipeline: post-ingest OCR fallback, rebuilds chunks + re-attaches speakers.
- deps: rapidocr-onnxruntime; packages.txt adds libgl1/libglib2.0-0 for OpenCV.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- config.py +11 -0
- ocr.py +120 -0
- packages.txt +3 -1
- pipeline.py +18 -2
- requirements.txt +1 -0
- visual.py +25 -1
config.py
CHANGED
|
@@ -114,6 +114,17 @@ SUBTITLE_TEXT_CODECS = frozenset({
|
|
| 114 |
"subrip", "srt", "ass", "ssa", "mov_text", "webvtt", "vtt", "text", "eia_608",
|
| 115 |
})
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
# ββ Speaker diarization (pyannote) + name attribution βββββββββββββββββββββββββ
|
| 118 |
# Identifies who-spoke-when; synthesis then attributes lines and maps a speaker to
|
| 119 |
# a name when they introduce themselves. Gated models β the Space's HF_TOKEN must
|
|
|
|
| 114 |
"subrip", "srt", "ass", "ssa", "mov_text", "webvtt", "vtt", "text", "eia_608",
|
| 115 |
})
|
| 116 |
|
| 117 |
+
# OCR of burned-in (hardcoded) captions β the LAST rung. Only runs when the audio
|
| 118 |
+
# stayed unreliable, there was no embedded sub track, AND CLIP actually sees text
|
| 119 |
+
# on screen, so it's off for the vast majority of videos. RapidOCR (onnxruntime).
|
| 120 |
+
USE_OCR = True
|
| 121 |
+
OCR_FPS = 1.0 # sample ~1 frame/sec
|
| 122 |
+
OCR_MAX_FRAMES = 90
|
| 123 |
+
OCR_FRAME_W = 1280
|
| 124 |
+
OCR_FRAME_H = 720
|
| 125 |
+
OCR_BOTTOM_FRACTION = 0.34 # crop the bottom third (where captions sit)
|
| 126 |
+
VISUAL_ONSCREEN_TEXT_SIM = 0.22 # CLIP gate: frames must look like they contain text
|
| 127 |
+
|
| 128 |
# ββ Speaker diarization (pyannote) + name attribution βββββββββββββββββββββββββ
|
| 129 |
# Identifies who-spoke-when; synthesis then attributes lines and maps a speaker to
|
| 130 |
# a name when they introduce themselves. Gated models β the Space's HF_TOKEN must
|
ocr.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 2 |
+
# NINA β OCR of burned-in (hardcoded) captions
|
| 3 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 4 |
+
# Last-resort transcript source: when the audio is unreliable, there's no embedded
|
| 5 |
+
# subtitle track, and the frames actually contain on-screen text, read the captions
|
| 6 |
+
# burned into the picture. Uses RapidOCR (onnxruntime β already a dependency) on the
|
| 7 |
+
# bottom strip of sampled frames, then collapses repeated cues into timed segments.
|
| 8 |
+
#
|
| 9 |
+
# Best-effort: any failure returns [] and the pipeline keeps the ASR transcript.
|
| 10 |
+
|
| 11 |
+
import difflib
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import ffmpeg
|
| 15 |
+
|
| 16 |
+
from config import (
|
| 17 |
+
OCR_BOTTOM_FRACTION, OCR_FPS, OCR_FRAME_H, OCR_FRAME_W, OCR_MAX_FRAMES,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
_engine = None
|
| 21 |
+
_failed = False
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _get_engine():
|
| 25 |
+
global _engine, _failed
|
| 26 |
+
if _failed:
|
| 27 |
+
return None
|
| 28 |
+
if _engine is None:
|
| 29 |
+
try:
|
| 30 |
+
from rapidocr_onnxruntime import RapidOCR
|
| 31 |
+
_engine = RapidOCR()
|
| 32 |
+
print("[NINA] OCR engine ready (RapidOCR/onnxruntime).")
|
| 33 |
+
except Exception as e:
|
| 34 |
+
_failed = True
|
| 35 |
+
print(f"[NINA] OCR unavailable: {e} β skipping burned-in captions.")
|
| 36 |
+
return None
|
| 37 |
+
return _engine
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _sample_frames(video_path: str, duration: float):
|
| 41 |
+
"""Even frames at OCR_FPS (capped), forced to OCR_FRAME_WΓH. Returns (frames, times)."""
|
| 42 |
+
fps = OCR_FPS
|
| 43 |
+
if duration and duration > 0:
|
| 44 |
+
fps = min(OCR_FPS, max(0.05, OCR_MAX_FRAMES / duration))
|
| 45 |
+
W, H = OCR_FRAME_W, OCR_FRAME_H
|
| 46 |
+
try:
|
| 47 |
+
out, _ = (
|
| 48 |
+
ffmpeg.input(video_path)
|
| 49 |
+
.filter("fps", fps=fps)
|
| 50 |
+
.filter("scale", W, H)
|
| 51 |
+
.output("pipe:", format="rawvideo", pix_fmt="rgb24")
|
| 52 |
+
.run(capture_stdout=True, capture_stderr=True)
|
| 53 |
+
)
|
| 54 |
+
except ffmpeg.Error:
|
| 55 |
+
return np.zeros((0, H, W, 3), dtype=np.uint8), np.zeros((0,))
|
| 56 |
+
if not out:
|
| 57 |
+
return np.zeros((0, H, W, 3), dtype=np.uint8), np.zeros((0,))
|
| 58 |
+
frames = np.frombuffer(out, np.uint8).reshape(-1, H, W, 3)[:OCR_MAX_FRAMES]
|
| 59 |
+
times = np.array([(i + 0.5) / fps for i in range(len(frames))])
|
| 60 |
+
return frames, times
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _read_frame(engine, img: np.ndarray) -> str:
|
| 64 |
+
"""OCR the bottom strip of one frame β a single cleaned line of caption text."""
|
| 65 |
+
h = img.shape[0]
|
| 66 |
+
strip = img[int(h * (1.0 - OCR_BOTTOM_FRACTION)):, :, :]
|
| 67 |
+
try:
|
| 68 |
+
result, _ = engine(strip)
|
| 69 |
+
except Exception:
|
| 70 |
+
return ""
|
| 71 |
+
if not result:
|
| 72 |
+
return ""
|
| 73 |
+
# result: list of [box, text, score]; keep confident lines, join in reading order.
|
| 74 |
+
parts = [r[1].strip() for r in result if len(r) >= 3 and r[2] and r[2] >= 0.5 and r[1].strip()]
|
| 75 |
+
return " ".join(parts).strip()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _similar(a: str, b: str) -> bool:
|
| 79 |
+
if not a or not b:
|
| 80 |
+
return False
|
| 81 |
+
return difflib.SequenceMatcher(None, a, b).ratio() >= 0.8
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def ocr_burned_in(video_path: str, duration: float) -> list[dict]:
|
| 85 |
+
"""Return burned-in caption text as [{text,start,end}] segments, or []."""
|
| 86 |
+
try:
|
| 87 |
+
engine = _get_engine()
|
| 88 |
+
if engine is None:
|
| 89 |
+
return []
|
| 90 |
+
frames, times = _sample_frames(video_path, duration)
|
| 91 |
+
if len(frames) == 0:
|
| 92 |
+
return []
|
| 93 |
+
|
| 94 |
+
segments: list[dict] = []
|
| 95 |
+
cur_text, cur_start, cur_end = None, None, None
|
| 96 |
+
step = (1.0 / OCR_FPS) if OCR_FPS else 1.0
|
| 97 |
+
|
| 98 |
+
for img, t in zip(frames, times):
|
| 99 |
+
text = _read_frame(engine, img)
|
| 100 |
+
if cur_text and (text == cur_text or _similar(text, cur_text)):
|
| 101 |
+
cur_end = t # same caption persisting
|
| 102 |
+
continue
|
| 103 |
+
if cur_text: # caption changed β close the previous one
|
| 104 |
+
segments.append({"text": cur_text, "start": round(cur_start, 2),
|
| 105 |
+
"end": round((cur_end or cur_start) + step, 2)})
|
| 106 |
+
cur_text = text or None
|
| 107 |
+
cur_start = t if text else None
|
| 108 |
+
cur_end = t if text else None
|
| 109 |
+
|
| 110 |
+
if cur_text:
|
| 111 |
+
segments.append({"text": cur_text, "start": round(cur_start, 2),
|
| 112 |
+
"end": round((cur_end or cur_start) + step, 2)})
|
| 113 |
+
|
| 114 |
+
segments = [s for s in segments if len(s["text"]) >= 3]
|
| 115 |
+
if segments:
|
| 116 |
+
print(f"[NINA] OCR recovered {len(segments)} on-screen caption(s).")
|
| 117 |
+
return segments
|
| 118 |
+
except Exception as e:
|
| 119 |
+
print(f"[NINA] OCR failed: {e}")
|
| 120 |
+
return []
|
packages.txt
CHANGED
|
@@ -1 +1,3 @@
|
|
| 1 |
-
ffmpeg
|
|
|
|
|
|
|
|
|
| 1 |
+
ffmpeg
|
| 2 |
+
libgl1
|
| 3 |
+
libglib2.0-0
|
pipeline.py
CHANGED
|
@@ -10,13 +10,14 @@ from cache import _cache, disk_load, disk_save, disk_update_precise, evict_stale
|
|
| 10 |
from compress import ensure_compressed, file_mb, too_large
|
| 11 |
from config import (
|
| 12 |
RETRANSCRIBE_MAX, BI_SCORE_GLOBAL_FLOOR, BI_SCORE_HYBRID_FLOOR,
|
| 13 |
-
MAX_UPLOAD_MB, USE_DIARIZATION, USE_SUBTITLES, USE_VOCAL_ISOLATION,
|
| 14 |
)
|
| 15 |
from diarize import (
|
| 16 |
annotate_region_speakers, attach_speakers, diarize, name_roster,
|
| 17 |
speaker_display_map, speaker_note,
|
| 18 |
)
|
| 19 |
from enhance import isolate_vocals
|
|
|
|
| 20 |
from subtitles import extract_embedded_subs
|
| 21 |
from retrieval import (
|
| 22 |
add_entities_to_chunks, bi_encode_retrieve, classify_query,
|
|
@@ -27,7 +28,7 @@ from synthesis import (
|
|
| 27 |
_fallback_summary, format_output, llm_synthesize_stream, prompt_to_words,
|
| 28 |
words_to_global_chunks,
|
| 29 |
)
|
| 30 |
-
from visual import add_visual_tags, analyze_visual, visual_scores
|
| 31 |
|
| 32 |
|
| 33 |
# ββ Cold-start ingestion βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -92,6 +93,21 @@ def ingest_video(video_path: str) -> dict:
|
|
| 92 |
|
| 93 |
# Tag the final transcript with speaker labels (needs both branches done).
|
| 94 |
attach_speakers(result["segments"], result.get("turns") or [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
print("[NINA] Ingest done β audio, visual and speakers ready.")
|
| 96 |
|
| 97 |
return {
|
|
|
|
| 10 |
from compress import ensure_compressed, file_mb, too_large
|
| 11 |
from config import (
|
| 12 |
RETRANSCRIBE_MAX, BI_SCORE_GLOBAL_FLOOR, BI_SCORE_HYBRID_FLOOR,
|
| 13 |
+
MAX_UPLOAD_MB, USE_DIARIZATION, USE_OCR, USE_SUBTITLES, USE_VOCAL_ISOLATION,
|
| 14 |
)
|
| 15 |
from diarize import (
|
| 16 |
annotate_region_speakers, attach_speakers, diarize, name_roster,
|
| 17 |
speaker_display_map, speaker_note,
|
| 18 |
)
|
| 19 |
from enhance import isolate_vocals
|
| 20 |
+
from ocr import ocr_burned_in
|
| 21 |
from subtitles import extract_embedded_subs
|
| 22 |
from retrieval import (
|
| 23 |
add_entities_to_chunks, bi_encode_retrieve, classify_query,
|
|
|
|
| 28 |
_fallback_summary, format_output, llm_synthesize_stream, prompt_to_words,
|
| 29 |
words_to_global_chunks,
|
| 30 |
)
|
| 31 |
+
from visual import add_visual_tags, analyze_visual, has_on_screen_text, visual_scores
|
| 32 |
|
| 33 |
|
| 34 |
# ββ Cold-start ingestion βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 93 |
|
| 94 |
# Tag the final transcript with speaker labels (needs both branches done).
|
| 95 |
attach_speakers(result["segments"], result.get("turns") or [])
|
| 96 |
+
|
| 97 |
+
# Last rung of the ladder: if the audio transcript is STILL unreliable, there was
|
| 98 |
+
# no embedded sub track, and the frames actually contain on-screen text, OCR the
|
| 99 |
+
# burned-in captions and use those instead.
|
| 100 |
+
if USE_OCR:
|
| 101 |
+
rel = transcript_reliability(result["segments"])
|
| 102 |
+
if not rel["reliable"] and has_on_screen_text(result["visual"]):
|
| 103 |
+
print(f"[NINA] Transcript still weak (score {rel['score']}) + on-screen text "
|
| 104 |
+
f"detected β reading burned-in captions (OCR)β¦")
|
| 105 |
+
ocr_segs = ocr_burned_in(video_path, media_duration(video_path))
|
| 106 |
+
if ocr_segs:
|
| 107 |
+
result["segments"] = ocr_segs
|
| 108 |
+
result["chunks"] = add_entities_to_chunks(semantic_chunk(ocr_segs))
|
| 109 |
+
attach_speakers(result["segments"], result.get("turns") or [])
|
| 110 |
+
|
| 111 |
print("[NINA] Ingest done β audio, visual and speakers ready.")
|
| 112 |
|
| 113 |
return {
|
requirements.txt
CHANGED
|
@@ -24,3 +24,4 @@ huggingface-hub==1.15.0
|
|
| 24 |
faster-whisper==1.2.1
|
| 25 |
ctranslate2==4.7.2
|
| 26 |
onnxruntime==1.26.0
|
|
|
|
|
|
| 24 |
faster-whisper==1.2.1
|
| 25 |
ctranslate2==4.7.2
|
| 26 |
onnxruntime==1.26.0
|
| 27 |
+
rapidocr-onnxruntime==1.4.4 # OCR of burned-in captions (needs libgl1 β see packages.txt)
|
visual.py
CHANGED
|
@@ -4,7 +4,8 @@ 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,
|
|
|
|
| 8 |
)
|
| 9 |
from models import TORCH_DEVICE, get_clip, get_concept_embs
|
| 10 |
|
|
@@ -127,3 +128,26 @@ def add_visual_tags(regions: list[dict], visual: dict) -> list[dict]:
|
|
| 127 |
for r in regions:
|
| 128 |
r["visual_tags"] = region_visual_tags(visual, r["start"], r["end"])
|
| 129 |
return regions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
from config import (
|
| 6 |
CLIP_FRAME_SIZE, CLIP_MAX_FRAMES, CLIP_MAX_FPS, CLIP_MIN_FPS,
|
| 7 |
+
DEBUG, VISUAL_CONCEPTS, VISUAL_ONSCREEN_TEXT_SIM, VISUAL_TAG_MIN_SIM,
|
| 8 |
+
VISUAL_TAGS_TOP_K,
|
| 9 |
)
|
| 10 |
from models import TORCH_DEVICE, get_clip, get_concept_embs
|
| 11 |
|
|
|
|
| 128 |
for r in regions:
|
| 129 |
r["visual_tags"] = region_visual_tags(visual, r["start"], r["end"])
|
| 130 |
return regions
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# Concepts that imply readable on-screen text β the gate for the OCR fallback.
|
| 134 |
+
_TEXT_CONCEPT_IDX = [
|
| 135 |
+
i for i, c in enumerate(VISUAL_CONCEPTS)
|
| 136 |
+
if any(k in c.lower() for k in ("text on screen", "source code", "webpage",
|
| 137 |
+
"screen recording", "slides"))
|
| 138 |
+
]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def has_on_screen_text(visual: dict) -> bool:
|
| 142 |
+
"""True if any frame looks like it contains readable text β used to decide whether
|
| 143 |
+
OCR of burned-in captions is worth attempting."""
|
| 144 |
+
embs = visual.get("emb")
|
| 145 |
+
if embs is None or len(embs) == 0 or not _TEXT_CONCEPT_IDX:
|
| 146 |
+
return False
|
| 147 |
+
try:
|
| 148 |
+
concepts = get_concept_embs()[_TEXT_CONCEPT_IDX] # (k, D), normalised
|
| 149 |
+
en = embs / (np.linalg.norm(embs, axis=1, keepdims=True) + 1e-9)
|
| 150 |
+
sims = en @ concepts.T # (frames, k)
|
| 151 |
+
return float(sims.max()) >= VISUAL_ONSCREEN_TEXT_SIM
|
| 152 |
+
except Exception:
|
| 153 |
+
return False
|