Arrcttacsrks commited on
Commit
74329f2
·
verified ·
1 Parent(s): 16372c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -20
app.py CHANGED
@@ -24,10 +24,57 @@ from dotenv import load_dotenv
24
  load_dotenv()
25
 
26
  class FaceIntegrDataset:
27
- # [Previous FaceIntegrDataset class implementation remains the same]
28
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  def swap_face(source_file, target_file, doFaceEnhancer):
 
31
  try:
32
  # Initialize dataset handler
33
  dataset_handler = FaceIntegrDataset()
@@ -44,6 +91,9 @@ def swap_face(source_file, target_file, doFaceEnhancer):
44
  output_path = os.path.join(folder_path, f"Image{timestamp}.jpg")
45
 
46
  # Save the input images
 
 
 
47
  source_image = Image.fromarray(source_file)
48
  source_image.save(source_path)
49
  target_image = Image.fromarray(target_file)
@@ -117,50 +167,103 @@ def swap_face(source_file, target_file, doFaceEnhancer):
117
 
118
  # Read the output image before cleaning up
119
  if os.path.exists(output_path):
120
- output_image = np.array(Image.open(output_path))
 
121
  # Clean up temp folder after reading the image
122
  shutil.rmtree(folder_path)
123
- return output_image
124
  else:
125
  print("Output image not found")
126
- shutil.rmtree(folder_path)
 
127
  return None
128
 
129
  except Exception as e:
130
  print(f"Error in face swap process: {str(e)}")
131
- if os.path.exists(folder_path):
132
  shutil.rmtree(folder_path)
133
- raise gr.Error("Face swap failed. Please check your Hugging Face token and try again.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
  # Gradio interface setup
136
  title = "Face - Интегратор"
137
  description = r"""
138
  The application will save the image history to Hugging Face dataset using the environment variable token.
 
139
  """
140
  article = r"""
141
- <br><br><br><br><br>
 
 
 
 
 
142
  """
143
 
144
- with gr.Blocks(title=title) as app:
 
 
145
  gr.Markdown(description)
 
146
  with gr.Row():
147
- with gr.Column():
148
- source_image = gr.Image(label="Source Image")
149
- target_image = gr.Image(label="Target Image")
150
- enhance_checkbox = gr.Checkbox(
151
- label="Применить алгоритм?",
152
- info="Улучшение качества изображения"
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  )
154
- with gr.Column():
155
- output_image = gr.Image(label="Output Image")
156
 
157
- process_btn = gr.Button("Process")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  process_btn.click(
159
  fn=swap_face,
160
  inputs=[source_image, target_image, enhance_checkbox],
161
- outputs=output_image
 
162
  )
163
 
164
  gr.Markdown(article)
165
 
166
- app.launch()
 
 
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()
 
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)
 
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
+ # Create custom style
188
+ custom_css = """
189
+ .container {
190
+ max-width: 1200px;
191
+ margin: auto;
192
+ padding: 20px;
193
+ }
194
+ .output-image {
195
+ min-height: 400px;
196
+ border: 1px solid #ccc;
197
+ border-radius: 8px;
198
+ padding: 10px;
199
+ }
200
+ """
201
 
202
  # Gradio interface setup
203
  title = "Face - Интегратор"
204
  description = r"""
205
  The application will save the image history to Hugging Face dataset using the environment variable token.
206
+ Please upload source and target images to begin the face swap process.
207
  """
208
  article = r"""
209
+ <div style="text-align: center; max-width: 650px; margin: 40px auto;">
210
+ <p>
211
+ This tool performs face swapping with optional enhancement.
212
+ The processed images are automatically saved to the Hugging Face dataset.
213
+ </p>
214
+ </div>
215
  """
216
 
217
+ # Create Gradio interface with improved layout
218
+ with gr.Blocks(title=title, css=custom_css) as app:
219
+ gr.Markdown(f"<h1 style='text-align: center;'>{title}</h1>")
220
  gr.Markdown(description)
221
+
222
  with gr.Row():
223
+ with gr.Column(scale=1):
224
+ source_image = gr.Image(
225
+ label="Source Image",
226
+ type="numpy",
227
+ tool="upload"
228
+ )
229
+
230
+ with gr.Column(scale=1):
231
+ target_image = gr.Image(
232
+ label="Target Image",
233
+ type="numpy",
234
+ tool="upload"
235
+ )
236
+
237
+ with gr.Column(scale=1):
238
+ output_image = gr.Image(
239
+ label="Output Image",
240
+ type="numpy",
241
+ elem_classes="output-image"
242
  )
 
 
243
 
244
+ with gr.Row():
245
+ enhance_checkbox = gr.Checkbox(
246
+ label="Применить алгоритм?",
247
+ info="Улучшение качества изображения",
248
+ value=False
249
+ )
250
+
251
+ with gr.Row():
252
+ process_btn = gr.Button(
253
+ "Process Face Swap",
254
+ variant="primary",
255
+ size="lg"
256
+ )
257
+
258
+ # Set up the processing event
259
  process_btn.click(
260
  fn=swap_face,
261
  inputs=[source_image, target_image, enhance_checkbox],
262
+ outputs=output_image,
263
+ api_name="swap_face"
264
  )
265
 
266
  gr.Markdown(article)
267
 
268
+ # Launch the application
269
+ app.launch(share=False)