oneryalcin's picture
Five classes: add plain text and images, re-captured pages
10d623c verified
Raw History Blame Contribute Delete
8.23 kB
"""Turn raw captures into a COCO dataset with five classes: icon, text control, input field, plain text, image.
Usage: uv run --with pillow --with numpy --with pyobjc-framework-Vision --with pyobjc-framework-Quartz python prep.py
- drops captures that are unstable, nearly empty, too dense for the detector's 300 queries, or mostly a foreign frame
- keeps a dark capture only when it really looks different from the light one
- paints cross-origin frames grey (their controls cannot be labelled) and drops labels inside them
- class: input by tag/role; otherwise text control if OCR reads a word inside the box, or the page says the element
has text and the pixels look like letters (textlike.py); else icon. Plain-text blocks are "text".
- icon against image is decided by look for controls and non-controls alike: 48 px or more on the short side and
many colours is an image, anything else an icon. Each label carries "control": true/false.
- splits by site, so no site appears in two splits
"""
import hashlib, json, re, shutil, sys
from collections import Counter
from pathlib import Path
from urllib.parse import urlparse
import numpy as np
from PIL import Image, ImageDraw
from textlike import shows_text
HERE = Path(__file__).parent
import os
RAW, OUT = HERE / "data" / os.environ.get("RAW", "raw"), HERE / "data" / os.environ.get("OUT", "coco")
VALID_BELOW = int(os.environ.get("VALID_BELOW", "20")) # sites hashing to 6..VALID_BELOW-1 go to validation
VARIANTS = set(os.environ.get("VARIANTS", "").split(",")) - {""} # e.g. top,scroll,dark for the first-pass images only
W, H = 1440, 900
CLASSES = ["icon", "text_control", "input", "text", "image"] # by look; each label also says whether it is a control
MAX_LABELS = 280 # the detector has 300 queries
INPUT_TYPES = {"", "text", "search", "email", "password", "number", "tel", "url", "date", "datetime-local", "time", "month", "week"}
INPUT_ROLES = {"textbox", "searchbox", "combobox", "spinbutton"}
def ocr_words(path):
import Quartz, Vision
from Foundation import NSURL
src = Quartz.CGImageSourceCreateWithURL(NSURL.fileURLWithPath_(str(path)), None)
img = Quartz.CGImageSourceCreateImageAtIndex(src, 0, None)
req = Vision.VNRecognizeTextRequest.alloc().init()
req.setRecognitionLevel_(Vision.VNRequestTextRecognitionLevelAccurate)
req.setUsesLanguageCorrection_(False)
Vision.VNImageRequestHandler.alloc().initWithCGImage_options_(img, None).performRequests_error_([req], None)
words = []
for o in req.results() or []:
c = o.topCandidates_(1)[0]
for m in re.finditer(r"\S+", str(c.string())):
ob, _ = c.boundingBoxForRange_error_((m.start(), m.end() - m.start()), None)
if ob is None:
continue
b = ob.boundingBox()
words.append((m.group(), ((b.origin.x + b.size.width / 2) * W, (1 - b.origin.y - b.size.height / 2) * H)))
return words
def klass(e, words, im):
if e["tag"] in ("textarea", "select") or (e["tag"] == "input" and e["type"] in INPUT_TYPES) or e["role"] in INPUT_ROLES:
return 2
r = e["rect"]
for text, (cx, cy) in words:
if r[0] - 2 <= cx <= r[2] + 2 and r[1] - 2 <= cy <= r[3] + 2 and len(re.sub(r"[^A-Za-z0-9]", "", text)) >= 2:
return 1
return 1 if shows_text(im, e) else 0 # OCR misses short and small words ("API", 11 px footer links)
def picture(im, r):
"""Photo-like rather than a pictogram: at least 48 px on the short side and many colours."""
if min(r[2] - r[0], r[3] - r[1]) < 48:
return False
a = np.asarray(im.crop(tuple(int(v) for v in r)).resize((32, 32))) >> 4
return len({tuple(p) for p in a.reshape(-1, 3)}) >= 40
def site(url):
host = urlparse(url).netloc.lower().removeprefix("www.")
parts = host.split(".")
return ".".join(parts[-3:] if parts[-2] in ("co", "com", "gov", "org", "ac") and len(parts[-1]) == 2 else parts[-2:])
def main():
skipped = Counter()
kept = []
tops = {}
for jf in sorted(RAW.glob("*.json")):
d = json.loads(jf.read_text())
png = RAW / f"{d['id']}.png"
if not png.exists():
continue
if VARIANTS and d["variant"] not in VARIANTS:
continue
if d["W"] != W or d["H"] != H:
skipped["wrong size"] += 1
continue
if not d["stable"]:
skipped["labels moved during capture"] += 1
continue
foreign = [f["rect"] for f in d["frames"] if f["kind"] == "cross-origin frame"]
if sum(max(0, min(r[2], W) - max(r[0], 0)) * max(0, min(r[3], H) - max(r[1], 0)) for r in foreign) > 0.35 * W * H:
skipped["mostly a foreign frame"] += 1
continue
els = [e for e in d["els"] if (e["rect"][2] - e["rect"][0]) * (e["rect"][3] - e["rect"][1]) <= 0.30 * W * H
and not any(f[0] <= (e["rect"][0] + e["rect"][2]) / 2 <= f[2] and f[1] <= (e["rect"][1] + e["rect"][3]) / 2 <= f[3] for f in foreign)]
if len(els) < 8:
skipped["fewer than 8 controls"] += 1
continue
inside_foreign = lambda r: any(f[0] <= (r[0] + r[2]) / 2 <= f[2] and f[1] <= (r[1] + r[3]) / 2 <= f[3] for f in foreign)
area = lambda r: (r[2] - r[0]) * (r[3] - r[1])
statics = [x for x in d.get("statics", []) if not inside_foreign(x["rect"]) and area(x["rect"]) <= (0.5 if x["kind"] == "text" else 0.6) * W * H]
if len(els) + len(statics) > MAX_LABELS:
skipped[f"more than {MAX_LABELS} labels"] += 1
continue
small = np.asarray(Image.open(png).convert("L").resize((144, 90)), dtype=np.int16)
uid = d["id"].rsplit("_", 1)[0]
if d["variant"] == "top":
tops[uid] = small
elif d["variant"] == "dark" and uid in tops and np.abs(small - tops[uid]).mean() < 12:
skipped["dark capture same as light"] += 1
continue
kept.append((d, png, els + statics, foreign))
print(f"kept {len(kept)} captures; skipped {dict(skipped)}")
sites = sorted({site(d["source_url"]) for d, *_ in kept})
def split_of(s):
h = int(hashlib.sha1(s.encode()).hexdigest(), 16) % 100
return "test" if h < 6 else "valid" if h < VALID_BELOW else "train"
if OUT.exists():
shutil.rmtree(OUT)
coco = {s: {"images": [], "annotations": [], "categories": [{"id": i, "name": n, "supercategory": "control"} for i, n in enumerate(CLASSES)]}
for s in ("train", "valid", "test")}
counts = {s: Counter() for s in coco}
for n, (d, png, els, foreign) in enumerate(kept):
s = split_of(site(d["source_url"]))
(OUT / s).mkdir(parents=True, exist_ok=True)
im = Image.open(png).convert("RGB")
if foreign:
dr = ImageDraw.Draw(im)
for r in foreign:
dr.rectangle(r, fill=(128, 128, 128))
name = f"{d['id']}.jpg"
im.save(OUT / s / name, quality=92)
words = ocr_words(png)
img_id = len(coco[s]["images"])
coco[s]["images"].append({"id": img_id, "file_name": name, "width": W, "height": H, "source_url": d["source_url"], "variant": d["variant"]})
for e in els:
r = e["rect"]
k = klass(e, words, im) if "kind" not in e else 3 if e["kind"] == "text" else 4
if k in (0, 4): # icon or image by look, whether or not it can be clicked
k = 4 if picture(im, r) else 0
counts[s][CLASSES[k]] += 1
coco[s]["annotations"].append({"id": len(coco[s]["annotations"]), "image_id": img_id, "category_id": k,
"control": "kind" not in e, "bbox": [r[0], r[1], r[2] - r[0], r[3] - r[1]], "area": (r[2] - r[0]) * (r[3] - r[1]), "iscrowd": 0})
if n % 100 == 0:
print(f" {n}/{len(kept)}", flush=True)
for s, c in coco.items():
(OUT / s / "_annotations.coco.json").write_text(json.dumps(c))
ns = len({site(i["source_url"]) for i in c["images"]})
print(f"{s:5s} images {len(c['images']):4d} | sites {ns:3d} | labels {len(c['annotations']):6d} {dict(counts[s])}")
if __name__ == "__main__":
main()