Spaces:
Running on Zero
Running on Zero
Download app.py from glarr/Prompt-Reverse-Engineer: direct link, hf CLI and curl.
- Browser
- Download file 15.7 kB
-
https://huggingface.co/spaces/glarr/Prompt-Reverse-Engineer/resolve/main/app.py
- Command line
-
hf download hf://spaces/glarr/Prompt-Reverse-Engineer/app.py
-
curl -L -o app.py https://huggingface.co/spaces/glarr/Prompt-Reverse-Engineer/resolve/main/app.py
15.7 kB
| 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. | |
| def gpu_extract(image): | |
| return C.vlm.extract_dsg(image) | |
| def gpu_vqa(image, statements, template): | |
| return C.scorer.vqa_scores(image, statements, template) | |
| def gpu_rewrite(og, proxy, prompt, failed): | |
| return C.vlm.rewrite(og, proxy, prompt, failed) | |
| def gpu_render(prompt, seed, width, height): | |
| return C.renderer(prompt, seed, width, height) | |
| 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]] = {} | |
| 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) | |