File size: 15,706 Bytes
8f0eb46
610364e
a39d07d
610364e
a39d07d
 
9823bb5
a39d07d
610364e
2144a09
610364e
a39d07d
2144a09
610364e
9823bb5
610364e
a39d07d
2144a09
610364e
 
2144a09
9823bb5
 
 
 
 
 
 
 
2144a09
610364e
 
9823bb5
610364e
 
2144a09
610364e
9823bb5
610364e
 
 
 
9823bb5
610364e
 
 
 
9823bb5
610364e
 
 
 
9823bb5
610364e
 
 
 
 
9823bb5
610364e
8f0eb46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a39d07d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f0eb46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a39d07d
 
 
 
 
610364e
8f0eb46
 
a39d07d
 
 
 
2144a09
610364e
 
 
 
8f0eb46
610364e
 
 
a39d07d
 
 
 
610364e
a39d07d
 
610364e
a39d07d
 
 
 
 
 
 
 
 
 
 
2144a09
 
8f0eb46
2144a09
8f0eb46
 
 
 
 
 
 
 
 
 
 
a39d07d
 
 
8f0eb46
 
a39d07d
8f0eb46
 
 
a39d07d
8f0eb46
 
a39d07d
 
8f0eb46
 
 
a39d07d
 
 
 
8f0eb46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2144a09
a39d07d
610364e
 
 
a39d07d
 
2144a09
 
a39d07d
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
import html
import json
import shutil
import tempfile
import time
import uuid
from pathlib import Path
from urllib.parse import quote

import gradio as gr
import spaces
from PIL import Image, features

from inversion import EngineConfig, iter_inversion
from inversion.backends import BackendSettings, choose_gpu_size, load_components
from inversion.engine import Backends
from inversion.explorer import render_explorer

SETTINGS = BackendSettings()
C = load_components(SETTINGS)

# ZeroGPU copies ALL resident weights onto the GPU at the start of every @spaces.GPU call, so the slice
# must hold all of them plus activations. With the default FLUX.2-klein-4B the weights are ~33.9 GB and fit a
# "large" slice (50.87 GB). Qwen3-VL-8B + FLUX.1-schnell + DINOv2 in bf16 is ~51.6 GB, which fails with a CUDA
# OOM before any code runs, so choose_gpu_size() requests "xlarge" for it (or set PROXY_FP8=1 to fit "large").
RESIDENT_BYTES = C.resident_bytes()
GPU_SIZE = choose_gpu_size(SETTINGS.zerogpu_size, RESIDENT_BYTES)
print(f"[startup] resident model weights: {RESIDENT_BYTES / 1e9:.1f} GB -> ZeroGPU size '{GPU_SIZE}'", flush=True)


# Each model call gets its own (short) ZeroGPU allocation instead of one long one
# for the whole loop. Outside Spaces/ZeroGPU, @spaces.GPU is a no-op.
@spaces.GPU(duration=180, size=GPU_SIZE)
def gpu_extract(image):
    return C.vlm.extract_dsg(image)


@spaces.GPU(duration=90, size=GPU_SIZE)
def gpu_vqa(image, statements, template):
    return C.scorer.vqa_scores(image, statements, template)


@spaces.GPU(duration=120, size=GPU_SIZE)
def gpu_rewrite(og, proxy, prompt, failed):
    return C.vlm.rewrite(og, proxy, prompt, failed)


@spaces.GPU(duration=60, size=GPU_SIZE)
def gpu_render(prompt, seed, width, height):
    return C.renderer(prompt, seed, width, height)


@spaces.GPU(duration=30, size=GPU_SIZE)
def gpu_embed(image):
    return C.dino.embed(image)


BACKENDS = Backends(extract_dsg=gpu_extract, vqa_scores=gpu_vqa, rewrite=gpu_rewrite,
                    render=gpu_render, embed=gpu_embed, meta=C.info)


# --------------------------------------------------------------------------- look

def _short(model_id: str) -> str:
    return model_id.rsplit("/", 1)[-1]


MODEL_CHIP = " · ".join([
    _short(SETTINGS.vlm_model_id if SETTINGS.vlm_backend == "local" else SETTINGS.vlm_api_model),
    _short(SETTINGS.proxy_model_id if SETTINGS.proxy_backend == "flux" else SETTINGS.fal_endpoint),
    _short(SETTINGS.dino_model_id),
])

BRAND = gr.themes.Color(
    c50="#EEF3FD", c100="#DCE6FA", c200="#B9CDF5", c300="#8AABEC", c400="#5A85DD",
    c500="#3A68CF", c600="#2B59C3", c700="#234AA3", c800="#1E4297", c900="#1A3570", c950="#0F2048",
    name="brand",
)

