imseldrith 0Scottzilla0 commited on
Commit
b062617
·
verified ·
1 Parent(s): 327fa2d

Update app.py (#2)

Browse files

- Update app.py (a57ed4682be746df61032f8ddafc3cac7917a29a)


Co-authored-by: Scott Copeland <[email protected]>

Files changed (1) hide show
  1. app.py +172 -131
app.py CHANGED
@@ -5,163 +5,204 @@ import uuid
5
  import time
6
  import shutil
7
 
8
- os.makedirs("./output", exist_ok=True)
9
-
10
- def run(*args):
11
- source, target, unique_id, *rest_args = args
12
- if not os.path.exists(source):
13
- return "Source file does not exist"
14
- if not os.path.exists(target):
15
- return "Target file does not exist"
16
- remove_old_directories("./output", num_minutes=60)
17
- filename = os.path.basename(target)
18
- os.makedirs(f"./output/{unique_id}",exist_ok=True)
19
- output = f"./output/{unique_id}/{filename}"
20
- frame_processor = rest_args[0]
21
- selected_frame_processors = ' '.join(frame_processor)
22
-
23
- face_analyser_direction = rest_args[1]
24
- face_recognition = rest_args[2]
25
- face_analyser_gender = rest_args[3]
26
-
27
- cmd = (
28
- f"python run.py --execution-providers cpu -s {source} -t {target} -o {output} "
29
- f"--frame-processors {selected_frame_processors} "
30
- f"--face-analyser-direction {face_analyser_direction} "
31
- )
32
- if face_recognition != 'none':
33
- cmd += f"--face-recognition {face_recognition} "
34
- if face_analyser_gender != 'none':
35
- cmd += f"--face-analyser-gender {face_analyser_gender} "
36
-
37
- if len(rest_args) > 4:
38
- skip_audio = rest_args[4]
39
- keep_fps = rest_args[5]
40
- keep_temp = rest_args[6]
41
- if skip_audio:
42
- cmd += "--skip-audio "
43
- if keep_fps:
44
- cmd += "--keep-fps "
45
- if keep_temp:
46
- cmd += "--keep-temp "
47
-
48
- try:
49
- print("Started...", cmd)
50
- output_text = sp.run(cmd, shell=True, capture_output=True, text=True).stdout
51
- print(output_text)
52
- return output
53
- except Exception as e:
54
- return f"An error occurred: {str(e)}"
55
-
56
- def clear_output(unique_id):
57
- try:
58
- output_path = f"./output/{unique_id}"
59
- if os.path.exists(output_path):
60
- print("Trying to delete ")
61
- for filename in os.listdir(output_path):
62
- file_path = os.path.join(output_path, filename)
63
- if os.path.isfile(file_path):
64
- os.remove(file_path)
65
- print(f"Output files in {output_path} are deleted")
66
- return "Output files for unique_id deleted"
67
- else:
68
- print(f"Output files in {output_path} does not exist")
69
- return "Output directory for (output_path} does not exist"
70
- except Exception as e:
71
- return f"An error occurred: {str(e)}"
72
-
73
- def remove_old_directories(directory, num_minutes=60):
74
- now = time.time()
75
-
76
- for r, d, f in os.walk(directory):
77
- for dir_name in d:
78
- dir_path = os.path.join(r, dir_name)
79
- timestamp = os.path.getmtime(dir_path)
80
- age_minutes = (now - timestamp) / 60 # Convert to minutes
81
-
82
- if age_minutes >= num_minutes:
83
- try:
84
- print("Removing", dir_path)
85
- shutil.rmtree(dir_path)
86
- print("Directory removed:", dir_path)
87
- except Exception as e:
88
- print(e)
89
- pass
90
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- def get_theme() -> gr.Theme:
93
- return gr.themes.Soft(
94
- primary_hue = gr.themes.colors.red,
95
- secondary_hue = gr.themes.colors.gray,
96
- font = gr.themes.GoogleFont('Inter')
97
- ).set(
98
- background_fill_primary = '*neutral_50',
99
- block_label_text_size = '*text_sm',
100
- block_title_text_size = '*text_sm'
101
- )
102
 
103
- with gr.Blocks(theme=get_theme(), title="DeepFakeAI 1.0.0") as ui:
 
104
  with gr.Group():
105
  gr.HTML('<center><a href="https://codegenius.me">DeepFakeAI 1.0.1</a></center>')
106
-
107
  with gr.Group():
108
  with gr.Column(scale=3):
109
- frame_processor_checkbox = gr.CheckboxGroup(
110
- choices = ['face_swapper', 'face_enhancer', 'frame_enhancer'],
111
- label = 'FRAME PROCESSORS',
112
- value = ['face_swapper'] # Default value
113
- )
114
-
115
 
116
  with gr.Group():
117
  with gr.Column(scale=3):
118
- face_analyser_direction_dropdown = gr.Dropdown(
119
- label = 'FACE ANALYSER DIRECTION',
120
- choices = ['left-right', 'right-left', 'top-bottom', 'bottom-top', 'small-large', 'large-small'],
121
- value = 'left-right'
122
- )
123
- face_analyser_age_dropdown = gr.Dropdown(
124
- label = 'FACE RECOGNITION',
125
- choices = ['none'] + ['reference', 'many'],
126
- value = 'reference'
127
- )
128
- face_analyser_gender_dropdown = gr.Dropdown(
129
- label = 'FACE ANALYSER GENDER',
130
- choices = ['none'] + ['male', 'female'],
131
- value = 'none'
132
- )
133
- unique_id = gr.Textbox(value=str(uuid.uuid4()), visible=False)
134
- with gr.Tab("Image: "):
135
  source_image = gr.Image(type="filepath", label="SOURCE IMAGE")
136
- target_image = gr.Image(type="filepath", label="TARGET IMAGE")
137
  image_button = gr.Button("START")
138
  clear_button = gr.ClearButton(value="CLEAR")
139
- image_output = gr.Image(label="OUTPUT")
140
  clear_button.add(image_output)
141
-
142
  image_button.click(
143
- run,
144
- inputs=[source_image, target_image, unique_id, frame_processor_checkbox, face_analyser_direction_dropdown, face_analyser_age_dropdown, face_analyser_gender_dropdown],
145
  outputs=image_output
146
  )
147
- clear_button.click(fn=clear_output, inputs=unique_id)
148
-
149
- with gr.Tab("Video: "):
150
  source_image_video = gr.Image(type="filepath", label="SOURCE IMAGE")
151
- target_video = gr.Video(label="TARGET VIDEO")
152
  with gr.Group():
153
  skip_audio = gr.Checkbox(label="SKIP AUDIO")
154
  keep_fps = gr.Checkbox(label="KEEP FPS")
155
  keep_temp = gr.Checkbox(label="KEEP TEMP")
156
  video_button = gr.Button("START")
157
  clear_video_button = gr.ClearButton(value="CLEAR")
158
- video_output = gr.Video(label="OUTPUT")
159
  clear_video_button.add(video_output)
160
  video_button.click(
161
- run,
162
- 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],
163
  outputs=video_output
164
  )
