mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 17:21:26 +09:00
## Summary Turns the **P8 phantom-parenthetical** class from a review *gate* into a deterministic *auto-fix*, widening the fully-auto class without loosening the quality bar. Part of the full-auto-review initiative (measurement re-assessment phase). The 2026-08-30 reconstruction re-measure of the corpus (see below) showed that deleting phantom parentheticals — `(Instrumental break)`, `(I'm sorry)`, and unanchored `(Angel baby)` duplicate copies — is a recurring, cleanly-deterministic human edit. Previously these only *gated* the job to human review; now they're auto-deleted so the affected jobs auto-ship with correct output. ## Changes - **`deterministic.phantom_parenthetical_suggestions`** — emits a `delete` for a parenthetical run whose **every word is a gap word** (the decisive signal: this correctly deletes an unanchored duplicate even when its tokens appear elsewhere in the references, e.g. `(Angel baby)`). Guards: skips pure-vocalization parentheticals (left to the vocalization gate) and long runs (> 5 words). Wired into `deterministic_suggestions`, so it flows through the same cache / apply / score paths as P4/P5. - **`scorer._extract_gating_signals`** — now excludes words that a **winning** delete suggestion removes (winner-aware via `pick_accept_all_winners`) before scanning for the phantom/vocalization gates. A phantom that will be auto-deleted no longer trips the phantom gate, while genuine absurd-duration phantoms stay gated. ## Validation - **Corpus + battery (25 jobs):** 6/6 correct-direction deletes, **zero false positives**. The two known-human cases reproduce exactly (`(I'm sorry)`×3, `(Instrumental break)`); two initially-unverified deletes (`(only to my)`, `(Dreaming)`) confirmed correct — neither appears in the human's final. - **Private `validate_scorer.py` green:** safety preserved (33453fa0 still not-auto via its genuine gap/anchor signals; raw phantom safety-net gate intact); P8 fires 33453fa0 ×3, 8e465dc7 ×1, 5f90b799 ×1. - **Tests:** new unit tests for the fixer (8) + scorer delete-awareness incl. winner-vs-loser conflict handling (2). `backend/tests/services` 380 passed; auto_approval + auto_correct 230 passed; review routes + instrumental summary 91 passed. - **CodeRabbit** local review: no findings. ## Measurement note Human-edit measurement now uses **reconstruction** (diff post-AI vs final), not the `edit_log` — which was proven unreliable (never logs timing edits; null path is ambiguous). Documented in `docs/LESSONS-LEARNED.md`. @coderabbitai ignore Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
476 lines
19 KiB
Python
476 lines
19 KiB
Python
"""Deterministic auto-correct suggestion generators (no LLM).
|
|
|
|
Mechanical residual-edit classes from the 2026-08 20-job replay-review corpus,
|
|
emitted as ordinary suggestions so they flow through the exact same paths as
|
|
the LLM ones: shown in the review UI, auto-applied on load, applied server-side
|
|
by the auto-approval executor, counted by the scorer's gap-coverage signal, and
|
|
cached alongside the LLM output.
|
|
|
|
Pattern 4 — leading-connective over-insertion: AudioShake is too eager to
|
|
insert a short connective ("And", "Oh", …) at a segment start. When that word
|
|
is a gap word (no confident reference match) and no reference source's reading
|
|
of the gap supports it, emit a delete (+ re-capitalize the next word).
|
|
|
|
Pattern 5 — reference-majority resolution: when a gap's transcription contains
|
|
an implausible proper noun (capitalized mid-line token absent from every
|
|
reference source) and >=2/3 of the reference sources agree on the same reading
|
|
for that gap, replace the gap with the majority reading. The red-flag token is
|
|
REQUIRED, not just preferred: the corpus shows plain 2/3-majority gaps that the
|
|
human deliberately left alone (Miguel 6d0640fa "though"->"dog" and an
|
|
explicit-lyrics rewrite), while the one edit he did make ("yo Mick," ->
|
|
"Come here,") had the proper-noun signature.
|
|
|
|
Pattern 8 (fix) — phantom parenthetical: AudioShake hallucinates or mis-segments
|
|
short parenthetical phrases that no confident reference match backs — standalone
|
|
lines "(Instrumental break)" / "(I'm sorry)" / "(Angel baby)", or unanchored
|
|
duplicate copies of a real line wrapped in parens. The 2026-08-30 reconstruction
|
|
re-measure showed these are a recurring human deletion (Clean Bandit 894781ab,
|
|
33453fa0). Previously these only *gated* the job to human review (scorer's
|
|
phantom signature); here we delete the phantom run so the job can auto-ship. The
|
|
decisive signal is that EVERY word of the parenthetical run is a gap word (no
|
|
confident reference match) — this correctly deletes the "(Angel baby)" duplicate
|
|
even though "angel"/"baby" appear elsewhere in the references. Pure vocalization
|
|
parentheticals ("(ooh)") are left to the vocalization gate (timing/grouping is a
|
|
musical judgement, not a clean delete).
|
|
|
|
Everything here is pure and conservative: no evidence -> no suggestion.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import difflib
|
|
import logging
|
|
import re
|
|
import uuid
|
|
from typing import Any, Dict, List, Optional, Tuple
|
|
|
|
from backend.services.auto_approval.scorer import _is_vocalization_token
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Short connectives/interjections AudioShake over-inserts at segment starts —
|
|
# exactly the set documented in the corpus (Pattern 4: And / But / So / Oh / A).
|
|
# Deliberately NOT the near-misses like "ah"/"yeah": those double as
|
|
# vocalization tokens, where deleting the leading word is a musical judgement.
|
|
# The reference check below does the real gating; this list only scopes
|
|
# which leading words are candidates.
|
|
LEADING_CONNECTIVES = frozenset({"and", "but", "so", "oh", "a"})
|
|
|
|
# P4/P5 confidences: high enough to auto-apply, below full LLM consensus so a
|
|
# conflicting multi-model AI suggestion wins its conflict group.
|
|
P4_CONFIDENCE = 0.9
|
|
P5_CONFIDENCE = 0.85
|
|
|
|
# P8 phantom-parenthetical delete: a strong deterministic signal (all-gap
|
|
# parenthetical run), so confident enough to auto-apply.
|
|
P8_CONFIDENCE = 0.9
|
|
# Never delete a long parenthetical block deterministically — a multi-word
|
|
# parenthetical could be a genuine sung aside. The corpus phantoms are 2-4 words.
|
|
P8_MAX_RUN_WORDS = 5
|
|
|
|
# P5 size guards: never rewrite long spans deterministically.
|
|
P5_MAX_GAP_WORDS = 6
|
|
P5_MAX_READING_WORDS = 8
|
|
# A red-flag token this similar to some reference token is a spelling/
|
|
# transliteration variant ("Crick"~"Cricket", "Projectorinsky"~
|
|
# "Projektorinski"), not an implausible name. The right fix there is the
|
|
# LLM's (it handles proper-noun spelling well); the gap alignment is also
|
|
# often skewed in exactly these cases, so the majority "reading" is junk
|
|
# (corpus 507513ba aligned gap "Crick" to reference "and").
|
|
P5_SPELLING_VARIANT_RATIO = 0.75
|
|
|
|
_TOKEN_NORM_RE = re.compile(r"^[^\w]+|[^\w]+$")
|
|
|
|
|
|
def _norm(text: str) -> str:
|
|
return _TOKEN_NORM_RE.sub("", (text or "").lower())
|
|
|
|
|
|
def _norm_join(texts: List[str]) -> str:
|
|
return " ".join(t for t in (_norm(x) for x in texts) if t)
|
|
|
|
|
|
def _ref_word_streams(
|
|
reference_lyrics: Dict[str, Any],
|
|
) -> Dict[str, Tuple[List[str], Dict[str, int]]]:
|
|
"""Per source: (ordered word texts, word_id -> position)."""
|
|
streams: Dict[str, Tuple[List[str], Dict[str, int]]] = {}
|
|
for source, ref in (reference_lyrics or {}).items():
|
|
texts: List[str] = []
|
|
index: Dict[str, int] = {}
|
|
for seg in ref.get("segments") or []:
|
|
for w in seg.get("words") or []:
|
|
wid = w.get("id")
|
|
if wid:
|
|
index[wid] = len(texts)
|
|
texts.append(w.get("text") or "")
|
|
streams[source] = (texts, index)
|
|
return streams
|
|
|
|
|
|
def _gap_readings(
|
|
gap: Dict[str, Any],
|
|
anchors_by_id: Dict[str, Dict[str, Any]],
|
|
streams: Dict[str, Tuple[List[str], Dict[str, int]]],
|
|
) -> Dict[str, List[str]]:
|
|
"""Each source's reading of the gap (raw word texts).
|
|
|
|
Prefer the gap's own per-source alignment. When a source aligned neither
|
|
gap word (empty list — common), derive the reading from the reference
|
|
stream around the surrounding anchors: the words strictly between the
|
|
anchors when both aligned for that source, else the same-count window
|
|
after the preceding (or before the following) anchor. A source with no
|
|
usable anchor alignment contributes no reading.
|
|
"""
|
|
n = len(gap.get("transcribed_word_ids") or [])
|
|
pre = anchors_by_id.get(gap.get("preceding_anchor_id") or "")
|
|
fol = anchors_by_id.get(gap.get("following_anchor_id") or "")
|
|
readings: Dict[str, List[str]] = {}
|
|
for source, (texts, index) in streams.items():
|
|
aligned_ids = (gap.get("reference_word_ids") or {}).get(source) or []
|
|
aligned = [texts[index[i]] for i in aligned_ids if i in index]
|
|
if aligned:
|
|
readings[source] = aligned
|
|
continue
|
|
pre_ids = ((pre or {}).get("reference_word_ids") or {}).get(source) or []
|
|
fol_ids = ((fol or {}).get("reference_word_ids") or {}).get(source) or []
|
|
lo = index[pre_ids[-1]] + 1 if pre_ids and pre_ids[-1] in index else None
|
|
hi = index[fol_ids[0]] if fol_ids and fol_ids[0] in index else None
|
|
if lo is not None and hi is not None:
|
|
if lo <= hi <= lo + n + 4:
|
|
readings[source] = texts[lo:hi]
|
|
elif lo is not None:
|
|
readings[source] = texts[lo : lo + n]
|
|
elif hi is not None:
|
|
readings[source] = texts[max(0, hi - n) : hi]
|
|
return readings
|
|
|
|
|
|
def _word_maps(
|
|
segments: List[Dict[str, Any]],
|
|
) -> Tuple[Dict[str, Dict[str, Any]], Dict[str, str]]:
|
|
"""(word_id -> word dict, word_id -> segment_id) from the CURRENT segments."""
|
|
words: Dict[str, Dict[str, Any]] = {}
|
|
seg_of: Dict[str, str] = {}
|
|
for seg in segments or []:
|
|
for w in seg.get("words") or []:
|
|
wid = w.get("id")
|
|
if wid:
|
|
words[wid] = w
|
|
seg_of[wid] = seg.get("id") or ""
|
|
return words, seg_of
|
|
|
|
|
|
def _make_suggestion(
|
|
*,
|
|
op: str,
|
|
word_ids: List[str],
|
|
segment_ids: List[str],
|
|
original_text: str,
|
|
new_text: str,
|
|
reason: str,
|
|
category: str,
|
|
confidence: float,
|
|
) -> Dict[str, Any]:
|
|
"""A suggestion dict shaped exactly like the LLM ones after validation."""
|
|
return {
|
|
"id": str(uuid.uuid4()),
|
|
"op": op,
|
|
"word_ids": word_ids,
|
|
"segment_ids": segment_ids,
|
|
"original_text": original_text,
|
|
"new_text": new_text,
|
|
"reason": reason,
|
|
"category": category,
|
|
"confidence": confidence,
|
|
"models": ["deterministic"],
|
|
"consensus": 1,
|
|
"total_models": 1,
|
|
"conflict_group": None,
|
|
}
|
|
|
|
|
|
def _capitalize(text: str) -> str:
|
|
for i, ch in enumerate(text):
|
|
if ch.isalpha():
|
|
return text[:i] + ch.upper() + text[i + 1 :]
|
|
return text
|
|
|
|
|
|
def leading_connective_suggestions(
|
|
segments: List[Dict[str, Any]],
|
|
correction_data: Dict[str, Any],
|
|
streams: Dict[str, Tuple[List[str], Dict[str, int]]],
|
|
) -> List[Dict[str, Any]]:
|
|
"""Pattern 4: delete an unsupported leading connective, re-capitalize next word."""
|
|
gaps = correction_data.get("gap_sequences") or []
|
|
anchors_by_id = {
|
|
a.get("id"): a for a in correction_data.get("anchor_sequences") or [] if a.get("id")
|
|
}
|
|
gap_of_word: Dict[str, Dict[str, Any]] = {}
|
|
for gap in gaps:
|
|
for wid in gap.get("transcribed_word_ids") or []:
|
|
gap_of_word[wid] = gap
|
|
|
|
out: List[Dict[str, Any]] = []
|
|
for seg in segments or []:
|
|
words = seg.get("words") or []
|
|
if len(words) < 3:
|
|
continue
|
|
first = words[0]
|
|
wid = first.get("id")
|
|
token = _norm(first.get("text") or "")
|
|
if not wid or token not in LEADING_CONNECTIVES:
|
|
continue
|
|
gap = gap_of_word.get(wid)
|
|
if gap is None:
|
|
# A confidently reference-anchored leading word is legitimate.
|
|
continue
|
|
if _is_vocalization_token(words[1].get("text") or ""):
|
|
# "Oh- whoa, ..." — a vocalization run, not an over-inserted
|
|
# connective before a sentence; grouping there is musical judgement.
|
|
continue
|
|
readings = _gap_readings(gap, anchors_by_id, streams)
|
|
if not readings:
|
|
continue # no reference evidence either way -> leave it alone
|
|
if any(token in {_norm(t) for t in reading} for reading in readings.values()):
|
|
continue # some source supports the connective at this position
|
|
seg_id = seg.get("id") or ""
|
|
out.append(
|
|
_make_suggestion(
|
|
op="delete",
|
|
word_ids=[wid],
|
|
segment_ids=[seg_id],
|
|
original_text=first.get("text") or "",
|
|
new_text="",
|
|
reason=(
|
|
f'Removed leading "{first.get("text", "").strip()}" — the '
|
|
"transcription inserted it at the line start but no reference "
|
|
"source has it at this position"
|
|
),
|
|
category="mishearing",
|
|
confidence=P4_CONFIDENCE,
|
|
)
|
|
)
|
|
nxt = words[1]
|
|
nxt_text = nxt.get("text") or ""
|
|
capitalized = _capitalize(nxt_text)
|
|
if nxt.get("id") and capitalized != nxt_text:
|
|
out.append(
|
|
_make_suggestion(
|
|
op="replace",
|
|
word_ids=[nxt.get("id")],
|
|
segment_ids=[seg_id],
|
|
original_text=nxt_text,
|
|
new_text=capitalized,
|
|
reason="Capitalized the new first word of the line",
|
|
category="formatting",
|
|
confidence=P4_CONFIDENCE,
|
|
)
|
|
)
|
|
return out
|
|
|
|
|
|
def _majority_reading(
|
|
readings: Dict[str, List[str]], total_sources: int
|
|
) -> Optional[List[str]]:
|
|
"""The reading >=2/3 of ALL sources agree on (>=2 absolute), else None."""
|
|
votes: Dict[str, List[List[str]]] = {}
|
|
for reading in readings.values():
|
|
if reading:
|
|
votes.setdefault(_norm_join(reading), []).append(reading)
|
|
if not votes:
|
|
return None
|
|
key, group = max(votes.items(), key=lambda kv: len(kv[1]))
|
|
if not key or len(group) < 2 or len(group) * 3 < total_sources * 2:
|
|
return None
|
|
return group[0]
|
|
|
|
|
|
def reference_majority_suggestions(
|
|
segments: List[Dict[str, Any]],
|
|
correction_data: Dict[str, Any],
|
|
streams: Dict[str, Tuple[List[str], Dict[str, int]]],
|
|
) -> List[Dict[str, Any]]:
|
|
"""Pattern 5: replace an implausible-proper-noun gap with the >=2/3 majority reading."""
|
|
words_by_id, seg_of = _word_maps(segments)
|
|
anchors_by_id = {
|
|
a.get("id"): a for a in correction_data.get("anchor_sequences") or [] if a.get("id")
|
|
}
|
|
all_ref_tokens = {
|
|
_norm(t) for texts, _ in streams.values() for t in texts if _norm(t)
|
|
}
|
|
seg_first_word_ids = {
|
|
(seg.get("words") or [{}])[0].get("id") for seg in segments or []
|
|
}
|
|
total_sources = len(streams)
|
|
|
|
out: List[Dict[str, Any]] = []
|
|
for gap in correction_data.get("gap_sequences") or []:
|
|
gap_ids = gap.get("transcribed_word_ids") or []
|
|
if not gap_ids or len(gap_ids) > P5_MAX_GAP_WORDS:
|
|
continue
|
|
gap_words = [words_by_id.get(i) for i in gap_ids]
|
|
if any(w is None for w in gap_words):
|
|
continue # a gap word no longer exists in the working segments
|
|
# Red flag (REQUIRED): a capitalized mid-line token no reference knows.
|
|
# A token merely SIMILAR to a reference token is a spelling variant,
|
|
# not an implausible name — that's the LLM's fix, not ours.
|
|
red_flag = None
|
|
for wid, w in zip(gap_ids, gap_words):
|
|
text = (w.get("text") or "").strip()
|
|
norm = _norm(text)
|
|
if not (
|
|
text
|
|
and text[0].isupper()
|
|
and wid not in seg_first_word_ids
|
|
and norm
|
|
and norm not in all_ref_tokens
|
|
):
|
|
continue
|
|
if any(
|
|
difflib.SequenceMatcher(None, norm, ref).ratio()
|
|
>= P5_SPELLING_VARIANT_RATIO
|
|
for ref in all_ref_tokens
|
|
):
|
|
continue
|
|
red_flag = text
|
|
break
|
|
if red_flag is None:
|
|
continue
|
|
readings = _gap_readings(gap, anchors_by_id, streams)
|
|
majority = _majority_reading(readings, total_sources)
|
|
if majority is None or len(majority) > P5_MAX_READING_WORDS:
|
|
continue
|
|
original = [w.get("text") or "" for w in gap_words]
|
|
if _norm_join(majority) == _norm_join(original):
|
|
continue
|
|
segment_ids = sorted({seg_of.get(i, "") for i in gap_ids})
|
|
out.append(
|
|
_make_suggestion(
|
|
op="replace",
|
|
word_ids=list(gap_ids),
|
|
segment_ids=segment_ids,
|
|
original_text=" ".join(original),
|
|
new_text=" ".join(majority).strip(),
|
|
reason=(
|
|
f'Transcription "{" ".join(original)}" contains "{red_flag}", '
|
|
"which no reference source has; the majority of reference "
|
|
f'sources read this as "{" ".join(majority).strip()}"'
|
|
),
|
|
category="mishearing",
|
|
confidence=P5_CONFIDENCE,
|
|
)
|
|
)
|
|
return out
|
|
|
|
|
|
def _parenthetical_runs(
|
|
words: List[Dict[str, Any]],
|
|
) -> List[Tuple[int, int]]:
|
|
"""Maximal (start, end-inclusive) index runs whose words form one parenthetical
|
|
unit — the first word opens with "(" and the paren balance closes at the end.
|
|
Handles single-word "(word)" and multi-word "(Instrumental break)"."""
|
|
runs: List[Tuple[int, int]] = []
|
|
i = 0
|
|
n = len(words)
|
|
while i < n:
|
|
text = (words[i].get("text") or "").lstrip()
|
|
if text[:1] == "(":
|
|
balance = 0
|
|
j = i
|
|
closed = False
|
|
while j < n:
|
|
tj = words[j].get("text") or ""
|
|
balance += tj.count("(") - tj.count(")")
|
|
if balance <= 0:
|
|
closed = True
|
|
break
|
|
j += 1
|
|
if closed and j < n:
|
|
runs.append((i, j))
|
|
i = j + 1
|
|
continue
|
|
i += 1
|
|
return runs
|
|
|
|
|
|
def phantom_parenthetical_suggestions(
|
|
segments: List[Dict[str, Any]],
|
|
correction_data: Dict[str, Any],
|
|
) -> List[Dict[str, Any]]:
|
|
"""Pattern 8 (fix): delete an all-gap parenthetical run that no confident
|
|
reference match backs (phantom / mis-segmented backing bit).
|
|
|
|
Guards: every word of the run is a gap word (the decisive signal); the run is
|
|
not purely vocalization (those go to the vocalization gate); and it's short
|
|
(<= P8_MAX_RUN_WORDS). Deleting a whole segment's words is fine — the apply
|
|
step drops the now-empty segment."""
|
|
gap_ids: set = set()
|
|
for gap in correction_data.get("gap_sequences") or []:
|
|
gap_ids.update(gap.get("transcribed_word_ids") or [])
|
|
if not gap_ids:
|
|
return []
|
|
|
|
out: List[Dict[str, Any]] = []
|
|
for seg in segments or []:
|
|
words = seg.get("words") or []
|
|
seg_id = seg.get("id") or ""
|
|
for start, end in _parenthetical_runs(words):
|
|
run = words[start : end + 1]
|
|
if not (1 <= len(run) <= P8_MAX_RUN_WORDS):
|
|
continue
|
|
run_ids = [w.get("id") for w in run]
|
|
if not all(run_ids):
|
|
continue
|
|
# Decisive signal: the entire parenthetical is unanchored (all gap).
|
|
if not all(wid in gap_ids for wid in run_ids):
|
|
continue
|
|
# Leave pure-vocalization parentheticals to the vocalization gate.
|
|
if all(_is_vocalization_token(w.get("text") or "") for w in run):
|
|
continue
|
|
original = " ".join((w.get("text") or "") for w in run)
|
|
out.append(
|
|
_make_suggestion(
|
|
op="delete",
|
|
word_ids=list(run_ids),
|
|
segment_ids=[seg_id],
|
|
original_text=original,
|
|
new_text="",
|
|
reason=(
|
|
f'Removed phantom parenthetical "{original.strip()}" — no '
|
|
"reference source confidently matches it; the transcription "
|
|
"hallucinated or mis-segmented a backing/aside bit"
|
|
),
|
|
category="phantom",
|
|
confidence=P8_CONFIDENCE,
|
|
)
|
|
)
|
|
return out
|
|
|
|
|
|
def deterministic_suggestions(
|
|
segments: List[Dict[str, Any]],
|
|
reference_lyrics: Dict[str, Any],
|
|
correction_data: Optional[Dict[str, Any]],
|
|
) -> List[Dict[str, Any]]:
|
|
"""All deterministic suggestions for the current working segments.
|
|
|
|
Needs the job's ``corrections.json`` dict for gap/anchor alignment; with
|
|
none available (or on any internal error) it returns [] — deterministic
|
|
fixes are an enhancement, never a failure mode.
|
|
"""
|
|
if not correction_data or not reference_lyrics:
|
|
return []
|
|
try:
|
|
streams = _ref_word_streams(reference_lyrics)
|
|
if not streams:
|
|
return []
|
|
return (
|
|
leading_connective_suggestions(segments, correction_data, streams)
|
|
+ reference_majority_suggestions(segments, correction_data, streams)
|
|
+ phantom_parenthetical_suggestions(segments, correction_data)
|
|
)
|
|
except Exception:
|
|
logger.warning("deterministic suggestion generation failed", exc_info=True)
|
|
return []
|