Thedeezat Cursor commited on
Commit
2251e5d
·
1 Parent(s): 9a0b6df

fix(it): soften zlib compression gate; ultra-short tail after phrase

Browse files

- ASR_COMPRESSION_RATIO_THRESHOLD_IT (default 2.8): Italian rejects CR only when
very high, repetition obvious, or paired with nsp/alp; skip CR-only proxy when
nsp/alp missing, speech_rms>=0.035, reasonable text length.
- low_confidence_short: Italian CR paired with same skip rule.
- Per-lang last accepted phrase + ultra_short_tail_after_phrase (segment/window
configurable); continuation overlap avoids dropping same-utterance chunks.
- Logs: [it_filter] decision=accept|reject ...

Co-authored-by: Cursor <cursoragent@cursor.com>

Files changed (1) hide show
  1. main.py +127 -22
main.py CHANGED
@@ -68,6 +68,10 @@ _NO_SPEECH_THRESHOLD_EN = float(os.environ.get("ASR_NO_SPEECH_THRESHOLD_EN", "0.
68
  _NO_SPEECH_THRESHOLD_IT = float(os.environ.get("ASR_NO_SPEECH_THRESHOLD_IT", "0.84"))
69
  # Lower threshold = reject repetitive / gibberish text sooner (helps tail hallucinations).
70
  _COMPRESSION_RATIO_THRESHOLD = float(os.environ.get("ASR_COMPRESSION_RATIO_THRESHOLD", "1.6"))
 
 
 
 
71
  _LOGPROB_THRESHOLD = float(os.environ.get("ASR_LOGPROB_THRESHOLD", "-1.0"))
72
  # Transformers forced-Italian: reject when average token logprob is below this (more negative = stricter).
73
  _ASR_AVG_LOGPROB_REJECT_IT = float(os.environ.get("ASR_AVG_LOGPROB_REJECT_IT", "-0.92"))
@@ -408,6 +412,36 @@ def _english_word_density_secondary_signals(
408
  return hints
409
 
410
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411
  def _strip_italian_conj_echo_suffix(text: str) -> str:
412
  """Strip Whisper tail hallucination ``... W e W`` (same word echoed after conjunction)."""
413
  t = (text or "").strip()
@@ -1350,6 +1384,8 @@ _last_signal_by_lang: dict[str, dict[str, float]] = {
1350
  "italian": {"speech_rms": 0.0, "ts": 0.0},
1351
  "auto": {"speech_rms": 0.0, "ts": 0.0},
1352
  }
 
 
1353
 
1354
 
1355
  def _text_compression_ratio(text: str) -> float:
@@ -1423,7 +1459,8 @@ def get_pipe():
1423
  f"forced_rt_it={_FAST_REALTIME_MODEL_IT} forced_rt_en={_FAST_REALTIME_MODEL_EN} "
1424
  f"use_forced_rt={_FAST_USE_REALTIME_FOR_FORCED} italian_backend={_ASR_ITALIAN_BACKEND} "
1425
  f"no_speech_auto={_NO_SPEECH_THRESHOLD} en={_NO_SPEECH_THRESHOLD_EN} it={_NO_SPEECH_THRESHOLD_IT} "
1426
- f"compression_ratio={_COMPRESSION_RATIO_THRESHOLD} log_prob_fw={_FAST_LOG_PROB_THRESHOLD} "
 
1427
  f"vad_env_unset={_ASR_VAD_FILTER_UNSET} vad_filter_global={_ASR_VAD_FILTER_FAST} "
1428
  f"vad_it_effective={_vad_enabled_forced_italian()}"
1429
  )
@@ -2067,6 +2104,9 @@ def startup() -> None:
2067
  f"ASR_TRIM_TRAILING_SILENCE_IT={_ASR_TRIM_TRAILING_SILENCE_IT} "
2068
  f"ASR_TRIM_TRAILING_SILENCE_EN={_ASR_TRIM_TRAILING_SILENCE_EN} "
2069
  f"ASR_FORCE_SEGMENTATION_FORCED={_ASR_FORCE_SEGMENTATION_FORCED} "
 
 
 
2070
  f"ASR_MIN_RMS={_MIN_RMS}"
2071
  )
2072
  if _HOLOLENS_ITA_PROFILE:
@@ -2376,31 +2416,51 @@ async def audio(request: Request) -> Response:
2376
  f"speech_rms={speech_rms:.5f} threshold={min_speech_thr:.5f} chunk_s={duration_s:.2f}"
2377
  )
