mr2along commited on
Commit
03b3e32
·
verified ·
1 Parent(s): 7aecd10

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -48
app.py CHANGED
@@ -1,67 +1,105 @@
1
  import gradio as gr
2
  import subprocess
3
  import os
 
4
  from datetime import datetime
5
  from PIL import Image
6
- from huggingface_hub import login, upload_file
7
-
8
- # --- Config ---
9
- # REPO_ID = os.environ.get("HFPATH")
10
- # HF_TOKEN = os.environ.get("MAGIC")
11
- # login(HF_TOKEN)
12
- # def upload_to_hf(filepath):
13
- # filename = os.path.basename(filepath)
14
- # SUBFOLDER = datetime.now().strftime("%Y%m%d")
15
- # path_in_repo = f"{SUBFOLDER}/{filename}"
16
- # upload_file(
17
- # path_or_fileobj=filepath,
18
- # path_in_repo=path_in_repo,
19
- # repo_id=REPO_ID,
20
- # repo_type="dataset"
21
- # )
22
- # return f"https://huggingface.co/datasets/{REPO_ID}/blob/main/{filename}"
23
-
24
- def run_scripts(target, source, use_face_enhancer):
25
- output_images = [] # List to store processed images
26
- for target_file in target:
27
- target_extension = os.path.splitext(target_file.name)[-1] # Get file extension
28
- timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
29
- output_path1 = f"output_{timestamp}{target_extension}" # Output path
30
-
31
- # Run subprocess command to process the image
32
- cmd1 = [
33
- "python3", "run.py", "-s", source.name, "-t", target_file.name,
34
- "-o", output_path1, "--frame-processor", "face_swapper"
 
 
35
  ]
36
- result = subprocess.run(cmd1)
37
 
38
- if result.returncode != 0:
39
- print("Subprocess failed.")
40
- continue # Skip to the next file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- # Check if the file exists before opening it
43
- if os.path.isfile(output_path1):
44
- output_image = Image.open(output_path1)
45
- output_images.append(output_image)
46
- else:
47
- print(f"File not found: {output_path1}")
48
- continue # Optionally skip to the next file
49
 
50
- return output_images # Return the list of processed images
51
 
52
- # Gradio interface
53
  iface = gr.Interface(
54
  fn=run_scripts,
55
  inputs=[
56
- gr.Files(label="Target Files"), # Input for target files (image/video)
57
- gr.File(label="Source File"), # Input for source file (image)
58
- gr.Checkbox(label="Use Face Enhancer") # Option for face enhancer
59
  ],
60
- outputs=gr.Gallery(label="Output Images"), # Output for processed images
61
  title="Face Swapper",
62
- description="Upload a target image/video and a source image to swap faces.",
63
  live=False
64
  )
65
 
66
  if __name__ == "__main__":
67
- iface.launch()
 
1
  import gradio as gr
2
  import subprocess
3
  import os
4
+ import shutil
5
  from datetime import datetime
6
  from PIL import Image
7
+ import uuid
8
+
9
+ OUTPUT_DIR = "outputs"
10
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
11
+
12
+
13
+ def run_scripts(target_files, source_file, use_face_enhancer):
14
+
15
+ if not target_files or not source_file:
16
+ return []
17
+
18
+ output_results = []
19
+
20
+ for target_file in target_files:
21
+
22
+ # ===== Unique filename =====
23
+ unique_id = uuid.uuid4().hex[:8]
24
+ extension = os.path.splitext(target_file.name)[-1]
25
+ output_path = os.path.join(
26
+ OUTPUT_DIR,
27
+ f"swap_{unique_id}{extension}"
28
+ )
29
+
30
+ # ===== Build command =====
31
+ cmd = [
32
+ "python3",
33
+ "run.py",
34
+ "-s", source_file.name,
35
+ "-t", target_file.name,
36
+ "-o", output_path,
37
+ "--frame-processor", "face_swapper"
38
  ]
 
39
 
40
+ if use_face_enhancer:
41
+ cmd += ["--face-enhancer"]
42
+
43
+ print("Running:", " ".join(cmd))
44
+
45
+ try:
46
+ result = subprocess.run(
47
+ cmd,
48
+ capture_output=True,
49
+ text=True
50
+ )
51
+
52
+ if result.returncode != 0:
53
+ print("Error:")
54
+ print(result.stderr)
55
+ continue
56
+
57
+ except Exception as e:
58
+ print("Subprocess crashed:", str(e))
59
+ continue
60
+
61
+ # ===== Check output exists =====
62
+ if not os.path.exists(output_path):
63
+ print("Output not found:", output_path)
64
+ continue
65
+
66
+ # ===== Handle file types =====
67
+ ext = extension.lower()
68
+
69
+ try:
70
+ if ext in [".png", ".jpg", ".jpeg", ".webp"]:
71
+ img = Image.open(output_path).convert("RGB")
72
+ output_results.append(img)
73
+
74
+ elif ext == ".gif":
75
+ # Return gif path directly (Gallery hiển thị được)
76
+ output_results.append(output_path)
77
+
78
+ elif ext in [".mp4", ".mov", ".avi"]:
79
+ output_results.append(output_path)
80
+
81
+ else:
82
+ output_results.append(output_path)
83
+
84
+ except Exception as e:
85
+ print("Error loading result:", str(e))
86
+ continue
87
 
88
+ return output_results
 
 
 
 
 
 
89
 
 
90
 
 
91
  iface = gr.Interface(
92
  fn=run_scripts,
93
  inputs=[
94
+ gr.Files(label="Target Files (Image / GIF / Video)"),
95
+ gr.File(label="Source Face Image"),
96
+ gr.Checkbox(label="Use Face Enhancer", value=False)
97
  ],
98
+ outputs=gr.Gallery(label="Results"),
99
  title="Face Swapper",
100
+ description="Upload target images/videos and a source image to swap faces.",
101
  live=False
102
  )
103
 
104
  if __name__ == "__main__":
105
+ iface.launch()