tuan2308 commited on
Commit
f945872
·
verified ·
1 Parent(s): 9c02e65

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -19
app.py CHANGED
@@ -8,21 +8,15 @@ from basicsr.archs.rrdbnet_arch import RRDBNet
8
  from basicsr.utils.download_util import load_file_from_url
9
  from realesrgan import RealESRGANer
10
  from realesrgan.archs.srvgg_arch import SRVGGNetCompact
 
11
 
12
  last_file = None
13
- img_mode = "RGB"
14
-
15
- def image_properties(img):
16
- """Returns the dimensions (width and height) and color mode of the input image"""
17
- global img_mode
18
- if img:
19
- img_mode = "RGB" # Force the image mode to RGB
20
- properties = f"Resolution: Width: {img.size[0]}, Height: {img.size[1]} | Color Mode: {img_mode}"
21
- return properties
22
 
23
  @spaces.GPU(duration=120)
24
  def realesrgan(img, model_name, denoise_strength, face_enhance, outscale):
25
- """Real-ESRGAN function to restore (and upscale) images."""
 
26
  if not img:
27
  return
28
 
@@ -56,6 +50,7 @@ def realesrgan(img, model_name, denoise_strength, face_enhance, outscale):
56
  if not os.path.isfile(model_path):
57
  ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
58
  for url in file_url:
 
59
  model_path = load_file_from_url(
60
  url=url, model_dir=os.path.join(ROOT_DIR, 'weights'), progress=True, file_name=None)
61
 
@@ -89,9 +84,9 @@ def realesrgan(img, model_name, denoise_strength, face_enhance, outscale):
89
  channel_multiplier=2,
90
  bg_upsampler=upsampler)
91
 
92
- # Convert the input PIL image to cv2 image (forcing RGB mode)
93
- cv_img = numpy.array(img.convert("RGB"))
94
- img = cv2.cvtColor(cv_img, cv2.COLOR_RGB2BGR)
95
 
96
  # Apply restoration
97
  try:
@@ -103,8 +98,13 @@ def realesrgan(img, model_name, denoise_strength, face_enhance, outscale):
103
  print('Error', error)
104
  print('If you encounter CUDA out of memory, try to set --tile with a smaller number.')
105
  else:
106
- # Save restored image
107
- out_filename = f"output_{rnd_string(8)}.jpg"
 
 
 
 
 
108
  cv2.imwrite(out_filename, output)
109
  global last_file
110
  last_file = out_filename
@@ -112,14 +112,17 @@ def realesrgan(img, model_name, denoise_strength, face_enhance, outscale):
112
 
113
 
114
  def rnd_string(x):
115
- """Returns a string of 'x' random characters"""
 
116
  characters = "abcdefghijklmnopqrstuvwxyz_0123456789"
117
  result = "".join((random.choice(characters)) for i in range(x))
118
  return result
119
 
120
 
121
  def reset():
122
- """Resets the Image components of the Gradio interface and deletes the last processed image"""
 
 
123
  global last_file
124
  if last_file:
125
  print(f"Deleting {last_file} ...")
@@ -128,6 +131,44 @@ def reset():
128
  return gr.update(value=None), gr.update(value=None)
129
 
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  def main():
132
  # Gradio Interface
133
  with gr.Blocks(title="Real-ESRGAN Gradio Demo", theme="dark") as demo:
@@ -156,9 +197,9 @@ def main():
156
 
157
  with gr.Row():
158
  with gr.Group():
159
- input_image = gr.Image(label="Input Image", type="pil", image_mode="RGB")
160
  input_image_properties = gr.Textbox(label="Image Properties", max_lines=1)
161
- output_image = gr.Image(label="Output Image", image_mode="RGB")
162
  with gr.Row():
163
  reset_btn = gr.Button("Remove images")
164
  restore_btn = gr.Button("Upscale")
@@ -169,6 +210,8 @@ def main():
169
  inputs=[input_image, model_name, denoise_strength, face_enhance, outscale],
170
  outputs=output_image)
171
  reset_btn.click(fn=reset, inputs=[], outputs=[output_image, input_image])
 
 
172
 