THEME = gr.themes.Base(
    primary_hue=BRAND,
    neutral_hue="slate",
    radius_size="md",
    font=[gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"],
    font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace"],
).set(
    body_background_fill="#F5F6F8",
    block_background_fill="#FFFFFF",
    block_border_color="#E3E6EB",
    block_border_width="1px",
    block_radius="12px",
    block_shadow="none",
    block_label_text_color="#5B6270",
    block_title_text_color="#14171F",
    block_title_text_weight="500",
    border_color_primary="#E3E6EB",
    body_text_color_subdued="#5B6270",
    input_background_fill="#FFFFFF",
    input_border_color="#D3D7DE",
    slider_color="#2B59C3",
    color_accent="#2B59C3",
    color_accent_soft="#EAF0FC",
    link_text_color="#2B59C3",
    button_primary_background_fill="#2B59C3",
    button_primary_background_fill_hover="#1E4297",
    button_primary_text_color="#FFFFFF",
    button_secondary_background_fill="#FFFFFF",
    button_secondary_border_color="#D3D7DE",
    button_large_radius="10px",
    button_large_text_size="15px",
    checkbox_background_color_selected="#2B59C3",
    table_even_background_fill="#FFFFFF",
    table_odd_background_fill="#FAFBFC",
    section_header_text_weight="600",
)

APP_DIR = Path(__file__).parent / "app"
CSS_PATHS = [APP_DIR / "theme.css", APP_DIR / "explorer.css"]  # loaded via launch(css_paths=...)
EXPLORER_JS = (APP_DIR / "explorer.js").read_text(encoding="utf-8")  # run explorer behaviour (gr.HTML js_on_load)

# Each run's original, proxy renders and report live in their own folder and are served by URL
# (a Gradio static path), so the explorer HTML stays small while it streams.
RUNS_ROOT = Path(tempfile.mkdtemp(prefix="pre_runs_"))
gr.set_static_paths([str(RUNS_ROOT)])
RUN_TTL_S = 6 * 3600
IMAGE_EXT = "webp" if features.check("webp") else "png"


def _file_url(path: Path) -> str:
    return "gradio_api/file=" + quote(path.resolve().as_posix(), safe="/:")


class _RunFiles:
    """One run's folder: every image is written once and then referenced by URL."""

    def __init__(self):
        self.dir = RUNS_ROOT / uuid.uuid4().hex
        self.dir.mkdir(parents=True)
        self._urls: dict[int, tuple[Image.Image, str]] = {}

    @property
    def run_id(self) -> str:
        return self.dir.name

    def url(self, image: Image.Image, name: str | None = None) -> str:
        hit = self._urls.get(id(image))
        if hit is not None and hit[0] is image:
            return hit[1]
        path = self.dir / f"{name or f'render_{len(self._urls)}'}.{IMAGE_EXT}"
        image.convert("RGB").save(path, quality=90) if IMAGE_EXT == "webp" else image.convert("RGB").save(path)
        url = _file_url(path)
        self._urls[id(image)] = (image, url)  # keep the image alive so its id() is never reused
        return url

    def write_report(self, run) -> Path:
        path = self.dir / "report.json"
        path.write_text(json.dumps(run.to_dict(), indent=2), encoding="utf-8")
        return path


def _prune_runs() -> None:
    cutoff = time.time() - RUN_TTL_S
    for folder in RUNS_ROOT.iterdir():
        try:
            if folder.is_dir() and folder.stat().st_mtime < cutoff:
                shutil.rmtree(folder, ignore_errors=True)
        except OSError:
            pass


LOGO = ('<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" '
        'stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 0 1 15.5-6.2L21 8"/><path d="M21 3v5h-5"/>'
        '<path d="M21 12a9 9 0 0 1-15.5 6.2L3 16"/><path d="M3 21v-5h5"/></svg>')

HEADER_HTML = f"""
<div class="pre-header">
  <div class="pre-brand">
    <div class="pre-logo">{LOGO}</div>
    <div><div class="pre-title">Prompt Reverse Engineer</div>
    <div class="pre-sub">Image → verified text-to-image prompt</div></div>
  </div>
  <nav class="pre-nav">
    <a href="#method">How it works</a>
    <a href="#cite">Cite</a>
    <span class="pre-chip"><span class="pre-dot"></span>{html.escape(MODEL_CHIP)}</span>
  </nav>
</div>
"""

INTRO_HTML = """
<div class="pre-card pre-intro" id="method">
  <h1>Turn an image back into a prompt you can verify</h1>
  <p>Instead of one free-form caption, the image is broken into checkable facts. A fast model renders the
  prompt, every fact is checked against the render, and only the failed parts are rewritten.</p>
  <ol class="pre-how">
    <li><span class="pre-n">01</span><b>Extract a scene graph</b>
      <span>Shapes, colors, medium and relations, each placed on a 3 × 3 grid.</span></li>
    <li><span class="pre-n">02</span><b>Ground on the original</b>
      <span>Facts the original itself fails are removed, so no unverified style words reach the prompt.</span></li>
    <li><span class="pre-n">03</span><b>Render and verify</b>
      <span>A proxy model renders the prompt; VQAScore checks each fact and DINO checks the layout.</span></li>
    <li><span class="pre-n">04</span><b>Rewrite only what failed</b>
      <span>Targeted edits repeat until both scores clear their gates or iterations run out.</span></li>
  </ol>
</div>
<div class="pre-placeholder"><b>Results appear here</b>
  <span>The verified prompt, proxy renders and per-fact scores stream in as each step finishes.</span></div>
"""

# --------------------------------------------------------------------------- run

def _outputs(run, files: _RunFiles, og_url: str, og_size: tuple[int, int], report: Path | None = None):
    explorer = render_explorer(run, og_url=og_url, og_size=og_size, image_url=files.url,
                               report_url=_file_url(report) if report else None, run_id=files.run_id)
    return (
        gr.update(visible=False),  # intro
        gr.update(visible=True),  # results
        explorer,
        run.best_prompt,  # hidden: keeps the API returning the prompt string
        str(report) if report else None,  # hidden: and the JSON report
        gr.update(value="Running…", interactive=False),
    )


def invert(image, max_iters, vqa_gate, dino_gate, fail_threshold, w_vqa, base_seed, ground):
    if image is None:
        raise gr.Error("Upload an image to start.")
    cfg = EngineConfig(max_iters=int(max_iters), vqa_gate=vqa_gate, dino_gate=dino_gate,
                       fail_threshold=fail_threshold, w_vqa=w_vqa, w_dino=round(1 - w_vqa, 4),
                       base_seed=int(base_seed), ground=bool(ground))
    _prune_runs()
    files = _RunFiles()
    og = image.convert("RGB")
    og_url = files.url(og, "original")
    run = None
    for run in iter_inversion(og, BACKENDS, cfg):
        yield _outputs(run, files, og_url, og.size)
    assert run is not None
    yield _outputs(run, files, og_url, og.size, files.write_report(run))


def _on_image(img):
    has = img is not None
    return gr.update(value="Invert image", interactive=has), gr.update(visible=not has)


def _after_run(img):
    # Runs after every run, including failed ones, so the button never stays disabled.
    return gr.update(value="Run again" if img is not None else "Invert image", interactive=img is not None)


# --------------------------------------------------------------------------- layout

with gr.Blocks(title="Prompt Reverse Engineer") as demo:
    gr.HTML(HEADER_HTML)

    with gr.Row(equal_height=False):
        with gr.Column(scale=1, min_width=320):
            with gr.Group(elem_classes="pre-group"):
                gr.HTML('<p class="pre-step-title">1 · Original image</p>', elem_classes="pre-group-title")
                image = gr.Image(type="pil", label="Original image", show_label=False,
                                 sources=["upload", "clipboard"], height=320, elem_classes="pre-image")
            with gr.Group(elem_classes="pre-group"):
                gr.HTML('<p class="pre-step-title">2 · Stopping rule</p>', elem_classes="pre-group-title")
                max_iters = gr.Slider(1, 8, value=3, step=1, label="Max iterations")
                vqa_gate = gr.Slider(0.5, 1.0, value=0.82, step=0.01, label="Min. predicate agreement (S_VQA)")
                dino_gate = gr.Slider(0.0, 1.0, value=0.65, step=0.01, label="Min. layout similarity (S_DINO)",
                                      info="Set to 0 to stop on S_VQA alone.")
            with gr.Accordion("Advanced settings", open=False):
                fail_threshold = gr.Slider(0.3, 0.95, value=0.70, step=0.01, label="Failure threshold",
                                           info="Facts scoring below this are sent to the rewriter.")
                w_vqa = gr.Slider(0.0, 1.0, value=0.7, step=0.05, label="Weight on S_VQA",
                                  info="Picks the best iteration; the rest of the weight goes to S_DINO.")
                base_seed = gr.Number(value=42, precision=0, label="Base seed", info="Iteration t uses seed base + t − 1.")
                ground = gr.Checkbox(value=True, label="Ground predicates on the original",
                                     info="Removes facts the scorer rejects on the original image.")
            run_button = gr.Button("Invert image", variant="primary", size="lg", interactive=False)
            hint = gr.HTML('<p class="pre-hint">Upload an image to start.</p>')

        with gr.Column(scale=3, min_width=560):
            intro = gr.HTML(INTRO_HTML)
            with gr.Column(visible=False) as results:
                explorer = gr.HTML(js_on_load=EXPLORER_JS)
            best_prompt = gr.Textbox(label="Verified prompt", visible=False)
            report = gr.File(label="Run report (JSON)", visible=False)

    with gr.Accordion("Cite", open=False, elem_id="cite"):
        gr.Markdown("""Author: Larrain, G

```bibtex
@misc{qwen3technicalreport,
  title={Qwen3 Technical Report}, author={Qwen Team}, year={2025},
  eprint={2505.09388}, archivePrefix={arXiv}, primaryClass={cs.CL}, url={https://arxiv.org/abs/2505.09388}
}

@article{Qwen2.5-VL,
  title={Qwen2.5-VL Technical Report},
  author={Bai, Shuai and Chen, Keqin and Liu, Xuejing and Wang, Jialin and Ge, Wenbin and Song, Sibo and Dang, Kai and Wang, Peng and Wang, Shijie and Tang, Jun and Zhong, Humen and Zhu, Yuanzhi and Yang, Mingkun and Li, Zhaohai and Wan, Jianqiang and Wang, Pengfei and Ding, Wei and Fu, Zheren and Xu, Yiheng and Ye, Jiabo and Zhang, Xi and Xie, Tianbao and Cheng, Zesen and Zhang, Hang and Yang, Zhibo and Xu, Haiyang and Lin, Junyang},
  journal={arXiv preprint arXiv:2502.13923}, year={2025}
}

@article{Qwen2VL,
  title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution},
  author={Wang, Peng and Bai, Shuai and Tan, Sinan and Wang, Shijie and Fan, Zhihao and Bai, Jinze and Chen, Keqin and Liu, Xuejing and Wang, Jialin and Ge, Wenbin and Fan, Yang and Dang, Kai and Du, Mengfei and Ren, Xuancheng and Men, Rui and Liu, Dayiheng and Zhou, Chang and Zhou, Jingren and Lin, Junyang},
  journal={arXiv preprint arXiv:2409.12191}, year={2024}
}

@article{Qwen-VL,
  title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond},
  author={Bai, Jinze and Bai, Shuai and Yang, Shusheng and Wang, Shijie and Tan, Sinan and Wang, Peng and Lin, Junyang and Zhou, Chang and Zhou, Jingren},
  journal={arXiv preprint arXiv:2308.12966}, year={2023}
}

@inproceedings{cho2024dsg,
  title={Davidsonian Scene Graph: Improving Reliability in Fine-grained Evaluation for Text-to-Image Generation},
  author={Cho, Jaemin and Hu, Yushi and Garg, Roopal and Anderson, Peter and Krishna, Ranjay and Baldridge, Jason and Bansal, Mohit and Pont-Tuset, Jordi and Wang, Su},
  booktitle={International Conference on Learning Representations (ICLR)}, year={2024}
}

@inproceedings{lin2024vqascore,
  title={Evaluating Text-to-Visual Generation with Image-to-Text Generation},
  author={Lin, Zhiqiu and Pathak, Deepak and Li, Baiqi and Li, Jiayao and Xia, Xide and Neubig, Graham and Zhang, Pengchuan and Ramanan, Deva},
  booktitle={European Conference on Computer Vision (ECCV)}, year={2024}
}

@article{oquab2024dinov2,
  title={DINOv2: Learning Robust Visual Features without Supervision},
  author={Oquab, Maxime and Darcet, Timoth{\\'e}e and Moutakanni, Th{\\'e}o and others},
  journal={Transactions on Machine Learning Research (TMLR)}, year={2024}
}

@article{simeoni2025dinov3,
  title={DINOv3}, author={Sim{\\'e}oni, Oriane and others},
  journal={arXiv preprint arXiv:2508.10104}, year={2025}
}

@misc{flux2024,
  title={FLUX}, author={{Black Forest Labs}}, year={2024},
  howpublished={https://github.com/black-forest-labs/flux}
}
```""")

    image.change(_on_image, [image], [run_button, hint])
    run_button.click(
        invert,
        [image, max_iters, vqa_gate, dino_gate, fail_threshold, w_vqa, base_seed, ground],
        [intro, results, explorer, best_prompt, report, run_button],
    ).then(_after_run, [image], [run_button])

if __name__ == "__main__":
    demo.launch(theme=THEME, css_paths=CSS_PATHS)