Path: blob/master/modules/gfpgan_model.py
3055 views
from __future__ import annotations12import logging3import os45import torch67from modules import (8devices,9errors,10face_restoration,11face_restoration_utils,12modelloader,13shared,14)1516logger = logging.getLogger(__name__)17model_url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth"18model_download_name = "GFPGANv1.4.pth"19gfpgan_face_restorer: face_restoration.FaceRestoration | None = None202122class FaceRestorerGFPGAN(face_restoration_utils.CommonFaceRestoration):23def name(self):24return "GFPGAN"2526def get_device(self):27return devices.device_gfpgan2829def load_net(self) -> torch.Module:30for model_path in modelloader.load_models(31model_path=self.model_path,32model_url=model_url,33command_path=self.model_path,34download_name=model_download_name,35ext_filter=['.pth'],36):37if 'GFPGAN' in os.path.basename(model_path):38return modelloader.load_spandrel_model(39model_path,40device=self.get_device(),41expected_architecture='GFPGAN',42).model43raise ValueError("No GFPGAN model found")4445def restore(self, np_image):46def restore_face(cropped_face_t):47assert self.net is not None48return self.net(cropped_face_t, return_rgb=False)[0]4950return self.restore_with_helper(np_image, restore_face)515253def gfpgan_fix_faces(np_image):54if gfpgan_face_restorer:55return gfpgan_face_restorer.restore(np_image)56logger.warning("GFPGAN face restorer not set up")57return np_image585960def setup_model(dirname: str) -> None:61global gfpgan_face_restorer6263try:64face_restoration_utils.patch_facexlib(dirname)65gfpgan_face_restorer = FaceRestorerGFPGAN(model_path=dirname)66shared.face_restorers.append(gfpgan_face_restorer)67except Exception:68errors.report("Error setting up GFPGAN", exc_info=True)697071