173
  gr.Markdown(
174
  """Made with love by Ilaria 💖 | Support me on [Ko-Fi](https://ko-fi.com/ilariaowo) | Join [AI Hub](https://discord.gg/aihub)
 
8
  from basicsr.utils.download_util import load_file_from_url
9
  from realesrgan import RealESRGANer
10
  from realesrgan.archs.srvgg_arch import SRVGGNetCompact
11
+ from torchvision.transforms.functional import rgb_to_grayscale
12
 
13
  last_file = None
14
+ img_mode = "RGBA"
 
 
 
 
 
 
 
 
15
 
16
  @spaces.GPU(duration=120)
17
  def realesrgan(img, model_name, denoise_strength, face_enhance, outscale):
18
+ """Real-ESRGAN function to restore (and upscale) images.
19
+ """
20
  if not img:
21
  return
22
 
 
50
  if not os.path.isfile(model_path):
51
  ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
52
  for url in file_url:
53
+ # model_path will be updated
54
  model_path = load_file_from_url(
55
  url=url, model_dir=os.path.join(ROOT_DIR, 'weights'), progress=True, file_name=None)
56
 
 
84
  channel_multiplier=2,
85
  bg_upsampler=upsampler)
86
 
87
+ # Convert the input PIL image to cv2 image, so that it can be processed by realesrgan
88
+ cv_img = numpy.array(img)
89
+ img = cv2.cvtColor(cv_img, cv2.COLOR_RGBA2BGRA)
90
 
91
  # Apply restoration
92
  try:
 
98
  print('Error', error)
99
  print('If you encounter CUDA out of memory, try to set --tile with a smaller number.')
100
  else:
101
+ # Save restored image and return it to the output Image component
102
+ if img_mode == 'RGBA': # RGBA images should be saved in png format
103
+ extension = 'jpg'
104
+ else:
105
+ extension = 'jpg'
106
+
107
+ out_filename = f"output_{rnd_string(8)}.{extension}"
108
  cv2.imwrite(out_filename, output)
109
  global last_file
110
  last_file = out_filename
 
112
 
113
 
114
  def rnd_string(x):
115
+ """Returns a string of 'x' random characters
116
+ """
117
  characters = "abcdefghijklmnopqrstuvwxyz_0123456789"
118
  result = "".join((random.choice(characters)) for i in range(x))
119
  return result
120
 
121
 
122
  def reset():
123
+ """Resets the Image components of the Gradio interface and deletes
124
+ the last processed image
125
+ """
126
  global last_file
127
  if last_file:
128
  print(f"Deleting {last_file} ...")
 
131
  return gr.update(value=None), gr.update(value=None)
132
 
133
 
134
+ def has_transparency(img):
135
+ """This function works by first checking to see if a "transparency" property is defined
136
+ in the image's info -- if so, we return "True". Then, if the image is using indexed colors
137
+ (such as in GIFs), it gets the index of the transparent color in the palette
138
+ (img.info.get("transparency", -1)) and checks if it's used anywhere in the canvas
139
+ (img.getcolors()). If the image is in RGBA mode, then presumably it has transparency in
140
+ it, but it double-checks by getting the minimum and maximum values of every color channel
141
+ (img.getextrema()), and checks if the alpha channel's smallest value falls below 255.
142
+ https://stackoverflow.com/questions/43864101/python-pil-check-if-image-is-transparent
143
+ """
144
+ if img.info.get("transparency", None) is not None:
145
+ return True
146
+ if img.mode == "P":
147
+ transparent = img.info.get("transparency", -1)
148
+ for _, index in img.getcolors():
149
+ if index == transparent:
150
+ return True
151
+ elif img.mode == "RGBA":
152
+ extrema = img.getextrema()
153
+ if extrema[3][0] < 255:
154
+ return True
155
+ return False
156
+
157
+
158
+ def image_properties(img):
159
+ """Returns the dimensions (width and height) and color mode of the input image and
160
+ also sets the global img_mode variable to be used by the realesrgan function
161
+ """
162
+ global img_mode
163
+ if img:
164
+ if has_transparency(img):
165
+ img_mode = "RGBA"
166
+ else:
167
+ img_mode = "RGB"
168
+ properties = f"Resolution: Width: {img.size[0]}, Height: {img.size[1]} | Color Mode: {img_mode}"
169
+ return properties
170
+
171
+
172
  def main():
173
  # Gradio Interface
174
  with gr.Blocks(title="Real-ESRGAN Gradio Demo", theme="dark") as demo:
 
197
 
198
  with gr.Row():
199
  with gr.Group():
200
+ input_image = gr.Image(label="Input Image", type="pil", image_mode="RGBA")
201
  input_image_properties = gr.Textbox(label="Image Properties", max_lines=1)
202
+ output_image = gr.Image(label="Output Image", image_mode="RGBA")
203
  with gr.Row():
204
  reset_btn = gr.Button("Remove images")
205
  restore_btn = gr.Button("Upscale")
 
210
  inputs=[input_image, model_name, denoise_strength, face_enhance, outscale],
211
  outputs=output_image)
212
  reset_btn.click(fn=reset, inputs=[], outputs=[output_image, input_image])
213
+ # reset_btn.click(None, inputs=[], outputs=[input_image], _js="() => (null)\n")
214
+ # Undocumented method to clear a component's value using Javascript
215
 
216
  gr.Markdown(
217
  """Made with love by Ilaria 💖 | Support me on [Ko-Fi](https://ko-fi.com/ilariaowo) | Join [AI Hub](https://discord.gg/aihub)