File size: 14,640 Bytes
7c21061
 
 
 
 
 
 
 
 
 
5e40307
7c21061
 
 
5e40307
7c21061
 
5e40307
7c21061
8c5e6cc
 
 
 
 
 
 
7c21061
 
 
5e40307
 
 
 
 
 
 
 
f368e2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e40307
f368e2d
 
 
 
5e40307
f368e2d
5e40307
 
f368e2d
 
 
 
5e40307
f368e2d
5e40307
f368e2d
 
5e40307
 
 
 
 
 
 
 
f368e2d
5e40307
f368e2d
5e40307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f368e2d
5e40307
f368e2d
5e40307
 
 
 
 
 
 
 
 
 
 
 
 
be80524
521dbac
 
5e40307
 
f368e2d
5e40307
 
fad52c2
 
 
be80524
fad52c2
5e40307
f368e2d
5e40307
 
 
 
521dbac
5e40307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521dbac
cde89ae
 
7c21061
 
be80524
7c21061
 
 
 
 
 
 
 
5e40307
7c21061
5e40307
7c21061
 
 
5e40307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521dbac
5e40307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c21061
 
 
 
 
 
 
 
5e40307
 
7c21061
5e40307
 
7c21061
be80524
 
 
 
 
 
5e40307
7c21061
 
 
521dbac
 
7c21061
 
 
5e40307
 
 
 
7c21061
 
 
 
 
 
 
 
 
5e40307
521dbac
5e40307
7c21061
be80524
7c21061
5e40307
 
 
 
 
 
 
be80524
5e40307
be80524
521dbac
 
be80524
5e40307
 
be80524
521dbac
 
5e40307
7c21061
521dbac
7c21061
be80524
 
 
5e40307
 
 
 
be80524
521dbac
 
be80524
521dbac
be80524
5e40307
 
 
7c21061
 
5e40307
 
 
 
 
be80524
5e40307
7c21061
5e40307
7c21061
 
 
 
 
 
 
 
 
 
 
 
 
 
be80524
7c21061
 
 
 
 
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#!/usr/bin/env python3
"""
Gradio app for Trace Model inference visualization.

Takes an image, runs the trace model to predict trajectory points,
overlays the trace on the image, and displays the predicted coordinates.

Model: https://huggingface.co/mihirgrao/trace-model
"""

import base64
import os
import tempfile
import logging
from typing import List, Optional, Tuple

import gradio as gr
import requests

from trace_inference import (
    DEFAULT_MODEL_ID,
    build_prompt,
    preprocess_image_for_trace,
    run_inference,
)
from trajectory_viz import visualize_trajectory_on_image

logger = logging.getLogger(__name__)

# Global server state (eval server mode)
_server_state = {"server_url": None, "base_url": "http://localhost"}


def discover_available_models(
    base_url: str = "http://localhost",
    port_range: Tuple[int, int] = (8000, 8010),
) -> List[Tuple[str, str]]:
    """Discover trace eval servers by pinging /health. Returns [(server_url, model_name), ...].
    For ngrok or https URLs, uses the URL as-is. For localhost, scans ports."""
    base_url = base_url.strip().rstrip("/")
    urls_to_check: List[Tuple[str, str]] = []

    # Single URL mode: ngrok, https, or URL that already has a port
    if "ngrok" in base_url or base_url.startswith("https://"):
        urls_to_check = [(base_url, "Trace (ngrok/external)")]
    elif ":" in base_url.split("//")[-1].split("/")[0]:
        # Already has port (e.g. http://localhost:8000)
        urls_to_check = [(base_url, "Trace")]
    else:
        # Scan ports for localhost
        start_port, end_port = port_range
        for port in range(start_port, end_port + 1):
            urls_to_check.append((f"{base_url}:{port}", f"Trace @ port {port}"))

    available = []
    headers = {}
    if "ngrok" in base_url:
        headers["ngrok-skip-browser-warning"] = "true"
    for server_url, label in urls_to_check:
        try:
            r = requests.get(f"{server_url}/health", timeout=5.0, headers=headers)
            if r.status_code == 200:
                try:
                    info = requests.get(
                        f"{server_url}/model_info", timeout=5.0, headers=headers
                    ).json()
                    name = info.get("model_id", label)
                except Exception:
                    name = label
                available.append((server_url, name))
        except requests.exceptions.RequestException as e:
            logger.debug(f"Could not reach {server_url}/health: {e}")
            continue
    return available


def get_model_info_for_url(server_url: str) -> Optional[str]:
    """Get formatted model info for a trace eval server."""
    if not server_url:
        return None
    headers = {"ngrok-skip-browser-warning": "true"} if "ngrok" in server_url else {}
    try:
        r = requests.get(f"{server_url.rstrip('/')}/model_info", timeout=5.0, headers=headers)
        if r.status_code == 200:
            return format_trace_model_info(r.json())
    except Exception as e:
        logger.warning(f"Could not fetch model info: {e}")
    return None


