Flatten skill category directory structure
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""下载 mv-creator 内置风格预设图到本地缓存。
|
||||
|
||||
用法:
|
||||
python3 download_style_presets.py <cache_dir>
|
||||
python3 download_style_presets.py <cache_dir> --style cinematic
|
||||
|
||||
也可作为模块导入,调用 ensure_style_presets(cache_dir) 获取本地路径。
|
||||
|
||||
CDN 源仅在本脚本内部使用,不对外暴露。下载到本地后,所有调用方
|
||||
(render_preview.py / 生图工具的 image_paths)都使用本地路径。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
# Internal CDN source — do not reference these URLs from markdown or other code.
|
||||
_CDN_BASE = "https://cdn.hailuoai.com/hailuo-video-web/public_assets"
|
||||
_PRESETS = {
|
||||
"cinematic": ["01_highway.png", "02_bar.png", "03_canyon.png", "04_starry.png"],
|
||||
"oil-painting": ["01_highway.png", "02_bar.png", "03_prairie.png", "04_campfire.png"],
|
||||
"noir-illustration": ["01_highway.png", "02_bar.png", "03_stage.png"],
|
||||
}
|
||||
|
||||
PRESET_STYLES: tuple[str, ...] = tuple(_PRESETS.keys())
|
||||
|
||||
|
||||
def _fetch_one(style_id: str, filename: str, cache_dir: Path) -> Path | None:
|
||||
"""Download a single preset image; skip if already cached.
|
||||
|
||||
Returns the local path on success (cached or freshly downloaded), or None
|
||||
if the download failed.
|
||||
"""
|
||||
out_dir = cache_dir / style_id
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
local = out_dir / filename
|
||||
if local.exists():
|
||||
return local
|
||||
url = f"{_CDN_BASE}/{style_id}/{filename}"
|
||||
try:
|
||||
urllib.request.urlretrieve(url, local)
|
||||
except Exception as exc: # noqa: BLE001 — log and continue
|
||||
print(f"WARN: failed to download {url}: {exc}", file=sys.stderr)
|
||||
return None
|
||||
return local
|
||||
|
||||
|
||||
def ensure_style_presets(
|
||||
cache_dir: Path,
|
||||
styles: tuple[str, ...] | None = None,
|
||||
) -> dict[str, list[Path]]:
|
||||
"""Ensure preset images exist under cache_dir; download missing ones.
|
||||
|
||||
Args:
|
||||
cache_dir: Directory to cache preset images. Created if absent.
|
||||
styles: Optional subset of style ids to ensure. Defaults to all known.
|
||||
|
||||
Returns:
|
||||
{style_id: [local_path, ...]} — only includes styles with at least one
|
||||
successfully cached image.
|
||||
"""
|
||||
targets = styles or PRESET_STYLES
|
||||
result: dict[str, list[Path]] = {}
|
||||
for style_id in targets:
|
||||
filenames = _PRESETS.get(style_id)
|
||||
if not filenames:
|
||||
print(f"WARN: unknown style id: {style_id}", file=sys.stderr)
|
||||
continue
|
||||
paths: list[Path] = []
|
||||
for fn in filenames:
|
||||
local = _fetch_one(style_id, fn, cache_dir)
|
||||
if local is not None:
|
||||
paths.append(local)
|
||||
if paths:
|
||||
result[style_id] = paths
|
||||
return result
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Download mv-creator built-in style presets")
|
||||
parser.add_argument("cache_dir", type=Path, help="Local cache directory")
|
||||
parser.add_argument(
|
||||
"--style",
|
||||
action="append",
|
||||
choices=PRESET_STYLES,
|
||||
help="Only download specific style(s); may be passed multiple times",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
cache_dir: Path = args.cache_dir.resolve()
|
||||
selected = tuple(args.style) if args.style else None
|
||||
result = ensure_style_presets(cache_dir, styles=selected)
|
||||
|
||||
if not result:
|
||||
print("ERROR: no presets cached", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
for style_id, paths in result.items():
|
||||
print(f"{style_id}: {len(paths)} files")
|
||||
for p in paths:
|
||||
print(f" {p}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env python3
|
||||
"""校验背景图设计 design.md 格式是否符合规范。
|
||||
|
||||
用法:
|
||||
# 校验单个背景
|
||||
python validate_background_design.py .mv/{song}/{theme}/backgrounds/{bg}/design.md
|
||||
|
||||
# 校验 backgrounds 目录下所有背景
|
||||
python validate_background_design.py .mv/{song}/{theme}/backgrounds/
|
||||
|
||||
规则:
|
||||
- 必须有一级标题 # 背景名
|
||||
- 必须包含 5 个二级标题分区:场景描述、出场幕列表、生图设定、候选图、选定图
|
||||
- 场景描述必须包含至少 3 项关键词(环境类型、地形/空间、色调/氛围、关键元素、天气/时段)
|
||||
- 生图设定必须包含:提示词、模型、参考图
|
||||
- 候选图必须有至少 1 条列表项
|
||||
- 候选图路径对应的文件必须存在
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REQUIRED_SECTIONS = ["场景描述", "出场幕列表", "生图设定", "候选图", "选定图"]
|
||||
PROMPT_FIELDS = ["提示词:", "模型:", "参考图:"]
|
||||
|
||||
# 中英 section / field 映射
|
||||
SECTION_ALIASES = {
|
||||
"场景描述": "Scene Description",
|
||||
"出场幕列表": "Scene List",
|
||||
"生图设定": "Image Settings",
|
||||
"候选图": "Candidates",
|
||||
"选定图": "Selected",
|
||||
}
|
||||
PROMPT_FIELD_ALIASES = {
|
||||
"提示词:": ("Prompt:", "Prompt:"),
|
||||
"模型:": ("Model:", "Model:"),
|
||||
"参考图:": ("Reference:", "Reference:"),
|
||||
}
|
||||
IMG_EXTS = {".png", ".jpg", ".jpeg", ".webp"}
|
||||
|
||||
H1_RE = re.compile(r"^#\s+(.+)$")
|
||||
H2_RE = re.compile(r"^##\s+(.+)$")
|
||||
LIST_RE = re.compile(r"^-\s+(.+)$")
|
||||
CANDIDATE_RE = re.compile(r"^-\s+(candidate_\S+)")
|
||||
|
||||
|
||||
def parse_design(text: str) -> dict:
|
||||
"""解析 design.md,返回结构化数据。"""
|
||||
lines = text.split("\n")
|
||||
result = {"title": None, "sections": {}}
|
||||
current_section = None
|
||||
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
|
||||
h1 = H1_RE.match(stripped)
|
||||
if h1:
|
||||
result["title"] = h1.group(1)
|
||||
continue
|
||||
|
||||
h2 = H2_RE.match(stripped)
|
||||
if h2:
|
||||
current_section = h2.group(1)
|
||||
result["sections"][current_section] = []
|
||||
continue
|
||||
|
||||
if current_section is not None:
|
||||
result["sections"][current_section].append(stripped)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_section(sections: dict, zh_name: str) -> list:
|
||||
"""从 sections 字典中获取内容,兼容中英 section header。"""
|
||||
en_name = SECTION_ALIASES.get(zh_name, "")
|
||||
return sections.get(zh_name, sections.get(en_name, []))
|
||||
|
||||
|
||||
def has_section(sections: dict, zh_name: str) -> bool:
|
||||
"""检查 section 是否存在,兼容中英。"""
|
||||
en_name = SECTION_ALIASES.get(zh_name, "")
|
||||
return zh_name in sections or en_name in sections
|
||||
|
||||
|
||||
def has_prompt_field(content: str, zh_field: str) -> bool:
|
||||
"""检查生图设定字段是否存在,兼容中英。"""
|
||||
if zh_field in content:
|
||||
return True
|
||||
for alias in PROMPT_FIELD_ALIASES.get(zh_field, ()):
|
||||
if alias in content:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def validate_one(design_path: Path) -> list[str]:
|
||||
"""校验单个 design.md,返回问题列表。"""
|
||||
issues = []
|
||||
bg_dir = design_path.parent
|
||||
bg_name = bg_dir.name
|
||||
|
||||
text = design_path.read_text(encoding="utf-8")
|
||||
data = parse_design(text)
|
||||
|
||||
# 背景名
|
||||
if not data["title"]:
|
||||
issues.append(f"ERROR [{bg_name}] 缺少一级标题 # 背景名")
|
||||
|
||||
# 必需分区
|
||||
for section in REQUIRED_SECTIONS:
|
||||
if not has_section(data["sections"], section):
|
||||
en = SECTION_ALIASES.get(section, "")
|
||||
issues.append(f"ERROR [{bg_name}] 缺少分区 ## {section}/{en}")
|
||||
|
||||
# 场景描述:需要包含至少 3 项列表项
|
||||
scene_desc = get_section(data["sections"], "场景描述")
|
||||
if scene_desc:
|
||||
items = [l for l in scene_desc if LIST_RE.match(l)]
|
||||
if len(items) < 3:
|
||||
issues.append(
|
||||
f"WARN [{bg_name}] 场景描述/Scene Description 列表项不足(需至少 3 项,当前 {len(items)} 项)"
|
||||
)
|
||||
|
||||
# 出场幕列表:需要有内容
|
||||
scene_list = get_section(data["sections"], "出场幕列表")
|
||||
if scene_list:
|
||||
content = "\n".join(scene_list).strip()
|
||||
if not content:
|
||||
issues.append(f"WARN [{bg_name}] 出场幕列表/Scene List 内容为空")
|
||||
|
||||
# 生图设定:需要提示词、模型、参考图
|
||||
img_settings = get_section(data["sections"], "生图设定")
|
||||
if img_settings:
|
||||
content = "\n".join(img_settings)
|
||||
for field in PROMPT_FIELDS:
|
||||
if not has_prompt_field(content, field):
|
||||
issues.append(f"ERROR [{bg_name}] 生图设定/Image Settings 缺少字段 {field}")
|
||||
|
||||
# 候选图:需要至少 1 条,且文件存在
|
||||
candidates_lines = get_section(data["sections"], "候选图")
|
||||
if candidates_lines:
|
||||
candidates = []
|
||||
for line in candidates_lines:
|
||||
m = CANDIDATE_RE.match(line)
|
||||
if m:
|
||||
candidates.append(m.group(1))
|
||||
if not candidates:
|
||||
issues.append(f"ERROR [{bg_name}] 候选图/Candidates 为空(需要至少 1 张)")
|
||||
for fname in candidates:
|
||||
actual_name = fname.split()[0] if " " in fname else fname
|
||||
fpath = bg_dir / actual_name
|
||||
if not fpath.exists():
|
||||
issues.append(f"WARN [{bg_name}] 候选图文件不存在: {actual_name}")
|
||||
|
||||
# 选定图:检查是否已选定
|
||||
selected_lines = get_section(data["sections"], "选定图")
|
||||
if selected_lines:
|
||||
content = "\n".join(selected_lines).strip()
|
||||
if not content:
|
||||
issues.append(f"INFO [{bg_name}] 选定图/Selected 尚未填写(待用户挑选)")
|
||||
elif "selected" in content:
|
||||
sel_path = bg_dir / "selected.jpg"
|
||||
sel_png = bg_dir / "selected.png"
|
||||
if not sel_path.exists() and not sel_png.exists():
|
||||
issues.append(f"WARN [{bg_name}] selected.jpg/png 文件不存在")
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def find_designs(path: Path) -> list[Path]:
|
||||
"""查找所有 design.md 文件。"""
|
||||
if path.is_file() and path.name == "design.md":
|
||||
return [path]
|
||||
if path.is_dir():
|
||||
designs = []
|
||||
for d in sorted(path.iterdir()):
|
||||
if d.is_dir():
|
||||
dm = d / "design.md"
|
||||
if dm.exists():
|
||||
designs.append(dm)
|
||||
return designs
|
||||
return []
|
||||
|
||||
|
||||
def print_summary(all_issues: dict[str, list[str]]) -> None:
|
||||
print("=== 背景图设计校验报告 ===\n")
|
||||
print(f"背景数量: {len(all_issues)}")
|
||||
print()
|
||||
|
||||
total_errors = 0
|
||||
total_warns = 0
|
||||
|
||||
for bg_name, issues in all_issues.items():
|
||||
errors = [i for i in issues if "ERROR" in i]
|
||||
warns = [i for i in issues if "WARN" in i]
|
||||
total_errors += len(errors)
|
||||
total_warns += len(warns)
|
||||
|
||||
status = "PASS" if not errors else "FAIL"
|
||||
print(f" [{status}] {bg_name} — {len(errors)} 错误, {len(warns)} 警告")
|
||||
|
||||
print()
|
||||
if total_errors == 0 and total_warns == 0:
|
||||
no_info = all(not any("INFO" in i for i in iss) for iss in all_issues.values())
|
||||
if no_info:
|
||||
print("ALL PASS")
|
||||
else:
|
||||
print("ALL PASS (部分背景待用户选图)")
|
||||
else:
|
||||
all_issues_flat = [i for iss in all_issues.values() for i in iss]
|
||||
print(f"发现 {len(all_issues_flat)} 个问题:\n")
|
||||
for issue in all_issues_flat:
|
||||
print(f" {issue}")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("用法:")
|
||||
print(" python validate_background_design.py <design.md 路径>")
|
||||
print(" python validate_background_design.py <backgrounds 目录路径>")
|
||||
sys.exit(1)
|
||||
|
||||
target = Path(sys.argv[1]).resolve()
|
||||
if not target.exists():
|
||||
print(f"ERROR: 路径不存在: {target}")
|
||||
sys.exit(1)
|
||||
|
||||
designs = find_designs(target)
|
||||
if not designs:
|
||||
print(f"ERROR: 未找到 design.md 文件: {target}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"\n--- 背景图设计校验 ---\n")
|
||||
|
||||
all_issues = {}
|
||||
for dp in designs:
|
||||
bg_name = dp.parent.name
|
||||
issues = validate_one(dp)
|
||||
all_issues[bg_name] = issues
|
||||
|
||||
print_summary(all_issues)
|
||||
|
||||
has_error = any("ERROR" in i for iss in all_issues.values() for i in iss)
|
||||
sys.exit(1 if has_error else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env python3
|
||||
"""校验角色设计 design.md 格式是否符合规范。
|
||||
|
||||
用法:
|
||||
# 校验单个角色
|
||||
python validate_character_design.py .mv/{song}/{theme}/{character}/design.md
|
||||
|
||||
# 校验 theme 下所有角色
|
||||
python validate_character_design.py .mv/{song}/{theme}/
|
||||
|
||||
规则:
|
||||
- 必须有一级标题 # 角色名
|
||||
- 必须包含 6 个二级标题分区:外貌特征、性格气质、标志物件、生图设定、候选图、选定图
|
||||
- 外貌特征必须包含列表项
|
||||
- 生图设定必须包含:提示词、模型、参考图
|
||||
- 候选图必须有至少 1 条列表项
|
||||
- 候选图路径对应的文件必须存在
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REQUIRED_SECTIONS = ["外貌特征", "性格气质", "标志物件", "生图设定", "候选图", "选定图"]
|
||||
PROMPT_FIELDS = ["提示词:", "模型:", "参考图:"]
|
||||
|
||||
# 中英 section / field 映射,校验时兼容双语
|
||||
SECTION_ALIASES = {
|
||||
"外貌特征": "Appearance",
|
||||
"性格气质": "Personality",
|
||||
"标志物件": "Signature Items",
|
||||
"生图设定": "Image Settings",
|
||||
"候选图": "Candidates",
|
||||
"选定图": "Selected",
|
||||
}
|
||||
PROMPT_FIELD_ALIASES = {
|
||||
"提示词:": ("Prompt:", "Prompt:"),
|
||||
"模型:": ("Model:", "Model:"),
|
||||
"参考图:": ("Reference:", "Reference:"),
|
||||
}
|
||||
IMG_EXTS = {".png", ".jpg", ".jpeg", ".webp"}
|
||||
|
||||
H1_RE = re.compile(r"^#\s+(.+)$")
|
||||
H2_RE = re.compile(r"^##\s+(.+)$")
|
||||
LIST_RE = re.compile(r"^-\s+(.+)$")
|
||||
CANDIDATE_RE = re.compile(r"^-\s+(candidate_\S+)")
|
||||
|
||||
|
||||
def parse_design(text: str) -> dict:
|
||||
"""解析 design.md,返回结构化数据。"""
|
||||
lines = text.split("\n")
|
||||
result = {"title": None, "sections": {}}
|
||||
current_section = None
|
||||
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
|
||||
h1 = H1_RE.match(stripped)
|
||||
if h1:
|
||||
result["title"] = h1.group(1)
|
||||
continue
|
||||
|
||||
h2 = H2_RE.match(stripped)
|
||||
if h2:
|
||||
current_section = h2.group(1)
|
||||
result["sections"][current_section] = []
|
||||
continue
|
||||
|
||||
if current_section is not None:
|
||||
result["sections"][current_section].append(stripped)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_section(sections: dict, zh_name: str) -> list:
|
||||
"""从 sections 字典中获取内容,兼容中英 section header。"""
|
||||
en_name = SECTION_ALIASES.get(zh_name, "")
|
||||
return sections.get(zh_name, sections.get(en_name, []))
|
||||
|
||||
|
||||
def has_section(sections: dict, zh_name: str) -> bool:
|
||||
"""检查 section 是否存在,兼容中英。"""
|
||||
en_name = SECTION_ALIASES.get(zh_name, "")
|
||||
return zh_name in sections or en_name in sections
|
||||
|
||||
|
||||
def has_prompt_field(content: str, zh_field: str) -> bool:
|
||||
"""检查生图设定字段是否存在,兼容中英。"""
|
||||
if zh_field in content:
|
||||
return True
|
||||
for alias in PROMPT_FIELD_ALIASES.get(zh_field, ()):
|
||||
if alias in content:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def validate_one(design_path: Path) -> list[str]:
|
||||
"""校验单个 design.md,返回问题列表。"""
|
||||
issues = []
|
||||
char_dir = design_path.parent
|
||||
char_name = char_dir.name
|
||||
|
||||
text = design_path.read_text(encoding="utf-8")
|
||||
data = parse_design(text)
|
||||
|
||||
# 角色名
|
||||
if not data["title"]:
|
||||
issues.append(f"ERROR [{char_name}] 缺少一级标题 # 角色名")
|
||||
|
||||
# 必需分区
|
||||
for section in REQUIRED_SECTIONS:
|
||||
if not has_section(data["sections"], section):
|
||||
en = SECTION_ALIASES.get(section, "")
|
||||
issues.append(f"ERROR [{char_name}] 缺少分区 ## {section}/{en}")
|
||||
|
||||
# 外貌特征:需要列表项
|
||||
appearance = get_section(data["sections"], "外貌特征")
|
||||
if appearance:
|
||||
items = [l for l in appearance if LIST_RE.match(l)]
|
||||
if len(items) < 2:
|
||||
issues.append(f"WARN [{char_name}] 外貌特征/Appearance 列表项过少(至少 2 项)")
|
||||
|
||||
# 标志物件:需要列表项
|
||||
sig_items = get_section(data["sections"], "标志物件")
|
||||
if sig_items:
|
||||
items = [l for l in sig_items if LIST_RE.match(l)]
|
||||
if not items:
|
||||
issues.append(f"WARN [{char_name}] 标志物件/Signature Items 缺少列表项")
|
||||
|
||||
# 生图设定:需要提示词、模型、参考图
|
||||
img_settings = get_section(data["sections"], "生图设定")
|
||||
if img_settings:
|
||||
content = "\n".join(img_settings)
|
||||
for field in PROMPT_FIELDS:
|
||||
if not has_prompt_field(content, field):
|
||||
issues.append(f"ERROR [{char_name}] 生图设定/Image Settings 缺少字段 {field}")
|
||||
|
||||
# 候选图:需要至少 1 条,且文件存在
|
||||
candidates_lines = get_section(data["sections"], "候选图")
|
||||
if candidates_lines:
|
||||
candidates = []
|
||||
for line in candidates_lines:
|
||||
m = CANDIDATE_RE.match(line)
|
||||
if m:
|
||||
candidates.append(m.group(1))
|
||||
if not candidates:
|
||||
issues.append(f"ERROR [{char_name}] 候选图/Candidates 为空(需要至少 1 张)")
|
||||
for fname in candidates:
|
||||
actual_name = fname.split()[0] if " " in fname else fname
|
||||
fpath = char_dir / actual_name
|
||||
if not fpath.exists():
|
||||
issues.append(f"WARN [{char_name}] 候选图文件不存在: {actual_name}")
|
||||
|
||||
# 选定图:检查是否已选定
|
||||
selected_lines = get_section(data["sections"], "选定图")
|
||||
if selected_lines:
|
||||
content = "\n".join(selected_lines).strip()
|
||||
if not content:
|
||||
issues.append(f"INFO [{char_name}] 选定图/Selected 尚未填写(待用户挑选)")
|
||||
elif "selected" in content:
|
||||
sel_path = char_dir / "selected.jpg"
|
||||
sel_png = char_dir / "selected.png"
|
||||
if not sel_path.exists() and not sel_png.exists():
|
||||
issues.append(f"WARN [{char_name}] selected.jpg/png 文件不存在")
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def find_designs(path: Path) -> list[Path]:
|
||||
"""查找所有 design.md 文件。"""
|
||||
if path.is_file() and path.name == "design.md":
|
||||
return [path]
|
||||
if path.is_dir():
|
||||
designs = []
|
||||
for d in sorted(path.iterdir()):
|
||||
if d.is_dir():
|
||||
dm = d / "design.md"
|
||||
if dm.exists():
|
||||
designs.append(dm)
|
||||
return designs
|
||||
return []
|
||||
|
||||
|
||||
def print_summary(all_issues: dict[str, list[str]]) -> None:
|
||||
print("=== 角色设计校验报告 ===\n")
|
||||
print(f"角色数量: {len(all_issues)}")
|
||||
print()
|
||||
|
||||
total_errors = 0
|
||||
total_warns = 0
|
||||
|
||||
for char_name, issues in all_issues.items():
|
||||
errors = [i for i in issues if "ERROR" in i]
|
||||
warns = [i for i in issues if "WARN" in i]
|
||||
infos = [i for i in issues if "INFO" in i]
|
||||
total_errors += len(errors)
|
||||
total_warns += len(warns)
|
||||
|
||||
status = "PASS" if not errors else "FAIL"
|
||||
print(f" [{status}] {char_name} — {len(errors)} 错误, {len(warns)} 警告")
|
||||
|
||||
print()
|
||||
if total_errors == 0 and total_warns == 0:
|
||||
no_info = all(not any("INFO" in i for i in iss) for iss in all_issues.values())
|
||||
if no_info:
|
||||
print("ALL PASS")
|
||||
else:
|
||||
print("ALL PASS (部分角色待用户选图)")
|
||||
else:
|
||||
all_issues_flat = [i for iss in all_issues.values() for i in iss]
|
||||
print(f"发现 {len(all_issues_flat)} 个问题:\n")
|
||||
for issue in all_issues_flat:
|
||||
print(f" {issue}")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("用法:")
|
||||
print(" python validate_character_design.py <design.md 路径>")
|
||||
print(" python validate_character_design.py <theme 目录路径>")
|
||||
sys.exit(1)
|
||||
|
||||
target = Path(sys.argv[1]).resolve()
|
||||
if not target.exists():
|
||||
print(f"ERROR: 路径不存在: {target}")
|
||||
sys.exit(1)
|
||||
|
||||
designs = find_designs(target)
|
||||
if not designs:
|
||||
print(f"ERROR: 未找到 design.md 文件: {target}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"\n--- 角色设计校验 ---\n")
|
||||
|
||||
all_issues = {}
|
||||
for dp in designs:
|
||||
char_name = dp.parent.name
|
||||
issues = validate_one(dp)
|
||||
all_issues[char_name] = issues
|
||||
|
||||
print_summary(all_issues)
|
||||
|
||||
has_error = any("ERROR" in i for iss in all_issues.values() for i in iss)
|
||||
sys.exit(1 if has_error else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""校验 lyric.md 歌词格式是否符合要求。
|
||||
|
||||
规则:
|
||||
- 时间码格式正确:M:SS 或 MM:SS
|
||||
- 时间段必须连续,不能有间隙或重叠
|
||||
- 时长不能为负或零
|
||||
- 纯音乐段不应包含歌词
|
||||
- 歌词段至少包含 1 行歌词
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
TIME_RE = re.compile(r"^(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})$")
|
||||
TAG_RE = re.compile(r"^\[(prelude|interlude|outro)\]$")
|
||||
|
||||
|
||||
def parse_time(minutes: str, seconds: str) -> float:
|
||||
return int(minutes) * 60 + int(seconds)
|
||||
|
||||
|
||||
def parse_lyric_file(path: str) -> list[dict]:
|
||||
"""解析 lyric.md,返回段落列表。"""
|
||||
text = Path(path).read_text(encoding="utf-8")
|
||||
|
||||
# 提取 ``` 代码块内容
|
||||
m = re.search(r"```\n(.*?)```", text, re.DOTALL)
|
||||
if not m:
|
||||
print("ERROR: 未找到 ``` 代码块")
|
||||
sys.exit(1)
|
||||
|
||||
content = m.group(1).strip()
|
||||
segments: list[dict] = []
|
||||
current_tag: str | None = None
|
||||
|
||||
for line in content.split("\n"):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
tag_match = TAG_RE.match(line)
|
||||
if tag_match:
|
||||
current_tag = tag_match.group(1)
|
||||
continue
|
||||
|
||||
time_match = TIME_RE.match(line)
|
||||
if time_match:
|
||||
start = parse_time(time_match.group(1), time_match.group(2))
|
||||
end = parse_time(time_match.group(3), time_match.group(4))
|
||||
segments.append({
|
||||
"start": start,
|
||||
"end": end,
|
||||
"tag": current_tag,
|
||||
"lines": [],
|
||||
"raw_time": line,
|
||||
})
|
||||
current_tag = None # tag 只作用于紧跟的段落
|
||||
continue
|
||||
|
||||
# 歌词行
|
||||
if segments:
|
||||
segments[-1]["lines"].append(line)
|
||||
|
||||
return segments
|
||||
|
||||
|
||||
def validate(segments: list[dict]) -> list[str]:
|
||||
"""校验段落,返回警告/错误列表。"""
|
||||
issues: list[str] = []
|
||||
|
||||
for i, seg in enumerate(segments):
|
||||
duration = seg["end"] - seg["start"]
|
||||
time_label = seg["raw_time"]
|
||||
is_instrumental = seg["tag"] is not None
|
||||
line_count = len(seg["lines"])
|
||||
|
||||
# 时长为负或零
|
||||
if duration <= 0:
|
||||
issues.append(f"ERROR [{time_label}] 时长无效 ({duration:.0f}s)")
|
||||
continue
|
||||
|
||||
# 单段时长上限检查 (不超过20s)
|
||||
if duration > 20:
|
||||
issues.append(f"WARN [{time_label}] 时长过长 ({duration:.0f}s > 20s)")
|
||||
|
||||
if is_instrumental:
|
||||
if line_count > 0:
|
||||
issues.append(
|
||||
f"WARN [{time_label}] [{seg['tag']}] 纯音乐段包含 {line_count} 行歌词"
|
||||
)
|
||||
else:
|
||||
if line_count < 1:
|
||||
issues.append(
|
||||
f"WARN [{time_label}] 歌词段无歌词内容"
|
||||
)
|
||||
|
||||
# 连续性检查
|
||||
if i > 0:
|
||||
prev_end = segments[i - 1]["end"]
|
||||
if abs(seg["start"] - prev_end) > 0.01:
|
||||
issues.append(
|
||||
f"ERROR [{time_label}] 与上一段不连续 "
|
||||
f"(上段结束 {prev_end:.0f}s, 本段开始 {seg['start']:.0f}s)"
|
||||
)
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def print_summary(segments: list[dict], issues: list[str]) -> None:
|
||||
total = len(segments)
|
||||
instrumental = sum(1 for s in segments if s["tag"])
|
||||
lyric_segs = total - instrumental
|
||||
total_duration = segments[-1]["end"] - segments[0]["start"] if segments else 0
|
||||
|
||||
print(f"=== 歌词校验报告 ===\n")
|
||||
print(f"总时长: {int(total_duration // 60)}:{int(total_duration % 60):02d}")
|
||||
print(f"总段数: {total} (歌词段 {lyric_segs}, 纯音乐段 {instrumental})")
|
||||
print()
|
||||
|
||||
# 段落明细
|
||||
print(f"{'时间码':<18} {'时长':>5} {'行数':>4} {'类型':<10}")
|
||||
print("-" * 45)
|
||||
for seg in segments:
|
||||
duration = seg["end"] - seg["start"]
|
||||
seg_type = f"[{seg['tag']}]" if seg["tag"] else "歌词"
|
||||
print(f"{seg['raw_time']:<18} {duration:>4.0f}s {len(seg['lines']):>4} {seg_type:<10}")
|
||||
|
||||
print()
|
||||
if issues:
|
||||
print(f"发现 {len(issues)} 个问题:\n")
|
||||
for issue in issues:
|
||||
print(f" {issue}")
|
||||
else:
|
||||
print("ALL PASS")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
# 默认查找所有 lyric.md
|
||||
base = Path(__file__).resolve().parent.parent / ".mv"
|
||||
files = list(base.glob("*/lyric.md"))
|
||||
if not files:
|
||||
print("用法: python validate_lyric.py <lyric.md 路径>")
|
||||
sys.exit(1)
|
||||
else:
|
||||
files = [Path(sys.argv[1])]
|
||||
|
||||
for path in files:
|
||||
print(f"\n--- {path} ---\n")
|
||||
segments = parse_lyric_file(str(path))
|
||||
issues = validate(segments)
|
||||
print_summary(segments, issues)
|
||||
|
||||
# 有 ERROR 则返回非零退出码
|
||||
has_error = any("ERROR" in i for i in issues)
|
||||
sys.exit(1 if has_error else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,249 @@
|
||||
#!/usr/bin/env python3
|
||||
"""校验物件设计 design.md 格式是否符合规范。
|
||||
|
||||
用法:
|
||||
# 校验单个物件
|
||||
python validate_props_design.py .mv/{song}/{theme}/props/{prop}/design.md
|
||||
|
||||
# 校验 props 目录下所有物件
|
||||
python validate_props_design.py .mv/{song}/{theme}/props/
|
||||
|
||||
规则:
|
||||
- 必须有一级标题 # 物件名
|
||||
- 必须包含 5 个二级标题分区:外观描述、叙事作用、生图设定、候选图、选定图
|
||||
- 外观描述必须包含至少 3 项关键词(类型、形态、颜色/材质、尺寸/比例、细节特征)
|
||||
- 生图设定必须包含:提示词、模型、参考图
|
||||
- 候选图必须有至少 1 条列表项
|
||||
- 候选图路径对应的文件必须存在
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REQUIRED_SECTIONS = ["外观描述", "叙事作用", "生图设定", "候选图", "选定图"]
|
||||
PROMPT_FIELDS = ["提示词:", "模型:", "参考图:"]
|
||||
|
||||
# 中英 section / field 映射
|
||||
SECTION_ALIASES = {
|
||||
"外观描述": "Appearance",
|
||||
"叙事作用": "Narrative Role",
|
||||
"生图设定": "Image Settings",
|
||||
"候选图": "Candidates",
|
||||
"选定图": "Selected",
|
||||
}
|
||||
PROMPT_FIELD_ALIASES = {
|
||||
"提示词:": ("Prompt:", "Prompt:"),
|
||||
"模型:": ("Model:", "Model:"),
|
||||
"参考图:": ("Reference:", "Reference:"),
|
||||
}
|
||||
IMG_EXTS = {".png", ".jpg", ".jpeg", ".webp"}
|
||||
|
||||
H1_RE = re.compile(r"^#\s+(.+)$")
|
||||
H2_RE = re.compile(r"^##\s+(.+)$")
|
||||
LIST_RE = re.compile(r"^-\s+(.+)$")
|
||||
CANDIDATE_RE = re.compile(r"^-\s+(candidate_\S+)")
|
||||
|
||||
|
||||
def parse_design(text: str) -> dict:
|
||||
"""解析 design.md,返回结构化数据。"""
|
||||
lines = text.split("\n")
|
||||
result = {"title": None, "sections": {}}
|
||||
current_section = None
|
||||
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
|
||||
h1 = H1_RE.match(stripped)
|
||||
if h1:
|
||||
result["title"] = h1.group(1)
|
||||
continue
|
||||
|
||||
h2 = H2_RE.match(stripped)
|
||||
if h2:
|
||||
current_section = h2.group(1)
|
||||
result["sections"][current_section] = []
|
||||
continue
|
||||
|
||||
if current_section is not None:
|
||||
result["sections"][current_section].append(stripped)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_section(sections: dict, zh_name: str) -> list:
|
||||
"""从 sections 字典中获取内容,兼容中英 section header。"""
|
||||
en_name = SECTION_ALIASES.get(zh_name, "")
|
||||
return sections.get(zh_name, sections.get(en_name, []))
|
||||
|
||||
|
||||
def has_section(sections: dict, zh_name: str) -> bool:
|
||||
"""检查 section 是否存在,兼容中英。"""
|
||||
en_name = SECTION_ALIASES.get(zh_name, "")
|
||||
return zh_name in sections or en_name in sections
|
||||
|
||||
|
||||
def has_prompt_field(content: str, zh_field: str) -> bool:
|
||||
"""检查生图设定字段是否存在,兼容中英。"""
|
||||
if zh_field in content:
|
||||
return True
|
||||
for alias in PROMPT_FIELD_ALIASES.get(zh_field, ()):
|
||||
if alias in content:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def validate_one(design_path: Path) -> list[str]:
|
||||
"""校验单个 design.md,返回问题列表。"""
|
||||
issues = []
|
||||
prop_dir = design_path.parent
|
||||
prop_name = prop_dir.name
|
||||
|
||||
text = design_path.read_text(encoding="utf-8")
|
||||
data = parse_design(text)
|
||||
|
||||
# 物件名
|
||||
if not data["title"]:
|
||||
issues.append(f"ERROR [{prop_name}] 缺少一级标题 # 物件名")
|
||||
|
||||
# 必需分区
|
||||
for section in REQUIRED_SECTIONS:
|
||||
if not has_section(data["sections"], section):
|
||||
en = SECTION_ALIASES.get(section, "")
|
||||
issues.append(f"ERROR [{prop_name}] 缺少分区 ## {section}/{en}")
|
||||
|
||||
# 外观描述:需要包含至少 3 项列表项
|
||||
appearance = get_section(data["sections"], "外观描述")
|
||||
if appearance:
|
||||
items = [l for l in appearance if LIST_RE.match(l)]
|
||||
if len(items) < 3:
|
||||
issues.append(
|
||||
f"WARN [{prop_name}] 外观描述/Appearance 列表项不足(需至少 3 项,当前 {len(items)} 项)"
|
||||
)
|
||||
|
||||
# 叙事作用:需要有内容
|
||||
narrative = get_section(data["sections"], "叙事作用")
|
||||
if narrative:
|
||||
content = "\n".join(narrative).strip()
|
||||
if not content:
|
||||
issues.append(f"WARN [{prop_name}] 叙事作用/Narrative Role 内容为空")
|
||||
|
||||
# 生图设定:需要提示词、模型、参考图
|
||||
img_settings = get_section(data["sections"], "生图设定")
|
||||
if img_settings:
|
||||
content = "\n".join(img_settings)
|
||||
for field in PROMPT_FIELDS:
|
||||
if not has_prompt_field(content, field):
|
||||
issues.append(f"ERROR [{prop_name}] 生图设定/Image Settings 缺少字段 {field}")
|
||||
|
||||
# 候选图:需要至少 1 条,且文件存在
|
||||
candidates_lines = get_section(data["sections"], "候选图")
|
||||
if candidates_lines:
|
||||
candidates = []
|
||||
for line in candidates_lines:
|
||||
m = CANDIDATE_RE.match(line)
|
||||
if m:
|
||||
candidates.append(m.group(1))
|
||||
if not candidates:
|
||||
issues.append(f"ERROR [{prop_name}] 候选图/Candidates 为空(需要至少 1 张)")
|
||||
for fname in candidates:
|
||||
actual_name = fname.split()[0] if " " in fname else fname
|
||||
fpath = prop_dir / actual_name
|
||||
if not fpath.exists():
|
||||
issues.append(f"WARN [{prop_name}] 候选图文件不存在: {actual_name}")
|
||||
|
||||
# 选定图:检查是否已选定
|
||||
selected_lines = get_section(data["sections"], "选定图")
|
||||
if selected_lines:
|
||||
content = "\n".join(selected_lines).strip()
|
||||
if not content:
|
||||
issues.append(f"INFO [{prop_name}] 选定图/Selected 尚未填写(待用户挑选)")
|
||||
elif "selected" in content:
|
||||
sel_path = prop_dir / "selected.jpg"
|
||||
sel_png = prop_dir / "selected.png"
|
||||
if not sel_path.exists() and not sel_png.exists():
|
||||
issues.append(f"WARN [{prop_name}] selected.jpg/png 文件不存在")
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def find_designs(path: Path) -> list[Path]:
|
||||
"""查找所有 design.md 文件。"""
|
||||
if path.is_file() and path.name == "design.md":
|
||||
return [path]
|
||||
if path.is_dir():
|
||||
designs = []
|
||||
for d in sorted(path.iterdir()):
|
||||
if d.is_dir():
|
||||
dm = d / "design.md"
|
||||
if dm.exists():
|
||||
designs.append(dm)
|
||||
return designs
|
||||
return []
|
||||
|
||||
|
||||
def print_summary(all_issues: dict[str, list[str]]) -> None:
|
||||
print("=== 物件设计校验报告 ===\n")
|
||||
print(f"物件数量: {len(all_issues)}")
|
||||
print()
|
||||
|
||||
total_errors = 0
|
||||
total_warns = 0
|
||||
|
||||
for prop_name, issues in all_issues.items():
|
||||
errors = [i for i in issues if "ERROR" in i]
|
||||
warns = [i for i in issues if "WARN" in i]
|
||||
infos = [i for i in issues if "INFO" in i]
|
||||
total_errors += len(errors)
|
||||
total_warns += len(warns)
|
||||
|
||||
status = "PASS" if not errors else "FAIL"
|
||||
print(f" [{status}] {prop_name} — {len(errors)} 错误, {len(warns)} 警告")
|
||||
|
||||
print()
|
||||
if total_errors == 0 and total_warns == 0:
|
||||
no_info = all(not any("INFO" in i for i in iss) for iss in all_issues.values())
|
||||
if no_info:
|
||||
print("ALL PASS")
|
||||
else:
|
||||
print("ALL PASS (部分物件待用户选图)")
|
||||
else:
|
||||
all_issues_flat = [i for iss in all_issues.values() for i in iss]
|
||||
print(f"发现 {len(all_issues_flat)} 个问题:\n")
|
||||
for issue in all_issues_flat:
|
||||
print(f" {issue}")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("用法:")
|
||||
print(" python validate_props_design.py <design.md 路径>")
|
||||
print(" python validate_props_design.py <props 目录路径>")
|
||||
sys.exit(1)
|
||||
|
||||
target = Path(sys.argv[1]).resolve()
|
||||
if not target.exists():
|
||||
print(f"ERROR: 路径不存在: {target}")
|
||||
sys.exit(1)
|
||||
|
||||
designs = find_designs(target)
|
||||
if not designs:
|
||||
print(f"ERROR: 未找到 design.md 文件: {target}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"\n--- 物件设计校验 ---\n")
|
||||
|
||||
all_issues = {}
|
||||
for dp in designs:
|
||||
prop_name = dp.parent.name
|
||||
issues = validate_one(dp)
|
||||
all_issues[prop_name] = issues
|
||||
|
||||
print_summary(all_issues)
|
||||
|
||||
has_error = any("ERROR" in i for iss in all_issues.values() for i in iss)
|
||||
sys.exit(1 if has_error else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,223 @@
|
||||
#!/usr/bin/env python3
|
||||
"""校验 script.md 脚本格式是否符合预览解析器要求。
|
||||
|
||||
规则:
|
||||
- 每幕必须用 ## 标题
|
||||
- 时间码格式:* M:SS - M:SS (Xs)(不加粗、不带段落标签)
|
||||
- 每幕时长必须为 4~15 秒的整数
|
||||
- 时间段连续,不能有间隙或重叠
|
||||
- 每幕必须包含 **场景描述:**
|
||||
- 每幕可选包含 **关键物件:**
|
||||
- 每幕必须包含 **视觉风格:**
|
||||
- 每幕必须包含 **转场:**
|
||||
- 可选:与 lyric.md 交叉校验时间码
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
MIN_DURATION = 4
|
||||
MAX_DURATION = 15
|
||||
|
||||
SCENE_RE = re.compile(r"^##\s+(.+)$")
|
||||
TIME_RE = re.compile(
|
||||
r"^\*\s+(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})"
|
||||
r"(?:\s+\((\d+)s\))?\s*$"
|
||||
)
|
||||
BAD_TIME_BOLD_RE = re.compile(r"^\*\s+\*\*")
|
||||
|
||||
|
||||
def parse_time(minutes: str, seconds: str) -> int:
|
||||
return int(minutes) * 60 + int(seconds)
|
||||
|
||||
|
||||
def parse_script(path: str) -> list[dict]:
|
||||
"""解析 script.md,返回幕列表。"""
|
||||
text = Path(path).read_text(encoding="utf-8")
|
||||
lines = text.split("\n")
|
||||
scenes: list[dict] = []
|
||||
current: dict | None = None
|
||||
|
||||
for line_raw in lines:
|
||||
line = line_raw.strip()
|
||||
|
||||
scene_match = SCENE_RE.match(line)
|
||||
if scene_match:
|
||||
if current:
|
||||
scenes.append(current)
|
||||
current = {
|
||||
"title": scene_match.group(1),
|
||||
"time_raw": None,
|
||||
"start": None,
|
||||
"end": None,
|
||||
"duration_tag": None,
|
||||
"has_lyrics": False,
|
||||
"has_desc": False,
|
||||
"has_props": False,
|
||||
"has_style": False,
|
||||
"has_transition": False,
|
||||
"raw_lines": [],
|
||||
}
|
||||
continue
|
||||
|
||||
if current is None:
|
||||
continue
|
||||
|
||||
current["raw_lines"].append(line)
|
||||
|
||||
time_match = TIME_RE.match(line)
|
||||
if time_match:
|
||||
current["time_raw"] = line.lstrip("* ")
|
||||
current["start"] = parse_time(time_match.group(1), time_match.group(2))
|
||||
current["end"] = parse_time(time_match.group(3), time_match.group(4))
|
||||
if time_match.group(5) is not None:
|
||||
current["duration_tag"] = int(time_match.group(5))
|
||||
continue
|
||||
|
||||
if line.startswith(">"):
|
||||
current["has_lyrics"] = True
|
||||
if line.startswith("**场景描述:**") or line.startswith("**场景描述:**"):
|
||||
current["has_desc"] = True
|
||||
if line.startswith("**关键物件:**") or line.startswith("**关键物件:**"):
|
||||
current["has_props"] = True
|
||||
if line.startswith("**视觉风格:**") or line.startswith("**视觉风格:**"):
|
||||
current["has_style"] = True
|
||||
if line.startswith("**转场:**") or line.startswith("**转场:**"):
|
||||
current["has_transition"] = True
|
||||
|
||||
if current:
|
||||
scenes.append(current)
|
||||
|
||||
return scenes
|
||||
|
||||
|
||||
def validate(scenes: list[dict]) -> list[str]:
|
||||
"""校验幕列表,返回问题列表。"""
|
||||
issues: list[str] = []
|
||||
|
||||
if not scenes:
|
||||
issues.append("ERROR 未找到任何 ## 场景标题")
|
||||
return issues
|
||||
|
||||
for i, sc in enumerate(scenes):
|
||||
label = sc["title"]
|
||||
|
||||
# 检查时间码
|
||||
if sc["start"] is None:
|
||||
issues.append(f"ERROR [{label}] 缺少时间码行(格式:* M:SS - M:SS (Xs))")
|
||||
continue
|
||||
|
||||
# 检查加粗时间码
|
||||
for raw_line in sc["raw_lines"]:
|
||||
if BAD_TIME_BOLD_RE.match(raw_line):
|
||||
issues.append(f"ERROR [{label}] 时间码不应加粗(去掉 **)")
|
||||
break
|
||||
|
||||
duration = sc["end"] - sc["start"]
|
||||
if duration <= 0:
|
||||
issues.append(f"ERROR [{label}] 时长无效 ({duration}s)")
|
||||
continue
|
||||
|
||||
# 时长标签检查
|
||||
if sc["duration_tag"] is None:
|
||||
issues.append(f"ERROR [{label}] 缺少时长标签(格式:* M:SS - M:SS (Xs))")
|
||||
elif sc["duration_tag"] != duration:
|
||||
issues.append(
|
||||
f"ERROR [{label}] 时长标签 ({sc['duration_tag']}s) "
|
||||
f"与实际时长 ({duration}s) 不一致"
|
||||
)
|
||||
|
||||
# 时长范围检查
|
||||
if not (MIN_DURATION <= duration <= MAX_DURATION):
|
||||
issues.append(
|
||||
f"ERROR [{label}] 时长 {duration}s 超出范围 "
|
||||
f"(要求 {MIN_DURATION}~{MAX_DURATION}s)"
|
||||
)
|
||||
|
||||
# 整数检查(时间码本身是整数秒,这里 double check)
|
||||
if duration != int(duration):
|
||||
issues.append(f"ERROR [{label}] 时长必须为整数秒 (当前 {duration}s)")
|
||||
|
||||
# 连续性检查
|
||||
if i > 0 and scenes[i - 1]["end"] is not None:
|
||||
prev_end = scenes[i - 1]["end"]
|
||||
if abs(sc["start"] - prev_end) > 1:
|
||||
issues.append(
|
||||
f"ERROR [{label}] 与上一幕不连续 "
|
||||
f"(上幕结束 {_fmt(prev_end)}, 本幕开始 {_fmt(sc['start'])})"
|
||||
)
|
||||
|
||||
# 必填字段检查
|
||||
if not sc["has_desc"]:
|
||||
issues.append(f"WARN [{label}] 缺少 **场景描述:**")
|
||||
if not sc["has_style"]:
|
||||
issues.append(f"WARN [{label}] 缺少 **视觉风格:**")
|
||||
if not sc["has_transition"]:
|
||||
issues.append(f"WARN [{label}] 缺少 **转场:**")
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def _fmt(seconds: float) -> str:
|
||||
return f"{int(seconds // 60)}:{int(seconds % 60):02d}"
|
||||
|
||||
|
||||
def print_summary(scenes: list[dict], issues: list[str]) -> None:
|
||||
total = len(scenes)
|
||||
with_lyrics = sum(1 for s in scenes if s["has_lyrics"])
|
||||
total_duration = 0
|
||||
if scenes and scenes[-1]["end"] is not None and scenes[0]["start"] is not None:
|
||||
total_duration = scenes[-1]["end"] - scenes[0]["start"]
|
||||
|
||||
print("=== 脚本校验报告 ===\n")
|
||||
print(f"总时长: {_fmt(total_duration)}")
|
||||
print(f"总幕数: {total} (歌词幕 {with_lyrics}, 纯画面幕 {total - with_lyrics})")
|
||||
print(f"时长约束: {MIN_DURATION}~{MAX_DURATION}s")
|
||||
print()
|
||||
|
||||
print(f"{'幕名':<20} {'时间码':<20} {'时长':>5} {'歌词':>4} {'描述':>4} {'物件':>4} {'风格':>4} {'转场':>4}")
|
||||
print("-" * 82)
|
||||
for sc in scenes:
|
||||
duration = (sc["end"] - sc["start"]) if sc["start"] is not None else 0
|
||||
time_str = sc["time_raw"] or "缺失"
|
||||
check = lambda v: "Y" if v else "-"
|
||||
title = sc["title"][:18]
|
||||
ok = " " if MIN_DURATION <= duration <= MAX_DURATION else "!!"
|
||||
print(
|
||||
f"{title:<20} {time_str:<20} {duration:>3.0f}s{ok}"
|
||||
f"{check(sc['has_lyrics']):>4} {check(sc['has_desc']):>4} "
|
||||
f"{check(sc['has_props']):>4} {check(sc['has_style']):>4} "
|
||||
f"{check(sc['has_transition']):>4}"
|
||||
)
|
||||
|
||||
print()
|
||||
if issues:
|
||||
print(f"发现 {len(issues)} 个问题:\n")
|
||||
for issue in issues:
|
||||
print(f" {issue}")
|
||||
else:
|
||||
print("ALL PASS")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("用法: python validate_script.py <script.md 路径>")
|
||||
sys.exit(1)
|
||||
|
||||
script_path = Path(sys.argv[1])
|
||||
if not script_path.exists():
|
||||
print(f"ERROR: 文件不存在: {script_path}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"\n--- {script_path} ---\n")
|
||||
scenes = parse_script(str(script_path))
|
||||
issues = validate(scenes)
|
||||
print_summary(scenes, issues)
|
||||
|
||||
has_error = any("ERROR" in i for i in issues)
|
||||
sys.exit(1 if has_error else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,321 @@
|
||||
#!/usr/bin/env python3
|
||||
"""校验 storyboard.md 分镜规划格式是否符合规范。
|
||||
|
||||
用法:
|
||||
python validate_storyboard.py .mv/{song}/{theme}/storyboard.md
|
||||
|
||||
规则:
|
||||
- 每幕必须用 ## 标题
|
||||
- 时间码格式:* M:SS - M:SS (Xs)
|
||||
- 每幕必须包含:出场角色、场景背景、场景描述、视频提示词、参考图
|
||||
- 出场角色(非"无")对应的角色目录和 selected.jpg 必须存在
|
||||
- 场景背景对应的 backgrounds/ 目录和 selected.jpg 必须存在
|
||||
- 关键物件对应的 props/ 目录和 selected.jpg 必须存在
|
||||
- 可选:与 script.md 交叉校验幕数和时间码
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SCENE_RE = re.compile(r"^##\s+(.+)$")
|
||||
TIME_RE = re.compile(
|
||||
r"^\*\s+(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})"
|
||||
r"(?:\s+\((\d+)s\))?\s*$"
|
||||
)
|
||||
|
||||
|
||||
def parse_time(minutes: str, seconds: str) -> int:
|
||||
return int(minutes) * 60 + int(seconds)
|
||||
|
||||
|
||||
def parse_storyboard(path: str) -> list[dict]:
|
||||
"""解析 storyboard.md,返回幕列表。"""
|
||||
text = Path(path).read_text(encoding="utf-8")
|
||||
lines = text.split("\n")
|
||||
scenes: list[dict] = []
|
||||
current: dict | None = None
|
||||
current_field: str | None = None
|
||||
|
||||
for line_raw in lines:
|
||||
line = line_raw.strip()
|
||||
|
||||
scene_match = SCENE_RE.match(line)
|
||||
if scene_match:
|
||||
if current:
|
||||
scenes.append(current)
|
||||
current = {
|
||||
"title": scene_match.group(1),
|
||||
"start": None,
|
||||
"end": None,
|
||||
"duration_tag": None,
|
||||
"time_raw": None,
|
||||
"characters": None,
|
||||
"background": None,
|
||||
"props": None,
|
||||
"has_desc": False,
|
||||
"has_prompt": False,
|
||||
"has_refs": False,
|
||||
}
|
||||
current_field = None
|
||||
continue
|
||||
|
||||
if current is None:
|
||||
continue
|
||||
|
||||
time_match = TIME_RE.match(line)
|
||||
if time_match:
|
||||
current["time_raw"] = line.lstrip("* ")
|
||||
current["start"] = parse_time(time_match.group(1), time_match.group(2))
|
||||
current["end"] = parse_time(time_match.group(3), time_match.group(4))
|
||||
if time_match.group(5) is not None:
|
||||
current["duration_tag"] = int(time_match.group(5))
|
||||
current_field = None
|
||||
continue
|
||||
|
||||
# 字段检测 (兼容中英)
|
||||
if line.startswith(("出场角色:", "出场角色:", "Characters:", "Characters:")):
|
||||
chars = line.split(":", 1)[-1].split(":", 1)[-1].strip()
|
||||
current["characters"] = chars
|
||||
current_field = "characters"
|
||||
continue
|
||||
if line.startswith(("场景背景:", "场景背景:", "Scene Background:", "Scene Background:")):
|
||||
bg = line.split(":", 1)[-1].split(":", 1)[-1].strip()
|
||||
current["background"] = bg
|
||||
current_field = "background"
|
||||
continue
|
||||
if line.startswith(("关键物件:", "关键物件:", "Key Props:", "Key Props:")):
|
||||
props = line.split(":", 1)[-1].split(":", 1)[-1].strip()
|
||||
current["props"] = props
|
||||
current_field = "props"
|
||||
continue
|
||||
if line.startswith(("场景描述:", "场景描述:", "Scene Description:", "Scene Description:")):
|
||||
current["has_desc"] = True
|
||||
current_field = "desc"
|
||||
continue
|
||||
if line.startswith(("生图提示词:", "生图提示词:", "视频提示词:", "视频提示词:", "Video Prompt:", "Video Prompt:")):
|
||||
current["has_prompt"] = True
|
||||
current_field = "prompt"
|
||||
continue
|
||||
if line.startswith(("参考图:", "参考图:", "Reference:", "Reference:")):
|
||||
current["has_refs"] = True
|
||||
current_field = "refs"
|
||||
continue
|
||||
|
||||
if current:
|
||||
scenes.append(current)
|
||||
|
||||
return scenes
|
||||
|
||||
|
||||
def validate(scenes: list[dict], theme_dir: Path) -> list[str]:
|
||||
"""校验幕列表,返回问题列表。"""
|
||||
issues: list[str] = []
|
||||
|
||||
if not scenes:
|
||||
issues.append("ERROR 未找到任何 ## 场景标题")
|
||||
return issues
|
||||
|
||||
for i, sc in enumerate(scenes):
|
||||
label = sc["title"]
|
||||
|
||||
# 时间码
|
||||
if sc["start"] is None:
|
||||
issues.append(f"ERROR [{label}] 缺少时间码行(格式:* M:SS - M:SS (Xs))")
|
||||
else:
|
||||
duration = sc["end"] - sc["start"]
|
||||
if duration <= 0:
|
||||
issues.append(f"ERROR [{label}] 时长无效 ({duration}s)")
|
||||
if sc["duration_tag"] is not None and sc["duration_tag"] != duration:
|
||||
issues.append(
|
||||
f"ERROR [{label}] 时长标签 ({sc['duration_tag']}s) "
|
||||
f"与实际时长 ({duration}s) 不一致"
|
||||
)
|
||||
# 连续性
|
||||
if i > 0 and scenes[i - 1]["end"] is not None:
|
||||
prev_end = scenes[i - 1]["end"]
|
||||
if abs(sc["start"] - prev_end) > 1:
|
||||
issues.append(
|
||||
f"ERROR [{label}] 与上一幕不连续 "
|
||||
f"(上幕结束 {_fmt(prev_end)}, 本幕开始 {_fmt(sc['start'])})"
|
||||
)
|
||||
|
||||
# 必填字段
|
||||
if sc["characters"] is None:
|
||||
issues.append(f"ERROR [{label}] 缺少 出场角色/Characters")
|
||||
if sc["background"] is None:
|
||||
issues.append(f"ERROR [{label}] 缺少 场景背景/Scene Background")
|
||||
if not sc["has_desc"]:
|
||||
issues.append(f"ERROR [{label}] 缺少 场景描述/Scene Description")
|
||||
if not sc["has_prompt"]:
|
||||
issues.append(f"ERROR [{label}] 缺少 视频提示词/Video Prompt")
|
||||
if not sc["has_refs"]:
|
||||
issues.append(f"WARN [{label}] 缺少 参考图/Reference")
|
||||
|
||||
# 出场角色 → 角色目录 + selected.jpg 检查
|
||||
if sc["characters"] and sc["characters"].lower() not in ("(无)", "(无)", "无", "none", "(none)", "n/a"):
|
||||
char_names = [c.strip() for c in sc["characters"].split("、")]
|
||||
if len(char_names) == 1:
|
||||
char_names = [c.strip() for c in sc["characters"].split(",")]
|
||||
for cname in char_names:
|
||||
if not cname:
|
||||
continue
|
||||
char_dir = theme_dir / "characters" / cname
|
||||
if not char_dir.exists():
|
||||
issues.append(
|
||||
f"WARN [{label}] 角色目录不存在: characters/{cname}/"
|
||||
)
|
||||
else:
|
||||
sel = char_dir / "selected.jpg"
|
||||
sel_png = char_dir / "selected.png"
|
||||
if not sel.exists() and not sel_png.exists():
|
||||
issues.append(
|
||||
f"WARN [{label}] 角色 {cname} 缺少 selected.jpg/png"
|
||||
)
|
||||
|
||||
# 场景背景 → backgrounds/ 目录 + selected.jpg 检查
|
||||
if sc["background"]:
|
||||
bg_dir = theme_dir / "backgrounds" / sc["background"]
|
||||
if not bg_dir.exists():
|
||||
issues.append(
|
||||
f"WARN [{label}] 背景目录不存在: backgrounds/{sc['background']}/"
|
||||
)
|
||||
else:
|
||||
sel = bg_dir / "selected.jpg"
|
||||
sel_png = bg_dir / "selected.png"
|
||||
if not sel.exists() and not sel_png.exists():
|
||||
issues.append(
|
||||
f"WARN [{label}] 背景 {sc['background']} 缺少 selected.jpg/png"
|
||||
)
|
||||
|
||||
# 关键物件 → props/ 目录 + selected.jpg 检查
|
||||
if sc["props"] and sc["props"].lower() not in ("(无)", "(无)", "无", "", "none", "(none)", "n/a"):
|
||||
prop_names = [p.strip() for p in sc["props"].split("、")]
|
||||
if len(prop_names) == 1:
|
||||
prop_names = [p.strip() for p in sc["props"].split(",")]
|
||||
for pname in prop_names:
|
||||
if not pname:
|
||||
continue
|
||||
prop_dir = theme_dir / "props" / pname
|
||||
if not prop_dir.exists():
|
||||
issues.append(
|
||||
f"WARN [{label}] 物件目录不存在: props/{pname}/"
|
||||
)
|
||||
else:
|
||||
sel = prop_dir / "selected.jpg"
|
||||
sel_png = prop_dir / "selected.png"
|
||||
if not sel.exists() and not sel_png.exists():
|
||||
issues.append(
|
||||
f"WARN [{label}] 物件 {pname} 缺少 selected.jpg/png"
|
||||
)
|
||||
|
||||
# 与 script.md 交叉校验
|
||||
script_path = theme_dir / "script.md"
|
||||
if script_path.exists():
|
||||
_cross_validate_script(scenes, script_path, issues)
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def _cross_validate_script(scenes: list[dict], script_path: Path, issues: list[str]):
|
||||
"""与 script.md 交叉校验幕数和时间码。"""
|
||||
text = script_path.read_text(encoding="utf-8")
|
||||
script_scenes = []
|
||||
for line in text.split("\n"):
|
||||
line = line.strip()
|
||||
sm = SCENE_RE.match(line)
|
||||
if sm:
|
||||
script_scenes.append({"title": sm.group(1), "start": None, "end": None})
|
||||
tm = TIME_RE.match(line)
|
||||
if tm and script_scenes:
|
||||
script_scenes[-1]["start"] = parse_time(tm.group(1), tm.group(2))
|
||||
script_scenes[-1]["end"] = parse_time(tm.group(3), tm.group(4))
|
||||
|
||||
if len(scenes) != len(script_scenes):
|
||||
issues.append(
|
||||
f"WARN [交叉校验] 分镜幕数 ({len(scenes)}) "
|
||||
f"与脚本幕数 ({len(script_scenes)}) 不一致"
|
||||
)
|
||||
return
|
||||
|
||||
for i, (sb, sc) in enumerate(zip(scenes, script_scenes)):
|
||||
if sb["start"] is not None and sc["start"] is not None:
|
||||
if sb["start"] != sc["start"] or sb["end"] != sc["end"]:
|
||||
issues.append(
|
||||
f"WARN [交叉校验] 第 {i+1} 幕时间码与脚本不一致 "
|
||||
f"(分镜 {sb['time_raw']}, 脚本 {_fmt(sc['start'])}-{_fmt(sc['end'])})"
|
||||
)
|
||||
|
||||
|
||||
def _fmt(seconds: int) -> str:
|
||||
return f"{seconds // 60}:{seconds % 60:02d}"
|
||||
|
||||
|
||||
def print_summary(scenes: list[dict], issues: list[str]) -> None:
|
||||
total = len(scenes)
|
||||
total_duration = 0
|
||||
if scenes and scenes[-1]["end"] is not None and scenes[0]["start"] is not None:
|
||||
total_duration = scenes[-1]["end"] - scenes[0]["start"]
|
||||
with_chars = sum(
|
||||
1 for s in scenes
|
||||
if s["characters"] and s["characters"].lower() not in ("(无)", "(无)", "无", "none", "(none)", "n/a")
|
||||
)
|
||||
|
||||
print("=== 分镜规划校验报告 ===\n")
|
||||
print(f"总时长: {_fmt(total_duration)}")
|
||||
print(f"总幕数: {total} (含角色 {with_chars}, 纯空镜 {total - with_chars})")
|
||||
print()
|
||||
|
||||
print(
|
||||
f"{'幕名':<20} {'时间码':<20} {'时长':>5} {'角色':>4} "
|
||||
f"{'背景':>4} {'描述':>4} {'prompt':>6}"
|
||||
)
|
||||
print("-" * 78)
|
||||
for sc in scenes:
|
||||
duration = (sc["end"] - sc["start"]) if sc["start"] is not None else 0
|
||||
time_str = sc["time_raw"] or "缺失"
|
||||
check = lambda v: "Y" if v else "-"
|
||||
has_char = sc["characters"] is not None and sc["characters"].lower() not in ("(无)", "(无)", "无", "none", "(none)", "n/a")
|
||||
has_bg = sc["background"] is not None
|
||||
title = sc["title"][:18]
|
||||
print(
|
||||
f"{title:<20} {time_str:<20} {duration:>3}s "
|
||||
f"{check(has_char):>4} {check(has_bg):>4} "
|
||||
f"{check(sc['has_desc']):>4} {check(sc['has_prompt']):>6}"
|
||||
)
|
||||
|
||||
print()
|
||||
if issues:
|
||||
errors = [i for i in issues if "ERROR" in i]
|
||||
warns = [i for i in issues if "WARN" in i]
|
||||
infos = [i for i in issues if "INFO" in i]
|
||||
print(f"发现 {len(issues)} 个问题 ({len(errors)} 错误, {len(warns)} 警告, {len(infos)} 信息):\n")
|
||||
for issue in issues:
|
||||
print(f" {issue}")
|
||||
else:
|
||||
print("ALL PASS")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("用法: python validate_storyboard.py <storyboard.md 路径>")
|
||||
sys.exit(1)
|
||||
|
||||
sb_path = Path(sys.argv[1]).resolve()
|
||||
if not sb_path.exists():
|
||||
print(f"ERROR: 文件不存在: {sb_path}")
|
||||
sys.exit(1)
|
||||
|
||||
theme_dir = sb_path.parent
|
||||
|
||||
print(f"\n--- 分镜规划校验 ---\n")
|
||||
scenes = parse_storyboard(str(sb_path))
|
||||
issues = validate(scenes, theme_dir)
|
||||
print_summary(scenes, issues)
|
||||
|
||||
has_error = any("ERROR" in i for i in issues)
|
||||
sys.exit(1 if has_error else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user