mr2along commited on
Commit
d6d9fcb
·
verified ·
1 Parent(s): de78640

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -67
app.py CHANGED
@@ -10,58 +10,33 @@ from face_swapper import Inswapper, paste_to_whole
10
  from face_analyser import analyse_face
11
  from face_enhancer import load_face_enhancer_model, get_available_enhancer_names
12
  import tempfile
13
- from huggingface_hub import login, hf_hub_download, upload_file, HfApi,upload_folder
14
  from datetime import datetime
15
  import shutil
16
 
17
-
18
  # --- Config ---
19
  REPO_ID = os.environ.get("HFPATH")
20
  HF_TOKEN = os.environ.get("MAGIC")
21
  login(HF_TOKEN)
 
22
  # --- Download function ---
23
  api = HfApi()
24
 
25
- # --- Download function ---
26
  def download_from_hf(subfolder):
27
  downloaded_files = []
28
-
29
- # List all files in the repository
30
- all_files = api.list_repo_files(repo_id=REPO_ID,repo_type="dataset")
31
-
32
- # Filter files that start with the specified subfolder
33
  for file in all_files:
34
  if file.startswith(subfolder + "/"):
35
- # Download the file
36
- downloaded_file = hf_hub_download(repo_id=REPO_ID, filename=file,repo_type="dataset" )
37
  downloaded_files.append(downloaded_file)
38
-
39
  return downloaded_files
 
40
  # --- Upload function ---
41
- def upload_to_hf(filepath):
42
- filename = os.path.basename(filepath)
43
- SUBFOLDER = datetime.now().strftime("%Y%m%d")
44
- path_in_repo = f"{SUBFOLDER}/{filename}"
45
- upload_file(
46
- path_or_fileobj=filepath,
47
- path_in_repo=path_in_repo,
48
- repo_id=REPO_ID,
49
- repo_type="dataset"
50
- )
51
- return f"https://huggingface.co/datasets/{REPO_ID}/blob/main/{path_in_repo}"
52
- # --- Upload function ---
53
  def upload_to_fd(path):
54
- #filename = os.path.basename(filepath)
55
  SUBFOLDER = datetime.now().strftime("%Y%m%d")
56
- path_in_repo = f"{SUBFOLDER}"
57
- upload_folder(
58
- folder_path=path,
59
- path_in_repo=path_in_repo,
60
- repo_id=REPO_ID,
61
- repo_type="dataset"
62
- )
63
- return f"https://huggingface.co/datasets/{REPO_ID}/blob/main/{path_in_repo}"
64
- # ------------------------------
65
  # ------------------------------ ARGS ------------------------------
66
  parser = argparse.ArgumentParser(description="Face Swapper (Multi-target, Male+Female Sources)")
67
  parser.add_argument("--out_dir", default=os.getcwd())
