Skip to content

zenstory-ai/video-recap-skills / skills/video-recap

video-recap

Verified

把一段或多集视频做成带画框字幕的中文解说成片或纯原声高光短片。用户提供 .mp4 / .mov / .mkv / .webm,要求做影视解说、短剧二创、加旁白配音、跨集混剪或导出剪映草稿时使用;串联完成看片识台词、定主线与留原声、按台词停顿切镜头、写词检查、TTS 配音与混音加字幕。触发词:视频解说、影视解说、视频旁白、生成解说、视频 recap、video recap、voiceover、narration、recap。

FileKindSize
SKILL.mdskill md18.4 KB
assets/dashboard/app.jsscript16.2 KB
assets/dashboard/index.htmlother867 B
assets/dashboard/styles.cssother22.6 KB
assets/dashboard/tokens.cssother8.9 KB
assets/dashboard/views.jsscript31.4 KB
references/audio-modes.mdmarkdown3.6 KB
references/config-playbook.mdmarkdown8.1 KB
references/creative-editing-playbook.mdmarkdown12.3 KB
references/data-schema.mdmarkdown34.6 KB
references/index-tts.mdmarkdown2.1 KB
references/jianying/LICENSE.duo-videoother1.0 KB
references/jianying/SOURCE.mdmarkdown703 B
references/jianying/empty_draft_meta_info.jsonconfig1.7 KB
references/jianying/empty_jy_material_video.jsonconfig1.8 KB
references/jianying/empty_jy_meta_material_value.jsonconfig358 B
references/jianying/empty_jy_project_info.jsonconfig3.6 KB
references/jianying/empty_jy_segment.jsonconfig1.3 KB
references/jianying/empty_jy_text_styles.jsonconfig440 B
references/jianying/empty_yj_material_audio.jsonconfig865 B
references/jianying/empty_yj_material_text.jsonconfig2.4 KB
references/packaging.mdmarkdown6.8 KB
references/promotional-copy.mdmarkdown4.1 KB
references/prompt-templates.mdmarkdown2.0 KB
references/research-guide.mdmarkdown2.7 KB
references/resource-library.mdmarkdown12.1 KB
references/shot-review.mdmarkdown4.8 KB
scripts/agent_text.pyscript2.7 KB
scripts/artifacts.pyscript972 B
scripts/asr.pyscript12.5 KB
scripts/asr_timing_evidence.pyscript4.2 KB
scripts/assemble.pyscript31.0 KB
scripts/assemble_constants.pyscript894 B
scripts/assembly_contract.pyscript10.3 KB
scripts/assembly_settings.pyscript3.8 KB
scripts/audio_automation.pyscript6.6 KB
scripts/audio_mix.pyscript18.5 KB
scripts/briefing/__init__.pyscript101 B
scripts/briefing/builder.pyscript31.1 KB
scripts/briefing/context.pyscript6.1 KB
scripts/briefing/timeline.pyscript23.0 KB
scripts/codec_peak.pyscript5.1 KB
scripts/cut.pyscript148 B
scripts/cut_cli.pyscript12.4 KB
scripts/cut_contract.pyscript13.3 KB
scripts/cut_qc.pyscript1.9 KB
scripts/cut_render.pyscript13.2 KB
scripts/dashboard/__init__.pyscript159 B
scripts/dashboard/data.pyscript24.6 KB
scripts/dashboard/io.pyscript7.1 KB
scripts/dashboard/runs.pyscript21.8 KB
scripts/dashboard/templates.pyscript9.6 KB
scripts/dashboard_server.pyscript9.3 KB
scripts/detect.pyscript22.2 KB
scripts/doctor.pyexecutablescript12.9 KB
scripts/entry_suggestion.pyscript4.6 KB
scripts/export_jianying.pyscript5.6 KB
scripts/extract.pyscript2.5 KB
scripts/final_qc.pyscript19.0 KB
scripts/frame_grid.pyscript10.6 KB
scripts/jianying/__init__.pyscript49 B
scripts/jianying/builders.pyscript11.3 KB
scripts/jianying/model.pyscript2.7 KB
scripts/jianying/optional.pyscript1012 B
scripts/jianying/schema.pyscript2.5 KB
scripts/jianying/templates.pyscript1.0 KB
scripts/jianying/timeline_contract.pyscript5.8 KB
scripts/jianying/tracks.pyscript2.0 KB
scripts/jianying/writer.pyscript7.8 KB
scripts/lib.pyscript29.6 KB
scripts/library.pyscript31.1 KB
scripts/lint_summary.pyscript5.0 KB
scripts/loudness.pyscript14.7 KB
scripts/materials.pyscript22.1 KB
scripts/media.pyscript18.8 KB
scripts/narration_audio.pyscript13.5 KB
scripts/narration_lint.pyscript24.1 KB
scripts/narrative_selection.pyscript8.9 KB
scripts/packaging.pyscript6.1 KB
scripts/packaging_fonts.pyscript12.0 KB
scripts/packaging_plates.pyscript31.2 KB
scripts/packaging_studio.pyscript34.1 KB
scripts/providers/__init__.pyscript72 B
scripts/providers/fish_audio.pyscript3.1 KB
scripts/providers/index_tts.pyscript8.8 KB
scripts/recap.pyscript183 B
scripts/recap_cli.pyscript6.9 KB
scripts/recap_inspect.pyscript16.5 KB
scripts/recap_runner.pyscript22.0 KB
scripts/recap_runtime.pyscript11.8 KB
scripts/recap_source.pyscript1.8 KB
scripts/recap_stage_qc.pyscript2.7 KB
scripts/recap_timeline.pyscript7.7 KB
scripts/render_preflight.pyscript1.7 KB
scripts/resources/__init__.pyscript200 B
scripts/resources/lock.pyscript6.8 KB
scripts/resources/project_binding.pyscript16.1 KB
scripts/sentence_boundaries.pyscript28.8 KB
scripts/sentence_gate.pyscript8.6 KB
scripts/sfx_mix.pyscript14.6 KB
scripts/shot_review.pyscript18.9 KB
scripts/source_subtitles.pyscript7.2 KB
scripts/speech_ownership.pyscript9.3 KB
scripts/storyboard.pyscript21.8 KB
scripts/subtitles/__init__.pyscript56 B
scripts/subtitles/core.pyscript19.0 KB
scripts/subtitles/render.pyscript8.0 KB
scripts/timeline.pyscript8.2 KB
scripts/timeline_emit.pyscript5.4 KB
scripts/tts_audio.pyscript9.6 KB
scripts/tts_cache.pyscript4.5 KB
scripts/understand.pyscript171 B
scripts/understanding_brief.pyscript6.3 KB
scripts/understanding_cache.pyscript8.0 KB
scripts/understanding_runner.pyscript9.8 KB
scripts/understanding_storyboard.pyscript11.9 KB
scripts/validate.pyscript5.7 KB
scripts/visual_render.pyscript10.1 KB
scripts/vlm.pyscript16.4 KB
scripts/voiceover.pyscript28.0 KB