165
- clear_video_button.click(fn=clear_output, inputs=unique_id)
166
 
167
  ui.launch(debug=True)
 
5
  import time
6
  import shutil
7
 
8
+ # Constants
9
+ OUTPUT_DIR = './output'
10
+ NUM_MINUTES = 60
11
+
12
+ # Create output directory if it doesn't exist
13
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
14
+
15
+ class DeepFakeAI:
16
+ def __init__(self):
17
+ # Initialize the frame processor checkbox
18
+ self.frame_processor_checkbox = gr.CheckboxGroup(
19
+ choices=['face_swapper', 'face_enhancer', 'frame_enhancer'],
20
+ label='FRAME PROCESSORS',
21
+ value=['face_swapper'] # Default value
22
+ )
23
+
24
+ # Initialize the face analyser direction dropdown
25
+ self.face_analyser_direction_dropdown = gr.Dropdown(
26
+ label='FACE ANALYSER DIRECTION',
27
+ choices=['left-right', 'right-left', 'top-bottom', 'bottom-top', 'small-large', 'large-small'],
28
+ value='left-right'
29
+ )
30
+
31
+ # Initialize the face analyser age dropdown
32
+ self.face_analyser_age_dropdown = gr.Dropdown(
33
+ label='FACE RECOGNITION',
34
+ choices=['none'] + ['reference', 'many'],
35
+ value='reference'
36
+ )
37
+
38
+ # Initialize the face analyser gender dropdown
39
+ self.face_analyser_gender_dropdown = gr.Dropdown(
40
+ label='FACE ANALYSER GENDER',
41
+ choices=['none'] + ['male', 'female'],
42
+ value='none'
43
+ )
44
+
45
+ # Initialize the unique id textbox
46
+ self.unique_id = gr.Textbox(value=str(uuid.uuid4()), visible=False)
47
+
48
+ def run(self, *args):
49
+ # Unpack input arguments
50
+ source, target, unique_id, *rest_args = args
51
+
52
+ # Check if source and target files exist
53
+ if not os.path.exists(source):
54
+ return "Source file does not exist"
55
+ if not os.path.exists(target):
56
+ return "Target file does not exist"
57
+
58
+ # Remove old directories
59
+ self.remove_old_directories(OUTPUT_DIR, NUM_MINUTES)
60
+
61
+ # Get filename and create output directory
62
+ filename = os.path.basename(target)
63
+ output_dir = os.path.join(OUTPUT_DIR, unique_id)
64
+ os.makedirs(output_dir, exist_ok=True)
65
+ output = os.path.join(output_dir, filename)
66
+
67
+ # Get frame processor and face analyser settings
68
+ frame_processor = rest_args[0]
69
+ selected_frame_processors = ' '.join(frame_processor)
70
+ face_analyser_direction = rest_args[1]
71
+ face_recognition = rest_args[2]
72
+ face_analyser_gender = rest_args[3]
73
+
74
+ # Construct command to run
75
+ cmd = [
76
+ 'python', 'run.py',
77
+ '--execution-providers', 'cpu',
78
+ '-s', source,
79
+ '-t', target,
80
+ '-o', output,
81
+ '--frame-processors', selected_frame_processors,
82
+ '--face-analyser-direction', face_analyser_direction
83
+ ]
84
+ if face_recognition != 'none':
85
+ cmd.extend(['--face-recognition', face_recognition])
86
+ if face_analyser_gender != 'none':
87
+ cmd.extend(['--face-analyser-gender', face_analyser_gender])
88
+
89
+ # Add additional flags if present
90
+ if len(rest_args) > 4:
91
+ skip_audio = rest_args[4]
92
+ keep_fps = rest_args[5]
93
+ keep_temp = rest_args[6]
94
+ if skip_audio:
95
+ cmd.append('--skip-audio')
96
+ if keep_fps:
97
+ cmd.append('--keep-fps')
98
+ if keep_temp:
99
+ cmd.append('--keep-temp')
100
+
101
+ try:
102
+ print("Started...", cmd)
103
+ output_text = sp.run(cmd, capture_output=True, text=True).stdout
104
+ print(output_text)
105
+ return output
106
+ except Exception as e:
107
+ return f"An error occurred: {str(e)}"
108
+
109
+ def clear_output(self, unique_id):
110
+ try:
111
+ output_path = os.path.join(OUTPUT_DIR, unique_id)
112
+ if os.path.exists(output_path):
113
+ print("Trying to delete")
114
+ shutil.rmtree(output_path)
115
+ print(f"Output files in {output_path} are deleted")
116
+ return "Output files for unique_id deleted"
117
+ else:
118
+ print(f"Output files in {output_path} does not exist")
119
+ return "Output directory for (output_path} does not exist"
120
+ except Exception as e:
121
+ return f"An error occurred: {str(e)}"
122
+
123
+ def remove_old_directories(self, directory, num_minutes):
124
+ now = time.time()
125
+
126
+ for r, d, f in os.walk(directory):
127
+ for dir_name in d:
128
+ dir_path = os.path.join(r, dir_name)
129
+ timestamp = os.path.getmtime(dir_path)
130
+ age_minutes = (now - timestamp) / 60 # Convert to minutes
131
+
132
+ if age_minutes >= num_minutes:
133
+ try:
134
+ print("Removing", dir_path)
135
+ shutil.rmtree(dir_path)
136
+ print("Directory removed:", dir_path)
137
+ except Exception as e:
138
+ print(e)
139
+ pass
140
+
141
+ def get_theme(self) -> gr.Theme:
142
+ return gr.themes.Soft(
143
+ primary_hue=gr.themes.colors.red,
144
+ secondary_hue=gr.themes.colors.gray,
145
+ font=gr.themes.GoogleFont('Inter')
146
+ ).set(
147
+ background_fill_primary='*neutral_50',
148
+ block_label_text_size='*text_sm',
149
+ block_title_text_size='*text_sm'
150
+ )
151
 