@@ -109,10 +84,10 @@ def swap_on_frame(frame_bgr, analysed_source_male, analysed_source_female, enhan
109
 
110
  if analysed_source_male is not None and analysed_source_female is not None:
111
  src_face = analysed_source_male if gender == 1 else analysed_source_female
112
- elif analysed_source_male is not None and analysed_source_female is None:
113
  if gender == 1:
114
  src_face = analysed_source_male
115
- elif analysed_source_female is not None and analysed_source_male is None:
116
  if gender == 0:
117
  src_face = analysed_source_female
118
 
@@ -133,7 +108,7 @@ def swap_on_frame(frame_bgr, analysed_source_male, analysed_source_female, enhan
133
  crop_mask=(0, 0, 0, 0),
134
  blur_amount=0.1,
135
  erode_amount=0.15,
136
- blend_method="laplacian",
137
  )
138
 
139
  if enhancer_name != "NONE":
@@ -166,41 +141,33 @@ def swap_faces(target_files, male_file, female_file, enhancer_name="NONE"):
166
 
167
  output_files = []
168
 
169
- for f in target_files:
170
- target_path = f.name
171
- ext = os.path.splitext(target_path)[-1].lower()
172
-
173
- # -------------------- IMAGE --------------------
174
- if ext in [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp"]:
175
- frame_bgr = cv2.imread(target_path)
176
- out_frame = swap_on_frame(frame_bgr, analysed_source_male, analysed_source_female, enhancer_name)
177
 
178
- # Save the output image to a temporary file
179
- with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as temp_file:
180
- #timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
181
- output_path = temp_file.name
182
- cv2.imwrite(output_path, out_frame) # Convert BGR to RGB before saving
183
- output_files.append(output_path)
184
- #upload_to_hf(output_path)
185
 
 
 
 
 
186
 
 
 
 
 
 
 
187
 
 
 
 
 
188
 
189
- # Tạo thư mục tạm thời
190
- with tempfile.TemporaryDirectory() as temp_dir:
191
- print(f"Thư mục tạm thời được tạo: {temp_dir}")
192
-
193
- # Lặp qua từng đường dẫn file trong danh sách
194
- for source_file in output_files:
195
- # Tạo đường dẫn đầy đủ cho file đích trong thư mục tạm
196
- destination_file = os.path.join(temp_dir, os.path.basename(source_file))
197
-
198
- # Sao chép file vào thư mục tạm
199
- shutil.copy(source_file, destination_file)
200
- print(f"Đã sao chép {source_file} vào {destination_file}")
201
-
202
- # Tải lên thư mục tạm lên Hugging Face
203
- upload_to_fd(temp_dir)
204
 
205
  print(f"✔ Hoàn tất tất cả trong {time.time() - start_time:.2f}s")
206
  return output_files
@@ -231,4 +198,4 @@ with gr.Blocks() as demo:
231
  )
232
 
233
  if __name__ == "__main__":
234
- demo.launch()
 
10
  from face_analyser import analyse_face
11
  from face_enhancer import load_face_enhancer_model, get_available_enhancer_names
12
  import tempfile
13
+ from huggingface_hub import login, hf_hub_download, upload_file, HfApi, upload_folder
14
  from datetime import datetime
15
  import shutil
16
 
 
17
  # --- Config ---
18
  REPO_ID = os.environ.get("HFPATH")
19
  HF_TOKEN = os.environ.get("MAGIC")
20
  login(HF_TOKEN)
21
+
22
  # --- Download function ---
23
  api = HfApi()
24
 
 
25
  def download_from_hf(subfolder):
26
  downloaded_files = []
27
+ all_files = api.list_repo_files(repo_id=REPO_ID, repo_type="dataset")
 
 
 
 
28
  for file in all_files:
29
  if file.startswith(subfolder + "/"):
30
+ downloaded_file = hf_hub_download(repo_id=REPO_ID, filename=file, repo_type="dataset")
 
31
  downloaded_files.append(downloaded_file)
 
32
  return downloaded_files
33
+
34
  # --- Upload function ---
 
 
 
 
 
 
 
 
 
 
 
 
35
  def upload_to_fd(path):
 
36
  SUBFOLDER = datetime.now().strftime("%Y%m%d")
37
+ upload_folder(folder_path=path, path_in_repo=SUBFOLDER, repo_id=REPO_ID, repo_type="dataset")
38
+ return f"https://huggingface.co/datasets/{REPO_ID}/blob/main/{SUBFOLDER}"
39
+
 
 
 
 
 
 
40
  # ------------------------------ ARGS ------------------------------
41
  parser = argparse.ArgumentParser(description="Face Swapper (Multi-target, Male+Female Sources)")
42
  parser.add_argument("--out_dir", default=os.getcwd())
 
84
 
85
  if analysed_source_male is not None and analysed_source_female is not None:
86
  src_face = analysed_source_male if gender == 1 else analysed_source_female
87
+ elif analysed_source_male is not None:
88
  if gender == 1:
89
  src_face = analysed_source_male
90
+ elif analysed_source_female is not None:
91
  if gender == 0:
92
  src_face = analysed_source_female
93
 
 
108
  crop_mask=(0, 0, 0, 0),
109
  blur_amount=0.1,
110
  erode_amount=0.15,
111
+ blend_method="laplacian
112
  )
113
 
114
  if enhancer_name != "NONE":
 
141
 
142
  output_files = []
143
 
144
+ # Tạo thư mục tạm và lưu file đầu ra vào đó
145
+ with tempfile.TemporaryDirectory() as temp_dir:
146
+ print(f"Thư mục tạm thời được tạo: {temp_dir}")
 
 
 
 
 
147
 
148
+ for f in target_files:
149
+ target_path = f.name
150
+ ext = os.path.splitext(target_path)[-1].lower()
 
 
 
 
151
 
152
+ # -------------------- IMAGE --------------------
153
+ if ext in [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp"]:
154
+ frame_bgr = cv2.imread(target_path)
155
+ out_frame = swap_on_frame(frame_bgr, analysed_source_male, analysed_source_female, enhancer_name)
156
 
157
+ # Tạo file tạm và ghi bức ảnh vào đó
158
+ with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as temp_file:
159
+ output_path = temp_file.name
160
+ cv2.imwrite(output_path, out_frame) # Ghi bức ảnh vào file tạm
161
+ output_files.append(output_path)
162
+ print(f"File tạm được tạo tại: {output_path}")
163
 
164
+ # Sao chép file vào thư mục tạm
165
+ destination_file = os.path.join(temp_dir, os.path.basename(output_path))
166
+ shutil.copy(output_path, destination_file)
167
+ print(f"Đã sao chép {output_path} vào {destination_file}")
168
 
169
+ # Tải lên thư mục tạm lên Hugging Face
170
+ upload_to_fd(temp_dir)
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
  print(f"✔ Hoàn tất tất cả trong {time.time() - start_time:.2f}s")
173
  return output_files
 
198
  )
199
 
200
  if __name__ == "__main__":
201
+ demo.launch()