scripts/resources/project_binding.py

View on GitHub
"""Resolve a ``recap_project.json`` binding into the settings stage scripts already accept.

Only video-recap reads the library. A bound subtitle style becomes ``SUBTITLE_*`` env for
assemble.py, a bound voice becomes the voiceover provider / voice arguments, a bound
BGM becomes ``BGM_PATH``, a bound production reference becomes a marked copy in the work_dir
that only the writing agent reads. Stage scripts keep seeing concrete paths and values; they never
learn about templates. Anything the caller already set explicitly must agree with the
binding — a silent override would make the delivered file disagree with the project.
"""
from __future__ import annotations

import json
import os
from pathlib import Path

import library as library_lib
from lib import read_json_object

PROJECT_FILE = "recap_project.json"
PROJECT_SCHEMA = "video-recap.project.v1"
PROJECT_KEYS = {"schema", "name", "library", "bindings", "notes"}
BINDING_KINDS = ("subtitle_style", "packaging", "voice", "bgm", "production_reference")
GEOMETRY_ROLES = {"subtitle_style", "packaging"}


class BindingError(SystemExit):
    """A project binding that cannot be applied; exits before any stage runs."""

    def __init__(self, message):
        super().__init__(f"项目绑定无法使用: {message}")


def project_path(value) -> Path:
    path = Path(value).expanduser().resolve()
    if path.is_dir():
        path = path / PROJECT_FILE
    if not path.is_file():
        raise BindingError(f"找不到 {path}")
    return path