152
+ # Create an instance of the DeepFakeAI class
153
+ app = DeepFakeAI()
 
 
 
 
 
 
 
 
154
 
155
+ # Create the UI
156
+ with gr.Blocks(theme=app.get_theme(), title="DeepFakeAI 1.0.0") as ui:
157
  with gr.Group():
158
  gr.HTML('<center><a href="https://codegenius.me">DeepFakeAI 1.0.1</a></center>')
159
+
160
  with gr.Group():
161
  with gr.Column(scale=3):
162
+ gr.Label("FRAME PROCESSORS")
163
+ app.frame_processor_checkbox.render()
 
 
 
 
164
 
165
  with gr.Group():
166
  with gr.Column(scale=3):
167
+ gr.Label("FACE ANALYSER DIRECTION")
168
+ app.face_analyser_direction_dropdown.render()
169
+ gr.Label("FACE RECOGNITION")
170
+ app.face_analyser_age_dropdown.render()
171
+ gr.Label("FACE ANALYSER GENDER")
172
+ app.face_analyser_gender_dropdown.render()
173
+ app.unique_id.render()
174
+
175
+ with gr.Tab("Image:"):
 
 
 
 
 
 
 
 
176
  source_image = gr.Image(type="filepath", label="SOURCE IMAGE")
