cmvr-visual/backend/app/domain/native_av.py

277 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""原生对白的实测逐词时间投影;没有逐词证据时拒绝推算字幕位置。"""
import re
import unicodedata
TURN_POLICY = "h3-two-person-turns-screen-v1"
def _normalize(value, *, fold_single_digits):
if not isinstance(value, str):
raise ValueError("原生对白文字无效")
value = unicodedata.normalize("NFKC", value).casefold()
# 与推理端内容质检采用相同的普通话同音归一化,原始词和实测时间仍完整保留。
if fold_single_digits:
value = re.sub(
r"(?<![0-9])[0-9](?![0-9])", lambda match: "零一二三四五六七八九"[int(match[0])], value
)
return "".join(
c for c in value.translate(str.maketrans({"她": "他", "它": "他"})) if c.isalnum()
)
def normalize_native_text(value):
return _normalize(value, fold_single_digits=True)
def align_native_utterances(report, utterances, *, audio_offset_samples=0):
"""逐个消费完整词,不把整段时间均分到台词或截开跨句的 ASR 词。"""
if (
not isinstance(report, dict)
or report.get("sample_rate") != 48000
or type(report.get("sample_rate")) is not int
or report.get("timestamp_source") != "whisper-word-timestamps"
or report.get("timestamp_origin") != "audio_asset"
or type(audio_offset_samples) is not int
or audio_offset_samples < 0
):
raise ValueError("缺少原声音轨的48k逐词时间证据")
words = report.get("words")
if not isinstance(words, list) or not 1 <= len(words) <= 10000:
raise ValueError("逐词时间证据为空,不能使用分块边界代替")
if any(not isinstance(word, dict) or not isinstance(word.get("text"), str) for word in words):
raise ValueError("逐词时间格式无效")
# 数字归一化依赖相邻字符,必须先处理整串;例如两个词1、2仍代表12,不能变成一二。
whole = normalize_native_text("".join(word["text"] for word in words))
lengths = [len(_normalize(word["text"], fold_single_digits=False)) for word in words]
if len(whole) != sum(lengths):
raise ValueError("整串归一化无法可靠映射回完整词,不能推算台词边界")
checked = []
previous = 0
position = 0
for word, length in zip(words, lengths, strict=True):
text = whole[position : position + length]
position += length
a, b = word.get("start_sample"), word.get("end_sample")
if type(a) is not int or type(b) is not int or a < previous or b < a or (text and a == b):
raise ValueError("逐词时间重叠或倒退")
previous = b
if text:
checked.append((text, a, b, word))
if not isinstance(utterances, list) or not 1 <= len(utterances) <= 1000:
raise ValueError("需要有序的原生对白台词")
cursor = 0
aligned = []
for u in utterances:
if not isinstance(u, dict) or not u.get("id"):
raise ValueError("台词编号无效")
expected = normalize_native_text(u.get("spoken_text") or u.get("text"))
if not expected:
raise ValueError("台词不能只有标点")
combined = ""
matched = []
while len(combined) < len(expected) and cursor < len(checked):
token, a, b, word = checked[cursor]
combined += token
if not expected.startswith(combined):
raise ValueError("原声逐词内容与台词不符,或一个词跨越多句台词")
matched.append(word)
cursor += 1
if combined != expected or not matched:
raise ValueError("原声缺少完整台词,禁止按镜头边界补齐字幕")
aligned.append(
dict(
utterance_id=u["id"],
start_sample=matched[0]["start_sample"] + audio_offset_samples,
end_sample=matched[-1]["end_sample"] + audio_offset_samples,
words=[dict(w) for w in matched],
)
)
if cursor != len(checked):
raise ValueError("原声包含未分配的额外对白")
return aligned
def validate_turn_report(report, contract, aligned, sources, frames):
"""将服务端逐轮证据重新绑定到本轮选片、原声与参考,拒绝旧请求或不完整报告。"""
from app.domain.stories import digest
speaker_ids = contract["speaker_ids"]
intent = dict(
speaker_ids=speaker_ids,
turns=contract["turns"],
first_frame_sha256=contract["first_frame_sha256"],
references=[sources[k] for k in ("face_0", "face_1", "voice_0", "voice_1")],
)
if (
report.get("policy") != TURN_POLICY
or report.get("controls") is not False
or report.get("certificate_sha256") != contract["certificate_sha256"]
or not contract["certificate_sha256"]
or report.get("source_sha256") != sources
or sources["first_frame"] != contract["first_frame_sha256"]
or report.get("author_sha256") != digest(intent)
):
raise ValueError("候选报告与本次原片、原声、角色参考或认证版本不匹配")
checks = report.get("checks", {})
if (
not isinstance(checks, dict)
or not isinstance(report.get("turns"), list)
or len(report["turns"]) != 2
or len(aligned) != 2
):
raise ValueError("双人逐轮证据不完整")
mandatory = (
"geometry",
"audio_binding",
"tracking",
"visual",
*["tail_" + s for s in speaker_ids],
)
if any(
not isinstance(checks.get(k), dict)
or checks[k].get("decision") not in ("pass", "indeterminate", "reject")
for k in mandatory
):
raise ValueError("双人原片、跟踪或收尾测量缺失")
if checks["audio_binding"]["decision"] != "pass" or checks["geometry"]["decision"] != "pass":
raise ValueError("候选音轨或画面规格无法验证")
if (
checks["visual"].get("source_matched") is not True
or checks["visual"].get("review_sha256") != sources["visual_review"]
):
raise ValueError("整镜视觉检查与候选来源不符")
geometry = checks["geometry"]
if [
geometry.get("width"),
geometry.get("height"),
geometry.get("fps"),
geometry.get("frames"),
] != [1344, 768, 24, frames]:
raise ValueError("双人画布或帧数与本次配置不符")
states = [v.get("decision") for v in checks.values() if isinstance(v, dict)]
for row, time, turn in zip(report["turns"], aligned, contract["turns"], strict=True):
who = turn["speaker_id"]
listener = next(s for s in speaker_ids if s != who)
if (
not isinstance(row, dict)
or row.get("utterance_id") != turn["utterance_id"]
or time["utterance_id"] != turn["utterance_id"]
or row.get("expected_speaker_id") != who
or row.get("listener_id") != listener
or row.get("start_sample") != time["start_sample"]
or row.get("end_sample") != time["end_sample"]
or row.get("decision") not in ("pass", "reject", "indeterminate")
or not isinstance(row.get("voice"), dict)
):
raise ValueError("轮次证据与指定台词、角色或实测时间不匹配")
observed = row["voice"].get("observed_speaker_id")
if (
observed is not None
and observed != who
or row.get("listener_sync", {}).get("decision") == "pass"
or row.get("speaker_sync", {}).get("decision") == "reject"
):
return "reject"
if row["decision"] == "pass" and (
observed != who
or row.get("speaker_sync", {}).get("decision") != "pass"
or row.get("listener_rest", {}).get("decision") != "pass"
or not isinstance(row.get("listener_sync"), dict)
):
raise ValueError("自动通过的轮次缺少声线与双脸同步对照")
states.append(row["decision"])
if checks["tracking"]["decision"] == "pass":
tracks = report.get("tracks")
if (
not isinstance(tracks, dict)
or set(tracks) != set(speaker_ids)
or any(not isinstance(t, list) or len(t) != frames for t in tracks.values())
):
raise ValueError("双脸连续轨迹缺失")
for side, role in enumerate(speaker_ids):
for i, obs in enumerate(tracks[role]):
scores = obs.get("identity_similarities") if isinstance(obs, dict) else None
if (
not isinstance(scores, list)
or len(scores) != 2
or any(type(s) not in (int, float) or not -1.001 <= s <= 1.001 for s in scores)
or scores[side] < 0.4
or scores[side] - scores[1 - side] < 0.14
or obs.get("frame") != i
or not isinstance(obs.get("box"), list)
or len(obs["box"]) != 4
or type(obs.get("track_iou")) not in (int, float)
or not 0.35 <= obs["track_iou"] <= 1
):
raise ValueError("人脸轨迹缺少逐帧独立身份、连续性或位置证据")
verdict = (
"reject"
if "reject" in states
else "pass"
if all(s == "pass" for s in states)
else "indeterminate"
)
if report.get("decision") != verdict:
raise ValueError("候选总评与逐轮证据不一致")
return verdict
CONTENT_POLICY = "whisper-sensevoice-consensus-v1"
def content_consensus(report, expected):
from app.domain.native_silence import verified_silence
if not isinstance(expected, str):
return False
if not expected.strip():
return verified_silence(report, expected)
normalized = normalize_native_text(expected)
if not normalized:
return False
fields = dict(
content_verification_policy=CONTENT_POLICY,
content_decision_source="whisper_sensevoice_consensus",
secondary_status="completed",
secondary_asr_revision="90c1c61912018b70ada0fcc024ea24aca62f2e63",
secondary_runtime_revision="6991744856587fa44379e8b5dcc432debffeb1be",
normalized_expected_text=normalized,
normalized_transcript=normalized,
normalized_secondary_transcript=normalized,
)
if any(report.get(k) != v for k, v in fields.items()):
return False
for name in ("content_error_rate", "secondary_content_error_rate"):
if type(report.get(name)) not in (int, float) or report[name] != 0:
return False
for name in ("transcript", "secondary_transcript"):
if (
not isinstance(report.get(name), str)
or normalize_native_text(report[name]) != normalized
):
return False
return True
def source_audio_matches_video(audio, video):
"""核对由原生提取任务签入的同源关系,单独读报告无需重新进行画面验收。"""
from app.domain.stories import digest
provenance = audio.get("provenance") or {}
sidecar = (video.get("provenance") or {}).get("native_source_audio_asset_id")
return bool(
video.get("sha256")
and audio.get("sha256")
and sidecar
and sidecar == provenance.get("source_audio_asset_id")
and audio.get("sample_rate") == 48000
and type(audio.get("sample_count")) is int
and audio["sample_count"] > 0
and provenance.get("native_av_policy") == "native_av_v1"
and type(provenance.get("audio_offset_samples")) is int
and provenance["audio_offset_samples"] >= 0
and audio.get("context_hash")
== digest(dict(video_sha=video["sha256"], policy="native_av_v1"))
)