nex_animation/backend/app/services/asr.py

241 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""成片听写(whisper.cpp 本地转写):回答「这一段里到底说了什么」。
画面质检看的是帧,而联合音视频模型最常见的穿帮是**听觉**的——镜头开头冒出一段
谁也听不懂的话。成因是提示词里的画面描述被模型当台词念了出来(逐条实测见
:func:`app.services.prompt.joint_speech_duration_seconds`)。这类穿帮看码率、看时长、
看画面全是 100 分,只有把音轨听一遍才暴露,所以这里补一路「听」。
whisper.cpp 是纯命令行本地模型:不花钱、不联网、不出本机,适合放进自动质检。
"""
from __future__ import annotations
import difflib
import json
import logging
import re
import shutil
import subprocess
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from app.config import PROJECT_ROOT, settings
from app.services import ffmpeg as ff
log = logging.getLogger(__name__)
# 台词前这么多字用来定位「人声真正从哪儿开始」。取 6 个是因为:再短容易被泄漏文本里
# 恰好出现的同一个字带偏(「医院诊室内」和「医院使用的是」开头就撞了 2 个字),
# 再长则一旦开头被念错/念漏就整段对不上。
_ANCHOR_CHARS = 6
# 台词之前允许出现的杂音字数。ASR 本身会吞字、会把语气词识别成别词,
# 1~2 个字的残渣不算事故;实测泄漏都是 4~6 字起的成词短语(「都市清新风格」)。
_LEAK_CHARS = 3
# 但**字数少不等于没泄漏**:project 12 镜 #7(shot40)只漏出「固定」两个字
# (caption 原文「…近景,过肩镜头,固定机位」),只看字数就放行了。
# 补一条精确规则:这段杂音是不是**逐字出自本镜提示词**。命中即事故,与长短无关。
# 2 个字是下限,但只有「整段杂音全在提示词里」时才够分量——上百字的 caption 里
# 撞见任意两个连续汉字太容易了(「画面」「办公室」),部分命中必须到 3 字才算照抄。
# 反过来,无台词镜 whisper 会幻听(shot40 实测整段只吐出「字幕君」),
# 幻听不是提示词的子串,这条规则对它天然不响。
_LEAK_MATCH_CHARS = 2 # 杂音整体逐字命中时的最低字数
_LEAK_PART_CHARS = 3 # 只命中杂音的一部分时的最低字数
_PUNCT = re.compile(r"[\s,。!?、;:…—-·\"'“”‘’,.!?;:\"'()()【】\[\]<>《》~《》<>]+")
# whisper 的 initial prompt:这一句同时干两件事——提示领域(中文口播),
# 以及**强制输出简体**。不带它时 small 模型会跟着台词里的字形飘到繁体
# (实测输出「俊傑」「醫院」「風格」),跟分镜里的简体台词对不上,自检就会误判。
_SIMPLIFY_PROMPT = "以下是简体中文的普通话视频台词字幕。"
@dataclass
class Segment:
text: str
start: float
end: float
@dataclass
class Transcript:
segments: list[Segment] = field(default_factory=list)
text: str = ""
@property
def cjk_count(self) -> int:
return len([ch for ch in normalise(self.text) if "\u4e00" <= ch <= "\u9fff"])
def model_path() -> Path | None:
raw = str(settings.asr_model or "").strip()
if not raw:
return None
p = Path(raw)
if not p.is_absolute():
p = PROJECT_ROOT / p
return p if p.is_file() else None
def binary() -> str:
configured = str(settings.asr_bin or "").strip()
if configured:
return configured if Path(configured).is_file() else (shutil.which(configured) or "")
for name in ("whisper-cli", "whisper"): # whisper.cpp 的新/旧可执行名
found = shutil.which(name)
if found:
return found
return ""
def available() -> tuple[bool, str]:
"""能不能听写。不能时给出**具体缺什么**,让质检说明理由而不是静默跳过。"""
if not bool(getattr(settings, "qc_asr_enabled", True)):
return False, "已关闭(QC_ASR_ENABLED=false)"
if not binary():
return False, "未找到 whisper-cli(brew install whisper-cpp)"
if model_path() is None:
return False, f"缺少模型文件 {settings.asr_model}"
if not ff.available():
return False, "缺少 ffmpeg,无法从成片抽音轨"
return True, ""
def normalise(text: str) -> str:
"""比对用归一化:去标点空白。繁简交给 initial prompt 解决(见 :data:`_SIMPLIFY_PROMPT`)。"""
return _PUNCT.sub("", str(text or ""))
def prompt_leak(before: str, prompt: str) -> dict:
"""台词前那段杂音是不是**逐字出自本镜提示词**——画面描述被念出来的铁证。
判据是「有没有一段连续的字原样出现在提示词里」,不是「杂音有几个字」:
泄漏文本是提示词的一个子串,这一点很难用巧合解释;而幻听(「字幕君」)、
ASR 同音误判(shot39 台词里的「汇智」听成「绘制」——它落在台词位置上,
根本不会进入这段杂音)都不是子串,天然不响。
短到 2 字的命中要求整段杂音都被覆盖,就是为了不把撞词当泄漏。
``autojunk=False``**必须显式传**:默认开启时 SequenceMatcher 会把出现超过
200 次的字符当「多数派」丢弃,中文 caption 里「面、镜、头」这类字很容易越线,
一旦丢弃最长公共子串会莫名变短,正好把要抓的泄漏判成干净。
"""
a, b = normalise(before), normalise(prompt)
if not a or not b:
return {"match": "", "chars": 0, "narrated": False}
hit = difflib.SequenceMatcher(None, a, b, autojunk=False).find_longest_match(0, len(a), 0, len(b))
whole = hit.size >= len(a) # 整段杂音都是提示词的原话
enough = hit.size >= (_LEAK_MATCH_CHARS if whole else _LEAK_PART_CHARS)
return {"match": a[hit.a:hit.a + hit.size], "chars": hit.size,
"verbatim": whole, "narrated": bool(hit.size) and enough}
def transcribe(media: str | Path, *, language: str = "zh",
timeout: int | None = None) -> Transcript | None:
"""转写成片音轨。任何失败都返回 ``None``——质检不能被一个可选能力打挂。"""
exe = binary()
model = model_path()
if not exe or model is None or not ff.available():
return None
src = Path(media)
if not src.is_file():
return None
limit = int(timeout or settings.asr_timeout or 240)
tmp = Path(tempfile.mkdtemp(prefix="nex-asr-"))
wav, base = tmp / "audio.wav", tmp / "out"
try:
subprocess.run([ff.resolve_binary("ffmpeg"), "-y", "-v", "error", "-i", str(src),
"-vn", "-ac", "1", "-ar", "16000", str(wav)],
check=True, capture_output=True, timeout=limit)
# -ng 是硬要求:这份 Homebrew 构建带 Metal backend,开采样时会直接 abort 崩进程。
subprocess.run([exe, "-m", str(model), "-f", str(wav), "-l", language or "zh",
"-ng", "-t", "4", "--prompt", _SIMPLIFY_PROMPT,
"-oj", "-of", str(base)],
check=True, capture_output=True, timeout=limit)
payload = json.loads(base.with_suffix(".json").read_text(encoding="utf-8"))
except Exception as exc: # noqa: BLE001 - 可选能力
log.warning("听写失败 %s:%s", src.name, str(exc)[:300])
return None
finally:
shutil.rmtree(tmp, ignore_errors=True)
segs = [Segment(normalise(str(x.get("text") or "")),
float(x.get("offsets", {}).get("from") or 0) / 1000.0,
float(x.get("offsets", {}).get("to") or 0) / 1000.0)
for x in payload.get("transcription", [])]
segs = [x for x in segs if x.text]
return Transcript(segments=segs, text="".join(x.text for x in segs))
def _speech_start(transcript: Transcript, index: int) -> float:
"""台词落在第几个字 → 找到承载它的那一段的起点(秒)。找不到就用 0。"""
for seg in transcript.segments:
if index < len(seg.text):
return seg.start
index -= len(seg.text)
return transcript.segments[0].start if transcript.segments else 0.0
def audit_dialogue(media: str | Path, dialogue: str, *, prompt: str = "",
timeout: int | None = None) -> dict | None:
"""听一遍成片,回答三个问题:台词念全了没、开口前多念了什么、大概几秒开始说。
做法是先定位「台词真正从转写文本的第几个字开始」(拿台词前 :data:`_ANCHOR_CHARS`
个字滑窗找最像的位置),它前面那几个字就是被多念出来的东西。
之所以不直接判断「转写里有没有台词」:台词本身几乎总能被念出来,
事故形态是**前面多一段**,必须按位置算。
``prompt`` 传本镜**实际下发的画面描述**(去掉台词的部分,见
:func:`app.services.quality.shot_caption`),用来跑 :func:`prompt_leak`
这条精确规则。留空时退化成只看字数——宁可少抓,不可误伤。
"""
transcript = transcribe(media, timeout=timeout)
if transcript is None:
return None
want, got = normalise(dialogue), transcript.text
if not want:
# 无台词镜头同样要听(这是 shot40 的盲区:以前质检在这里直接 return,
# 成片里的泄漏全靠人肉看片发现)。但判据只用逐字命中:
# 这种镜头本来就可能有任何听得见的动静(键盘声、音乐、幻听),
# 只有「念的正好是提示词里的原话」才叫穿帮。
leak = prompt_leak(got, prompt)
return {"transcript": got, "before": got if leak["narrated"] else "",
"before_chars": len(got) if leak["narrated"] else 0,
"missing": 0, "coverage": 1.0, "speech_start": 0.0,
"narration": leak["match"], "narrated": leak["narrated"],
"leaked": leak["narrated"], "incomplete": False,
"ok": not leak["narrated"]}
anchor = want[:_ANCHOR_CHARS]
if len(got) < len(anchor):
best, ratio = 0, difflib.SequenceMatcher(None, anchor, got).ratio() if got else 0.0
else:
# 先把每个落点的相似度都算完,再取「并列最优里最靠后的那一个」。
# 为什么取最靠后:台词开头那几个字本来就容易和泄漏文本糊在一起
# (shot-03-task656 实测念了「中景」,「中景再后台操作」与「我在后台操作」
# 的相似度并列第一)。取靠前的落点会把「景」吞进台词里,
# 只剩「中」1 个字,精确规则就够不着了;取靠后的落点宁可多算一个字的杂音。
scores = [difflib.SequenceMatcher(None, anchor, got[i:i + len(anchor)]).ratio()
for i in range(len(got) - len(anchor) + 1)]
ratio = max(scores)
best = max(i for i, score in enumerate(scores) if score >= ratio - 0.02)
before = got[:best]
spoken = got[best:]
# 覆盖率:台词有多少字真的被念出来了。低覆盖率 + 前面有杂音,通常是模型把台词
# 换成了提示词里的别的句子(S02 实测:开头「不用担心」整段被「都市清新风格」顶替)。
matcher = difflib.SequenceMatcher(None, want, spoken, autojunk=False)
covered = sum(b.size for b in matcher.get_matching_blocks())
coverage = round(covered / len(want), 2) if want else 1.0
missing = max(0, len(want) - covered)
# 两种穿帮分开说,因为处置不同:
# before → 台词前面多念了一段(空档被画面描述填掉,本文件的立身之本);
# incomplete → 台词本身缺字/被顶替(S02 实测「不用担心」整段换成「都市清新风格」,
# 此时 before 只剩 2 个残渣字,只看 before 会漏报)。
leak = prompt_leak(before, prompt)
# 两条规则取并集,因为各有各的抓法:
# 字数规则 → 抓改写型泄漏(shot41「我是小慧选」是 caption 里
# 「<Picture 2>中的紫小慧」的转述,逐字对不上,只能靠成词短语的字数);
# 逐字规则 → 抓短到看不出是短语的泄漏(shot40 只剩「固定」两字)。
leaked = len(before) >= _LEAK_CHARS or leak["narrated"]
incomplete = missing >= _LEAK_CHARS
return {"transcript": got, "before": before, "before_chars": len(before),
"missing": missing, "coverage": coverage,
"speech_start": round(_speech_start(transcript, best), 2),
"narration": leak["match"], "narrated": leak["narrated"],
"leaked": leaked, "incomplete": incomplete, "ok": not leaked and not incomplete}