177
+ target_image = gr.Files(label="TARGET IMAGE(S)")
178
  image_button = gr.Button("START")
179
  clear_button = gr.ClearButton(value="CLEAR")
180
+ image_output = gr.Files(label="OUTPUT")
181
  clear_button.add(image_output)
182
+
183
  image_button.click(
184
+ app.run,
185
+ inputs=[source_image, target_image, app.unique_id, app.frame_processor_checkbox, app.face_analyser_direction_dropdown, app.face_analyser_age_dropdown, app.face_analyser_gender_dropdown],
186
  outputs=image_output
187
  )
188
+ clear_button.click(fn=app.clear_output, inputs=app.unique_id)
189
+
190
+ with gr.Tab("Video:"):
191
  source_image_video = gr.Image(type="filepath", label="SOURCE IMAGE")
192
+ target_video = gr.Files(label="TARGET VIDEO(S)")
193
  with gr.Group():
194
  skip_audio = gr.Checkbox(label="SKIP AUDIO")
195
  keep_fps = gr.Checkbox(label="KEEP FPS")
196
  keep_temp = gr.Checkbox(label="KEEP TEMP")
197
  video_button = gr.Button("START")
198
  clear_video_button = gr.ClearButton(value="CLEAR")
199
+ video_output = gr.Files(label="OUTPUT")
200
  clear_video_button.add(video_output)
201
  video_button.click(
202
+ app.run,
203
+ inputs=[source_image_video, target_video, app.unique_id, app.frame_processor_checkbox, app.face_analyser_direction_dropdown, app.face_analyser_age_dropdown, app.face_analyser_gender_dropdown, skip_audio, keep_fps, keep_temp],
204
  outputs=video_output
205
  )
206
+ clear_video_button.click(fn=app.clear_output, inputs=app.unique_id)
207
 
208
  ui.launch(debug=True)