Files changed (1) hide show
  1. app.py +43 -344
app.py CHANGED
@@ -1,344 +1,43 @@
1
- from __future__ import annotations
2
- import gradio as gr
3
- import os
4
- import cv2
5
- import numpy as np
6
- from PIL import Image
7
- from moviepy.editor import *
8
- from share_btn import community_icon_html, loading_icon_html, share_js
9
-
10
- import pathlib
11
- import shlex
12
- import subprocess
13
-
14
- if os.getenv('SYSTEM') == 'spaces':
15
- with open('patch') as f:
16
- subprocess.run(shlex.split('patch -p1'), stdin=f, cwd='ControlNet')
17
-
18
- base_url = 'https://huggingface.co/lllyasviel/ControlNet/resolve/main/annotator/ckpts/'
19
-
20
- names = [
21
- 'body_pose_model.pth',
22
- 'dpt_hybrid-midas-501f0c75.pt',
23
- 'hand_pose_model.pth',
24
- 'mlsd_large_512_fp32.pth',
25
- 'mlsd_tiny_512_fp32.pth',
26
- 'network-bsds500.pth',
27
- 'upernet_global_small.pth',
28
- ]
29
-
30
- for name in names:
31
- command = f'wget https://huggingface.co/lllyasviel/ControlNet/resolve/main/annotator/ckpts/{name} -O {name}'
32
- out_path = pathlib.Path(f'ControlNet/annotator/ckpts/{name}')
33
- if out_path.exists():
34
- continue
35
- subprocess.run(shlex.split(command), cwd='ControlNet/annotator/ckpts/')
36
-
37
- from model import (DEFAULT_BASE_MODEL_FILENAME, DEFAULT_BASE_MODEL_REPO,
38
- DEFAULT_BASE_MODEL_URL, Model)
39
-
40
- model = Model()
41
-
42
-
43
- def controlnet(i, prompt, control_task, seed_in, ddim_steps, scale, low_threshold, high_threshold, value_threshold, distance_threshold, bg_threshold):
44
- img= Image.open(i)
45
- np_img = np.array(img)
46
-
47
- a_prompt = "best quality, extremely detailed"
48
- n_prompt = "longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality"
49
- num_samples = 1
50
- image_resolution = 512
51
- detect_resolution = 512
52
- eta = 0.0
53
- #low_threshold = 100
54
- #high_threshold = 200
55
- #value_threshold = 0.1
56
- #distance_threshold = 0.1
57
- #bg_threshold = 0.4
58
-
59
- if control_task == 'Canny':
60
- result = model.process_canny(np_img, prompt, a_prompt, n_prompt, num_samples,
61
- image_resolution, ddim_steps, scale, seed_in, eta, low_threshold, high_threshold)
62
- elif control_task == 'Depth':
63
- result = model.process_depth(np_img, prompt, a_prompt, n_prompt, num_samples,
64
- image_resolution, detect_resolution, ddim_steps, scale, seed_in, eta)
65
- elif control_task == 'Hed':
66
- result = model.process_hed(np_img, prompt, a_prompt, n_prompt, num_samples,
67
- image_resolution, detect_resolution, ddim_steps, scale, seed_in, eta)
68
- elif control_task == 'Hough':
69
- result = model.process_hough(np_img, prompt, a_prompt, n_prompt, num_samples,
70
- image_resolution, detect_resolution, ddim_steps, scale, seed_in, eta, value_threshold,
71
- distance_threshold)
72
- elif control_task == 'Normal':
73
- result = model.process_normal(np_img, prompt, a_prompt, n_prompt, num_samples,
74
- image_resolution, detect_resolution, ddim_steps, scale, seed_in, eta, bg_threshold)
75
- elif control_task == 'Pose':
76
- result = model.process_pose(np_img, prompt, a_prompt, n_prompt, num_samples,
77
- image_resolution, detect_resolution, ddim_steps, scale, seed_in, eta)
78
- elif control_task == 'Scribble':
79
- result = model.process_scribble(np_img, prompt, a_prompt, n_prompt, num_samples,
80
- image_resolution, ddim_steps, scale, seed_in, eta)
81
- elif control_task == 'Seg':
82
- result = model.process_seg(np_img, prompt, a_prompt, n_prompt, num_samples,
83
- image_resolution, detect_resolution, ddim_steps, scale, seed_in, eta)
84
-
85
- #print(result[0])
86
- processor_im = Image.fromarray(result[0])
87
- processor_im.save("process_" + control_task + "_" + str(i) + ".jpeg")
88
- im = Image.fromarray(result[1])
89
- im.save("your_file" + str(i) + ".jpeg")
90
- return "your_file" + str(i) + ".jpeg", "process_" + control_task + "_" + str(i) + ".jpeg"
91
-
92
- def change_task_options(task):
93
- if task == "Canny" :
94
- return canny_opt.update(visible=True), hough_opt.update(visible=False), normal_opt.update(visible=False)
95
- elif task == "Hough" :
96
- return canny_opt.update(visible=False),hough_opt.update(visible=True), normal_opt.update(visible=False)
97
- elif task == "Normal" :
98
- return canny_opt.update(visible=False),hough_opt.update(visible=False), normal_opt.update(visible=True)
99
- else :
100
- return canny_opt.update(visible=False),hough_opt.update(visible=False), normal_opt.update(visible=False)
101
-
102
- def get_frames(video_in):
103
- frames = []
104
- #resize the video
105
- clip = VideoFileClip(video_in)
106
-
107
- #check fps
108
- if clip.fps > 30:
109
- print("vide rate is over 30, resetting to 30")
110
- clip_resized = clip.resize(height=512)
111
- clip_resized.write_videofile("video_resized.mp4", fps=30)
112
- else:
113
- print("video rate is OK")
114
- clip_resized = clip.resize(height=512)
115
- clip_resized.write_videofile("video_resized.mp4", fps=clip.fps)
116
-
117
- print("video resized to 512 height")
118
-
119
- # Opens the Video file with CV2
120
- cap= cv2.VideoCapture("video_resized.mp4")
121
-
122
- fps = cap.get(cv2.CAP_PROP_FPS)
123
- print("video fps: " + str(fps))
124
- i=0
125
- while(cap.isOpened()):
126
- ret, frame = cap.read()
127
- if ret == False:
128
- break
129
- cv2.imwrite('kang'+str(i)+'.jpg',frame)
130
- frames.append('kang'+str(i)+'.jpg')
131
- i+=1
132
-
133
- cap.release()
134
- cv2.destroyAllWindows()
135
- print("broke the video into frames")
136
-
137
- return frames, fps
138
-
139
-
140
- def convert(gif):
141
- if gif != None:
142
- clip = VideoFileClip(gif.name)
143
- clip.write_videofile("my_gif_video.mp4")
144
- return "my_gif_video.mp4"
145
- else:
146
- pass
147
-
148
-
149
- def create_video(frames, fps, type):
150
- print("building video result")
151
- clip = ImageSequenceClip(frames, fps=fps)
152
- clip.write_videofile(type + "_result.mp4", fps=fps)
153
-
154
- return type + "_result.mp4"
155
-
156
-
157
- def infer(prompt,video_in, control_task, seed_in, trim_value, ddim_steps, scale, low_threshold, high_threshold, value_threshold, distance_threshold, bg_threshold, gif_import):
158
- print(f"""
159
- ———————————————
160
- {prompt}
161
- ———————————————""")
162
-
163
- # 1. break video into frames and get FPS
164
- break_vid = get_frames(video_in)
165
- frames_list= break_vid[0]
166
- fps = break_vid[1]
167
- n_frame = int(trim_value*fps)
168
-
169
- if n_frame >= len(frames_list):
170
- print("video is shorter than the cut value")
171
- n_frame = len(frames_list)
172
-
173
- # 2. prepare frames result arrays
174
- processor_result_frames = []
175
- result_frames = []
176
- print("set stop frames to: " + str(n_frame))
177
-
178
- for i in frames_list[0:int(n_frame)]:
179
- controlnet_img = controlnet(i, prompt,control_task, seed_in, ddim_steps, scale, low_threshold, high_threshold, value_threshold, distance_threshold, bg_threshold)
180
- #images = controlnet_img[0]
181
- #rgb_im = images[0].convert("RGB")
182
-
183
- # exporting the image
184
- #rgb_im.save(f"result_img-{i}.jpg")
185
- processor_result_frames.append(controlnet_img[1])
186
- result_frames.append(controlnet_img[0])
187
- print("frame " + i + "/" + str(n_frame) + ": done;")
188
-
189
- processor_vid = create_video(processor_result_frames, fps, "processor")
190
- final_vid = create_video(result_frames, fps, "final")
191
-
192
- files = [processor_vid, final_vid]
193
- if gif_import != None:
194
- final_gif = VideoFileClip(final_vid)
195
- final_gif.write_gif("final_result.gif")
196
- final_gif = "final_result.gif"
197
-
198
- files.append(final_gif)
199
- print("finished !")
200
-
201
- return final_vid, gr.Accordion.update(visible=True), gr.Video.update(value=processor_vid, visible=True), gr.File.update(value=files, visible=True), gr.Group.update(visible=True)
202
-
203
-
204
- def clean():
205
- return gr.Accordion.update(visible=False),gr.Video.update(value=None, visible=False), gr.Video.update(value=None), gr.File.update(value=None, visible=False), gr.Group.update(visible=False)
206
-
207
- title = """
208
- <div style="text-align: center; max-width: 700px; margin: 0 auto;">
209
- <div
210
- style="
211
- display: inline-flex;
212
- align-items: center;
213
- gap: 0.8rem;
214
- font-size: 1.75rem;
215
- "
216
- >
217
- <h1 style="font-weight: 900; margin-bottom: 7px; margin-top: 5px;">
218
- ControlNet Video
219
- </h1>
220
- </div>
221
- <p style="margin-bottom: 10px; font-size: 94%">
222
- Apply ControlNet to a video
223
- </p>
224
- </div>
225
- """
226
-
227
- article = """
228
-
229
- <div class="footer">
230
- <p>
231
- Follow <a href="https://twitter.com/fffiloni" target="_blank">Sylvain Filoni</a> for future updates 🤗
232
- </p>
233
- </div>
234
- <div id="may-like-container" style="display: flex;justify-content: center;flex-direction: column;align-items: center;margin-bottom: 30px;">
235
- <p>You may also like: </p>
236
- <div id="may-like-content" style="display:flex;flex-wrap: wrap;align-items:center;height:20px;">
237
-
238
- <svg height="20" width="148" style="margin-left:4px;margin-bottom: 6px;">
239
- <a href="https://huggingface.co/spaces/fffiloni/Pix2Pix-Video" target="_blank">
240
- <image href="https://img.shields.io/badge/🤗 Spaces-Pix2Pix_Video-blue" src="https://img.shields.io/badge/🤗 Spaces-Pix2Pix_Video-blue.png" height="20"/>
241
- </a>
242
- </svg>
243
-
244
- </div>
245
-
246
- </div>
247
-
248
- """
249
-
250
- with gr.Blocks(css='style.css') as demo:
251
- with gr.Column(elem_id="col-container"):
252
- gr.HTML(title)
253
- gr.HTML("""
254
- <a style="display:inline-block" href="https://huggingface.co/spaces/fffiloni/ControlNet-Video?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a>
255
- """, elem_id="duplicate-container")
256
- with gr.Row():
257
- with gr.Column():
258
- video_inp = gr.Video(label="Video source", source="upload", type="filepath", elem_id="input-vid")
259
- video_out = gr.Video(label="ControlNet video result", elem_id="video-output")
260
-
261
- with gr.Group(elem_id="share-btn-container", visible=False) as share_group:
262
- community_icon = gr.HTML(community_icon_html)
263
- loading_icon = gr.HTML(loading_icon_html)
264
- share_button = gr.Button("Share to community", elem_id="share-btn")
265
-
266
- with gr.Accordion("Detailed results", visible=False) as detailed_result:
267
- prep_video_out = gr.Video(label="Preprocessor video result", visible=False, elem_id="prep-video-output")
268
- files = gr.File(label="Files can be downloaded ;)", visible=False)
269
-
270
- with gr.Column():
271
- #status = gr.Textbox()
272
-
273
- prompt = gr.Textbox(label="Prompt", placeholder="enter prompt", show_label=True, elem_id="prompt-in")
274
-
275
- with gr.Row():
276
- control_task = gr.Dropdown(label="Control Task", choices=["Canny", "Depth", "Hed", "Hough", "Normal", "Pose", "Scribble", "Seg"], value="Pose", multiselect=False, elem_id="controltask-in")
277
- seed_inp = gr.Slider(label="Seed", minimum=0, maximum=2147483647, step=1, value=123456, elem_id="seed-in")
278
-
279
- with gr.Row():
280
- trim_in = gr.Slider(label="Cut video at (s)", minimun=1, maximum=5, step=1, value=1)
281
-
282
- with gr.Accordion("Advanced Options", open=False):
283
- with gr.Tab("Diffusion Settings"):
284
- with gr.Row(visible=False) as canny_opt:
285
- low_threshold = gr.Slider(label='Canny low threshold', minimum=1, maximum=255, value=100, step=1)
286
- high_threshold = gr.Slider(label='Canny high threshold', minimum=1, maximum=255, value=200, step=1)
287
-
288
- with gr.Row(visible=False) as hough_opt:
289
- value_threshold = gr.Slider(label='Hough value threshold (MLSD)', minimum=0.01, maximum=2.0, value=0.1, step=0.01)
290
- distance_threshold = gr.Slider(label='Hough distance threshold (MLSD)', minimum=0.01, maximum=20.0, value=0.1, step=0.01)
291
-
292
- with gr.Row(visible=False) as normal_opt:
293
- bg_threshold = gr.Slider(label='Normal background threshold', minimum=0.0, maximum=1.0, value=0.4, step=0.01)
294
-
295
- ddim_steps = gr.Slider(label='Steps', minimum=1, maximum=100, value=20, step=1)
296
- scale = gr.Slider(label='Guidance Scale', minimum=0.1, maximum=30.0, value=9.0, step=0.1)
297
-
298
- with gr.Tab("GIF import"):
299
- gif_import = gr.File(label="import a GIF instead", file_types=['.gif'])
300
- gif_import.change(convert, gif_import, video_inp, queue=False)
301
-
302
- with gr.Tab("Custom Model"):
303
- current_base_model = gr.Text(label='Current base model',
304
- value=DEFAULT_BASE_MODEL_URL)
305
- with gr.Row():
306
- with gr.Column():
307
- base_model_repo = gr.Text(label='Base model repo',
308
- max_lines=1,
309
- placeholder=DEFAULT_BASE_MODEL_REPO,
310
- interactive=True)
311
- base_model_filename = gr.Text(
312
- label='Base model file',
313
- max_lines=1,
314
- placeholder=DEFAULT_BASE_MODEL_FILENAME,
315
- interactive=True)
316
- change_base_model_button = gr.Button('Change base model')
317
-
318
- gr.HTML(
319
- '''<p>You can use other base models by specifying the repository name and filename.<br />
320
- The base model must be compatible with Stable Diffusion v1.5.</p>''')
321
-
322
- change_base_model_button.click(fn=model.set_base_model,
323
- inputs=[
324
- base_model_repo,
325
- base_model_filename,
326
- ],
327
- outputs=current_base_model, queue=False)
328
-
329
- submit_btn = gr.Button("Generate ControlNet video")
330
-
331
- inputs = [prompt,video_inp,control_task, seed_inp, trim_in, ddim_steps, scale, low_threshold, high_threshold, value_threshold, distance_threshold, bg_threshold, gif_import]
332
- outputs = [video_out, detailed_result, prep_video_out, files, share_group]
333
- #outputs = [status]
334
-
335
-
336
- gr.HTML(article)
337
- control_task.change(change_task_options, inputs=[control_task], outputs=[canny_opt, hough_opt, normal_opt], queue=False)
338
- submit_btn.click(clean, inputs=[], outputs=[detailed_result, prep_video_out, video_out, files, share_group], queue=False)
339
- submit_btn.click(infer, inputs, outputs)
340
- share_button.click(None, [], [], _js=share_js)
341
-
342
-
343
-
344
- demo.queue(max_size=12).launch()
 
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name = 'phenaki-pytorch',
5
+ packages = find_packages(exclude=[]),
6
+ version = '0.3.0',
7
+ license='MIT',
8
+ description = 'Phenaki - Pytorch',
9
+ author = 'Phil Wang',
10
+ author_email = 'lucidrains@gmail.com',
11
+ long_description_content_type = 'text/markdown',
12
+ url = 'https://github.com/lucidrains/phenaki-pytorch',
13
+ keywords = [
14
+ 'artificial intelligence',
15
+ 'deep learning',
16
+ 'transformers',
17
+ 'attention mechanisms',
18
+ 'text-to-video'
19
+ ],
20
+ install_requires=[
21
+ 'accelerate',
22
+ 'beartype',
23
+ 'einops>=0.6',
24
+ 'ema-pytorch>=0.1.1',
25
+ 'opencv-python',
26
+ 'pillow',
27
+ 'numpy',
28
+ 'sentencepiece',
29
+ 'torch>=1.6',
30
+ 'torchtyping',
31
+ 'torchvision',
32
+ 'transformers>=4.20.1',
33
+ 'tqdm',
34
+ 'vector-quantize-pytorch>=0.10.15'
35
+ ],
36
+ classifiers=[
37
+ 'Development Status :: 4 - Beta',
38
+ 'Intended Audience :: Developers',
39
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
40
+ 'License :: OSI Approved :: MIT License',
41
+ 'Programming Language :: Python :: 3.6',
42
+ ],
43
+ )