Spaces:
Running on Zero
Running on Zero
File size: 2,660 Bytes
ac6787a 90aa867 ac6787a 90aa867 ac6787a 90aa867 ac6787a 90aa867 ac6787a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | 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()
|