codeformer_model.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import os
  2. import cv2
  3. import torch
  4. import modules.face_restoration
  5. import modules.shared
  6. from modules import shared, devices, modelloader, errors
  7. from modules.paths import models_path
  8. # codeformer people made a choice to include modified basicsr library to their project which makes
  9. # it utterly impossible to use it alongside with other libraries that also use basicsr, like GFPGAN.
  10. # I am making a choice to include some files from codeformer to work around this issue.
  11. model_dir = "Codeformer"
  12. model_path = os.path.join(models_path, model_dir)
  13. model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth'
  14. codeformer = None
  15. def setup_model(dirname):
  16. os.makedirs(model_path, exist_ok=True)
  17. path = modules.paths.paths.get("CodeFormer", None)
  18. if path is None:
  19. return
  20. try:
  21. from torchvision.transforms.functional import normalize
  22. from modules.codeformer.codeformer_arch import CodeFormer
  23. from basicsr.utils import img2tensor, tensor2img
  24. from facelib.utils.face_restoration_helper import FaceRestoreHelper
  25. from facelib.detection.retinaface import retinaface
  26. net_class = CodeFormer
  27. class FaceRestorerCodeFormer(modules.face_restoration.FaceRestoration):
  28. def name(self):
  29. return "CodeFormer"
  30. def __init__(self, dirname):
  31. self.net = None
  32. self.face_helper = None
  33. self.cmd_dir = dirname
  34. def create_models(self):
  35. if self.net is not None and self.face_helper is not None:
  36. self.net.to(devices.device_codeformer)
  37. return self.net, self.face_helper
  38. model_paths = modelloader.load_models(model_path, model_url, self.cmd_dir, download_name='codeformer-v0.1.0.pth', ext_filter=['.pth'])
  39. if len(model_paths) != 0:
  40. ckpt_path = model_paths[0]
  41. else:
  42. print("Unable to load codeformer model.")
  43. return None, None
  44. net = net_class(dim_embd=512, codebook_size=1024, n_head=8, n_layers=9, connect_list=['32', '64', '128', '256']).to(devices.device_codeformer)
  45. checkpoint = torch.load(ckpt_path)['params_ema']
  46. net.load_state_dict(checkpoint)
  47. net.eval()
  48. if hasattr(retinaface, 'device'):
  49. retinaface.device = devices.device_codeformer
  50. face_helper = FaceRestoreHelper(1, face_size=512, crop_ratio=(1, 1), det_model='retinaface_resnet50', save_ext='png', use_parse=True, device=devices.device_codeformer)
  51. self.net = net
  52. self.face_helper = face_helper
  53. return net, face_helper
  54. def send_model_to(self, device):
  55. self.net.to(device)
  56. self.face_helper.face_det.to(device)
  57. self.face_helper.face_parse.to(device)
  58. def restore(self, np_image, w=None):
  59. np_image = np_image[:, :, ::-1]
  60. original_resolution = np_image.shape[0:2]
  61. self.create_models()
  62. if self.net is None or self.face_helper is None:
  63. return np_image
  64. self.send_model_to(devices.device_codeformer)
  65. self.face_helper.clean_all()
  66. self.face_helper.read_image(np_image)
  67. self.face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5)
  68. self.face_helper.align_warp_face()
  69. for cropped_face in self.face_helper.cropped_faces:
  70. cropped_face_t = img2tensor(cropped_face / 255., bgr2rgb=True, float32=True)
  71. normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
  72. cropped_face_t = cropped_face_t.unsqueeze(0).to(devices.device_codeformer)
  73. try:
  74. with torch.no_grad():
  75. output = self.net(cropped_face_t, w=w if w is not None else shared.opts.code_former_weight, adain=True)[0]
  76. restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))
  77. del output
  78. devices.torch_gc()
  79. except Exception:
  80. errors.report('Failed inference for CodeFormer', exc_info=True)
  81. restored_face = tensor2img(cropped_face_t, rgb2bgr=True, min_max=(-1, 1))
  82. restored_face = restored_face.astype('uint8')
  83. self.face_helper.add_restored_face(restored_face)
  84. self.face_helper.get_inverse_affine(None)
  85. restored_img = self.face_helper.paste_faces_to_input_image()
  86. restored_img = restored_img[:, :, ::-1]
  87. if original_resolution != restored_img.shape[0:2]:
  88. restored_img = cv2.resize(restored_img, (0, 0), fx=original_resolution[1]/restored_img.shape[1], fy=original_resolution[0]/restored_img.shape[0], interpolation=cv2.INTER_LINEAR)
  89. self.face_helper.clean_all()
  90. if shared.opts.face_restoration_unload:
  91. self.send_model_to(devices.cpu)
  92. return restored_img
  93. global codeformer
  94. codeformer = FaceRestorerCodeFormer(dirname)
  95. shared.face_restorers.append(codeformer)
  96. except Exception:
  97. errors.report("Error setting up CodeFormer", exc_info=True)
  98. # sys.path = stored_sys_path