Spaces:
Running on Zero
Running on Zero
Download grounding_demo/console.py from FanLR/GroundingPI: direct link, hf CLI and curl.
- Browser
- Download file 7.36 kB
-
https://huggingface.co/spaces/FanLR/GroundingPI/resolve/main/grounding_demo/console.py
- Command line
-
hf download hf://spaces/FanLR/GroundingPI/grounding_demo/console.py
-
curl -L -o console.py https://huggingface.co/spaces/FanLR/GroundingPI/resolve/main/grounding_demo/console.py
7.36 kB
| """Presentation helpers; expected answers never enter model requests.""" | |
| from __future__ import annotations | |
| import html | |
| import json | |
| from collections import Counter | |
| from .render import PALETTE | |
| PREFIXES = { | |
| "grounding": "Locate all the instances that match the following categories: ", | |
| "dense": "Locate all the instances that match the following categories: ", | |
| "referring": "Locate the target referred to by the following description: ", | |
| "dense_point": "Point to: ", | |
| "refer_point": "Point to the target referred to by the following description: ", | |
| "referring_point_in_mask": "Point to the target referred to by the following description: ", | |
| "dense_point_in_mask": "Point to: ", | |
| "layout": "Detect all document layout elements that match the following categories: ", | |
| "gui": "Point to the UI element to click for the following instruction: ", | |
| } | |
| CATEGORY_ROUTES = {"grounding", "dense", "layout", "dense_point_in_mask"} | |
| # Presentation only: never alter the released model prompt or expected answer. | |
| TASK_HELP = { | |
| "grounding": [ | |
| "Open-Vocabulary Grounding", | |
| "Turn category names into visual primitives: what is present, and where it is.", | |
| "Separate categories with commas. Select a result to inspect its original pixels.", | |
| "car, person" | |
| ], | |
| "dense": [ | |
| "Grounding in Dense Scenes", | |
| "Explore object-level perception in crowded scenes, including small and overlapping instances.", | |
| "Enter object categories. Inspect overlapping predictions one instance at a time.", | |
| "person, chair" | |
| ], | |
| "referring": [ | |
| "Language, Grounded in Context", | |
| "Link descriptions of appearance, position, and relationships to a specific visual target.", | |
| "Describe appearance, position, or relationships in a complete phrase.", | |
| "The person standing beside the table" | |
| ], | |
| "dense_point": [ | |
| "Dense Object Pointing", | |
| "Represent multiple objects as localized points: a compact form of visual grounding.", | |
| "Describe the targets to locate. Points indicate positions, not object boundaries.", | |
| "All visible people" | |
| ], | |
| "referring_point_in_mask": [ | |
| "Point Inside a Referred Target", | |
| "Use a description to predict a point inside the target object.", | |
| "Describe the target. The output is an image-relative point inside the object.", | |
| "The person wearing a flotation device" | |
| ], | |
| "visual_prompt": [ | |
| "Grounding by Visual Example", | |
| "Use spatial exemplars to identify related instances through a shared grounding interface.", | |
| "Green INPUT boxes come from your prompt, not model predictions. Coordinates use the 0–999 range.", | |
| "Given reference boxes <|box_start|><100><100><200><200><|box_end|> ..." | |
| ], | |
| "ocr": [ | |
| "Reading with Spatial Context", | |
| "Bind recognized text to its image region, connecting what is read with where it appears.", | |
| "Use an OCR instruction. Select a transcription to inspect the original pixels.", | |
| "Read and locate the text in the image" | |
| ], | |
| "dense_point_in_mask": [ | |
| "Point Inside Multiple Targets", | |
| "Predict an interior point for each matching instance in a crowded scene.", | |
| "Separate categories with commas. Each prediction marks a point inside an instance.", | |
| "van, bus, truck, car, pedestrian" | |
| ], | |
| "gui": [ | |
| "Grounding Intent in Interfaces", | |
| "Map an interaction instruction to a visual target within an interface.", | |
| "Describe the element to select. The demo predicts a point; it does not execute clicks.", | |
| "Click the search button" | |
| ] | |
| } | |
| def task_help_html(route): | |
| title, description, hint, _ = TASK_HELP[route] | |
| return ( | |
| "<div class='task-guide'>" | |
| f"<strong>{html.escape(title)}</strong><p>{html.escape(description)}</p>" | |
| f"<small>{html.escape(hint)}</small></div>" | |
| ) | |
| def query_from_prompt(prompt: str, route: str) -> str: | |
| text = prompt.removeprefix("<image>").strip() | |
| prefix = PREFIXES.get(route, "") | |
| if prefix and text.startswith(prefix): | |
| text = text[len(prefix) :].removesuffix(".") | |
| if route in CATEGORY_ROUTES: | |
| text = text.replace("</c>", ", ") | |
| return text | |
| def compile_query(query: str, route: str) -> str: | |
| text = query.strip() | |
| if route in CATEGORY_ROUTES: | |
| text = "</c>".join( | |
| part.strip() for part in text.replace(",", ",").split(",") if part.strip() | |
| ) | |
| prefix = PREFIXES.get(route, "") | |
| return "<image>\n" + prefix + text + ("." if prefix else "") | |
| def metrics_html(route, state="Ready", count=0, elapsed=None, usage=None): | |
| rows = [ | |
| ("Status", state), | |
| ("Task", route), | |
| ("Model", "GroundingPI"), | |
| ("Detections", str(count)), | |
| ("Latency", f"{elapsed:.2f} s" if elapsed is not None else "—"), | |
| ("Output tokens", str((usage or {}).get("completion_tokens", "—"))), | |
| ] | |
| return ( | |
| "<dl class='metrics-list'>" | |
| + "".join(f"<div><dt>{html.escape(k)}</dt><dd>{html.escape(v)}</dd></div>" for k, v in rows) | |
| + "</dl>" | |
| ) | |
| def targets_html(items, pending=False, image_source=""): | |
| if not items: | |
| title = "Awaiting visual evidence" if pending else "Explore a visual target" | |
| hint = ( | |
| "Your image stays visible while the model processes the request." | |
| if pending | |
| else "Choose an example, run grounding, then select a category to inspect." | |
| ) | |
| return ( | |
| "<div class='empty-targets'><svg viewBox='0 0 40 40' width='40' height='40' " | |
| "fill='none' aria-hidden='true'><path d='M13 6H6v7M27 6h7v7M6 27v7h7M34 27v7h-7' " | |
| "stroke='currentColor' stroke-width='1.8' stroke-linecap='round'/>" | |
| "<circle cx='20' cy='20' r='5' stroke='currentColor' stroke-width='1.8'/></svg>" | |
| f"<b>{title}</b><small>{hint}</small></div>" | |
| ) | |
| counts = Counter(item["label"] for item in items) | |
| chips = "".join( | |
| "<button type='button' class='target-chip' aria-pressed='false' " | |
| f"aria-label='{html.escape(f'Inspect {label}, {count} target' + ('s' if count != 1 else ''), quote=True)}' " | |
| f"data-label='{html.escape(label, quote=True)}' " | |
| f"data-coordinates='{html.escape(json.dumps([item['coordinates'] for item in items if item['label'] == label]), quote=True)}'>" | |
| f"<i aria-hidden='true' style='--category-color:rgb{PALETTE[idx % len(PALETTE)]}'></i><span>{html.escape(label)}</span><b>{count}</b></button>" | |
| for idx, (label, count) in enumerate(counts.items()) | |
| ) | |
| caption = "Live model predictions · select a target or category to inspect" | |
| return ( | |
| (f"<img class='focus-source' hidden alt='' src='{html.escape(image_source, quote=True)}'>" if image_source else "") | |
| + f"<div class='targets-summary'><b>{len(items)}</b> {'target' if len(items) == 1 else 'targets'} <span>{len(counts)} {'category' if len(counts) == 1 else 'categories'}</span></div>" | |
| f"<div class='target-chips'>{chips}</div>" | |
| "<div class='focus-help'><span>Inspect individual instances</span>" | |
| "<button type='button' class='clear-focus' hidden>Show all</button></div>" | |
| f"<div class='targets-caption'>{caption}</div>" | |
| ) | |