Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,22 +1,15 @@
|
|
| 1 |
# -*- coding:UTF-8 -*-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
import
|
| 5 |
-
from roop.core import start, decode_execution_providers
|
| 6 |
-
from roop.processors.frame.core import get_frame_processors_modules
|
| 7 |
-
from roop.utilities import normalize_output_path
|
| 8 |
-
from roop.face_analyser import get_many_faces
|
| 9 |
-
import os
|
| 10 |
-
import requests
|
| 11 |
import cv2
|
| 12 |
-
|
| 13 |
from PIL import Image
|
| 14 |
-
|
| 15 |
-
from fastapi.responses import FileResponse
|
| 16 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 17 |
import shutil
|
| 18 |
import logging
|
| 19 |
-
import
|
|
|
|
| 20 |
|
| 21 |
app = FastAPI()
|
| 22 |
|
|
@@ -27,26 +20,12 @@ logger = logging.getLogger(__name__)
|
|
| 27 |
# Add CORS middleware
|
| 28 |
app.add_middleware(
|
| 29 |
CORSMiddleware,
|
| 30 |
-
allow_origins=["*"], # Update with
|
| 31 |
allow_credentials=True,
|
| 32 |
allow_methods=["*"],
|
| 33 |
allow_headers=["*"],
|
| 34 |
)
|
| 35 |
|
| 36 |
-
article_text = """
|
| 37 |
-
<div style="text-align: center;">
|
| 38 |
-
<p>Enjoying the tool? Buy me a coffee and get exclusive prompt guides!</p>
|
| 39 |
-
<p><i>Instantly unlock helpful tips for creating better prompts!</i></p>
|
| 40 |
-
<div style="display: flex; justify-content: center;">
|
| 41 |
-
<a href=\"https://piczify.lemonsqueezy.com/buy/0f5206fa-68e8-42f6-9ca8-4f80c587c83e\">
|
| 42 |
-
<img src=\"https://www.buymeacoffee.com/assets/img/custom_images/yellow_img.png\"
|
| 43 |
-
alt=\"Buy Me a Coffee\"
|
| 44 |
-
style=\"height: 40px; width: auto; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); border-radius: 10px;\">
|
| 45 |
-
</a>
|
| 46 |
-
</div>
|
| 47 |
-
</div>
|
| 48 |
-
"""
|
| 49 |
-
|
| 50 |
def download_model():
|
| 51 |
model_dir = Path("models")
|
| 52 |
model_path = model_dir / "inswapper_128.onnx"
|
|
@@ -64,96 +43,96 @@ def download_model():
|
|
| 64 |
logger.info("Model downloaded successfully.")
|
| 65 |
except Exception as e:
|
| 66 |
logger.error(f"Failed to download model: {e}")
|
| 67 |
-
raise RuntimeError("Could not download inswapper_128.onnx. Please
|
| 68 |
-
else:
|
| 69 |
-
logger.info("Model already exists at: %s", model_path)
|
| 70 |
|
|
|
|
| 71 |
download_model()
|
| 72 |
|
| 73 |
-
def
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
@app.post("/swap-face/")
|
| 81 |
-
async def swap_face(source_file: UploadFile = File(...), target_file: UploadFile = File(...), doFaceEnhancer: bool = True
|
| 82 |
try:
|
| 83 |
# Save uploaded files temporarily
|
| 84 |
-
source_path = "
|
| 85 |
-
target_path = "
|
| 86 |
output_path = "output.jpg"
|
| 87 |
|
| 88 |
# Read and save source image
|
| 89 |
source_content = await source_file.read()
|
| 90 |
with open(source_path, "wb") as f:
|
| 91 |
f.write(source_content)
|
| 92 |
-
|
| 93 |
-
|
|
|
|
| 94 |
|
| 95 |
-
# Read and save target image
|
| 96 |
target_content = await target_file.read()
|
| 97 |
with open(target_path, "wb") as f:
|
| 98 |
f.write(target_content)
|
| 99 |
-
target_image = Image.open(target_path)
|
| 100 |
-
target_size = target_image.size
|
| 101 |
-
target_image.save(target_path, quality=100, subsampling=0)
|
| 102 |
-
|
| 103 |
-
# Load images as NumPy arrays for face detection
|
| 104 |
-
source_img = cv2.imread(source_path)
|
| 105 |
target_img = cv2.imread(target_path)
|
| 106 |
-
if
|
| 107 |
-
raise
|
| 108 |
-
|
| 109 |
-
# Debug: Check face detection
|
| 110 |
-
logger.info("Source faces detected: %s", get_many_faces(source_img))
|
| 111 |
-
logger.info("Target faces detected: %s", get_many_faces(target_img))
|
| 112 |
-
|
| 113 |
-
# Set up roop globals
|
| 114 |
-
roop.globals.source_path = source_path
|
| 115 |
-
roop.globals.target_path = target_path
|
| 116 |
-
roop.globals.output_path = normalize_output_path(
|
| 117 |
-
roop.globals.source_path, roop.globals.target_path, output_path
|
| 118 |
-
)
|
| 119 |
-
roop.globals.frame_processors = ["face_swapper", "face_enhancer"]
|
| 120 |
-
roop.globals.headless = True
|
| 121 |
-
roop.globals.keep_fps = True
|
| 122 |
-
roop.globals.keep_audio = True
|
| 123 |
-
roop.globals.keep_frames = False
|
| 124 |
-
roop.globals.many_faces = False
|
| 125 |
-
roop.globals.reference_face_position = 0
|
| 126 |
-
roop.globals.similar_face_distance = 0.6
|
| 127 |
-
roop.globals.video_encoder = "libx264"
|
| 128 |
-
roop.globals.video_quality = 18
|
| 129 |
-
roop.globals.max_memory = 16
|
| 130 |
-
roop.globals.execution_providers = decode_execution_providers(["cpu"])
|
| 131 |
-
roop.globals.execution_threads = 4
|
| 132 |
-
|
| 133 |
-
logger.info("Using frame processors: %s", roop.globals.frame_processors)
|
| 134 |
-
|
| 135 |
-
# Validate frame processors
|
| 136 |
-
for frame_processor in get_frame_processors_modules(
|
| 137 |
-
roop.globals.frame_processors
|
| 138 |
-
):
|
| 139 |
-
if not frame_processor.pre_check():
|
| 140 |
-
raise HTTPException(status_code=500, detail=f"Pre-check failed for {frame_processor.__name__}")
|
| 141 |
|
| 142 |
# Perform face swap
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
except Exception as e:
|
| 154 |
logger.error("Error in swap_face: %s", str(e))
|
| 155 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 156 |
-
|
| 157 |
-
if __name__ == "__main__":
|
| 158 |
-
import uvicorn
|
| 159 |
-
uvicorn.run(app, host="127.0.0.1", port=8000)
|
|
|
|
| 1 |
# -*- coding:UTF-8 -*-
|
| 2 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 3 |
+
from fastapi.responses import Response
|
| 4 |
+
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import cv2
|
| 6 |
+
import numpy as np
|
| 7 |
from PIL import Image
|
| 8 |
+
import os
|
|
|
|
|
|
|
| 9 |
import shutil
|
| 10 |
import logging
|
| 11 |
+
import requests
|
| 12 |
+
from pathlib import Path
|
| 13 |
|
| 14 |
app = FastAPI()
|
| 15 |
|
|
|
|
| 20 |
# Add CORS middleware
|
| 21 |
app.add_middleware(
|
| 22 |
CORSMiddleware,
|
| 23 |
+
allow_origins=["*"], # Update with Framer domain in production
|
| 24 |
allow_credentials=True,
|
| 25 |
allow_methods=["*"],
|
| 26 |
allow_headers=["*"],
|
| 27 |
)
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
def download_model():
|
| 30 |
model_dir = Path("models")
|
| 31 |
model_path = model_dir / "inswapper_128.onnx"
|
|
|
|
| 43 |
logger.info("Model downloaded successfully.")
|
| 44 |
except Exception as e:
|
| 45 |
logger.error(f"Failed to download model: {e}")
|
| 46 |
+
raise RuntimeError("Could not download inswapper_128.onnx. Please check logs.")
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
# Download model on startup
|
| 49 |
download_model()
|
| 50 |
|
| 51 |
+
def get_many_faces(image):
|
| 52 |
+
"""Simplified face detection using insightface (placeholder)."""
|
| 53 |
+
from insightface.app import FaceAnalysis
|
| 54 |
+
app = FaceAnalysis(name="buffalo_l")
|
| 55 |
+
app.prepare(ctx_id=0, det_size=(640, 640))
|
| 56 |
+
faces = app.get(image)
|
| 57 |
+
return faces if faces else []
|
| 58 |
+
|
| 59 |
+
def swap_faces(source_img, target_img):
|
| 60 |
+
"""Perform face swapping using insightface and inswapper model."""
|
| 61 |
+
from insightface.utils import face_align
|
| 62 |
+
from insightface.model_zoo import face_swapper
|
| 63 |
+
|
| 64 |
+
# Initialize face analysis
|
| 65 |
+
face_analyzer = FaceAnalysis(name="buffalo_l")
|
| 66 |
+
face_analyzer.prepare(ctx_id=0, det_size=(640, 640))
|
| 67 |
+
|
| 68 |
+
# Detect faces
|
| 69 |
+
source_faces = face_analyzer.get(source_img)
|
| 70 |
+
target_faces = face_analyzer.get(target_img)
|
| 71 |
+
|
| 72 |
+
if not source_faces or not target_faces:
|
| 73 |
+
raise ValueError("No faces detected in one or both images.")
|
| 74 |
+
if len(source_faces) > 1 or len(target_faces) > 1:
|
| 75 |
+
raise ValueError("Multiple faces detected; only one face per image is supported.")
|
| 76 |
+
|
| 77 |
+
source_face = source_faces[0]
|
| 78 |
+
target_face = target_faces[0]
|
| 79 |
+
|
| 80 |
+
# Load the face swapper model
|
| 81 |
+
model_path = Path("models/inswapper_128.onnx")
|
| 82 |
+
swapper = face_swapper.FaceSwapper(model_path)
|
| 83 |
+
|
| 84 |
+
# Perform face swap
|
| 85 |
+
result = swapper.get(target_img, target_face, source_face, paste_back=True)
|
| 86 |
+
|
| 87 |
+
# Resize to match target image size
|
| 88 |
+
target_pil = Image.fromarray(cv2.cvtColor(target_img, cv2.COLOR_BGR2RGB))
|
| 89 |
+
result_pil = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
|
| 90 |
+
result_pil = result_pil.resize(target_pil.size, Image.Resampling.LANCZOS)
|
| 91 |
+
|
| 92 |
+
return cv2.cvtColor(np.array(result_pil), cv2.COLOR_RGB2BGR)
|
| 93 |
|
| 94 |
@app.post("/swap-face/")
|
| 95 |
+
async def swap_face(source_file: UploadFile = File(...), target_file: UploadFile = File(...), doFaceEnhancer: bool = True):
|
| 96 |
try:
|
| 97 |
# Save uploaded files temporarily
|
| 98 |
+
source_path = "temp_source.jpg"
|
| 99 |
+
target_path = "temp_target.jpg"
|
| 100 |
output_path = "output.jpg"
|
| 101 |
|
| 102 |
# Read and save source image
|
| 103 |
source_content = await source_file.read()
|
| 104 |
with open(source_path, "wb") as f:
|
| 105 |
f.write(source_content)
|
| 106 |
+
source_img = cv2.imread(source_path)
|
| 107 |
+
if source_img is None:
|
| 108 |
+
raise ValueError("Failed to load source image.")
|
| 109 |
|
| 110 |
+
# Read and save target image
|
| 111 |
target_content = await target_file.read()
|
| 112 |
with open(target_path, "wb") as f:
|
| 113 |
f.write(target_content)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
target_img = cv2.imread(target_path)
|
| 115 |
+
if target_img is None:
|
| 116 |
+
raise ValueError("Failed to load target image.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
# Perform face swap
|
| 119 |
+
result_img = swap_faces(source_img, target_img)
|
| 120 |
+
|
| 121 |
+
# Save the result
|
| 122 |
+
cv2.imwrite(output_path, result_img)
|
| 123 |
+
|
| 124 |
+
# Read the output image
|
| 125 |
+
with open(output_path, "rb") as f:
|
| 126 |
+
image_data = f.read()
|
| 127 |
+
|
| 128 |
+
# Clean up temporary files
|
| 129 |
+
for path in [source_path, target_path, output_path]:
|
| 130 |
+
if os.path.exists(path):
|
| 131 |
+
os.remove(path)
|
| 132 |
+
|
| 133 |
+
# Return the swapped image
|
| 134 |
+
return Response(content=image_data, media_type="image/jpeg")
|
| 135 |
+
|
| 136 |
except Exception as e:
|
| 137 |
logger.error("Error in swap_face: %s", str(e))
|
| 138 |
+
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
|
|
|
|
|
|