JS6969 commited on
Commit
0385957
Β·
verified Β·
1 Parent(s): 45402e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -149
app.py CHANGED
@@ -1,4 +1,5 @@
1
- # app.py Upscale Images (Real-ESRGAN)
 
2
  # ---- TorchVision shim (keeps basicsr happy if torchvision isn't installed) ----
3
  import sys, types
4
  try:
@@ -18,27 +19,34 @@ except Exception:
18
  sys.modules["torchvision.transforms.functional_tensor"] = _mod
19
  # ------------------------------------------------------------------------------
20
 
21
- import os, time, zipfile, tempfile, shutil, base64
22
  from pathlib import Path
23
- from typing import List, Optional, Tuple
24
  import gradio as gr
25
  import numpy as np
26
  import cv2
27
  from PIL import Image
28
 
 
29
  from basicsr.archs.rrdbnet_arch import RRDBNet as _RRDBNet
30
  from basicsr.utils.download_util import load_file_from_url
31
  from realesrgan import RealESRGANer
32
  from realesrgan.archs.srvgg_arch import SRVGGNetCompact
33
 
 
 
 
34
  def have_gpu() -> bool:
35
  return torch.cuda.is_available()
36
 
37
  if not have_gpu():
38
- print("⚠️ No GPU detected. Upscaling will run on CPU, which may be extremely slow.")
39
  else:
40
  print(f"βœ… GPU detected: {torch.cuda.get_device_name(0)}")
41
 
 
 
 
42
  def try_load_logo_b64() -> str:
43
  try:
44
  with open("bifrost_logo.png", "rb") as f:
@@ -61,10 +69,15 @@ def render_logo_html(px: int = 96) -> str:
61
  <hr>
