"""Host-independent segmentation, camera scaffolds and project persistence.""" import copy import hashlib import json import math import os from pathlib import Path import re import threading import uuid import numpy as np from .director_rules import default_config, validate_config LOCK = threading.RLock() def project_path(root, project_id): if not re.fullmatch(r"[0-9a-f]{32}", str(project_id)): raise ValueError("项目编号无效,请先运行音频分析节点。") root = Path(root).resolve() result = (root / project_id).resolve() if result.parent != root: raise ValueError("项目路径越界。") return result def inside(root, path): root, path = Path(root).resolve(), Path(path).resolve() if not path.is_relative_to(root): raise ValueError("文件不属于当前项目。") return path REFERENCE_MIRROR_ROOT = "H3LV" MAX_SEGMENT_REFERENCES = 6 REFERENCE_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif"} MAX_REFERENCE_BYTES = 32 * 1024 * 1024 def reference_directory(directory): return Path(directory)/"refs" def normalize_reference_names(value, directory=None): """Validate the ordered per-segment reference list without reordering it.""" if value in (None, ""): return [] if not isinstance(value, (list, tuple)): raise ValueError("分段参考图必须按顺序保存为列表。") names = [] for item in value: name = str(item or "").strip() if not name: raise ValueError("分段参考图存在空白项,请重新选择图片。") if Path(name).name != name: raise ValueError("参考图文件名无效。") names.append(name) if len(names) > MAX_SEGMENT_REFERENCES: raise ValueError(f"每段最多 {MAX_SEGMENT_REFERENCES} 张参考图。") if directory is not None: root = reference_directory(directory) for name in names: if not (root/name).is_file(): raise ValueError(f"参考图已丢失:{name}。请在分段卡片中重新上传。") return names def store_reference(directory, index, filename, content): """Persist one uploaded picture inside the project and return its stored name.""" suffix = Path(str(filename or "")).suffix.lower() if suffix not in REFERENCE_IMAGE_EXTENSIONS: raise ValueError("参考图只支持 PNG、JPG、WEBP、BMP 或 GIF 格式。") if not content: raise ValueError("上传的参考图内容为空。") if len(content) > MAX_REFERENCE_BYTES: raise ValueError("单张参考图不能超过 32 MiB。") root = reference_directory(directory) root.mkdir(parents=True, exist_ok=True) name = f"seg{int(index):04d}_{uuid.uuid4().hex[:8]}{suffix}" temporary = root/f".{name}.tmp" temporary.write_bytes(content) os.replace(temporary, root/name) return name def remove_reference(directory, name): root = reference_directory(directory) path = inside(root, root/str(name)) if path.is_file(): path.unlink() return path.name # Distinguishes "not supplied" from an explicit value when saving a project. UNSET = object() def normalize_default_reference_count(value): """Normalize the project-wide fallback count for unconfigured segments. None keeps the legacy behaviour: every connected canvas reference is used. """ if value is None or value == "": return None try: count = int(value) except (TypeError, ValueError) as exc: raise ValueError("默认参考图张数必须是整数。") from exc if not 0 <= count <= MAX_SEGMENT_REFERENCES: raise ValueError(f"默认参考图张数必须在 0 到 {MAX_SEGMENT_REFERENCES} 之间。") return count def output_preview(output_root, path, fps=24): """Describe an output file in the format consumed by VHS video previews.""" if not path: return None output_root = Path(output_root).resolve() path = inside(output_root, path) if not path.is_file(): return None relative = path.relative_to(output_root) subfolder = "" if relative.parent == Path(".") else relative.parent.as_posix() return {"filename": path.name, "subfolder": subfolder, "type": "output", "format": "video/h264-mp4", "frame_rate": float(fps), "fullpath": str(path)} def state_file(directory, name): if Path(name).name != str(name): raise ValueError("项目状态文件名无效。") return Path(directory) / "state" / str(name) def audio_file(directory, name): if Path(name).name != str(name): raise ValueError("项目音频文件名无效。") return Path(directory) / "audio" / str(name) def read_plan(root, project_id): with LOCK: return json.loads(state_file(project_path(root, project_id), "segments.json").read_text(encoding="utf-8")) def read_project_transcript(directory, plan): """Read ASR data, reconstructing enough text timing for legacy project review.""" path = state_file(directory, "transcript.json") if path.is_file(): try: return json.loads(path.read_text(encoding="utf-8")), False except (OSError, json.JSONDecodeError): pass segments = [{"start": float(row["start"]), "end": float(row["end"]), "text": str(row.get("text", "")).strip()} for row in plan.get("segments", []) if str(row.get("text", "")).strip()] if not segments: raise ValueError("这个旧项目缺少语音识别缓存,也没有可恢复的分段文本。请重新运行音频分析。") return {"segments": segments, "words": []}, True def write_plan(root, plan): with LOCK: directory = project_path(root, plan["id"]) state = directory / "state" state.mkdir(parents=True, exist_ok=True) temp = state / f".segments-{uuid.uuid4().hex}.tmp" temp.write_text(json.dumps(plan, ensure_ascii=False, indent=2), encoding="utf-8") temp.replace(state / "segments.json") def frames_for(seconds, edit_frames): return 5 + 17 * math.ceil((max(124, math.ceil(seconds * 24), edit_frames) - 5) / 17) def preview_bounds(plan, index, start=None, end=None, boundary=False): """Resolve a bounded, unsaved segment preview without changing the plan.""" row = plan["segments"][int(index)] sr = int(plan["sample_rate"]) if (start is None) != (end is None): raise ValueError("试听起止时间必须同时提供。") if start is None: a, b = int(row["start_sample"]), int(row["end_sample"]) else: start, end = float(start), float(end) if not math.isfinite(start) or not math.isfinite(end): raise ValueError("试听时间无效。") a, b = round(start*sr), round(end*sr) if a < 0 or b > int(plan["samples"]) or b <= a: raise ValueError("试听范围必须位于原曲内,且结束时间晚于开始时间。") if b-a > round((float(plan["max_seconds"])+1/sr)*sr): raise ValueError("试听片段超过最长分段时长。") if boundary: a, b = max(0, b-2*sr), min(int(plan["samples"]), b+2*sr) return a, b def envelope(audio, sr): if not len(audio) or not np.isfinite(audio).all(): raise ValueError("音频为空或含无效数值。") if audio.ndim == 1: audio = audio[:, None] hop = max(1, round(sr * .02)) power = np.mean(np.square(audio.astype(np.float64)), axis=1) starts = np.arange(0, len(audio), hop) blocks = np.add.reduceat(power, starts) / np.minimum(hop, len(audio) - starts) smooth = np.convolve(np.pad(blocks, (2, 2), mode="edge"), np.ones(5) / 5, mode="valid") return starts, 10 * np.log10(np.maximum(smooth, 1e-12)) def _mono(audio): return audio.astype(np.float64) if audio.ndim == 1 else np.mean(audio.astype(np.float64), axis=1) def waveform_peaks(audio, bins=1200): mono = np.abs(_mono(audio)) if not len(mono): return [] edges = np.linspace(0, len(mono), min(bins, len(mono)) + 1, dtype=int) peaks = [float(np.max(mono[edges[i]:edges[i+1]])) for i in range(len(edges)-1)] scale = np.percentile(peaks, 99) if peaks else 1 return [round(min(1, value/max(scale, 1e-9)), 4) for value in peaks] def zero_crossing(audio, starts, sr): mono = _mono(audio) signs = mono >= 0 changes = np.r_[0, signs[1:] != signs[:-1]].astype(np.int32) prefix = np.r_[0, np.cumsum(changes)] width = max(1, round(sr*.04)) ends = np.minimum(len(mono), starts + width) return (prefix[ends]-prefix[starts]) / np.maximum(1, ends-starts) def rhythm_analysis(audio, sr, hop_seconds=.02): """Return an approximate beat grid used only after vocal-safety scoring.""" mono = _mono(audio) hop, width = max(1, round(sr*hop_seconds)), max(32, round(sr*.04)) window = np.hanning(width) flux, previous = [], None for start in range(0, max(1, len(mono)-width+1), hop): frame = mono[start:start+width] if len(frame) < width: frame = np.pad(frame, (0, width-len(frame))) magnitude = np.abs(np.fft.rfft(frame*window)) flux.append(0 if previous is None else float(np.maximum(0, magnitude-previous).sum())) previous = magnitude flux = np.asarray(flux, dtype=np.float64) if len(flux) < 80 or np.max(flux) <= 0: return {"tempo_bpm": None, "confidence": 0, "beats": [], "bars": []} flux /= np.percentile(flux, 95) or 1 flux = np.maximum(0, flux-np.median(flux)) min_lag = max(1, round(60/180/hop_seconds)) max_lag = min(len(flux)//3, round(60/60/hop_seconds)) scores = np.asarray([np.dot(flux[lag:], flux[:-lag]) for lag in range(min_lag, max_lag+1)]) if not len(scores) or np.max(scores) <= 0: return {"tempo_bpm": None, "confidence": 0, "beats": [], "bars": []} lag = int(np.argmax(scores))+min_lag period = lag*hop_seconds anchor_index = int(np.argmax(flux[:min(len(flux), max(lag*4, 1))])) anchor = anchor_index*hop_seconds duration = len(audio)/sr first = anchor-math.ceil(anchor/period)*period beats = np.arange(first, duration+.5*period, period) beats = beats[(beats >= 0) & (beats <= duration)] sampled = [flux[min(len(flux)-1, round(t/hop_seconds))] for t in beats] phase = max(range(min(4, len(sampled))), key=lambda p: sum(sampled[p::4]), default=0) bars = beats[phase::4] confidence = float(np.clip(np.max(scores)/(np.mean(scores)+1e-9)/4, 0, 1)) return {"tempo_bpm": round(60/period, 2), "confidence": round(confidence, 3), "beats": [round(float(t), 3) for t in beats], "bars": [round(float(t), 3) for t in bars]} def _sections(lines, starts, active, sr, duration, minimum=2): recognized = np.zeros(len(starts), dtype=bool) for line in lines: recognized |= (starts/sr < line["end"]) & ((starts+.02*sr)/sr > line["start"]) quiet_text = ~recognized & ~active sections, i = [], 0 while i < len(quiet_text): if not quiet_text[i]: i += 1 continue j = i+1 while j < len(quiet_text) and quiet_text[j]: j += 1 a, b = starts[i]/sr, min((starts[j-1]/sr)+.02, duration) if b-a >= minimum: if a <= .25: kind = "intro" elif b >= duration-.25: kind = "outro" else: kind = "interlude" sections.append({"start": round(a, 3), "end": round(b, 3), "kind": kind, "confidence": "medium", "reason": "无识别文字且分离人声活动较低"}) i = j return sections def segmentation(audio, sr, transcript, mode, maximum, target, mix_audio=None, return_analysis=False): if not 5 <= maximum <= 15 or not 5 <= target <= maximum: raise ValueError("首版测试范围:5 ≤ 目标时长 ≤ 最长时长 ≤ 15 秒。") starts, db = envelope(audio, sr) lines, words = transcript.get("segments", []), transcript.get("words", []) noise, voice = np.percentile(db, [15, 85]) dynamic = max(6, float(voice-noise)) quiet_threshold = min(float(np.median(db)-8), float(noise+.35*dynamic)) active_threshold = float(noise+.55*dynamic) active = db > active_threshold zcr = zero_crossing(audio, starts, sr) zcr_high = float(np.percentile(zcr, 75)) rhythm = rhythm_analysis(audio if mix_audio is None else mix_audio, sr) beat_points = rhythm["beats"] phrase_ranges = [(min(a["end"], b["start"])-.75, max(a["end"], b["start"])+.75) for a, b in zip(lines, lines[1:])] candidates = {} def word_overlap(t): return [w["word"] for w in words if w["start"]+.02 < t < w["end"]-.02] def quiet_span(i): a = b = i while a > 0 and db[a-1] <= quiet_threshold: a -= 1 while b+1 < len(db) and db[b+1] <= quiet_threshold: b += 1 return a, b, (b-a+1)*.02 def add(point, reason, penalty, warnings=None, kind="valley", confidence=.5): point = int(np.clip(point, 1, len(audio)-1)) i = min(len(db)-1, int(np.searchsorted(starts, point))) overlap = word_overlap(point/sr) item = {"sample": point, "db": float(db[i]), "reason": reason, "penalty": penalty, "warnings": list(warnings or []), "kind": kind, "confidence_score": confidence, "overlap": bool(overlap), "protected_words": overlap} if overlap: item["warnings"].append("切点与估计字时间戳重叠:"+"/".join(overlap)) item["penalty"] += 20 item["confidence_score"] = min(item["confidence_score"], .15) old = candidates.get(point) if old is None or item["penalty"] < old["penalty"]: candidates[point] = item for i in range(1, len(db) - 1): if db[i] <= db[i - 1] and db[i] < db[i + 1] and db[i] <= min(db[max(0, i-15):i+16]): a, b, span = quiet_span(i) previous = float(np.mean(db[max(0, i-10):i])) if i else db[i] following = float(np.mean(db[i+1:min(len(db), i+6)])) if i+1 < len(db) else db[i] if span >= .08: add(starts[i], "持续低人声区", 4, kind="quiet", confidence=.65) elif previous-db[i] >= 6 and following <= quiet_threshold+4: add(starts[i], "拖音衰减后的能量落点", 3, kind="drag_end", confidence=.72) elif zcr[i] >= zcr_high and db[i] < active_threshold: add(starts[i], "疑似换气附近的低能量区", 3.5, ["气口为声学估计,需要试听"], "breath", .62) else: add(starts[i], "人声局部低谷(非已确认句尾)", 7, ["可能在句中,需要试听"], "valley", .4) # Faster-Whisper often makes adjacent lyric segments touch exactly even when # the waveform contains a clear cadence gap. Search each ASR boundary window # directly instead of requiring it to have survived the generic-minimum pass. for first, second in zip(lines, lines[1:]): center = (float(first["end"])+float(second["start"]))/2 indices = [i for i, sample in enumerate(starts) if center-.75 <= sample/sr <= center+.75 and not word_overlap(sample/sr)] if not indices: continue i = min(indices, key=lambda n: db[n]) span = quiet_span(i)[2] if db[i] <= quiet_threshold and span >= .06: add(starts[i], "分句附近的持续低能量区", 0, kind="phrase_gap", confidence=.92) elif db[i] < active_threshold: add(starts[i], "分句附近的人声低谷", 3, ["低谷较短,需要试听确认"], "phrase_valley", .64) point = round(center*sr) if .02 < center < len(audio)/sr-.02 and not word_overlap(center): add(point, "ASR 分句边界", 5, ["分句处没有清晰持续低谷,需要检查唱音拖尾"], "phrase_boundary", .55) for lo, hi in phrase_ranges: options = [] for point, c in candidates.items(): if not lo <= point/sr <= hi or c["db"] > quiet_threshold or c["overlap"]: continue i = int(np.searchsorted(starts, point)) if quiet_span(i)[2] >= .08: options.append(c) if options: chosen = min(options, key=lambda c: c["db"]) chosen.update(reason="分句附近的持续低能量区", penalty=0, kind="phrase_gap", confidence_score=.92) chosen["warnings"] = [] sections = _sections(lines, starts, active, sr, len(audio)/sr) for section in sections: for t, edge in ((section["start"], "开始"), (section["end"], "结束")): if .05 < t < len(audio)/sr-.05 and not word_overlap(t): add(round(t*sr), f"疑似{section['kind']} {edge}边界", 2, ["无人声段为声学估计,需要试听"], "section", .75) # Word boundaries are fallback candidates for overlong phrases, never unflagged safe cuts. for word in words: point = round(word["end"] * sr) if 0 < point < len(audio) and point not in candidates: add(point, "估计词界回退", 12, ["词界回退,可能截断唱歌拖音"], "word_fallback", .28) # Preserve full coverage even for silence, ASR failure or sustained notes. for t in np.arange(target, len(audio) / sr, target): point = round(t * sr) if point not in candidates: warnings = ["无可靠切点,按时长回退,必须检查"] i = min(len(db)-1, int(np.searchsorted(starts, point))) if active[i]: warnings.append("强制切点可能落在持续唱音区") add(point, "时长强制回退", 40, warnings, "forced", .08) candidates[0] = {"sample": 0, "db": -120, "penalty": 0, "warnings": [], "reason": "音频开始", "kind": "endpoint", "confidence_score": 1, "overlap": False, "protected_words": []} candidates[len(audio)] = {"sample": len(audio), "db": -120, "penalty": 0, "warnings": [], "reason": "音频结束", "kind": "endpoint", "confidence_score": 1, "overlap": False, "protected_words": []} points = sorted(candidates) costs, prev = {0: 0}, {} levels = [c["db"] for c in candidates.values() if c["kind"] == "phrase_gap"] quiet, loud = np.percentile(levels if levels else db, [10, 90]) for j, end in enumerate(points[1:], 1): costs[end] = float("inf") for start in reversed(points[:j]): duration = (end-start) / sr if duration > maximum: break if duration < 3 and end != len(audio): continue c = candidates[end] level = 0 if end == len(audio) else float(np.clip((c["db"]-quiet)/max(loud-quiet, 1), 0, 1)) beat_cost = 0 if end != len(audio) and beat_points: beat_cost = min(abs(end/sr-b) for b in beat_points) / max(60/(rhythm["tempo_bpm"] or 120), .2) beat_cost = min(.5, beat_cost)*.35 score = costs.get(start, float("inf")) + .5 + ((duration-target)/4)**2 + c["penalty"] + 2*level + beat_cost if duration < 3: score += 5 if score < costs[end]: costs[end], prev[end] = score, start if len(audio) not in prev: raise ValueError("无法构造完整分段,请调整目标时长。") boundaries = [len(audio)] while boundaries[-1]: boundaries.append(prev[boundaries[-1]]) boundaries.reverse() selected = set(boundaries) rows = [] for start, end in zip(boundaries, boundaries[1:]): related = [line["text"] for line in lines if start/sr <= (line["start"]+line["end"])/2 < end/sr] mask = (starts >= start) & (starts < end) level = float(np.median(db[mask])) if mask.any() else -120 rows.append({"start_sample": start, "end_sample": end, "text": " / ".join(related), "energy_db": level, "reason": candidates[end]["reason"], "warnings": list(candidates[end]["warnings"]), "boundary_kind": candidates[end]["kind"], "boundary_confidence": round(float(candidates[end]["confidence_score"]), 3), "vocal_state": "含识别人声" if related else "人声状态不确定"}) if not return_analysis: return rows diagnostics = [] ranked = sorted(candidates.values(), key=lambda c: (c["sample"] not in selected, c["penalty"], c["sample"]))[:600] for c in sorted(ranked, key=lambda c: c["sample"]): diagnostics.append({"time": round(c["sample"]/sr, 3), "kind": c["kind"], "reason": c["reason"], "confidence": round(float(c["confidence_score"]), 3), "selected": c["sample"] in selected, "protected": c["overlap"], "warnings": c["warnings"]}) analysis = {"schema": 2, "duration": len(audio)/sr, "waveform": { "original": waveform_peaks(audio if mix_audio is None else mix_audio), "vocals": waveform_peaks(audio)}, "phrases": [{"start": round(float(s["start"]), 3), "end": round(float(s["end"]), 3), "text": s["text"]} for s in lines], "protected_words": [{"start": round(float(w["start"]), 3), "end": round(float(w["end"]), 3), "text": w["word"]} for w in words], "sections": sections, "rhythm": rhythm, "candidates": diagnostics, "thresholds_db": {"quiet": round(quiet_threshold, 2), "active": round(active_threshold, 2)}, "limitations": ["气口、拖音和无人声段均为声学估计,必须试听确认", "节拍仅用于安全候选间的次级择优"]} return rows, analysis def camera_plan(mode, index, count, energy, median, previous_camera="", previous_frame="medium close-up"): if mode == "speaking": return "medium close-up", "medium close-up", "a steady locked-off camera" framing = "medium close-up" if index == 0 else previous_frame if index == 0: return framing, "medium shot", ( "a restrained physical dolly out from chest-up to waist-up framing; " "the singer changes scale gently while reference-stage landmarks become more readable") if index == count-1: if framing == "medium shot": return framing, "medium close-up", ( "a restrained physical dolly in from waist-up to chest-up framing; " "the singer grows gently in frame with visible background parallax") return framing, framing, ( "a very slow lateral camera truck through a small arc; " "background landmarks shift subtly while the singer's scale remains constant") if energy > median and "dolly in" not in previous_camera and framing == "medium shot": return framing, "medium close-up", ( "a deliberate physical dolly in from waist-up to chest-up framing, " "with visible foreground/background parallax and the singer's face kept readable") direction, background = ("left", "right") if "dolly in" in previous_camera else ("right", "left") return framing, framing, ( f"a slow lateral camera truck to the {direction} through a small arc on the same side of the performer; " f"the background landmarks visibly slide {background} relative to the singer while {framing} framing is maintained") def director_preferences(plan): """Normalize local-rule controls while keeping legacy saved projects readable.""" supplied = plan.get("director") or {} performance = supplied.get("performance_intensity", "auto") camera = supplied.get("camera_activity", "auto") widest = supplied.get("widest_framing", "medium close-up") note = str(supplied.get("note", plan.get("visual_brief", "")) or "").strip() if performance not in {"auto", "restrained", "natural", "energetic"}: performance = "auto" if camera not in {"auto", "steady", "moderate", "dynamic"}: camera = "auto" if plan.get("mode") == "singing" and camera == "steady": camera = "moderate" if widest not in {"close-up", "medium close-up", "medium shot", "full shot"}: widest = "medium close-up" rules = (validate_config(supplied["rule_config"]) if isinstance(supplied.get("rule_config"), dict) else default_config()) return {"mode": "rule", "performance_intensity": performance, "camera_activity": camera, "widest_framing": widest, "note": note, "rule_config": rules, "schedule_seed": str(supplied.get("schedule_seed") or plan.get("id") or "h3lv"), "rule_revision": str(supplied.get("rule_revision") or "legacy")} REFERENCE_LAYOUT_ALIASES = { "single_composite": "single_composite", "单图:图1人物+场景": "single_composite", "单图:人物+场景": "single_composite", "solo_scene": "solo_scene", "单人+场景:图1人物,图2场景": "solo_scene", "双图:图1人物,图2场景": "solo_scene", } REFERENCE_ROLE_LABELS = { "performer": "主表演者", "performer_environment": "人物与环境同图", "performer_reference": "人物补充参考", "environment": "场景环境", "appearance": "服装或外形参考", "prop": "道具参考", "other": "其他可见参考", "ignore": "不参与提示词", } def dynamic_reference_manifest(definitions, picture_count=None): """Validate user-declared roles without inferring meaning from image count.""" if isinstance(definitions, str): try: definitions = json.loads(definitions or "[]") except json.JSONDecodeError as exc: raise ValueError("参考图职责设置无法读取,请重新打开“设置参考图职责”保存。") from exc if isinstance(definitions, dict): definitions = definitions.get("assets", []) if not isinstance(definitions, list): raise ValueError("参考图职责必须是按图片顺序保存的列表。") count = int(picture_count if picture_count is not None else len(definitions)) if not 1 <= count <= 9: raise ValueError("请连接 1至9 张参考图。") if len(definitions) != count: raise ValueError(f"已连接 {count} 张图,但参考图职责保存了 {len(definitions)} 项;请重新确认。") assets = [] for index, supplied in enumerate(definitions, 1): if not isinstance(supplied, dict): raise ValueError(f"图{index}的参考职责无效。") role = str(supplied.get("role") or "unspecified").strip() if role not in REFERENCE_ROLE_LABELS: raise ValueError(f"图{index}尚未指定参考职责,请打开“设置参考图职责”。") name = str(supplied.get("name") or REFERENCE_ROLE_LABELS[role]).strip()[:80] if role == "other" and not str(supplied.get("name") or "").strip(): raise ValueError(f"图{index}选择了“其他可见参考”,请填写它的名称。") asset = {"id": f"ref_{index:02d}", "picture": index, "role": role, "name": name} snapshot = str(supplied.get("snapshot") or "").strip() if snapshot: asset["snapshot"] = snapshot assets.append(asset) primary = [item for item in assets if item["role"] in {"performer", "performer_environment"}] if len(primary) != 1: raise ValueError("参考图职责中需要且只能指定1张“主表演者”或“人物与环境同图”。") performer_pictures = [item["picture"] for item in assets if item["role"] in {"performer", "performer_environment", "performer_reference", "appearance"}] # A combined performer/environment image still defines only Subject 1. # It must not recreate the old single-picture bug by inventing Subject 2. environment_pictures = [item["picture"] for item in assets if item["role"] == "environment"] subjects = [] subjects.append({"id": "performer_1", "subject": 1, "kind": "performer", "name": primary[0]["name"], "pictures": performer_pictures, "includes_environment": primary[0]["role"] == "performer_environment"}) next_subject = 2 if environment_pictures: subjects.append({"id": "environment", "subject": next_subject, "kind": "environment", "name": "环境", "pictures": environment_pictures}) next_subject += 1 for item in assets: if item["role"] in {"prop", "other"}: subjects.append({"id": item["id"], "subject": next_subject, "kind": item["role"], "name": item["name"], "pictures": [item["picture"]]}) next_subject += 1 environment = next((item for item in subjects if item["kind"] == "environment"), None) return {"schema": 3, "layout": "dynamic", "picture_count": count, "assets": assets, "subjects": subjects, "performers": [{"id": "performer_1", "subject": 1, "picture": primary[0]["picture"], "pictures": performer_pictures, "speaker": "S1"}], "environment": ({"id": "environment", "subject": environment["subject"], "picture": environment_pictures[0], "pictures": environment_pictures} if environment else None)} def reference_manifest(layout="solo_scene"): """Return one stable picture/Subject contract for the whole project.""" layout = REFERENCE_LAYOUT_ALIASES.get(str(layout), str(layout)) if layout not in {"single_composite", "solo_scene"}: raise ValueError("双人图片组合已停用;请选择单图或双图单人模式。") performers = [{"id": "performer_1", "subject": 1, "picture": 1, "speaker": "S1"}] environment_picture = 1 if layout == "single_composite" else 2 environment = {"id": "environment", "subject": 2, "picture": environment_picture} picture_count = 1 if layout == "single_composite" else 2 return {"schema": 2, "layout": layout, "picture_count": picture_count, "performers": performers, "environment": environment} def normalize_reference_manifest(plan): supplied = plan.get("references") if isinstance(supplied, dict) and supplied.get("schema") == 3: manifest = dynamic_reference_manifest(supplied.get("assets", []), supplied.get("picture_count")) elif isinstance(supplied, dict) and supplied.get("layout"): manifest = reference_manifest(supplied["layout"]) else: # Legacy projects used Picture 1 as performer and Picture 2 as environment. manifest = reference_manifest("solo_scene") plan["references"] = manifest return manifest def reference_brief_lines(manifest, mode="singing"): if manifest.get("schema") == 3: parts = [] for subject in manifest["subjects"]: pictures = "、".join(f"" for number in subject["pictures"]) if subject["kind"] == "performer": suffix = "及同图可见环境;环境不单独编号" if subject.get("includes_environment") else "" role = f"{pictures}=主表演者 {suffix}" elif subject["kind"] == "environment": role = f"{pictures}=场景环境 " else: role = f"{pictures}={subject['name']} " parts.append(role) vocal_action = "说话" if mode == "speaking" else "唱歌" return "参考:动态参考图;" + ";".join(parts) + \ f"。