Arrcttacsrks commited on
Commit
3179874
1 Parent(s): ce35e91

Upload app(10).py

Browse files
Files changed (1) hide show
  1. app(10).py +278 -0
app(10).py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding:UTF-8 -*-
2
+ #!/usr/bin/env python
3
+ import numpy as np
4
+ import gradio as gr
5
+ import roop.globals
6
+ from roop.core import (
7
+ start,
8
+ decode_execution_providers,
9
+ suggest_max_memory,
10
+ suggest_execution_threads,
11
+ )
12
+ from roop.processors.frame.core import get_frame_processors_modules
13
+ from roop.utilities import normalize_output_path
14
+ import os
15
+ from PIL import Image
16
+ from datetime import datetime
17
+ from huggingface_hub import HfApi, login
18
+ from datasets import load_dataset, Dataset
19
+ import json
20
+ import shutil
21
+ from dotenv import load_dotenv
22
+
23
+ # Load environment variables
24
+ load_dotenv()
25
+
26
+ class FaceIntegrDataset:
27
+ def __init__(self, repo_id="Arrcttacsrks/face_integrData"):
28
+ # Get token from environment variable
29
+ self.token = os.getenv('hf_token')
30
+ if not self.token:
31
+ raise ValueError("HF_TOKEN environment variable is not set")
32
+
33
+ self.repo_id = repo_id
34
+ self.api = HfApi()
35
+
36
+ # Login to Hugging Face
37
+ login(self.token)
38
+
39
+ # Create local temp directory for organizing files
40
+ self.temp_dir = "temp_dataset"
41
+ os.makedirs(self.temp_dir, exist_ok=True)
42
+
43
+ def create_date_folder(self):
44
+ """Create folder structure based on current date"""
45
+ current_date = datetime.now().strftime("%Y-%m-%d")
46
+ folder_path = os.path.join(self.temp_dir, current_date)
47
+ os.makedirs(folder_path, exist_ok=True)
48
+ return folder_path, current_date
49
+
50
+ def save_metadata(self, source_path, target_path, output_path, timestamp):
51
+ """Save metadata for the face swap operation"""
52
+ metadata = {
53
+ "timestamp": timestamp,
54
+ "source_image": source_path,
55
+ "target_image": target_path,
56
+ "output_image": output_path,
57
+ "date_created": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
58
+ }
59
+ return metadata
60
+
61
+ def upload_to_hf(self, local_folder, date_folder):
62
+ """Upload files to Hugging Face dataset"""
63
+ try:
64
+ # Upload the files
65
+ self.api.upload_folder(
66
+ folder_path=local_folder,
67
+ repo_id=self.repo_id,
68
+ repo_type="dataset",
69
+ path_in_repo=date_folder
70
+ )
71
+ return True
72
+ except Exception as e:
73
+ print(f"Error uploading to Hugging Face: {str(e)}")
74
+ return False
75
+
76
+ def swap_face(source_file, target_file, doFaceEnhancer):
77
+ folder_path = None
78
+ try:
79
+ # Initialize dataset handler
80
+ dataset_handler = FaceIntegrDataset()
81
+
82
+ # Create date-based folder
83
+ folder_path, date_folder = dataset_handler.create_date_folder()
84
+
85
+ # Generate timestamp for unique identification
86
+ timestamp = datetime.now().strftime("%S%M%H%d%m%Y")
87
+
88
+ # Save input images with timestamp in folder
89
+ source_path = os.path.join(folder_path, f"source_{timestamp}.jpg")
90
+ target_path = os.path.join(folder_path, f"target_{timestamp}.jpg")
91
+ output_path = os.path.join(folder_path, f"Image{timestamp}.jpg")
92
+
93
+ # Save the input images
94
+ if source_file is None or target_file is None:
95
+ raise ValueError("Source and target images are required")
96
+
97
+ source_image = Image.fromarray(source_file)
98
+ source_image.save(source_path)
99
+ target_image = Image.fromarray(target_file)
100
+ target_image.save(target_path)
101
+
102
+ print("source_path: ", source_path)
103
+ print("target_path: ", target_path)
104
+
105
+ # Set global paths
106
+ roop.globals.source_path = source_path
107
+ roop.globals.target_path = target_path
108
+ roop.globals.output_path = normalize_output_path(
109
+ roop.globals.source_path,
110
+ roop.globals.target_path,
111
+ output_path
112
+ )
113
+
114
+ # Configure face processing options
115
+ if doFaceEnhancer:
116
+ roop.globals.frame_processors = ["face_swapper", "face_enhancer"]
117
+ else:
118
+ roop.globals.frame_processors = ["face_swapper"]
119
+
120
+ # Set global parameters
121
+ roop.globals.headless = True
122
+ roop.globals.keep_fps = True
123
+ roop.globals.keep_audio = True
124
+ roop.globals.keep_frames = False
125
+ roop.globals.many_faces = False
126
+ roop.globals.video_encoder = "libx264"
127
+ roop.globals.video_quality = 18
128
+ roop.globals.max_memory = suggest_max_memory()
129
+ roop.globals.execution_providers = decode_execution_providers(["cuda"])
130
+ roop.globals.execution_threads = suggest_execution_threads()
131
+
132
+ print(
133
+ "start process",
134
+ roop.globals.source_path,
135
+ roop.globals.target_path,
136
+ roop.globals.output_path,
137
+ )
138
+
139
+ # Check frame processors
140
+ for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
141
+ if not frame_processor.pre_check():
142
+ return None
143
+
144
+ # Process the face swap
145
+ start()
146
+
147
+ # Save metadata
148
+ metadata = dataset_handler.save_metadata(
149
+ f"source_{timestamp}.jpg",
150
+ f"target_{timestamp}.jpg",
151
+ f"Image{timestamp}.jpg",
152
+ timestamp
153
+ )
154
+
155
+ # Save metadata to JSON file in the same folder
156
+ metadata_path = os.path.join(folder_path, f"metadata_{timestamp}.json")
157
+ with open(metadata_path, 'w') as f:
158
+ json.dump(metadata, f, indent=4)
159
+
160
+ # Upload to Hugging Face
161
+ upload_success = dataset_handler.upload_to_hf(folder_path, date_folder)
162
+
163
+ if upload_success:
164
+ print(f"Successfully uploaded files to dataset {dataset_handler.repo_id}")
165
+ else:
166
+ print("Failed to upload files to Hugging Face dataset")
167
+
168
+ # Read the output image before cleaning up
169
+ if os.path.exists(output_path):
170
+ output_image = Image.open(output_path)
171
+ output_array = np.array(output_image)
172
+ # Clean up temp folder after reading the image
173
+ shutil.rmtree(folder_path)
174
+ return output_array
175
+ else:
176
+ print("Output image not found")
177
+ if folder_path and os.path.exists(folder_path):
178
+ shutil.rmtree(folder_path)
179
+ return None
180
+
181
+ except Exception as e:
182
+ print(f"Error in face swap process: {str(e)}")
183
+ if folder_path and os.path.exists(folder_path):
184
+ shutil.rmtree(folder_path)
185
+ raise gr.Error(f"Face swap failed: {str(e)}")
186
+
187
+ def create_interface():
188
+ # Create custom style
189
+ custom_css = """
190
+ .container {
191
+ max-width: 1200px;
192
+ margin: auto;
193
+ padding: 20px;
194
+ }
195
+ .output-image {
196
+ min-height: 400px;
197
+ border: 1px solid #ccc;
198
+ border-radius: 8px;
199
+ padding: 10px;
200
+ }
201
+ """
202
+
203
+ # Gradio interface setup
204
+ title = "Face - Интегратор"
205
+ description = r"""
206
+ The application will save the image history to Hugging Face dataset using the environment variable token.
207
+ Please upload source and target images to begin the face swap process.
208
+ """
209
+ article = r"""
210
+ <div style="text-align: center; max-width: 650px; margin: 40px auto;">
211
+ <p>
212
+ This tool performs face swapping with optional enhancement.
213
+ The processed images are automatically saved to the Hugging Face dataset.
214
+ </p>
215
+ </div>
216
+ """
217
+
218
+ # Create Gradio interface with improved layout
219
+ with gr.Blocks(title=title, css=custom_css) as app:
220
+ gr.Markdown(f"<h1 style='text-align: center;'>{title}</h1>")
221
+ gr.Markdown(description)
222
+
223
+ with gr.Row():
224
+ with gr.Column(scale=1):
225
+ source_image = gr.Image(
226
+ label="Source Image",
227
+ type="numpy",
228
+ sources=["upload"]
229
+ )
230
+
231
+ with gr.Column(scale=1):
232
+ target_image = gr.Image(
233
+ label="Target Image",
234
+ type="numpy",
235
+ sources=["upload"]
236
+ )
237
+
238
+ with gr.Column(scale=1):
239
+ output_image = gr.Image(
240
+ label="Output Image",
241
+ type="numpy",
242
+ interactive=False,
243
+ elem_classes="output-image"
244
+ )
245
+
246
+ with gr.Row():
247
+ enhance_checkbox = gr.Checkbox(
248
+ label="Применить алгоритм?",
249
+ info="Улучшение качества изображения",
250
+ value=False
251
+ )
252
+
253
+ with gr.Row():
254
+ process_btn = gr.Button(
255
+ "Process Face Swap",
256
+ variant="primary",
257
+ size="lg"
258
+ )
259
+
260
+ # Set up the processing event
261
+ process_btn.click(
262
+ fn=swap_face,
263
+ inputs=[source_image, target_image, enhance_checkbox],
264
+ outputs=output_image,
265
+ api_name="swap_face"
266
+ )
267
+
268
+ gr.Markdown(article)
269
+
270
+ return app
271
+
272
+ def main():
273
+ # Create and launch the interface
274
+ app = create_interface()
275
+ app.launch(share=False)
276
+
277
+ if __name__ == "__main__":
278
+ main()