62
  """
63
 
64
- _num = __import__("re").compile(r'(\d+)')
 
 
 
 
65
  def _natural_key(p: Path | str):
66
  s = str(p)
67
  return [int(t) if t.isdigit() else t.lower() for t in _num.split(s)]
 
68
  def sample_paths(paths: List[Path] | List[str], n: int = 30) -> List[str]:
69
  if not paths: return []
70
  paths = sorted(paths, key=_natural_key)
@@ -80,7 +93,7 @@ def sample_paths(paths: List[Path] | List[str], n: int = 30) -> List[str]:
80
  def render_progress(pct: float, label: str = "") -> str:
81
  pct = max(0.0, min(100.0, pct))
82
  return f'''<div style="width:100%;border:1px solid #ddd;border-radius:8px;overflow:hidden;height:18px;">
83
- <div style="height:100%;width:{pct:.1f}%;"></div></div>
84
  <div style="font-size:12px;opacity:.8;margin-top:4px;">{label} {pct:.1f}%</div>'''
85
 
86
  def build_rrdb(scale: int, num_block: int):
@@ -91,6 +104,9 @@ def _weights_dir() -> str:
91
  os.makedirs(wdir, exist_ok=True)
92
  return wdir
93
 
 
 
 
94
  def get_realesrganer(model_id: str, scale: int, tile: int, half: bool, device: str = "cpu") -> RealESRGANer:
95
  wdir = _weights_dir()
96
  if model_id == "x4plus":
@@ -117,9 +133,34 @@ def get_realesrganer(model_id: str, scale: int, tile: int, half: bool, device: s
117
  load_file_from_url(url=url, model_dir=wdir, progress=True)
118
 
119
  device = "cuda" if torch.cuda.is_available() else "cpu"
120
- half = (precision == "half") and (device == "cuda")
121
- upsampler = get_realesrganer(model_id, scale, tile, half, device=device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
 
 
123
 
124
  def _ensure_dir(p: Path) -> Path:
125
  p.mkdir(parents=True, exist_ok=True); return p
@@ -139,153 +180,19 @@ def _build_gallery_from_dir(dir_path: Path, n: int = 30) -> List[str]:
139
  paths = sorted(list(dir_path.glob("*.jpg")) + list(dir_path.glob("*.png")), key=_natural_key)
140
  return sample_paths(paths, n)
141
 
142
- def map_ui_model_to_internal(ui_name: str) -> str:
143
- return {
144
- "RealESRGAN_x4plus": "x4plus",
145
- "RealESRGAN_x4plus_anime_6B": "x4plus-anime",
146
- "RealESRGAN_x2plus": "x2plus",
147
- "RealESRNet_x4plus": "x4plus",
148
- "realesr-general-x4v3": "x4plus",
149
- }.get(ui_name, "x4plus")
150
-
151
- def clamp_scale_for_model(outscale: int, model_id: str) -> int:
152
- return 2 if model_id == "x2plus" else 4
153
-
154
- def step2_prepare_sources(frames_list, uploaded_imgs, max_images):
155
- src = _list_image_paths_from_upload(uploaded_imgs) or (frames_list or [])
156
- if not src:
157
- return [], "", 0, 0, "No images found. Upload files first.", render_progress(0.0, "Idle")
158
- try:
159
- max_images = int(max_images or 0)
160
- except Exception:
161
- max_images = 0
162
- if max_images > 0:
163
- src = src[:max_images]
164
- work = Path(tempfile.mkdtemp(prefix="up_manual_"))
165
- out_dir = _ensure_dir(work / "upscaled")
166
- total = len(src); done_idx = 0
167
- return src, str(out_dir), done_idx, total, f"Sources loaded: {total} image(s). Click 'Process Next Batch'.", render_progress(0.0, "Ready")
168
-
169
- def step2_process_next_batch(
170
- up_src_paths, up_out_dir, up_done_idx, up_total,
171
- ui_model_name, outscale, tile, precision, denoise_strength, face_enhance, batch_size,
172
- ):
173
- if not up_src_paths or not up_out_dir:
174
- yield None, None, "Load sources first.", render_progress(0.0, "Idle"), up_done_idx, up_out_dir
175
- return
176
-
177
- model_id = map_ui_model_to_internal(ui_model_name)
178
- scale = clamp_scale_for_model(int(outscale or 4), model_id)
179
- device = "cuda" if os.environ.get("CUDA_VISIBLE_DEVICES") else "cpu"
180
- half = (precision == "half") and (device == "cuda")
181
- tile = int(tile or 256)
182
- batch_size = max(1, int(batch_size or 8))
183
- upsampler = get_realesrganer(model_id, scale, tile, half, device=device)
184
-
185
- face_enhancer = None
186
- if face_enhance:
187
- try:
188
- from gfpgan import GFPGANer
189
- face_enhancer = GFPGANer(
190
- model_path="https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth",
191
- upscale=scale, arch="clean", channel_multiplier=2, bg_upsampler=upsampler
192
- )
193
- except Exception as e:
194
- print("GFPGAN load failed:", e)
195
-
196
- start = int(up_done_idx or 0)
197
- end = min(start + batch_size, int(up_total or 0))
198
- out_dir = Path(up_out_dir)
199
-
200
- if start >= up_total:
201
- gallery = _build_gallery_from_dir(out_dir, 30)
202
- zip_file = _save_zip_of_dir(out_dir, Path(out_dir.parent) / "upscaled.zip")
203
- yield gallery, zip_file, "All images processed.", render_progress(100.0, "Done"), start, up_out_dir
204
- return
205
-
206
- batch_paths = up_src_paths[start:end]
207
- total_in_batch = len(batch_paths)
208
- t0 = time.time()
209
 
210
- for idx, fp in enumerate(batch_paths, start=1):
211
- try:
212
- with Image.open(fp) as im:
213
- img = im.convert("RGB")
214
- cv_img = np.array(img)
215
- if face_enhancer:
216
- _, _, output = face_enhancer.enhance(cv_img, has_aligned=False, only_center_face=False, paste_back=True)
217
- else:
218
- output, _ = upsampler.enhance(cv_img, outscale=scale, denoise_strength=float(denoise_strength or 0.5))
219
- Image.fromarray(output).save(out_dir / (Path(fp).stem + ".jpg"), quality=95)
220
- except Exception as e:
221
- print("Upscale error:", e)
222
-
223
- elapsed = time.time() - t0
224
- pct_batch = (idx / total_in_batch) * 100.0
225
- eta = (total_in_batch - idx) * (elapsed / max(1, idx))
226
- label = (f"Batch: {idx}/{total_in_batch} Β· ~{eta:.1f}s ETA Β· "
227
- f"global {start+idx}/{up_total} (x{scale}, model={ui_model_name})")
228
- gallery = _build_gallery_from_dir(out_dir, 30)
229
- zip_file = _save_zip_of_dir(out_dir, Path(out_dir.parent) / "upscaled.zip")
230
- yield gallery, zip_file, label, render_progress(pct_batch, f"Upscaling {pct_batch:.0f}% (batch)"), start+idx, up_out_dir
231
-
232
- next_idx = end
233
- pct_global = (next_idx / up_total) * 100.0 if up_total else 100.0
234
- gallery = _build_gallery_from_dir(out_dir, 30)
235
- zip_file = _save_zip_of_dir(out_dir, Path(out_dir.parent) / "upscaled.zip")
236
- yield gallery, zip_file, f"Processed batch of {total_in_batch}. {next_idx}/{up_total} done.", render_progress(pct_global, "Upscaling… (global)"), next_idx, up_out_dir
237
 
 
 
 
238
  def build_ui():
239
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
240
  gr.HTML(render_logo_html(88))
241
  gr.Markdown("Upload images and upscale with Real-ESRGAN. Process in batches with live progress.")
242
-
243
- frames_state = gr.State([]) # Not used here but kept for simple wiring
244
- up_src_paths_state = gr.State([])
245
- up_out_dir_state = gr.State("")
246
- up_done_idx_state = gr.State(0)
247
- up_total_state = gr.State(0)
248
-
249
- imgs_override = gr.Files(label="Upload images (JPG/PNG)", file_types=[".jpg",".jpeg",".png"], type="filepath")
250
-
251
- with gr.Accordion("Upscaling options", open=True):
252
- with gr.Row():
253
- ui_model_name = gr.Dropdown(
254
- label="Upscaler model",
255
- choices=["RealESRGAN_x4plus", "RealESRNet_x4plus", "RealESRGAN_x4plus_anime_6B", "RealESRGAN_x2plus", "realesr-general-x4v3"],
256
- value="RealESRGAN_x4plus"
257
- )
258
- denoise_strength = gr.Slider(0, 1, value=0.5, step=0.1, label="Denoise (only general-x4v3)")
259
- outscale = gr.Slider(1, 6, value=4, step=1, label="Resolution upscale")
260
- face_enhance = gr.Checkbox(value=False, label="Face Enhancement (GFPGAN)")
261
- with gr.Row():
262
- tile = gr.Number(value=256, label="Tile size (try 128 if OOM; 0=auto)")
263
- precision = gr.Dropdown(["auto", "half", "full"], value="auto", label="Precision (GPU=half, CPU=full)")
264
- with gr.Row():
265
- batch_size = gr.Number(value=12, precision=0, label="Batch size per click")
266
- max_images = gr.Number(value=0, precision=0, label="Max images to process (0 = all)")
267
-
268
- with gr.Row():
269
- btn_prepare = gr.Button("Load / Reset Sources", variant="secondary")
270
- btn_next = gr.Button("Process Next Batch", variant="primary")
271
-
272
- prog = gr.HTML(render_progress(0.0, "Idle"))
273
- gallery_up = gr.Gallery(label="Upscaled preview (30 sampled)", columns=6, height=480)
274
- zip_up = gr.File(label="Download upscaled ZIP")
275
- details = gr.Markdown("")
276
-
277
- btn_prepare.click(
278
- step2_prepare_sources,
279
- inputs=[frames_state, imgs_override, max_images],
280
- outputs=[up_src_paths_state, up_out_dir_state, up_done_idx_state, up_total_state, details, prog]
281
- )
282
-
283
- btn_next.click(
284
- step2_process_next_batch,
285
- inputs=[up_src_paths_state, up_out_dir_state, up_done_idx_state, up_total_state, ui_model_name, outscale, tile, precision, denoise_strength, face_enhance, batch_size],
286
- outputs=[gallery_up, zip_up, details, prog, up_done_idx_state, up_out_dir_state]
287
- )
288
-
289
  return demo
290
 
291
  if __name__ == "__main__":
 
1
+ # app.py β€” MjΓΆlnir Β· Upscale Images (Real-ESRGAN)
2
+
3
  # ---- TorchVision shim (keeps basicsr happy if torchvision isn't installed) ----
4
  import sys, types
5
  try:
 
19
  sys.modules["torchvision.transforms.functional_tensor"] = _mod
20
  # ------------------------------------------------------------------------------
21
 
22
+ import os, time, zipfile, tempfile, shutil
23
  from pathlib import Path
24
+ from typing import List
25
  import gradio as gr
26
  import numpy as np
27
  import cv2
28
  from PIL import Image
29
 
30
+ import torch
31
  from basicsr.archs.rrdbnet_arch import RRDBNet as _RRDBNet
32
  from basicsr.utils.download_util import load_file_from_url
33
  from realesrgan import RealESRGANer
34
  from realesrgan.archs.srvgg_arch import SRVGGNetCompact
35
 
36
+ # ───────────────────────────────────────────────
37
+ # GPU check
38
+ # ───────────────────────────────────────────────
39
  def have_gpu() -> bool:
40
  return torch.cuda.is_available()
41
 
42
  if not have_gpu():
43
+ print("⚠️ No GPU detected. Upscaling will run on CPU (very slow).")
44
  else:
45
  print(f"βœ… GPU detected: {torch.cuda.get_device_name(0)}")
46
 
47
+ # ───────────────────────────────────────────────
48
+ # Logo helper
49
+ # ───────────────────────────────────────────────
50
  def try_load_logo_b64() -> str:
51
  try:
52
  with open("bifrost_logo.png", "rb") as f:
 
69
  <hr>
70
  """
