cog_predict.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. # flake8: noqa
  2. # This file is used for deploying replicate models
  3. # running: cog predict -i img=@inputs/00017_gray.png -i version='General - v3' -i scale=2 -i face_enhance=True -i tile=0
  4. # push: cog push r8.im/xinntao/realesrgan
  5. import os
  6. os.system('pip install gfpgan')
  7. os.system('python setup.py develop')
  8. import cv2
  9. import shutil
  10. import tempfile
  11. import torch
  12. from basicsr.archs.rrdbnet_arch import RRDBNet
  13. from basicsr.archs.srvgg_arch import SRVGGNetCompact
  14. from realesrgan.utils import RealESRGANer
  15. try:
  16. from cog import BasePredictor, Input, Path
  17. from gfpgan import GFPGANer
  18. except Exception:
  19. print('please install cog and realesrgan package')
  20. class Predictor(BasePredictor):
  21. def setup(self):
  22. os.makedirs('output', exist_ok=True)
  23. # download weights
  24. if not os.path.exists('weights/realesr-general-x4v3.pth'):
  25. os.system(
  26. 'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth -P ./weights'
  27. )
  28. if not os.path.exists('weights/GFPGANv1.4.pth'):
  29. os.system('wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P ./weights')
  30. if not os.path.exists('weights/RealESRGAN_x4plus.pth'):
  31. os.system(
  32. 'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P ./weights'
  33. )
  34. if not os.path.exists('weights/RealESRGAN_x4plus_anime_6B.pth'):
  35. os.system(
  36. 'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P ./weights'
  37. )
  38. if not os.path.exists('weights/realesr-animevideov3.pth'):
  39. os.system(
  40. 'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth -P ./weights'
  41. )
  42. def choose_model(self, scale, version, tile=0):
  43. half = True if torch.cuda.is_available() else False
  44. if version == 'General - RealESRGANplus':
  45. model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
  46. model_path = 'weights/RealESRGAN_x4plus.pth'
  47. self.upsampler = RealESRGANer(
  48. scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)
  49. elif version == 'General - v3':
  50. model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
  51. model_path = 'weights/realesr-general-x4v3.pth'
  52. self.upsampler = RealESRGANer(
  53. scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)
  54. elif version == 'Anime - anime6B':
  55. model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)
  56. model_path = 'weights/RealESRGAN_x4plus_anime_6B.pth'
  57. self.upsampler = RealESRGANer(
  58. scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)
  59. elif version == 'AnimeVideo - v3':
  60. model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')
  61. model_path = 'weights/realesr-animevideov3.pth'
  62. self.upsampler = RealESRGANer(
  63. scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)
  64. self.face_enhancer = GFPGANer(
  65. model_path='weights/GFPGANv1.4.pth',
  66. upscale=scale,
  67. arch='clean',
  68. channel_multiplier=2,
  69. bg_upsampler=self.upsampler)
  70. def predict(
  71. self,
  72. img: Path = Input(description='Input'),
  73. version: str = Input(
  74. description='RealESRGAN version. Please see [Readme] below for more descriptions',
  75. choices=['General - RealESRGANplus', 'General - v3', 'Anime - anime6B', 'AnimeVideo - v3'],
  76. default='General - v3'),
  77. scale: float = Input(description='Rescaling factor', default=2),
  78. face_enhance: bool = Input(
  79. description='Enhance faces with GFPGAN. Note that it does not work for anime images/vidoes', default=False),
  80. tile: int = Input(
  81. description=
  82. 'Tile size. Default is 0, that is no tile. When encountering the out-of-GPU-memory issue, please specify it, e.g., 400 or 200',
  83. default=0)
  84. ) -> Path:
  85. if tile <= 100 or tile is None:
  86. tile = 0
  87. print(f'img: {img}. version: {version}. scale: {scale}. face_enhance: {face_enhance}. tile: {tile}.')
  88. try:
  89. extension = os.path.splitext(os.path.basename(str(img)))[1]
  90. img = cv2.imread(str(img), cv2.IMREAD_UNCHANGED)
  91. if len(img.shape) == 3 and img.shape[2] == 4:
  92. img_mode = 'RGBA'
  93. elif len(img.shape) == 2:
  94. img_mode = None
  95. img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
  96. else:
  97. img_mode = None
  98. h, w = img.shape[0:2]
  99. if h < 300:
  100. img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4)
  101. self.choose_model(scale, version, tile)
  102. try:
  103. if face_enhance:
  104. _, _, output = self.face_enhancer.enhance(
  105. img, has_aligned=False, only_center_face=False, paste_back=True)
  106. else:
  107. output, _ = self.upsampler.enhance(img, outscale=scale)
  108. except RuntimeError as error:
  109. print('Error', error)
  110. print('If you encounter CUDA out of memory, try to set "tile" to a smaller size, e.g., 400.')
  111. if img_mode == 'RGBA': # RGBA images should be saved in png format
  112. extension = 'png'
  113. # save_path = f'output/out.{extension}'
  114. # cv2.imwrite(save_path, output)
  115. out_path = Path(tempfile.mkdtemp()) / f'out.{extension}'
  116. cv2.imwrite(str(out_path), output)
  117. except Exception as error:
  118. print('global exception: ', error)
  119. finally:
  120. clean_folder('output')
  121. return out_path
  122. def clean_folder(folder):
  123. for filename in os.listdir(folder):
  124. file_path = os.path.join(folder, filename)
  125. try:
  126. if os.path.isfile(file_path) or os.path.islink(file_path):
  127. os.unlink(file_path)
  128. elif os.path.isdir(file_path):
  129. shutil.rmtree(file_path)
  130. except Exception as e:
  131. print(f'Failed to delete {file_path}. Reason: {e}')