HariLogicgo commited on
Commit
a520e24
Β·
1 Parent(s): 64abd1e

old gradio code

Browse files
Files changed (1) hide show
  1. app.py +26 -65
app.py CHANGED
@@ -1,18 +1,13 @@
1
  import os
2
  os.environ["OMP_NUM_THREADS"] = "1"
3
-
4
  import cv2
5
  import shutil
6
  import uuid
7
- import subprocess
8
- import numpy as np
9
  import insightface
10
  from insightface.app import FaceAnalysis
11
  from huggingface_hub import hf_hub_download
12
- from fastapi import FastAPI, UploadFile, File
13
- from fastapi.responses import StreamingResponse
14
- import io
15
- import gradio as gr
16
 
17
  # -------------------------------------------------
18
  # Paths
@@ -54,8 +49,8 @@ for f in buffalo_files:
54
  # -------------------------------------------------
55
  # Initialize face analysis and swapper
56
  # -------------------------------------------------
57
- app_face = FaceAnalysis(name="buffalo_l", root=MODELS_DIR, providers=['CPUExecutionProvider'])
58
- app_face.prepare(ctx_id=0, det_size=(640, 640))
59
  swapper = insightface.model_zoo.get_model(inswapper_path, providers=['CPUExecutionProvider'])
60
 
61
  # -------------------------------------------------
@@ -76,108 +71,74 @@ ensure_codeformer()
76
  # -------------------------------------------------
77
  # Pipeline Function
78
  # -------------------------------------------------
 
 
 
79
  def face_swap_and_enhance(src_img, tgt_img):
80
  try:
81
  src_bgr = cv2.cvtColor(src_img, cv2.COLOR_RGB2BGR)
82
  tgt_bgr = cv2.cvtColor(tgt_img, cv2.COLOR_RGB2BGR)
83
 
84
- src_faces = app_face.get(src_bgr)
85
- tgt_faces = app_face.get(tgt_bgr)
86
  if not src_faces or not tgt_faces:
87
- return None, "❌ Face not detected in one of the images."
88
 
89
- # clean dirs
90
  shutil.rmtree(UPLOAD_DIR, ignore_errors=True)
91
  shutil.rmtree(RESULT_DIR, ignore_errors=True)
92
  os.makedirs(UPLOAD_DIR, exist_ok=True)
93
  os.makedirs(RESULT_DIR, exist_ok=True)
94
 
95
- # save swapped
96
  unique_name = f"swapped_{uuid.uuid4().hex[:8]}.jpg"
97
  swapped_path = os.path.join(UPLOAD_DIR, unique_name)
98
  swapped_bgr = swapper.get(tgt_bgr, tgt_faces[0], src_faces[0])
99
  cv2.imwrite(swapped_path, swapped_bgr)
100
 
101
- # run CodeFormer
102
  cmd = f"python {CODEFORMER_PATH} -w 0.7 --input_path {swapped_path} --output_path {RESULT_DIR} --bg_upsampler realesrgan --face_upsample"
103
  result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
104
  if result.returncode != 0:
105
- return None, f"❌ CodeFormer failed:\n{result.stderr}"
106
 
 
107
  final_results_dir = os.path.join(RESULT_DIR, "final_results")
108
  if not os.path.exists(final_results_dir):
109
- return None, "❌ CodeFormer did not produce final results."
110
 
111
  final_files = [f for f in os.listdir(final_results_dir) if f.endswith(".png")]
112
  if not final_files:
113
- return None, "❌ No enhanced image found in final results."
114
 
115
  final_path = os.path.join(final_results_dir, final_files[0])
116
  final_img = cv2.cvtColor(cv2.imread(final_path), cv2.COLOR_BGR2RGB)
117
 
118
- return final_img, None
119
 
120
  except Exception as e:
121
- return None, f"❌ Error: {str(e)}"
122
-
123
- # -------------------------------------------------
124
- # FastAPI REST API
125
- # -------------------------------------------------
126
- api = FastAPI()
127
- # Add this to your app.py in the FastAPI section
128
- @api.get("/api/health")
129
- async def health_check():
130
- return {"status": "healthy", "message": "FaceSwap API is running"}
131
-
132
- @api.post("/api/faceswap")
133
- async def faceswap(src_img: UploadFile = File(...), tgt_img: UploadFile = File(...)):
134
- """
135
- REST API endpoint for face swapping.
136
- Accepts source and target images as file uploads.
137
- Returns enhanced face-swapped image as PNG.
138
- """
139
- try:
140
- # Read images from uploads
141
- src = cv2.imdecode(np.frombuffer(await src_img.read(), np.uint8), cv2.IMREAD_COLOR)
142
- tgt = cv2.imdecode(np.frombuffer(await tgt_img.read(), np.uint8), cv2.IMREAD_COLOR)
143
-
144
- # Run face swap + CodeFormer enhancement
145
- result_img, err = face_swap_and_enhance(
146
- cv2.cvtColor(src, cv2.COLOR_BGR2RGB),
147
- cv2.cvtColor(tgt, cv2.COLOR_BGR2RGB)
148
- )
149
 
150
- if result_img is None:
151
- return {"error": err}
152
 
153
- # Encode as PNG and return
154
- _, buffer = cv2.imencode(".png", cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR))
155
- return StreamingResponse(io.BytesIO(buffer.tobytes()), media_type="image/png")
156
-
157
- except Exception as e:
158
- return {"error": f"Exception: {str(e)}"}
159
  # -------------------------------------------------
