AkashKumarave commited on
Commit
19d53bf
·
verified ·
1 Parent(s): 373cea6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -75
app.py CHANGED
@@ -1,93 +1,67 @@
1
- # -*- coding: UTF-8 -*-
2
  import gradio as gr
3
- import cv2
4
  import numpy as np
5
- from fastapi import FastAPI
6
- from fastapi.middleware.cors import CORSMiddleware
7
- from contextlib import asynccontextmanager
8
  from insightface.app import FaceAnalysis
9
- from insightface.model_zoo.face_swapper import FaceSwapper
10
  from pathlib import Path
11
- import requests
12
- import os
13
- import logging
14
-
15
- # Configure logging
16
- logging.basicConfig(level=logging.INFO)
17
- logger = logging.getLogger(__name__)
18
-
19
- # Initialize FastAPI
20
- app = FastAPI(title="Face Swap API", description="Gradio-based Face Swap App")
21
- app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
22
 
23
- # Health Check Endpoint
24
- @app.get("/health")
25
- async def health_check():
26
- return {"status": "healthy"}
27
 
28
- # Download Model Function
29
  MODEL_PATH = Path("models/inswapper_128.onnx")
30
- MODEL_URL = "https://huggingface.co/ezioruan/inswapper_128.onnx/resolve/main/inswapper_128.onnx"
 
31
 
32
- def download_model():
33
- if not MODEL_PATH.exists():
34
- logger.info("Downloading model...")
35
- os.makedirs("models", exist_ok=True)
36
- response = requests.get(MODEL_URL, stream=True, timeout=30)
37
- response.raise_for_status()
38
- with open(MODEL_PATH, 'wb') as f:
39
- for chunk in response.iter_content(chunk_size=8192):
40
- f.write(chunk)
41
- logger.info("Model downloaded successfully.")
42
 
43
- download_model()
 
 
44
 
45
- # Initialize Face Analyzer & Swapper
46
- face_analyzer = FaceAnalysis(name="buffalo_l")
47
- face_analyzer.prepare(ctx_id=0, det_size=(640, 640))
48
- face_swapper = FaceSwapper(MODEL_PATH)
49
 
50
- # Face Swap Function
51
- def swap_faces(source_img, target_img):
52
- source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)
53
- target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)
54
 
55
- source_faces = face_analyzer.get(source_img)
56
- target_faces = face_analyzer.get(target_img)
 
 
 
 
57
 
58
- if not source_faces or not target_faces:
59
- return "Error: No faces detected in one or both images."
60
- if len(source_faces) > 1 or len(target_faces) > 1:
61
- return "Error: Multiple faces detected; only one face per image is supported."
62
 
63
- result_img = face_swapper.get(target_img, target_faces[0], source_faces[0], paste_back=True)
64
- return cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB)
 
65
 
66
- # Gradio UI
67
- def gradio_face_swap(source_img, target_img):
68
- try:
69
- result = swap_faces(source_img, target_img)
70
- if isinstance(result, str):
71
- return result # Error message
72
- return result
73
  except Exception as e:
74
- return f"Error: {str(e)}"
75
 
76
- gr_interface = gr.Interface(
77
- fn=gradio_face_swap,
78
- inputs=[
79
- gr.Image(label="Upload Source Face"),
80
- gr.Image(label="Upload Target Image")
81
- ],
82
- outputs=gr.Image(label="Swapped Face"),
83
- title="AI Face Swap",
84
- description="Upload two images: one with the source face and another where you want the face swapped.",
85
- live=True
86
- )
87
-
88
- # Launch Gradio
89
- app = gr.mount_gradio_app(app, gr_interface, path="/")
90
 
91
- if __name__ == "__main__":
92
- import uvicorn
93
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
1
  import gradio as gr
 
2
  import numpy as np
3
+ import cv2
4
+ import onnxruntime
 
5
  from insightface.app import FaceAnalysis
 
6
  from pathlib import Path
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # Initialize Face Analysis
9
+ face_analyzer = FaceAnalysis(name="buffalo_l")
10
+ face_analyzer.prepare(ctx_id=0, det_size=(640, 640))
 
11
 
12
+ # Load Face Swapper Model
13
  MODEL_PATH = Path("models/inswapper_128.onnx")
14
+ if not MODEL_PATH.exists():
15
+ raise FileNotFoundError("Model file inswapper_128.onnx not found.")
16
 
17
+ session = onnxruntime.InferenceSession(str(MODEL_PATH))
18
+
19
+ def swap_faces(source_img, target_img):
20
+ """Perform face swapping using the ONNX model."""
21
+ try:
22
+ # Convert images to correct format
23
+ source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)
24
+ target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)
 
 
25
 
26
+ # Detect faces
27
+ source_faces = face_analyzer.get(source_img)
28
+ target_faces = face_analyzer.get(target_img)
29
 
30
+ if not source_faces or not target_faces:
31
+ return "No faces detected in one or both images."
32
+ if len(source_faces) > 1 or len(target_faces) > 1:
33
+ return "Multiple faces detected; only one face per image is supported."
34
 
35
+ source_face = source_faces[0]
36
+ target_face = target_faces[0]
 
 
37
 
38
+ # Prepare input data for ONNX model
39
+ input_data = {
40
+ "target_image": target_img,
41
+ "target_face": target_face.embedding,
42
+ "source_face": source_face.embedding
43
+ }
44
 
45
+ # Run the ONNX model
46
+ result = session.run(None, input_data)[0]
 
 
47
 
48
+ # Convert result to image format
49
+ result_img = np.clip(result * 255, 0, 255).astype(np.uint8)
50
+ result_img = cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB)
51
 
52
+ return result_img
 
 
 
 
 
 
53
  except Exception as e:
54
+ return f"Face swap failed: {e}"
55
 
56
+ # Gradio UI
57
+ with gr.Blocks() as demo:
58
+ gr.Markdown("# Face Swap Tool 🚀")
59
+ with gr.Row():
60
+ input_source = gr.Image(label="Source Face", type="pil")
61
+ input_target = gr.Image(label="Target Image", type="pil")
62
+ btn_swap = gr.Button("Swap Faces")
63
+ output_image = gr.Image(label="Swapped Face")
64
+ btn_swap.click(swap_faces, inputs=[input_source, input_target], outputs=output_image)
 
 
 
 
 
65
 
66
+ # Launch Gradio App
67
+ demo.launch()