File size: 13,410 Bytes
e297a71
 
780320d
 
 
 
 
80fbabd
 
 
 
ba815e8
e297a71
 
 
 
87c1890
 
780320d
80fbabd
e297a71
 
 
 
d73c075
e297a71
 
 
 
d73c075
 
 
 
e297a71
d73c075
 
 
 
e297a71
 
80fbabd
e297a71
 
80fbabd
 
 
 
 
312d6de
e297a71
312d6de
 
 
e297a71
d73c075
 
 
 
312d6de
 
e297a71
80fbabd
e297a71
312d6de
80fbabd
312d6de
e297a71
312d6de
e297a71
d73c075
 
80fbabd
 
312d6de
 
80fbabd
312d6de
 
80fbabd
312d6de
 
 
80fbabd
312d6de
 
 
 
80fbabd
312d6de
 
80fbabd
 
 
312d6de
 
 
 
 
 
 
 
 
 
 
 
e297a71
 
d73c075
e297a71
80fbabd
 
 
 
c5e0035
80fbabd
 
 
 
 
 
 
bff0b56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80fbabd
 
 
e297a71
80fbabd
 
e297a71
80fbabd
 
 
 
 
 
 
 
 
 
 
 
780320d
312d6de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e297a71
 
80fbabd
e297a71
 
87c1890
780320d
 
24ee135
780320d
 
 
 
e297a71
312d6de
 
780320d
849f41d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ea1d5c
87c1890
 
e297a71
 
3fd8a80
e297a71
 
 
 
 
 
 
 
 
 
80fbabd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc4acf0
 
 
e297a71
80fbabd
e297a71
dc4acf0
80fbabd
e297a71
 
 
d73c075
87c1890
80fbabd
e297a71
 
 
 
 
 
 
3fd8a80
 
f1cb021
3fd8a80
 
 
 
 
 
e297a71
80fbabd
e297a71
d73c075
80fbabd
 
 
 
 
 
e297a71
80fbabd
 
e297a71
 
03165d8
80fbabd
e297a71
312d6de
7129381
312d6de
 
 
 
 
 
 
 
 
 
 
d73c075
e297a71
80fbabd
312d6de
87e5339
d73c075
 
e297a71
80fbabd
312d6de
87e5339
80fbabd
 
 
 
312d6de
87e5339
80fbabd
 
 
 
312d6de
87e5339
d73c075
 
e297a71
80fbabd
e297a71
 
87c1890
312d6de
 
87c1890
 
 
780320d
e297a71
 
 
738ecfb
e08ff81
bff0b56
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import gradio as gr
import subprocess
import os
import shutil
from pathlib import Path
import spaces

# import the updated recursive_multiscale_sr that expects a list of centers
from inference_coz_single import recursive_multiscale_sr

from PIL import Image, ImageDraw

# ------------------------------------------------------------------
# CONFIGURE THESE PATHS TO MATCH YOUR PROJECT STRUCTURE
# ------------------------------------------------------------------

INPUT_DIR   = "samples"
OUTPUT_DIR  = "inference_results/coz_vlmprompt"


# ------------------------------------------------------------------
# HELPER: Resize & center-crop to 512, preserving aspect ratio
# ------------------------------------------------------------------

def resize_and_center_crop(img: Image.Image, size: int) -> Image.Image:
    """
    Resize the input PIL image so that its shorter side == `size`,
    then center-crop to exactly (size x size).
    """
    w, h = img.size
    scale = size / min(w, h)
    new_w, new_h = int(w * scale), int(h * scale)
    img = img.resize((new_w, new_h), Image.LANCZOS)

    left = (new_w - size) // 2
    top  = (new_h - size) // 2
    return img.crop((left, top, left + size, top + size))


# ------------------------------------------------------------------
# HELPER: Draw four true “nested” rectangles, matching the SR logic
# ------------------------------------------------------------------

