Spaces:
Running on Zero
Running on Zero
File size: 8,925 Bytes
0a59602 22ea444 55c8b34 0a59602 22ea444 0a59602 22ea444 0a59602 55c8b34 0a59602 22ea444 0a59602 55c8b34 | 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 | 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)
@spaces.GPU(duration=_estimate_duration)
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)
|