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

251 lines
9.1 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.

"""从同源识别和双声道活动提取可复核的字幕边界。所有声音证据仍在 48k 素材坐标。"""
from collections import defaultdict
from itertools import groupby
from math import isfinite
import re
import unicodedata
from uuid import NAMESPACE_URL, uuid5
from app.domain.native_av import (
align_native_utterances,
normalize_native_text,
content_consensus,
source_audio_matches_video,
)
from app.domain.native_silence import MODEL_SHA256, POLICY, REVISION
VERSION = "native-rhythm-v1"
WINDOW = 1536 # Silero 每窗 512 个 16k 样本
PAUSE = 14400
SEMANTIC = re.compile(
r"[+-]?\d+(?:[.::/]\d+)*(?:%|%)?|"
r"[A-Za-z0-9]+(?:[-_./'’][A-Za-z0-9]+)*"
)
def display_text(source, punctuation):
if punctuation == "preserve":
return source
# 小数、时刻、型号、缩写中的符号保留;源文本中的正常空格也保留。
protected = {i for token in SEMANTIC.finditer(source) for i in range(*token.span())}
parts = []
skipped = False
for i, ch in enumerate(source):
if i not in protected and unicodedata.category(ch).startswith("P"):
skipped = True
continue
if skipped and parts and parts[-1].isalnum() and ch.isalnum():
if parts[-1].isascii() or ch.isascii():
parts.append(" ")
parts.append(ch)
skipped = False
return re.sub(" +", " ", "".join(parts)).strip(" ")
def stable_id(uid, start, end):
return uuid5(NAMESPACE_URL, f"cmvr:rhythm:{uid}:{start}:{end}").hex
def _activity(report):
vad = report.get("silence_verification")
count = report["source_end_sample"]
if type(count) is not int or count <= 0:
raise ValueError("原声音轨长度无效")
windows = (count + WINDOW - 1) // WINDOW
required = dict(
policy=POLICY,
revision=REVISION,
model_sha256=MODEL_SHA256,
status="completed",
source="silero-vad-onnx-cpu",
decision="speech",
source_audio_sha256=report["audio_sha256"],
source_start_sample=0,
source_end_sample=count,
sample_rate=16000,
sample_count=(count + 2) // 3,
window_size_samples=512,
window_count=windows,
channels=2,
threshold=0.5,
negative_threshold=0.35,
)
if (
not isinstance(vad, dict)
or not 1 <= windows <= 10000
or any(type(vad.get(k)) is not type(v) or vad[k] != v for k, v in required.items())
):
raise ValueError("缺少匹配原声的双声道语音窗")
channels = vad.get("channel_probabilities")
if (
not isinstance(channels, list)
or len(channels) != 2
or any(
not isinstance(c, list)
or len(c) != windows
or any(type(p) not in (int, float) or not isfinite(p) or not 0 <= p <= 1 for p in c)
for c in channels
)
):
raise ValueError("双声道逐窗概率无效")
pairs = list(zip(*channels, strict=True))
if vad.get("probabilities") != [max(pair) for pair in pairs]:
raise ValueError("逐窗概率与声道证据不符")
# 连续两窗强信号、双声道与周围弱信号共同支持边界;孤立峰保留为噪声候选。
spans = []
for active, group in groupby(enumerate(pairs), key=lambda v: min(v[1]) >= 0.35):
if not active:
continue
block = list(group)
if not any(
min(left[1]) >= 0.5 and min(right[1]) >= 0.5 for left, right in zip(block, block[1:])
):
continue
a, b = block[0][0] * WINDOW, min(count, (block[-1][0] + 1) * WINDOW)
if spans and a - spans[-1][1] < PAUSE:
spans[-1] = spans[-1][0], b
else:
spans.append((a, b))
if not spans:
raise ValueError("没有连续且两声道一致的语音活动")
return spans
def _source_ends(source, words):
# 标点归到前一个分句;跨词的发音稿改写或多对一字形只能确认为整句。
spoken = "".join(w["text"] for w in words)
normalized = normalize_native_text(source)
if normalize_native_text(spoken) != normalized:
return None
glyphs = [i for i, ch in enumerate(source) if normalize_native_text(ch)]
if len(glyphs) != len(normalized):
return None
glyphs.append(len(source))
cursor, ends = 0, []
for w in words:
cursor += len(normalize_native_text(w["text"]))
if cursor >= len(glyphs):
return None
ends.append(glyphs[cursor])
if not ends or ends[-1] != len(source):
return None
return ends
def _phrases(line, words, spans, pacing):
source = line["text"]
whole = [
(
0,
len(source),
spans[0][0],
spans[-1][1],
"automatic" if pacing == "sentence" else "sentence_fallback",
)
]
if pacing == "sentence" or len(spans) == 1:
return whole
ends = _source_ends(source, words)
if not ends:
return whole
word_groups = []
for word in words:
matches = [
i
for i, (a, b) in enumerate(spans)
if word["start_sample"] < b and a < word["end_sample"]
]
if len(matches) != 1:
return whole
word_groups.append(matches[0])
groups = [
(key, list(items)) for key, items in groupby(enumerate(word_groups), key=lambda t: t[1])
]
if [k for k, _ in groups] != list(range(len(spans))) or any(b - a < 12000 for a, b in spans):
return whole
output, start = [], 0
for key, items in groups:
end = ends[items[-1][0]]
if any(m.start() < end < m.end() for m in SEMANTIC.finditer(source)):
return whole
output.append((start, end, *spans[key], "automatic"))
start = end
return output
def measure_shot(sid, assigned, bindings, report, pacing, *, two_person=False):
audio = bindings.get("native_audio:" + sid) or {}
video = bindings.get("video:" + sid) or {}
evidence = (bindings.get("native_alignment:" + sid) or {}).get("provenance") or {}
sha = audio.get("sha256")
expected = "".join(u.get("spoken_text") or u["text"] for u in assigned)
required = dict(
native_av_policy="native_av_v1",
audio_sha256=sha,
sample_rate=48000,
source_start_sample=0,
source_end_sample=audio.get("sample_count"),
speaker_id=sid if two_person else assigned[0]["speaker_id"],
expected_text=expected,
decision="pass",
asr_revision="41f01f3fe87f28c78e2fbf8b568835947dd65ed9",
word_alignment_status="completed",
)
matched_gate = (
evidence.get("video_sha256") == video.get("sha256")
and evidence.get("audio_sha256") == sha
and evidence.get("native_av_policy") == "native_av_v1"
and evidence.get("shot_id") == sid
)
if two_person:
# 整轨识别以镜头 ID 标识;说话人的归属来自已通过或已人工签认的逐轮验收。
gate_sha = (bindings.get("native_alignment:" + sid) or {}).get("sha256")
if (
not matched_gate
or not gate_sha
or gate_sha != (bindings.get("native_report:" + sid) or {}).get("sha256")
or evidence.get("turn_decision") not in {"pass", "manual"}
or not evidence.get("turn_report_asset_id")
or not evidence.get("turn_report_sha256")
or not evidence.get("turn_certificate_sha256")
):
raise ValueError("同框对白的逐轮身份、原声或候选版本尚未核对")
if (
not isinstance(report, dict)
or not sha
or not video.get("sha256")
or not (matched_gate or source_audio_matches_video(audio, video))
or any(report.get(k) != v for k, v in required.items())
or report.get("reasons")
or not content_consensus(report, expected)
):
raise ValueError("原声、完整台词或识别版本尚未核对")
aligned = align_native_utterances(report, assigned)
activity = _activity(report)
by_turn = defaultdict(list)
for a, b in activity:
hits = [u["utterance_id"] for u in aligned if u["start_sample"] < b and a < u["end_sample"]]
if len(hits) != 1:
raise ValueError("语音活动无法唯一分配给发言轮次")
by_turn[hits[0]].append((a, b))
result = {}
for line, aligned_line in zip(assigned, aligned, strict=True):
spans = by_turn[line["id"]]
words = aligned_line["words"]
if not spans or any(
w["end_sample"] > report["source_end_sample"]
or not any(w["start_sample"] < b and a < w["end_sample"] for a, b in spans)
for w in words
):
raise ValueError("部分台词缺少对应的发声证据")
result[line["id"]] = _phrases(line, words, spans, pacing)
offset = (audio.get("provenance") or {}).get("audio_offset_samples", 0)
if (
type(offset) is not int
or offset < 0
or (matched_gate and evidence.get("audio_offset_samples") != offset)
):
raise ValueError("原声偏移与选用镜头不符")
return result, offset