Spaces:
Running on Zero

image-upscaler / app.py
sorabing's picture
Upload app.py
90aa867 verified
Raw History Blame Contribute Delete
2.66 kB
import os
import tempfile
import urllib.request
import gradio as gr
import numpy as np
import spaces
import torch
from PIL import Image
from spandrel import ModelLoader
# Real-ESRGAN x4 (BSD-3 license) - downloaded once when the Space starts
MODEL_URL = "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth"
MODEL_PATH = "RealESRGAN_x4plus.pth"
MAX_SIDE = 1280 # cap input size so a single image doesn't eat the daily GPU quota
if not os.path.exists(MODEL_PATH):
urllib.request.urlretrieve(MODEL_URL, MODEL_PATH)
model = ModelLoader().load_from_file(MODEL_PATH).eval()
model.to("cuda") # on ZeroGPU this is allowed at startup
@spaces.GPU(duration=60)
def upscale(img: Image.Image, scale: str):
if img is None:
raise gr.Error("กรุณาอัปโหลดภาพก่อน")
img = img.convert("RGB")
w, h = img.size
if max(w, h) > MAX_SIDE:
r = MAX_SIDE / max(w, h)
img = img.resize((int(w * r), int(h * r)), Image.LANCZOS)
w, h = img.size
x = torch.from_numpy(np.array(img)).permute(2, 0, 1).float().div(255).unsqueeze(0).to("cuda")
with torch.inference_mode():
y = model(x)
y = y.squeeze(0).clamp(0, 1).permute(1, 2, 0).mul(255).round().byte().cpu().numpy()
out = Image.fromarray(y)
if scale == "x2":
out = out.resize((w * 2, h * 2), Image.LANCZOS)
# "before" = original enlarged the ordinary way, same size as the result, for a fair side-by-side
before = img.resize(out.size, Image.BICUBIC)
path = os.path.join(tempfile.mkdtemp(), f"upscaled_{scale}.png")
out.save(path)
return (before, out), path
with gr.Blocks(title="ปรับภาพชัดด้วย AI") as demo:
gr.Markdown("# ✨ ปรับภาพชัดด้วย AI\nอัปโหลดภาพ เลือกขนาด แล้วกดปรับภาพ จากนั้นลากเส้นกลางภาพเพื่อเทียบก่อน/หลัง")
with gr.Row():
with gr.Column(scale=1):
inp = gr.Image(type="pil", label="ภาพต้นฉบับ")
scale = gr.Radio(["x2", "x4"], value="x2", label="ขยายภาพ")
btn = gr.Button("ปรับภาพให้ชัด", variant="primary")
file = gr.File(label="ดาวน์โหลดภาพ")
with gr.Column(scale=2):
out = gr.ImageSlider(type="pil", label="ซ้าย = ขยายธรรมดา | ขวา = AI", height=600)
btn.click(upscale, inputs=[inp, scale], outputs=[out, file])
demo.launch()