def _value(params, key):
    node = params.get(key)
    return node.get("value") if isinstance(node, dict) else None


def _record(entry):
    return json.loads(Path(entry["record"]).read_text(encoding="utf-8"))


def _ass_color_param(params, key):
    raw = _value(params, key)
    if raw is None:
        return None
    try:
        return library_lib.to_ass_color(raw)
    except ValueError as exc:
        raise BindingError(str(exc)) from exc


def _subtitle_env(template, record, resources):
    params = record["params"]
    canvas = record["canvas"]
    env = {
        "SUBTITLE_PLAY_RES_X": canvas["width"],
        "SUBTITLE_PLAY_RES_Y": canvas["height"],
        "SUBTITLE_FONT_SIZE": _value(params, "size_px"),
        "SUBTITLE_OUTLINE": _value(params, "outline_px"),
        "SUBTITLE_SHADOW": _value(params, "shadow_px"),
        "SUBTITLE_PRIMARY_COLOR": _ass_color_param(params, "primary_color"),
        "SUBTITLE_OUTLINE_COLOR": _ass_color_param(params, "outline_color"),
        "SUBTITLE_MAX_CHARS": _value(params, "max_chars"),
        "SUBTITLE_MAX_LINES": _value(params, "max_lines"),
    }
    font = params["font"]
    if font.get("resource"):
        resource = resources[font["resource"]]
        env["SUBTITLE_FONT_NAME"] = (_record(resource).get("font") or {}).get("family")
        env["SUBTITLE_FONT_FILE"] = resource["files"][0]["path"]
    else:
        env["SUBTITLE_FONT_NAME"] = font["family"]
    band = _value(params, "band")
    if band:
        env["SUBTITLE_ALIGNMENT"] = 2
        env["SUBTITLE_MARGIN_V"] = canvas["height"] - band["y_bot"]
    return {k: str(v) for k, v in env.items() if v is not None}


def _voice_updates(resource, args):
    record = _record(resource)
    voice = record.get("voice") or {}
    provider = voice.get("provider")
    consent = (record.get("consent") or {}).get("status")
    if resource["files"] and consent == "denied":
        raise BindingError(f"音色 {resource['id']} 的参考音频声音授权为 denied")
    if args.tts_provider not in ("auto", provider):
        raise BindingError(f"音色 {resource['id']} 属于 {provider},与 --tts-provider {args.tts_provider} 冲突")
    updates, env = {"tts_provider": provider}, {}
    if provider == "mimo-tts":
        if resource["files"]:
            updates["voice_ref"] = resource["files"][0]["path"]
        else:
            updates["mimo_tts_voice"] = voice.get("voice_id")
    elif provider == "fish-audio":
        env["FISH_TTS_REFERENCE_ID"] = voice.get("voice_id")
    else:
        env["INDEX_TTS_VOICE"] = voice.get("voice_id")
    return updates, env


