Malina Claude Opus 4.8 commited on
Commit
6acd603
Β·
1 Parent(s): 264efa2

NINA: anti-hallucination ASR + honest low-confidence handling (Phase 1)

Browse files

On noisy/musical/distorted audio Whisper fabricates fluent nonsense, and the LLM
was reporting it as fact. Now:
- transcribe_fast gets hallucination guards (no_speech/log_prob/compression-ratio
thresholds, condition_on_previous_text=False) and records no_speech_prob +
compression_ratio per segment
- transcript_reliability() scores the transcript; an unreliable one (poor mean
logprob / mostly weak / mostly no-speech) is flagged
- synthesis: when unreliable, the system prompt tells the model the audio is hard
to make out and to say so plainly instead of inventing meaning for garbled text

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

Files changed (4) hide show
  1. audio.py +55 -5
  2. config.py +20 -0
  3. pipeline.py +16 -7
  4. synthesis.py +23 -5
audio.py CHANGED
@@ -3,7 +3,11 @@ 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
@@ -23,22 +27,68 @@ def media_duration(media_path: str) -> float:
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
 
 
3
  from faster_whisper.audio import decode_audio
4
 
5
  from config import (
6
+ ASR_NO_SPEECH_CEILING, ASR_RELIABILITY_LOGPROB_FLOOR,
7
+ ASR_UNRELIABLE_WEAK_FRACTION, ASR_WEAK_SEGMENT_LOGPROB,
8
  DEBUG, PRECISE_LOGPROB_GATE, RETRANSCRIBE_MAX, SAMPLE_RATE,
9
+ WHISPER_COMPRESSION_RATIO_THRESHOLD, WHISPER_CONDITION_ON_PREV,
10
+ WHISPER_LOGPROB_THRESHOLD, WHISPER_NO_SPEECH_THRESHOLD,
11
  )
12
  from models import get_whisper_precise, whisper_fast
13
  from utils import fmt_time
 
27
 
28
 
29
  def transcribe_fast(audio: np.ndarray) -> list[dict]:
30
+ """Base-model full-video pass: greedy + Silero VAD, with hallucination guards.
31
+
32
+ Stores avg_logprob, no_speech_prob and compression_ratio per segment so the
33
+ pipeline can judge how trustworthy the transcript is (see transcript_reliability).
34
+ """
35
  segments_gen, _ = whisper_fast.transcribe(
36
  audio, beam_size=1, vad_filter=True, word_timestamps=False,
37
+ condition_on_previous_text=WHISPER_CONDITION_ON_PREV,
38
+ no_speech_threshold=WHISPER_NO_SPEECH_THRESHOLD,
39
+ log_prob_threshold=WHISPER_LOGPROB_THRESHOLD,
40
+ compression_ratio_threshold=WHISPER_COMPRESSION_RATIO_THRESHOLD,
41
  )
42
  return [
43
  {
44
+ "text": seg.text.strip(),
45
+ "start": round(seg.start, 2),
46
+ "end": round(seg.end, 2),
47
+ "logprob": round(float(getattr(seg, "avg_logprob", 0.0) or 0.0), 3),
48
+ "no_speech": round(float(getattr(seg, "no_speech_prob", 0.0) or 0.0), 3),
49
+ "comp_ratio": round(float(getattr(seg, "compression_ratio", 0.0) or 0.0), 3),
50
  }
51
  for seg in segments_gen
52
  if seg.text.strip()
53
  ]
54
 
55
 
