Andyson commited on
Commit
d263724
·
verified ·
1 Parent(s): 1f6c0f5

Upload videos_zip_two_refiners/scripts/concat_video_chunks.py with huggingface_hub

Browse files
videos_zip_two_refiners/scripts/concat_video_chunks.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Concatenate MP4 chunks by decoding and re-encoding with PyAV."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ from fractions import Fraction
9
+ from pathlib import Path
10
+
11
+ import av
12
+
13
+
14
+ def concat_videos(inputs: list[Path], output_path: Path, fps: float) -> int:
15
+ if not inputs:
16
+ raise ValueError("No input chunks to concatenate")
17
+
18
+ first = av.open(str(inputs[0]))
19
+ try:
20
+ first_stream = first.streams.video[0]
21
+ width = first_stream.width
22
+ height = first_stream.height
23
+ finally:
24
+ first.close()
25
+
26
+ output_path.parent.mkdir(parents=True, exist_ok=True)
27
+ container = av.open(str(output_path), "w")
28
+ success = False
29
+ frame_count = 0
30
+ try:
31
+ output_fps = round(fps)
32
+ time_base = Fraction(1, output_fps)
33
+ stream = container.add_stream("libx264", rate=output_fps, options={"crf": "19", "preset": "veryfast"})
34
+ stream.width = width
35
+ stream.height = height
36
+ stream.pix_fmt = "yuv420p"
37
+ stream.time_base = time_base
38
+ stream.codec_context.thread_count = 0
39
+ stream.codec_context.thread_type = "FRAME"
40
+
41
+ for input_path in inputs:
42
+ chunk = av.open(str(input_path))
43
+ try:
44
+ video_stream = chunk.streams.video[0]
45
+ if video_stream.width != width or video_stream.height != height:
46
+ raise ValueError(
47
+ f"Chunk {input_path} is {video_stream.width}x{video_stream.height}, "
48
+ f"expected {width}x{height}"
49
+ )
50
+ for frame in chunk.decode(video_stream):
51
+ frame = frame.reformat(width=width, height=height, format="yuv420p")
52
+ frame.pts = frame_count
53
+ frame.time_base = time_base
54
+ for packet in stream.encode(frame):
55
+ container.mux(packet)
56
+ frame_count += 1
57
+ finally:
58
+ chunk.close()
59
+
60
+ for packet in stream.encode():
61
+ container.mux(packet)
62
+ success = True
63
+ finally:
64
+ container.close()
65
+ if not success:
66
+ output_path.unlink(missing_ok=True)
67
+ return frame_count
68
+
69
+
70
+ def main() -> None:
71
+ parser = argparse.ArgumentParser()
72
+ parser.add_argument("--output", required=True)
73
+ parser.add_argument("--fps", type=float, required=True)
74
+ parser.add_argument("inputs", nargs="+")
75
+ args = parser.parse_args()
76
+
77
+ frames = concat_videos([Path(p) for p in args.inputs], Path(args.output), args.fps)
78
+ print(json.dumps({"frames": frames}))
79
+
80
+
81
+ if __name__ == "__main__":
82
+ main()