DStardust commited on
Commit
a1ec2be
·
verified ·
1 Parent(s): 7860d25

Update scripts/reconstruct_media.py

Browse files
Files changed (1) hide show
  1. scripts/reconstruct_media.py +61 -45
scripts/reconstruct_media.py CHANGED
@@ -9,31 +9,12 @@ from __future__ import annotations
9
 
10
  import argparse
11
  import csv
12
- import subprocess
13
  from pathlib import Path
14
 
15
 
16
  VIDEO_EXTENSIONS = (".mp4", ".mov", ".mkv", ".avi", ".webm")
17
 
18
 
19
- def build_resize_filter(mode: str, width: str, height: str) -> str:
20
- w = int(width)
21
- h = int(height)
22
- if mode == "stretch":
23
- return f"scale={w}:{h}"
24
- if mode == "pad_to_square":
25
- return (
26
- f"scale={w}:{h}:force_original_aspect_ratio=decrease,"
27
- f"pad={w}:{h}:(ow-iw)/2:(oh-ih)/2"
28
- )
29
- if mode == "center_crop":
30
- return (
31
- f"scale={w}:{h}:force_original_aspect_ratio=increase,"
32
- f"crop={w}:{h}:(iw-{w})/2:(ih-{h})/2"
33
- )
34
- raise ValueError(f"Unsupported resize_mode: {mode}")
35
-
36
-
37
  def find_source_video(source_root: Path, source_dataset: str, source_video_id: str) -> Path:
38
  dataset_root = source_root / source_dataset
39
  candidates = []
@@ -49,7 +30,58 @@ def find_source_video(source_root: Path, source_dataset: str, source_video_id: s
49
  )
50
 
51
 
52
- def reconstruct_row(row: dict[str, str], source_root: Path, output_root: Path, dry_run: bool) -> None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  if row.get("source_dataset") == "Self-recorded":
54
  return
55
  input_video = find_source_video(source_root, row["source_dataset"], row["source_video_id"])
@@ -59,33 +91,12 @@ def reconstruct_row(row: dict[str, str], source_root: Path, output_root: Path, d
59
  output_path = output_root / rel_output
60
  output_path.parent.mkdir(parents=True, exist_ok=True)
61
 
62
- resize_filter = build_resize_filter(
63
- row.get("resize_mode", "stretch"),
64
- row["target_width"],
65
- row["target_height"],
66
- )
67
- command = ["ffmpeg", "-y"]
68
- start = row.get("source_start_sec", "").strip()
69
- end = row.get("source_end_sec", "").strip()
70
- if start:
71
- command.extend(["-ss", start])
72
- if end:
73
- command.extend(["-to", end])
74
- command.extend(
75
- [
76
- "-i",
77
- str(input_video),
78
- "-vf",
79
- resize_filter,
80
- "-r",
81
- row.get("fps", "4"),
82
- "-an",
83
- str(output_path),
84
- ]
85
  )
86
- print(" ".join(command))
87
  if not dry_run:
88
- subprocess.run(command, check=True)
89
 
90
 
91
  def main() -> int:
@@ -98,8 +109,13 @@ def main() -> int:
98
 
99
  source_root = Path(args.source_root)
100
  output_root = Path(args.output_root)
 
101
  with Path(args.manifest).open(newline="", encoding="utf-8") as handle:
102
  for row in csv.DictReader(handle):
 
 
 
 
103
  reconstruct_row(row, source_root, output_root, args.dry_run)
104
  return 0
105
 
 
9
 
10
  import argparse
11
  import csv
 
12
  from pathlib import Path
13
 
14
 
15
  VIDEO_EXTENSIONS = (".mp4", ".mov", ".mkv", ".avi", ".webm")
16
 
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  def find_source_video(source_root: Path, source_dataset: str, source_video_id: str) -> Path:
19
  dataset_root = source_root / source_dataset
20
  candidates = []
 
30
  )
31
 
32
 
33
+ def reconstruct_with_opencv(row: dict[str, str], input_video: Path, output_path: Path) -> None:
34
+ try:
35
+ import cv2
36
+ except ImportError as exc:
37
+ raise RuntimeError(
38
+ "OpenCV is required for reconstruction. Install opencv-python."
39
+ ) from exc
40
+
41
+ fps = float(row.get("fps", "4"))
42
+ width = int(row["target_width"])
43
+ height = int(row["target_height"])
44
+ cap = cv2.VideoCapture(str(input_video))
45
+ if not cap.isOpened():
46
+ raise RuntimeError(f"Failed to open source video: {input_video}")
47
+
48
+ try:
49
+ raw_fps = cap.get(cv2.CAP_PROP_FPS)
50
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
51
+ duration = frame_count / raw_fps if raw_fps > 0 else 0
52
+ target_frame_count = int(duration * fps)
53
+ if target_frame_count <= 0:
54
+ raise RuntimeError(f"Invalid target frame count for {input_video}")
55
+
56
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
57
+ writer = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
58
+ if not writer.isOpened():
59
+ raise RuntimeError(f"Failed to open output video writer: {output_path}")
60
+ try:
61
+ for i in range(target_frame_count):
62
+ target_time = i / fps
63
+ raw_frame_idx = int(round(target_time * raw_fps))
64
+ if raw_frame_idx >= frame_count:
65
+ raw_frame_idx = frame_count - 1
66
+ cap.set(cv2.CAP_PROP_POS_FRAMES, raw_frame_idx)
67
+ success, frame = cap.read()
68
+ if not success:
69
+ continue
70
+ if frame.shape[1] != width or frame.shape[0] != height:
71
+ frame = cv2.resize(frame, (width, height))
72
+ writer.write(frame)
73
+ finally:
74
+ writer.release()
75
+ finally:
76
+ cap.release()
77
+
78
+
79
+ def reconstruct_row(
80
+ row: dict[str, str],
81
+ source_root: Path,
82
+ output_root: Path,
83
+ dry_run: bool,
84
+ ) -> None:
85
  if row.get("source_dataset") == "Self-recorded":
86
  return
87
  input_video = find_source_video(source_root, row["source_dataset"], row["source_video_id"])
 
91
  output_path = output_root / rel_output
92
  output_path.parent.mkdir(parents=True, exist_ok=True)
93
 
94
+ print(
95
+ f"opencv {input_video} -> {output_path} "
96
+ f"resize={row['target_width']}x{row['target_height']} fps={row.get('fps', '4')}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  )
 
98
  if not dry_run:
99
+ reconstruct_with_opencv(row, input_video, output_path)
100
 
101
 
102
  def main() -> int:
 
109
 
110
  source_root = Path(args.source_root)
111
  output_root = Path(args.output_root)
112
+ seen_outputs: set[str] = set()
113
  with Path(args.manifest).open(newline="", encoding="utf-8") as handle:
114
  for row in csv.DictReader(handle):
115
+ output_key = row.get("expected_local_output_path", "")
116
+ if output_key in seen_outputs:
117
+ continue
118
+ seen_outputs.add(output_key)
119
  reconstruct_row(row, source_root, output_root, args.dry_run)
120
  return 0
121