File size: 10,470 Bytes
57b7d38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
"""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())