ilhamdev commited on
Commit
fbacbaf
·
verified ·
1 Parent(s): e31f7d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -22
app.py CHANGED
@@ -9,7 +9,7 @@ import requests
9
 
10
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
11
 
12
- # Gunakan dictionary untuk menyimpan model yang sudah dimuat (Lazy Loading)
13
  models = {
14
  '2x': None,
15
  '4x': None,
@@ -17,14 +17,11 @@ models = {
17
  }
18
 
19
  def get_model(size):
20
- """Unduh dan muat model hanya saat diminta, untuk menghindari error koneksi saat startup."""
21
  if models[size] is not None:
22
  return models[size]
23
 
24
- if size == '2x': scale = 2
25
- elif size == '4x': scale = 4
26
- else: scale = 8
27
-
28
  model_name = f'RealESRGAN_x{scale}.pth'
29
  cache_dir = 'weights'
30
  os.makedirs(cache_dir, exist_ok=True)
@@ -40,7 +37,7 @@ def get_model(size):
40
  break
41
  except (requests.exceptions.ConnectionError, Exception) as e:
42
  if i == retries - 1:
43
- raise e # Jika gagal 5 kali, lempar error
44
  time.sleep(2 ** i) # Tunggu sebelum mencoba lagi (Exponential backoff)
45
 
46
  # Inisialisasi dan muat bobot tanpa download ulang (download=False)
@@ -57,7 +54,7 @@ def inference(image, size):
57
 
58
  width, height = image.size
59
  if width >= 5000 or height >= 5000:
60
- raise gr.Error("The image is too large.")
61
 
62
  if torch.cuda.is_available():
63
  torch.cuda.empty_cache()
@@ -67,15 +64,15 @@ def inference(image, size):
67
 
68
  try:
69
  result = model.predict(image.convert('RGB'))
70
- except torch.cuda.OutOfMemoryError as e:
71
- print(e)
72
- # Jika 4x atau 8x kehabisan VRAM (OOM), otomatis fallback ke 2x
73
  if size in ['4x', '8x']:
74
  print(f"OOM on {size}, falling back to 2x...")
75
  model2 = get_model('2x')
76
  result = model2.predict(image.convert('RGB'))
 
77
  else:
78
- raise gr.Error("Out of Memory error.")
79
 
80
  print(f"Image size ({device}): {size} ... OK")
81
  return result
@@ -83,21 +80,21 @@ def inference(image, size):
83
 
84
  title = "Face Real ESRGAN UpScale: 2x 4x 8x"
85
  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"
86
- # Perbaikan HTML tag </div> di akhir
87
  article = "<div style='text-align: center;'>Twitter <a href='https://twitter.com/DoEvent' target='_blank'>Max Skobeev</a> | <a href='https://huggingface.co/ai-forever/Real-ESRGAN' target='_blank'>Model card</a></div>"
88
 
89
 
90
- gr.Interface(inference,
91
- [gr.Image(type="pil", label="Input Image"),
92
- gr.Radio(['2x', '4x', '8x'],
93
- type="value",
94
- value='2x',
95
- label='Resolution model')],
96
- gr.Image(type="pil", label="Output"),
97
  title=title,
98
  description=description,
99
  article=article,
100
- examples=[['groot.jpeg', "2x"]], # Pastikan file groot.jpeg ada di repo Anda
101
  allow_flagging='never',
102
  cache_examples=False,
103
- ).queue(api_open=True).launch(show_error=True, show_api=True)
 
9
 
10
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
11
 
12
+ # Dictionary untuk menyimpan model yang sudah dimuat (Lazy Loading)
13
  models = {
14
  '2x': None,
15
  '4x': None,
 
17
  }
18
 
19
  def get_model(size):
20
+ """Unduh dan muat model hanya saat diminta untuk menghindari error koneksi saat startup."""
21
  if models[size] is not None:
22
  return models[size]
23
 
24
+ scale = 2 if size == '2x' else 4 if size == '4x' else 8
 
 
 
25
  model_name = f'RealESRGAN_x{scale}.pth'
26
  cache_dir = 'weights'
27
  os.makedirs(cache_dir, exist_ok=True)
 
37
  break
38
  except (requests.exceptions.ConnectionError, Exception) as e:
39
  if i == retries - 1:
40
+ raise gr.Error(f"Gagal mengunduh model {model_name} setelah {retries} percobaan. Coba lagi nanti.")
41
  time.sleep(2 ** i) # Tunggu sebelum mencoba lagi (Exponential backoff)
42
 
43
  # Inisialisasi dan muat bobot tanpa download ulang (download=False)
 
54
 
55
  width, height = image.size
56
  if width >= 5000 or height >= 5000:
57
+ raise gr.Error("The image is too large (max 4999x4999).")
58
 
59
  if torch.cuda.is_available():
60
  torch.cuda.empty_cache()
 
64
 
65
  try:
66
  result = model.predict(image.convert('RGB'))
67
+ except torch.cuda.OutOfMemoryError:
68
+ # Jika 4x atau 8x kehabisan VRAM, otomatis fallback ke 2x
 
69
  if size in ['4x', '8x']:
70
  print(f"OOM on {size}, falling back to 2x...")
71
  model2 = get_model('2x')
72
  result = model2.predict(image.convert('RGB'))
73
+ gr.Info("VRAM penuh. Hasil diproses menggunakan model 2x sebagai alternatif.")
74
  else:
75
+ raise gr.Error("Out of Memory error. Coba dengan gambar yang lebih kecil.")
76
 
77
  print(f"Image size ({device}): {size} ... OK")
78
  return result
 
80
 
81
  title = "Face Real ESRGAN UpScale: 2x 4x 8x"
82
  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"
83
+ # Perbaikan: Menutup tag div dengan benar (</div>)
84
  article = "<div style='text-align: center;'>Twitter <a href='https://twitter.com/DoEvent' target='_blank'>Max Skobeev</a> | <a href='https://huggingface.co/ai-forever/Real-ESRGAN' target='_blank'>Model card</a></div>"
85
 
86
 
87
+ gr.Interface(
88
+ fn=inference,
89
+ inputs=[
90
+ gr.Image(type="pil", label="Input Image"),
91
+ gr.Radio(['2x', '4x', '8x'], type="value", value='2x', label='Resolution model')
92
+ ],
93
+ outputs=gr.Image(type="pil", label="Output"),
94
  title=title,
95
  description=description,
96
  article=article,
97
+ examples=[['groot.jpeg', "2x"]], # Pastikan file groot.jpeg ada di repository Anda
98
  allow_flagging='never',
99
  cache_examples=False,
100
+ ).queue(api_open=True).launch(show_error=True, show_api=True)