160
- # Gradio UI
161
  # -------------------------------------------------
162
  with gr.Blocks() as demo:
163
- gr.Markdown("### Face Swap + CodeFormer Enhancement")
164
 
165
  with gr.Row():
166
  src_input = gr.Image(type="numpy", label="Upload Your Face")
167
  tgt_input = gr.Image(type="numpy", label="Upload Target Image")
168
 
169
  btn = gr.Button("Swap Face")
 
170
  output_img = gr.Image(type="numpy", label="Enhanced Output")
 
171
  error_box = gr.Textbox(label="Logs / Errors", interactive=False)
172
 
173
  def process(src, tgt):
174
- img, err = face_swap_and_enhance(src, tgt)
175
- return img, err
176
-
177
- btn.click(process, [src_input, tgt_input], [output_img, error_box])
178
 
179
- # Mount FastAPI into Gradio
180
- demo.app = api
181
 
182
- # Launch (only once)
183
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import os
2
  os.environ["OMP_NUM_THREADS"] = "1"
3
+ import gradio as gr
4
  import cv2
5
  import shutil
6
  import uuid
 
 
7
  import insightface
8
  from insightface.app import FaceAnalysis
9
  from huggingface_hub import hf_hub_download
10
+ import subprocess
 
 
 
11
 
12
  # -------------------------------------------------
13
  # Paths
 
49
  # -------------------------------------------------
50
  # Initialize face analysis and swapper
51
  # -------------------------------------------------
52
+ app = FaceAnalysis(name="buffalo_l", root=MODELS_DIR, providers=['CPUExecutionProvider'])
53
+ app.prepare(ctx_id=0, det_size=(640, 640))
54
  swapper = insightface.model_zoo.get_model(inswapper_path, providers=['CPUExecutionProvider'])
55
 
56
  # -------------------------------------------------
 
71
  # -------------------------------------------------
72
  # Pipeline Function
73
  # -------------------------------------------------
74
+ # -------------------------------------------------
75
+ # Pipeline Function (defaults applied)
76
+ # -------------------------------------------------
77
  def face_swap_and_enhance(src_img, tgt_img):
78
  try:
79
  src_bgr = cv2.cvtColor(src_img, cv2.COLOR_RGB2BGR)
80
  tgt_bgr = cv2.cvtColor(tgt_img, cv2.COLOR_RGB2BGR)
81
 
82
+ src_faces = app.get(src_bgr)
83
+ tgt_faces = app.get(tgt_bgr)
84
  if not src_faces or not tgt_faces:
85
+ return None, None, "❌ Face not detected in one of the images."
86
 
 
87
  shutil.rmtree(UPLOAD_DIR, ignore_errors=True)
88
  shutil.rmtree(RESULT_DIR, ignore_errors=True)
89
  os.makedirs(UPLOAD_DIR, exist_ok=True)
90
  os.makedirs(RESULT_DIR, exist_ok=True)
91
 
92
+ # ---------------- Save swapped face ----------------
93
  unique_name = f"swapped_{uuid.uuid4().hex[:8]}.jpg"
94
  swapped_path = os.path.join(UPLOAD_DIR, unique_name)
95
  swapped_bgr = swapper.get(tgt_bgr, tgt_faces[0], src_faces[0])
96
  cv2.imwrite(swapped_path, swapped_bgr)
97
 
98
+ # ---------------- Run CodeFormer ----------------
99
  cmd = f"python {CODEFORMER_PATH} -w 0.7 --input_path {swapped_path} --output_path {RESULT_DIR} --bg_upsampler realesrgan --face_upsample"
100
  result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
101
  if result.returncode != 0:
102
+ return None, None, f"❌ CodeFormer failed:\n{result.stderr}"
103
 
104
+ # ---------------- Locate final result ----------------
105
  final_results_dir = os.path.join(RESULT_DIR, "final_results")
106
  if not os.path.exists(final_results_dir):
107
+ return None, None, "❌ CodeFormer did not produce final results."
108
 
109
  final_files = [f for f in os.listdir(final_results_dir) if f.endswith(".png")]
110
  if not final_files:
111
+ return None, None, "❌ No enhanced image found in final results."
112
 
113
  final_path = os.path.join(final_results_dir, final_files[0])
114
  final_img = cv2.cvtColor(cv2.imread(final_path), cv2.COLOR_BGR2RGB)
115
 
116
+ return final_img, final_path, ""
117
 
118
  except Exception as e:
119
+ return None, None, f"❌ Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
 
 
121
 
 
 
 
 
 
 
122
  # -------------------------------------------------
123
+ # Gradio Interface (simplified)
124
  # -------------------------------------------------
125
  with gr.Blocks() as demo:
126
+ gr.Markdown("Face Swap")
127
 
128
  with gr.Row():
129
  src_input = gr.Image(type="numpy", label="Upload Your Face")
130
  tgt_input = gr.Image(type="numpy", label="Upload Target Image")
131
 
132
  btn = gr.Button("Swap Face")
133
+
134
  output_img = gr.Image(type="numpy", label="Enhanced Output")
135
+ download = gr.File(label="⬇️ Download Enhanced Image")
136
  error_box = gr.Textbox(label="Logs / Errors", interactive=False)
137
 
138
  def process(src, tgt):
139
+ img, path, err = face_swap_and_enhance(src, tgt)
140
+ return img, path, err
 
 
141
 
142
+ btn.click(process, [src_input, tgt_input], [output_img, download, error_box])
 
143
 
144
+ demo.launch(share=True)