"""将父台词、素材坐标和编辑例外汇合到可冻结的全片字幕表。""" from collections import defaultdict from app.domain.continuity import compile_story_timing from app.domain.rhythm_captions import VERSION, display_text, measure_shot, stable_id from app.domain.timeline import Subtitle def _remap(edit, text): old = edit["source_text"] a, b = edit["source_start"], edit["source_end"] if old == text: return a, b piece = old[a:b] start = text.find(piece) if ( not piece or old.find(piece) != a or old.find(piece, a + 1) != -1 or start < 0 or text.find(piece, start + 1) != -1 ): raise ValueError("人工编辑的原文范围已变化,请核对并重新绑定") return start, start + len(piece) def _apply_edits(line, base, edits, punctuation): """按原文覆盖;删除范围不复活,拆分没有自动边界时保留为待校时。""" source, uid = line["text"], line["id"] overlays = sorted(((*_remap(e, source), e) for e in edits), key=lambda entry: entry[:2]) if any(a < last[1] for last, (a, b, e) in zip(overlays, overlays[1:])): raise ValueError("此台词的人工编辑范围发生重叠") starts = {a: left for a, b, left, right, status in base} ends = {b: right for a, b, left, right, status in base} def row(a, b, left, right, status, edit=None): e = edit or {} if e.get("timing_override"): left, right = e["start_frame"], e["end_frame"] text = e["text"] if e.get("text_override") else display_text(source[a:b], punctuation) return dict( id=e.get("id") or stable_id(uid, a, b), source_text=source, source_start=a, source_end=b, text=text, local_start_frame=left, local_end_frame=right, status=status if left is not None and right is not None else "pending", text_override=e.get("text_override", False), timing_override=e.get("timing_override", False), ) output = [] for a, b, e in overlays: if not e.get("deleted"): output.append(row(a, b, starts.get(a), ends.get(b), "manual", e)) for a, b, left, right, status in base: cursor = a for x, y, e in overlays: if y <= a: continue if x >= b: break if cursor < x: output.append(row(cursor, x, starts.get(cursor), ends.get(x), status)) cursor = max(cursor, y) if cursor < b: output.append(row(cursor, b, starts.get(cursor), ends.get(b), status)) return output def _non_dialogue(manifest, bindings): from app.services.editor_media import _legacy_rows captions = manifest["captions"] m = { **manifest, "spec": { **manifest["spec"], "dialogue": {**manifest["spec"]["dialogue"], "enabled": False}, }, "captions": { **captions, "cues": [c for c in captions["cues"] if c["anchor"] != "utterance"], }, } if not m["captions"]["cues"] and not m.get("audio", {}).get("segments"): return [] # 保留有效的版本化 StorySpec,借用传统四类锚点的换算器。 return _legacy_rows(m, bindings, prepared={"utterances": []}, limit_count=False) def _limit_rows(rows, issues, punctuation): """总计包含手工及旁白;只合并同句、相邻来源、无锁的自动段。""" excess = len(rows) - 1000 if excess <= 0: return rows result = [] for row in rows: prior = result[-1] if result else None if ( excess and prior and row.get("utterance_id") and row["utterance_id"] == prior["utterance_id"] and row["status"] == prior["status"] == "automatic" and prior["source_end"] == row["source_start"] ): prior.update( source_end=row["source_end"], end_frame=row["end_frame"], local_end_frame=row["local_end_frame"], ) prior["text"] = display_text( prior["source_text"][prior["source_start"] : prior["source_end"]], punctuation ) prior["id"] = stable_id(row["utterance_id"], prior["source_start"], prior["source_end"]) excess -= 1 else: result.append(row) if excess: loc = result[1000] issues.append( dict( code="caption_limit", unit_id=loc.get("utterance_id") or loc["id"], message="字幕数量超过1000条,请在此处或之前合并同句字幕", ) ) return result def project_captions(manifest, bindings, reports, prepared, *, utterance_id=None): from app.services.editor_media import assigned_utterance_ids caps = manifest["captions"] presentation = caps["presentation"] issues = [] def issue(code, uid, message): issues.append(dict(code=code, unit_id=uid, message=message)) if prepared and prepared.get("effective_manifest"): manifest = {**prepared["effective_manifest"], "captions": caps} try: rows = [] if utterance_id is not None else _non_dialogue(manifest, bindings) except ValueError as exc: rows = [] issue("invalid_caption", "captions", str(exc)) spec = manifest["spec"] dialogue = spec.get("dialogue", {}) if not dialogue.get("enabled"): return dict(rows=_limit_rows(rows, issues, presentation["punctuation"]), issues=issues) lines = {u["id"]: u for u in dialogue["utterances"]} sequences = {seq["id"]: seq for seq in dialogue["sequences"]} timing = (prepared or {}).get("timing") or compile_story_timing(spec) timing_by_id = {t["shot_id"]: t for t in timing["shots"]} resolved = set() old_cues = {c["utterance_id"]: c for c in caps["cues"] if c["anchor"] == "utterance"} edits = defaultdict(list) for e in caps["edits"]: edits[e["utterance_id"]].append(e) for shot in spec["shots"]: sid = shot["id"] ids = assigned_utterance_ids(shot, sequences) if utterance_id is not None and utterance_id not in ids: continue assigned = [lines[uid] for uid in ids if uid in lines] if not assigned: continue t = timing_by_id[sid] shot_start, duration = t["start_frame"], t["contribution_frames"] trim = t.get("source_start_frame", 0) + t.get("dedup_frames", 0) intervals = {} reason = "等待原声识别和双声道语音活动证据" offset = 0 if reports.get(sid) and dialogue.get("generation") == "native_av": try: intervals, offset = measure_shot( sid, assigned, bindings, reports[sid], presentation["pacing"], two_person=shot["performance"].get("dialogue_staging") == "two_person_turns", ) except ValueError as exc: reason = str(exc) for line in assigned: uid, source = line["id"], line["text"] if utterance_id is not None and uid != utterance_id: continue cue = old_cues.get(uid) or {} if uid in resolved: issue("caption_duplicate_turn", uid, "同一台词出现在多个镜头,请核对发言轮次") continue resolved.add(uid) if caps["mode"] == "manual" and not cue and not edits[uid]: continue fragments = intervals.get(uid, []) base = [ ( a, b, (left + offset + 1000) // 2000 - trim, (right + offset + 1000) // 2000 - trim, status, ) for a, b, left, right, status in fragments ] if not base: base = [(0, len(source), None, None, "pending")] line_edits = edits[uid] audio_sha = (bindings.get("native_audio:" + sid) or {}).get("sha256") if any( not e.get("deleted") and e.get("timing_override") and e.get("audio_sha256") and e["audio_sha256"] != audio_sha for e in line_edits ): issue("caption_audio_changed", uid, "原声已更换,请试听并重新确认受保护的字幕时间") if not line_edits and (cue.get("text_override") or cue.get("timing_override")): # 旧时间锁锚在已投影的父句(包含音频偏移),不再加偏移。 evidence = (bindings.get("native_alignment:" + sid) or {}).get("provenance") or {} parent = next( (u for u in evidence.get("utterances", []) if u["utterance_id"] == uid), {} ) start, end = base[0][2], base[-1][3] if cue.get("timing_override"): start = end = None if type(parent.get("start_sample")) is int: origin = (parent["start_sample"] + 1000) // 2000 - trim start, end = origin + cue["start_frame"], origin + cue["end_frame"] base = [(0, len(source), start, end, "manual")] line_edits = [ dict( cue, source_start=0, source_end=len(source), source_text=source, start_frame=start, end_frame=end, ) ] try: display = _apply_edits(line, base, line_edits, presentation["punctuation"]) except ValueError as exc: issue("caption_edit_conflict", uid, str(exc)) display = _apply_edits(line, base, [], presentation["punctuation"]) for row in display: left, right = row["local_start_frame"], row["local_end_frame"] row.update( utterance_id=uid, turn_id=uid, shot_id=sid, speaker_id=line["speaker_id"], algorithm_version=VERSION, audio_sha256=audio_sha, evidence_version=(reports.get(sid) or {}).get("asr_revision"), start_frame=None if left is None else shot_start + left, end_frame=None if right is None else shot_start + right, ) rows.append(row) if not row["text"].strip(): issue("empty_caption", uid, "显示文字为空") if left is None or right is None: issue("caption_timing_pending", uid, "待校时:" + reason) elif left < 0 or right <= left or right > duration: issue("caption_out_of_range", uid, "字幕时间超出镜头选用范围,请校时") else: try: Subtitle( start_frame=row["start_frame"], end_frame=row["end_frame"], text=row["text"], ) except ValueError: issue("invalid_caption", uid, "字幕含不支持的字符或长度超限") for uid in lines.keys() - resolved: if utterance_id is not None and uid != utterance_id: continue if caps["mode"] in ("script", "ai_script") or uid in edits or uid in old_cues: issue("caption_unassigned", uid, "待校时:台词尚未唯一分配到镜头") rows.sort(key=lambda r: (r["start_frame"] is None, r["start_frame"] or 0, r["source_start"])) previous = None for row in rows: if row["start_frame"] is None or row["end_frame"] is None: continue if previous and row["start_frame"] < previous["end_frame"]: issue( "caption_overlap", row.get("utterance_id") or row["id"], "字幕时间重叠,请核对受保护的时间", ) if previous is None or row["end_frame"] > previous["end_frame"]: previous = row rows = _limit_rows(rows, issues, presentation["punctuation"]) return dict(rows=rows, issues=issues)