2378
  raw_text = ""
2379
- # Decode-confidence gates (Transformers Whisper now supplies avg_logprob / zlib token compression).
2380
  if raw_text:
2381
  no_speech_prob = decode_conf.get("no_speech_prob")
2382
  avg_logprob = decode_conf.get("avg_logprob")
2383
  comp = decode_conf.get("compression_ratio")
2384
- has_signal = no_speech_prob is not None or avg_logprob is not None or (
2385
- comp is not None and float(comp) > float(_COMPRESSION_RATIO_THRESHOLD)
 
 
 
 
 
 
 
 
 
 
 
2386
  )
2387
- if has_signal:
2388
- weak_decode = (
2389
- (no_speech_prob is not None and float(no_speech_prob) > 0.55)
2390
- or (
2391
- avg_logprob is not None
2392
- and float(avg_logprob) < float(_ASR_AVG_LOGPROB_REJECT_IT)
2393
- )
2394
- or (comp is not None and float(comp) > (float(_COMPRESSION_RATIO_THRESHOLD) + 0.2))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2395
  )
2396
- if weak_decode:
2397
- print(
2398
- f"[reject] lang=italian reason=confidence_meta "
2399
- f"chunk_s={duration_s:.2f} speech_rms={speech_rms:.5f} "
2400
- f"no_speech_prob={no_speech_prob} avg_logprob={avg_logprob} "
2401
- f"compression_ratio={comp}"
2402
- )
2403
- raw_text = ""
2404
  # Short-utterance mode: stricter post-decode confidence checks.
2405
  if short_mode_forced_it and raw_text:
2406
  words_now = [w for w in _WORD_RE.findall(raw_text)]
@@ -2537,12 +2597,29 @@ async def audio(request: Request) -> Response:
2537
  nsp = decode_conf.get("no_speech_prob")
2538
  alp = decode_conf.get("avg_logprob")
2539
  comp = decode_conf.get("compression_ratio")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2540
  conf_weak = (
2541
  (nsp is not None and float(nsp) > 0.55)
2542
  or (alp is not None and float(alp) < -0.92)
2543
- or (comp is not None and float(comp) > (_COMPRESSION_RATIO_THRESHOLD + 0.2))
2544
  )
2545
- conf_missing = nsp is None and alp is None
2546
  # Italian path can have missing confidence metadata; don't reject strong speech for that alone.
2547
  reject_low_conf_short = conf_weak or (
2548
  forced_language == "english" and conf_missing
@@ -2666,6 +2743,28 @@ async def audio(request: Request) -> Response:
2666
  f"speech_rms={speech_rms:.5f} prev_speech_rms={prev_speech_rms:.5f} dt={dt_s:.2f}"
2667
  )
2668
  raw_text = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2669
  text = raw_text.upper().strip() if raw_text else ""
2670
  lang_key = forced_language if forced_language in {"english", "italian"} else "auto"
2671
  # Optional tiny-fragment suppression (off by default to avoid hard-coded word dropping).
@@ -2683,6 +2782,12 @@ async def audio(request: Request) -> Response:
2683
  deduped = ""
2684
  _last_text_by_lang[lang_key] = text
2685
  _last_signal_by_lang[lang_key] = {"speech_rms": float(speech_rms), "ts": time.time()}
 
 
 
 
 
 
2686
  text = deduped
2687
  if text and forced_language in {"english", "italian"}:
