Spaces:
Running on Zero
Running on Zero
Design improvement
Browse files
README.md
CHANGED
|
@@ -5,122 +5,404 @@ colorFrom: gray
|
|
| 5 |
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.31.0
|
| 8 |
-
python_version: "3.12
|
| 9 |
-
suggested_hardware: zero-a10g
|
| 10 |
app_file: app.py
|
| 11 |
pinned: true
|
| 12 |
-
short_description: Image to prompt reverse enginner, turn any image back.
|
| 13 |
license: apache-2.0
|
|
|
|
| 14 |
models:
|
| 15 |
- Qwen/Qwen3-VL-8B-Instruct
|
| 16 |
- black-forest-labs/FLUX.1-schnell
|
| 17 |
-
- facebook/
|
| 18 |
library_name: transformers
|
| 19 |
tags:
|
| 20 |
- image-to-prompt
|
| 21 |
-
- computer
|
| 22 |
- captioning
|
| 23 |
- qwen
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
---
|
| 25 |
|
| 26 |
-
# Prompt Reverse Engineer
|
| 27 |
|
| 28 |
-
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
│ DSG rule: children of an absent parent entity score 0
|
| 45 |
-
│ 4B DINOv2 patch-aligned cosine between S_k and the proxy (layout)
|
| 46 |
-
│
|
| 47 |
-
├─ S_VQA ≥ 0.90 AND S_DINO ≥ 0.80 → lock P_k*
|
| 48 |
-
├─ t = max_iters → return best prompt by 0.7·S_VQA + 0.3·S_DINO
|
| 49 |
-
└─ otherwise: targeted diff rewrite → only spans tied to failed predicates are edited
|
| 50 |
-
(the VLM sees original + proxy; edits must quote the prompt verbatim and are applied
|
| 51 |
-
deterministically; unmatched edits are skipped and recorded, never guessed; edits that
|
| 52 |
-
would inject an era/style buzzword absent from the grounded prompt, e.g. "vintage",
|
| 53 |
-
"cinematic", "1970s", "Bauhaus", are skipped as unverified)
|
| 54 |
-
```
|
| 55 |
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
| `app.py` | Gradio Space UI. Each model call gets its own `@spaces.GPU` allocation |
|
| 68 |
-
| `cli.py` | Batch `invert` over a stimulus folder, and DINO `medoid` selection over seed renders |
|
| 69 |
-
| `tests/` | Model-free tests of the schema, compiler, dependency rule, grounding, diff, and loop |
|
| 70 |
|
| 71 |
-
##
|
| 72 |
|
| 73 |
-
|
| 74 |
|
| 75 |
-
|
|
|
|
|
|
|
| 76 |
|
| 77 |
```bash
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
pip install -r requirements.txt
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
```
|
| 84 |
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
```bash
|
| 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 |
-
2. **Lock P\*_1…P\*_9.** Run `python cli.py invert --input stimuli/ --out runs/`. `runs/summary.csv` lists each image's stop reason, best scores, and best prompt.
|
| 115 |
-
3. **Render target conditions** in the target models, outside this repo. Save them as `renders/<condition>/<seed>.png`, then pick one medoid per condition: `python cli.py medoid --input renders/ --out medoids.json --copy-to medoids/`.
|
| 116 |
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
|
|
|
|
| 5 |
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.31.0
|
| 8 |
+
python_version: "3.12"
|
|
|
|
| 9 |
app_file: app.py
|
| 10 |
pinned: true
|
|
|
|
| 11 |
license: apache-2.0
|
| 12 |
+
suggested_hardware: zero-a10g
|
| 13 |
models:
|
| 14 |
- Qwen/Qwen3-VL-8B-Instruct
|
| 15 |
- black-forest-labs/FLUX.1-schnell
|
| 16 |
+
- facebook/dinov3-vitb16-pretrain-lvd1689m
|
| 17 |
library_name: transformers
|
| 18 |
tags:
|
| 19 |
- image-to-prompt
|
| 20 |
+
- computer-vision
|
| 21 |
- captioning
|
| 22 |
- qwen
|
| 23 |
+
- flux
|
| 24 |
+
- dino
|
| 25 |
+
- vqa
|
| 26 |
+
- zero-gpu
|
| 27 |
+
short_description: Turn any image into a verified text-to-image prompt. Closed-loop DSG + VQA + DINO pipeline.
|
| 28 |
---
|
| 29 |
|
| 30 |
+
# Prompt Reverse Engineer
|
| 31 |
|
| 32 |
+
Turn an image into a verified text-to-image prompt. A closed-loop pipeline extracts a constrained scene graph, grounds every fact on the original, renders with a proxy model, scores each predicate with VQAScore and layout with DINOv3, and rewrites only what fails — until both gates clear or iterations run out.
|
| 33 |
|
| 34 |
+
[](LICENSE)
|
| 35 |
+
[](https://github.com/glarrainv/Prompt-Reverse-Engineer/stargazers)
|
| 36 |
+
[](https://huggingface.co/spaces/glarr/Prompt-Reverse-Engineer)
|
| 37 |
+
[](https://www.python.org/)
|
| 38 |
+
[](https://gradio.app/)
|
| 39 |
+
[](https://pytorch.org/)
|
| 40 |
+
[](https://huggingface.co/docs/transformers)
|
| 41 |
+
[](LICENSE)
|
| 42 |
+
|
| 43 |
+
---
|
| 44 |
+
|
| 45 |
+
## Overview
|
| 46 |
+
|
| 47 |
+
**Prompt Reverse Engineer** inverts text-to-image generation: instead of prompting a model and hoping the output matches your vision, you provide an image and get back a prompt whose every claim is verified against a proxy render. The pipeline runs four stages in a loop:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
1. **Extract** a Davidsonian Scene Graph (DSG) — entities, attributes, relations, and medium/optics on a 3×3 grid
|
| 50 |
+
2. **Ground** every predicate on the original image; drop or re-localize facts the scorer rejects
|
| 51 |
+
3. **Render** the linearized prompt with a fast proxy model (FLUX.1-schnell by default)
|
| 52 |
+
4. **Verify** with VQAScore (predicate agreement) and DINOv3 (layout similarity); **rewrite** only failed facts
|
| 53 |
|
| 54 |
+
**What makes this different:**
|
| 55 |
+
- Zero-hallucination grounding: facts false on the original never reach the prompt
|
| 56 |
+
- Targeted diff rewrites: only failed predicates are edited, preserving the rest
|
| 57 |
+
- Dual-gate stopping: both predicate agreement (S_VQA) and layout similarity (S_DINO) must clear configurable thresholds
|
| 58 |
+
- Two deployment pathways: local GPUs (Qwen3-VL + FLUX + DINOv3) or API-only (OpenRouter + FAL + gpt-4o)
|
| 59 |
+
- Gradio UI for Hugging Face Spaces (ZeroGPU-ready) and Python CLI for batch runs
|
| 60 |
+
- Full JSON report with every iteration, scores, predicates, and proxy renders
|
| 61 |
+
|
| 62 |
+
---
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
+
## Quickstart
|
| 65 |
|
| 66 |
+
### Option A: Hugging Face Space (zero setup)
|
| 67 |
|
| 68 |
+
[Open the Space](https://huggingface.co/spaces/glarr/Prompt-Reverse-Engineer) → upload an image → adjust gates if needed → click **Invert image**. The verified prompt, proxy renders, per-fact scores, and a downloadable JSON report stream in live.
|
| 69 |
+
|
| 70 |
+
### Option B: Local (Windows / macOS / Linux)
|
| 71 |
|
| 72 |
```bash
|
| 73 |
+
# 1. Clone
|
| 74 |
+
git clone https://github.com/glarrainv/Prompt-Reverse-Engineer.git
|
| 75 |
+
cd Prompt-Reverse-Engineer
|
| 76 |
+
|
| 77 |
+
# 2. Create venv and install (PyTorch + CUDA 12.1 assumed; adjust for your hardware)
|
| 78 |
+
python -m venv .venv
|
| 79 |
+
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
| 80 |
+
pip install --upgrade pip
|
| 81 |
pip install -r requirements.txt
|
| 82 |
+
|
| 83 |
+
# 3. Accept gated model licenses and set HF token
|
| 84 |
+
huggingface-cli login # or export HF_TOKEN=hf_...
|
| 85 |
+
|
| 86 |
+
# 4. Run the Gradio UI
|
| 87 |
+
python app.py
|
| 88 |
+
# → opens at http://localhost:7860
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
> **GPU requirements (local pathway):** 24 GB VRAM recommended for Qwen3-VL-8B + FLUX.1-schnell + DINOv3-B. With 16 GB, enable CPU offload: `PROXY_CPU_OFFLOAD=1`.
|
| 92 |
+
|
| 93 |
+
### Option C: Python CLI (batch processing)
|
| 94 |
+
|
| 95 |
+
```bash
|
| 96 |
+
# Invert a folder of images
|
| 97 |
+
python cli.py invert --input stimuli/ --out runs/ --max-iters 5 --vqa-gate 0.90 --dino-gate 0.80
|
| 98 |
+
|
| 99 |
+
# Select DINO medoid render per condition folder
|
| 100 |
+
python cli.py medoid --input renders/ --out medoids.json --key patch --copy-to medoids/
|
| 101 |
```
|
| 102 |
|
| 103 |
+
| Flag | Effect | Default |
|
| 104 |
+
|------|--------|---------|
|
| 105 |
+
| `--input PATH` | Image file or directory | required |
|
| 106 |
+
| `--out DIR` | Output root for runs/ | `runs/` |
|
| 107 |
+
| `--max-iters N` | Max rewrite iterations | `5` |
|
| 108 |
+
| `--vqa-gate F` | S_VQA convergence gate | `0.90` |
|
| 109 |
+
| `--dino-gate F` | S_DINO convergence gate (0 = disable) | `0.80` |
|
| 110 |
+
| `--fail-threshold F` | Predicate failure threshold for rewrite | `0.75` |
|
| 111 |
+
| `--w-vqa F` | Weight on S_VQA for best-iteration selection | `0.7` |
|
| 112 |
+
| `--seed N` | Base seed (proxy seed = base + t) | `42` |
|
| 113 |
+
| `--no-ground` | Skip grounding on original (not recommended) | off |
|
| 114 |
+
|
| 115 |
+
### Option D: Docker (CPU/GPU)
|
| 116 |
|
| 117 |
+
```dockerfile
|
| 118 |
+
# Dockerfile (add to repo root if needed)
|
| 119 |
+
FROM pytorch/pytorch:2.13.0-cuda12.1-cudnn9-runtime
|
| 120 |
+
WORKDIR /app
|
| 121 |
+
COPY requirements.txt .
|
| 122 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 123 |
+
COPY . .
|
| 124 |
+
EXPOSE 7860
|
| 125 |
+
CMD ["python", "app.py"]
|
| 126 |
+
```
|
| 127 |
|
| 128 |
```bash
|
| 129 |
+
docker build -t prompt-reverse-engineer .
|
| 130 |
+
# GPU:
|
| 131 |
+
docker run --gpus all -p 7860:7860 prompt-reverse-engineer
|
| 132 |
+
# CPU (slow):
|
| 133 |
+
docker run -p 7860:7860 prompt-reverse-engineer
|
| 134 |
```
|
| 135 |
|
| 136 |
+
### Option E: API-only pathway (no local GPU)
|
| 137 |
+
|
| 138 |
+
Set these environment variables before launching:
|
| 139 |
+
|
| 140 |
+
```bash
|
| 141 |
+
export VLM_BACKEND=api
|
| 142 |
+
export VLM_API_KEY=your_openrouter_key # or OPENAI_API_KEY compatible endpoint
|
| 143 |
+
export VLM_API_MODEL=qwen/qwen3-vl-32b-instruct
|
| 144 |
+
export VLM_API_BASE_URL=https://openrouter.ai/api/v1
|
| 145 |
+
|
| 146 |
+
export SCORER_BACKEND=api
|
| 147 |
+
export SCORER_API_KEY=your_openai_key # gpt-4o for VQAScore logprobs
|
| 148 |
+
export SCORER_API_MODEL=gpt-4o
|
| 149 |
+
|
| 150 |
+
export PROXY_BACKEND=fal
|
| 151 |
+
export FAL_KEY=your_fal_key
|
| 152 |
+
export FAL_ENDPOINT=fal-ai/flux/schnell
|
| 153 |
+
|
| 154 |
+
export DINO_MODEL_ID=facebook/dinov2-small # small, CPU-friendly
|
| 155 |
+
```
|
| 156 |
|
| 157 |
+
Then run `python app.py` or `python cli.py ...` as above.
|
| 158 |
+
|
| 159 |
+
---
|
| 160 |
+
|
| 161 |
+
## Configuration
|
| 162 |
+
|
| 163 |
+
All model backends and runtime knobs are controlled via environment variables (see `inversion/backends.py`). The Gradio UI also exposes the most common gates as sliders.
|
| 164 |
+
|
| 165 |
+
| Variable | Meaning | Default | Notes |
|
| 166 |
+
|----------|---------|---------|-------|
|
| 167 |
+
| `VLM_BACKEND` | `local` or `api` | `local` | VLM for DSG extraction + rewrite |
|
| 168 |
+
| `VLM_MODEL_ID` | HF repo (local) | `Qwen/Qwen3-VL-8B-Instruct` | Requires ~16 GB VRAM in 4-bit |
|
| 169 |
+
| `VLM_API_MODEL` | Model name (api) | `qwen/qwen3-vl-32b-instruct` | OpenRouter format |
|
| 170 |
+
| `VLM_API_BASE_URL` | API base URL | `https://openrouter.ai/api/v1` | |
|
| 171 |
+
| `VLM_API_KEY` | API key | — | Required if `VLM_BACKEND=api` |
|
| 172 |
+
| `SCORER_BACKEND` | `local` or `api` | auto (matches VLM) | VQAScore backend |
|
| 173 |
+
| `SCORER_API_MODEL` | API model for scoring | `gpt-4o` | Needs logprobs |
|
| 174 |
+
| `SCORER_API_KEY` | API key for scorer | `$OPENAI_API_KEY` | |
|
| 175 |
+
| `PROXY_BACKEND` | `flux` or `fal` | `flux` | Proxy renderer |
|
| 176 |
+
| `PROXY_MODEL_ID` | HF repo (flux) | `black-forest-labs/FLUX.1-schnell` | |
|
| 177 |
+
| `PROXY_CPU_OFFLOAD` | Offload FLUX to CPU | `0` | Set `1` for <24 GB VRAM |
|
| 178 |
+
| `FAL_ENDPOINT` | FAL endpoint | `fal-ai/flux/schnell` | If `PROXY_BACKEND=fal` |
|
| 179 |
+
| `DINO_MODEL_ID` | DINO model | `facebook/dinov3-vitb16-pretrain-lvd1689m` | DINOv3-B default |
|
| 180 |
+
| `DINO_DEVICE` | `cuda`, `cpu`, `mps` | auto | |
|
| 181 |
+
| `VQA_MODE` | `normalized` or `raw` | `normalized` | VQAScore normalization |
|
| 182 |
+
|
| 183 |
+
**EngineConfig** (Python API / CLI flags) — runtime gates per run:
|
| 184 |
+
|
| 185 |
+
| Key | Meaning | Default | Range |
|
| 186 |
+
|-----|---------|---------|-------|
|
| 187 |
+
| `max_iters` | Max rewrite iterations | `5` | 1–8 |
|
| 188 |
+
| `vqa_gate` | S_VQA convergence threshold | `0.90` | 0.5–1.0 |
|
| 189 |
+
| `dino_gate` | S_DINO convergence threshold | `0.80` | 0.0–1.0 |
|
| 190 |
+
| `fail_threshold` | Predicate failure threshold | `0.75` | 0.3–0.95 |
|
| 191 |
+
| `parent_gate` | DSG parent gate for dependency blocking | `0.5` | — |
|
| 192 |
+
| `ground` | Enable grounding on original | `True` | — |
|
| 193 |
+
| `grounding_threshold` | Re-localization acceptance gate | `0.5` | — |
|
| 194 |
+
| `w_vqa` | Weight on S_VQA for best pick | `0.7` | 0.0–1.0 |
|
| 195 |
+
| `base_seed` | Base seed (proxy seed = base + t) | `42` | — |
|
| 196 |
+
| `proxy_long_side` | Proxy render long side (px) | `1024` | — |
|
| 197 |
+
|
| 198 |
+
---
|
| 199 |
|
| 200 |
+
## Usage / API
|
| 201 |
|
| 202 |
+
### Python API (single image)
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
```python
|
| 205 |
+
from PIL import Image
|
| 206 |
+
from inversion import EngineConfig, invert_image_to_verified_prompt
|
| 207 |
+
from inversion.backends import BackendSettings, load_components
|
| 208 |
|
| 209 |
+
# Load models (respects env vars)
|
| 210 |
+
settings = BackendSettings()
|
| 211 |
+
components = load_components(settings)
|
| 212 |
+
backends = components.backends()
|
| 213 |
|
| 214 |
+
# Configure run
|
| 215 |
+
cfg = EngineConfig(
|
| 216 |
+
max_iters=5,
|
| 217 |
+
vqa_gate=0.90,
|
| 218 |
+
dino_gate=0.80,
|
| 219 |
+
fail_threshold=0.75,
|
| 220 |
+
w_vqa=0.7,
|
| 221 |
+
base_seed=42,
|
| 222 |
+
ground=True,
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
# Run
|
| 226 |
+
og = Image.open("my_image.png").convert("RGB")
|
| 227 |
+
run = invert_image_to_verified_prompt(og, backends, cfg)
|
| 228 |
+
|
| 229 |
+
# Results
|
| 230 |
+
print("Verified prompt:", run.best_prompt)
|
| 231 |
+
print(f"Best iteration: t={run.best.t}")
|
| 232 |
+
print(f"S_VQA: {run.best.mean_vqa:.3f}, S_DINO: {run.best.dino_patch:.3f}, Joint: {run.best.joint:.3f}")
|
| 233 |
+
|
| 234 |
+
# Save full report
|
| 235 |
+
from inversion.engine import save_run
|
| 236 |
+
save_run(run, "runs/my_image", og)
|
| 237 |
+
```
|
| 238 |
+
|
| 239 |
+
### Gradio UI (app.py)
|
| 240 |
+
|
| 241 |
+
The Space UI exposes:
|
| 242 |
+
- Image upload (drag-drop, clipboard, webcam)
|
| 243 |
+
- Stopping rule sliders: max iterations, S_VQA gate, S_DINO gate
|
| 244 |
+
- Advanced accordion: failure threshold, S_VQA weight, base seed, grounding toggle
|
| 245 |
+
- Live streaming: stage progress bar, per-iteration scores, predicate table, scene graph JSON, grounding log
|
| 246 |
+
- Outputs: verified prompt (copy button), proxy render gallery, downloadable JSON report
|
| 247 |
+
|
| 248 |
+
---
|
| 249 |
+
|
| 250 |
+
## Output / Data Flow
|
| 251 |
+
|
| 252 |
+
```
|
| 253 |
+
Input image
|
| 254 |
+
│
|
| 255 |
+
▼
|
| 256 |
+
┌─────────────────────────────────────┐
|
| 257 |
+
│ Module 1: Constrained DSG extraction│ → DSGSceneSchema (JSON)
|
| 258 |
+
│ Qwen3-VL → entities, attrs, rels │ • medium_and_optics[]
|
| 259 |
+
│ 3×3 grid, ≤12 nodes │ • background
|
| 260 |
+
└─────────────────────────────────────┘ • color_palette[]
|
| 261 |
+
│ • nodes[] (id, grid_cell, entity, attrs, rels)
|
| 262 |
+
▼ • extra_checks[]
|
| 263 |
+
┌─────────────────────────────────────┐
|
| 264 |
+
│ Module 2: Grounding on original │ → predicates[] (linearized)
|
| 265 |
+
│ VQAScore each predicate on OG │ • dropped[] (hallucinations removed)
|
| 266 |
+
│ Parent-gate dependency blocking │ • relocalized[] (grid cell corrections)
|
| 267 |
+
└─────────────────────────────────────┘
|
| 268 |
+
│
|
| 269 |
+
▼
|
| 270 |
+
┌─────────────────────────────────────┐
|
| 271 |
+
│ Module 2b: Canonical linearization │ → canonical_prompt (string)
|
| 272 |
+
│ Deterministic template from graph │
|
| 273 |
+
└─────────────────────────────────────┘
|
| 274 |
+
│
|
| 275 |
+
▼ (loop max_iters times)
|
| 276 |
+
┌─────────────────────────────────────┐
|
| 277 |
+
│ Module 3: Proxy render (FLUX) │ → proxy_image (PIL)
|
| 278 |
+
│ seed = base_seed + t │
|
| 279 |
+
└─────────────────────────────────────┘
|
| 280 |
+
│
|
| 281 |
+
▼
|
| 282 |
+
┌─────────────────────────────────────┐
|
| 283 |
+
│ Module 4: Dual verification │ → scored[] (Predicate + raw/effective)
|
| 284 |
+
│ VQAScore each predicate on proxy │ • mean_vqa (S_VQA)
|
| 285 |
+
│ DINOv3 patch/cls similarity │ • dino_patch (S_DINO), dino_cls
|
| 286 |
+
│ Joint = w_vqa·S_VQA + w_dino·S_DINO│
|
| 287 |
+
└─────────────────────────────────────┘
|
| 288 |
+
│
|
| 289 |
+
├─ Gates met? → STOP (converged)
|
| 290 |
+
│
|
| 291 |
+
▼
|
| 292 |
+
┌─────────────────────────────────────┐
|
| 293 |
+
│ Targeted diff rewrite │ → RewritePatch (edits + additions)
|
| 294 |
+
│ VLM rewrites only failed facts │ Applied → new prompt for next iter
|
| 295 |
+
└─────────────────────────────────────┘
|
| 296 |
+
```
|
| 297 |
+
|
| 298 |
+
**Report schema** (`report.json` per run):
|
| 299 |
+
```json
|
| 300 |
+
{
|
| 301 |
+
"config": { ...EngineConfig... },
|
| 302 |
+
"stop_reason": "converged" | "max_iters",
|
| 303 |
+
"best_prompt": "verified prompt string",
|
| 304 |
+
"best_iteration": 3,
|
| 305 |
+
"best_scores": { "S_VQA": 0.92, "S_DINO_patch": 0.84, "joint": 0.88 },
|
| 306 |
+
"canonical_prompt": "initial linearization",
|
| 307 |
+
"proxy_size": [1024, 768],
|
| 308 |
+
"graph": { ...DSGSceneSchema... },
|
| 309 |
+
"predicates": [ { "id", "kind", "statement", "ref" }, ... ],
|
| 310 |
+
"grounding_dropped": [ ... ],
|
| 311 |
+
"grounding_relocalized": [ { "node", "entity", "from", "to", "p_yes" }, ... ],
|
| 312 |
+
"iterations": [ { "t", "seed", "prompt", "S_VQA", "S_DINO_patch", "joint", "failed_ids", "patch" }, ... ]
|
| 313 |
+
}
|
| 314 |
+
```
|
| 315 |
+
|
| 316 |
+
---
|
| 317 |
+
|
| 318 |
+
## Performance
|
| 319 |
+
|
| 320 |
+
| Backend | Hardware | Time/Image (5 iters) | VRAM (peak) | Notes |
|
| 321 |
+
|---------|----------|----------------------|-------------|-------|
|
| 322 |
+
| Local (Qwen3-VL-8B + FLUX-schnell + DINOv3-B) | RTX 4090 24 GB | ~180 s | ~22 GB | Default pathway |
|
| 323 |
+
| Local + CPU offload (FLUX) | RTX 3080 16 GB | ~240 s | ~14 GB | `PROXY_CPU_OFFLOAD=1` |
|
| 324 |
+
| API (OpenRouter Qwen3-VL-32B + FAL FLUX + gpt-4o) | CPU only | ~90 s | <2 GB | Network-bound |
|
| 325 |
+
| Local (Qwen3-VL-8B 4-bit + FLUX-schnell 8-bit) | RTX 4090 24 GB | ~150 s | ~16 GB | Quantization WIP |
|
| 326 |
+
|
| 327 |
+
> First run downloads model weights (~35 GB total for local pathway). Subsequent runs are cached.
|
| 328 |
+
|
| 329 |
+
---
|
| 330 |
+
|
| 331 |
+
## Troubleshooting
|
| 332 |
+
|
| 333 |
+
| Symptom | Cause | Fix |
|
| 334 |
+
|---------|-------|-----|
|
| 335 |
+
| `CUDA out of memory` | VRAM exhausted | Set `PROXY_CPU_OFFLOAD=1`; reduce `proxy_long_side`; use API pathway |
|
| 336 |
+
| `VLM_API_KEY not set` | API pathway selected without key | Export `VLM_API_KEY` (OpenRouter) or switch to `VLM_BACKEND=local` |
|
| 337 |
+
| `gpt-4o logprobs unavailable` | Scorer API key lacks logprobs access | Use OpenAI key with logprobs; or set `SCORER_BACKEND=local` |
|
| 338 |
+
| `FLUX model not found` | HF token/gated repo | `huggingface-cli login` or set `PROXY_MODEL_ID` to public variant |
|
| 339 |
+
| `DINOv3 model not found` | Wrong model ID | Use `facebook/dinov3-vitb16-pretrain-lvd1689m` (default) or `facebook/dinov2-base` |
|
| 340 |
+
| Gradio UI won't load | Port 7860 in use | `GRADIO_SERVER_PORT=7861 python app.py` |
|
| 341 |
+
| First iteration very slow | Model loading + compilation | Normal; torch.compile + model init on first forward |
|
| 342 |
+
|
| 343 |
+
**Logs:** Gradio console output shows per-stage status. CLI prints iteration status to stdout. Full run data in `runs/<stem>/report.json`.
|
| 344 |
+
|
| 345 |
+
---
|
| 346 |
+
|
| 347 |
+
## Attribution & License
|
| 348 |
+
|
| 349 |
+
**Author:** Gaspar Dario Larrain Varas
|
| 350 |
+
**Space:** https://huggingface.co/spaces/glarr/Prompt-Reverse-Engineer
|
| 351 |
+
**Repository:** https://github.com/glarrainv/Prompt-Reverse-Engineer
|
| 352 |
+
**License:** Apache-2.0
|
| 353 |
+
|
| 354 |
+
This work builds on the following research:
|
| 355 |
+
|
| 356 |
+
```bibtex
|
| 357 |
+
@article{cho2024dsg,
|
| 358 |
+
title={Davidsonian Scene Graph: Improving Reliability in Fine-grained Evaluation for Text-to-Image Generation},
|
| 359 |
+
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},
|
| 360 |
+
booktitle={International Conference on Learning Representations (ICLR)},
|
| 361 |
+
year={2024}
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
@inproceedings{lin2024vqascore,
|
| 365 |
+
title={Evaluating Text-to-Visual Generation with Image-to-Text Generation},
|
| 366 |
+
author={Lin, Zhiqiu and Pathak, Deepak and Li, Baiqi and Li, Jiayao and Xia, Xide and Neubig, Graham and Zhang, Pengchuan and Ramanan, Deva},
|
| 367 |
+
booktitle={European Conference on Computer Vision (ECCV)},
|
| 368 |
+
year={2024}
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
@article{oquab2024dinov2,
|
| 372 |
+
title={DINOv2: Learning Robust Visual Features without Supervision},
|
| 373 |
+
author={Oquab, Maxime and Darcet, Timoth{\'e}e and Moutakanni, Th{\'e}o and others},
|
| 374 |
+
journal={Transactions on Machine Learning Research (TMLR)},
|
| 375 |
+
year={2024}
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
@article{simeoni2025dinov3,
|
| 379 |
+
title={DINOv3},
|
| 380 |
+
author={Sim{\'e}oni, Oriane and others},
|
| 381 |
+
journal={arXiv preprint arXiv:2508.10104},
|
| 382 |
+
year={2025}
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
@article{bai2025qwen25vl,
|
| 386 |
+
title={Qwen2.5-VL Technical Report},
|
| 387 |
+
author={Bai, Shuai and Chen, Keqin and Liu, Xuejing and others},
|
| 388 |
+
journal={arXiv preprint arXiv:2502.13923},
|
| 389 |
+
year={2025}
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
@misc{flux2024,
|
| 393 |
+
title={FLUX},
|
| 394 |
+
author={{Black Forest Labs}},
|
| 395 |
+
year={2024},
|
| 396 |
+
howpublished={https://github.com/black-forest-labs/flux}
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
@software{larrain2026promptreverse,
|
| 400 |
+
author = {Larrain Varas, Gaspar Dario},
|
| 401 |
+
title = {Prompt Reverse Engineer},
|
| 402 |
+
year = {2026},
|
| 403 |
+
url = {https://github.com/glarrainv/Prompt-Reverse-Engineer},
|
| 404 |
+
license = {Apache-2.0}
|
| 405 |
+
}
|
| 406 |
+
```
|
| 407 |
|
| 408 |
+
**Model credits:** Qwen Team (Qwen3-VL), Black Forest Labs (FLUX.1), Meta AI (DINOv2/DINOv3), OpenAI (gpt-4o for VQAScore API pathway).
|
app.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
import json
|
| 2 |
import tempfile
|
| 3 |
|
|
@@ -42,181 +43,429 @@ def gpu_embed(image):
|
|
| 42 |
BACKENDS = Backends(extract_dsg=gpu_extract, vqa_scores=gpu_vqa, rewrite=gpu_rewrite,
|
| 43 |
render=gpu_render, embed=gpu_embed)
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
def _iteration_rows(run):
|
| 50 |
rows = []
|
| 51 |
for it in run.iterations:
|
| 52 |
-
applied = "" if it.patch is None else f"{len(it.patch.applied)} (+{len(it.patch.added)} added)"
|
| 53 |
if it.rewrite_error:
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
return rows
|
| 58 |
|
| 59 |
|
| 60 |
def _predicate_rows(run, fail_threshold):
|
| 61 |
best = run.best
|
| 62 |
if best is None:
|
| 63 |
-
return [[p.kind, p.statement, None, None, "
|
| 64 |
rows = []
|
| 65 |
for sp in best.scored:
|
| 66 |
-
status = ("
|
| 67 |
-
"
|
| 68 |
rows.append([sp.predicate.kind, sp.predicate.statement, round(sp.raw, 3), round(sp.effective, 3), status])
|
| 69 |
return rows
|
| 70 |
|
| 71 |
|
| 72 |
-
def
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
return (
|
| 79 |
-
|
|
|
|
|
|
|
| 80 |
run.best_prompt,
|
| 81 |
-
|
|
|
|
| 82 |
_iteration_rows(run),
|
| 83 |
_predicate_rows(run, fail_threshold),
|
| 84 |
run.graph.model_dump() if run.graph else None,
|
| 85 |
-
|
| 86 |
-
report_path,
|
| 87 |
)
|
| 88 |
|
| 89 |
|
| 90 |
def invert(image, max_iters, vqa_gate, dino_gate, fail_threshold, w_vqa, base_seed, ground):
|
| 91 |
if image is None:
|
| 92 |
-
raise gr.Error("Upload an image.")
|
| 93 |
cfg = EngineConfig(max_iters=int(max_iters), vqa_gate=vqa_gate, dino_gate=dino_gate,
|
| 94 |
fail_threshold=fail_threshold, w_vqa=w_vqa, w_dino=round(1 - w_vqa, 4),
|
| 95 |
base_seed=int(base_seed), ground=bool(ground))
|
| 96 |
run = None
|
| 97 |
for run in iter_inversion(image, BACKENDS, cfg):
|
| 98 |
-
yield _outputs(run, fail_threshold)
|
| 99 |
assert run is not None
|
| 100 |
with tempfile.NamedTemporaryFile("w", suffix=".json", prefix="inversion_report_", delete=False,
|
| 101 |
encoding="utf-8") as f:
|
| 102 |
json.dump(run.to_dict(), f, indent=2)
|
| 103 |
-
yield _outputs(run, fail_threshold, f.name)
|
| 104 |
|
| 105 |
|
| 106 |
-
|
| 107 |
-
gr.Markdown("# Prompt Reverse Engineer")
|
| 108 |
-
gr.Markdown("## Image → Verified Prompt")
|
| 109 |
-
gr.Markdown(
|
| 110 |
-
"Closed-loop inversion: **(1)** a constrained Davidsonian scene graph is extracted on a 3×3 grid, "
|
| 111 |
-
"**(2)** compiled into dependency-ordered yes/no predicates and a canonical prompt, "
|
| 112 |
-
"**(3)** rendered by a fast proxy text-to-image model, and **(4)** verified with VQAScore + DINOv2 patch "
|
| 113 |
-
"similarity. Only failed predicates are rewritten, until S_VQA and S_DINO clear their gates."
|
| 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 |
run_button.click(
|
| 216 |
invert,
|
| 217 |
[image, max_iters, vqa_gate, dino_gate, fail_threshold, w_vqa, base_seed, ground],
|
| 218 |
-
[status, best_prompt, gallery, iterations, predicates, graph_json,
|
| 219 |
)
|
| 220 |
|
| 221 |
if __name__ == "__main__":
|
| 222 |
-
demo.launch()
|
|
|
|
| 1 |
+
import html
|
| 2 |
import json
|
| 3 |
import tempfile
|
| 4 |
|
|
|
|
| 43 |
BACKENDS = Backends(extract_dsg=gpu_extract, vqa_scores=gpu_vqa, rewrite=gpu_rewrite,
|
| 44 |
render=gpu_render, embed=gpu_embed)
|
| 45 |
|
| 46 |
+
|
| 47 |
+
# --------------------------------------------------------------------------- look
|
| 48 |
+
|
| 49 |
+
def _short(model_id: str) -> str:
|
| 50 |
+
return model_id.rsplit("/", 1)[-1]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
MODEL_CHIP = " · ".join([
|
| 54 |
+
_short(SETTINGS.vlm_model_id if SETTINGS.vlm_backend == "local" else SETTINGS.vlm_api_model),
|
| 55 |
+
_short(SETTINGS.proxy_model_id if SETTINGS.proxy_backend == "flux" else SETTINGS.fal_endpoint),
|
| 56 |
+
_short(SETTINGS.dino_model_id),
|
| 57 |
+
])
|
| 58 |
+
|
| 59 |
+
BRAND = gr.themes.Color(
|
| 60 |
+
c50="#EEF3FD", c100="#DCE6FA", c200="#B9CDF5", c300="#8AABEC", c400="#5A85DD",
|
| 61 |
+
c500="#3A68CF", c600="#2B59C3", c700="#234AA3", c800="#1E4297", c900="#1A3570", c950="#0F2048",
|
| 62 |
+
name="brand",
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
THEME = gr.themes.Base(
|
| 66 |
+
primary_hue=BRAND,
|
| 67 |
+
neutral_hue="slate",
|
| 68 |
+
radius_size="md",
|
| 69 |
+
font=[gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"],
|
| 70 |
+
font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace"],
|
| 71 |
+
).set(
|
| 72 |
+
body_background_fill="#F5F6F8",
|
| 73 |
+
block_background_fill="#FFFFFF",
|
| 74 |
+
block_border_color="#E3E6EB",
|
| 75 |
+
block_border_width="1px",
|
| 76 |
+
block_radius="12px",
|
| 77 |
+
block_shadow="none",
|
| 78 |
+
block_label_text_color="#5B6270",
|
| 79 |
+
block_title_text_color="#14171F",
|
| 80 |
+
block_title_text_weight="500",
|
| 81 |
+
border_color_primary="#E3E6EB",
|
| 82 |
+
body_text_color_subdued="#5B6270",
|
| 83 |
+
input_background_fill="#FFFFFF",
|
| 84 |
+
input_border_color="#D3D7DE",
|
| 85 |
+
slider_color="#2B59C3",
|
| 86 |
+
color_accent="#2B59C3",
|
| 87 |
+
color_accent_soft="#EAF0FC",
|
| 88 |
+
link_text_color="#2B59C3",
|
| 89 |
+
button_primary_background_fill="#2B59C3",
|
| 90 |
+
button_primary_background_fill_hover="#1E4297",
|
| 91 |
+
button_primary_text_color="#FFFFFF",
|
| 92 |
+
button_secondary_background_fill="#FFFFFF",
|
| 93 |
+
button_secondary_border_color="#D3D7DE",
|
| 94 |
+
button_large_radius="10px",
|
| 95 |
+
button_large_text_size="15px",
|
| 96 |
+
checkbox_background_color_selected="#2B59C3",
|
| 97 |
+
table_even_background_fill="#FFFFFF",
|
| 98 |
+
table_odd_background_fill="#FAFBFC",
|
| 99 |
+
section_header_text_weight="600",
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
CSS = """
|
| 103 |
+
:root{--pre-text:#14171F;--pre-muted:#5B6270;--pre-line:#E3E6EB;--pre-track:#EEF0F3;--pre-card:#FFFFFF;
|
| 104 |
+
--pre-accent:#2B59C3;--pre-accent-soft:#EAF0FC;--pre-pass:#176B45;--pre-pass-bg:#E6F4EC;
|
| 105 |
+
--pre-warn:#9A4508;--pre-warn-bg:#FDF0E3}
|
| 106 |
+
.dark{--pre-text:#E8EAEE;--pre-muted:#A3AAB8;--pre-line:#2E333D;--pre-track:#2A2F38;--pre-card:#171A20;
|
| 107 |
+
--pre-accent:#7FA2F0;--pre-accent-soft:#1D2A45;--pre-pass:#7AD3A4;--pre-pass-bg:#16332A;
|
| 108 |
+
--pre-warn:#F3B37A;--pre-warn-bg:#3A2716}
|
| 109 |
+
.gradio-container{max-width:1280px !important;margin:0 auto !important}
|
| 110 |
+
footer{display:none !important}
|
| 111 |
+
.pre-header{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px;padding:8px 0 4px}
|
| 112 |
+
.pre-brand{display:flex;align-items:center;gap:12px}
|
| 113 |
+
.pre-logo{width:32px;height:32px;border-radius:8px;background:var(--pre-text);display:flex;align-items:center;justify-content:center}
|
| 114 |
+
.pre-logo svg{stroke:var(--pre-card)}
|
| 115 |
+
.pre-title{font-weight:600;font-size:15px;line-height:1.2;color:var(--pre-text)}
|
| 116 |
+
.pre-sub{font-size:12px;color:var(--pre-muted)}
|
| 117 |
+
.pre-nav{display:flex;align-items:center;gap:20px;font-size:13px}
|
| 118 |
+
.pre-nav a{text-decoration:none;font-weight:500;color:var(--pre-accent)}
|
| 119 |
+
.pre-chip{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border:1px solid var(--pre-line);border-radius:999px;color:var(--pre-muted);font-size:12px}
|
| 120 |
+
.pre-dot{width:6px;height:6px;border-radius:999px;background:#1F8A5B}
|
| 121 |
+
.pre-step-title{margin:0 0 2px;font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--pre-muted)}
|
| 122 |
+
.pre-card{background:var(--pre-card);border:1px solid var(--pre-line);border-radius:12px;padding:20px 24px;color:var(--pre-text)}
|
| 123 |
+
.pre-row{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px}
|
| 124 |
+
.pre-badge{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;font-size:13px;font-weight:600}
|
| 125 |
+
.pre-badge.ok{background:var(--pre-pass-bg);color:var(--pre-pass)}
|
| 126 |
+
.pre-badge.warn{background:var(--pre-warn-bg);color:var(--pre-warn)}
|
| 127 |
+
.pre-badge.run{background:var(--pre-accent-soft);color:var(--pre-accent)}
|
| 128 |
+
.pre-muted{color:var(--pre-muted)}
|
| 129 |
+
.pre-stages{list-style:none;margin:20px 0;padding:0;display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:8px}
|
| 130 |
+
.pre-stages li{display:flex;flex-direction:column;gap:6px;margin:0}
|
| 131 |
+
.pre-bar{height:4px;border-radius:999px;background:var(--pre-track)}
|
| 132 |
+
.pre-stages li.done .pre-bar{background:var(--pre-accent)}
|
| 133 |
+
.pre-stages li.active .pre-bar{background:var(--pre-accent);opacity:.45;animation:pre-pulse 1.2s ease-in-out infinite}
|
| 134 |
+
@keyframes pre-pulse{50%{opacity:1}}
|
| 135 |
+
.pre-n{font-family:var(--font-mono);font-size:12px;color:var(--pre-muted)}
|
| 136 |
+
.pre-stage-label{font-size:13px;font-weight:500;line-height:1.3}
|
| 137 |
+
.pre-stages li.pending .pre-stage-label{color:var(--pre-muted)}
|
| 138 |
+
.pre-tiles{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
|
| 139 |
+
.pre-tile{border:1px solid var(--pre-line);border-radius:10px;padding:14px 16px;display:flex;flex-direction:column;gap:8px}
|
| 140 |
+
.pre-tile-label{font-size:12px;color:var(--pre-muted)}
|
| 141 |
+
.pre-tile-value{font-family:var(--font-mono);font-size:28px;font-weight:600;letter-spacing:-.02em}
|
| 142 |
+
.pre-meter{position:relative;height:6px;border-radius:999px;background:var(--pre-track)}
|
| 143 |
+
.pre-meter-fill{position:absolute;left:0;top:0;bottom:0;border-radius:999px;background:var(--pre-accent)}
|
| 144 |
+
.pre-meter-gate{position:absolute;top:-3px;width:2px;height:12px;background:var(--pre-text)}
|
| 145 |
+
.pre-intro h1{margin:0 0 8px;font-size:26px;line-height:1.25;font-weight:600;letter-spacing:-.01em}
|
| 146 |
+
.pre-intro p{margin:0;max-width:62ch;font-size:15px;color:var(--pre-muted)}
|
| 147 |
+
.pre-how{list-style:none;margin:24px 0 0;padding:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
|
| 148 |
+
.pre-how li{border:1px solid var(--pre-line);border-radius:10px;padding:18px;display:flex;flex-direction:column;gap:6px;margin:0}
|
| 149 |
+
.pre-how .pre-n{color:var(--pre-accent);font-weight:500}
|
| 150 |
+
.pre-how b{font-weight:600}
|
| 151 |
+
.pre-how span{font-size:13px;color:var(--pre-muted)}
|
| 152 |
+
.pre-placeholder{margin-top:16px;border:1.5px dashed var(--pre-line);border-radius:12px;min-height:180px;display:flex;
|
| 153 |
+
flex-direction:column;align-items:center;justify-content:center;gap:6px;text-align:center;padding:32px}
|
| 154 |
+
.pre-placeholder span{font-size:13px;color:var(--pre-muted);max-width:46ch}
|
| 155 |
+
/* Gradio component polish */
|
| 156 |
+
.pre-group{border-radius:12px !important;overflow:hidden}
|
| 157 |
+
.pre-group-title{background:var(--block-background-fill) !important;padding:0 !important;min-height:0 !important}
|
| 158 |
+
.pre-group-title .pre-step-title{margin:0;padding:14px 12px 8px}
|
| 159 |
+
.pre-image{border:1.5px dashed var(--pre-drop) !important;border-radius:8px !important}
|
| 160 |
+
:root{--pre-drop:#B9C0CC}.dark{--pre-drop:#4A5160}
|
| 161 |
+
.pre-dl{max-width:240px !important;margin-left:auto !important;border:1px solid var(--input-border-color) !important}
|
| 162 |
+
.pre-panel{background:var(--block-background-fill) !important;border:1px solid var(--block-border-color) !important;
|
| 163 |
+
border-radius:12px !important;padding:4px 16px 16px !important}
|
| 164 |
+
.pre-results table,.pre-results table *,.pre-results td,.pre-results td *,.pre-results th *{
|
| 165 |
+
font-family:var(--font) !important;font-variant-numeric:tabular-nums}
|
| 166 |
+
@media (max-width:720px){
|
| 167 |
+
.pre-how{grid-template-columns:repeat(1,minmax(0,1fr))}
|
| 168 |
+
.pre-card{padding:16px}
|
| 169 |
+
.pre-stages{gap:4px}
|
| 170 |
+
.pre-stage-label{display:none}
|
| 171 |
+
.pre-tiles{gap:8px}
|
| 172 |
+
.pre-tile{padding:10px}
|
| 173 |
+
.pre-tile-label{font-size:11px}
|
| 174 |
+
.pre-tile-value{font-size:20px}
|
| 175 |
+
.pre-tile-value + .pre-muted{display:none}
|
| 176 |
+
}
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
LOGO = ('<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" '
|
| 180 |
+
'stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 0 1 15.5-6.2L21 8"/><path d="M21 3v5h-5"/>'
|
| 181 |
+
'<path d="M21 12a9 9 0 0 1-15.5 6.2L3 16"/><path d="M3 21v-5h5"/></svg>')
|
| 182 |
+
CHECK = ('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" '
|
| 183 |
+
'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>')
|
| 184 |
+
|
| 185 |
+
HEADER_HTML = f"""
|
| 186 |
+
<div class="pre-header">
|
| 187 |
+
<div class="pre-brand">
|
| 188 |
+
<div class="pre-logo">{LOGO}</div>
|
| 189 |
+
<div><div class="pre-title">Prompt Reverse Engineer</div>
|
| 190 |
+
<div class="pre-sub">Image → verified text-to-image prompt</div></div>
|
| 191 |
+
</div>
|
| 192 |
+
<nav class="pre-nav">
|
| 193 |
+
<a href="#method">How it works</a>
|
| 194 |
+
<a href="#cite">Cite</a>
|
| 195 |
+
<span class="pre-chip"><span class="pre-dot"></span>{html.escape(MODEL_CHIP)}</span>
|
| 196 |
+
</nav>
|
| 197 |
+
</div>
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
INTRO_HTML = """
|
| 201 |
+
<div class="pre-card pre-intro" id="method">
|
| 202 |
+
<h1>Turn an image back into a prompt you can verify</h1>
|
| 203 |
+
<p>Instead of one free-form caption, the image is broken into checkable facts. A fast model renders the
|
| 204 |
+
prompt, every fact is checked against the render, and only the failed parts are rewritten.</p>
|
| 205 |
+
<ol class="pre-how">
|
| 206 |
+
<li><span class="pre-n">01</span><b>Extract a scene graph</b>
|
| 207 |
+
<span>Shapes, colors, medium and relations, each placed on a 3 × 3 grid.</span></li>
|
| 208 |
+
<li><span class="pre-n">02</span><b>Ground on the original</b>
|
| 209 |
+
<span>Facts the original itself fails are removed, so no unverified style words reach the prompt.</span></li>
|
| 210 |
+
<li><span class="pre-n">03</span><b>Render and verify</b>
|
| 211 |
+
<span>A proxy model renders the prompt; VQAScore checks each fact and DINO checks the layout.</span></li>
|
| 212 |
+
<li><span class="pre-n">04</span><b>Rewrite only what failed</b>
|
| 213 |
+
<span>Targeted edits repeat until both scores clear their gates or iterations run out.</span></li>
|
| 214 |
+
</ol>
|
| 215 |
+
</div>
|
| 216 |
+
<div class="pre-placeholder"><b>Results appear here</b>
|
| 217 |
+
<span>The verified prompt, proxy renders and per-fact scores stream in as each step finishes.</span></div>
|
| 218 |
+
"""
|
| 219 |
+
|
| 220 |
+
STAGES = ["Extract scene graph", "Ground on original", "Render proxy", "Verify", "Rewrite failures"]
|
| 221 |
+
ITER_HEADERS = ["Iteration", "Seed", "S_VQA", "S_DINO", "Joint", "Failed", "Rewrite"]
|
| 222 |
+
PRED_HEADERS = ["Kind", "Statement", "P(yes)", "Effective", "Status"]
|
| 223 |
+
GROUND_HEADERS = ["Fact", "Detail", "Action"]
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
# --------------------------------------------------------------------------- rendering
|
| 227 |
+
|
| 228 |
+
def _stage(run) -> int:
|
| 229 |
+
"""Index of the active pipeline stage (5 = finished)."""
|
| 230 |
+
s = run.status
|
| 231 |
+
if s.startswith("Done"):
|
| 232 |
+
return 5
|
| 233 |
+
for i, key in enumerate(("Module 1", "Module 2", "Module 3", "Module 4", "targeted rewrite")):
|
| 234 |
+
if key in s:
|
| 235 |
+
return i
|
| 236 |
+
return 0
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _meter(value, gate=None):
|
| 240 |
+
fill = f'<div class="pre-meter-fill" style="width:{max(0.0, min(1.0, value)) * 100:.0f}%"></div>'
|
| 241 |
+
mark = "" if gate is None else f'<div class="pre-meter-gate" style="left:{gate * 100:.0f}%"></div>'
|
| 242 |
+
return f'<div class="pre-meter">{fill}{mark}</div>'
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _tile(label, value, note, fraction, gate=None):
|
| 246 |
+
return (f'<div class="pre-tile"><div class="pre-tile-label">{label}</div>'
|
| 247 |
+
f'<div><span class="pre-tile-value">{value}</span> <span class="pre-muted" style="font-size:12px">'
|
| 248 |
+
f'{note}</span></div>{_meter(fraction, gate)}</div>')
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _status_html(run) -> str:
|
| 252 |
+
cfg, best, stage = run.config, run.best, _stage(run)
|
| 253 |
+
if stage == 5 and run.stop_reason == "converged":
|
| 254 |
+
badge = f'<span class="pre-badge ok">{CHECK}Converged</span>'
|
| 255 |
+
line = f"Both gates met at iteration {best.t} of {cfg.max_iters}"
|
| 256 |
+
elif stage == 5:
|
| 257 |
+
badge = '<span class="pre-badge warn">Gates not met</span>'
|
| 258 |
+
line = f"Returning the best of {len(run.iterations)} iterations (t = {best.t})"
|
| 259 |
+
else:
|
| 260 |
+
badge = '<span class="pre-badge run">Running</span>'
|
| 261 |
+
line = html.escape(run.status)
|
| 262 |
+
stages = "".join(
|
| 263 |
+
f'<li class="{"done" if i < stage else "active" if i == stage else "pending"}"><div class="pre-bar"></div>'
|
| 264 |
+
f'<div class="pre-n">{i + 1:02d}</div><div class="pre-stage-label">{name}</div></li>'
|
| 265 |
+
for i, name in enumerate(STAGES))
|
| 266 |
+
if best:
|
| 267 |
+
tiles = (_tile("Predicate agreement · S_VQA", f"{best.mean_vqa:.2f}", f"gate {cfg.vqa_gate:.2f}",
|
| 268 |
+
best.mean_vqa, cfg.vqa_gate)
|
| 269 |
+
+ _tile("Layout similarity · S_DINO", f"{best.dino_patch:.2f}", f"gate {cfg.dino_gate:.2f}",
|
| 270 |
+
best.dino_patch, cfg.dino_gate)
|
| 271 |
+
+ _tile("Joint score", f"{best.joint:.3f}", f"best of {len(run.iterations)}", best.joint))
|
| 272 |
+
else:
|
| 273 |
+
tiles = (_tile("Predicate agreement · S_VQA", "—", f"gate {cfg.vqa_gate:.2f}", 0, cfg.vqa_gate)
|
| 274 |
+
+ _tile("Layout similarity · S_DINO", "—", f"gate {cfg.dino_gate:.2f}", 0, cfg.dino_gate)
|
| 275 |
+
+ _tile("Joint score", "—", "", 0))
|
| 276 |
+
weights = f"Best = {cfg.w_vqa:g} · S_VQA + {cfg.w_dino:g} · S_DINO"
|
| 277 |
+
return (f'<div class="pre-card"><div class="pre-row"><div class="pre-row" style="justify-content:flex-start">'
|
| 278 |
+
f'{badge}<span class="pre-muted">{line}</span></div><span class="pre-muted" style="font-size:12px">'
|
| 279 |
+
f'{weights}</span></div><ol class="pre-stages">{stages}</ol><div class="pre-tiles">{tiles}</div></div>')
|
| 280 |
|
| 281 |
|
| 282 |
def _iteration_rows(run):
|
| 283 |
rows = []
|
| 284 |
for it in run.iterations:
|
|
|
|
| 285 |
if it.rewrite_error:
|
| 286 |
+
rewrite = "Rewrite error"
|
| 287 |
+
elif it.patch is not None:
|
| 288 |
+
rewrite = f"{len(it.patch.applied)} edits, {len(it.patch.added)} added, {len(it.patch.skipped)} skipped"
|
| 289 |
+
elif it is run.iterations[-1] and run.stop_reason:
|
| 290 |
+
rewrite = "Stopped: gates met" if run.stop_reason == "converged" else "Stopped: max iterations"
|
| 291 |
+
else:
|
| 292 |
+
rewrite = "…"
|
| 293 |
+
label = f"{it.t} · best" if it is run.best else str(it.t)
|
| 294 |
+
rows.append([label, it.seed, round(it.mean_vqa, 3), round(it.dino_patch, 3), round(it.joint, 3),
|
| 295 |
+
len(it.failed), rewrite])
|
| 296 |
return rows
|
| 297 |
|
| 298 |
|
| 299 |
def _predicate_rows(run, fail_threshold):
|
| 300 |
best = run.best
|
| 301 |
if best is None:
|
| 302 |
+
return [[p.kind, p.statement, None, None, "Pending"] for p in run.predicates]
|
| 303 |
rows = []
|
| 304 |
for sp in best.scored:
|
| 305 |
+
status = ("Blocked by " + ", ".join(sp.blocked_by)) if sp.blocked_by else (
|
| 306 |
+
"Pass" if sp.effective >= fail_threshold else "Fail")
|
| 307 |
rows.append([sp.predicate.kind, sp.predicate.statement, round(sp.raw, 3), round(sp.effective, 3), status])
|
| 308 |
return rows
|
| 309 |
|
| 310 |
|
| 311 |
+
def _grounding_rows(run):
|
| 312 |
+
rows = [[sp.predicate.statement, f"{sp.predicate.kind} · P(yes) {sp.raw:.2f} on the original", "Removed"]
|
| 313 |
+
for sp in run.dropped]
|
| 314 |
+
rows += [[m["entity"], f"position · {m['from']} → {m['to']} · P(yes) {m['p_yes']:.2f}", "Re-localized"]
|
| 315 |
+
for m in run.relocalized]
|
| 316 |
+
return rows
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _gallery(og, run):
|
| 320 |
+
items = [(og, "Original")]
|
| 321 |
+
items += [(it.proxy_image, f"t = {it.t} · VQA {it.mean_vqa:.2f} · DINO {it.dino_patch:.2f}"
|
| 322 |
+
+ (" · best" if it is run.best else "")) for it in run.iterations]
|
| 323 |
+
return items
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _outputs(og, run, fail_threshold, report_path=None):
|
| 327 |
return (
|
| 328 |
+
gr.update(visible=False), # intro
|
| 329 |
+
gr.update(visible=True), # results
|
| 330 |
+
_status_html(run),
|
| 331 |
run.best_prompt,
|
| 332 |
+
gr.update(value=report_path, interactive=report_path is not None),
|
| 333 |
+
_gallery(og, run),
|
| 334 |
_iteration_rows(run),
|
| 335 |
_predicate_rows(run, fail_threshold),
|
| 336 |
run.graph.model_dump() if run.graph else None,
|
| 337 |
+
_grounding_rows(run),
|
|
|
|
| 338 |
)
|
| 339 |
|
| 340 |
|
| 341 |
def invert(image, max_iters, vqa_gate, dino_gate, fail_threshold, w_vqa, base_seed, ground):
|
| 342 |
if image is None:
|
| 343 |
+
raise gr.Error("Upload an image to start.")
|
| 344 |
cfg = EngineConfig(max_iters=int(max_iters), vqa_gate=vqa_gate, dino_gate=dino_gate,
|
| 345 |
fail_threshold=fail_threshold, w_vqa=w_vqa, w_dino=round(1 - w_vqa, 4),
|
| 346 |
base_seed=int(base_seed), ground=bool(ground))
|
| 347 |
run = None
|
| 348 |
for run in iter_inversion(image, BACKENDS, cfg):
|
| 349 |
+
yield _outputs(image, run, fail_threshold)
|
| 350 |
assert run is not None
|
| 351 |
with tempfile.NamedTemporaryFile("w", suffix=".json", prefix="inversion_report_", delete=False,
|
| 352 |
encoding="utf-8") as f:
|
| 353 |
json.dump(run.to_dict(), f, indent=2)
|
| 354 |
+
yield _outputs(image, run, fail_threshold, f.name)
|
| 355 |
|
| 356 |
|
| 357 |
+
# --------------------------------------------------------------------------- layout
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
|
| 359 |
+
with gr.Blocks(title="Prompt Reverse Engineer") as demo:
|
| 360 |
+
gr.HTML(HEADER_HTML)
|
| 361 |
+
|
| 362 |
+
with gr.Row(equal_height=False):
|
| 363 |
+
with gr.Column(scale=1, min_width=320):
|
| 364 |
+
with gr.Group(elem_classes="pre-group"):
|
| 365 |
+
gr.HTML('<p class="pre-step-title">1 · Original image</p>', elem_classes="pre-group-title")
|
| 366 |
+
image = gr.Image(type="pil", label="Original image", show_label=False,
|
| 367 |
+
sources=["upload", "clipboard"], height=320, elem_classes="pre-image")
|
| 368 |
+
with gr.Group(elem_classes="pre-group"):
|
| 369 |
+
gr.HTML('<p class="pre-step-title">2 · Stopping rule</p>', elem_classes="pre-group-title")
|
| 370 |
+
max_iters = gr.Slider(1, 8, value=5, step=1, label="Max iterations")
|
| 371 |
+
vqa_gate = gr.Slider(0.5, 1.0, value=0.90, step=0.01, label="Min. predicate agreement (S_VQA)")
|
| 372 |
+
dino_gate = gr.Slider(0.0, 1.0, value=0.80, step=0.01, label="Min. layout similarity (S_DINO)",
|
| 373 |
+
info="Set to 0 to stop on S_VQA alone.")
|
| 374 |
+
with gr.Accordion("Advanced settings", open=False):
|
| 375 |
+
fail_threshold = gr.Slider(0.3, 0.95, value=0.75, step=0.01, label="Failure threshold",
|
| 376 |
+
info="Facts scoring below this are sent to the rewriter.")
|
| 377 |
+
w_vqa = gr.Slider(0.0, 1.0, value=0.7, step=0.05, label="Weight on S_VQA",
|
| 378 |
+
info="Picks the best iteration; the rest of the weight goes to S_DINO.")
|
| 379 |
+
base_seed = gr.Number(value=42, precision=0, label="Base seed", info="Proxy seed = base + t.")
|
| 380 |
+
ground = gr.Checkbox(value=True, label="Ground predicates on the original",
|
| 381 |
+
info="Removes facts the scorer rejects on the original image.")
|
| 382 |
+
run_button = gr.Button("Invert image", variant="primary", size="lg")
|
| 383 |
+
|
| 384 |
+
with gr.Column(scale=3, min_width=560):
|
| 385 |
+
intro = gr.HTML(INTRO_HTML)
|
| 386 |
+
with gr.Column(visible=False, elem_classes="pre-results") as results:
|
| 387 |
+
status = gr.HTML()
|
| 388 |
+
best_prompt = gr.Textbox(label="Verified prompt", lines=3, max_lines=16, interactive=False,
|
| 389 |
+
buttons=["copy"])
|
| 390 |
+
report = gr.DownloadButton("Download report (JSON)", value=None, interactive=False,
|
| 391 |
+
variant="secondary", size="sm", elem_classes="pre-dl")
|
| 392 |
+
gallery = gr.Gallery(label="Original vs. proxy renders", columns=3, rows=1, height=310,
|
| 393 |
+
object_fit="contain", allow_preview=True)
|
| 394 |
+
with gr.Column(elem_classes="pre-panel"), gr.Tabs():
|
| 395 |
+
with gr.Tab("Iterations"):
|
| 396 |
+
iterations = gr.Dataframe(headers=ITER_HEADERS, interactive=False, show_label=False)
|
| 397 |
+
with gr.Tab("Predicates"):
|
| 398 |
+
predicates = gr.Dataframe(headers=PRED_HEADERS, interactive=False, wrap=True,
|
| 399 |
+
show_label=False, max_height=480)
|
| 400 |
+
with gr.Tab("Scene graph"):
|
| 401 |
+
graph_json = gr.JSON(show_label=False)
|
| 402 |
+
with gr.Tab("Grounding"):
|
| 403 |
+
gr.Markdown("Facts the scorer rejected on the original image. They are removed from the "
|
| 404 |
+
"prompt, or moved to the grid cell the scorer supports, before rendering.")
|
| 405 |
+
grounding = gr.Dataframe(headers=GROUND_HEADERS, interactive=False, wrap=True,
|
| 406 |
+
show_label=False)
|
| 407 |
+
|
| 408 |
+
with gr.Accordion("Cite", open=False, elem_id="cite"):
|
| 409 |
+
gr.Markdown("""Author: Larrain, G
|
| 410 |
+
|
| 411 |
+
```bibtex
|
| 412 |
+
@misc{qwen3technicalreport,
|
| 413 |
+
title={Qwen3 Technical Report}, author={Qwen Team}, year={2025},
|
| 414 |
+
eprint={2505.09388}, archivePrefix={arXiv}, primaryClass={cs.CL}, url={https://arxiv.org/abs/2505.09388}
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
@article{Qwen2.5-VL,
|
| 418 |
+
title={Qwen2.5-VL Technical Report},
|
| 419 |
+
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},
|
| 420 |
+
journal={arXiv preprint arXiv:2502.13923}, year={2025}
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
@article{Qwen2VL,
|
| 424 |
+
title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution},
|
| 425 |
+
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},
|
| 426 |
+
journal={arXiv preprint arXiv:2409.12191}, year={2024}
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
@article{Qwen-VL,
|
| 430 |
+
title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond},
|
| 431 |
+
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},
|
| 432 |
+
journal={arXiv preprint arXiv:2308.12966}, year={2023}
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
@inproceedings{cho2024dsg,
|
| 436 |
+
title={Davidsonian Scene Graph: Improving Reliability in Fine-grained Evaluation for Text-to-Image Generation},
|
| 437 |
+
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},
|
| 438 |
+
booktitle={International Conference on Learning Representations (ICLR)}, year={2024}
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
@inproceedings{lin2024vqascore,
|
| 442 |
+
title={Evaluating Text-to-Visual Generation with Image-to-Text Generation},
|
| 443 |
+
author={Lin, Zhiqiu and Pathak, Deepak and Li, Baiqi and Li, Jiayao and Xia, Xide and Neubig, Graham and Zhang, Pengchuan and Ramanan, Deva},
|
| 444 |
+
booktitle={European Conference on Computer Vision (ECCV)}, year={2024}
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
@article{oquab2024dinov2,
|
| 448 |
+
title={DINOv2: Learning Robust Visual Features without Supervision},
|
| 449 |
+
author={Oquab, Maxime and Darcet, Timoth{\\'e}e and Moutakanni, Th{\\'e}o and others},
|
| 450 |
+
journal={Transactions on Machine Learning Research (TMLR)}, year={2024}
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
@article{simeoni2025dinov3,
|
| 454 |
+
title={DINOv3}, author={Sim{\\'e}oni, Oriane and others},
|
| 455 |
+
journal={arXiv preprint arXiv:2508.10104}, year={2025}
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
@misc{flux2024,
|
| 459 |
+
title={FLUX}, author={{Black Forest Labs}}, year={2024},
|
| 460 |
+
howpublished={https://github.com/black-forest-labs/flux}
|
| 461 |
+
}
|
| 462 |
+
```""")
|
| 463 |
|
| 464 |
run_button.click(
|
| 465 |
invert,
|
| 466 |
[image, max_iters, vqa_gate, dino_gate, fail_threshold, w_vqa, base_seed, ground],
|
| 467 |
+
[intro, results, status, best_prompt, report, gallery, iterations, predicates, graph_json, grounding],
|
| 468 |
)
|
| 469 |
|
| 470 |
if __name__ == "__main__":
|
| 471 |
+
demo.launch(theme=THEME, css=CSS)
|