from fastapi import FastAPI, File, UploadFile from fastapi.responses import Response from io import BytesIO from PIL import Image import torch import uvicorn import os import sys sys.path.append('CodeFormer') import os import cv2 import torch import torch.nn.functional as F import gradio as gr from torchvision.transforms.functional import normalize from basicsr.utils import imwrite, img2tensor, tensor2img from basicsr.utils.download_util import load_file_from_url from facelib.utils.face_restoration_helper import FaceRestoreHelper from basicsr.archs.rrdbnet_arch import RRDBNet from basicsr.utils.realesrgan_utils import RealESRGANer from facelib.utils.misc import is_gray from basicsr.utils.registry import ARCH_REGISTRY os.system("pip freeze") pretrain_model_url = { 'codeformer': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth', 'detection': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/detection_Resnet50_Final.pth', 'parsing': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/parsing_parsenet.pth', 'realesrgan': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/RealESRGAN_x2plus.pth' } # download weights if not os.path.exists('CodeFormer/weights/CodeFormer/codeformer.pth'): load_file_from_url(url=pretrain_model_url['codeformer'], model_dir='CodeFormer/weights/CodeFormer', progress=True, file_name=None) if not os.path.exists('CodeFormer/weights/facelib/detection_Resnet50_Final.pth'): load_file_from_url(url=pretrain_model_url['detection'], model_dir='CodeFormer/weights/facelib', progress=True, file_name=None) if not os.path.exists('CodeFormer/weights/facelib/parsing_parsenet.pth'): load_file_from_url(url=pretrain_model_url['parsing'], model_dir='CodeFormer/weights/facelib', progress=True, file_name=None) if not os.path.exists('CodeFormer/weights/realesrgan/RealESRGAN_x2plus.pth'): load_file_from_url(url=pretrain_model_url['realesrgan'], model_dir='CodeFormer/weights/realesrgan', progress=True, file_name=None) # Import the CodeFormer model processing function from codeformer_model import enhance_image # Make sure this function is defined app = FastAPI() @app.post("/enhance") async def enhance_image_api(file: UploadFile = File(...)): try: # Load image image = Image.open(file.file).convert("RGB") # Process the image using the CodeFormer model enhanced_image = enhance_image(image) # Convert the processed image to bytes img_byte_arr = BytesIO() enhanced_image.save(img_byte_arr, format="PNG") img_byte_arr = img_byte_arr.getvalue() return Response(content=img_byte_arr, media_type="image/png") except Exception as e: return {"error": str(e)} # Required to run on Hugging Face Spaces if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", 7860)))