2688
  print(
 
68
  _NO_SPEECH_THRESHOLD_IT = float(os.environ.get("ASR_NO_SPEECH_THRESHOLD_IT", "0.84"))
69
  # Lower threshold = reject repetitive / gibberish text sooner (helps tail hallucinations).
70
  _COMPRESSION_RATIO_THRESHOLD = float(os.environ.get("ASR_COMPRESSION_RATIO_THRESHOLD", "1.6"))
71
+ # Italian-only zlib/text compression gate — keeps EN/global defaults stable when transformers omits nsp/alp.
72
+ _COMPRESSION_RATIO_THRESHOLD_IT = float(os.environ.get("ASR_COMPRESSION_RATIO_THRESHOLD_IT", "2.8"))
73
+ _ASR_ULTRA_SHORT_TAIL_WINDOW_S = float(os.environ.get("ASR_ULTRA_SHORT_TAIL_WINDOW_S", "3.0"))
74
+ _ASR_ULTRA_SHORT_TAIL_MAX_SEGMENT_S = float(os.environ.get("ASR_ULTRA_SHORT_TAIL_MAX_SEGMENT_S", "0.75"))
75
  _LOGPROB_THRESHOLD = float(os.environ.get("ASR_LOGPROB_THRESHOLD", "-1.0"))
76
  # Transformers forced-Italian: reject when average token logprob is below this (more negative = stricter).
77
  _ASR_AVG_LOGPROB_REJECT_IT = float(os.environ.get("ASR_AVG_LOGPROB_REJECT_IT", "-0.92"))
 
412
  return hints
413
 
414
 
415
+ def _decode_has_strong_confidence(decode_conf: dict[str, float | None]) -> bool:
416
+ """When metadata exists and indicates confident decoding (avoid rejecting tails aggressively)."""
417
+ nsp = decode_conf.get("no_speech_prob")
418
+ alp = decode_conf.get("avg_logprob")
419
+ if nsp is not None and float(nsp) < 0.35:
420
+ return True
421
+ if alp is not None and float(alp) > -0.55:
422
+ return True
423
+ return False
424
+
425
+
426
+ def _is_utterance_continuation(prev_upper: str, cur_upper: str) -> bool:
427
+ """Overlap-aware continuation for chunked captions (same active utterance / phrase)."""
428
+ pu = (prev_upper or "").strip().upper()
429
+ cu = (cur_upper or "").strip().upper()
430
+ if not pu or not cu:
431
+ return False
432
+ pw = pu.split()
433
+ cw = cu.split()
434
+ if not pw or not cw:
435
+ return False
436
+ max_k = min(len(pw), len(cw), 16)
437
+ for k in range(max_k, 0, -1):
438
+ if pw[-k:] == cw[:k]:
439
+ return True
440
+ pj = " ".join(pw)
441
+ cj = " ".join(cw)
442
+ return pj in cj or cj in pj
443
+
444
+
445
  def _strip_italian_conj_echo_suffix(text: str) -> str:
446
  """Strip Whisper tail hallucination ``... W e W`` (same word echoed after conjunction)."""
447
  t = (text or "").strip()
 
1384
  "italian": {"speech_rms": 0.0, "ts": 0.0},
1385
  "auto": {"speech_rms": 0.0, "ts": 0.0},
1386
  }
1387
+ # Last non-empty accepted transcript per forced language (post-dedup), for ultra-short tail rejection.
1388
+ _last_accepted_phrase_by_lang: dict[str, dict[str, float | str]] = {}
1389
 
1390
 
1391
  def _text_compression_ratio(text: str) -> float:
 
1459
  f"forced_rt_it={_FAST_REALTIME_MODEL_IT} forced_rt_en={_FAST_REALTIME_MODEL_EN} "
1460
  f"use_forced_rt={_FAST_USE_REALTIME_FOR_FORCED} italian_backend={_ASR_ITALIAN_BACKEND} "
1461
  f"no_speech_auto={_NO_SPEECH_THRESHOLD} en={_NO_SPEECH_THRESHOLD_EN} it={_NO_SPEECH_THRESHOLD_IT} "
1462
+ f"compression_ratio={_COMPRESSION_RATIO_THRESHOLD} compression_ratio_it={_COMPRESSION_RATIO_THRESHOLD_IT} "
1463
+ f"log_prob_fw={_FAST_LOG_PROB_THRESHOLD} "
1464
  f"vad_env_unset={_ASR_VAD_FILTER_UNSET} vad_filter_global={_ASR_VAD_FILTER_FAST} "
1465
  f"vad_it_effective={_vad_enabled_forced_italian()}"
1466
  )
 
