"""Repair missing character crops. Reads each video's existing character_crops/meta/*.json files, re-extracts the referenced frames from the source video using the SAME ffmpeg parameters originally used (scene_threshold + scale_width), then re-creates only the crops that are currently missing on disk. Uses a more permissive minimum-side policy than the main pipeline so crops from lower-resolution sources survive. Existing crops are left untouched. """ import argparse import json import shutil import subprocess import sys from pathlib import Path from PIL import Image def discover_source_videos(source_dir: Path) -> dict[str, Path]: """Build a stem -> source video path index for fast lookup.""" patterns = ("*.mp4", "*.mkv", "*.mov", "*.avi", "*.webm") found: dict[str, Path] = {} for pattern in patterns: for video in source_dir.rglob(pattern): found.setdefault(video.stem, video) return found def extract_frames(video: Path, output_dir: Path, scene_threshold: float, scale_width: int) -> None: """Re-run the same ffmpeg select used by the pipeline so frame indices align.""" output_dir.mkdir(parents=True, exist_ok=True) vf_parts = [f"select='gt(scene,{scene_threshold})'"] if scale_width > 0: vf_parts.append(f"scale={scale_width}:-2") vf = ",".join(vf_parts) cmd = [ "ffmpeg", "-hide_banner", "-loglevel", "warning", "-i", str(video), "-vf", vf, "-fps_mode", "vfr", "-y", "-compression_level", "0", str(output_dir / "%08d.png"), ] subprocess.run(cmd, check=True) def gather_missing(meta_dir: Path, crops_dir: Path) -> tuple[dict[str, list[dict]], int]: """Return {frame_name: [detection_dict, ...]} for crops missing from disk, plus a count of crops already present.""" by_frame: dict[str, list[dict]] = {} already_present = 0 for meta_file in sorted(meta_dir.glob("*.json")): try: with meta_file.open("r", encoding="utf-8") as fp: meta = json.load(fp) except (OSError, json.JSONDecodeError) as exc: print(f" Skipping malformed meta {meta_file.name}: {exc}", file=sys.stderr) continue frame_name = meta.get("frame") if not frame_name: continue for det in meta.get("detections", []): crop_filename = det.get("file") if not crop_filename or "crop_box" not in det: continue if (crops_dir / crop_filename).exists(): already_present += 1 else: by_frame.setdefault(frame_name, []).append(det) return by_frame, already_present def restore_one( crop_path: Path, src_frame: Image.Image, crop_box: list[int], min_side: int, max_side: int, ) -> str: x1, y1, x2, y2 = (int(round(v)) for v in crop_box) crop = src_frame.crop((x1, y1, x2, y2)) width, height = crop.size if width <= 0 or height <= 0: return "invalid_box" if min(width, height) < min_side: return "too_small" # Optional ceiling on the long side; default behaviour preserves the original size. if max_side > 0 and max(width, height) > max_side: scale = max_side / max(width, height) crop = crop.resize( (max(1, int(round(width * scale))), max(1, int(round(height * scale)))), Image.Resampling.LANCZOS, ) crop.save(crop_path, compress_level=0) return "ok" def repair_video( video_dir: Path, source_video: Path, scene_threshold: float, scale_width: int, min_side: int, max_side: int, ) -> dict[str, object]: crops_dir = video_dir / "character_crops" meta_dir = crops_dir / "meta" if not meta_dir.exists(): return {"status": "no_meta"} by_frame, already_present = gather_missing(meta_dir, crops_dir) missing_total = sum(len(v) for v in by_frame.values()) if missing_total == 0: return {"status": "all_present", "already_present": already_present} temp_frames = video_dir / "_repair_frames" if temp_frames.exists(): shutil.rmtree(temp_frames) print(f" Need {missing_total} crop(s) across {len(by_frame)} frame(s); re-extracting...") try: extract_frames(source_video, temp_frames, scene_threshold, scale_width) except subprocess.CalledProcessError as exc: shutil.rmtree(temp_frames, ignore_errors=True) return {"status": "ffmpeg_failed", "error": str(exc)} restored = 0 skipped_small = 0 no_frame = 0 invalid = 0 failed = 0 try: for frame_name, dets in sorted(by_frame.items()): frame_path = temp_frames / frame_name if not frame_path.exists(): no_frame += len(dets) continue try: with Image.open(frame_path) as src: src_rgb = src.convert("RGB") for det in dets: crop_path = crops_dir / det["file"] try: result = restore_one( crop_path, src_rgb, det["crop_box"], min_side, max_side, ) except Exception as exc: print(f" Failed {det['file']}: {exc}", file=sys.stderr) failed += 1 continue if result == "ok": restored += 1 elif result == "too_small": skipped_small += 1 elif result == "invalid_box": invalid += 1 except Exception as exc: print(f" Failed to open {frame_name}: {exc}", file=sys.stderr) failed += len(dets) finally: shutil.rmtree(temp_frames, ignore_errors=True) return { "status": "ok", "already_present": already_present, "restored": restored, "skipped_too_small": skipped_small, "missing_source_frame": no_frame, "invalid_box": invalid, "failed": failed, } def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Repair missing character crops by re-extracting from source video.") parser.add_argument("--source-dir", required=True, help="Directory containing source videos (scanned recursively).") parser.add_argument("--output-root", required=True, help="Root directory holding per-video output subdirs.") parser.add_argument( "--target", default=None, help="Restrict to this single subdir name (e.g. \"[P3]xxx\"). If omitted, every subdir with a meta dir is processed.", ) parser.add_argument( "--scene-threshold", type=float, default=0.08, help="MUST match the scene-threshold used in the original extraction (frame indices align deterministically).", ) parser.add_argument( "--scale-width", type=int, default=0, help="MUST match the original extraction. 0 = no scaling (matches the user's pipeline default).", ) parser.add_argument( "--min-side", type=int, default=512, help="Drop a restored crop only if its shortest side is below this many pixels.", ) parser.add_argument( "--max-side", type=int, default=0, help="Optional ceiling on the longest side; 0 = preserve original resolution.", ) return parser.parse_args() def main() -> int: args = parse_args() source_dir = Path(args.source_dir) output_root = Path(args.output_root) if not source_dir.exists(): print(f"Source dir not found: {source_dir}", file=sys.stderr) return 2 if not output_root.exists(): print(f"Output root not found: {output_root}", file=sys.stderr) return 2 if args.target: targets = [output_root / args.target] else: targets = sorted( d for d in output_root.iterdir() if d.is_dir() and (d / "character_crops" / "meta").exists() ) if not targets: print("No targets found.", file=sys.stderr) return 1 source_index = discover_source_videos(source_dir) if not source_index: print(f"No source videos discovered under {source_dir}", file=sys.stderr) return 2 summary: list[dict] = [] total_restored = 0 for i, target in enumerate(targets, start=1): print(f"[{i}/{len(targets)}] {target.name}") if not target.exists(): print(f" Subdir does not exist: {target}") summary.append({"target": target.name, "status": "missing_subdir"}) continue source_video = source_index.get(target.name) if source_video is None: print(f" No source video matches stem '{target.name}'") summary.append({"target": target.name, "status": "no_source"}) continue try: result = repair_video( video_dir=target, source_video=source_video, scene_threshold=args.scene_threshold, scale_width=args.scale_width, min_side=args.min_side, max_side=args.max_side, ) except Exception as exc: print(f" Repair failed: {exc}", file=sys.stderr) summary.append({"target": target.name, "status": "error", "error": str(exc)}) continue print(f" -> {result}") summary.append({"target": target.name, **result}) if isinstance(result.get("restored"), int): total_restored += result["restored"] print(f"\nDone. Total restored: {total_restored}") report = output_root / "repair_report.json" try: with report.open("w", encoding="utf-8") as fp: json.dump({"summary": summary, "total_restored": total_restored}, fp, ensure_ascii=False, indent=2) print(f"Report: {report}") except OSError as exc: print(f"Could not write report: {exc}", file=sys.stderr) return 0 if __name__ == "__main__": raise SystemExit(main())