def _same_setting(key, current, value):
    if key.endswith(("_PATH", "_FILE", "VOICE_REF")):
        return Path(current).expanduser().resolve() == Path(value).expanduser().resolve()
    if key in ("SUBTITLE_PRIMARY_COLOR", "SUBTITLE_OUTLINE_COLOR"):
        try:
            return library_lib.to_ass_color(current) == library_lib.to_ass_color(value)
        except ValueError:
            return current == value
    try:
        return float(current) == float(value)
    except ValueError:
        return current == value


def _check_env_conflicts(env, environ):
    for key, value in env.items():
        current = environ.get(key, "").strip()
        if current and not _same_setting(key, current, value):
            raise BindingError(f"{key}={current} 与项目绑定的 {value} 冲突;删掉其中一处")


def _check_arg_conflicts(updates, args):
    for key, value in updates.items():
        current = getattr(args, key, None)
        if key == "tts_provider" or current in (None, ""):
            continue
        if str(current) != str(value):
            raise BindingError(f"--{key.replace('_', '-')} {current} 与项目绑定的 {value} 冲突")


def resolve_project(value, args, environ=None, *, include_voice=True) -> dict:
    """Load and validate a project; return what to apply plus the lock's project block."""
    environ = os.environ if environ is None else environ
    path = project_path(value)
    try:
        project = json.loads(path.read_text(encoding="utf-8"))
    except ValueError as exc:
        raise BindingError(f"{path} 无法解析: {exc}") from None
    if not isinstance(project, dict) or project.get("schema") != PROJECT_SCHEMA:
        raise BindingError(f"{path} 的 schema 必须是 {PROJECT_SCHEMA}")
    unknown = sorted(set(project) - PROJECT_KEYS)
    bindings = project.get("bindings") or {}
    if not isinstance(bindings, dict):
        raise BindingError(f"{path} 的 bindings 必须是 object")
    unknown += sorted(f"bindings.{k}" for k in set(bindings) - set(BINDING_KINDS))
    if unknown:
        raise BindingError(f"{path} 有未知字段: {', '.join(unknown)}")
    not_ids = sorted(k for k, v in bindings.items() if v is not None and not isinstance(v, str))
    if not_ids:
        raise BindingError(f"{path} 的 bindings.{not_ids[0]} 必须是资源或模板 id 字符串")
    library_root = (path.parent / str(project.get("library", ""))).resolve()
    if not (library_root / "library.json").is_file():
        raise BindingError(f"库目录无效(缺少 library.json): {library_root}")
    index, report = library_lib.scan_library(library_root)
    resources = {r["id"]: r for r in index["resources"]}
    templates = {f"{t['id']}@v{t['version']}": t for t in index["templates"]}
    errors = {}
    for issue in report.errors:
        errors.setdefault(issue["path"], issue["message"])

    def require_valid(entry, label):
        rel = Path(entry["record"]).relative_to(library_root).as_posix()
        if rel in errors:
            raise BindingError(f"{label}: {errors[rel]}(先运行 library.py check)")

    def template(kind):
        ref = bindings.get(kind)
        if not ref:
            return None
        entry = templates.get(ref)
        if entry is None or entry["kind"] != kind:
            raise BindingError(f"{kind} 模板 {ref} 不存在或无效(先运行 library.py check)")
        if entry["status"] != "adopted":
            raise BindingError(f"{kind} 模板 {ref} 的状态是 {entry['status']},只有 adopted 能绑定")
        require_valid(entry, ref)
        for _, rid in entry["refs"]:
            if rid not in resources:
                raise BindingError(f"{ref} 引用的资源 {rid} 不存在或无效(先运行 library.py check)")
            require_valid(resources[rid], f"{ref} 引用的资源 {rid}")
        used_templates.append({"role": kind, "id": entry["id"], "version": entry["version"],
                               "status": entry["status"], "canvas": entry["canvas"]})
        return entry

    def resource(kind):
        rid = bindings.get(kind)
        if not rid:
            return None
        entry = resources.get(rid)
        if entry is None or entry["kind"] != kind:
            raise BindingError(f"{kind} 资源 {rid} 不存在或无效(先运行 library.py check)")
        require_valid(entry, f"{kind} 资源 {rid}")
        return entry

    env, updates, used_templates = {}, {}, []
    subtitle = template("subtitle_style")
    if subtitle:
        env.update(_subtitle_env(subtitle, _record(subtitle), resources))
    packaging = template("packaging")
    reference = template("production_reference")
    if reference:
        reference = {"template": {"id": reference["id"], "version": reference["version"]},
                     "payload": json.loads((Path(reference["record"]).parent / library_lib.REFERENCE_FILE)
                                           .read_text(encoding="utf-8"))}
    voice = resource("voice") if include_voice else None
    if voice:
        voice_updates, voice_env = _voice_updates(voice, args)
        updates.update(voice_updates)
        env.update(voice_env)
    bgm = resource("bgm")
    if bgm:
        if include_voice and _record(bgm).get("has_vocal") is True:
            raise BindingError(
                f"BGM 资源 {bgm['id']} 标记了有人声(has_vocal=true),解说模式下请换用纯音乐 BGM"
            )
        env["BGM_PATH"] = bgm["files"][0]["path"]
    material_env = environ.get("VIDEO_RECAP_MATERIAL_LIBRARY_DIR", "").strip()
    if (material_env and not getattr(args, "material_library_dir", None)
            and Path(material_env).expanduser().resolve() != library_root):
        raise BindingError(
            f"VIDEO_RECAP_MATERIAL_LIBRARY_DIR={material_env} 与项目的库 {library_root} 不是同一个目录;"
            "素材库与资源库共用根目录,删掉其中一处"
        )
    _check_env_conflicts(env, environ)
    _check_env_conflicts(
        {name: updates[key] for key, name in (("mimo_tts_voice", "MIMO_TTS_VOICE"), ("voice_ref", "VOICE_REF"))
         if key in updates},
        environ,
    )
    _check_arg_conflicts(updates, args)
    return {
        "path": str(path),
        "name": project.get("name", ""),
        "library": str(library_root),
        "env": env,
        "arg_updates": updates,
        "templates": used_templates,
        "packaging": packaging and {"record": _record(packaging), "resources": resources},
        "production_reference": reference,
    }