def make_preview_with_boxes(
    image_path: str,
    scale_option: str,
    cx_norm: float,
    cy_norm: float,
) -> tuple[Image.Image, list[tuple[float, float]]]:
    """
    Returns:
        - The preview image with drawn boxes.
        - A list of (cx_norm, cy_norm) for each box (normalized to 512×512).
    """
    try:
        orig = Image.open(image_path).convert("RGB")
    except Exception as e:
        fallback = Image.new("RGB", (512, 512), (200, 200, 200))
        ImageDraw.Draw(fallback).text((20, 20), f"Error:\n{e}", fill="red")
        return fallback, []

    base = resize_and_center_crop(orig, 512)

    scale_int = int(scale_option.replace("x", ""))
    if scale_int <= 1:
        sizes = [512.0, 512.0, 512.0, 512.0]
    else:
        sizes = [512.0 / (scale_int ** (i + 1)) for i in range(4)]

    draw = ImageDraw.Draw(base)
    colors = ["red", "lime", "cyan", "yellow"]
    width = 3

    abs_cx = cx_norm * 512.0
    abs_cy = cy_norm * 512.0

    prev_x0, prev_y0, prev_size = 0.0, 0.0, 512.0
    centers: list[tuple[float, float]] = []

    for i, crop_size in enumerate(sizes):
        x0 = abs_cx - (crop_size / 2.0)
        y0 = abs_cy - (crop_size / 2.0)

        min_x0 = prev_x0
        max_x0 = prev_x0 + prev_size - crop_size
        min_y0 = prev_y0
        max_y0 = prev_y0 + prev_size - crop_size

        x0 = max(min_x0, min(x0, max_x0))
        y0 = max(min_y0, min(y0, max_y0))
        x1 = x0 + crop_size
        y1 = y0 + crop_size

        draw.rectangle([(int(round(x0)), int(round(y0))),
                        (int(round(x1)), int(round(y1)))],
                       outline=colors[i % len(colors)], width=width)

        # --- compute normalized center of this box ---
        cx_box = ((x0 - prev_x0) + crop_size / 2.0) / float(prev_size)
        cy_box = ((y0 - prev_y0) + crop_size / 2.0) / float(prev_size)
        centers.append((cx_box, cy_box))

        prev_x0, prev_y0, prev_size = x0, y0, crop_size

    return base, centers




# ------------------------------------------------------------------
# HELPER FUNCTION FOR INFERENCE (build a list of identical centers)
# ------------------------------------------------------------------

@spaces.GPU()
def run_with_upload(
    uploaded_image_path: str,
    upscale_option: str,
    cx_norm: float,
    cy_norm: float,
):
    """
    Perform chain-of-zoom super-resolution on a given image, using recursive multi-scale upscaling centered on a specific point.

    This function enhances a given image by progressively zooming into a specific point, using a recursive deep super-resolution model.
    
    Args:
        uploaded_image_path (str): Path to the input image file on disk.
        upscale_option (str): The desired upscale factor as a string. Valid options are "1x", "2x", and "4x".
            - "1x" means no upscaling.
            - "2x" means 2× enlargement per zoom step.
            - "4x" means 4× enlargement per zoom step.
        cx_norm (float): Normalized X-coordinate (0 to 1) of the zoom center.
        cy_norm (float): Normalized Y-coordinate (0 to 1) of the zoom center.

    Returns:
        list[PIL.Image.Image]: A list of progressively zoomed-in and super-resolved images at each recursion step (typically 4),
        centered around the user-specified point.
        
    Note:
        The center point is repeated for each recursion level to maintain consistency during zooming.
        This function uses a modified version of the `recursive_multiscale_sr` pipeline for inference.
    """
    if uploaded_image_path is None:
        return []

    upscale_value = int(upscale_option.replace("x", ""))
    rec_num = 4  # match the SR pipeline’s default recursion depth

    centers = [(cx_norm, cy_norm)] * rec_num

    # Call the modified SR function
    sr_list, _ = recursive_multiscale_sr(
        uploaded_image_path,
        upscale=upscale_value,
        rec_num=rec_num,
        centers=centers,
    )

    # Return the list of PIL images (Gradio Gallery expects a list)
    return sr_list

@spaces.GPU()
def magnify(
    uploaded_image_path: str,
    upscale_option: str,
    centres: list
):
    """
    Perform chain-of-zoom super-resolution on a given image, using recursive multi-scale upscaling centered on a specific point.

    This function enhances a given image by progressively zooming into a specific point, using a recursive deep super-resolution model.
    
    Args:
        uploaded_image_path (str): Path to the input image file on disk.
        upscale_option (str): The desired upscale factor as a string. Valid options are "1x", "2x", and "4x".
            - "1x" means no upscaling.
            - "2x" means 2× enlargement per zoom step.
            - "4x" means 4× enlargement per zoom step.
        centres (list): Normalized list of X-coordinate, Y-coordinate (0 to 1) of the zoom center.

    Returns:
        list[PIL.Image.Image]: A list of progressively zoomed-in and super-resolved images at each recursion step (typically 4),
        centered around the user-specified point.
        
    Note:
        The center point is repeated for each recursion level to maintain consistency during zooming.
        This function uses a modified version of the `recursive_multiscale_sr` pipeline for inference.
    """
    if uploaded_image_path is None:
        return []

    upscale_value = int(upscale_option.replace("x", ""))
    rec_num = len(centres)

    # Call the modified SR function
    sr_list, _ = recursive_multiscale_sr(
        uploaded_image_path,
        upscale=upscale_value,
        rec_num=rec_num,
        centers=centres,
    )

    # Return the list of PIL images (Gradio Gallery expects a list)
    return sr_list



# ------------------------------------------------------------------
# BUILD THE GRADIO INTERFACE (two sliders + correct preview)
# ------------------------------------------------------------------

css = """
#col-container {
    margin: 0 auto;
    max-width: 1024px;
}
"""

