Spaces:
Runtime error
Runtime error
Update utils.py
Browse files
utils.py
CHANGED
@@ -1,36 +1,51 @@
|
|
|
|
1 |
from pytube import YouTube
|
2 |
import numpy as np
|
3 |
-
from decord import VideoReader
|
4 |
import imageio
|
5 |
|
6 |
|
7 |
def download_youtube_video(url: str):
|
8 |
yt = YouTube(url)
|
9 |
|
10 |
-
streams = yt.streams.filter(file_extension=
|
11 |
file_path = streams[0].download()
|
12 |
return file_path
|
13 |
|
14 |
|
15 |
-
def
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
|
21 |
-
return indices
|
22 |
-
|
23 |
-
|
24 |
-
def sample_frames_from_video_file(file_path: str, num_frames: int = 16):
|
25 |
-
videoreader = VideoReader(file_path, num_threads=1, ctx=cpu(0))
|
26 |
|
27 |
# sample frames
|
28 |
-
|
29 |
-
|
|
|
30 |
frames = videoreader.get_batch(indices).asnumpy()
|
|
|
31 |
return frames
|
32 |
|
33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
converted_frames = frames.astype(np.uint8)
|
35 |
-
|
36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pathlib import Path
|
2 |
from pytube import YouTube
|
3 |
import numpy as np
|
4 |
+
from decord import VideoReader
|
5 |
import imageio
|
6 |
|
7 |
|
8 |
def download_youtube_video(url: str):
|
9 |
yt = YouTube(url)
|
10 |
|
11 |
+
streams = yt.streams.filter(file_extension="mp4")
|
12 |
file_path = streams[0].download()
|
13 |
return file_path
|
14 |
|
15 |
|
16 |
+
def sample_frames_from_video_file(
|
17 |
+
file_path: str, num_frames: int = 16, frame_sampling_rate=1
|
18 |
+
):
|
19 |
+
videoreader = VideoReader(file_path)
|
20 |
+
videoreader.seek(0)
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
# sample frames
|
23 |
+
start_idx = 0
|
24 |
+
end_idx = num_frames * frame_sampling_rate - 1
|
25 |
+
indices = np.linspace(start_idx, end_idx, num=num_frames, dtype=np.int64)
|
26 |
frames = videoreader.get_batch(indices).asnumpy()
|
27 |
+
|
28 |
return frames
|
29 |
|
30 |
+
|
31 |
+
def get_num_total_frames(file_path: str):
|
32 |
+
videoreader = VideoReader(file_path)
|
33 |
+
videoreader.seek(0)
|
34 |
+
return len(videoreader)
|
35 |
+
|
36 |
+
|
37 |
+
def convert_frames_to_gif(frames, save_path: str = "frames.gif"):
|
38 |
converted_frames = frames.astype(np.uint8)
|
39 |
+
Path(save_path).parent.mkdir(parents=True, exist_ok=True)
|
40 |
+
imageio.mimsave(save_path, converted_frames, fps=8)
|
41 |
+
return save_path
|
42 |
+
|
43 |
+
|
44 |
+
def create_gif_from_video_file(
|
45 |
+
file_path: str,
|
46 |
+
num_frames: int = 16,
|
47 |
+
frame_sampling_rate: int = 1,
|
48 |
+
save_path: str = "frames.gif",
|
49 |
+
):
|
50 |
+
frames = sample_frames_from_video_file(file_path, num_frames, frame_sampling_rate)
|
51 |
+
return convert_frames_to_gif(frames, save_path)
|