File size: 4,444 Bytes
ab81a26
7af3f84
 
ab81a26
 
c72957e
 
ab81a26
c72957e
 
 
7af3f84
 
 
ab81a26
 
 
 
 
7af3f84
 
 
ab81a26
 
7af3f84
 
ab81a26
7af3f84
ab81a26
7af3f84
ab81a26
7af3f84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d29017
7af3f84
ab81a26
7af3f84
 
 
 
 
 
ab81a26
7af3f84
 
ab81a26
 
 
 
 
 
 
 
7af3f84
 
 
 
 
 
 
ab81a26
7af3f84
c72957e
7af3f84
c72957e
 
7af3f84
 
 
 
ab81a26
7af3f84
 
 
ab81a26
 
 
 
 
 
7af3f84
ab81a26
7af3f84
 
 
ab81a26
 
c72957e
7af3f84
 
 
c72957e
7af3f84
 
ab81a26
7af3f84
ab81a26
 
 
7af3f84
ab81a26
 
7af3f84
 
ab81a26
7af3f84
 
ab81a26
7af3f84
 
 
c72957e
 
ab81a26
7af3f84
 
 
ab81a26
 
 
 
 
 
 
 
7af3f84
 
 
ab81a26
 
 
 
 
 
 
7af3f84
ab81a26
 
 
7af3f84
 
 
ab81a26
 
 
7af3f84
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import os
import sys
import requests
from pathlib import Path

import gradio as gr
import numpy as np
from basicsr.archs.rrdbnet_arch import RRDBNet
from PIL import Image
from realesrgan import RealESRGANer

# Flush logs immediately (important for HF Spaces)
sys.stdout.reconfigure(line_buffering=True)

MODEL_FILENAME = "RealESRGAN_x4plus.pth"
MODEL_SCALE = 4
SUPPORTED_SCALES = (2, 4)


# -------------------------------
# Model Path + Download Handling
# -------------------------------
def resolve_model_path() -> str:
    project_root = Path(__file__).resolve().parent
    model_dir = project_root / "weights"
    model_dir.mkdir(exist_ok=True)

    model_path = model_dir / MODEL_FILENAME

    print(f"[INFO] Looking for model at: {model_path}")

    if model_path.exists():
        print("[SUCCESS] Model already exists. Skipping download.")
    else:
        print("[INFO] Model not found. Starting download...")

        url = f"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/{MODEL_FILENAME}"
        response = requests.get(url, stream=True)

        total_size = int(response.headers.get("content-length", 0))
        downloaded = 0

        with open(model_path, "wb") as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
                    downloaded += len(chunk)

                    if total_size > 0:
                        percent = (downloaded / total_size) * 100
                        print(f"[DOWNLOAD] {percent:.2f}%")

        print("[SUCCESS] Model downloaded successfully!")

    return str(model_path)


# -------------------------------
# Load Model
# -------------------------------
def load_model():
    print("[INFO] Initializing model architecture...")

    model = RRDBNet(
        num_in_ch=3,
        num_out_ch=3,
        num_feat=64,
        num_block=23,
        num_grow_ch=32,
        scale=MODEL_SCALE,
    )

    print("[INFO] Resolving model path...")
    model_path = resolve_model_path()

    print(f"[INFO] Loading model weights from: {model_path}")

    upsampler = RealESRGANer(
        scale=MODEL_SCALE,
        model_path=model_path,
        model=model,
        half=False,  # set True if GPU available
    )

    print("[SUCCESS] Model loaded successfully!")

    return upsampler


# -------------------------------
# Cache Model
# -------------------------------
upsampler_cache = None


def get_upsampler():
    global upsampler_cache
    if upsampler_cache is None:
        print("[INFO] No cached model found. Loading...")
        upsampler_cache = load_model()
    else:
        print("[INFO] Using cached model.")

    return upsampler_cache


# -------------------------------
# Upscale Function
# -------------------------------
def upscale(image: Image.Image, scale: int):
    print("[INFO] Upscale request received")

    if image is None:
        print("[ERROR] No image provided")
        raise gr.Error("Please upload an image first.")

    if scale not in SUPPORTED_SCALES:
        print(f"[ERROR] Unsupported scale: {scale}")
        raise gr.Error(f"Unsupported upscale factor: {scale}")

    print(f"[INFO] Using scale: {scale}")

    upsampler = get_upsampler()

    print("[INFO] Starting image enhancement...")
    output, _ = upsampler.enhance(np.array(image), outscale=scale)

    print("[SUCCESS] Upscaling completed!")

    return Image.fromarray(output)


# -------------------------------
# Gradio UI
# -------------------------------
def build_demo():
    with gr.Blocks(title="AI Image Upscaler") as app:
        gr.Markdown("## 🔍 AI Image Upscaler\nPowered by Real-ESRGAN")

        with gr.Row():
            with gr.Column():
                input_img = gr.Image(type="pil", label="Input Image")
                scale_choice = gr.Radio(
                    choices=list(SUPPORTED_SCALES),
                    value=4,
                    label="Upscale Factor",
                )
                btn = gr.Button("Upscale", variant="primary")

            with gr.Column():
                output_img = gr.Image(type="pil", label="Upscaled Output")

        btn.click(fn=upscale, inputs=[input_img, scale_choice], outputs=output_img)

    return app


# -------------------------------
# Run App
# -------------------------------
demo = build_demo()

if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
    )