with gr.Blocks(css=css) as demo:

    session_centres = gr.State()

    with gr.Column(elem_id="col-container"):

        gr.HTML(
            """
            <div style="text-align: left;">
                <p style="font-size:16px; display: inline; margin: 0;">
                    <strong>Chain-of-Zoom</strong> – Extreme Super-Resolution via Scale Autoregression and Preference Alignment
                </p>
                <a href="https://github.com/bryanswkim/Chain-of-Zoom" style="display: inline-block; vertical-align: middle; margin-left: 0.5em;">
                    [Github]
                </a>
            </div>
            <div style="text-align: left;">
                <strong>HF Space by:</strong>
                <a href="https://twitter.com/alexandernasa/" style="display: inline-block; vertical-align: middle; margin-left: 0.5em;">
                    <img src="https://img.shields.io/twitter/url/https/twitter.com/cloudposse.svg?style=social&label=Follow Me" alt="GitHub Repo">
                </a>
            </div>
            """
        )
        with gr.Row():
            with gr.Column():
                # 1) Image upload component
                upload_image = gr.Image(
                    label="Input image",
                    type="filepath"
                )

                # 2) Radio for choosing 1× / 2× / 4× upscaling
                upscale_radio = gr.Radio(
                    choices=["1x", "2x", "4x"],
                    value="2x",
                    show_label=False
                )

                # 3) Two sliders for normalized center (0..1)
                center_x = gr.Slider(
                    label="Center X (normalized)",
                    minimum=0.0,
                    maximum=1.0,
                    step=0.01,
                    value=0.5
                )
                center_y = gr.Slider(
                    label="Center Y (normalized)",
                    minimum=0.0,
                    maximum=1.0,
                    step=0.01,
                    value=0.5
                )

                # 4) Button to launch inference
                run_button = gr.Button("🔎 Chain-of-Zoom it", variant="primary")
                
                gr.Markdown("*Click anywhere on the preview image to select coordinates to zoom*")

                # 5) Preview (512×512 + four truly nested boxes)
                preview_with_box = gr.Image(
                    label="Preview",
                    type="pil",
                    interactive=False
                )


            with gr.Column():
                # 6) Gallery to display multiple output images
                output_gallery = gr.Gallery(
                    label="Inference Results",
                    show_label=True,
                    elem_id="gallery",
                    columns=[2], rows=[2]
                )

                examples = gr.Examples(
                    # List of example-rows. Each row is [input_image, scale, cx, cy]
                    examples=[["samples/0479.png", "4x", 0.5, 0.5], ["samples/0064.png", "4x", 0.5, 0.5], ["samples/0245.png", "4x", 0.5, 0.5], ["samples/0393.png", "4x", 0.5, 0.5]],
                    inputs=[upload_image, upscale_radio, center_x, center_y],
                    outputs=[output_gallery],
                    fn=run_with_upload,
                    cache_examples=True  
                )

        # ------------------------------------------------------------------
        # CALLBACK #1: update the preview whenever inputs change
        # ------------------------------------------------------------------

        def update_preview(
            img_path: str,
            scale_opt: str,
            cx: float,
            cy: float
        ) -> Image.Image | None:
            """
            If no image uploaded, show blank; otherwise, draw four nested boxes
            exactly as the SR pipeline would crop at each recursion.
            """
            if img_path is None:
                return None, []
            return make_preview_with_boxes(img_path, scale_opt, cx, cy)

        def get_select_coords(input_img, evt: gr.SelectData):
            print("coordinates selected")
            i = evt.index[1] 
            j = evt.index[0]

            w, h = input_img.size

            return gr.update(value=j/w), gr.update(value=i/h)


        preview_with_box.select(get_select_coords, [preview_with_box], [center_x, center_y])
            

        upload_image.change(
            fn=update_preview,
            inputs=[upload_image, upscale_radio, center_x, center_y],
            outputs=[preview_with_box, session_centres],
            show_api=False
        )
        upscale_radio.change(
            fn=update_preview,
            inputs=[upload_image, upscale_radio, center_x, center_y],
            outputs=[preview_with_box, session_centres],
            show_api=False
        )
        center_x.change(
            fn=update_preview,
            inputs=[upload_image, upscale_radio, center_x, center_y],
            outputs=[preview_with_box, session_centres],
            show_api=False
        )
        center_y.change(
            fn=update_preview,
            inputs=[upload_image, upscale_radio, center_x, center_y],
            outputs=[preview_with_box, session_centres],
            show_api=False
        )

        # ------------------------------------------------------------------
        # CALLBACK #2: on button‐click, run the SR pipeline
        # ------------------------------------------------------------------

        run_button.click(
            fn=magnify,
            inputs=[upload_image, upscale_radio, session_centres],
            outputs=[output_gallery]
        )


# ------------------------------------------------------------------
# START THE GRADIO SERVER
# ------------------------------------------------------------------
demo.queue()

demo.launch(share=True, mcp_server=True)