def format_trace_model_info(info: dict) -> str:
    """Format trace model info as markdown."""
    lines = ["## Model Information\n"]
    lines.append(f"**Model ID:** `{info.get('model_id', 'Unknown')}`\n")
    if "model_class" in info:
        lines.append(f"**Model Class:** `{info.get('model_class')}`\n")
    if "total_parameters" in info:
        lines.append(f"**Parameters:** {info.get('total_parameters', 0):,}\n")
    if "error" in info:
        lines.append(f"**Error:** {info['error']}\n")
    return "".join(lines)


def check_server_health(server_url: str) -> Tuple[str, Optional[dict], Optional[str]]:
    """Check trace eval server health. Returns (status_msg, health_data, model_info_text)."""
    if not server_url:
        return "Please provide a server URL.", None, None
    headers = {"ngrok-skip-browser-warning": "true"} if "ngrok" in server_url else {}
    try:
        r = requests.get(f"{server_url.rstrip('/')}/health", timeout=5.0, headers=headers)
        r.raise_for_status()
        data = r.json()
        info = get_model_info_for_url(server_url)
        _server_state["server_url"] = server_url
        return f"Server connected: {data.get('status', 'ok')}", data, info
    except requests.exceptions.RequestException as e:
        return f"Error connecting to server: {str(e)}", None, None


def run_inference_via_server(
    image_path: str,
    instruction: str,
    server_url: str,
    is_oxe: bool = False,
) -> Tuple[str, Optional[str]]:
    """Run inference via trace eval server. Returns (prediction, overlay_path)."""
    with open(image_path, "rb") as f:
        image_b64 = base64.b64encode(f.read()).decode("utf-8")
    headers = {"ngrok-skip-browser-warning": "true"} if "ngrok" in server_url else {}
    r = requests.post(
        f"{server_url.rstrip('/')}/predict",
        json={
            "image_base64": image_b64,
            "instruction": instruction,
            "is_oxe": is_oxe,
        },
        timeout=120.0,
        headers=headers,
    )
    r.raise_for_status()
    data = r.json()
    if "error" in data:
        return data["error"], None
    prediction = data.get("prediction", "")
    trajectory = data.get("trajectory", [])

    overlay_path = None
    if trajectory and len(trajectory) >= 2:
        _, preprocessed_path = preprocess_image_for_trace(image_path)
        try:
            with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as f:
                overlay_path = f.name
            img_arr = visualize_trajectory_on_image(
                trajectory=trajectory,
                image_path=preprocessed_path,
                output_path=overlay_path,
                normalized=True,
            )
            if img_arr is None:
                visualize_trajectory_on_image(
                    trajectory=trajectory,
                    image_path=preprocessed_path,
                    output_path=overlay_path,
                    normalized=False,
                )
        finally:
            if os.path.exists(preprocessed_path):
                try:
                    os.unlink(preprocessed_path)
                except Exception:
                    pass
    return prediction, overlay_path


# --- Gradio UI ---
try:
    demo = gr.Blocks(title="Trace Model Visualizer")
except TypeError:
    demo = gr.Blocks(title="Trace Model Visualizer")

