|
|
import gradio as gr |
|
|
import cv2 |
|
|
import torch |
|
|
from gfpgan import GFPGANer |
|
|
import numpy as np |
|
|
import os |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
MODEL_PATH = 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth' |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
local_model_path = "GFPGANv1.3.pth" |
|
|
if not os.path.exists(local_model_path): |
|
|
print(f"Downloading model to {local_model_path}...") |
|
|
torch.hub.download_url_to_file(MODEL_PATH, local_model_path, progress=True) |
|
|
print("Model download complete.") |
|
|
else: |
|
|
print(f"Model {local_model_path} already exists.") |
|
|
|
|
|
|
|
|
restorer = GFPGANer( |
|
|
model_path=local_model_path, |
|
|
upscale=2, |
|
|
arch='clean', |
|
|
channel_multiplier=2, |
|
|
bg_upsampler=None, |
|
|
device='cpu' |
|
|
) |
|
|
|
|
|
def gfpgan_restore_face(input_image_np): |
|
|
""" |
|
|
Restores faces in an input image using GFPGAN. |
|
|
input_image_np: A NumPy array representing the input image (BGR format from cv2.imdecode). |
|
|
Returns a NumPy array representing the restored image (BGR format). |
|
|
""" |
|
|
if input_image_np is None: |
|
|
raise gr.Error("Error: Could not read input image. Please upload a valid image.") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
try: |
|
|
|
|
|
|
|
|
_, _, restored_img = restorer.enhance( |
|
|
input_image_np, |
|
|
has_aligned=False, |
|
|
only_center_face=False |
|
|
|
|
|
) |
|
|
except Exception as e: |
|
|
print(f"Error during GFPGAN processing: {e}") |
|
|
raise gr.Error(f"GFPGAN processing failed: {e}. Check server logs for details.") |
|
|
|
|
|
if restored_img is None: |
|
|
|
|
|
|
|
|
print("No faces were detected or restored by GFPGAN.") |
|
|
|
|
|
return input_image_np |
|
|
|
|
|
return restored_img |
|
|
|
|
|
|
|
|
iface = gr.Interface( |
|
|
fn=gfpgan_restore_face, |
|
|
inputs=gr.Image(type="numpy", label="Upload Input Image"), |
|
|
outputs=gr.Image(type="numpy", label="Restored Output Image"), |
|
|
title="GFPGAN Face Restoration (CPU)", |
|
|
description="Upload an image with faces to restore them using GFPGAN. Runs on CPU, so it might be slow for large images.", |
|
|
allow_flagging="never" |
|
|
) |
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
|
|
|
|
|
iface.launch() |