anthienlong commited on
Commit
50ea707
·
verified ·
1 Parent(s): 32278d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -49
app.py CHANGED
@@ -2,77 +2,85 @@ import torch
2
  from PIL import Image
3
  from RealESRGAN import RealESRGAN
4
  import gradio as gr
 
 
5
 
6
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
7
- model2 = RealESRGAN(device, scale=2)
8
- model2.load_weights('weights/RealESRGAN_x2.pth', download=True)
9
- model4 = RealESRGAN(device, scale=4)
10
- model4.load_weights('weights/RealESRGAN_x4.pth', download=True)
11
- model8 = RealESRGAN(device, scale=8)
12
- model8.load_weights('weights/RealESRGAN_x8.pth', download=True)
13
 
 
 
 
 
 
 
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  def inference(image, size):
16
- global model2
17
- global model4
18
- global model8
19
  if image is None:
20
  raise gr.Error("Image not uploaded")
21
-
22
 
23
- if torch.cuda.is_available():
24
- torch.cuda.empty_cache()
25
-
26
- if size == '2x':
27
- try:
28
- result = model2.predict(image.convert('RGB'))
29
- except torch.cuda.OutOfMemoryError as e:
30
- print(e)
31
- model2 = RealESRGAN(device, scale=2)
32
- model2.load_weights('weights/RealESRGAN_x2.pth', download=False)
33
  result = model2.predict(image.convert('RGB'))
34
- elif size == '4x':
35
- try:
36
  result = model4.predict(image.convert('RGB'))
37
- except torch.cuda.OutOfMemoryError as e:
38
- print(e)
39
- model4 = RealESRGAN(device, scale=4)
40
- model4.load_weights('weights/RealESRGAN_x4.pth', download=False)
41
- result = model2.predict(image.convert('RGB'))
42
- else:
43
- try:
44
  width, height = image.size
45
  if width >= 5000 or height >= 5000:
46
  raise gr.Error("The image is too large.")
47
  result = model8.predict(image.convert('RGB'))
48
- except torch.cuda.OutOfMemoryError as e:
49
- print(e)
50
- model8 = RealESRGAN(device, scale=8)
51
- model8.load_weights('weights/RealESRGAN_x8.pth', download=False)
52
- result = model2.predict(image.convert('RGB'))
53
-
54
- print(f"Image size ({device}): {size} ... OK")
55
- return result
56
 
 
 
 
 
 
 
57
 
 
58
  title = "Face Real ESRGAN UpScale: 2x 4x 8x"
59
  description = "This is an unofficial demo for Real-ESRGAN. Scales the resolution of a photo. This model shows better results on faces compared to the original version.<br>Telegram BOT: https://t.me/restoration_photo_bot"
60
  article = "<div style='text-align: center;'>Twitter <a href='https://twitter.com/DoEvent' target='_blank'>Max Skobeev</a> | <a href='https://huggingface.co/sberbank-ai/Real-ESRGAN' target='_blank'>Model card</a><div>"
61
 
62
-
63
- gr.Interface(inference,
64
- [gr.Image(type="pil"),
65
- gr.Radio(["2x", "4x", "8x"],
66
- type="value",
67
- value="2x",
68
- label="Resolution model")],
69
  gr.Image(type="pil", label="Output"),
70
  title=title,
71
  description=description,
72
  article=article,
73
  examples=[["groot.jpeg", "2x"]],
74
  flagging_mode="never",
75
- cache_mode="lazy",
76
- delete_cache=(44000, 44000),
77
- ).queue(api_open=True).launch(show_error=True, show_api=True)
78
-
 
 
 
2
  from PIL import Image
3
  from RealESRGAN import RealESRGAN
4
  import gradio as gr
5
+ import os
6
+ import spaces
7
 
8
+ # Kiểm tra cấu hình GPU
9
+ if torch.cuda.is_available():
10
+ print(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
11
+ device = torch.device("cuda")
12
+ else:
13
+ print("CUDA is not available. Using CPU.")
14
+ device = torch.device("cpu")
15
 
16
+ # Lazy loading cho các mô hình
17
+ class LazyRealESRGAN:
18
+ def __init__(self, device, scale):
19
+ self.device = device
20
+ self.scale = scale
21
+ self.model = None
22
 
23
+ def load_model(self):
24
+ if self.model is None:
25
+ self.model = RealESRGAN(self.device, scale=self.scale)
26
+ self.model.load_weights(f'weights/RealESRGAN_x{self.scale}.pth', download=True)
27
+
28
+ def predict(self, img):
29
+ self.load_model()
30
+ return self.model.predict(img)
31
+
32
+ model2 = LazyRealESRGAN(device, scale=2)
33
+ model4 = LazyRealESRGAN(device, scale=4)
34
+ model8 = LazyRealESRGAN(device, scale=8)
35
+
36
+ # Hàm inference chính
37
+ @spaces.GPU
38
  def inference(image, size):
 
 
 
39
  if image is None:
40
  raise gr.Error("Image not uploaded")
 
41
 
42
+ try:
43
+ if torch.cuda.is_available():
44
+ torch.cuda.empty_cache()
45
+
46
+ if size == '2x':
 
 
 
 
 
47
  result = model2.predict(image.convert('RGB'))
48
+ elif size == '4x':
 
49
  result = model4.predict(image.convert('RGB'))
50
+ else:
 
 
 
 
 
 
51
  width, height = image.size
52
  if width >= 5000 or height >= 5000:
53
  raise gr.Error("The image is too large.")
54
  result = model8.predict(image.convert('RGB'))
 
 
 
 
 
 
 
 
55
 
56
+ print(f"Image size ({device}): {size} ... OK")
57
+ return result
58
+ except torch.cuda.OutOfMemoryError:
59
+ raise gr.Error("GPU out of memory. Try a smaller image or lower upscaling factor.")
60
+ except Exception as e:
61
+ raise gr.Error(f"An error occurred: {str(e)}")
62
 
63
+ # Cấu hình giao diện Gradio
64
  title = "Face Real ESRGAN UpScale: 2x 4x 8x"
65
  description = "This is an unofficial demo for Real-ESRGAN. Scales the resolution of a photo. This model shows better results on faces compared to the original version.<br>Telegram BOT: https://t.me/restoration_photo_bot"
66
  article = "<div style='text-align: center;'>Twitter <a href='https://twitter.com/DoEvent' target='_blank'>Max Skobeev</a> | <a href='https://huggingface.co/sberbank-ai/Real-ESRGAN' target='_blank'>Model card</a><div>"
67
 
68
+ # Khởi tạo và chạy giao diện Gradio
69
+ iface = gr.Interface(
70
+ inference,
71
+ [
72
+ gr.Image(type="pil"),
73
+ gr.Radio(["2x", "4x", "8x"], type="value", value="2x", label="Resolution model")
74
+ ],
75
  gr.Image(type="pil", label="Output"),
76
  title=title,
77
  description=description,
78
  article=article,
79
  examples=[["groot.jpeg", "2x"]],
80
  flagging_mode="never",
81
+ cache_examples=True
82
+ )
83
+
84
+ # Chạy ứng dụng
85
+ if __name__ == "__main__":
86
+ iface.launch(debug=True, show_error=True)