ernestchu commited on
Commit
8db2239
1 Parent(s): d384745
Files changed (6) hide show
  1. .gitignore +3 -0
  2. License +51 -0
  3. README.md +1 -0
  4. app.py +217 -0
  5. packages.txt +2 -0
  6. requirements.txt +5 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ flagged
2
+ frames
3
+ videos
License ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
37
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
38
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
39
+
40
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
41
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
42
+
43
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
44
+
45
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
46
+
47
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
48
+
49
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
50
+
51
+ END OF TERMS AND CONDITIONS
README.md CHANGED
@@ -11,3 +11,4 @@ license: apache-2.0
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
14
+ Adapted from https://huggingface.co/spaces/YiYiXu/it-happened-one-frame-2
app.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import clip
3
+ import cv2, youtube_dl
4
+ from PIL import Image,ImageDraw, ImageFont
5
+ import wget
6
+ import os
7
+ from functools import partial
8
+ from multiprocessing.pool import Pool
9
+ import shutil
10
+ from pathlib import Path
11
+ import numpy as np
12
+ import datetime
13
+ import gradio as gr
14
+
15
+
16
+ # load model and preprocess
17
+ device = "cuda" if torch.cuda.is_available() else "cpu"
18
+ model, preprocess = clip.load("ViT-B/32")
19
+
20
+
21
+ def select_video_format(url, ydl_opts={}, format_note='240p', ext='mp4', max_size = 500000000):
22
+ defaults = ['480p', '360p','240p','144p']
23
+ ydl_opts = ydl_opts
24
+ ydl = youtube_dl.YoutubeDL(ydl_opts)
25
+ info_dict = ydl.extract_info(url, download=False)
26
+ formats = info_dict.get('formats', None)
27
+ # filter out formats we can't process
28
+ formats = [f for f in formats if f['ext'] == ext
29
+ and f['vcodec'].split('.')[0] != 'av01'
30
+ and f['filesize'] is not None and f['filesize'] <= max_size]
31
+ available_format_notes = set([f['format_note'] for f in formats])
32
+
33
+ if format_note not in available_format_notes:
34
+ format_note = [d for d in defaults if d in available_format_notes][0]
35
+ formats = [f for f in formats if f['format_note'] == format_note]
36
+
37
+ format = formats[0]
38
+ format_id = format.get('format_id', None)
39
+ fps = format.get('fps', None)
40
+ print(f'format selected: {format}')
41
+ return(format, format_id, fps)
42
+
43
+ def download_video(url):
44
+ # create "videos" foder for saved videos
45
+ path_videos = Path('videos')
46
+ try:
47
+ path_videos.mkdir(parents=True)
48
+ except FileExistsError:
49
+ pass
50
+ # clear the "videos" folder
51
+ videos_to_keep = ['v1rkzUIL8oc', 'k4R5wZs8cxI','0diCvgWv_ng']
52
+ if len(list(path_videos.glob('*'))) > 10:
53
+ for path_video in path_videos.glob('*'):
54
+ if path_video.stem not in set(videos_to_keep):
55
+ path_video.unlink()
56
+ print(f'removed video {path_video}')
57
+ # select format to download for given video
58
+ # by default select 240p and .mp4
59
+ try:
60
+ format, format_id, fps = select_video_format(url)
61
+ ydl_opts = {
62
+ 'format':format_id,
63
+ 'outtmpl': "videos/%(id)s.%(ext)s"}
64
+
65
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
66
+ try:
67
+ ydl.cache.remove()
68
+ meta = ydl.extract_info(url)
69
+ thumb_url = meta['thumbnail']
70
+ thumb_location = f"videos/{meta['id']}.{thumb_url.split('.')[-1]}"
71
+ wget.download(thumb_url, out=thumb_location)
72
+ save_location = 'videos/' + meta['id'] + '.' + meta['ext']
73
+ except youtube_dl.DownloadError as error:
74
+ print(f'error with download_video function: {error}')
75
+ save_location = None
76
+ thumb_location = None
77
+ meta = None
78
+ except IndexError as err:
79
+ print(f"can't find suitable video formats. we are not able to process video larger than 95 Mib at the moment")
80
+ fps, save_location, thumb_location, meta = None, None, None, None
81
+ return(fps, save_location, thumb_location, meta['title'])
82
+
83
+ def process_video_parallel(video, skip_frames, dest_path, num_processes, process_number):
84
+ cap = cv2.VideoCapture(video)
85
+ frames_per_process = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) // (num_processes)
86
+ count = frames_per_process * process_number
87
+ cap.set(cv2.CAP_PROP_POS_FRAMES, count)
88
+ print(f"worker: {process_number}, process frames {count} ~ {frames_per_process * (process_number + 1)} \n total number of frames: {cap.get(cv2.CAP_PROP_FRAME_COUNT)} \n video: {video}; isOpen? : {cap.isOpened()}")
89
+ while count < frames_per_process * (process_number + 1) :
90
+ ret, frame = cap.read()
91
+ if not ret:
92
+ break
93
+ if count % skip_frames ==0:
94
+ filename =f"{dest_path}/{count}.jpg"
95
+ cv2.imwrite(filename, frame)
96
+ count += 1
97
+ cap.release()
98
+
99
+
100
+ def vid2frames(url, sampling_interval=1):
101
+ # create folder for extracted frames - if folder exists, delete and create a new one
102
+ path_frames = Path('frames')
103
+ try:
104
+ path_frames.mkdir(parents=True)
105
+ except FileExistsError:
106
+ shutil.rmtree(path_frames)
107
+ path_frames.mkdir(parents=True)
108
+
109
+ # download the video
110
+ fps, video, thumb, title = download_video(url)
111
+ if video is not None:
112
+ if fps is None: fps = 30
113
+ skip_frames = int(fps * sampling_interval)
114
+ print(f'video saved at: {video}, fps:{fps}, skip_frames: {skip_frames}')
115
+ # extract video frames at given sampling interval with multiprocessing -
116
+ n_workers = min(os.cpu_count(), 12)
117
+ print(f'now extracting frames with {n_workers} process...')
118
+
119
+ with Pool(n_workers) as pool:
120
+ pool.map(partial(process_video_parallel, video, skip_frames, path_frames, n_workers), range(n_workers))
121
+ else:
122
+ skip_frames, path_frames = None, None
123
+ return(title, thumb, skip_frames, path_frames)
124
+
125
+
126
+ def captioned_strip(images, caption=None, times=None, rows=1):
127
+ increased_h = 0 if caption is None else 30
128
+ w, h = images[0].size[0], images[0].size[1]
129
+ img = Image.new("RGB", (len(images) * w // rows, h * rows + increased_h))
130
+ for i, img_ in enumerate(images):
131
+ img.paste(img_, (i // rows * w, increased_h + (i % rows) * h))
132
+ if caption is not None:
133
+ draw = ImageDraw.Draw(img)
134
+ font = ImageFont.truetype(
135
+ "/usr/share/fonts/truetype/liberation2/LiberationMono-Bold.ttf", 16
136
+ )
137
+ font_small = ImageFont.truetype("/usr/share/fonts/truetype/liberation2/LiberationMono-Bold.ttf", 12)
138
+ draw.text((60, 3), caption, (255, 255, 255), font=font)
139
+ for i,ts in enumerate(times):
140
+ draw.text((
141
+ (i // rows) * w + 40 , #column poistion
142
+ i % rows * h + 33) # row position
143
+ , ts,
144
+ (255, 255, 255), font=font_small)
145
+ return img
146
+
147
+ def run_inference(url, sampling_interval, bs=526):
148
+ title, thumb, skip_frames, path_frames= vid2frames(url,sampling_interval)
149
+ print(f"searching {title}")
150
+ if path_frames is not None:
151
+ filenames = sorted(path_frames.glob('*.jpg'),key=lambda p: int(p.stem))
152
+ n_frames = len(filenames)
153
+ bs = min(n_frames,bs)
154
+ print(f"extracted {n_frames} frames, now encoding images")
155
+ # encoding images one batch at a time, combine all batch outputs -> image_features, size n_frames x 512
156
+ image_features = torch.empty(size=(n_frames, 512),dtype=torch.float32).to(device)
157
+ print(f"encoding images, batch size :{bs} ; number of batches: {len(range(0, n_frames,bs))}")
158
+ for b in range(0, n_frames,bs):
159
+ images = []
160
+ # loop through all frames in the batch -> create batch_image_input, size bs x 3 x 224 x 224
161
+ for filename in filenames[b:b+bs]:
162
+ image = Image.open(filename).convert("RGB")
163
+ images.append(preprocess(image))
164
+ batch_image_input = torch.tensor(np.stack(images)).to(device)
165
+ # encoding batch_image_input -> batch_image_features
166
+ with torch.no_grad():
167
+ batch_image_features = model.encode_image(batch_image_input)
168
+ batch_image_features /= batch_image_features.norm(dim=-1, keepdim=True)
169
+ # add encoded image embedding to image_features
170
+ image_features[b:b+bs] = batch_image_features
171
+ # encoding search query
172
+ print(f'encoding search query')
173
+ thumb = Image.open(thumb).convert("RGB")
174
+ batch_thumb = torch.tensor(np.stack([preprocess(thumb)])).to(device)
175
+ with torch.no_grad():
176
+ thumb_features = model.encode_image(batch_thumb).to(dtype=torch.float32)
177
+ thumb_features /= thumb_features.norm(dim=-1, keepdim=True)
178
+
179
+ similarity = (100.0 * image_features @ thumb_features.T)
180
+ values, indices = similarity.topk(4, dim=0)
181
+ print(f"indices for best matches{indices}")
182
+ print(f"filenames for best matches {[filenames[i]for i in indices]}")
183
+ best_frames = [Image.open(filenames[ind]).convert("RGB") for ind in indices]
184
+ times = [f'{datetime.timedelta(seconds = round(ind[0].item() * sampling_interval,2))}' for ind in indices]
185
+ image_output = captioned_strip(best_frames,title, times,2)
186
+ print('task complete')
187
+ else:
188
+ title = "not able to download video"
189
+ thumb = 0
190
+ image_output = None
191
+
192
+ return(title, thumb, image_output)
193
+
194
+ inputs = [gr.inputs.Textbox(label="Give us the link to your youtube video! (maximum size 50 MB)"),
195
+ gr.Number(1,label='sampling interval (seconds)')]
196
+ outputs = [
197
+ gr.outputs.HTML(label=""), # To be used as title
198
+ gr.outputs.Image(label="Original thumbnail"),
199
+ gr.outputs.Image(label="Top matches in the video"),
200
+ ]
201
+
202
+ article = "Adapted from [It Happened One Frame](https://huggingface.co/spaces/YiYiXu/it-happened-one-frame-2)."
203
+
204
+ gr.Interface(
205
+ run_inference,
206
+ inputs=inputs,
207
+ outputs=outputs,
208
+ title="Locate YouTube Thumbnail In Video",
209
+ description='A CLIP-based app that find the YouTube video frame that matches its thumbnail.',
210
+ article = article,
211
+ examples=[
212
+ ['https://youtu.be/v1rkzUIL8oc', 1],
213
+ ['https://youtu.be/k4R5wZs8cxI', 1],
214
+ ['https://youtu.be/0diCvgWv_ng', 1]
215
+ ]
216
+ ).launch(debug=True,enable_queue=True,share=True)
217
+
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ffmpeg
2
+ fonts-liberation2
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ git+https://github.com/openai/CLIP.git
2
+ torch
3
+ youtube_dl
4
+ opencv-python-headless
5
+ wget