Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import base64
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
import requests
|
| 6 |
+
from fastapi import FastAPI
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
import insightface
|
| 9 |
+
|
| 10 |
+
# Load Face Detector + Recognition Model (first import may download weights)
|
| 11 |
+
model = insightface.app.FaceAnalysis(name="buffalo_l")
|
| 12 |
+
model.prepare(ctx_id=0, det_size=(640, 640))
|
| 13 |
+
|
| 14 |
+
app = FastAPI(title="Face Compare API")
|
| 15 |
+
|
| 16 |
+
class CompareRequest(BaseModel):
|
| 17 |
+
image1: str | None = None # base64
|
| 18 |
+
image2: str | None = None # base64
|
| 19 |
+
image1_url: str | None = None # URL
|
| 20 |
+
image2_url: str | None = None # URL
|
| 21 |
+
|
| 22 |
+
def b64_to_img(b64_string: str):
|
| 23 |
+
try:
|
| 24 |
+
img_data = base64.b64decode(b64_string)
|
| 25 |
+
arr = np.frombuffer(img_data, np.uint8)
|
| 26 |
+
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
|
| 27 |
+
return img
|
| 28 |
+
except Exception:
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
def url_to_img(url: str):
|
| 32 |
+
try:
|
| 33 |
+
resp = requests.get(url, timeout=10)
|
| 34 |
+
arr = np.frombuffer(resp.content, np.uint8)
|
| 35 |
+
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
|
| 36 |
+
return img
|
| 37 |
+
except Exception:
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
def get_embedding(img):
|
| 41 |
+
faces = model.get(img)
|
| 42 |
+
if len(faces) == 0:
|
| 43 |
+
return None
|
| 44 |
+
return faces[0].embedding
|
| 45 |
+
|
| 46 |
+
@app.post("/compare")
|
| 47 |
+
async def compare_faces(req: CompareRequest):
|
| 48 |
+
# Load images (prefer raw base64, else url)
|
| 49 |
+
img1 = b64_to_img(req.image1) if req.image1 else (url_to_img(req.image1_url) if req.image1_url else None)
|
| 50 |
+
img2 = b64_to_img(req.image2) if req.image2 else (url_to_img(req.image2_url) if req.image2_url else None)
|
| 51 |
+
|
| 52 |
+
if img1 is None or img2 is None:
|
| 53 |
+
return {"error": "Invalid image data or URL."}
|
| 54 |
+
|
| 55 |
+
emb1 = get_embedding(img1)
|
| 56 |
+
emb2 = get_embedding(img2)
|
| 57 |
+
|
| 58 |
+
if emb1 is None or emb2 is None:
|
| 59 |
+
return {"error": "No face detected in one or both images."}
|
| 60 |
+
|
| 61 |
+
# cosine similarity
|
| 62 |
+
similarity = float(np.dot(emb1, emb2) / (np.linalg.norm(emb1) * np.linalg.norm(emb2)))
|
| 63 |
+
matched = similarity > 0.55
|
| 64 |
+
|
| 65 |
+
return {"similarity": similarity, "match": matched}
|