91 lines
4.0 KiB
Python
91 lines
4.0 KiB
Python
"""原生对白的实测逐词时间投影;没有逐词证据时拒绝推算字幕位置。"""
|
||
|
||
import re
|
||
import unicodedata
|
||
|
||
|
||
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
|