def apply_project(resolved, args, environ=None) -> None:
    """Write the resolved settings where the stage skills will read them."""
    environ = os.environ if environ is None else environ
    for key, value in resolved["env"].items():
        environ[key] = value
    bound = set()
    for key, value in resolved["arg_updates"].items():
        if getattr(args, key, None) != value:
            bound.add(key)
        setattr(args, key, value)
    if not getattr(args, "material_library_dir", None):
        args.material_library_dir = resolved["library"]
        bound.add("material_library_dir")
    args._bound_from_project = frozenset(bound)
    args.resolved_project = resolved


def check_canvas(resolved, width, height) -> None:
    """Templates only apply to the canvas they were calibrated on."""
    for template in resolved["templates"]:
        if template["role"] not in GEOMETRY_ROLES:  # a production reference carries no geometry
            continue
        canvas = template["canvas"]
        if (canvas["width"], canvas["height"]) != (width, height):
            raise BindingError(
                f"{template['role']} 模板 {template['id']}@v{template['version']} 按 "
                f"{canvas['width']}x{canvas['height']} 校准,成片画布是 {width}x{height};换一个同画幅的模板"
            )


PACKAGING_LAYERS = "packaging_layers.json"
PACKAGING_PLAN = "packaging_plan.json"
REFERENCE_COPY = "production_reference.json"
_WRITTEN_BY = "video-recap --project"


def _ours(data) -> bool:
    return isinstance(data, dict) and data.get("written_by") == _WRITTEN_BY


