Shad0ws fcakyon commited on
Commit
15343a3
·
0 Parent(s):

Duplicate from fcakyon/zero-shot-video-classification

Browse files

Co-authored-by: Fatih <[email protected]>

Files changed (5) hide show
  1. .gitattributes +31 -0
  2. README.md +12 -0
  3. app.py +168 -0
  4. requirements.txt +6 -0
  5. utils.py +51 -0
.gitattributes ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.model filter=lfs diff=lfs merge=lfs -text
11
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
12
+ *.npy filter=lfs diff=lfs merge=lfs -text
13
+ *.npz filter=lfs diff=lfs merge=lfs -text
14
+ *.onnx filter=lfs diff=lfs merge=lfs -text
15
+ *.ot filter=lfs diff=lfs merge=lfs -text
16
+ *.parquet filter=lfs diff=lfs merge=lfs -text
17
+ *.pickle filter=lfs diff=lfs merge=lfs -text
18
+ *.pkl filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pt filter=lfs diff=lfs merge=lfs -text
21
+ *.pth filter=lfs diff=lfs merge=lfs -text
22
+ *.rar filter=lfs diff=lfs merge=lfs -text
23
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
25
+ *.tflite filter=lfs diff=lfs merge=lfs -text
26
+ *.tgz filter=lfs diff=lfs merge=lfs -text
27
+ *.wasm filter=lfs diff=lfs merge=lfs -text
28
+ *.xz filter=lfs diff=lfs merge=lfs -text
29
+ *.zip filter=lfs diff=lfs merge=lfs -text
30
+ *.zst filter=lfs diff=lfs merge=lfs -text
31
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Zero Shot Video Classification
3
+ emoji: 🔥
4
+ colorFrom: blue
5
+ colorTo: pink
6
+ sdk: gradio
7
+ sdk_version: 3.12.0
8
+ app_file: app.py
9
+ pinned: true
10
+ license: apache-2.0
11
+ duplicated_from: fcakyon/zero-shot-video-classification
12
+ ---
app.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ from transformers import AutoProcessor, AutoModel
4
+ from utils import (
5
+ convert_frames_to_gif,
6
+ download_youtube_video,
7
+ get_num_total_frames,
8
+ sample_frames_from_video_file,
9
+ )
10
+
11
+ FRAME_SAMPLING_RATE = 4
12
+ DEFAULT_MODEL = "microsoft/xclip-base-patch16-zero-shot"
13
+
14
+ VALID_ZEROSHOT_VIDEOCLASSIFICATION_MODELS = [
15
+ "microsoft/xclip-base-patch32",
16
+ "microsoft/xclip-base-patch16-zero-shot",
17
+ "microsoft/xclip-base-patch16-kinetics-600",
18
+ "microsoft/xclip-large-patch14ft/xclip-base-patch32-16-frames",
19
+ "microsoft/xclip-large-patch14",
20
+ "microsoft/xclip-base-patch16-hmdb-4-shot",
21
+ "microsoft/xclip-base-patch16-16-frames",
22
+ "microsoft/xclip-base-patch16-hmdb-2-shot",
23
+ "microsoft/xclip-base-patch16-ucf-2-shot",
24
+ "microsoft/xclip-base-patch16-ucf-8-shot",
25
+ "microsoft/xclip-base-patch16",
26
+ "microsoft/xclip-base-patch16-hmdb-8-shot",
27
+ "microsoft/xclip-base-patch16-hmdb-16-shot",
28
+ "microsoft/xclip-base-patch16-ucf-16-shot",
29
+ ]
30
+
31
+ processor = AutoProcessor.from_pretrained(DEFAULT_MODEL)
32
+ model = AutoModel.from_pretrained(DEFAULT_MODEL)
33
+
34
+ examples = [
35
+ [
36
+ "https://www.youtu.be/l1dBM8ZECao",
37
+ "sleeping dog,cat fight club,birds of prey",
38
+ ],
39
+ [
40
+ "https://youtu.be/VMj-3S1tku0",
41
+ "programming course,eating spaghetti,playing football",
42
+ ],
43
+ [
44
+ "https://youtu.be/BRw7rvLdGzU",
45
+ "game of thrones,the lord of the rings,vikings",
46
+ ],
47
+ ]
48
+
49
+
50
+ def select_model(model_name):
51
+ global processor, model
52
+ processor = AutoProcessor.from_pretrained(model_name)
53
+ model = AutoModel.from_pretrained(model_name)
54
+
55
+
56
+ def predict(youtube_url_or_file_path, labels_text):
57
+
58
+ if youtube_url_or_file_path.startswith("http"):
59
+ video_path = download_youtube_video(youtube_url_or_file_path)
60
+ else:
61
+ video_path = youtube_url_or_file_path
62
+
63
+ # rearrange sampling rate based on video length and model input length
64
+ num_total_frames = get_num_total_frames(video_path)
65
+ num_model_input_frames = model.config.vision_config.num_frames
66
+ if num_total_frames < FRAME_SAMPLING_RATE * num_model_input_frames:
67
+ frame_sampling_rate = num_total_frames // num_model_input_frames
68
+ else:
69
+ frame_sampling_rate = FRAME_SAMPLING_RATE
70
+
71
+ labels = labels_text.split(",")
72
+
73
+ frames = sample_frames_from_video_file(
74
+ video_path, num_model_input_frames, frame_sampling_rate
75
+ )
76
+ gif_path = convert_frames_to_gif(frames, save_path="video.gif")
77
+
78
+ inputs = processor(
79
+ text=labels, videos=list(frames), return_tensors="pt", padding=True
80
+ )
81
+ # forward pass
82
+ with torch.no_grad():
83
+ outputs = model(**inputs)
84
+
85
+ probs = outputs.logits_per_video[0].softmax(dim=-1).cpu().numpy()
86
+ label_to_prob = {}
87
+ for ind, label in enumerate(labels):
88
+ label_to_prob[label] = float(probs[ind])
89
+
90
+ return label_to_prob, gif_path
91
+
92
+
93
+ app = gr.Blocks()
94
+ with app:
95
+ gr.Markdown(
96
+ "# **<p align='center'>Zero-shot Video Classification with 🤗 Transformers</p>**"
97
+ )
98
+ gr.Markdown(
99
+ """
100
+ <p style='text-align: center'>
101
+ Follow me for more!
102
+ <br> <a href='https://twitter.com/fcakyon' target='_blank'>twitter</a> | <a href='https://github.com/fcakyon' target='_blank'>github</a> | <a href='https://www.linkedin.com/in/fcakyon/' target='_blank'>linkedin</a> | <a href='https://fcakyon.medium.com/' target='_blank'>medium</a>
103
+ </p>
104
+ """
105
+ )
106
+
107
+ with gr.Row():
108
+ with gr.Column():
109
+ model_names_dropdown = gr.Dropdown(
110
+ choices=VALID_ZEROSHOT_VIDEOCLASSIFICATION_MODELS,
111
+ label="Model:",
112
+ show_label=True,
113
+ value=DEFAULT_MODEL,
114
+ )
115
+ model_names_dropdown.change(fn=select_model, inputs=model_names_dropdown)
116
+ with gr.Tab(label="Youtube URL"):
117
+ gr.Markdown(
118
+ "### **Provide a Youtube video URL and a list of labels separated by commas**"
119
+ )
120
+ youtube_url = gr.Textbox(label="Youtube URL:", show_label=True)
121
+ youtube_url_labels_text = gr.Textbox(
122
+ label="Labels Text:", show_label=True
123
+ )
124
+ youtube_url_predict_btn = gr.Button(value="Predict")
125
+ with gr.Tab(label="Local File"):
126
+ gr.Markdown(
127
+ "### **Upload a video file and provide a list of labels separated by commas**"
128
+ )
129
+ video_file = gr.Video(label="Video File:", show_label=True)
130
+ local_video_labels_text = gr.Textbox(
131
+ label="Labels Text:", show_label=True
132
+ )
133
+ local_video_predict_btn = gr.Button(value="Predict")
134
+ with gr.Column():
135
+ video_gif = gr.Image(
136
+ label="Input Clip",
137
+ show_label=True,
138
+ )
139
+ with gr.Column():
140
+ predictions = gr.Label(label="Predictions:", show_label=True)
141
+
142
+ gr.Markdown("**Examples:**")
143
+ gr.Examples(
144
+ examples,
145
+ [youtube_url, youtube_url_labels_text],
146
+ [predictions, video_gif],
147
+ fn=predict,
148
+ cache_examples=True,
149
+ )
150
+
151
+ youtube_url_predict_btn.click(
152
+ predict,
153
+ inputs=[youtube_url, youtube_url_labels_text],
154
+ outputs=[predictions, video_gif],
155
+ )
156
+ local_video_predict_btn.click(
157
+ predict,
158
+ inputs=[video_file, local_video_labels_text],
159
+ outputs=[predictions, video_gif],
160
+ )
161
+ gr.Markdown(
162
+ """
163
+ \n Demo created by: <a href=\"https://github.com/fcakyon\">fcakyon</a>.
164
+ <br> Based on this <a href=\"https://huggingface.co/docs/transformers/main/model_doc/xclip">HuggingFace model</a>.
165
+ """
166
+ )
167
+
168
+ app.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio
2
+ torch
3
+ decord
4
+ pytube
5
+ imageio
6
+ transformers @ git+https://github.com/huggingface/transformers.git@799cea64ac1029d66e9e58f18bc6f47892270723
utils.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)