ilhamdev commited on
Commit
c7b8af2
·
verified ·
1 Parent(s): dd374de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +8 -36
app.py CHANGED
@@ -8,16 +8,9 @@ import time
8
  import requests
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,
16
- '8x': 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
 
@@ -27,45 +20,35 @@ def get_model(size):
27
  os.makedirs(cache_dir, exist_ok=True)
28
  local_path = os.path.join(cache_dir, model_name)
29
 
30
- # Jika file belum ada, unduh dengan mekanisme retry (pengulangan)
31
  if not os.path.exists(local_path):
32
  retries = 5
33
  for i in range(retries):
34
  try:
35
- # Menggunakan ai-forever/Real-ESRGAN agar sesuai dengan README.md Anda
36
  hf_hub_download(repo_id='ai-forever/Real-ESRGAN', filename=model_name, local_dir=cache_dir)
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)
44
  model = RealESRGAN(device, scale=scale)
45
  model.load_weights(local_path, download=False)
46
-
47
- # Simpan ke cache memori
48
  models[size] = model
49
  return model
50
 
51
  def inference(image, size):
52
  if image is None:
53
  raise gr.Error("Image not uploaded")
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()
61
 
62
- # Ambil model yang diminta pengguna
63
  model = get_model(size)
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')
@@ -73,28 +56,17 @@ def inference(image, size):
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
79
 
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)
 
8
  import requests
9
 
10
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
11
+ models = {'2x': None, '4x': None, '8x': None}
 
 
 
 
 
 
12
 
13
  def get_model(size):
 
14
  if models[size] is not None:
15
  return models[size]
16
 
 
20
  os.makedirs(cache_dir, exist_ok=True)
21
  local_path = os.path.join(cache_dir, model_name)
22
 
 
23
  if not os.path.exists(local_path):
24
  retries = 5
25
  for i in range(retries):
26
  try:
 
27
  hf_hub_download(repo_id='ai-forever/Real-ESRGAN', filename=model_name, local_dir=cache_dir)
28
  break
29
  except (requests.exceptions.ConnectionError, Exception) as e:
30
  if i == retries - 1:
31
+ raise gr.Error(f"Gagal mengunduh model {model_name} setelah {retries} percobaan.")
32
+ time.sleep(2 ** i)
33
 
 
34
  model = RealESRGAN(device, scale=scale)
35
  model.load_weights(local_path, download=False)
 
 
36
  models[size] = model
37
  return model
38
 
39
  def inference(image, size):
40
  if image is None:
41
  raise gr.Error("Image not uploaded")
42
+ if image.size[0] >= 5000 or image.size[1] >= 5000:
 
 
43
  raise gr.Error("The image is too large (max 4999x4999).")
44
 
45
  if torch.cuda.is_available():
46
  torch.cuda.empty_cache()
47
 
 
48
  model = get_model(size)
 
49
  try:
50
  result = model.predict(image.convert('RGB'))
51
  except torch.cuda.OutOfMemoryError:
 
52
  if size in ['4x', '8x']:
53
  print(f"OOM on {size}, falling back to 2x...")
54
  model2 = get_model('2x')
 
56
  gr.Info("VRAM penuh. Hasil diproses menggunakan model 2x sebagai alternatif.")
57
  else:
58
  raise gr.Error("Out of Memory error. Coba dengan gambar yang lebih kecil.")
 
 
59
  return result
60
 
 
61
  title = "Face Real ESRGAN UpScale: 2x 4x 8x"
62
  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"
 
63
  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>"
64
 
 
65
  gr.Interface(
66
  fn=inference,
67
+ inputs=[gr.Image(type="pil", label="Input Image"), gr.Radio(['2x', '4x', '8x'], type="value", value='2x', label='Resolution model')],
 
 
 
68
  outputs=gr.Image(type="pil", label="Output"),
69
+ title=title, description=description, article=article,
70
+ examples=[['groot.jpeg', "2x"]], # Pastikan file groot.jpeg ada di repo Anda!
71
+ allow_flagging='never', cache_examples=False,
 
 
 
72
  ).queue(api_open=True).launch(show_error=True, show_api=True)