Spaces:
Running on Zero
Running on Zero
multimodalart HF Staff
Tighten GPU duration to measured 45s (warm 0.6s / cold 33s); pass theme+css to launch() per Gradio 6
55c8b34 verified Download app.py from hugging-apps/readpoint: direct link, hf CLI and curl.
- Browser
- Download file 8.93 kB
-
https://huggingface.co/spaces/hugging-apps/readpoint/resolve/main/app.py
- Command line
-
hf download hf://spaces/hugging-apps/readpoint/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hugging-apps/readpoint/resolve/main/app.py
8.93 kB
| import spaces # ZeroGPU: must be imported before torch | |
| import time | |
| import numpy as np | |
| import gradio as gr | |
| from PIL import Image, ImageDraw, ImageFont | |
| from fast_read import FastReader | |
| MODEL_CHOICES = ["naver-ai/ReadPoint-0.8B", "naver-ai/ReadPoint-2B"] | |
| DEFAULT_MODE = "Point + box + self-check" | |
| # ZeroGPU rule: the primary adapter loads eagerly at module scope so every cold worker inherits it. | |
| # The 2B variant is loaded on first use inside the GPU call (a cold worker pays the download+merge | |
| # once; warm workers keep it) — the duration estimator below grants time for exactly that case. | |
| READERS = {MODEL_CHOICES[0]: FastReader(MODEL_CHOICES[0])} | |
| def _get_reader(model_choice: str) -> FastReader: | |
| """Return the reader for the chosen adapter, loading the 2B on first use.""" | |
| if model_choice not in READERS: | |
| READERS[model_choice] = FastReader(model_choice) | |
| return READERS[model_choice] | |
| def _estimate_duration(*args, **kwargs): | |
| """Grant extra GPU time only when the chosen adapter still needs a cold download + merge.""" | |
| # read_point(image, target, model_choice, mode): the adapter is the 3rd positional arg, | |
| # or a keyword; examples only pass (image, target), which lands on the eagerly-loaded 0.8B. | |
| mc = kwargs.get("model_choice") or (args[2] if len(args) > 2 else MODEL_CHOICES[0]) | |
| # measured on the live Space: warm read 0.6s; cold worker (VRAM streaming + CUDA-graph | |
| # capture) 33s -> 45s covers it; a cold 2B adapter still pays a multi-GB download + merge. | |
| return 360 if mc not in READERS else 45 | |
| def _load_font(size: int): | |
| for name in ("DejaVuSans-Bold.ttf", "DejaVuSans.ttf"): | |
| try: | |
| return ImageFont.truetype(name, size) | |
| except OSError: | |
| continue | |
| return ImageFont.load_default() | |
| def draw_overlay(image: Image.Image, point, box=None, p_yes=None): | |
| """Annotate the image with the point marker (and box + self-check if read in full mode).""" | |
| W, H = image.size | |
| x, y = point | |
| px, py = x * W / 1000, y * H / 1000 | |
| canvas = image.copy() | |
| d = ImageDraw.Draw(canvas, "RGBA") | |
| if box is not None: | |
| x1, y1, x2, y2 = box | |
| d.rectangle( | |
| [x1 * W / 1000, y1 * H / 1000, x2 * W / 1000, y2 * H / 1000], | |
| outline=(255, 106, 0, 255), width=max(3, W // 240), | |
| ) | |
| r = max(6, W // 90) | |
| d.ellipse([px - r, py - r, px + r, py + r], fill=(255, 106, 0, 110), outline=(255, 106, 0, 255), width=max(2, W // 320)) | |
| d.line([px - 2 * r, py, px + 2 * r, py], fill=(255, 106, 0, 255), width=2) | |
| d.line([px, py - 2 * r, px, py + 2 * r], fill=(255, 106, 0, 255), width=2) | |
| return canvas | |
| def render_heatmap(dist_x: np.ndarray, dist_y: np.ndarray): | |
| """Render the joint probability map on the 1000x1000 grid the model reads over.""" | |
| grid = np.outer(dist_y, dist_x) # rows = y (000 top .. 999 bottom), cols = x | |
| grid = grid / grid.sum() | |
| # square-root scaling keeps small secondary modes visible; blur the peak slightly for a smooth map | |
| p = np.sqrt(grid) | |
| k = np.outer(np.hanning(61), np.hanning(61)); k /= k.sum() | |
| p = np.real(np.fft.ifft2(np.fft.fft2(p, s=(1061, 1061))) * np.fft.fft2(k, s=(1061, 1061)))[:1000, :1000] | |
| p = np.clip(p, 0, None) | |
| p = p / (p.max() + 1e-12) | |
| lo = np.array([24, 30, 66], dtype=np.float64) # dark navy | |
| hi = np.array([255, 138, 40], dtype=np.float64) # warm orange | |
| arr = np.zeros((1000, 1000, 3), dtype=np.uint8) | |
| for c in range(3): | |
| arr[..., c] = lo[c] + (hi[c] - lo[c]) * p | |
| argmy, argmx = np.unravel_index(grid.argmax(), grid.shape) | |
| d = ImageDraw.Draw(Image.fromarray(arr)) | |
| d.ellipse([argmx - 22, argmy - 22, argmx + 22, argmy + 22], outline=(255, 255, 255), width=4) | |
| d.ellipse([argmx - 34, argmy - 34, argmx + 34, argmy + 34], outline=(255, 255, 255, 90), width=2) | |
| f = _load_font(26) | |
| d.text((12, 8), "x: 000 to 999 (left to right)", fill=(200, 208, 226), font=f) | |
| d.text((12, 960), "y: 000 to 999 (top to bottom)", fill=(200, 208, 226), font=f) | |
| return Image.fromarray(arr) | |
| def read_point(image, target: str = "", model_choice: str = MODEL_CHOICES[0], mode: str = DEFAULT_MODE): | |
| """Point at a target in an image and read the probability of every point in one forward pass. | |
| Args: | |
| image: input image. | |
| target: what to point at, e.g. "the cat's left ear". | |
| model_choice: adapter to use, "naver-ai/ReadPoint-0.8B" or "naver-ai/ReadPoint-2B". | |
| mode: "Point only" or "Point + box + self-check". | |
| """ | |
| if image is None: | |
| raise gr.Error("Please provide an image.") | |
| if not target or not target.strip(): | |
| raise gr.Error("Please describe what to point at.") | |
| img = image if isinstance(image, Image.Image) else Image.open(image) | |
| img = img.convert("RGB") | |
| reader = _get_reader(model_choice if model_choice in MODEL_CHOICES else MODEL_CHOICES[0]) | |
| full = mode == "Point + box + self-check" | |
| t0 = time.perf_counter() | |
| res = reader.read(img, target, full=full) | |
| elapsed = time.perf_counter() - t0 | |
| x, y = res["point"] | |
| overlay = draw_overlay(img, res["point"], res.get("box"), res.get("p_yes")) | |
| heat = render_heatmap(res["dist"]["x"], res["dist"]["y"]) | |
| lines = [f"**Point** — x `{x:03d}`, y `{y:03d}` · ({x * img.size[0] / 1000:.0f}, {y * img.size[1] / 1000:.0f}) px in a {img.size[0]}×{img.size[1]} image"] | |
| if "box" in res: | |
| x1, y1, x2, y2 = res["box"] | |
| lines.append(f"**Box** — ({x1:03d}, {y1:03d}) → ({x2:03d}, {y2:03d}) /1000") | |
| if "p_yes" in res: | |
| verdict = "yes — precise at this resolution" if res["p_yes"] >= 0.5 else "no — not precise at this resolution" | |
| lines.append(f"**Self-check P(yes)** — `{res['p_yes']:.2f}` · the model says {verdict}") | |
| lines.append(f"**Read time** — {elapsed:.2f} s (single forward pass; exact distributions over 000–999 per axis, nothing sampled)") | |
| return overlay, heat, "\n\n".join(lines) | |
| CSS = """ | |
| #col-container { max-width: 1200px; margin: 0 auto; } | |
| .dark .gradio-container { color: var(--body-text-color); } | |
| """ | |
| with gr.Blocks() as demo: | |
| with gr.Column(elem_id="col-container"): | |
| gr.Markdown( | |
| """ | |
| # ReadPoint — fast self-checking pointing decision models | |
| Point a small VLM at a target and **one forward pass** reads the probability of *every* point (000–999 per axis) — | |
| no token-by-token writing — plus an optional bounding box and a self-check confidence. Adapters by NAVER Cloud AI | |
| ([paper](https://huggingface.co/papers/2611.38866) · [project page](https://naver-ai.github.io/ReadPoint/) · | |
| [0.8B](https://huggingface.co/naver-ai/ReadPoint-0.8B) · [2B](https://huggingface.co/naver-ai/ReadPoint-2B)). | |
| """ | |
| ) | |
| with gr.Row(): | |
| with gr.Column(): | |
| image_in = gr.Image(type="pil", label="Image", height=340) | |
| target = gr.Textbox( | |
| label="Point to…", placeholder="e.g. the cat's left ear", lines=1, value="" | |
| ) | |
| with gr.Accordion("Options", open=False): | |
| model_choice = gr.Radio( | |
| MODEL_CHOICES, value=MODEL_CHOICES[0], label="Adapter", info="0.8B is the fast variant; 2B is the accurate one." | |
| ) | |
| mode = gr.Radio( | |
| ["Point only", "Point + box + self-check"], | |
| value="Point + box + self-check", | |
| label="What to read", | |
| info="Everything is read in the same single forward pass.", | |
| ) | |
| run = gr.Button("Point", variant="primary") | |
| with gr.Column(): | |
| overlay_out = gr.Image(type="pil", label="Point (and box) overlay", height=340, show_label=True) | |
| heat_out = gr.Image(type="pil", label="Probability of every point (1000 × 1000 grid)", height=340) | |
| report = gr.Markdown() | |
| run.click(read_point, [image_in, target, model_choice, mode], [overlay_out, heat_out, report]) | |
| gr.Examples( | |
| examples=[ | |
| ["examples/cat_tabby.jpg", "the cat's left eye"], | |
| ["examples/red_fox.jpg", "the fox's face"], | |
| ["examples/living_room_blue_couch.jpg", "the wall-mounted TV"], | |
| ["examples/motorcycle_street.jpg", "the round headlight"], | |
| ["examples/rubber_ducks.jpg", "the smallest rubber duck"], | |
| ["examples/acoustic_guitar.jpg", "the sound hole"], | |
| ], | |
| inputs=[image_in, target], | |
| outputs=[overlay_out, heat_out, report], | |
| fn=read_point, | |
| cache_examples=True, | |
| cache_mode="lazy", | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True) | |