Spaces:
Running
on
T4
Running
on
T4
Commit
Β·
4b4508d
1
Parent(s):
a520e24
gradio+fastapi
Browse files- app.py +156 -34
- requirements.txt +3 -2
app.py
CHANGED
|
@@ -8,6 +8,15 @@ import insightface
|
|
| 8 |
from insightface.app import FaceAnalysis
|
| 9 |
from huggingface_hub import hf_hub_download
|
| 10 |
import subprocess
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# -------------------------------------------------
|
| 13 |
# Paths
|
|
@@ -69,56 +78,71 @@ def ensure_codeformer():
|
|
| 69 |
ensure_codeformer()
|
| 70 |
|
| 71 |
# -------------------------------------------------
|
| 72 |
-
#
|
| 73 |
# -------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
# -------------------------------------------------
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
| 76 |
# -------------------------------------------------
|
| 77 |
def face_swap_and_enhance(src_img, tgt_img):
|
| 78 |
try:
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
if not src_faces or not tgt_faces:
|
| 85 |
-
return None, None, "β Face not detected in one of the images."
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
|
| 116 |
-
|
| 117 |
|
| 118 |
except Exception as e:
|
| 119 |
return None, None, f"β Error: {str(e)}"
|
| 120 |
|
| 121 |
-
|
| 122 |
# -------------------------------------------------
|
| 123 |
# Gradio Interface (simplified)
|
| 124 |
# -------------------------------------------------
|
|
@@ -141,4 +165,102 @@ with gr.Blocks() as demo:
|
|
| 141 |
|
| 142 |
btn.click(process, [src_input, tgt_input], [output_img, download, error_box])
|
| 143 |
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
from insightface.app import FaceAnalysis
|
| 9 |
from huggingface_hub import hf_hub_download
|
| 10 |
import subprocess
|
| 11 |
+
import tempfile
|
| 12 |
+
import numpy as np
|
| 13 |
+
import threading
|
| 14 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException, Response
|
| 15 |
+
from fastapi.responses import RedirectResponse
|
| 16 |
+
from pydantic import BaseModel
|
| 17 |
+
from motor.motor_asyncio import AsyncIOMotorClient
|
| 18 |
+
from bson.objectid import ObjectId
|
| 19 |
+
from gradio import mount_gradio_app
|
| 20 |
|
| 21 |
# -------------------------------------------------
|
| 22 |
# Paths
|
|
|
|
| 78 |
ensure_codeformer()
|
| 79 |
|
| 80 |
# -------------------------------------------------
|
| 81 |
+
# MongoDB setup
|
| 82 |
# -------------------------------------------------
|
| 83 |
+
MONGODB_URL = os.getenv(
|
| 84 |
+
"MONGODB_URL",
|
| 85 |
+
"mongodb+srv://harilogicgo_db_user:[email protected]/?retryWrites=true&w=majority&appName=Cluster0"
|
| 86 |
+
)
|
| 87 |
+
client = AsyncIOMotorClient(MONGODB_URL)
|
| 88 |
+
database = client.FaceSwap
|
| 89 |
+
target_images_collection = database.get_collection("Target_Images")
|
| 90 |
+
source_images_collection = database.get_collection("Source_Images")
|
| 91 |
+
results_collection = database.get_collection("Results")
|
| 92 |
+
|
| 93 |
+
# -------------------------------------------------
|
| 94 |
+
# Lock for face swap to prevent concurrent file operations
|
| 95 |
# -------------------------------------------------
|
| 96 |
+
swap_lock = threading.Lock()
|
| 97 |
+
|
| 98 |
+
# -------------------------------------------------
|
| 99 |
+
# Pipeline Function (with lock for safety)
|
| 100 |
# -------------------------------------------------
|
| 101 |
def face_swap_and_enhance(src_img, tgt_img):
|
| 102 |
try:
|
| 103 |
+
with swap_lock:
|
| 104 |
+
shutil.rmtree(UPLOAD_DIR, ignore_errors=True)
|
| 105 |
+
shutil.rmtree(RESULT_DIR, ignore_errors=True)
|
| 106 |
+
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 107 |
+
os.makedirs(RESULT_DIR, exist_ok=True)
|
| 108 |
|
| 109 |
+
src_bgr = cv2.cvtColor(src_img, cv2.COLOR_RGB2BGR)
|
| 110 |
+
tgt_bgr = cv2.cvtColor(tgt_img, cv2.COLOR_RGB2BGR)
|
|
|
|
|
|
|
| 111 |
|
| 112 |
+
src_faces = app.get(src_bgr)
|
| 113 |
+
tgt_faces = app.get(tgt_bgr)
|
| 114 |
+
if not src_faces or not tgt_faces:
|
| 115 |
+
return None, None, "β Face not detected in one of the images."
|
| 116 |
|
| 117 |
+
# ---------------- Save swapped face ----------------
|
| 118 |
+
unique_name = f"swapped_{uuid.uuid4().hex[:8]}.jpg"
|
| 119 |
+
swapped_path = os.path.join(UPLOAD_DIR, unique_name)
|
| 120 |
+
swapped_bgr = swapper.get(tgt_bgr, tgt_faces[0], src_faces[0])
|
| 121 |
+
cv2.imwrite(swapped_path, swapped_bgr)
|
| 122 |
|
| 123 |
+
# ---------------- Run CodeFormer ----------------
|
| 124 |
+
cmd = f"python {CODEFORMER_PATH} -w 0.7 --input_path {swapped_path} --output_path {RESULT_DIR} --bg_upsampler realesrgan --face_upsample"
|
| 125 |
+
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
| 126 |
+
if result.returncode != 0:
|
| 127 |
+
return None, None, f"β CodeFormer failed:\n{result.stderr}"
|
| 128 |
|
| 129 |
+
# ---------------- Locate final result ----------------
|
| 130 |
+
final_results_dir = os.path.join(RESULT_DIR, "final_results")
|
| 131 |
+
if not os.path.exists(final_results_dir):
|
| 132 |
+
return None, None, "β CodeFormer did not produce final results."
|
| 133 |
|
| 134 |
+
final_files = [f for f in os.listdir(final_results_dir) if f.endswith(".png")]
|
| 135 |
+
if not final_files:
|
| 136 |
+
return None, None, "β No enhanced image found in final results."
|
| 137 |
|
| 138 |
+
final_path = os.path.join(final_results_dir, final_files[0])
|
| 139 |
+
final_img = cv2.cvtColor(cv2.imread(final_path), cv2.COLOR_BGR2RGB)
|
| 140 |
|
| 141 |
+
return final_img, final_path, ""
|
| 142 |
|
| 143 |
except Exception as e:
|
| 144 |
return None, None, f"β Error: {str(e)}"
|
| 145 |
|
|
|
|
| 146 |
# -------------------------------------------------
|
| 147 |
# Gradio Interface (simplified)
|
| 148 |
# -------------------------------------------------
|
|
|
|
| 165 |
|
| 166 |
btn.click(process, [src_input, tgt_input], [output_img, download, error_box])
|
| 167 |
|
| 168 |
+
# -------------------------------------------------
|
| 169 |
+
# FastAPI App
|
| 170 |
+
# -------------------------------------------------
|
| 171 |
+
app = FastAPI()
|
| 172 |
+
|
| 173 |
+
# Redirect root to Gradio for backward compatibility
|
| 174 |
+
@app.get("/")
|
| 175 |
+
def root():
|
| 176 |
+
return RedirectResponse("/gradio")
|
| 177 |
+
|
| 178 |
+
# Health check
|
| 179 |
+
@app.get("/health")
|
| 180 |
+
def health():
|
| 181 |
+
return {"status": "healthy"}
|
| 182 |
+
|
| 183 |
+
# Upload source image
|
| 184 |
+
@app.post("/source")
|
| 185 |
+
async def upload_source(image: UploadFile = File(...)):
|
| 186 |
+
contents = await image.read()
|
| 187 |
+
doc = {
|
| 188 |
+
"filename": image.filename,
|
| 189 |
+
"content_type": image.content_type,
|
| 190 |
+
"data": contents
|
| 191 |
+
}
|
| 192 |
+
result = await source_images_collection.insert_one(doc)
|
| 193 |
+
return {"source_id": str(result.inserted_id)}
|
| 194 |
+
|
| 195 |
+
# Upload target image
|
| 196 |
+
@app.post("/target")
|
| 197 |
+
async def upload_target(image: UploadFile = File(...)):
|
| 198 |
+
contents = await image.read()
|
| 199 |
+
doc = {
|
| 200 |
+
"filename": image.filename,
|
| 201 |
+
"content_type": image.content_type,
|
| 202 |
+
"data": contents
|
| 203 |
+
}
|
| 204 |
+
result = await target_images_collection.insert_one(doc)
|
| 205 |
+
return {"target_id": str(result.inserted_id)}
|
| 206 |
+
|
| 207 |
+
# Face swap request model
|
| 208 |
+
class FaceSwapRequest(BaseModel):
|
| 209 |
+
source_id: str
|
| 210 |
+
target_id: str
|
| 211 |
+
|
| 212 |
+
# Perform face swap
|
| 213 |
+
@app.post("/faceswap")
|
| 214 |
+
async def perform_faceswap(request: FaceSwapRequest):
|
| 215 |
+
source_doc = await source_images_collection.find_one({"_id": ObjectId(request.source_id)})
|
| 216 |
+
if not source_doc:
|
| 217 |
+
raise HTTPException(status_code=404, detail="Source image not found")
|
| 218 |
+
|
| 219 |
+
target_doc = await target_images_collection.find_one({"_id": ObjectId(request.target_id)})
|
| 220 |
+
if not target_doc:
|
| 221 |
+
raise HTTPException(status_code=404, detail="Target image not found")
|
| 222 |
+
|
| 223 |
+
# Decode source
|
| 224 |
+
source_array = np.frombuffer(source_doc["data"], np.uint8)
|
| 225 |
+
source_bgr = cv2.imdecode(source_array, cv2.IMREAD_COLOR)
|
| 226 |
+
source_rgb = cv2.cvtColor(source_bgr, cv2.COLOR_BGR2RGB)
|
| 227 |
+
|
| 228 |
+
# Decode target
|
| 229 |
+
target_array = np.frombuffer(target_doc["data"], np.uint8)
|
| 230 |
+
target_bgr = cv2.imdecode(target_array, cv2.IMREAD_COLOR)
|
| 231 |
+
target_rgb = cv2.cvtColor(target_bgr, cv2.COLOR_BGR2RGB)
|
| 232 |
+
|
| 233 |
+
# Perform swap
|
| 234 |
+
final_img, final_path, err = face_swap_and_enhance(source_rgb, target_rgb)
|
| 235 |
+
if err:
|
| 236 |
+
raise HTTPException(status_code=500, detail=err)
|
| 237 |
+
|
| 238 |
+
# Read final bytes
|
| 239 |
+
with open(final_path, "rb") as f:
|
| 240 |
+
final_bytes = f.read()
|
| 241 |
+
|
| 242 |
+
# Store result
|
| 243 |
+
result_doc = {
|
| 244 |
+
"source_id": request.source_id,
|
| 245 |
+
"target_id": request.target_id,
|
| 246 |
+
"filename": "enhanced.png",
|
| 247 |
+
"content_type": "image/png",
|
| 248 |
+
"data": final_bytes
|
| 249 |
+
}
|
| 250 |
+
result = await results_collection.insert_one(result_doc)
|
| 251 |
+
return {"result_id": str(result.inserted_id)}
|
| 252 |
+
|
| 253 |
+
# Download result
|
| 254 |
+
@app.get("/download/{result_id}")
|
| 255 |
+
async def download_result(result_id: str):
|
| 256 |
+
doc = await results_collection.find_one({"_id": ObjectId(result_id)})
|
| 257 |
+
if not doc:
|
| 258 |
+
raise HTTPException(status_code=404, detail="Result not found")
|
| 259 |
+
return Response(
|
| 260 |
+
content=doc["data"],
|
| 261 |
+
media_type=doc["content_type"],
|
| 262 |
+
headers={"Content-Disposition": f"attachment; filename={doc['filename']}"}
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
# Mount Gradio at /gradio
|
| 266 |
+
app = mount_gradio_app(app, demo, path="/gradio")
|
requirements.txt
CHANGED
|
@@ -25,14 +25,15 @@ facexlib==0.2.5
|
|
| 25 |
|
| 26 |
# Face swap / insightface
|
| 27 |
insightface
|
| 28 |
-
onnxruntime
|
| 29 |
onnx
|
|
|
|
| 30 |
|
| 31 |
# App deps
|
| 32 |
gradio
|
| 33 |
huggingface_hub
|
| 34 |
fastapi
|
| 35 |
uvicorn
|
|
|
|
| 36 |
|
| 37 |
# Optional but included in CodeFormer repo
|
| 38 |
-
tb-nightly
|
|
|
|
| 25 |
|
| 26 |
# Face swap / insightface
|
| 27 |
insightface
|
|
|
|
| 28 |
onnx
|
| 29 |
+
onnxruntime-gpu # Changed from onnxruntime to support GPU
|
| 30 |
|
| 31 |
# App deps
|
| 32 |
gradio
|
| 33 |
huggingface_hub
|
| 34 |
fastapi
|
| 35 |
uvicorn
|
| 36 |
+
motor # Added for MongoDB async support
|
| 37 |
|
| 38 |
# Optional but included in CodeFormer repo
|
| 39 |
+
tb-nightly
|