import torch import torch.nn as nn from torchvision import transforms import timm import cv2 import numpy as np from fastapi import FastAPI, File, UploadFile, HTTPException, Request from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates from pydantic import BaseModel import os # ======================= 1. CONFIGURATION & SETUP ======================= # Set device for PyTorch DEVICE = "cuda" if torch.cuda.is_available() else "cpu" IMG_SIZE = 224 # Standard size for ViT-Base (224x224) # --- SINGLE-LAYER ANTI-SPOOFING THRESHOLD (ViT) --- # Thresold set to 0.50 (50%). ML_CONFIDENCE_THRESHOLD = 0.95 # Model Filename MODEL_FILENAME = "newonevits_qr_best_v2.pth" # Global variables for model and transformation model = None transform = None qr_detector = cv2.QRCodeDetector() # Used for image cropping (now unused) # Templates directory setup templates = Jinja2Templates(directory="templates") # FastAPI instance app = FastAPI(title="QR Code Anti-Spoofing API (ViT Only)") # API Response Model for structured output class PredictionResult(BaseModel): is_real: bool confidence: float message: str # ======================= 2. MODEL LOADING (ViT) ======================= @app.on_event("startup") async def load_ml_model(): """Loads the Vision Transformer (ViT) model and weights upon server startup.""" global model, transform # ImageNet Mean and Standard Deviation (CRITICAL for ML STABILITY) IMAGENET_MEAN = [0.485, 0.456, 0.406] IMAGENET_STD = [0.229, 0.224, 0.225] # Add Normalization required by the ViT training process transform = transforms.Compose([ transforms.ToPILImage(), transforms.Resize((IMG_SIZE, IMG_SIZE)), transforms.ToTensor(), # Converts to C, H, W and normalizes to 0-1 transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD) ]) try: model = timm.create_model('vit_base_patch16_224', pretrained=False, num_classes=2).to(DEVICE) if not os.path.exists(MODEL_FILENAME): raise FileNotFoundError(f"Model file not found: {MODEL_FILENAME}") model.load_state_dict(torch.load(MODEL_FILENAME, map_location=DEVICE)) model.eval() print(f"✅ Vision Transformer (ViT-Base) Model '{MODEL_FILENAME}' loaded successfully (Single-Layer).") except Exception as e: print(f"⚠️ Model loading error: {e}. Check if '{MODEL_FILENAME}' is in the current directory and matches the ViT architecture.") model = None # ======================= 3. HELPER FUNCTIONS ======================= def get_qr_code_region(image_np): """Returns the entire image without cropping, as requested by the user. NOTE: The ViT model will now process the full image, which might reduce accuracy if the QR code is small or the background is complex.""" # Returning the original image as requested. return image_np # NOTE: The fft_screen_check function has been REMOVED as requested. # ======================= 4. API ENDPOINTS ======================= @app.get("/", response_class=HTMLResponse) async def home(request: Request): """Serve the HTML frontend page using Jinja2 templates.""" # Ensure the templates directory and index.html are correctly set up return templates.TemplateResponse("index.html", {"request": request}) @app.post("/scan", response_model=PredictionResult) async def scan_card(file: UploadFile = File(...)): """The main endpoint for anti-spoofing detection (ViT Only).""" if model is None: raise HTTPException(status_code=503, detail="ML model is not loaded. Check server logs.") try: # 1. Read the uploaded file and decode it into a NumPy array contents = await file.read() image_np = np.frombuffer(contents, np.uint8) image_np = cv2.imdecode(image_np, cv2.IMREAD_COLOR) if image_np is None: raise HTTPException(status_code=400, detail="Invalid image file or format.") # 2. Prepare image for ML: Now uses the full image (No cropping) cropped_img_np = get_qr_code_region(image_np) # 3. ViT ML Classification (Single Layer) img_rgb = cv2.cvtColor(cropped_img_np, cv2.COLOR_BGR2RGB) # Apply transforms (including Normalization) and add batch dimension (N, C, H, W) img_tensor = transform(img_rgb).unsqueeze(0).to(DEVICE) # Run model inference with torch.no_grad(): output = model(img_tensor) probabilities = torch.softmax(output, dim=1)[0] # Extract results (Real: Index 1). Training logs confirmed FAKE=0, REAL=1. real_prob = probabilities[1].item() # 4. Apply the ML Confidence Threshold prediction = real_prob > ML_CONFIDENCE_THRESHOLD if prediction: return PredictionResult( is_real=True, confidence=real_prob, message=f"**REAL CARD CONFIRMED**. ViT Confidence: {real_prob:.2f} (Threshold: {ML_CONFIDENCE_THRESHOLD})" ) else: # Failed the single ViT check return PredictionResult( is_real=False, # Confidence reported will be the Fake probability (Index 0) confidence=probabilities[0].item(), message=f"**FAKE (Printout/Photo/Screen)**. ViT confidence too low for REAL. (Confidence: {real_prob:.2f} < {ML_CONFIDENCE_THRESHOLD})" ) except Exception as e: print(f"Error during scan: {e}") raise HTTPException(status_code=500, detail=f"Internal server error: {e}")