cog_predict.py 6.7 KB

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