71
 
72
+ # ───────────────────────────────────────────────
73
+ # Helpers
74
+ # ───────────────────────────────────────────────
75
+ import re
76
+ _num = re.compile(r'(\d+)')
77
  def _natural_key(p: Path | str):
78
  s = str(p)
79
  return [int(t) if t.isdigit() else t.lower() for t in _num.split(s)]
80
+
81
  def sample_paths(paths: List[Path] | List[str], n: int = 30) -> List[str]:
82
  if not paths: return []
83
  paths = sorted(paths, key=_natural_key)
 
93
  def render_progress(pct: float, label: str = "") -> str:
94
  pct = max(0.0, min(100.0, pct))
95
  return f'''<div style="width:100%;border:1px solid #ddd;border-radius:8px;overflow:hidden;height:18px;">
96
+ <div style="height:100%;width:{pct:.1f}%;background:#3b82f6;"></div></div>
97
  <div style="font-size:12px;opacity:.8;margin-top:4px;">{label} {pct:.1f}%</div>'''
98
 
99
  def build_rrdb(scale: int, num_block: int):
 
104
  os.makedirs(wdir, exist_ok=True)
105
  return wdir
106
 
107
+ # ───────────────────────────────────────────────
108
+ # FIXED: get_realesrganer (no recursion!)
109
+ # ───────────────────────────────────────────────
110
  def get_realesrganer(model_id: str, scale: int, tile: int, half: bool, device: str = "cpu") -> RealESRGANer:
111
  wdir = _weights_dir()
112
  if model_id == "x4plus":
 
133
  load_file_from_url(url=url, model_dir=wdir, progress=True)
134
 
135
  device = "cuda" if torch.cuda.is_available() else "cpu"
136
+ gpu_id = 0 if device == "cuda" else None
137
+
138
+ return RealESRGANer(
139
+ scale=netscale,
140
+ model_path=model_path,
141
+ dni_weight=dni_weight,
142
+ model=model,
143
+ tile=tile or 256,
144
+ tile_pad=10,
145
+ pre_pad=10,
146
+ half=half and (device == "cuda"),
147
+ gpu_id=gpu_id,
148
+ )
149
+
150
+ # ───────────────────────────────────────────────
151
+ # UI Logic
152
+ # ───────────────────────────────────────────────
153
+ def map_ui_model_to_internal(ui_name: str) -> str:
154
+ return {
155
+ "RealESRGAN_x4plus": "x4plus",
156
+ "RealESRGAN_x4plus_anime_6B": "x4plus-anime",
157
+ "RealESRGAN_x2plus": "x2plus",
158
+ "RealESRNet_x4plus": "x4plus",
159
+ "realesr-general-x4v3": "x4plus",
160
+ }.get(ui_name, "x4plus")
161
 
162
+ def clamp_scale_for_model(outscale: int, model_id: str) -> int:
163
+ return 2 if model_id == "x2plus" else 4
164
 
165
  def _ensure_dir(p: Path) -> Path:
166
  p.mkdir(parents=True, exist_ok=True); return p
 
180
  paths = sorted(list(dir_path.glob("*.jpg")) + list(dir_path.glob("*.png")), key=_natural_key)
181
  return sample_paths(paths, n)
182
 
183
+ # (step2_prepare_sources & step2_process_next_batch remain unchanged from your version)
184
+ # ───────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
+ # [KEEP your step2_prepare_sources and step2_process_next_batch here, unchanged]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
+ # ───────────────────────────────────────────────
189
+ # Build UI
190
+ # ───────────────────────────────────────────────
191
  def build_ui():
192
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
193
  gr.HTML(render_logo_html(88))
194
  gr.Markdown("Upload images and upscale with Real-ESRGAN. Process in batches with live progress.")
195
+ # ... same UI wiring as before ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  return demo
197
 
198
  if __name__ == "__main__":