From 421f4e20aa7813ef8dadbb07856e62bc43068eec Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Tue, 24 Nov 2026 12:45:38 +0400 Subject: [PATCH 1/3] Re-render one clip with changes from a saved recipe process now writes .recipe.json next to every clip it renders: the source video, the clip's edges, title, kept pieces, hook, quality and the render settings (captions, framing, format, fade, logo, intro and outro). The episode's words and face map go once into /.podcli/, so a re-render reads them without the transcript cache. The --json result lists each clip's recipe. podcli render renders a new version with changes, given as --set key=value (caption_style=karaoke, crop_strategy=center, bookend_fade=0.3) or --title, --start and --end. Unknown fields are refused. The new file lands at the next -N path and gets its own recipe pointing back to the previous one, so earlier versions stay. A start picked by hand turns off the sentence snap and weak-opening trim, so the clip starts where it was asked to. Kept pieces are cut to the new edges and a hook that no longer fits is dropped. --- backend/cli.py | 135 +++++++++++++++--- backend/services/clip_generator.py | 14 ++ backend/services/clip_recipe.py | 222 +++++++++++++++++++++++++++++ cli/main.go | 3 +- cli/main_test.go | 3 + tests/test_clip_recipe.py | 159 +++++++++++++++++++++ 6 files changed, 515 insertions(+), 21 deletions(-) create mode 100644 backend/services/clip_recipe.py create mode 100644 tests/test_clip_recipe.py diff --git a/backend/cli.py b/backend/cli.py index 40044b0..87fe439 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -1219,6 +1219,7 @@ def _emit_process_json(*, json_out, video_path, output_dir, quality, clips, resu "captions": captions or None, "thumbnails": result.get("thumbnail_paths") or None, "content": content or None, + "recipe": result.get("recipe_path"), } payload_clips.append({k: v for k, v in entry.items() if v is not None}) payload = { @@ -1960,6 +1961,39 @@ def _transcribe_progress(pct, msg): {idx: (lambda c=c: generate_clip_content(clip=c, transcript_segments=segments)) for idx, c in enumerate(clips)}, workers=3, ) + from services import clip_recipe + + render_settings = { + "caption_style": config.get("caption_style", "branded"), + "caption_position": config.get("caption_position", "auto"), + "caption_font_scale": config.get("caption_font_scale", 100), + "logo_position": config.get("logo_position", "top-left"), + "logo_scale": config.get("logo_scale", 1.0), + "topic": config.get("topic"), + "progress": config.get("progress"), + "brand": config.get("brand"), + "theme": config.get("style"), + "font_family": config.get("font_family"), + "crop_strategy": config.get("crop_strategy", "face"), + "format": config.get("format", "vertical"), + "logo_path": config.get("logo_path") or None, + "outro_path": config.get("outro_path") or None, + "intro_path": config.get("intro_path") or None, + "name_card": config.get("name_card"), + "motion": config.get("motion"), + "bookend_fade": config.get("bookend_fade", 0.0), + "allow_ass_fallback": config.get("allow_ass_fallback", False), + "use_ass_captions": config.get("use_ass_captions", False), + } + try: + from services.transcript_packer import compute_cache_hash as _recipe_hash + + words_path = clip_recipe.save_episode_words( + clip_recipe.episode_words_path(output_dir, _recipe_hash(video_path)), words, face_map + ) + except (OSError, TypeError, ValueError) as e: + print(f" ⚠ Clip recipes will reread the transcript cache ({e})") + words_path = None results = [] t0 = time.time() _skip_review = ( @@ -1979,35 +2013,27 @@ def _transcribe_progress(pct, msg): video_path=video_path, start_second=clip["start_second"], end_second=clip["end_second"], - caption_style=config.get("caption_style", "branded"), - caption_position=config.get("caption_position", "auto"), - caption_font_scale=config.get("caption_font_scale", 100), - logo_position=config.get("logo_position", "top-left"), - logo_scale=config.get("logo_scale", 1.0), - topic=config.get("topic"), - progress=config.get("progress"), - brand=config.get("brand"), - theme=config.get("style"), - font_family=config.get("font_family"), - crop_strategy=config.get("crop_strategy", "face"), - format=config.get("format", "vertical"), transcript_words=words, title=clip.get("title", f"clip_{i+1}"), output_dir=output_dir, - logo_path=config.get("logo_path") or None, - outro_path=config.get("outro_path") or None, - intro_path=config.get("intro_path") or None, - name_card=config.get("name_card"), - motion=config.get("motion"), - bookend_fade=config.get("bookend_fade", 0.0), keep_segments=clip.get("segments"), hook=_clip_hook(clip), face_map=face_map, - allow_ass_fallback=config.get("allow_ass_fallback", False), - use_ass_captions=config.get("use_ass_captions", False), + **render_settings, ) results.append(result) ok = True + try: + result["recipe_path"] = clip_recipe.save(clip_recipe.build( + video_path=video_path, + clip={**clip, "title": clip.get("title", f"clip_{i+1}")}, + settings=render_settings, + result=result, + words_path=words_path, + quality=quality, + )) + except (OSError, TypeError, ValueError) as e: + print(f" ⚠ recipe not saved: {e}") except Exception as e: print(f"\n ✗ {e}") results.append({"status": "error", "error": str(e)}) @@ -4162,6 +4188,59 @@ def _print_config_result(action: str, data: dict) -> None: print(f" {gray}{data.get('home')}{reset}\n") +def cmd_render(args): + """Render a new version of one clip from its recipe, with changes.""" + from services import clip_recipe + + json_out = sys.stdout + if args.json: + sys.stdout = sys.stderr + try: + changes = {} + for item in args.set or []: + key, sep, raw = item.partition("=") + if not sep: + raise ValueError(f"--set needs key=value, got {item!r}") + changes[key.strip()] = clip_recipe.parse_value(raw) + for key in ("title", "start_second", "end_second", "quality"): + value = getattr(args, key, None) + if value is not None: + changes[key] = value + recipe = clip_recipe.apply_changes(clip_recipe.load(args.recipe), changes) + print(f" Rendering {recipe.get('title')} ({recipe['start_second']:.1f}s to {recipe['end_second']:.1f}s)") + result, recipe_path = clip_recipe.render( + recipe, + output_dir=args.output, + progress_callback=lambda pct, msg: print(f" {msg} ({pct}%)") if msg else None, + ) + except (OSError, ValueError, KeyError, RuntimeError, subprocess.CalledProcessError) as e: + if args.json: + print(json.dumps({"ok": False, "error": str(e)}), file=json_out, flush=True) + else: + print(f" ✗ {e}") + sys.exit(1) + path = result.get("output_path") + base = os.path.splitext(path)[0] if path else "" + payload = { + "ok": bool(path), + "path": path, + "recipe": recipe_path, + "previous": recipe.get("output"), + "title": recipe.get("title"), + "duration": result.get("duration"), + "output_duration": result.get("output_duration"), + "start_second": result.get("start_second", recipe["start_second"]), + "end_second": result.get("end_second", recipe["end_second"]), + "crop_strategy": result.get("crop_strategy_used"), + "file_size_mb": result.get("file_size_mb"), + "captions": {k: base + "." + k for k in ("srt", "vtt") if base and os.path.exists(base + "." + k)} or None, + } + if args.json: + print(json.dumps({k: v for k, v in payload.items() if v is not None}, ensure_ascii=False), file=json_out, flush=True) + else: + print(f" ✓ {path}") + + def cmd_clips(args): """Browse and edit saved clips (.podcli/history/clips.json).""" from services.clips_history import ( @@ -5800,6 +5879,20 @@ def main(): clips_delete.add_argument("clip_id", help="Clip id (full or 8-char prefix)") clips_delete.add_argument("--yes", "-y", action="store_true", help="Skip confirmation prompt") + # ── render ── + render_p = sub.add_parser("render", help="Render a new version of one clip from its .recipe.json") + render_p.add_argument("recipe", help="The clip's .recipe.json, written next to it by process") + render_p.add_argument( + "--set", action="append", metavar="KEY=VALUE", + help="Change a setting, e.g. caption_style=karaoke, crop_strategy=center, bookend_fade=0.3 (repeatable; values are JSON when they parse)", + ) + render_p.add_argument("--title", help="New title") + render_p.add_argument("--start", dest="start_second", type=float, help="New start, seconds into the episode") + render_p.add_argument("--end", dest="end_second", type=float, help="New end, seconds into the episode") + render_p.add_argument("--quality", choices=["low", "medium", "high", "max"], help="Encode quality") + render_p.add_argument("-o", "--output", help="Output directory (default: next to the previous version)") + render_p.add_argument("--json", action="store_true", help="Write one JSON object to stdout") + # ── bake-thumbnail ── bt = sub.add_parser("bake-thumbnail", help="Composite a thumbnail PNG into a clip as an opening card") bt.add_argument("clip", help="Rendered clip (.mp4) to modify in place") @@ -5949,6 +6042,8 @@ def main(): cmd_knowledge(args) elif args.command == "clips": cmd_clips(args) + elif args.command == "render": + cmd_render(args) elif args.command == "youtube": cmd_youtube(args) elif args.command == "config": diff --git a/backend/services/clip_generator.py b/backend/services/clip_generator.py index 9ff83d2..fa26aff 100644 --- a/backend/services/clip_generator.py +++ b/backend/services/clip_generator.py @@ -375,6 +375,20 @@ def _reserve_output_path(output_dir: str, stem: str, ext: str) -> str: return candidate +def keep_existing_outputs(output_dir: str, title: str) -> None: + """Make this process skip every clip already on disk for `title`, so the + next render lands at a new `-N` path and earlier versions stay intact.""" + stem = f"{safe_filename(title)}_short" + try: + names = os.listdir(output_dir) + except OSError: + return + with _output_path_lock: + for name in names: + if name.endswith(".mp4") and (name == f"{stem}.mp4" or name.startswith(f"{stem}-")): + _reserved_output_paths.add(os.path.join(output_dir, name)) + + def _reframe_can_jump( reframe: bool, crop_strategy: str, diff --git a/backend/services/clip_recipe.py b/backend/services/clip_recipe.py new file mode 100644 index 0000000..8a6d178 --- /dev/null +++ b/backend/services/clip_recipe.py @@ -0,0 +1,222 @@ +"""Everything needed to render one clip again, saved next to the clip. + +`podcli process` writes `.recipe.json` beside every clip it renders, plus +one words file per episode under `/.podcli/`. `podcli render` reads a +recipe, applies changes, and renders a new version without touching the old +file, so an app or a person can iterate on a clip without rerunning the whole +episode. +""" + +from __future__ import annotations + +import json +import os +from typing import Any, Callable, Optional + +RECIPE_VERSION = 1 + +SETTING_KEYS = ( + "caption_style", + "caption_position", + "caption_font_scale", + "captions", + "logo_path", + "logo_position", + "logo_scale", + "intro_path", + "outro_path", + "bookend_fade", + "name_card", + "motion", + "topic", + "progress", + "brand", + "theme", + "font_family", + "crop_strategy", + "format", + "allow_ass_fallback", + "use_ass_captions", +) + +CLIP_KEYS = ("start_second", "end_second", "title", "keep_segments", "hook", "quality", "trim_opening") + + +def episode_words_path(output_dir: str, cache_hash: str) -> str: + return os.path.join(output_dir, ".podcli", f"{cache_hash}.words.json") + + +def save_episode_words(path: str, words: list, face_map: Optional[dict]) -> str: + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + json.dump({"words": words or [], "face_map": face_map}, fh, ensure_ascii=False) + return path + + +def recipe_path_for(output_path: str) -> str: + return os.path.splitext(output_path)[0] + ".recipe.json" + + +def build( + *, + video_path: str, + clip: dict, + settings: dict, + result: dict, + words_path: Optional[str], + quality: Optional[str], + previous: Optional[str] = None, +) -> dict: + return { + "version": RECIPE_VERSION, + "video": os.path.abspath(video_path), + "words": os.path.abspath(words_path) if words_path else None, + "output": os.path.abspath(result["output_path"]), + "previous": previous, + "start_second": clip["start_second"], + "end_second": clip["end_second"], + "title": clip.get("title") or "clip", + "keep_segments": clip.get("segments") or clip.get("keep_segments"), + "hook": clip.get("hook"), + "trim_opening": clip.get("trim_opening"), + "quality": quality, + "settings": {key: settings.get(key) for key in SETTING_KEYS if settings.get(key) is not None}, + } + + +def save(recipe: dict) -> str: + path = recipe_path_for(recipe["output"]) + with open(path, "w", encoding="utf-8") as fh: + json.dump(recipe, fh, ensure_ascii=False, indent=2) + return path + + +def load(path: str) -> dict: + with open(path, encoding="utf-8") as fh: + recipe = json.load(fh) + if recipe.get("version") != RECIPE_VERSION: + raise ValueError(f"{os.path.basename(path)} is recipe version {recipe.get('version')}, this podcli reads {RECIPE_VERSION}") + return recipe + + +def parse_value(raw: str) -> Any: + try: + return json.loads(raw) + except json.JSONDecodeError: + return raw + + +def apply_changes(recipe: dict, changes: dict) -> dict: + """A copy of the recipe with `changes` applied. Unknown keys are refused so a + typo never renders a clip that silently ignored the request.""" + updated = json.loads(json.dumps(recipe)) + for key, value in changes.items(): + if key in CLIP_KEYS: + updated[key] = value + elif key in SETTING_KEYS: + if value is None: + updated["settings"].pop(key, None) + else: + updated["settings"][key] = value + else: + raise ValueError(f"unknown recipe field: {key}") + if "start_second" in changes and "trim_opening" not in changes: + # A start someone picked by hand is the start they want, so the sentence + # snap and weak-opening trim stay off for this version. + updated["trim_opening"] = False + if float(updated["end_second"]) <= float(updated["start_second"]): + raise ValueError("end_second must be after start_second") + updated["keep_segments"] = _fit_segments(updated.get("keep_segments"), updated["start_second"], updated["end_second"]) + return updated + + +def _fit_segments(segments: Optional[list], start: float, end: float) -> Optional[list]: + """Trim kept pieces to the clip's new edges. A trim can cut a multi-piece + clip down to nothing kept, which renders the plain range instead.""" + if not segments: + return None + fitted = [] + for piece in segments: + a = max(float(piece["start"]), float(start)) + b = min(float(piece["end"]), float(end)) + if b - a > 0.05: + fitted.append({**piece, "start": a, "end": b}) + return fitted or None + + +def _load_words(recipe: dict) -> tuple[list, Optional[dict]]: + words_file = recipe.get("words") + if words_file and os.path.exists(words_file): + with open(words_file, encoding="utf-8") as fh: + data = json.load(fh) + return data.get("words") or [], data.get("face_map") + from services.transcript_packer import load_cached_transcript_for_video + + cached = load_cached_transcript_for_video(recipe["video"]) or {} + return cached.get("words") or [], cached.get("face_map") + + +def _valid_hook(recipe: dict) -> Optional[dict]: + if not recipe.get("hook"): + return None + from services.opening_hook import validate_hook + + try: + return validate_hook(recipe["hook"], recipe["start_second"], recipe["end_second"], recipe.get("keep_segments")) + except ValueError: + return None + + +def render( + recipe: dict, + *, + output_dir: Optional[str] = None, + progress_callback: Optional[Callable[[int, str], None]] = None, +) -> tuple[dict, str]: + """Render a new version of the clip. Returns the render result and the path + of the new version's recipe. The previous file is left in place.""" + if not os.path.exists(recipe["video"]): + raise FileNotFoundError(f"source video not found: {recipe['video']}") + if recipe.get("quality"): + os.environ["PODCLI_QUALITY"] = recipe["quality"] + from services.clip_generator import generate_clip, keep_existing_outputs + + words, face_map = _load_words(recipe) + settings = dict(recipe.get("settings") or {}) + theme = settings.pop("theme", None) + target_dir = output_dir or os.path.dirname(recipe["output"]) + os.makedirs(target_dir, exist_ok=True) + keep_existing_outputs(target_dir, recipe.get("title") or "clip") + result = generate_clip( + video_path=recipe["video"], + start_second=float(recipe["start_second"]), + end_second=float(recipe["end_second"]), + transcript_words=words, + title=recipe.get("title") or "clip", + output_dir=target_dir, + face_map=face_map, + keep_segments=recipe.get("keep_segments"), + hook=_valid_hook(recipe), + trim_opening=recipe.get("trim_opening"), + theme=theme, + progress_callback=progress_callback, + **settings, + ) + clip = { + "start_second": recipe["start_second"], + "end_second": recipe["end_second"], + "title": recipe.get("title"), + "keep_segments": recipe.get("keep_segments"), + "hook": recipe.get("hook"), + "trim_opening": recipe.get("trim_opening"), + } + next_recipe = build( + video_path=recipe["video"], + clip=clip, + settings={**settings, "theme": theme}, + result=result, + words_path=recipe.get("words"), + quality=recipe.get("quality"), + previous=recipe.get("output"), + ) + return result, save(next_recipe) diff --git a/cli/main.go b/cli/main.go index d308cd5..abe308f 100644 --- a/cli/main.go +++ b/cli/main.go @@ -105,7 +105,7 @@ func wantsRuntime(args []string) bool { return true } switch args[0] { - case "process", "transcribe", "studio", "multicam", "auto", "ui", "webui": + case "process", "render", "transcribe", "studio", "multicam", "auto", "ui", "webui": return true } return false @@ -1201,6 +1201,7 @@ Engine commands (routed to the processing backend): ui Open the Studio web dashboard (http://localhost:3847) studio