import io import logging from typing import Tuple import torch import lpips import numpy as np from fastapi import FastAPI, File, UploadFile, HTTPException from PIL import Image, UnidentifiedImageError logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Force CPU in Spaces container device = "cpu" logger.info(f"Using device: {device}") # Preload LPIPS (AlexNet) loss = lpips.LPIPS(net="alex").to(device).eval() logger.info("LPIPS model loaded successfully") app = FastAPI( title="Image Duplicate Detection API", description="API for detecting duplicate images using LPIPS perceptual similarity", version="1.0.0", ) def to_tensor(img: Image.Image, size: Tuple[int, int] = (256, 256)) -> torch.Tensor: img = img.convert("RGB").resize(size, Image.LANCZOS) arr = (np.asarray(img).astype("float32") / 255.0) * 2.0 - 1.0 return torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).to(device) @app.get("/health") async def health_check(): return {"status": "healthy", "device": device, "port": 7860} @app.post("/score") async def score(img1: UploadFile = File(...), img2: UploadFile = File(...)): if not (img1.content_type or "").startswith("image/"): raise HTTPException(status_code=400, detail="img1 must be an image file") if not (img2.content_type or "").startswith("image/"): raise HTTPException(status_code=400, detail="img2 must be an image file") try: pil_img1 = Image.open(io.BytesIO(await img1.read())) pil_img2 = Image.open(io.BytesIO(await img2.read())) except UnidentifiedImageError: raise HTTPException(status_code=400, detail="Invalid image format. Use PNG/JPG/JPEG/WEBP.") a, b = to_tensor(pil_img1), to_tensor(pil_img2) with torch.no_grad(): similarity_score = float(loss(a, b).item()) is_duplicate = similarity_score <= 0.08 return { "lpips": similarity_score, "is_duplicate": is_duplicate, "threshold": 0.08, "interpretation": "Lower LPIPS scores indicate higher similarity", } @app.get("/") async def root(): return { "message": "Image Duplicate Detection API", "version": "1.0.0", "endpoints": {"/score": "POST", "/health": "GET", "/docs": "GET"}, }