orik-ss's picture
Updated backend
c6c7c4a
Raw History Blame Contribute Delete
5.94 kB
"""
Seventh Sense AI - Face Recognition API Backend
This FastAPI server acts as a secure proxy to the cloud Face Recognition API.
The API key is stored securely in HuggingFace Spaces secrets.
"""
import os
import httpx
import time
import base64
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional
app = FastAPI(
title="Seventh Sense AI - Face Recognition",
description="Advanced AI-powered face comparison technology",
version="1.0.0"
)
# CORS middleware for development
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
SEVENTHSENSE_API_KEY = os.environ.get("SEVENTHSENSE_API_KEY", "")
SEVENTHSENSE_API_URL = os.environ.get("SEVENTHSENSE_API_URL", "")
# Match threshold - scores above this are considered a match
MATCH_THRESHOLD = 0.67
# Response models
class CompareResponse(BaseModel):
match: bool
similarity: float
face1_bbox: Optional[dict] = None
face2_bbox: Optional[dict] = None
processing_time: Optional[int] = None
message: Optional[str] = None
@app.get("/api/health")
async def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"api_configured": bool(SEVENTHSENSE_API_KEY),
"version": "1.0.0"
}
@app.post("/api/compare", response_model=CompareResponse)
async def compare_faces(
image1: UploadFile = File(..., description="First face image (probe)"),
image2: UploadFile = File(..., description="Second face image (gallery)")
):
"""
Compare two face images and determine if they belong to the same person.
The API key is securely stored in HuggingFace Spaces secrets and never exposed to the client.
Uses your cloud API endpoint with base64 encoded images.
"""
start_time = time.time()
# Validate file types
allowed_types = ["image/jpeg", "image/jpg", "image/png", "image/webp"]
if image1.content_type not in allowed_types:
raise HTTPException(status_code=400, detail=f"Invalid file type for image1: {image1.content_type}")
if image2.content_type not in allowed_types:
raise HTTPException(status_code=400, detail=f"Invalid file type for image2: {image2.content_type}")
# Read image data
image1_data = await image1.read()
image2_data = await image2.read()
# Size validation (max 10MB each)
max_size = 10 * 1024 * 1024
if len(image1_data) > max_size or len(image2_data) > max_size:
raise HTTPException(status_code=400, detail="Image size exceeds 10MB limit")
# Check if API is configured
if not SEVENTHSENSE_API_KEY or not SEVENTHSENSE_API_URL:
# Demo mode - return mock response for testing UI
# Remove this in production and require API key
processing_time = int((time.time() - start_time) * 1000)
return CompareResponse(
match=True,
similarity=0.87,
face1_bbox={"x": 100, "y": 80, "width": 150, "height": 180},
face2_bbox={"x": 110, "y": 90, "width": 140, "height": 170},
processing_time=processing_time,
message="Demo mode - Configure SEVENTHSENSE_API_KEY and SEVENTHSENSE_API_URL for production"
)
# Convert images to base64
probe_b64 = base64.b64encode(image1_data).decode("utf-8")
gallery_b64 = base64.b64encode(image2_data).decode("utf-8")
# Call the Seventh Sense AI API
try:
async with httpx.AsyncClient(timeout=30.0) as client:
# Prepare the request payload matching your API format
payload = {
"probe": [probe_b64],
"gallery": [gallery_b64],
"search_mode": "FAST"
}
headers = {
"x-api-key": SEVENTHSENSE_API_KEY,
"Content-Type": "application/json"
}
response = await client.post(
f"{SEVENTHSENSE_API_URL}/compare",
json=payload,
headers=headers
)
if response.status_code != 200:
raise HTTPException(
status_code=response.status_code,
detail=f"API error: {response.text}"
)
result = response.json()
processing_time = int((time.time() - start_time) * 1000)
# Get score from response
score = result.get("score", 0.0)
is_match = score >= MATCH_THRESHOLD
return CompareResponse(
match=is_match,
similarity=score,
face1_bbox=result.get("face1_bbox"),
face2_bbox=result.get("face2_bbox"),
processing_time=processing_time
)
except httpx.TimeoutException:
raise HTTPException(status_code=504, detail="API request timed out")
except httpx.RequestError as e:
raise HTTPException(status_code=502, detail=f"Failed to connect to API: {str(e)}")
# Serve static files (React build)
# In production, the React build output goes to /static
static_dir = os.path.join(os.path.dirname(__file__), "..", "static")
if os.path.exists(static_dir):
app.mount("/assets", StaticFiles(directory=os.path.join(static_dir, "assets")), name="assets")
@app.get("/{path:path}")
async def serve_spa(path: str):
"""Serve the React SPA for all non-API routes"""
file_path = os.path.join(static_dir, path)
if os.path.exists(file_path) and os.path.isfile(file_path):
return FileResponse(file_path)
return FileResponse(os.path.join(static_dir, "index.html"))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)