import os import cv2 import torch import uvicorn import numpy as np from fastapi import FastAPI, UploadFile, File, Form from fastapi.responses import HTMLResponse, JSONResponse from fastapi.staticfiles import StaticFiles from inference import Predictor from utils.image_processing import resize_image # ===================================================== # PERFORMANCE OPTIMIZATION # ===================================================== torch.set_grad_enabled(False) cv2.setNumThreads(0) # ===================================================== # CREATE OUTPUT FOLDER # ===================================================== os.makedirs("output", exist_ok=True) # ===================================================== # FASTAPI APP # ===================================================== app = FastAPI( title="AnimeGANv2 API", description="Fast Anime Cartoon Generator" ) app.mount("/output", StaticFiles(directory="output"), name="output") # ===================================================== # DEVICE # ===================================================== DEVICE = "cuda" if torch.cuda.is_available() else "cpu" print(f"Using device: {DEVICE}") # ===================================================== # STYLE MAP # ===================================================== STYLE_MAP = { "AnimeGAN_Hayao": "hayao", "AnimeGAN_Shinkai": "shinkai", "AnimeGANv2_Hayao": "hayao:v2", "AnimeGANv2_Shinkai": "shinkai:v2", "AnimeGANv2_Arcane": "arcane:v2", } # ===================================================== # MODEL CACHE # ===================================================== predictors = {} def get_predictor(style, imgsz): key = f"{style}_{imgsz}" if key not in predictors: print(f"Loading model: {style}") predictors[key] = Predictor( weight=STYLE_MAP[style], device=DEVICE, retain_color=False, imgsz=imgsz, ) return predictors[key] # ===================================================== # RESPONSIVE UI # ===================================================== HTML = """