troyy0206 commited on
Commit
e87bc3d
·
verified ·
1 Parent(s): af87dc6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ from PIL import Image
4
+ import cv2
5
+ import os
6
+
7
+ # Minimal Real-ESRGAN setup (CPU). This uses cv2 dnn_superres as a fallback
8
+ # if Real-ESRGAN import fails on CPU-only. For best quality, try realesrgan.
9
+ try:
10
+ from realesrgan import RealESRGAN
11
+ HAVE_REALESRGAN = True
12
+ except Exception:
13
+ HAVE_REALESRGAN = False
14
+
15
+ # Helper: upscale using Real-ESRGAN if available, else Lanczos as CPU fallback
16
+ def upscale_core(img: Image.Image, scale: int, model_key: str) -> Image.Image:
17
+ if HAVE_REALESRGAN:
18
+ # RealESRGAN works on CPU too (slow), but OK for a free Space
19
+ # Model choices
20
+ model_map = {
21
+ "pro": "RealESRGAN_x4plus",
22
+ "standard": "RealESRNet_x4plus",
23
+ "creative": "RealESRGAN_x4plus_anime_6B",
24
+ }
25
+ model_name = model_map.get(model_key, "RealESRGAN_x4plus")
26
+ upsampler = RealESRGAN(device="cpu", scale=4)
27
+ # Load model
28
+ upsampler.load_weights(model_name)
29
+ # If requested scale is 2/3/4, do single pass; if >4, chain extra resize
30
+ primary = min(max(scale,2), 4)
31
+ out = upsampler.predict(np.array(img), batch_size=1)
32
+ out_img = Image.fromarray(out)
33
+ if scale > 4:
34
+ factor = scale / 4.0
35
+ w = int(out_img.width * factor)
36
+ h = int(out_img.height * factor)
37
+ out_img = out_img.resize((w,h), Image.LANCZOS)
38
+ return out_img
39
+ else:
40
+ # Fallback: pure CPU Lanczos upscale (not AI, but ensures API always returns)
41
+ w = int(img.width * scale)
42
+ h = int(img.height * scale)
43
+ return img.resize((w, h), Image.LANCZOS)
44
+
45
+ def upscale(image: np.ndarray, scale: int, model: str) -> Image.Image:
46
+ pil = Image.fromarray(image)
47
+ scale = max(2, min(10, int(scale)))
48
+ model = (model or "pro").lower()
49
+ out = upscale_core(pil, scale, model)
50
+ return out
51
+
52
+ with gr.Blocks() as demo:
53
+ gr.Markdown("# Open-Source Image Upscaler API (Real-ESRGAN, CPU)")
54
+ with gr.Row():
55
+ inp = gr.Image(type="numpy", label="Upload")
56
+ scl = gr.Slider(2, 10, value=4, step=1, label="Scale")
57
+ mdl = gr.Dropdown(["pro","standard","creative"], value="pro", label="Model")
58
+ out = gr.Image(type="pil", label="Upscaled")
59
+
60
+ btn = gr.Button("Upscale")
61
+ btn.click(upscale, [inp, scl, mdl], [out])
62
+
63
+ # NOTE: Your PHP will call this endpoint:
64
+ # POST {SPACE_URL}/api/predict
65
+ # JSON: {"data": ["data:image/png;base64,...", 4, "pro"]}
66
+
67
+ demo.launch()