2104
  f"ASR_TRIM_TRAILING_SILENCE_IT={_ASR_TRIM_TRAILING_SILENCE_IT} "
2105
  f"ASR_TRIM_TRAILING_SILENCE_EN={_ASR_TRIM_TRAILING_SILENCE_EN} "
2106
  f"ASR_FORCE_SEGMENTATION_FORCED={_ASR_FORCE_SEGMENTATION_FORCED} "
2107
+ f"ASR_COMPRESSION_RATIO_THRESHOLD_IT={_COMPRESSION_RATIO_THRESHOLD_IT} "
2108
+ f"ASR_ULTRA_SHORT_TAIL_WINDOW_S={_ASR_ULTRA_SHORT_TAIL_WINDOW_S} "
2109
+ f"ASR_ULTRA_SHORT_TAIL_MAX_SEGMENT_S={_ASR_ULTRA_SHORT_TAIL_MAX_SEGMENT_S} "
2110
  f"ASR_MIN_RMS={_MIN_RMS}"
2111
  )
2112
  if _HOLOLENS_ITA_PROFILE:
 
2416
  f"speech_rms={speech_rms:.5f} threshold={min_speech_thr:.5f} chunk_s={duration_s:.2f}"
2417
  )
2418
  raw_text = ""
2419
+ # Decode-confidence gates: Italian transformers often omits nsp/alp — do not hard-drop on zlib CR alone.
2420
  if raw_text:
2421
  no_speech_prob = decode_conf.get("no_speech_prob")
2422
  avg_logprob = decode_conf.get("avg_logprob")
2423
  comp = decode_conf.get("compression_ratio")
2424
+ words_it = len(_WORD_RE.findall(raw_text))
2425
+ reasonable_it = len((raw_text or "").strip()) >= 8 or words_it >= 2
2426
+ meta_missing = no_speech_prob is None and avg_logprob is None
2427
+ cr_val = float(comp) if comp is not None else None
2428
+
2429
+ nsp_bad = no_speech_prob is not None and float(no_speech_prob) > 0.55
2430
+ alp_bad = avg_logprob is not None and float(avg_logprob) < float(_ASR_AVG_LOGPROB_REJECT_IT)
2431
+ skip_cr_proxy = meta_missing and speech_rms >= 0.035 and reasonable_it
2432
+ cr_hard_it = cr_val is not None and cr_val >= float(_COMPRESSION_RATIO_THRESHOLD_IT)
2433
+ cr_soft_bad = (
2434
+ cr_val is not None
2435
+ and cr_val > float(_COMPRESSION_RATIO_THRESHOLD) + 0.2
2436
+ and not skip_cr_proxy
2437
  )
2438
+ cr_repeat_bad = (
2439
+ cr_val is not None
2440
+ and cr_val > float(_COMPRESSION_RATIO_THRESHOLD) + 0.2
2441
+ and _should_drop_repetition_hallucination(raw_text)
2442
+ )
2443
+ comp_bad = bool(cr_hard_it or cr_soft_bad or cr_repeat_bad)
2444
+ weak_decode = bool(nsp_bad or alp_bad or comp_bad)
2445
+
2446
+ if weak_decode:
2447
+ print(
2448
+ f"[it_filter] decision=reject reason=confidence_meta "
2449
+ f"text={raw_text[:80]!r} speech_rms={speech_rms:.5f} compression_ratio={cr_val} "
2450
+ f"nsp_bad={nsp_bad} alp_bad={alp_bad} comp_bad={comp_bad} skip_cr_proxy={skip_cr_proxy}"
2451
+ )
2452
+ print(
2453
+ f"[reject] lang=italian reason=confidence_meta "
2454
+ f"chunk_s={duration_s:.2f} speech_rms={speech_rms:.5f} "
2455
+ f"no_speech_prob={no_speech_prob} avg_logprob={avg_logprob} "
2456
+ f"compression_ratio={comp}"
2457
+ )
2458
+ raw_text = ""
2459
+ elif cr_val is not None or not meta_missing:
2460
+ print(
2461
+ f"[it_filter] decision=accept reason=confidence_ok "
2462
+ f"text={raw_text[:80]!r} speech_rms={speech_rms:.5f} compression_ratio={cr_val}"
2463
  )
 
 
 
 
 
 
 
 
