cursors / build_dataset.py
fgreenlee_sfemu
Reclassify visually misleading move cursors as grabbing
dfc7b50
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "Pillow>=10.0",
# "datasets>=2.14",
# "PyMuPDF>=1.23",
# "huggingface-hub>=0.19",
# "pyobjc-framework-Cocoa>=10.0",
# ]
# ///
"""Build and push the Fraser/cursors HuggingFace dataset.
Collects cursors from:
1. macOS system cursors (PDF + info.plist, plus NSCursor for arrow)
2. Linux Adwaita (xcursor-extracted PNGs with hotspot metadata)
3. Linux SVG-rendered themes (apple_cursor, bibata, google_cursor, notwaita, xcursor_pro)
4. Google pre-built cursors (GoogleDot 200px PNGs)
Deduplicates by (cursor_type, os, variant), keeping the largest size.
"""
import io
import plistlib
import re
import sys
from collections import defaultdict
from pathlib import Path
import fitz # PyMuPDF
from PIL import Image
CURSOR_DATASET = Path("cursor_dataset")
MACOS_CURSORS_DIR = Path(
"/System/Library/Frameworks/ApplicationServices.framework"
"/Versions/A/Frameworks/HIServices.framework"
"/Versions/A/Resources/cursors"
)
# ── Cursor-type mappings ─────────────────────────────────────────────────────
LINUX_NAME_TO_TYPE = {
"default": "arrow", "left_ptr": "arrow", "arrow": "arrow",
"top_left_arrow": "arrow",
"pointer": "pointer", "hand2": "pointer", "pointing_hand": "pointer",
"text": "text", "xterm": "text",
"vertical-text": "text_vertical", "vertical_text": "text_vertical",
"crosshair": "crosshair", "cross": "crosshair", "tcross": "crosshair",
"cross_reverse": "crosshair", "diamond_cross": "crosshair",
"move": "move", "fleur": "move", "dnd-move": "move",
"grab": "grab", "hand1": "grab", "openhand": "grab",
"grabbing": "grabbing", "closedhand": "grabbing",
"not-allowed": "not_allowed", "crossed_circle": "not_allowed",
"no-drop": "not_allowed", "dnd_no_drop": "not_allowed",
"dnd-no-drop": "not_allowed",
"help": "help", "question_arrow": "help",
"context-menu": "context_menu", "context_menu": "context_menu",
"cell": "cell", "plus": "cell",
"copy": "copy", "dnd-copy": "copy", "dnd_copy": "copy",
"alias": "alias", "dnd-link": "alias", "dnd_link": "alias", "link": "alias",
"wait": "wait", "watch": "wait",
"progress": "progress", "left_ptr_watch": "progress",
"n-resize": "resize_n", "top_side": "resize_n",
"s-resize": "resize_s", "bottom_side": "resize_s",
"e-resize": "resize_e", "right_side": "resize_e",
"w-resize": "resize_w", "left_side": "resize_w",
"ne-resize": "resize_ne", "top_right_corner": "resize_ne",
"nw-resize": "resize_nw", "top_left_corner": "resize_nw",
"se-resize": "resize_se", "bottom_right_corner": "resize_se",
"sw-resize": "resize_sw", "bottom_left_corner": "resize_sw",
"ew-resize": "resize_ew", "sb_h_double_arrow": "resize_ew",
"col-resize": "resize_ew",
"ns-resize": "resize_ns", "sb_v_double_arrow": "resize_ns",
"row-resize": "resize_ns",
"nesw-resize": "resize_nesw", "fd_double_arrow": "resize_nesw",
"nwse-resize": "resize_nwse", "bd_double_arrow": "resize_nwse",
"zoom-in": "zoom_in", "zoom_in": "zoom_in",
"zoom-out": "zoom_out", "zoom_out": "zoom_out",
"all-scroll": "all_scroll", "all_scroll": "all_scroll",
}
MACOS_NAME_TO_TYPE = {
"busybutclickable": "progress",
"cell": "cell",
"closedhand": "grabbing",
"contextualmenu": "context_menu",
"copy": "copy",
# countinguphand/countingdownhand/countingupandownhand are finger-counting
# animations, not the spinning wait cursor (beach ball is system-controlled)
"cross": "crosshair",
"help": "help",
"ibeamvertical": "text",
"ibeamhorizontal": "text_vertical",
"makealias": "alias",
"move": "move",
"notallowed": "not_allowed",
"openhand": "grab",
"pointinghand": "pointer",
"resizedown": "resize_s",
"resizeeast": "resize_e",
"resizeeastwest": "resize_ew",
"resizeleft": "resize_w",
"resizeleftright": "resize_ew",
"resizenorth": "resize_n",
"resizenortheast": "resize_ne",
"resizenortheastsouthwest": "resize_nesw",
"resizenorthsouth": "resize_ns",
"resizenorthwest": "resize_nw",
"resizenorthwestsoutheast": "resize_nwse",
"resizeright": "resize_e",
"resizesouth": "resize_s",
"resizesoutheast": "resize_se",
"resizesouthwest": "resize_sw",
"resizeup": "resize_n",
"resizeupdown": "resize_ns",
"resizewest": "resize_w",
"zoomin": "zoom_in",
"zoomout": "zoom_out",
}
DEFAULT_HOTSPOTS = {
"arrow": (0.10, 0.05), "pointer": (0.35, 0.06),
"text": (0.50, 0.50), "text_vertical": (0.50, 0.50),
"crosshair": (0.50, 0.50), "move": (0.50, 0.50),
"grab": (0.50, 0.33), "grabbing": (0.50, 0.33),
"not_allowed": (0.50, 0.50), "help": (0.10, 0.05),
"context_menu": (0.10, 0.05), "cell": (0.50, 0.50),
"copy": (0.10, 0.05), "alias": (0.10, 0.05),
"wait": (0.50, 0.50), "progress": (0.10, 0.05),
"zoom_in": (0.33, 0.33), "zoom_out": (0.33, 0.33),
"all_scroll": (0.50, 0.50),
}
THEME_TO_OS = {
"apple_cursor": "linux-apple-cursor",
"bibata": "linux-bibata",
"google_cursor": "linux-google-cursor",
"notwaita": "linux-notwaita",
"xcursor_pro": "linux-xcursor-pro",
}
# ── Helpers ───────────────────────────────────────────────────────────────────
def hotspot_for(cursor_type):
if cursor_type.startswith("resize_"):
return (0.50, 0.50)
return DEFAULT_HOTSPOTS.get(cursor_type, (0.50, 0.50))
def pad_to_square(img, hx, hy):
w, h = img.size
s = max(w, h)
if w == h:
return img, hx, hy, s
out = Image.new("RGBA", (s, s), (0, 0, 0, 0))
xo, yo = (s - w) // 2, (s - h) // 2
out.paste(img, (xo, yo))
return out, (hx * w + xo) / s, (hy * h + yo) / s, s
def resolve_linux_type(name):
for candidate in [name, name.replace("_", "-"), name.replace("-", "_")]:
t = LINUX_NAME_TO_TYPE.get(candidate)
if t is not None:
return t
return None
def parse_hotspot_file(path):
data = {}
for line in Path(path).read_text().strip().splitlines():
if "=" in line:
k, v = line.split("=", 1)
data[k.strip()] = v.strip()
return data
def split_frame_name(name):
"""'left_ptr_watch-01' → ('left_ptr_watch', 1); static names → (name, None)."""
m = re.match(r"^(.+)-(\d+)$", name)
return (m.group(1), int(m.group(2))) if m else (name, None)
def make_row(cursor_type, os_name, frames, delay_ms, hx, hy, size_px, variant):
return dict(
cursor_type=cursor_type, os=os_name, frames=frames,
frame_delay_ms=int(delay_ms), hotspot_x=float(hx),
hotspot_y=float(hy), size_px=int(size_px), variant=variant,
)
# ── macOS cursors ─────────────────────────────────────────────────────────────
def render_pdf_frames(pdf_path, num_frames, target_size):
doc = fitz.open(str(pdf_path))
page = doc[0]
native_w, native_h = page.rect.width, page.rect.height
frame_h = native_h / num_frames
scale = target_size / max(native_w, frame_h)
pix = page.get_pixmap(matrix=fitz.Matrix(scale, scale), alpha=True)
full = Image.frombytes("RGBA", [pix.width, pix.height], pix.samples)
doc.close()
rfh = pix.height / num_frames
frames = []
for i in range(num_frames):
y1, y2 = round(i * rfh), round((i + 1) * rfh)
frames.append(full.crop((0, y1, pix.width, y2)))
return frames, native_w, frame_h
def process_macos(target_size=96):
print("── macOS system cursors ──")
rows, seen = [], set()
for d in sorted(MACOS_CURSORS_DIR.iterdir()):
if not d.is_dir():
continue
ct = MACOS_NAME_TO_TYPE.get(d.name)
if not ct or ct in seen:
continue
plist_path = d / "info.plist"
pdf_path = d / "cursor.pdf"
if not plist_path.exists() or not pdf_path.exists():
continue
with open(plist_path, "rb") as f:
info = plistlib.load(f)
hotx, hoty = float(info.get("hotx", 0)), float(info.get("hoty", 0))
nf = int(info.get("frames", 1))
delay_s = float(info.get("delay", 0))
try:
frames, nw, nfh = render_pdf_frames(pdf_path, nf, target_size)
except Exception as e:
print(f" SKIP {d.name}: render failed ({e})")
continue
hx = hotx / nw if nw else 0.5
hy = hoty / nfh if nfh else 0.5
padded, fhx, fhy, fsz = [], hx, hy, target_size
for i, fr in enumerate(frames):
pf, nhx, nhy, sz = pad_to_square(fr, hx, hy)
padded.append(pf)
if i == 0:
fhx, fhy, fsz = nhx, nhy, sz
seen.add(ct)
rows.append(make_row(ct, "macos", padded, delay_s * 1000, fhx, fhy, fsz, "default"))
print(f" {d.name}{ct} ({len(padded)} frames, {fsz}px)")
# Arrow cursor via NSCursor (not on filesystem)
if "arrow" not in seen:
try:
from AppKit import NSApplication, NSCursor
NSApplication.sharedApplication()
cur = NSCursor.arrowCursor()
ns_img = cur.image()
hs = cur.hotSpot()
reps = ns_img.representations()
best = max(reps, key=lambda r: r.pixelsWide())
png_data = best.representationUsingType_properties_(4, None)
img = Image.open(io.BytesIO(png_data)).convert("RGBA")
pt_w, pt_h = ns_img.size().width, ns_img.size().height
hx = hs.x / pt_w
hy = hs.y / pt_h
scale = target_size / max(img.size)
img = img.resize(
(int(img.width * scale), int(img.height * scale)), Image.LANCZOS
)
img, hx, hy, sz = pad_to_square(img, hx, hy)
seen.add("arrow")
rows.append(make_row("arrow", "macos", [img], 0, hx, hy, sz, "default"))
print(f" NSCursor.arrow → arrow ({sz}px)")
except Exception as e:
print(f" WARNING: arrow cursor failed: {e}")
print(f" Total: {len(rows)} macOS cursors")
return rows
# ── Adwaita ───────────────────────────────────────────────────────────────────
def process_adwaita(target_size=96):
print("── Adwaita ──")
base = CURSOR_DATASET / "system_themes" / "adwaita"
if not base.exists():
print(" NOT FOUND"); return []
aliases = set()
af = base / "_aliases.txt"
if af.exists():
for line in af.read_text().strip().splitlines():
parts = line.split("->")
if len(parts) == 2:
aliases.add(parts[0].strip())
rows, seen = [], set()
for cd in sorted(base.iterdir()):
if not cd.is_dir() or cd.name.startswith("_") or cd.name in aliases:
continue
ct = resolve_linux_type(cd.name)
if not ct or ct in seen:
continue
sz_dir = cd / f"{target_size}px"
if not sz_dir.exists():
continue
frame_dirs = sorted(
[d for d in sz_dir.iterdir() if d.is_dir() and d.name.startswith("frame_")],
key=lambda d: d.name,
)
frames, delay_ms, hs_file = [], 0, sz_dir / "hotspot.txt"
if frame_dirs:
for fd in frame_dirs:
pngs = list(fd.glob("*.png"))
if pngs:
frames.append(Image.open(pngs[0]).convert("RGBA"))
if delay_ms == 0:
hf = fd / "hotspot.txt"
if hf.exists():
delay_ms = int(parse_hotspot_file(hf).get("delay", 0))
hs_file = frame_dirs[0] / "hotspot.txt"
else:
pngs = list(sz_dir.glob("*.png"))
if pngs:
frames.append(Image.open(pngs[0]).convert("RGBA"))
if not frames:
continue
hx, hy = hotspot_for(ct)
if hs_file.exists():
hsd = parse_hotspot_file(hs_file)
w = int(hsd.get("width", target_size))
h = int(hsd.get("height", target_size))
hx = int(hsd.get("xhot", 0)) / w if w else 0.5
hy = int(hsd.get("yhot", 0)) / h if h else 0.5
seen.add(ct)
sz = max(frames[0].size)
rows.append(make_row(ct, "linux-adwaita", frames, delay_ms, hx, hy, sz, "default"))
print(f" {cd.name}{ct} ({len(frames)} frames, {sz}px)")
print(f" Total: {len(rows)} Adwaita cursors")
return rows
# ── SVG-rendered themes ───────────────────────────────────────────────────────
def process_svg_theme(theme, variant, target_size=96):
base = CURSOR_DATASET / "rendered_from_svg" / f"{theme}_{variant}"
if not base.exists():
return []
groups = defaultdict(list)
for entry in base.iterdir():
if not entry.is_dir():
continue
m = re.match(r"^(.+)_(\d+)px$", entry.name)
if not m or int(m.group(2)) != target_size:
continue
cursor_name = m.group(1)
bname, fnum = split_frame_name(cursor_name)
groups[bname].append((fnum, entry, cursor_name))
rows, seen = [], set()
for bname, entries in sorted(groups.items()):
ct = resolve_linux_type(bname)
if not ct or ct in seen:
continue
has_numbered = any(fn is not None for fn, _, _ in entries)
if has_numbered:
entries = [(fn, p, cn) for fn, p, cn in entries if fn is not None]
entries.sort(key=lambda x: x[0])
animated = True
else:
animated = False
frames = []
for _, dir_path, _ in entries:
pngs = list(dir_path.glob("*.png"))
if pngs:
try:
frames.append(Image.open(pngs[0]).convert("RGBA"))
except Exception:
continue
if not frames:
continue
hx, hy = hotspot_for(ct)
seen.add(ct)
sz = max(frames[0].size)
os_name = THEME_TO_OS[theme]
rows.append(make_row(ct, os_name, frames, 33 if animated else 0, hx, hy, sz, variant))
return rows
def process_all_svg_themes():
print("── SVG-rendered themes ──")
rows = []
for theme in ["apple_cursor", "bibata", "google_cursor", "notwaita", "xcursor_pro"]:
for variant in ["black", "white"]:
batch = process_svg_theme(theme, variant)
if batch:
print(f" {theme}/{variant}: {len(batch)} cursors")
rows.extend(batch)
print(f" Total: {len(rows)} SVG-rendered cursors")
return rows
# ── Google pre-built ──────────────────────────────────────────────────────────
def process_google_prebuilt():
print("── Google pre-built ──")
all_rows = []
variants = [
("GoogleDot-Black", "black"), ("GoogleDot-Blue", "blue"),
("GoogleDot-Red", "red"), ("GoogleDot-White", "white"),
]
for vdir, vname in variants:
base = CURSOR_DATASET / "open_source_themes" / "google_cursor" / vdir
if not base.exists():
continue
groups = defaultdict(list)
for f in base.iterdir():
if f.suffix.lower() != ".png":
continue
bname, fnum = split_frame_name(f.stem)
groups[bname].append((fnum, f))
rows, seen = [], set()
for bname, entries in sorted(groups.items()):
ct = resolve_linux_type(bname)
if not ct or ct in seen:
continue
has_numbered = any(fn is not None for fn, _ in entries)
if has_numbered:
entries = [(fn, p) for fn, p in entries if fn is not None]
entries.sort(key=lambda x: x[0])
animated = True
else:
animated = False
frames = []
for _, fpath in entries:
try:
frames.append(Image.open(fpath).convert("RGBA"))
except Exception:
continue
if not frames:
continue
hx, hy = hotspot_for(ct)
seen.add(ct)
sz = max(frames[0].size)
rows.append(make_row(ct, "linux-google-cursor", frames,
33 if animated else 0, hx, hy, sz, vname))
print(f" {vdir}: {len(rows)} cursors")
all_rows.extend(rows)
print(f" Total: {len(all_rows)} Google pre-built cursors")
return all_rows
# ── Dedup & push ──────────────────────────────────────────────────────────────
def deduplicate(rows):
best = {}
for r in rows:
key = (r["cursor_type"], r["os"], r["variant"])
if key not in best or r["size_px"] > best[key]["size_px"]:
best[key] = r
return list(best.values())
# Themes whose X11 "move" cursor is a closed hand (visually identical to
# "grabbing") rather than the standard four-way arrow. Reclassify so the
# label matches the visual appearance for grounding tasks.
_MOVE_IS_GRABBING = {"linux-apple-cursor", "linux-xcursor-pro"}
def fix_visual_labels(rows):
existing = {(r["cursor_type"], r["os"], r["variant"]) for r in rows}
fixed = 0
for r in rows:
if (
r["cursor_type"] == "move"
and r["os"] in _MOVE_IS_GRABBING
and ("grabbing", r["os"], r["variant"]) not in existing
):
r["cursor_type"] = "grabbing"
r["hotspot_x"], r["hotspot_y"] = hotspot_for("grabbing")
existing.discard(("move", r["os"], r["variant"]))
existing.add(("grabbing", r["os"], r["variant"]))
fixed += 1
if fixed:
print(f" Reclassified {fixed} move → grabbing (hand-shaped move cursors)")
return rows
def build_and_push(rows):
from datasets import Dataset, Features, Sequence, Value
from datasets import Image as HFImage
data = {k: [] for k in [
"cursor_type", "os", "frames", "frame_delay_ms",
"hotspot_x", "hotspot_y", "size_px", "variant",
]}
for r in rows:
for k in data:
data[k].append(r[k])
features = Features({
"cursor_type": Value("string"),
"os": Value("string"),
"frames": Sequence(HFImage()),
"frame_delay_ms": Value("int32"),
"hotspot_x": Value("float32"),
"hotspot_y": Value("float32"),
"size_px": Value("int32"),
"variant": Value("string"),
})
ds = Dataset.from_dict(data, features=features)
print(f"\nDataset: {len(ds)} rows")
print(ds)
ds.push_to_hub("Fraser/cursors")
print("Pushed to Fraser/cursors")
# ── Main ──────────────────────────────────────────────────────────────────────
def main():
rows = []
rows.extend(process_macos())
rows.extend(process_adwaita())
rows.extend(process_all_svg_themes())
rows.extend(process_google_prebuilt())
print(f"\nBefore dedup: {len(rows)} rows")
rows = deduplicate(rows)
print(f"After dedup: {len(rows)} rows")
rows = fix_visual_labels(rows)
by_os = defaultdict(int)
for r in rows:
by_os[r["os"]] += 1
for k, v in sorted(by_os.items()):
print(f" {k}: {v}")
build_and_push(rows)
if __name__ == "__main__":
main()