with demo:
    gr.Markdown(
        """
        # Trace Model Visualizer

        Upload an image and provide a natural language task instruction to predict the trajectory/trace using [mihirgrao/trace-model](https://huggingface.co/mihirgrao/trace-model).

        The model predicts coordinate points from your instruction; they are overlaid on the image (green β†’ red gradient) and listed below.
        """
    )

    server_url_state = gr.State(value=None)
    model_url_mapping_state = gr.State(value={})

    def discover_and_select_models(base_url: str):
        if not base_url:
            return (
                gr.update(choices=[], value=None),
                gr.update(value="Please provide a base URL", visible=True),
                gr.update(value="", visible=True),
                None,
                {},
            )
        _server_state["base_url"] = base_url
        models = discover_available_models(base_url, port_range=(8000, 8010))
        if not models:
            return (
                gr.update(choices=[], value=None),
                gr.update(
                    value="❌ No trace eval servers found on ports 8000-8010.",
                    visible=True,
                ),
                gr.update(value="", visible=True),
                None,
                {},
            )
        choices = []
        url_map = {}
        for url, name in models:
            choices.append(name)
            url_map[name] = url
        selected = choices[0] if choices else None
        selected_url = url_map.get(selected) if selected else None
        model_info_text = get_model_info_for_url(selected_url) if selected_url else ""
        status = f"βœ… Found {len(models)} server(s). Auto-selected first."
        _server_state["server_url"] = selected_url
        return (
            gr.update(choices=choices, value=selected),
            gr.update(value=status, visible=True),
            gr.update(value=model_info_text, visible=True),
            selected_url,
            url_map,
        )

    def on_model_selected(model_choice: str, url_mapping: dict):
        if not model_choice:
            return gr.update(value="No model selected", visible=True), gr.update(value="", visible=True), None
        server_url = url_mapping.get(model_choice) if url_mapping else None
        if not server_url:
            return (
                gr.update(value="Could not find server URL. Please rediscover.", visible=True),
                gr.update(value="", visible=True),
                None,
            )
        model_info_text = get_model_info_for_url(server_url) or ""
        status, _, _ = check_server_health(server_url)
        _server_state["server_url"] = server_url
        return gr.update(value=status, visible=True), gr.update(value=model_info_text, visible=True), server_url

    with gr.Sidebar():
        gr.Markdown("### πŸ”§ Model Configuration")

        base_url_input = gr.Textbox(
            label="Base Server URL",
            placeholder="http://localhost",
            value="http://localhost",
            interactive=True,
        )
        discover_btn = gr.Button("πŸ” Discover Eval Servers", variant="primary", size="lg")
        model_dropdown = gr.Dropdown(
            label="Select Eval Server",
            choices=[],
            value=None,
            interactive=True,
            info="Discover trace eval servers on ports 8000-8010",
        )
        server_status = gr.Markdown("Select an eval server below (auto-connects on selection)")
        gr.Markdown("---")
        gr.Markdown("### πŸ“‹ Model Information")
        model_info_display = gr.Markdown("")

        discover_btn.click(
            fn=discover_and_select_models,
            inputs=[base_url_input],
            outputs=[
                model_dropdown,
                server_status,
                model_info_display,
                server_url_state,
                model_url_mapping_state,
            ],
        )
        model_dropdown.change(
            fn=on_model_selected,
            inputs=[model_dropdown, model_url_mapping_state],
            outputs=[server_status, model_info_display, server_url_state],
        )

    with gr.Row():
        with gr.Column(scale=1):
            image_input = gr.Image(
                label="Upload Image",
                type="filepath",
                height=400,
            )
            instruction_input = gr.Textbox(
                label="Natural language instruction",
                placeholder="e.g. Pick up the red block and place it on the table. Stack the cube on top of the block.",
                value="",
                lines=4,
                info="Enter a task description in natural language. The model predicts the trace for this instruction.",
            )
            prompt_format = gr.Radio(
                choices=["LIBERO", "OXE"],
                value="LIBERO",
                label="Prompt Format",
                info="Switch between LIBERO and OXE training formats.",
            )
            gr.Markdown("### Local model (if no eval server selected)")
            model_id_input = gr.Textbox(
                label="Model ID",
                value=DEFAULT_MODEL_ID,
                info="Hugging Face model ID (auto-loads on first inference if no eval server selected)",
            )
            run_btn = gr.Button("Run Inference", variant="primary")

        with gr.Column(scale=1):
            prompt_display = gr.Markdown(
                f"**Prompt sent to model:**\n\n```\n{build_prompt('')}\n```",
                label="Model prompt",
            )
            overlay_output = gr.Image(
                label="Image with Trace Overlay",
                height=400,
            )
            prediction_output = gr.Textbox(
                label="Model Prediction (raw)",
                lines=6,
            )

    status_md = gr.Markdown(
        "Select an eval server from the sidebar (auto-connects), or run inference with local model."
    )

    def on_run_inference(image_path, instruction, model_id, server_url, prompt_mode):
        if image_path is None:
            return (
                "",
                "Please upload an image first.",
                None,
                "**Status:** Please upload an image.",
            )

        is_oxe = (prompt_mode == "OXE")
        if server_url:
            prompt = build_prompt(instruction, is_oxe=is_oxe)
            prompt_md = f"**Prompt sent to model:**\n\n```\n{prompt}\n```"
            pred, overlay_path = run_inference_via_server(
                image_path, instruction, server_url, is_oxe=is_oxe
            )
        else:
            prompt = build_prompt(instruction, is_oxe=is_oxe)
            prompt_md = f"**Prompt sent to model:**\n\n```\n{prompt}\n```"
            pred, overlay_path, _ = run_inference(image_path, prompt, model_id)

        status = "**Status:** Inference complete." if overlay_path else f"**Status:** {pred}"
        return prompt_md, pred, overlay_path, status

    def update_prompt_display(instruction: str, prompt_mode: str):
        is_oxe = (prompt_mode == "OXE")
        prompt = build_prompt(instruction, is_oxe=is_oxe)
        return f"**Prompt sent to model:**\n\n```\n{prompt}\n```"

    instruction_input.change(
        fn=update_prompt_display,
        inputs=[instruction_input, prompt_format],
        outputs=[prompt_display],
    )
    prompt_format.change(
        fn=update_prompt_display,
        inputs=[instruction_input, prompt_format],
        outputs=[prompt_display],
    )

    run_btn.click(
        fn=on_run_inference,
        inputs=[
            image_input,
            instruction_input,
            model_id_input,
            server_url_state,
            prompt_format,
        ],
        outputs=[
            prompt_display,
            prediction_output,
            overlay_output,
            status_md,
        ],
        api_name="run_inference",
    )


def main():
    """Launch the Gradio app."""
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        theme=gr.themes.Soft(),
    )


if __name__ == "__main__":
    main()