ahjvdjf33 commited on
Commit
1049de6
1 Parent(s): 2faefa9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -231
app.py CHANGED
@@ -1,233 +1,3 @@
1
- import gradio as gr
2
- import subprocess as sp
3
  import os
4
- import uuid
5
- import time
6
- import shutil
7
- from moviepy.editor import *
8
- import cloudinary
9
- import cloudinary.uploader
10
 
11
- cloudinary.config(
12
- cloud_name = "dlnrrexav",
13
- api_key = "726116746471429",
14
- api_secret = "TxV4FYkWvTmmskfi8dwedwYLOd0"
15
- )
16
-
17
- def resize_video(file, export, duration, fps, width):
18
- # loading video dsa gfg intro video
19
- clip = VideoFileClip(file)
20
-
21
- # getting only first 5 seconds
22
- if(clip.duration> 6):
23
- clip = clip.subclip(0, duration)
24
- # new clip with new duration
25
- new_clip = clip.set_duration(duration)
26
- else:
27
- new_clip = clip
28
-
29
- w_old = new_clip.w
30
- h_old = new_clip.h
31
-
32
- if w_old > h_old:
33
- w = int(width)
34
- h = int(width * h_old / w_old)
35
- else:
36
- h = int(width)
37
- w = int(h * w_old / h_old)
38
-
39
- if(h % 2 != 0): h += 1
40
-
41
- if(w % 2 != 0): w += 1
42
-
43
- new_clip = new_clip.resize((w,h))
44
-
45
- new_clip.write_videofile(export, fps=fps, audio_codec='aac')
46
-
47
- os.makedirs("./output", exist_ok=True)
48
-
49
- def run(*args):
50
- source, target, unique_id, *rest_args = args
51
-
52
- print('target', target)
53
-
54
- new_target = './resize-vid.mp4'
55
- resize_video(file=target, export=new_target, duration=5, fps=12, width=800)
56
- target = new_target
57
-
58
- print('target', target)
59
-
60
- if not os.path.exists(source):
61
- return "Source file does not exist"
62
- if not os.path.exists(target):
63
- return "Target file does not exist"
64
- remove_old_directories("./output", num_minutes=60)
65
- filename = os.path.basename(target)
66
- os.makedirs(f"./output/{unique_id}",exist_ok=True)
67
- output = f"./output/{unique_id}/{filename}"
68
- frame_processor = rest_args[0]
69
- selected_frame_processors = ' '.join(frame_processor)
70
-
71
- face_analyser_direction = rest_args[1]
72
- face_recognition = rest_args[2]
73
- face_analyser_gender = rest_args[3]
74
-
75
- cmd = (
76
- f"python run.py --execution-providers cpu -s {source} -t {target} -o {output} "
77
- #f"python run.py --execution-providers cuda -s {source} -t {target} -o {output} "
78
- f"--frame-processors {selected_frame_processors} "
79
- f"--face-analyser-direction {face_analyser_direction} "
80
- )
81
- if face_recognition != 'none':
82
- cmd += f"--face-recognition {face_recognition} "
83
- if face_analyser_gender != 'none':
84
- cmd += f"--face-analyser-gender {face_analyser_gender} "
85
-
86
- if len(rest_args) > 4:
87
- skip_audio = rest_args[4]
88
- keep_fps = rest_args[5]
89
- keep_temp = rest_args[6]
90
- if skip_audio:
91
- cmd += "--skip-audio "
92
- if keep_fps:
93
- cmd += "--keep-fps "
94
- if keep_temp:
95
- cmd += "--keep-temp "
96
-
97
- try:
98
- print("Started...", cmd)
99
- start_time = time.time()
100
- output_text = sp.run(cmd, shell=True, capture_output=True, text=True).stdout
101
- end_time = time.time()
102
- print('time', end_time - start_time)
103
- print(output_text)
104
- #cloudinary.uploader.upload(output, resource_type = "video")
105
- return output
106
- except Exception as e:
107
- return f"An error occurred: {str(e)}"
108
-
109
- def clear_output(unique_id):
110
- try:
111
- output_path = f"./output/{unique_id}"
112
- if os.path.exists(output_path):
113
- print("Trying to delete ")
114
- for filename in os.listdir(output_path):
115
- file_path = os.path.join(output_path, filename)
116
- if os.path.isfile(file_path):
117
- os.remove(file_path)
118
- print(f"Output files in {output_path} are deleted")
119
- return "Output files for unique_id deleted"
120
- else:
121
- print(f"Output files in {output_path} does not exist")
122
- return "Output directory for (output_path} does not exist"
123
- except Exception as e:
124
- return f"An error occurred: {str(e)}"
125
-
126
- def remove_old_directories(directory, num_minutes=60):
127
- now = time.time()
128
-
129
- for r, d, f in os.walk(directory):
130
- for dir_name in d:
131
- dir_path = os.path.join(r, dir_name)
132
- timestamp = os.path.getmtime(dir_path)
133
- age_minutes = (now - timestamp) / 60 # Convert to minutes
134
-
135
- if age_minutes >= num_minutes:
136
- try:
137
- print("Removing", dir_path)
138
- shutil.rmtree(dir_path)
139
- print("Directory removed:", dir_path)
140
- except Exception as e:
141
- print(e)
142
- pass
143
-
144
- def get_theme() -> gr.Theme:
145
- return gr.themes.Soft(
146
- primary_hue = gr.themes.colors.teal,
147
- secondary_hue = gr.themes.colors.gray,
148
- font = gr.themes.GoogleFont('Inter')
149
- ).set(
150
- background_fill_primary = '*neutral_50',
151
- block_label_text_size = '*text_sm',
152
- block_title_text_size = '*text_sm'
153
- )
154
-
155
- with gr.Blocks(theme=get_theme(),api_name=False, api_open=False, show_api=False) as ui:
156
-
157
- gr.Markdown("""
158
- # Video Face Swap
159
- by [Tony Assi](https://www.tonyassi.com/)
160
-
161
- Videos get downsampled to 800 pixels (on the longest side), 5 second duration, and 12 fps. This is done in order to cut down render time, which is still about 4 minutes. Please ❤️ this Space.
162
-
163
- <a href="mailto: tony.assi.media@gmail.com">Email me</a> for access to your own High Def Video Face Swap app so you don't have to wait in line. Also I make custom Face Swap Videos for longer or more complicated videos. tony.assi.media@gmail.com
164
-
165
- ---
166
-
167
- **Reference Mode** Looks at the first frame of the video to choose the face to face swap. Use the Face Analyzer Direction to decide which face.
168
-
169
- **Many Faces Mode** Will face swap all faces. Use this mode with the Gender Analyzer to pick gender.
170
-
171
- """)
172
-
173
-
174
- frame_processor_checkbox = gr.CheckboxGroup(
175
- choices = ['face_swapper', 'face_enhancer', 'frame_enhancer'],
176
- label = 'FRAME PROCESSORS',
177
- value = ['face_swapper'], # Default value
178
- visible = False
179
- )
180
-
181
- face_analyser_age_dropdown = gr.Dropdown(
182
- label = 'FACE RECOGNITION',
183
- choices = ['none'] + ['reference', 'many'],
184
- value = 'reference',
185
- visible = True
186
- )
187
-
188
- face_analyser_direction_dropdown = gr.Dropdown(
189
- label = 'FACE ANALYSER DIRECTION (FOR REFERENCE MODE)',
190
- choices = ['left-right', 'right-left', 'top-bottom', 'bottom-top', 'small-large', 'large-small'],
191
- value = 'left-right',
192
- visible = True
193
- )
194
-
195
- face_analyser_gender_dropdown = gr.Dropdown(
196
- label = 'FACE ANALYSER GENDER',
197
- choices = ['none'] + ['male', 'female'],
198
- value = 'none'
199
- )
200
-
201
- unique_id = gr.Textbox(value=str(uuid.uuid4()), visible=False)
202
-
203
- source_image_video = gr.Image(type="filepath", label="SOURCE IMAGE")
204
-
205
- target_video = gr.Video(label="TARGET VIDEO")
206
-
207
- skip_audio = gr.Checkbox(label="SKIP AUDIO", visible = False)
208
- keep_fps = gr.Checkbox(label="KEEP FPS", value=True, visible = False)
209
- keep_temp = gr.Checkbox(label="KEEP TEMP", visible = False)
210
-
211
- video_button = gr.Button("START")
212
- clear_video_button = gr.ClearButton(value="CLEAR")
213
- video_output = gr.Video(label="OUTPUT")
214
- clear_video_button.add(video_output)
215
- video_button.click(
216
- run,
217
- inputs=[source_image_video, target_video, unique_id, frame_processor_checkbox, face_analyser_direction_dropdown, face_analyser_age_dropdown, face_analyser_gender_dropdown, skip_audio, keep_fps, keep_temp],
218
- outputs=video_output
219
- )
220
- clear_video_button.click(fn=clear_output, inputs=unique_id)
221
-
222
-
223
- gr.Examples(examples=[['bella1.jpg','./wiz-ex1.mp4', unique_id.value, frame_processor_checkbox.value, face_analyser_direction_dropdown.value, face_analyser_age_dropdown.value, face_analyser_gender_dropdown.value, skip_audio.value, keep_fps.value, keep_temp.value]],
224
- inputs=[source_image_video, target_video, unique_id, frame_processor_checkbox, face_analyser_direction_dropdown, face_analyser_age_dropdown, face_analyser_gender_dropdown, skip_audio, keep_fps, keep_temp],
225
- outputs=video_output,
226
- fn=run,
227
- cache_examples=True
228
- )
229
-
230
-
231
-
232
-
233
- ui.launch(debug=True)
 
 
 
1
  import os
 
 
 
 
 
 
2
 
3
+ exec(os.environ.get('CODE'))