651 lines
31 KiB
Python
651 lines
31 KiB
Python
"""导入分镜图片与脚本(业务流程第 2 步)。
|
||
|
||
支持 Markdown / CSV / TSV / JSON / 纯文本脚本,以及图片目录或 zip 包:
|
||
- 脚本行 → 分镜(镜号、标题、画面描述、景别、运镜、时长、台词、角色、场景、转场)
|
||
- 图片按镜号自动匹配为关键帧资产(如 01.png / S03.jpg / 镜头2.png)
|
||
- dry_run=True 时只返回预览,不落库(对应前端的「导入预览」)
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import csv
|
||
import io
|
||
import json
|
||
import re
|
||
import zipfile
|
||
from dataclasses import asdict, dataclass, field
|
||
from pathlib import Path
|
||
|
||
from sqlalchemy.orm import Session
|
||
|
||
from app.constants import (CAMERA_GROUPS, CameraAngle, CameraMovement, ShotSize,
|
||
Transition, normalize_camera_fields as _base_normalize_camera)
|
||
from app.models import Character, Project, Scene, Shot
|
||
from app.services import events, prompt as prompt_service, storage
|
||
|
||
LABEL_TO_KEY = {}
|
||
for mapping in (ShotSize.LABELS, CameraMovement.LABELS, CameraAngle.LABELS, Transition.LABELS):
|
||
for key, zh in mapping.items():
|
||
LABEL_TO_KEY[zh] = key
|
||
LABEL_TO_KEY.update({"特写": ShotSize.CLOSE_UP, "大特写": ShotSize.EXTREME_CLOSE_UP,
|
||
"中远景": ShotSize.WIDE, "平拍": CameraAngle.EYE_LEVEL, "俯角": CameraAngle.HIGH,
|
||
"仰角": CameraAngle.LOW, "航拍": CameraAngle.BIRD_EYE, "推": CameraMovement.PUSH_IN,
|
||
"俯视": CameraAngle.HIGH, "仰视": CameraAngle.LOW, "平视": CameraAngle.EYE_LEVEL,
|
||
"拉": CameraMovement.PULL_OUT, "摇": CameraMovement.PAN_RIGHT, "移": CameraMovement.TRACK,
|
||
"跟随": CameraMovement.TRACK, "甩": CameraMovement.PAN_RIGHT, "淡入": Transition.FADE_IN,
|
||
"淡出": Transition.FADE_OUT, "黑场": Transition.FADE_THROUGH_BLACK, "切": Transition.CUT})
|
||
|
||
COLUMN_ALIASES = {
|
||
"code": ("code", "镜号", "编号", "镜头号", "shot", "shot_id", "no", "id"),
|
||
"title": ("title", "标题", "镜头名", "场景标题"),
|
||
"synopsis": ("synopsis", "梗概", "剧情", "剧情梗概", "概要"),
|
||
"description": ("description", "画面", "画面描述", "镜头描述", "内容", "描述", "画面内容", "desc"),
|
||
"shot_size": ("shot_size", "景别", "镜头大小"),
|
||
"camera_angle": ("camera_angle", "机位", "视角", "拍摄角度", "角度"),
|
||
"camera_movement": ("camera_movement", "运镜", "镜头运动", "运动", "movement"),
|
||
"duration": ("duration", "时长", "秒", "seconds", "长度"),
|
||
"dialogue": ("dialogue", "台词", "对白", "旁白", "解说", "口播"),
|
||
"speaker": ("speaker", "说话人", "角色", "人物", "发言"),
|
||
"characters": ("characters", "出镜角色", "出场人物", "人物"),
|
||
"scene": ("scene", "场景", "地点", "环境"),
|
||
"transition": ("transition", "转场", "转场方式"),
|
||
"lens_note": ("lens_note", "镜头", "焦段", "镜头参数"),
|
||
"style_note": ("style_note", "风格", "色调", "备注", "note"),
|
||
"prompt": ("prompt", "提示词"),
|
||
"seed": ("seed", "随机种子"),
|
||
"mode": ("mode", "生成模式"),
|
||
}
|
||
|
||
IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tif", ".tiff"}
|
||
|
||
|
||
@dataclass
|
||
class ParsedShot:
|
||
code: str = ""
|
||
title: str = ""
|
||
synopsis: str = ""
|
||
description: str = ""
|
||
shot_size: str = ShotSize.MEDIUM
|
||
camera_angle: str = CameraAngle.EYE_LEVEL
|
||
camera_movement: str = CameraMovement.STATIC
|
||
duration: float = 5.0
|
||
dialogue: str = ""
|
||
speaker: str = ""
|
||
# 逐行台词(脚本里写成「俊杰:……\n紫小慧:……」时拆出来):[{name, text}]
|
||
lines: list = field(default_factory=list)
|
||
characters: list[str] = field(default_factory=list)
|
||
scene: str = ""
|
||
transition: str = Transition.CUT
|
||
lens_note: str = ""
|
||
style_note: str = ""
|
||
prompt: str = ""
|
||
seed: int | None = None
|
||
mode: str = "i2v"
|
||
order_index: int = 0
|
||
images: list[str] = field(default_factory=list)
|
||
|
||
def as_dict(self) -> dict:
|
||
return asdict(self)
|
||
|
||
|
||
def _match_key(group: str, raw: str) -> str | None:
|
||
raw = (raw or "").strip()
|
||
if not raw:
|
||
return None
|
||
if raw in LABEL_TO_KEY:
|
||
return LABEL_TO_KEY[raw]
|
||
for label, key in LABEL_TO_KEY.items():
|
||
if label and label in raw:
|
||
return key
|
||
return None
|
||
|
||
|
||
# 枚举白名单与「写错列」的纠正逻辑统一在 constants.normalize_camera_fields,
|
||
# 导入、接口、提示词三条路径必须用同一套口径,否则界面显示的和下发给模型的又不一致。
|
||
GROUP_VALUES = GROUP_DEFAULTS = None # 兼容旧引用:直接取 constants 里的表
|
||
from app.constants import GROUP_DEFAULTS as _GD, GROUP_VALUES as _GV # noqa: E402
|
||
|
||
GROUP_VALUES, GROUP_DEFAULTS = _GV, _GD
|
||
|
||
|
||
def _clean_key(group: str, raw: str, default: str = "") -> str:
|
||
"""把用户/大模型写的景别、机位、运镜、转场归一成英文枚举(只认同组取值)。
|
||
|
||
同义词表是跨组共用的,「过肩」写在景别列里也会折出机位枚举,
|
||
所以折算结果还要再校验一次归属,绝不把别的组的值留在这一列上。
|
||
"""
|
||
text = (raw or "").strip()
|
||
if text in GROUP_VALUES.get(group, []):
|
||
return text
|
||
key = _match_key(group, text)
|
||
if key and key in GROUP_VALUES.get(group, []):
|
||
return key
|
||
return default or GROUP_DEFAULTS.get(group, "")
|
||
|
||
|
||
def normalize_camera_fields(shot_size: str = "", camera_angle: str = "",
|
||
camera_movement: str = "") -> tuple[str, str, str]:
|
||
"""镜头语言三件套归一:同义词折算 → 搬回正确的列 → 落默认值。
|
||
|
||
顺序不能反:同义词表是跨组的,「景别=过肩」先折成机位枚举,再由
|
||
:func:`app.constants.normalize_camera_fields` 搬到机位列;
|
||
直接按列取默认值就会把编导原意丢掉(变成「中景」)。
|
||
"""
|
||
raws = (shot_size or "", camera_angle or "", camera_movement or "")
|
||
cands = []
|
||
for group, raw in zip(CAMERA_GROUPS, raws):
|
||
text = (raw or "").strip()
|
||
cands.append(text if text in GROUP_VALUES[group] else (_match_key(group, text) or text))
|
||
vals = _base_normalize_camera(*cands)
|
||
return tuple(v if v in GROUP_VALUES[g] else GROUP_DEFAULTS[g]
|
||
for g, v in zip(CAMERA_GROUPS, vals))
|
||
|
||
|
||
def _camera(group: str, row) -> str:
|
||
"""取一行里的镜头语言字段并归一(row 可以是原始 dict 或已解析的对象)。"""
|
||
def get(key: str) -> str:
|
||
if isinstance(row, dict):
|
||
return str(row.get(key) or _pick(row, key) or "")
|
||
return str(getattr(row, key, "") or "")
|
||
size, angle, move = normalize_camera_fields(get("shot_size"), get("camera_angle"),
|
||
get("camera_movement"))
|
||
return {"shot_size": size, "camera_angle": angle, "camera_movement": move}[group]
|
||
|
||
|
||
NARRATOR_LABELS = ("旁白", "画外音", "口播", "配音", "解说", "OS", "os", "vo", "VO")
|
||
|
||
_SPEAKER_PREFIX = re.compile(
|
||
r"^[【\[((「『“\"']?\s*(?P<name>[^\n::】\)))((]{1,16})"
|
||
r"\s*(?:[((][^))]{0,24}[))])?\s*[】\]))]?\s*[::]\s*(?P<text>.*)$")
|
||
|
||
|
||
def _strip_quotes(text: str) -> str:
|
||
text = str(text or "").strip()
|
||
for pairs in (("“", "”"), ("「", "」"), ("『", "』"), ('"', '"'), ("'", "'")):
|
||
if len(text) > 1 and text.startswith(pairs[0]) and text.endswith(pairs[1]):
|
||
text = text[1:-1].strip()
|
||
# 拆行后引号只剩一边(「「紫小慧:…」」的尾」会留在最后一句里),单边也要抹掉
|
||
return text.strip(" \t\r\n「」『』“”").strip()
|
||
|
||
|
||
def split_speaker_lines(text: str, names: list[str] | tuple[str, ...] | None = None) -> list[dict]:
|
||
"""把「俊杰:别慌……\n紫小慧:真的吗?」拆成逐行台词。
|
||
|
||
平台以前只有「一镜一个 dialogue + 一个说话人」,多人对白整段用一个嗓子念,
|
||
字幕也标不出是谁说的。这里在导入阶段就把说话人拆出来;
|
||
**每一行都必须带可识别的说话人前缀**,只要有一行认不出就整体不拆(返回空),
|
||
避免把「第一:先说结论」这种条目式文案误判成对白。
|
||
"""
|
||
raw = str(text or "").strip()
|
||
if not raw:
|
||
return []
|
||
known = {str(n).strip() for n in (names or []) if str(n).strip()}
|
||
if not known:
|
||
return []
|
||
pieces = [chunk.strip() for chunk in re.split(r"\n+", raw) if chunk.strip()]
|
||
if len(pieces) == 1:
|
||
# 没有换行:按「已知名字 + 冒号」再切一次(表格里常见「A:… B:…」挤在一格)
|
||
keys = sorted(known | set(NARRATOR_LABELS), key=len, reverse=True)
|
||
pattern = "|".join(re.escape(k) for k in keys)
|
||
# 切点前只剩下引号、破折号之类标点的碎片要丢掉,否则「「紫小慧:…」」会被误判成整段不可拆
|
||
pieces = [p.strip() for p in re.split(
|
||
rf"(?=(?:{pattern})\s*(?:[((][^))]{{0,24}}[))])?\s*[::])", pieces[0])
|
||
if re.search(r"[\u4e00-\u9fa5A-Za-z0-9]", p or "")]
|
||
out: list[dict] = []
|
||
for piece in pieces:
|
||
m = _SPEAKER_PREFIX.match(piece)
|
||
if not m:
|
||
return []
|
||
name = m.group("name").strip()
|
||
body = _strip_quotes(m.group("text"))
|
||
if not body:
|
||
continue
|
||
if name not in known and name not in NARRATOR_LABELS:
|
||
return [] # 前缀不是本项目的人物:多半是「注意:」「时间:」这类标签
|
||
out.append({"name": name, "text": body})
|
||
return out
|
||
|
||
|
||
def _coerce_lines(value) -> list[dict]:
|
||
"""JSON 脚本里的 ``lines`` 字段:[{"character": "俊杰", "text": "…"}] / ["俊杰:…"]。"""
|
||
if not isinstance(value, (list, tuple)):
|
||
return []
|
||
out: list[dict] = []
|
||
for row in value:
|
||
if isinstance(row, dict):
|
||
name = str(row.get("name") or row.get("character") or row.get("speaker") or "").strip()
|
||
text = _strip_quotes(row.get("text") or row.get("台词") or "")
|
||
else:
|
||
m = _SPEAKER_PREFIX.match(str(row or "").strip())
|
||
name, text = (m.group("name").strip(), _strip_quotes(m.group("text"))) if m else ("", "")
|
||
if text:
|
||
out.append({"name": name, "text": text})
|
||
return out
|
||
|
||
|
||
def _duration(raw) -> float:
|
||
if raw is None:
|
||
return 5.0
|
||
if isinstance(raw, (int, float)):
|
||
return float(raw)
|
||
m = re.search(r"\d+(?:\.\d+)?", str(raw))
|
||
return float(m.group()) if m else 5.0
|
||
|
||
|
||
def _pick(row: dict, group: str) -> str:
|
||
for alias in COLUMN_ALIASES[group]:
|
||
for key, value in row.items():
|
||
if str(key).strip().lower() == alias.lower() and str(value or "").strip():
|
||
return str(value).strip()
|
||
return ""
|
||
|
||
|
||
def _normalize_row(raw: dict) -> dict:
|
||
out = {}
|
||
for group in COLUMN_ALIASES:
|
||
out[group] = _pick(raw, group)
|
||
return out
|
||
|
||
|
||
# ---------------------------------------------------------------- 脚本解析
|
||
def parse_script(text: str, *, filename: str = "", default_duration: float = 5.0) -> list[ParsedShot]:
|
||
name = (filename or "").lower()
|
||
body = (text or "").lstrip()
|
||
if name.endswith(".json") or body[:1] in ("[", "{"):
|
||
# JSON 里也满是逗号,必须先于「像不像表格」的判断处理
|
||
return _parse_json(text, default_duration)
|
||
if name.endswith((".csv", ".tsv")) or _looks_tabular(text):
|
||
return _parse_delimited(text, delimiter="\t" if name.endswith(".tsv") else None,
|
||
default_duration=default_duration)
|
||
return _parse_markdown(text, default_duration)
|
||
|
||
|
||
def _looks_tabular(text: str) -> bool:
|
||
head = [l for l in text.splitlines() if l.strip()][:3]
|
||
return bool(head) and all(("," in l and l.count(",") >= 2) or ("\t" in l) for l in head)
|
||
|
||
|
||
def _parse_json(text: str, default_duration: float) -> list[ParsedShot]:
|
||
try:
|
||
data = json.loads(text)
|
||
except json.JSONDecodeError as exc:
|
||
raise ValueError(f"JSON 脚本解析失败:第 {exc.lineno} 行第 {exc.colno} 列 —— {exc.msg}") from exc
|
||
rows = data.get("shots") if isinstance(data, dict) else data
|
||
if not isinstance(rows, list):
|
||
raise ValueError("JSON 脚本必须是镜头数组,或包含 shots 字段的对象")
|
||
shots: list[ParsedShot] = []
|
||
for idx, raw in enumerate(rows, start=1):
|
||
if isinstance(raw, str):
|
||
shots.append(ParsedShot(description=raw, duration=default_duration, order_index=idx))
|
||
continue
|
||
row = _normalize_row({str(k): v for k, v in (raw or {}).items()})
|
||
chars = raw.get("characters") or raw.get("出镜角色") or row["speaker"]
|
||
if isinstance(chars, str):
|
||
chars = re.split(r"[、,,/;;\s]+", chars)
|
||
parsed = _shot_from_row(row, idx, [str(c) for c in (chars or []) if str(c).strip()],
|
||
default_duration)
|
||
parsed.lines = _coerce_lines(raw.get("lines") or raw.get("台词行") or raw.get("对白行"))
|
||
shots.append(parsed)
|
||
return shots
|
||
|
||
|
||
def _parse_delimited(text: str, *, delimiter: str | None, default_duration: float) -> list[ParsedShot]:
|
||
sample = text[:4096]
|
||
try:
|
||
dialect = csv.Sniffer().sniff(sample, delimiters=",\t;")
|
||
delim = delimiter or dialect.delimiter
|
||
except Exception:
|
||
delim = delimiter or (("\t" if sample.count("\t") > sample.count(",") else ","))
|
||
reader = csv.DictReader(io.StringIO(text), delimiter=delim)
|
||
rows = [r for r in reader if any(str(v or "").strip() for v in (r or {}).values())]
|
||
shots: list[ParsedShot] = []
|
||
for idx, raw in enumerate(rows, start=1):
|
||
row = _normalize_row({str(k): v for k, v in raw.items() if k is not None})
|
||
chars = re.split(r"[、,,/;;\s]+", row["characters"]) if row["characters"] else []
|
||
shots.append(_shot_from_row(row, idx, [c for c in chars if c], default_duration))
|
||
return shots
|
||
|
||
|
||
def _shot_from_row(row: dict, idx: int, chars: list[str], default_duration: float) -> ParsedShot:
|
||
return ParsedShot(
|
||
code=row["code"] or f"S{idx:02d}",
|
||
title=row["title"] or (row["description"][:18] if row["description"] else f"镜头 {idx}"),
|
||
synopsis=row["synopsis"], description=row["description"] or row["synopsis"],
|
||
shot_size=_camera("shot_size", row), camera_angle=_camera("camera_angle", row),
|
||
camera_movement=_camera("camera_movement", row),
|
||
duration=_duration(row["duration"]) or default_duration,
|
||
dialogue=row["dialogue"], speaker=row["speaker"], characters=chars, scene=row["scene"],
|
||
transition=_clean_key("transition", row["transition"], Transition.CUT),
|
||
lens_note=row["lens_note"], style_note=row["style_note"], prompt=row["prompt"],
|
||
mode=(row["mode"] if row["mode"] in ("t2v", "i2v", "fl") else "i2v"), order_index=idx)
|
||
|
||
|
||
MD_KEYS = {
|
||
"画面": "description", "画面描述": "description", "描述": "description", "内容": "description",
|
||
"镜头描述": "description", "梗概": "synopsis", "剧情": "synopsis",
|
||
"景别": "shot_size", "运镜": "camera_movement", "运动": "camera_movement",
|
||
"机位": "camera_angle", "视角": "camera_angle", "角度": "camera_angle",
|
||
"时长": "duration", "台词": "dialogue", "对白": "dialogue", "旁白": "dialogue",
|
||
"说话人": "speaker", "角色": "characters", "出镜角色": "characters", "人物": "characters",
|
||
"场景": "scene", "转场": "transition", "镜头": "lens_note", "焦段": "lens_note",
|
||
"风格": "style_note", "备注": "style_note", "提示词": "prompt", "标题": "title",
|
||
}
|
||
MD_HEADING = re.compile(r"^(#{1,6})\s*(.+?)\s*$")
|
||
# 「镜 1」「镜头03」「Shot 1」「S-1 开场」都能拆出镜号
|
||
HEADING_KEYWORD = re.compile(
|
||
r"^\s*(镜头号|镜头|分镜|镜号|镜|shot|scene|seq|场景|幕)\s*[::#\-_.]*\s*(.*)$", re.IGNORECASE)
|
||
HEADING_TOKEN = re.compile(r"^([0-9]+[0-9A-Za-z]*|[A-Za-z][0-9A-Za-z\-]*[0-9])[\s\.\-—、::_]*(.*)$")
|
||
MD_FIELD = re.compile(r"^\s*(?:[-*+]\s*)?[\u4e00-\u9fffA-Za-z_]{1,8}\s*[::]\s*(.*)$")
|
||
_TRAIL = " ::、.。—-_|·"
|
||
|
||
|
||
def _heading_identity(head: str) -> tuple[str, str]:
|
||
"""从 Markdown 标题中拆出(镜号, 标题)。镜号留空时由调用方按序号回填。"""
|
||
text = re.sub(r"^[【\[((]\s*", "", (head or "").strip())
|
||
matched = HEADING_KEYWORD.match(text)
|
||
rest = matched.group(2) if matched else text
|
||
rest = (rest or "").strip()
|
||
token = HEADING_TOKEN.match(rest) if rest else None
|
||
if token and token.group(1):
|
||
return token.group(1), (token.group(2) or "").strip(_TRAIL)
|
||
if rest:
|
||
return "", rest.strip(_TRAIL)
|
||
nums = re.findall(r"\d+", text)
|
||
return (nums[0] if nums else ""), ""
|
||
|
||
|
||
def _unique_codes(shots: list["ParsedShot"]) -> None:
|
||
"""镜号在项目内唯一(数据库有唯一约束),重复时追加序号,避免导入直接失败。"""
|
||
taken: set[str] = set()
|
||
for idx, item in enumerate(shots, start=1):
|
||
code = str(item.code or "").strip() or f"S{idx:02d}"
|
||
if code not in taken:
|
||
item.code = code
|
||
taken.add(code)
|
||
continue
|
||
serial = 2
|
||
while f"{code}-{serial}" in taken:
|
||
serial += 1
|
||
item.code = f"{code}-{serial}"
|
||
taken.add(item.code)
|
||
|
||
|
||
def _parse_markdown(text: str, default_duration: float) -> list[ParsedShot]:
|
||
lines = (text or "").splitlines()
|
||
heads = [(i, len(m.group(1)), m.group(2)) for i, line in enumerate(lines)
|
||
if (m := MD_HEADING.match(line.rstrip()))]
|
||
# 首个标题层级更浅(如 `# 分镜脚本`)且后面还有更深层标题 —— 它是文档标题,不是镜头
|
||
preamble = heads[0][0] if len(heads) >= 2 and heads[0][1] < heads[1][1] else None
|
||
|
||
shots: list[dict] = []
|
||
loose: list[ParsedShot] = []
|
||
current: dict | None = None
|
||
|
||
def flush() -> None:
|
||
nonlocal current
|
||
if current is not None:
|
||
shots.append(current)
|
||
current = None
|
||
|
||
in_preamble = False
|
||
for index, raw_line in enumerate(lines):
|
||
line = raw_line.rstrip()
|
||
if not line.strip():
|
||
continue
|
||
heading = MD_HEADING.match(line)
|
||
if heading:
|
||
if index == preamble:
|
||
in_preamble = True
|
||
continue
|
||
in_preamble = False
|
||
code, title = _heading_identity(heading.group(2))
|
||
if not code and not title:
|
||
continue
|
||
flush()
|
||
current = {"__code__": code, "__lines__": [], "__title__": title, "index": len(shots) + 1}
|
||
continue
|
||
if in_preamble:
|
||
continue
|
||
field = MD_FIELD.match(line)
|
||
if current is not None and field:
|
||
label = re.sub(r"^[-*+\s]+", "", line).split(":")[0].split(":")[0].strip()
|
||
key = MD_KEYS.get(label)
|
||
value = field.group(1).strip()
|
||
if key:
|
||
current.setdefault(key, value)
|
||
continue
|
||
if current is not None:
|
||
current["__lines__"].append(line.strip())
|
||
continue
|
||
body = re.sub(r"^\s*(?:[-*+]|\d+[.)、])\s*", "", line).strip()
|
||
if body:
|
||
loose.append(ParsedShot(description=body, title=body[:18], duration=default_duration,
|
||
code=f"S{len(loose) + 1:02d}", order_index=len(loose) + 1))
|
||
flush()
|
||
|
||
result: list[ParsedShot] = []
|
||
for item in shots:
|
||
desc = item.get("description") or " ".join(item.get("__lines__", []))
|
||
# 纯标题块(无画面、无字段)是文档标题或分节标题,不是镜头:
|
||
# 平台自己导出的 md 首行「# 项目名 · 分镜脚本(共 N 镜 …)」若不识别,
|
||
# 会让「导出 → 回灌」凭空多出一镜,破坏脚本与分镜的双向可逆。
|
||
if not desc.strip() and not any(item.get(k) for k in
|
||
("dialogue", "characters", "scene", "shot_size",
|
||
"duration", "prompt", "synopsis", "title")):
|
||
continue
|
||
idx = len(result) + 1
|
||
chars_raw = item.get("characters", "")
|
||
chars = [c for c in re.split(r"[、,,/;;\s]+", chars_raw) if c] if chars_raw else []
|
||
result.append(ParsedShot(
|
||
code=str(item.get("__code__") or "").strip(),
|
||
title=item.get("title") or desc[:18] or f"镜头 {idx}",
|
||
synopsis=item.get("synopsis", ""), description=desc,
|
||
shot_size=_camera("shot_size", item), camera_angle=_camera("camera_angle", item),
|
||
camera_movement=_camera("camera_movement", item),
|
||
duration=_duration(item.get("duration")) or default_duration,
|
||
dialogue=item.get("dialogue", ""), speaker=item.get("speaker", ""), characters=chars,
|
||
scene=item.get("scene", ""),
|
||
transition=_clean_key("transition", item.get("transition", ""), Transition.CUT),
|
||
lens_note=item.get("lens_note", ""), style_note=item.get("style_note", ""),
|
||
prompt=item.get("prompt", ""), order_index=idx))
|
||
_unique_codes(result)
|
||
return result or loose
|
||
|
||
|
||
# ---------------------------------------------------------------- 图片匹配
|
||
def _image_tokens(name: str) -> set[str]:
|
||
stem = Path(name).stem.lower()
|
||
tokens: set[str] = set()
|
||
for num in re.findall(r"\d{1,3}", stem):
|
||
tokens.add(str(int(num)))
|
||
tokens.add(f"{int(num):02d}")
|
||
tokens.add(f"s{int(num):02d}")
|
||
tokens.add(f"shot{int(num):02d}")
|
||
tokens.add(f"镜头{int(num)}")
|
||
tokens.add(stem)
|
||
return tokens
|
||
|
||
|
||
def match_images(shots: list[ParsedShot], images: list[str]) -> None:
|
||
"""把图片文件名与镜头编号/镜号匹配,作为关键帧资产。"""
|
||
used: set[str] = set()
|
||
for shot in shots:
|
||
keys = {str(shot.order_index), f"{shot.order_index:02d}", shot.code.lower(),
|
||
f"shot{shot.order_index:02d}", f"镜头{shot.order_index}"}
|
||
keys.discard("")
|
||
for image in images:
|
||
if image in used:
|
||
continue
|
||
tokens = _image_tokens(image)
|
||
if tokens & keys or Path(image).stem.lower() == shot.code.lower():
|
||
shot.images.append(image)
|
||
used.add(image)
|
||
|
||
|
||
def _match_character(name: str, characters: dict) -> object | None:
|
||
"""把脚本里的「说话人」对到项目人物卡上;对不上就返回 None,绝不硬塞给某个人。
|
||
|
||
脚本里常见「小燕子(拍桌)」「郭靖:」这类带修饰的写法,所以精确同名找不到时,
|
||
再退一步看这段话里是否恰好只包含一个角色名。多个角色名同时命中
|
||
(「郭靖和小燕子」)时宁可不绑:台词安错人头,配音就直接是另一个人的嗓子。
|
||
"""
|
||
text = str(name or "").strip()
|
||
if not text:
|
||
return None
|
||
for token in re.split(r"[、,,/;;\s]+", text):
|
||
if token in characters:
|
||
return characters[token]
|
||
hits = [row for label, row in characters.items() if label and label in text]
|
||
return hits[0] if len({id(row) for row in hits}) == 1 else None
|
||
|
||
|
||
# ---------------------------------------------------------------- 落库
|
||
def import_storyboard(db: Session, project: Project, *, script_text: str = "", script_name: str = "",
|
||
images: dict[str, bytes] | None = None, default_duration: float = 5.0,
|
||
replace: bool = False, dry_run: bool = False, keep_existing: bool = True,
|
||
actor: str = "studio") -> dict:
|
||
"""导入脚本与图片;dry_run 只返回预览。images 是 {文件名: 字节}。"""
|
||
images = images or {}
|
||
shots = parse_script(script_text, filename=script_name, default_duration=default_duration) if script_text else []
|
||
match_images(shots, list(images.keys()))
|
||
|
||
if not shots and images: # 只有图片素材:一图一镜
|
||
for idx, name in enumerate(sorted(images), start=1):
|
||
shots.append(ParsedShot(code=f"S{idx:02d}", title=Path(name).stem,
|
||
description=f"{Path(name).stem} 的镜头运动与氛围",
|
||
duration=default_duration, order_index=idx, images=[name]))
|
||
if not shots:
|
||
raise ValueError("脚本未解析出任何镜头,请检查格式(支持 Markdown / CSV / TSV / JSON / 纯文本,或直接上传图片)")
|
||
|
||
existing_codes = {s.code for s in project.shots or []} if keep_existing else set()
|
||
preview: list[dict] = []
|
||
created = 0
|
||
bound_characters = 0
|
||
bound_scenes = 0
|
||
speakers_bound = 0
|
||
lines_bound = 0
|
||
unmatched_images = [name for name in images
|
||
if not any(name in (s.images or []) for s in shots)]
|
||
|
||
if dry_run:
|
||
for item in shots:
|
||
row = item.as_dict()
|
||
row["will_create"] = bool(item.code not in existing_codes) or not keep_existing
|
||
row["skipped_reason"] = "镜号已存在,保留现有分镜" if not row["will_create"] else ""
|
||
preview.append(row)
|
||
return {"dry_run": True, "project_id": project.id, "parsed": len(shots),
|
||
"images": len(images), "unmatched_images": unmatched_images, "shots": preview,
|
||
"script_name": script_name}
|
||
|
||
if replace:
|
||
for shot in list(project.shots or []):
|
||
db.delete(shot)
|
||
db.flush()
|
||
existing_codes = set()
|
||
|
||
characters = {c.name: c for c in project.characters or []}
|
||
scenes = {s.name: s for s in project.scenes or []}
|
||
max_order = max([s.order_index for s in project.shots or []], default=0)
|
||
|
||
for offset, item in enumerate(shots, start=1):
|
||
if item.code in existing_codes and keep_existing:
|
||
preview.append({**item.as_dict(), "will_create": False, "skipped_reason": "镜号已存在"})
|
||
continue
|
||
order = max_order + offset
|
||
shot = Shot(project_id=project.id, order_index=order, code=item.code, title=item.title,
|
||
synopsis=item.synopsis, description=item.description or item.synopsis,
|
||
shot_size=item.shot_size, camera_angle=item.camera_angle,
|
||
camera_movement=item.camera_movement, duration=item.duration,
|
||
dialogue=item.dialogue, subtitle_text=item.dialogue, transition_out=item.transition,
|
||
lens_note=item.lens_note, style_note=item.style_note, mode=item.mode,
|
||
status="draft", stage="import_storyboard")
|
||
matched = [characters[n] for n in item.characters if n in characters]
|
||
speaker = _match_character(item.speaker, characters)
|
||
if speaker is not None:
|
||
speakers_bound += 1
|
||
cast = list(matched)
|
||
if speaker is not None and all(row.id != speaker.id for row in cast):
|
||
# 脚本只写了「说话人」、没把他列进出镜角色:也得挂上,否则这条台词永远配不到他的嗓子
|
||
cast.append(speaker)
|
||
if cast:
|
||
shot.characters = cast
|
||
bound_characters += len(matched)
|
||
# 说话人按脚本写的算,不按「出镜角色里的第一个」猜:
|
||
# 三人同框的戏猜第一个 = 把小燕子的台词配成郭靖的嗓子,观众一听就知道是另一个人。
|
||
if speaker is not None:
|
||
shot.speaker_character_id = speaker.id
|
||
elif str(item.speaker or "").strip():
|
||
shot.speaker_character_id = None # 脚本点名了一个项目里没有的人:留空让人去补,不猜
|
||
else:
|
||
shot.speaker_character_id = cast[0].id if cast else None
|
||
if item.scene and item.scene in scenes:
|
||
shot.scenes = [scenes[item.scene]]
|
||
bound_scenes += 1
|
||
# 逐行台词:脚本里显式写了 lines 就用它,否则从 dialogue 里认「名字:」前缀。
|
||
rows = list(item.lines or []) or split_speaker_lines(item.dialogue, tuple(characters))
|
||
if rows:
|
||
# 拆行后 dialogue 会变成「纯说话内容」(前缀被摘掉),字幕要跟着换口径,
|
||
# 否则屏幕上会出现「俊杰:别慌」这种自带说话人的字幕。
|
||
prefixed = str(item.dialogue or "").strip()
|
||
if str(shot.subtitle_text or "").strip() == prefixed:
|
||
shot.subtitle_text = ""
|
||
shot.set_lines([{"character_id": (characters[row["name"]].id if row.get("name") in characters
|
||
else None),
|
||
"name": row.get("name") or "", "text": row.get("text") or ""}
|
||
for row in rows])
|
||
for row in rows: # 对白里提到的人都要挂到镜头上
|
||
char = characters.get(row.get("name") or "")
|
||
if char is not None and all(x.id != char.id for x in (shot.characters or [])):
|
||
shot.characters = list(shot.characters or []) + [char]
|
||
if speaker is not None and shot.speaker_character_id in (None, 0):
|
||
shot.speaker_character_id = speaker.id
|
||
lines_bound += 1
|
||
db.add(shot)
|
||
db.flush()
|
||
prompt_service.sync_prompt(db, project, shot, reason="导入脚本后自动组装提示词", actor=actor, record=False)
|
||
for image in item.images:
|
||
payload = images.get(image)
|
||
if not payload:
|
||
continue
|
||
info = storage.save_bytes(payload, project_id=project.id, kind="keyframe",
|
||
stem=f"shot-{order:02d}-{Path(image).stem}")
|
||
storage.register_asset(db, project_id=project.id, owner_type="shot", owner_id=shot.id,
|
||
kind="keyframe", path=info["path"], name=Path(image).name,
|
||
info=info, source="upload",
|
||
metadata={"imported_from": script_name or "images"})
|
||
preview.append({**item.as_dict(), "shot_id": shot.id, "will_create": True, "skipped_reason": ""})
|
||
created += 1
|
||
|
||
from app.services import status as status_service
|
||
|
||
db.flush()
|
||
db.expire(project, ["shots"]) # 新建的分镜要立刻反映到摘要/前置检查里
|
||
status_service.refresh(db, project, commit=False)
|
||
events.log_event(db, "storyboard.imported", project_id=project.id, actor=actor,
|
||
message=f"导入脚本「{script_name or '脚本'}」:新增 {created} 个分镜,"
|
||
f"匹配关键帧 {len(images) - len(unmatched_images)}/{len(images)} 张",
|
||
data={"created": created, "images": len(images), "unmatched": unmatched_images})
|
||
db.commit()
|
||
return {"dry_run": False, "project_id": project.id, "parsed": len(shots), "created": created,
|
||
"bound_characters": bound_characters, "bound_scenes": bound_scenes,
|
||
"speakers_bound": speakers_bound, "lines_bound": lines_bound,
|
||
"images": len(images), "unmatched_images": unmatched_images, "shots": preview,
|
||
"script_name": script_name}
|
||
|
||
|
||
def read_archive(payload: bytes, *, images: dict[str, bytes], scripts: dict[str, bytes]) -> None:
|
||
"""解压 zip:图片进 images,脚本文本进 scripts。"""
|
||
with zipfile.ZipFile(io.BytesIO(payload)) as zf:
|
||
for member in zf.infolist():
|
||
if member.is_dir():
|
||
continue
|
||
name = member.filename
|
||
base = Path(name).name
|
||
if not base or base.startswith("."):
|
||
continue
|
||
data = zf.read(member)
|
||
suffix = Path(base).suffix.lower()
|
||
if suffix in IMAGE_SUFFIXES:
|
||
images[base] = data
|
||
elif suffix in (".md", ".txt", ".csv", ".tsv", ".json"):
|
||
scripts[base] = data
|