56
+ def transcript_reliability(segments: list[dict]) -> dict:
57
+ """Judge how trustworthy a base-model transcript is, so synthesis can hedge on
58
+ garbled/musical audio instead of reporting Whisper's fabrications as fact.
59
+
60
+ Returns {reliable: bool, score: 0..1, mean_logprob, weak_fraction, mean_no_speech}.
61
+ """
62
+ if not segments:
63
+ return {"reliable": False, "score": 0.0, "mean_logprob": 0.0,
64
+ "weak_fraction": 1.0, "mean_no_speech": 1.0}
65
+
66
+ lps = [s.get("logprob", 0.0) for s in segments]
67
+ nsp = [s.get("no_speech", 0.0) for s in segments]
68
+ mean_lp = sum(lps) / len(lps)
69
+ mean_nsp = sum(nsp) / len(nsp)
70
+ weak_frac = sum(1 for lp in lps if lp < ASR_WEAK_SEGMENT_LOGPROB) / len(lps)
71
+
72
+ reliable = (
73
+ mean_lp >= ASR_RELIABILITY_LOGPROB_FLOOR
74
+ and weak_frac < ASR_UNRELIABLE_WEAK_FRACTION
75
+ and mean_nsp < ASR_NO_SPEECH_CEILING
76
+ )
77
+ # Rough 0..1 confidence: avg_logprob of ~0 β†’ 1.0, ~-1.0 β†’ 0.0.
78
+ score = max(0.0, min(1.0, 1.0 + mean_lp))
79
+
80
+ info = {
81
+ "reliable": bool(reliable),
82
+ "score": round(score, 3),
83
+ "mean_logprob": round(mean_lp, 3),
84
+ "weak_fraction": round(weak_frac, 3),
85
+ "mean_no_speech": round(mean_nsp, 3),
86
+ }
87
+ if DEBUG:
88
+ print(f"[DEBUG] ASR reliability: {info}")
89
+ return info
90
+
91
+
92
  def retranscribe_region(audio: np.ndarray, region: dict) -> str:
93
  """Slice waveform in-memory and run precise Whisper on the slice.
94
 
config.py CHANGED
@@ -14,6 +14,26 @@ RETRANSCRIBE_MAX = 12
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
19
  CHUNK_MAX_DURATION = 90.0
 
14
  # (RETRANSCRIBE_MAX) and the per-sector cache keep it from running on everything.
15
  PRECISE_LOGPROB_GATE = -0.40
16
 
17
+ # ── Whisper hallucination guards ───────────────────────────────────────────────
18
+ # On noisy / musical / distorted audio, Whisper invents fluent-but-fake speech
19
+ # (e.g. a concert recording β†’ plausible nonsense). These decode-time thresholds
20
+ # make it mark such audio as silence/low-confidence instead of fabricating, and
21
+ # disable cross-segment conditioning so it can't spiral into repetition loops.
22
+ WHISPER_NO_SPEECH_THRESHOLD = 0.6
23
+ WHISPER_LOGPROB_THRESHOLD = -1.0
24
+ WHISPER_COMPRESSION_RATIO_THRESHOLD = 2.4
25
+ WHISPER_CONDITION_ON_PREV = False
26
+
27
+ # ── ASR reliability β†’ honest hedging ──────────────────────────────────────────
28
+ # A transcript whose mean confidence is poor (or which is mostly weak segments,
29
+ # or mostly "no-speech") is flagged UNRELIABLE. Synthesis then tells the LLM the
30
+ # audio is hard to make out and to say so plainly rather than treating garbled
31
+ # fragments as real statements.
32
+ ASR_RELIABILITY_LOGPROB_FLOOR = -0.85 # mean segment avg_logprob below β†’ suspect
33
+ ASR_WEAK_SEGMENT_LOGPROB = -0.85 # a single segment is "weak" below this
34
+ ASR_UNRELIABLE_WEAK_FRACTION = 0.5 # β‰₯ this fraction weak β†’ unreliable
35
+ ASR_NO_SPEECH_CEILING = 0.55 # mean no_speech_prob above β†’ unreliable
36
+
37
  CHUNK_SPLIT_THRESHOLD = 0.45
38
  CHUNK_MIN_DURATION = 8.0
39
  CHUNK_MAX_DURATION = 90.0
pipeline.py CHANGED
@@ -3,7 +3,9 @@ import time
3
  from concurrent.futures import ThreadPoolExecutor
4
 
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 (
@@ -88,11 +90,11 @@ def _run_global(chunks: list[dict], visual: dict,
88
  # ── Streaming synthesis wrapper ────────────────────────────────────────────────
89
 
90
  def _synthesize_streaming(regions: list[dict], prompt: str,
91
- max_words: int, mode: str):
92
  print(f"[NINA] Running synthesis [{mode}]...")
93
  yield format_output(regions, prompt, "✍️ …", mode)
94
  last = ""
95
- for partial in llm_synthesize_stream(regions, prompt, max_words, mode):
96
  last = partial
97
  yield format_output(regions, prompt, partial, mode)
98
  if not last:
@@ -189,13 +191,20 @@ def run(video_path: str, prompt: str, token: str = ""):
189
  yield "No speech detected."
190
  return
191
 
 
 
 
 
 
 
 
192
  # Pass 1 routing
193
  mode = classify_query(prompt)
194
  print(f"[NINA] Query mode (pass 1): {mode}")
195
 
196
  if mode == "global":
197
  regions = _run_global(chunks, visual, prompt, max_words)
198
- yield from _synthesize_streaming(regions, prompt, max_words, "global")
199
  print(f"[NINA] Done β€” {len(regions)} region(s) [global].")
200
  return
201
 
@@ -214,7 +223,7 @@ def run(video_path: str, prompt: str, token: str = ""):
214
  if best_bi < BI_SCORE_GLOBAL_FLOOR:
215
  print(f"[NINA] bi-score {best_bi:.3f} below floor β†’ escalating to global.")
216
  regions = _run_global(chunks, visual, prompt, max_words)
217
- yield from _synthesize_streaming(regions, prompt, max_words, "global")
218
  print(f"[NINA] Done β€” {len(regions)} region(s) [escalated global].")
219
  return
220
  elif best_bi < BI_SCORE_HYBRID_FLOOR:
@@ -231,7 +240,7 @@ def run(video_path: str, prompt: str, token: str = ""):
231
  if not regions:
232
  print("[NINA] No regions after merge β†’ falling back to global.")
233
  regions = _run_global(chunks, visual, prompt, max_words)
234
- yield from _synthesize_streaming(regions, prompt, max_words, "global")
235
  return
236
 
237
  # Stage 7 + 7b in parallel: precise re-transcription (WHISPER) and visual
@@ -254,5 +263,5 @@ def run(video_path: str, prompt: str, token: str = ""):
254
  disk_update_precise(fp, precise_cache)
255
 
256
  # Stage 8: LLM synthesis (fuses audio + visual once both branches are done)
257
- yield from _synthesize_streaming(regions, prompt, max_words, mode)
258
  print(f"[NINA] Done β€” {len(regions)} region(s) [{mode}].")
 
3
  from concurrent.futures import ThreadPoolExecutor
4
 
5
  from auth import verify_usage_token
6
+ from audio import (
7
+ fill_precise, load_audio, media_duration, transcribe_fast, transcript_reliability,
8
+ )
9
  from cache import _cache, disk_load, disk_save, disk_update_precise, evict_stale, fingerprint
10
  from compress import ensure_compressed, file_mb, too_large
11
  from config import (
 
90
  # ── Streaming synthesis wrapper ────────────────────────────────────────────────
91
 
92
  def _synthesize_streaming(regions: list[dict], prompt: str,
93
+ max_words: int, mode: str, reliable: bool = True):
94
  print(f"[NINA] Running synthesis [{mode}]...")
95
  yield format_output(regions, prompt, "✍️ …", mode)
96
  last = ""
97
+ for partial in llm_synthesize_stream(regions, prompt, max_words, mode, reliable=reliable):
98
  last = partial
99
  yield format_output(regions, prompt, partial, mode)
100
  if not last:
 
191
  yield "No speech detected."
192
  return
193
 
194
+ # How trustworthy is the transcript? On garbled/musical audio we tell synthesis
195
+ # to flag the audio as unclear rather than report Whisper's fabrications as fact.
196
+ reliability = transcript_reliability(segments)
197
+ reliable = reliability["reliable"]
198
+ if not reliable:
199
+ print(f"[NINA] ⚠ Transcript looks UNRELIABLE {reliability} β€” synthesis will hedge.")
200
+
201
  # Pass 1 routing
202
  mode = classify_query(prompt)
203
  print(f"[NINA] Query mode (pass 1): {mode}")
204
 
205
  if mode == "global":
206
  regions = _run_global(chunks, visual, prompt, max_words)
207
+ yield from _synthesize_streaming(regions, prompt, max_words, "global", reliable=reliable)
208
  print(f"[NINA] Done β€” {len(regions)} region(s) [global].")
209
  return
210
 
 
223
  if best_bi < BI_SCORE_GLOBAL_FLOOR:
224
  print(f"[NINA] bi-score {best_bi:.3f} below floor β†’ escalating to global.")
225
  regions = _run_global(chunks, visual, prompt, max_words)
226
+ yield from _synthesize_streaming(regions, prompt, max_words, "global", reliable=reliable)
227
  print(f"[NINA] Done β€” {len(regions)} region(s) [escalated global].")
228
  return
229
  elif best_bi < BI_SCORE_HYBRID_FLOOR:
 
240
  if not regions:
241
  print("[NINA] No regions after merge β†’ falling back to global.")
242
  regions = _run_global(chunks, visual, prompt, max_words)
243
+ yield from _synthesize_streaming(regions, prompt, max_words, "global", reliable=reliable)
244
  return
245
 
246
  # Stage 7 + 7b in parallel: precise re-transcription (WHISPER) and visual
 
263
  disk_update_precise(fp, precise_cache)
264
 
265
  # Stage 8: LLM synthesis (fuses audio + visual once both branches are done)
266
+ yield from _synthesize_streaming(regions, prompt, max_words, mode, reliable=reliable)
267
  print(f"[NINA] Done β€” {len(regions)} region(s) [{mode}].")
synthesis.py CHANGED
@@ -118,7 +118,18 @@ def _detect_language(text: str) -> str:
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"
@@ -133,7 +144,8 @@ def _make_system_msg(language: str, max_words: int, tier: str) -> str:
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"
@@ -198,9 +210,14 @@ def _build_synth_prompt(regions: list[dict], prompt: str, max_words: int, mode:
198
 
199
 
200
  def llm_synthesize_stream(
201
- regions: list[dict], prompt: str, max_words: int = 150, mode: str = "specific"
 
202
  ):
203
- """Generator: yields the answer incrementally as the LLM streams tokens."""
 
 
 
 
204
  if not regions:
205
  yield "(No relevant regions to summarize.)"
206
  return
@@ -222,7 +239,8 @@ def llm_synthesize_stream(
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,
 
118
  return "English"
119
 
120
 
121
+ def _make_system_msg(language: str, max_words: int, tier: str,
122
+ reliable: bool = True) -> str:
123
+ audio_quality = "" if reliable else (
124
+ "\n\nAUDIO QUALITY (important) β€” This transcript was auto-extracted from "
125
+ "low-quality, noisy or distorted audio and is partly UNRELIABLE. Some fragments "
126
+ "may be garbled or nonsensical (speech-recognition errors), NOT real statements. "
127
+ "Do not treat incoherent or nonsensical fragments as things anyone actually said, "
128
+ "and do not invent a meaning for them. If the words don't form coherent sense, say "
129
+ "plainly (in the user's language) that the audio is too unclear to make out β€” e.g. "
130
+ "that you cannot reliably tell who is speaking or what is said. You may still rely on "
131
+ "any clearly coherent speech and on the on-screen cues."
132
+ )
133
  return (
134
  "You are NINA, a sharp assistant that answers questions about a video using ONLY "
135
  "the transcript fragments and on-screen cues you are given.\n\n"
 
144
  "GROUNDING β€” Use only what the fragments state. Never invent, infer, guess, or "
145
  "complete partial words, names or numbers. If the fragments don't address the "
146
  "question, say so plainly (in the user's language) instead of speculating. Don't "
147
+ "fix grammar inside quoted speech."
148
+ f"{audio_quality}\n\n"
149
  "FORMAT β€” Write a natural, flowing answer in prose (sentences or short paragraphs). "
150
  "Do NOT begin lines with timestamps. After the answer, add exactly one final line "
151
  "listing the moments you drew from, in this form:\n"
 
210
 
211
 
212
  def llm_synthesize_stream(
213
+ regions: list[dict], prompt: str, max_words: int = 150, mode: str = "specific",
214
+ reliable: bool = True,
215
  ):
216
+ """Generator: yields the answer incrementally as the LLM streams tokens.
217
+
218
+ `reliable=False` (poor ASR audio) makes the system prompt tell the model to flag
219
+ unclear audio instead of treating garbled fragments as real speech.
220
+ """
221
  if not regions:
222
  yield "(No relevant regions to summarize.)"
223
  return
 
239
  model=LLM_MODEL,
240
  messages=[
241
  {"role": "system",
242
+ "content": _make_system_msg(language, max_words, _summary_tier(max_words),
243
+ reliable=reliable)},
244
  {"role": "user", "content": synth_prompt},
245
  ],
246
  max_tokens=LLM_MAX_TOKENS,