def _sync_bound_file(work_dir, name, payload) -> None:
    """Write ``payload`` with our marker, or retire our old copy when nothing is bound.

    A caller-authored file (no ``written_by`` marker) is never deleted.
    """
    path = Path(work_dir) / name
    if payload is None:
        if path.exists() and _ours(read_json_object(path)):
            path.unlink()
        return
    # The marker goes last so a payload key of the same name can never unmark our copy.
    path.write_text(json.dumps({**payload, "written_by": _WRITTEN_BY}, ensure_ascii=False, indent=2),
                    encoding="utf-8")


def sync_packaging_layers(work_dir, resolved) -> None:
    """Write the bound packaging template's layers / studio_plan for assemble.py, or retire our old copy."""
    packaging = (resolved or {}).get("packaging")
    if not packaging:
        _sync_bound_file(work_dir, PACKAGING_LAYERS, None)
        _sync_bound_file(work_dir, PACKAGING_PLAN, None)
        return
    record, resources = packaging["record"], packaging["resources"]
    raw_layers = record["params"].get("layers") or []
    if raw_layers:
        layers = [{"name": layer["name"],
                   "path": resources[layer["image"]["resource"]]["files"][0]["path"],
                   "rect": layer["rect"]}
                  for layer in raw_layers]
        _sync_bound_file(work_dir, PACKAGING_LAYERS, {
            "template": {"id": record["id"], "version": record["version"]},
            "canvas": record["canvas"],
            "layers": layers,
        })
    else:
        _sync_bound_file(work_dir, PACKAGING_LAYERS, None)

    studio_plan = record["params"].get("studio_plan")
    if isinstance(studio_plan, dict):
        plan_path = Path(work_dir) / PACKAGING_PLAN
        if plan_path.exists():
            current = read_json_object(plan_path)
            if not _ours(current):
                cur_canvas = (current or {}).get("canvas")
                if isinstance(cur_canvas, dict) and (
                    cur_canvas.get("width"), cur_canvas.get("height")
                ) != (record["canvas"]["width"], record["canvas"]["height"]):
                    raise BindingError(
                        f"{plan_path} 的画布与绑定的包装模板 {record['id']}@v{record['version']} 冲突"
                    )
                return
        _sync_bound_file(work_dir, PACKAGING_PLAN, {
            "schema": "video-recap.packaging_plan.v1",
            "template": {"id": record["id"], "version": record["version"]},
            "canvas": record["canvas"],
            **studio_plan,
        })
    else:
        _sync_bound_file(work_dir, PACKAGING_PLAN, None)


def sync_production_reference(work_dir, resolved) -> None:
    """Hand the bound reference to the writing agent before its first pause; no script reads it.

    A caller's own copy is never rewritten: identical to the binding it is left as is, different
    from it is a conflict, like any other setting.
    """
    bound = (resolved or {}).get("production_reference")
    path = Path(work_dir) / REFERENCE_COPY
    if bound and path.exists():
        current = read_json_object(path)
        if not _ours(current):
            if current == bound["payload"]:
                return
            template = bound["template"]
            raise BindingError(f"{path} 不是 --project 写的,与绑定的 {template['id']}@v{template['version']} "
                               "不同;删掉其中一处")
    _sync_bound_file(work_dir, REFERENCE_COPY,
                     bound and {**bound["payload"], "template": bound["template"]})


def bound_reference_note(work_dir, resolved=None) -> str | None:
    """The pause-banner line for the bound reference in work_dir (our copy or the caller's identical one)."""
    data = read_json_object(Path(work_dir) / REFERENCE_COPY)
    bound = (resolved or {}).get("production_reference")
    if _ours(data):
        template = data.get("template") or {}
    elif bound and data == bound["payload"]:
        template = bound["template"]
    else:
        return None
    return f"本轮带制作参考 {template.get('id')}@v{template.get('version')}(可选,取舍写入 reference_methods)"
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 196kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 196kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 196kUpdated Claude CodeCodexVerifiedInstall