multimodalart HF Staff commited on
Commit
82416f7
·
verified ·
1 Parent(s): db0cf7d

Add PyAV video reader module

Browse files
Files changed (1) hide show
  1. video_av_reader.py +72 -0
video_av_reader.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyAV-based video reader for qwen-vl-utils.
2
+
3
+ The Space runtime ships torchvision >= 0.28, which removed
4
+ `torchvision.io.read_video` — the only decoder qwen-vl-utils 0.0.14 can call
5
+ without extra system libraries (torchcodec needs system FFmpeg shared libs;
6
+ decord has no cp310 wheels). PyAV wheels bundle their own FFmpeg, so this
7
+ reader reproduces qwen-vl-utils' official torchvision backend exactly:
8
+
9
+ * frame-count/average-fps metadata from the container stream,
10
+ * `smart_nframes` for the sampled-frame count (fps 2.0, min 4 / max 20,
11
+ floor to factor 2 — identical because we reuse their own function),
12
+ * `torch.linspace(0, total - 1, nframes).round().long()` index selection,
13
+ * `sample_fps = nframes / total * video_fps`,
14
+ * `video_metadata` dict with fps / frames_indices / total_num_frames.
15
+
16
+ `fetch_video` then handles smart_resize/BICUBIC/antialias exactly as before —
17
+ only the decode step is swapped, via `VIDEO_READER_BACKENDS["torchvision"]`.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import time
23
+ from typing import Any, Dict, Tuple
24
+
25
+ import av
26
+ import torch
27
+
28
+
29
+ def read_video_pyav(ele: Dict[str, Any]) -> Tuple[torch.Tensor, Dict[str, Any], float]:
30
+ """Decode a video with PyAV, returning (TCHW uint8 tensor, metadata, sample_fps).
31
+
32
+ Mirrors `qwen_vl_utils.vision_process._read_video_torchvision`.
33
+ """
34
+ from qwen_vl_utils.vision_process import smart_nframes
35
+
36
+ video_path = ele["video"]
37
+ started = time.time()
38
+ with av.open(video_path) as container:
39
+ stream = container.streams.video[0]
40
+ total_frames = stream.frames
41
+ video_fps = float(stream.average_rate) if stream.average_rate else 0.0
42
+ if not total_frames: # some containers don't report a frame count
43
+ total_frames = sum(1 for _ in container.decode(video=0))
44
+ container.seek(0)
45
+
46
+ nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
47
+ idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
48
+ sample_fps = nframes / max(total_frames, 1e-6) * video_fps
49
+
50
+ wanted = set(idx)
51
+ frames = []
52
+ for position, frame in enumerate(container.decode(video=0)):
53
+ if position > idx[-1]:
54
+ break
55
+ if position in wanted:
56
+ # to_ndarray(format="rgb24") -> HWC uint8, matching read_video
57
+ array = frame.to_ndarray(format="rgb24")
58
+ frames.append(torch.from_numpy(array).permute(2, 0, 1))
59
+ video = torch.stack(frames).contiguous()
60
+
61
+ if video.shape[0] != nframes: # truncated file: pad by repeating the last frame
62
+ pad = torch.stack([video[-1]] * (nframes - video.shape[0]))
63
+ video = torch.cat([video, pad])
64
+
65
+ metadata = {
66
+ "fps": video_fps,
67
+ "frames_indices": idx,
68
+ "total_num_frames": total_frames,
69
+ "video_backend": "pyav",
70
+ }
71
+ print(f"pyav: decoded {video.shape[0]} frames of {total_frames} in {time.time() - started:.2f}s", flush=True)
72
+ return video, metadata, sample_fps