2464
  # Short-utterance mode: stricter post-decode confidence checks.
2465
  if short_mode_forced_it and raw_text:
2466
  words_now = [w for w in _WORD_RE.findall(raw_text)]
 
2597
  nsp = decode_conf.get("no_speech_prob")
2598
  alp = decode_conf.get("avg_logprob")
2599
  comp = decode_conf.get("compression_ratio")
2600
+ reasonable_short = len((raw_text or "").strip()) >= 8 or words_n >= 2
2601
+ meta_miss_short = nsp is None and alp is None
2602
+ skip_cr_short_it = (
2603
+ forced_language == "italian"
2604
+ and meta_miss_short
2605
+ and speech_rms >= 0.035
2606
+ and reasonable_short
2607
+ )
2608
+ comp_weak = False
2609
+ if comp is not None:
2610
+ cv = float(comp)
2611
+ if forced_language == "italian":
2612
+ comp_weak = cv >= float(_COMPRESSION_RATIO_THRESHOLD_IT) or (
2613
+ cv > float(_COMPRESSION_RATIO_THRESHOLD) + 0.2 and not skip_cr_short_it
2614
+ )
2615
+ else:
2616
+ comp_weak = cv > float(_COMPRESSION_RATIO_THRESHOLD) + 0.2
2617
  conf_weak = (
2618
  (nsp is not None and float(nsp) > 0.55)
2619
  or (alp is not None and float(alp) < -0.92)
2620
+ or comp_weak
2621
  )
2622
+ conf_missing = meta_miss_short
2623
  # Italian path can have missing confidence metadata; don't reject strong speech for that alone.
2624
  reject_low_conf_short = conf_weak or (
2625
  forced_language == "english" and conf_missing
 
2743
  f"speech_rms={speech_rms:.5f} prev_speech_rms={prev_speech_rms:.5f} dt={dt_s:.2f}"
2744
  )
2745
  raw_text = ""
2746
+ # Ultra-short isolated chunk right after a completed phrase (thank-you / grazie tail pattern).
2747
+ if raw_text and forced_language in {"english", "italian"}:
2748
+ cand_u = raw_text.strip().upper()
2749
+ words_tail = len(_WORD_RE.findall(raw_text))
2750
+ with _last_text_lock:
2751
+ acc = _last_accepted_phrase_by_lang.get(forced_language)
2752
+ if acc and acc.get("text"):
2753
+ dt_tail = time.time() - float(acc.get("ts", 0.0))
2754
+ prev_txt = str(acc.get("text", ""))
2755
+ strong_meta = _decode_has_strong_confidence(decode_conf)
2756
+ if (
2757
+ float(duration_s) < float(_ASR_ULTRA_SHORT_TAIL_MAX_SEGMENT_S)
2758
+ and words_tail <= 2
2759
+ and dt_tail <= float(_ASR_ULTRA_SHORT_TAIL_WINDOW_S)
2760
+ and not _is_utterance_continuation(prev_txt, cand_u)
2761
+ and not strong_meta
2762
+ ):
2763
+ print(
2764
+ f"[reject] reason=ultra_short_tail_after_phrase text={raw_text[:80]!r} "
2765
+ f"segment_s={duration_s:.2f} dt={dt_tail:.2f}"
2766
+ )
2767
+ raw_text = ""
2768
  text = raw_text.upper().strip() if raw_text else ""
2769
  lang_key = forced_language if forced_language in {"english", "italian"} else "auto"
2770
  # Optional tiny-fragment suppression (off by default to avoid hard-coded word dropping).
 
2782
  deduped = ""
2783
  _last_text_by_lang[lang_key] = text
2784
  _last_signal_by_lang[lang_key] = {"speech_rms": float(speech_rms), "ts": time.time()}
2785
+ if deduped and lang_key in {"english", "italian"}:
2786
+ _last_accepted_phrase_by_lang[lang_key] = {
2787
+ "text": deduped,
2788
+ "speech_rms": float(speech_rms),
2789
+ "ts": time.time(),
2790
+ }
2791
  text = deduped
2792
  if text and forced_language in {"english", "italian"}:
2793
  print(