File size: 4,377 Bytes
39531a2
2ecae98
 
 
 
 
 
 
 
39531a2
 
 
2ecae98
 
 
39531a2
 
2ecae98
 
 
 
 
 
39531a2
2ecae98
 
39531a2
 
2ecae98
 
 
 
39531a2
 
2ecae98
 
 
 
39531a2
 
 
 
 
 
 
 
 
2ecae98
39531a2
2ecae98
 
 
39531a2
2ecae98
39531a2
 
 
 
 
 
2ecae98
39531a2
2ecae98
 
39531a2
 
2ecae98
 
 
39531a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ecae98
39531a2
2ecae98
 
39531a2
2ecae98
39531a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ecae98
39531a2
2ecae98
 
39531a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ecae98
39531a2
 
 
 
 
2ecae98
39531a2
 
 
 
 
2ecae98
39531a2
 
 
 
 
 
 
 
 
 
 
2ecae98
39531a2
 
2ecae98
 
39531a2
2ecae98
 
39531a2
2ecae98
39531a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ecae98
39531a2
2ecae98
39531a2
 
 
 
 
 
 
2ecae98
39531a2
2ecae98
39531a2
 
 
 
 
 
48b78cb
af1ac9c
39531a2
 
 
2ecae98
39531a2
 
 
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import spaces
import torch
from PIL import Image
from RealESRGAN import RealESRGAN
import gradio as gr
import numpy as np
import tempfile
import time

# ZeroGPU requires models to be placed on CUDA at module startup.
device = torch.device("cuda")


def load_model(scale):
    model = RealESRGAN(device, scale=scale)
    weights_path = f"weights/RealESRGAN_x{scale}.pth"

    try:
        model.load_weights(weights_path, download=True)
        print(f"Weights for scale {scale} loaded successfully.")
    except Exception as e:
        print(f"Error loading weights for scale {scale}: {e}")
        model.load_weights(weights_path, download=False)

    return model


# Load all models at startup.
model2 = load_model(2)
model4 = load_model(4)
model8 = load_model(8)


@spaces.GPU(duration=120)
def enhance_image(image, scale):
    try:
        print(f"Enhancing image with scale {scale}...")
        start_time = time.time()

        image_np = np.array(image.convert("RGB"))

        print(
            f"Image converted to numpy array: "
            f"shape {image_np.shape}, dtype {image_np.dtype}"
        )

        if scale == "2x":
            result = model2.predict(image_np)
        elif scale == "4x":
            result = model4.predict(image_np)
        else:
            result = model8.predict(image_np)

        enhanced_image = Image.fromarray(np.uint8(result))

        print(
            f"Image enhanced in "
            f"{time.time() - start_time:.2f} seconds"
        )

        return enhanced_image

    except Exception as e:
        print(f"Error enhancing image: {e}")
        raise


def muda_dpi(input_image, dpi):
    dpi_tuple = (dpi, dpi)

    image = Image.fromarray(
        input_image.astype("uint8"),
        "RGB"
    )

    temp_file = tempfile.NamedTemporaryFile(
        delete=False,
        suffix=".png"
    )

    image.save(
        temp_file,
        format="PNG",
        dpi=dpi_tuple
    )

    temp_file.close()

    return Image.open(temp_file.name)


def resize_image(input_image, width, height):
    image = Image.fromarray(
        input_image.astype("uint8"),
        "RGB"
    )

    resized_image = image.resize(
        (int(width), int(height))
    )

    temp_file = tempfile.NamedTemporaryFile(
        delete=False,
        suffix=".png"
    )

    resized_image.save(
        temp_file,
        format="PNG"
    )

    temp_file.close()

    return Image.open(temp_file.name)


def process_image(
    input_image,
    enhance,
    scale,
    adjust_dpi,
    dpi,
    resize,
    width,
    height
):
    original_image = Image.fromarray(
        input_image.astype("uint8"),
        "RGB"
    )

    if enhance:
        original_image = enhance_image(
            original_image,
            scale
        )

    if adjust_dpi:
        original_image = muda_dpi(
            np.array(original_image),
            int(dpi)
        )

    if resize:
        original_image = resize_image(
            np.array(original_image),
            int(width),
            int(height)
        )

    temp_file = tempfile.NamedTemporaryFile(
        delete=False,
        suffix=".png"
    )

    original_image.save(temp_file.name)
    temp_file.close()

    return original_image, temp_file.name


iface = gr.Interface(
    fn=process_image,

    inputs=[
        gr.Image(
            label="Upload"
        ),

        gr.Checkbox(
            label="Enhance Image (ESRGAN)"
        ),

        gr.Radio(
            ["2x", "4x", "8x"],
            type="value",
            value="2x",
            label="Resolution model"
        ),

        gr.Checkbox(
            label="Adjust DPI"
        ),

        gr.Number(
            label="DPI",
            value=300
        ),

        gr.Checkbox(
            label="Resize"
        ),

        gr.Number(
            label="Width",
            value=512
        ),

        gr.Number(
            label="Height",
            value=512
        )
    ],

    outputs=[
        gr.Image(
            label="Final Image"
        ),

        gr.File(
            label="Download Final Image"
        )
    ],

    title="Image Enhancer",

    description=(
        "Upload an image (.jpg, .png), enhance using AI, "
        "adjust DPI, resize and download the final result."
    ),

    examples=[
        ["gatuno.JPG"]
    ],

    cache_examples=False
)


iface.launch()