Sync from GitHub via hub-sync
Browse filesFiles changed (5)
- README.md+24-14
- SKILL.mdAdded+162
- falcon-perception-bucket.py+62-19
- falcon-perception.py+143-56
- review-detections.pyAdded+330
4 unmodified lines56789101121 unmodified lines333435363738214 unmodified lines2532542552562572582592602612622632642652662672682692702712721 unmodified line27427527627727827928028128228328428511 unmodified lines2972982993003013023033043054 unmodified lines3103113123133143153163173183194 unmodified lines# Object Detection Dataset Scripts7 scripts to **create**, convert, validate, inspect, diff, and sample object detection datasets on the Hub. Supports 6 bbox formats — no setup required.Start from nothing: `falcon-perception.py` generates a first-pass detection dataset for any class you can name, zero-shot, with no labelling and no training. The other six then convert, check, and measure it.This repository is inspired by [panlabel](https://github.com/strickvl/panlabel)21 unmodified lines|--------|-------------|| `falcon-perception.py` | **Create** a detection dataset zero-shot from any image dataset — name a class, get boxes + masks (runs on Apple Silicon too) || `falcon-perception-bucket.py` | Same, reading images from an HF bucket, resumable across restarts || `convert-hf-dataset.py` | Convert between 6 bbox formats and push to Hub || `validate-hf-dataset.py` | Check annotations for errors (invalid bboxes, duplicates, bounds) || `stats-hf-dataset.py` | Compute statistics (counts, label histogram, area, co-occurrence) |214 unmodified lines```bash# 1. does the model do the thing? (your laptop — no GPU needed)uv run falcon-perception.py --image page.jpg --query illustration --preview# 2. does it work on YOUR data? (first rows of the real corpus)uv run falcon-perception.py --dataset biglam/british-library-book-images \--config plates --limit 3 --preview# 3. the whole corpus, on a GPUhf jobs uv run --flavor a10g-large --secrets HF_TOKEN falcon-perception.py -- \--dataset biglam/british-library-book-images --config plates \--id-col fname --query illustration --out you/plates-illustrations# 4. it is already in `yolo` format — the rest of this directory just worksuv run validate-hf-dataset.py you/plates-illustrations --bbox-format yolouv run stats-hf-dataset.py you/plates-illustrations --bbox-format yolo```Falcon emits boxes as normalised centre x,y + w,h, which *is* the `yolo` format above, so no conversion step is needed.1 unmodified line**The correction loop.** A zero-shot first pass is a starting point, not ground truth. Convert it for human review, correct it, then diff the two to find out how good the first pass actually was:```bashuv run convert-hf-dataset.py you/plates-illustrations you/for-review --from yolo --to label_studio# ... correct in Label Studio, push as you/corrected ...uv run diff-hf-datasets.py you/plates-illustrations you/corrected # IoU match = zero-shot accuracy```**Runs without a CUDA GPU.** Unlike most recipes in this repo, `falcon-perception.py` selects the MLX backend on Apple Silicon automatically. It is slower there (~6 s/img vs ~0.4 on an A10G), which is the right trade for step 1 and 2 above — checking your class name works before spending GPU hours.### Known limits11 unmodified lines`--out` takes a file path as readily as a repo id — no Hub push, nothing to clean up:```bashuv run falcon-perception.py --image page.jpg --query illustration --out results.jsonuv run falcon-perception.py --image "scans/*.jpg" --query illustration --out results.jsonluv run falcon-perception.py --image page.jpg --query illustration --json | jq '.[0].objects.bbox'```Anything ending `.json`, `.jsonl` or `.parquet` is written locally; anything else is treated as a Hub dataset repo id.4 unmodified lines```pythonfrom datasets import load_datasetload_dataset("parquet", data_files=["hf://buckets/you/bl-masks/part-000000.parquet", ...],split="train").push_to_hub("you/bl-masks")```### Output columns`objects.bbox` (`yolo`), `objects.category`, `objects.area`, `objects.rectangularity`, plus `image`, `image_id`, `width`, `height`, `n_instances`, and `masks_rle` (COCO RLE — segmentation rides along; the bbox scripts ignore it).4 unmodified lines56789101121 unmodified lines33343536373839214 unmodified lines2542552562572582592602612622632642652662672682692702712722732741 unmodified line27627727827928028128228328428528628711 unmodified lines2993003013023033043053063074 unmodified lines3123133143153163173183193203213223233243253263273283294 unmodified lines# Object Detection Dataset Scripts8 scripts to **create**, convert, review, validate, inspect, diff, and sample object detection datasets on the Hub. Supports 6 bbox formats — no setup required.Start from nothing: `falcon-perception.py` generates a first-pass detection dataset for any class you can name, zero-shot, with no labelling and no training. The other six then convert, check, and measure it.This repository is inspired by [panlabel](https://github.com/strickvl/panlabel)21 unmodified lines|--------|-------------|| `falcon-perception.py` | **Create** a detection dataset zero-shot from any image dataset — name a class, get boxes + masks (runs on Apple Silicon too) || `falcon-perception-bucket.py` | Same, reading images from an HF bucket, resumable across restarts || `review-detections.py` | **Review** a detection dataset in your browser — keyboard accept/reject per image or per box, acceptance + missed rates, pushes a `review` column || `convert-hf-dataset.py` | Convert between 6 bbox formats and push to Hub || `validate-hf-dataset.py` | Check annotations for errors (invalid bboxes, duplicates, bounds) || `stats-hf-dataset.py` | Compute statistics (counts, label histogram, area, co-occurrence) |214 unmodified lines```bash# 1. does the model do the thing? (your laptop — no GPU needed)uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py --image page.jpg --query illustration --preview# 2. does it work on YOUR data? (first rows of the real corpus)uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py --dataset biglam/british-library-book-images \--config plates --limit 3 --preview# 3. the whole corpus, on a GPUhf jobs uv run --flavor a10g-large --secrets HF_TOKEN \https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py \--dataset biglam/british-library-book-images --config plates \--id-col fname --query illustration --out you/plates-illustrations# 4. it is already in `yolo` format — the rest of this directory just worksuv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/validate-hf-dataset.py you/plates-illustrations --bbox-format yolouv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/stats-hf-dataset.py you/plates-illustrations --bbox-format yolo```Falcon emits boxes as normalised centre x,y + w,h, which *is* the `yolo` format above, so no conversion step is needed.1 unmodified line**The correction loop.** A zero-shot first pass is a starting point, not ground truth. Convert it for human review, correct it, then diff the two to find out how good the first pass actually was:```bashuv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/convert-hf-dataset.py you/plates-illustrations you/for-review --from yolo --to label_studio# ... correct in Label Studio, push as you/corrected ...uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/diff-hf-datasets.py you/plates-illustrations you/corrected # IoU match = zero-shot accuracy```**Runs without a CUDA GPU.** Unlike most recipes in this repo, `falcon-perception.py` selects the MLX backend on Apple Silicon automatically. It is slower there (about 6 s/img vs 0.4 on an A10G), which is the right trade for step 1 and 2 above — checking your class name works before spending GPU hours.### Known limits11 unmodified lines`--out` takes a file path as readily as a repo id — no Hub push, nothing to clean up:```bashuv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py --image page.jpg --query illustration --out results.jsonuv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py --image "scans/*.jpg" --query illustration --out results.jsonluv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py --image page.jpg --query illustration --json | jq '.[0].objects.bbox'```Anything ending `.json`, `.jsonl` or `.parquet` is written locally; anything else is treated as a Hub dataset repo id.4 unmodified lines```pythonfrom datasets import load_datasetload_dataset("parquet", data_files="hf://buckets/you/bl-masks/part-*.parquet",split="train").push_to_hub("you/bl-masks")```### Output columns`objects.bbox` (`yolo`), `objects.category`, `objects.area`, `objects.rectangularity`, plus `image`, `image_id` (int64 — COCO-style trainers require an integer id), `source_id` (the original key), `width`, `height`, `n_instances`, and `masks_rle` (COCO RLE — segmentation rides along; the bbox scripts ignore it).### Train on the outputConvert to COCO pixel boxes, then fine-tune a compact Apache-2.0 detector (D-FINE, RT-DETRv2 — not ultralytics/YOLO, which is AGPL). The [`SKILL.md`](SKILL.md) in this directory walks an agent (or you) through the whole loop — teacher labels → validate → convert → train → honest eval:```bashuv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/convert-hf-dataset.py you/plates-illustrations you/plates-coco --from yolo --to coco_xywh```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162---name: detection-bootstrapdescription: Bootstrap an object-detection dataset and a small trained detector from images that have NO labels — zero-shot label with Falcon-Perception, validate, convert, then fine-tune a compact Apache-licensed model, all on Hugging Face Jobs. Runs fully autonomously or with human review checkpoints. Use when you have an image collection and want a detector but no annotations exist.---
# Bootstrap a detector from unlabeled images
The loop: **zero-shot teacher labels → validate → convert → train a small student → evaluate → publish.**Every step is a self-contained UV script from[`uv-scripts/object-detection`](https://huggingface.co/datasets/uv-scripts/object-detection) on theHugging Face Hub, or a `hf jobs` command. `--help` works on every script.
## Check if a human in the loop
You can use the approach outlined in this skill with or without a human in the loop.
- **With a human in the loop** (better models): show them the step-1 previews — "is the teacher boxing the right things?" is the highest-value question, and its fix is the cheapest (a better query, about $2 to re-run the teacher). Then train on a small slice first (500–1k images, about $1) and show 20 rendered predictions before spending on the full corpus. If corrections are worth collecting at volume, run a review pass with `review-detections.py` (keyboard accept/reject in the browser, per image or per box; prints the quotable acceptance + missed rates and pushes a `review` column), fold corrections in and retrain (about $1). Diff the corrected set against the first pass (`diff-hf-datasets.py`) to measure how good the zero-shot pass actually was.- **Autonomously** (headless): don't pause for review — use the numeric proxies, and say **unreviewed** in the final report and model card.
## 1. Sense-check the class name before spending GPU money (free)
Falcon-Perception queries are **class names, not instructions** ("photograph" works; "the photographs,excluding captions" returns nothing), and **one class per run** (combined queries collapse — run perclass and merge on `image_id`). Model details: `hf models card tiiuae/Falcon-Perception`.
Check cheaply on 3 images before any full pass. The teacher (Falcon-Perception) is a **0.6B model,1.3 GB download** — it runs on a CUDA GPU (fast), Apple Silicon (MLX backend auto-selected, about 6 s/image),or plain CPU (slow, but fine for 3 images). Run the check wherever is practical for you:
```# locally, if your machine can:uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py \ --dataset <USER>/<IMAGES> --limit 3 --query photograph --preview
# or the same check as a small job (previews don't persist on Jobs — push a tiny dataset instead):hf jobs uv run --flavor t4-small --secrets HF_TOKEN \ https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py \ --dataset <USER>/<IMAGES> --limit 3 --query photograph --out <USER>/<NAME>-check --private```
Judge the result before scaling up:- **If you can view images**, look at the rendered previews (or the pushed check dataset) — are the right things boxed?- **If you can't**, compare instance counts across candidate queries (`stats-hf-dataset.py` below works on a pushed check dataset): near-zero instances/image means the class name is wrong for this material — try a synonym (`photograph` / `illustration` / `figure` / `cartoon`). Suspiciously many (more than about 10/image) usually means the query is matching layout blocks, not pictures.- **No vision at all?** A vision-capable subagent can judge the previews if you can spawn one; otherwise tell the user the check ran unviewed.
(Falcon-Perception has a custom architecture, so it can't be served as an OpenAI-compatible endpoint —iterate via the batch script. If you swap in a teacher that vLLM can serve, a temporary hot server onJobs is the faster way to iterate on queries: see[Serve Models on Jobs](https://huggingface.co/docs/hub/jobs-serving).)
## 2. Teacher pass on Jobs
```hf jobs uv run --flavor a10g-large --secrets HF_TOKEN --timeout 2h \ https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py \ --dataset <USER>/<IMAGES> --query photograph --out <USER>/<NAME>-photograph --private```
- Avoid `a10g-small` — the engine sizes itself from the GPU and ignores host RAM, so it gets OOM-killed. `hf jobs hardware` lists current options and prices.- One job per class (step 1's rule). Merge per-class outputs by concatenating the `objects` entries of rows with the same `image_id`.- Output schema: `objects.bbox` in **YOLO format** (normalized center x, y, w, h), `objects.category`, `objects.area`, `objects.rectangularity`, plus `image`, `image_id`, `width`, `height`.- There are **no confidence scores** (the model has none). `rectangularity` (mask area ÷ box area) is the triage proxy: values near 0 are usually junk, 0.785 is a circle, 1.0 a full rectangle.- Submit with `--detach` (returns the job id immediately), then block on completion with `hf jobs wait <id> [<id> ...] --timeout 2h` — it exits 0 only if every job succeeded, so it chains cleanly into the next step. `hf jobs logs <id>` / `hf jobs inspect <id>` for progress and errors.- A job can sit in SCHEDULING while the flavor queue drains — that is a queue, not a failure. **Don't resubmit**: a second copy racing to the same `--out` just doubles the bill. If you do switch (`hf jobs hardware` for alternatives), cancel the queued copy first (`hf jobs cancel <id>`).- For images in a [storage bucket](https://huggingface.co/docs/hub/storage-buckets) instead of a dataset, use `falcon-perception-bucket.py` from the same repo (resumable).
## 3. Validate the labels (free, local)
```uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/validate-hf-dataset.py \ <USER>/<NAME>-photograph --bbox-format yolouv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/stats-hf-dataset.py \ <USER>/<NAME>-photograph --bbox-format yolo```
Expect **VALID** with 0 out-of-bounds and 0 zero-area boxes. `W001` warnings on empty images are normal —they are true negatives (pages with no instance), and they are useful training signal; keep them.Drop obvious junk before training: degenerate slivers (extreme aspect ratio + tiny area) and near-duplicateboxes (IoU > 0.9 within one image).
## 4. Convert YOLO → COCO for training (free, local)
Trainers expect COCO `xywh` pixels; the teacher emits YOLO normalized. One command:
```uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/convert-hf-dataset.py \ <USER>/<NAME>-photograph <USER>/<NAME>-coco --from yolo --to coco_xywh```
## 5. Train a small detector
Good starting points: [D-FINE](https://huggingface.co/ustc-community/dfine-small-coco) or[RT-DETRv2](https://huggingface.co/PekingU/rtdetr_v2_r18vd) — compact, Apache-2.0, in `transformers`(boxes only; for masks see the RF-DETR note below). Check the license fits the use —`hf models card <id>` shows it; flag restrictive licenses (e.g. ultralytics/YOLO is AGPL) to the userrather than deciding for them. Explore further:[transformers object-detection models](https://huggingface.co/models?pipeline_tag=object-detection&library=transformers&sort=trending) ·[ultralytics-library models](https://huggingface.co/models?library=ultralytics).
The **`huggingface-vision-trainer`** skill covers the training end to end (dataset validation,augmentation, mAP eval, Hub persistence) — install it with `hf skills add huggingface-vision-trainer`if you don't have it, and follow its object-detection path with the `<USER>/<NAME>-coco` dataset fromstep 4. Before training, decide a pragmatic validation split and never train on it.
Other trainers work too — the dataset is plain COCO. [RF-DETR](https://github.com/roboflow/rf-detr)(Apache-2.0, DINOv2 backbone) is a good starter, and its Seg variant can learn from the teacher's`masks_rle` masks. Decode them like this — each RLE lives in its own frame, which never matches therecorded width/height:
```pythonimport json, numpy as npfrom PIL import Imagefrom pycocotools import mask as mask_utils
for rle in json.loads(row["masks_rle"]): seg = mask_utils.decode({**rle, "counts": rle["counts"].encode()}) # frame = rle["size"] if seg.shape != (row["height"], row["width"]): seg = np.asarray(Image.fromarray(seg).resize((row["width"], row["height"]), Image.NEAREST))```
## 6. Evaluate honestly
- Report mAP on the held-out slice. Be clear about what it measures: **agreement with the teacher**, not accuracy against human truth — no human labels exist in this loop.- The student can at best match its teacher (measured on a comparable loop: student 97.4% vs teacher 95.0% human-acceptable on the same sample). The point of distilling is **throughput and cost** (10–100× cheaper per image than the teacher), not accuracy gains.- Spot-check 20 or so predictions visually before calling it done — or, if running without a human and you cannot view images, state prominently in the report that the model is **unreviewed**.- It can make sense to run this process in a loop: predict → review (a human, or a vision-capable agent, via `review-detections.py`) → retrain on the corrections → review again, until the acceptance rate stops improving.
## 7. Publish with honest provenance
Push the model and dataset — ask the user whether public or private; if you can't ask, default toprivate and say so. The cards must state: labels are **zero-shot weak labels** from Falcon-Perception(name the script + date), which filters ran, and that **recall is unmeasured** unless you measured itagainst an independent source. Say what the model is for and what it was trained on. A model trainedthis way is a first pass. The review loop above is how it gets better.10 unmodified lines11121314151617187 unmodified lines26272829303132333412 unmodified lines4748495051523 unmodified lines56575859606162636465666746 unmodified lines11411511611711811912012110 unmodified lines13213313413513613713827 unmodified lines1661671681691701711721731741751761771781791801811822 unmodified lines1851861871881891901911921931941951961971985 unmodified lines20420520620720820921021121221321421521621721821922022122222322422522622722822923010 unmodified lines# ///"""Falcon-Perception over a whole HF bucket, resumable.hf jobs uv run --flavor a10g-large --secrets HF_TOKEN falcon-bucket.py -- \--src biglam/bl-images --include 'full/embellishments/**/*.jpg' \--out davanstrien/bl-masks --query illustrationInput : bucketbag batched_files — bounded scratch, files deleted as the loop advances7 unmodified linesTo hand the result to the rest of this directory, publish it once at the end:from datasets import load_datasetload_dataset("parquet", data_files=["hf://buckets/you/bl-masks/part-000000.parquet", ...], split="train").push_to_hub("you/bl-masks")uv run validate-hf-dataset.py you/bl-masks --bbox-format yolo12 unmodified lines"""import argparseimport ioimport jsonimport time3 unmodified linesfrom bucketbag import batched_files, boost, completed_keys, iter_keys, put_filesfrom pycocotools import mask as mask_utils# Same YOLO column layout as falcon-perception.py, so both outputs validate with# `validate-hf-dataset.py --bbox-format yolo` and can be concatenated.# `__source_key` is bucketbag's resume column — the name is load-bearing.SCHEMA = pa.schema([("__source_key", pa.string()),("image_id", pa.string()),("width", pa.int32()),("height", pa.int32()),("objects", pa.struct([46 unmodified linesp.add_argument("--no-resume", action="store_true")args = p.parse_args()boost() # raise xet small-file concurrency — the whole point on many small objectsdone = set() if args.no_resume else completed_keys(args.out)print(f"{len(done)} keys already done", flush=True)10 unmodified linesif not keys:returnimport torch # noqa: F401from falcon_perception import PERCEPTION_MODEL_ID, build_prompt_for_task, load_and_prepare_model, setup_torch_configfrom falcon_perception.data import ImageProcessorfrom falcon_perception.paged_inference import (27 unmodified linesfor it in batch:try:img = it.image.convert("RGB") # convert() forces the load off diskif max(img.size) > args.max_dim * 2:img.thumbnail((args.max_dim * 2, args.max_dim * 2))pairs.append((str(it.key), img))except Exception as e:pairs.append((str(it.key), e))good = [(k, im) for k, im in pairs if not isinstance(im, Exception)]seqs = [Sequence(text=prompt, image=im, min_image_size=256,max_image_size=args.max_dim, request_idx=i, task=args.task)for i, (_, im) in enumerate(good)]t0 = time.perf_counter()if seqs:2 unmodified linesgen_total += dtrows = []for (key, im), seq in zip(good, seqs):aux = seq.output_auxboxes = pair_bboxes(aux.bboxes_raw)masks = list(aux.masks_rle)for m in masks:if isinstance(m.get("counts"), bytes):m["counts"] = m["counts"].decode()W, H = im.sizebbox, area, rect = [], [], []for i, b in enumerate(boxes):bbox.append([b["x"], b["y"], b["w"], b["h"]]) # yolo: cx, cy, w, h normalised5 unmodified linesm = masks[i]if isinstance(m.get("counts"), str):m = {**m, "counts": m["counts"].encode()}r = min(float(mask_utils.area(m)) / max(a * W * H, 1.0), 1.0)except Exception:r = 0.0rect.append(r)rows.append({"__source_key": key, "image_id": key, "width": W, "height": H,"objects": {"bbox": bbox, "category": [0] * len(bbox),"area": area, "rectangularity": rect},"n_instances": len(bbox), "masks_rle": json.dumps(masks),"query": args.query, "gen_seconds": dt / max(len(seqs), 1), "error": None,})for key, err in [(k, v) for k, v in pairs if isinstance(v, Exception)]:# a durable error row, never a gap — and it counts as done so it is# not retried forever on every re-runrows.append({k: None for k in SCHEMA.names} | {"__source_key": key, "image_id": key, "query": args.query,"error": f"{type(err).__name__}: {err}",})ext = "jsonl" if args.format == "jsonl" else "parquet"put_files([(f"part-{batch_i:06d}.{ext}", serialise(rows, args.format))], args.out)n += len(rows); batch_i += 1rate = n / (time.perf_counter() - t_all)print(f"batch {batch_i}: {len(rows)} rows ({dt / max(len(seqs), 1):.2f}s/img) "10 unmodified lines1112131415161718197 unmodified lines272829303132333412 unmodified lines474849505152533 unmodified lines57585960616263646566676869707172737446 unmodified lines12112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015110 unmodified lines16216316416516616727 unmodified lines1951961971981992002012022032042052062072082092102112122 unmodified lines2152162172182192202212222232242252262272282292305 unmodified lines23623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227310 unmodified lines# ///"""Falcon-Perception over a whole HF bucket, resumable.hf jobs uv run --flavor a10g-large --secrets HF_TOKEN \https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception-bucket.py \--src biglam/bl-images --prefix full/embellishments \--out davanstrien/bl-masks --query illustrationInput : bucketbag batched_files — bounded scratch, files deleted as the loop advances7 unmodified linesTo hand the result to the rest of this directory, publish it once at the end:from datasets import load_datasetload_dataset("parquet", data_files="hf://buckets/you/bl-masks/part-*.parquet",split="train").push_to_hub("you/bl-masks")uv run validate-hf-dataset.py you/bl-masks --bbox-format yolo12 unmodified lines"""import argparseimport hashlibimport ioimport jsonimport time3 unmodified linesfrom bucketbag import batched_files, boost, completed_keys, iter_keys, put_filesfrom pycocotools import mask as mask_utilsdef stable_id(key):"""Deterministic int64 image_id from the source key (COCO consumers need an int;a hash, not a running index, keeps ids identical across resumed runs)."""return int.from_bytes(hashlib.blake2b(str(key).encode(), digest_size=8).digest(), "big") >> 1# Same YOLO column layout as falcon-perception.py, so both outputs validate with# `validate-hf-dataset.py --bbox-format yolo` and can be concatenated.# `__source_key` is bucketbag's resume column — the name is load-bearing.SCHEMA = pa.schema([("__source_key", pa.string()),("image_id", pa.int64()), # int, not str: COCO-style trainers tensorise it("width", pa.int32()),("height", pa.int32()),("objects", pa.struct([46 unmodified linesp.add_argument("--no-resume", action="store_true")args = p.parse_args()if args.format == "jsonl" and not args.no_resume:# completed_keys only reads the done-set back from .parquet parts, so jsonl# output silently reprocesses EVERYTHING on every re-run.raise SystemExit("--format jsonl is not resumable; pass --no-resume to run it anyway.")try:import torchhas_cuda = torch.cuda.is_available()except ImportError: # falcon-perception pins torch off-darwin, so it may be absenthas_cuda = Falseif not has_cuda:raise SystemExit("This script needs a CUDA GPU (PagedInferenceEngine). ""For MLX/CPU-capable runs use falcon-perception.py instead.")boost() # raise xet small-file concurrency — the whole point on many small objectsfrom huggingface_hub import HfApi# first run: the out bucket may not exist yet — completed_keys 404s on a# missing bucket, killing the job before anything happensHfApi().create_bucket(args.out, private=True, exist_ok=True)done = set() if args.no_resume else completed_keys(args.out)print(f"{len(done)} keys already done", flush=True)10 unmodified linesif not keys:returnfrom falcon_perception import PERCEPTION_MODEL_ID, build_prompt_for_task, load_and_prepare_model, setup_torch_configfrom falcon_perception.data import ImageProcessorfrom falcon_perception.paged_inference import (27 unmodified linesfor it in batch:try:img = it.image.convert("RGB") # convert() forces the load off diskorig_size = img.size # SOURCE dims -- the images downstream tools decodeif max(img.size) > args.max_dim * 2:img.thumbnail((args.max_dim * 2, args.max_dim * 2))pairs.append((str(it.key), img, orig_size))except Exception as e:pairs.append((str(it.key), e, None))good = [(k, im, sz) for k, im, sz in pairs if not isinstance(im, Exception)]seqs = [Sequence(text=prompt, image=im, min_image_size=256,max_image_size=args.max_dim, request_idx=i, task=args.task)for i, (_, im, _) in enumerate(good)]t0 = time.perf_counter()if seqs:2 unmodified linesgen_total += dtrows = []for (key, im, orig_size), seq in zip(good, seqs):aux = seq.output_auxboxes = pair_bboxes(aux.bboxes_raw)masks = list(aux.masks_rle)for m in masks:if isinstance(m.get("counts"), bytes):m["counts"] = m["counts"].decode()# width/height are the SOURCE image's dims: boxes are normalised (frame-free),# and downstream pixel conversions run against the untouched bucket images.W, H = orig_sizebbox, area, rect = [], [], []for i, b in enumerate(boxes):bbox.append([b["x"], b["y"], b["w"], b["h"]]) # yolo: cx, cy, w, h normalised5 unmodified linesm = masks[i]if isinstance(m.get("counts"), str):m = {**m, "counts": m["counts"].encode()}# box area measured in the MASK's own frame (rle size) — mixing# frames skews rmh, mw = (m.get("size") or [H, W])[:2]r = min(float(mask_utils.area(m)) / max(a * mw * mh, 1.0), 1.0)except Exception:r = 0.0rect.append(r)rows.append({"__source_key": key, "image_id": stable_id(key), "width": W, "height": H,"objects": {"bbox": bbox, "category": [0] * len(bbox),"area": area, "rectangularity": rect},"n_instances": len(bbox), "masks_rle": json.dumps(masks),"query": args.query, "gen_seconds": dt / max(len(seqs), 1), "error": None,})for key, err, _ in [(k, v, s) for k, v, s in pairs if isinstance(v, Exception)]:# a durable error row, never a gap — and it counts as done so it is# not retried forever on every re-run. objects is EMPTY, not null:# a null struct crashes validate-hf-dataset.py after publish.rows.append({k: None for k in SCHEMA.names} | {"__source_key": key, "image_id": stable_id(key), "query": args.query,"objects": {"bbox": [], "category": [], "area": [], "rectangularity": []},"n_instances": 0, "masks_rle": "[]","error": f"{type(err).__name__}: {err}",})# part name derives from batch CONTENT, not a run-local counter: a resumed run's# counter restarts at 0 and put_files overwrites, silently destroying the first# run's parts. A content-derived name is stable per batch and collision-free# across resumes (a re-run of the same batch overwrites its own part, idempotent).ext = "jsonl" if args.format == "jsonl" else "parquet"part = hashlib.blake2b(rows[0]["__source_key"].encode(), digest_size=6).hexdigest()put_files([(f"part-{part}.{ext}", serialise(rows, args.format))], args.out)n += len(rows); batch_i += 1rate = n / (time.perf_counter() - t_all)print(f"batch {batch_i}: {len(rows)} rows ({dt / max(len(seqs), 1):.2f}s/img) "
32 unmodified lines3334353637383930 unmodified lines7071727374753 unmodified lines798081828384127 unmodified lines212213214215216217130 unmodified lines3483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793801 unmodified line3823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184191 unmodified line42142242342442542642742832 unmodified lines--config plates --limit 3 --preview# 3. the whole corpus, on a GPUhf jobs uv run --flavor a10g-large --secrets HF_TOKEN falcon-perception.py -- \--dataset biglam/british-library-book-images --config plates \--id-col fname --query illustration --out you/plates-illustrations30 unmodified linesimport argparseimport glob as globlibimport ioimport itertoolsimport json3 unmodified linesimport sysimport time# ── backend / engine selection ──────────────────────────────────────────────# The MLX and torch APIs match parameter-for-parameter, but are NOT drop-in:# torch also needs setup_torch_config(), a compile= kwarg, and every batch tensor127 unmodified linesyield buf# ── the two generation paths ────────────────────────────────────────────────130 unmodified linesgen = (run_paged(model, tokenizer, items, prompt, args) if use_pagedelse run_batch(model, tokenizer, items, prompt, args, backend, model_args.max_seq_len))records, n, t0 = [], 0, time.perf_counter()for key, im, aux, dt in gen:W, H = im.sizeboxes = pair_bboxes(aux.bboxes_raw)rles = list(aux.masks_rle)bbox, area, rect = [], [], []for i, b in enumerate(boxes):bbox.append([b["x"], b["y"], b["w"], b["h"]]) # yolo: cx, cy, w, h normaliseda = b["w"] * b["h"]area.append(a)r = 0.0if i < len(rles): # rectangularity -- the only triage signal availabletry:m = rles[i]if isinstance(m.get("counts"), str):m = {**m, "counts": m["counts"].encode()}r = min(float(mask_utils.area(m)) / max(a * W * H, 1.0), 1.0)except Exception:r = 0.0rect.append(r)n += 1print(f"[{n}] {key[:55]:55s} {len(bbox):2d} inst {dt:.2f}s", flush=True)if args.preview:print(f" -> {save_preview(key, im, boxes, rles, args.preview_dir)}", flush=True)if args.out or args.json:records.append({"image": im, "image_id": key, "width": W, "height": H,"objects": {"bbox": bbox, "category": [0] * len(bbox),"area": area, "rectangularity": rect},"n_instances": len(bbox),1 unmodified line{**m, "counts": m["counts"].decode() if isinstance(m.get("counts"), bytes) else m.get("counts")}for m in rles]),})wall = time.perf_counter() - t0print(f"\n{n} images in {wall:.1f}s ({n / max(wall, 1e-9):.2f} img/s)", flush=True)# --- local file output: everything except the PIL image, which is not serialisabledef plain(recs):return [{k: v for k, v in r.items() if k != "image"} for r in recs]if args.json:print(json.dumps(plain(records), indent=2), flush=True)if args.out and args.out.endswith((".json", ".jsonl", ".parquet")):rows = plain(records)if args.out.endswith(".json"):pathlib.Path(args.out).write_text(json.dumps(rows, indent=2))elif args.out.endswith(".jsonl"):pathlib.Path(args.out).write_text("".join(json.dumps(r) + "\n" for r in rows))else:import pyarrow as paimport pyarrow.parquet as pqpq.write_table(pa.Table.from_pylist(rows), args.out, compression="zstd")total = sum(r["n_instances"] for r in rows)print(f"{total} instances -> {args.out}", flush=True)returnif args.out:from datasets import Dataset, Features, Image as ImageFeat, Sequence as SeqFeat, Valuefeats = Features({"image": ImageFeat(), "image_id": Value("string"),"width": Value("int32"), "height": Value("int32"),"objects": {"bbox": SeqFeat(SeqFeat(Value("float32"))),"category": SeqFeat(Value("int64")),1 unmodified line"rectangularity": SeqFeat(Value("float32"))},"n_instances": Value("int32"), "masks_rle": Value("string"),})Dataset.from_list(records, features=feats).push_to_hub(args.out, private=args.private)print(f"{sum(r['n_instances'] for r in records)} instances -> {args.out}", flush=True)print(f"\nNEXT: validate-hf-dataset.py {args.out} --bbox-format yolo", flush=True)32 unmodified lines333435363738394030 unmodified lines717273747576773 unmodified lines8182838485868788899091929394959697127 unmodified lines225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274130 unmodified lines4054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474481 unmodified line4504514524534544554564574584594604614624634644654664674684694701 unmodified line47247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451532 unmodified lines--config plates --limit 3 --preview# 3. the whole corpus, on a GPUhf jobs uv run --flavor a10g-large --secrets HF_TOKEN \https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py \--dataset biglam/british-library-book-images --config plates \--id-col fname --query illustration --out you/plates-illustrations30 unmodified linesimport argparseimport glob as globlibimport hashlibimport ioimport itertoolsimport json3 unmodified linesimport sysimport timedef stable_id(key):"""Deterministic int64 image_id from the source key.COCO-style consumers (transformers RT-DETR / D-FINE annotation prep) require anINTEGER image_id -- a string crashes them with "ValueError: too many dimensions'str'". A content hash (not a running index) keeps ids identical across separateruns over the same source, so per-class runs merge on image_id cleanly."""return int.from_bytes(hashlib.blake2b(str(key).encode(), digest_size=8).digest(), "big") >> 1# ── backend / engine selection ──────────────────────────────────────────────# The MLX and torch APIs match parameter-for-parameter, but are NOT drop-in:# torch also needs setup_torch_config(), a compile= kwarg, and every batch tensor127 unmodified linesyield bufSCRIPT_URL = "https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py"def push_card(repo_id, query, counters):"""Dataset card with the repo's canonical provenance stamp (see AGENTS.md)."""from huggingface_hub import DatasetCardon_jobs = os.environ.get("JOB_ID") is not None # set by HF Jobs in-containerhw = os.environ.get("ACCELERATOR") or "" # e.g. "a10g-large"; empty on CPUorigin = (f"Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"+ (f" (`{hw}`)" if hw else "")) if on_jobs else "Generated"tags = "\n".join(f"- {t}" for t in (["uv-script", "hf-jobs"] if on_jobs else ["uv-script"]))args_summary = " ".join(sys.argv[1:])card = DatasetCard(f"""---tags:{tags}---# Zero-shot detection: `{query}`{counters["images"]} images, {counters["instances"]} instances. Labels are **zero-shot weaklabels** from [Falcon-Perception](https://huggingface.co/tiiuae/Falcon-Perception) -- no humanannotated anything, and recall against human truth is unmeasured. `objects.bbox` is `yolo`format (normalised centre x, y, w, h); `objects.rectangularity` (mask area / box area) is thetriage proxy -- the model emits no confidence scores.## Reproduction{origin} with the [`falcon-perception.py`]({SCRIPT_URL}) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:```bashhf jobs uv run --flavor a10g-large --secrets HF_TOKEN \\{SCRIPT_URL} \\{args_summary}```""")try:card.push_to_hub(repo_id)except Exception as e:print(f"WARNING: could not push dataset card ({e})", flush=True)# ── the two generation paths ────────────────────────────────────────────────130 unmodified linesgen = (run_paged(model, tokenizer, items, prompt, args) if use_pagedelse run_batch(model, tokenizer, items, prompt, args, backend, model_args.max_seq_len))# Records are STREAMED, never accumulated: a whole-corpus run used to hold every# decoded PIL image in a list until the final push (~3-12 MB each -> tens of GB# RSS -> OOM-killed before anything was pushed).counters = {"images": 0, "instances": 0}json_rows = [] # populated only when --json; records here are image-freet0 = time.perf_counter()def iter_records():for key, im, aux, dt in gen:W, H = im.sizeboxes = pair_bboxes(aux.bboxes_raw)rles = list(aux.masks_rle)bbox, area, rect = [], [], []for i, b in enumerate(boxes):bbox.append([b["x"], b["y"], b["w"], b["h"]]) # yolo: cx, cy, w, h normaliseda = b["w"] * b["h"]area.append(a)r = 0.0if i < len(rles): # rectangularity -- the only triage signal availabletry:m = rles[i]if isinstance(m.get("counts"), str):m = {**m, "counts": m["counts"].encode()}# measure box area in the MASK's own frame (rle size), not the# fitted image's -- the two never match, and mixing frames skews rmh, mw = (m.get("size") or [H, W])[:2]r = min(float(mask_utils.area(m)) / max(a * mw * mh, 1.0), 1.0)except Exception:r = 0.0rect.append(r)counters["images"] += 1counters["instances"] += len(bbox)print(f"[{counters['images']}] {key[:55]:55s} {len(bbox):2d} inst {dt:.2f}s", flush=True)if args.preview:print(f" -> {save_preview(key, im, boxes, rles, args.preview_dir)}", flush=True)rec = {"image": im, "image_id": stable_id(key), "source_id": key,"width": W, "height": H,"objects": {"bbox": bbox, "category": [0] * len(bbox),"area": area, "rectangularity": rect},"n_instances": len(bbox),1 unmodified line{**m, "counts": m["counts"].decode() if isinstance(m.get("counts"), bytes) else m.get("counts")}for m in rles]),}if args.json:json_rows.append(plain(rec))yield recdef plain(r): # everything except the PIL image, which is not serialisablereturn {k: v for k, v in r.items() if k != "image"}hub_out = args.out and not args.out.endswith((".json", ".jsonl", ".parquet"))if hub_out:from datasets import Dataset, Features, Image as ImageFeat, Sequence as SeqFeat, Valuefeats = Features({"image": ImageFeat(), "image_id": Value("int64"), "source_id": Value("string"),"width": Value("int32"), "height": Value("int32"),"objects": {"bbox": SeqFeat(SeqFeat(Value("float32"))),"category": SeqFeat(Value("int64")),1 unmodified line"rectangularity": SeqFeat(Value("float32"))},"n_instances": Value("int32"), "masks_rle": Value("string"),})# Stream through an ArrowWriter: accumulating records in RAM OOMs whole-corpus# runs, and the from_generator APIs pickle their callable, which this closure# (live generator, loaded model) cannot survive. The writer flushes to disk per# batch; from_file memory-maps the result back for the push.import tempfilefrom datasets.arrow_writer import ArrowWriterarrow_path = os.path.join(tempfile.mkdtemp(prefix="falcon-out-"), "data.arrow")with ArrowWriter(features=feats, path=arrow_path, writer_batch_size=100) as writer:for rec in iter_records():writer.write(feats.encode_example(rec))writer.finalize()ds = Dataset.from_file(arrow_path)ds.push_to_hub(args.out, private=args.private)push_card(args.out, args.query, counters)if args.json:print(json.dumps(json_rows, indent=2), flush=True)else:rows = [plain(r) for r in iter_records()]if args.json:print(json.dumps(rows, indent=2), flush=True)if args.out and args.out.endswith(".json"):pathlib.Path(args.out).write_text(json.dumps(rows, indent=2))elif args.out and args.out.endswith(".jsonl"):pathlib.Path(args.out).write_text("".join(json.dumps(r) + "\n" for r in rows))elif args.out:import pyarrow as paimport pyarrow.parquet as pqpq.write_table(pa.Table.from_pylist(rows), args.out, compression="zstd")wall = time.perf_counter() - t0n = counters["images"]print(f"\n{n} images in {wall:.1f}s ({n / max(wall, 1e-9):.2f} img/s)", flush=True)if args.out:print(f"{counters['instances']} instances -> {args.out}", flush=True)if hub_out:print(f"\nNEXT: validate-hf-dataset.py {args.out} --bbox-format yolo", flush=True)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330#!/usr/bin/env -S uv run --script# /// script# requires-python = ">=3.10"# dependencies = [# "gradio>=6,<7",# "fastapi",# "datasets>=4.5.0",# "pillow",# ]# ///"""Human triage for a detection dataset -> an accept/reject verdict per image or per box.
A minimal keyboard-first review UI for datasets in THIS DIRECTORY'S schema(yolo-normalized `objects.bbox` + `image`, `image_id`, `width`, `height` -- whatfalcon-perception.py pushes; run convert-hf-dataset.py first for anything else).Zero-shot teacher labels are suggestions, not ground truth: this is where ahuman turns them into something you can quote. Runs locally, opens yourbrowser, journals every decision, pushes the reviewed rows back to the Hub.
# quick first pass: accept/reject whole images (A / R keys) on a random sample uv run review-detections.py you/plates-illustrations --limit 200 \ --out you/plates-illustrations-reviewed
# detail pass: click boxes to reject them individually uv run review-detections.py you/plates-illustrations --mode boxes \ --out you/plates-illustrations-reviewed
Modes: quick whole-image verdict. A=accept R=reject M=accept-but-teacher-missed-something F=finish arrows=skip/back. Defaults to RANDOM order, so the summary's acceptance rate is an unbiased sample statistic you can quote. boxes click a box to toggle it rejected; A keeps the rest, R rejects the whole image (all boxes). Defaults to rectangularity-ASCENDING order (irregular instances first) -- best use of effort, but a biased sample: the summary says so and its rate should not be quoted.
Two numbers come out, measuring two different things: the ACCEPTANCE rate (arethe boxes that were drawn correct?) and the MISSED rate (how often did theteacher skip an instance? -- the M key). Quote them separately; neither impliesthe other.
The journal (default ./review-<dataset>-<split>.jsonl) is appended per decisionand tolerates a torn final line; re-running resumes at the first undecided image.--out pushes decided rows with a `review` column ({verdict, missed, box_keep,mode}) alongside the original schema."""
import argparseimport ioimport jsonimport osimport randomimport signalimport threading
from fastapi.responses import HTMLResponse, Response
DISPLAY_W = 980
PAGE = """<!doctype html><title>review-detections</title><style> body { margin:0; background:#181818; color:#ddd; font:14px system-ui; } #bar { padding:8px 14px; display:flex; gap:18px; align-items:center; } #bar b { color:#fff; } #keys { color:#888; margin-left:auto; } #stage { position:relative; margin:0 auto; width:max-content; } #img { display:block; } .box { position:absolute; border:3px solid #ffd200; cursor:pointer; } .box.rej { border-color:#f33; border-style:dashed; } #flash { position:fixed; inset:0; display:none; align-items:center; justify-content:center; font-size:80px; pointer-events:none; } #err { display:none; padding:6px 14px; background:#611; color:#fbb; }</style><div id=bar><b id=pos></b><span id=stats></span><span id=verdict></span><span id=keys></span></div><div id=err></div><div id=stage><img id=img><div id=boxes></div></div><div id=flash></div><script>const MODE = "__MODE__"; // substituted by the serverdocument.getElementById("keys").textContent = MODE === "quick" ? "A accept · R reject · M missed · ←/→ move · F finish" : "click box = reject it · A accept rest · R reject all · M missed · ←/→ · F finish";let idx = 0, meta = null, rejected = new Set();
async function load(i) { const r = await fetch(`/meta/${i}`); if (!r.ok) return; meta = await r.json(); idx = meta.idx; rejected = new Set(meta.rejected_boxes); document.getElementById("img").src = `/img/${idx}`; document.getElementById("pos").textContent = `${idx + 1} / ${meta.total}`; document.getElementById("stats").textContent = meta.stats; document.getElementById("verdict").textContent = meta.verdict ? `decided: ${meta.verdict}` : ""; const holder = document.getElementById("boxes"); holder.innerHTML = ""; meta.boxes.forEach(([x0, y0, x1, y1], j) => { const d = document.createElement("div"); d.className = "box" + (rejected.has(j) ? " rej" : ""); Object.assign(d.style, {left: x0 + "px", top: y0 + "px", width: (x1 - x0) + "px", height: (y1 - y0) + "px"}); if (MODE === "boxes") d.onclick = () => { rejected.has(j) ? rejected.delete(j) : rejected.add(j); d.classList.toggle("rej"); }; holder.appendChild(d); });}function flash(t, c) { const f = document.getElementById("flash"); f.textContent = t; f.style.color = c; f.style.display = "flex"; setTimeout(() => f.style.display = "none", 180);}async function decide(verdict, missed) { if (!meta) return; const box_keep = verdict === "reject" ? meta.boxes.map(() => false) : meta.boxes.map((_, j) => !rejected.has(j)); const r = await fetch("/decide", {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({idx, verdict, missed, box_keep, mode: MODE})}); if (!r.ok) { // do NOT advance on failure -- the journal write did not happen const e = document.getElementById("err"); e.textContent = `decision NOT saved (server error ${r.status}) — fix the problem and retry`; e.style.display = "block"; return; } document.getElementById("err").style.display = "none"; flash(verdict === "accept" ? (missed ? "+?" : "✓") : "✗", verdict === "accept" ? (missed ? "#fa3" : "#3c3") : "#f33"); load(idx + 1);}document.addEventListener("keydown", (e) => { if (e.key === "ArrowRight") load(idx + 1); else if (e.key === "ArrowLeft") load(idx - 1); else if (e.key === "a" || e.key === "A") decide("accept", false); else if (e.key === "r" || e.key === "R") decide("reject", false); else if (e.key === "m" || e.key === "M") decide("accept", true); else if (e.key === "f" || e.key === "F") { fetch("/finish", {method: "POST"}); document.getElementById("keys").textContent = "finished — see the terminal; you can close this tab"; }});fetch("/start").then(r => r.json()).then(d => load(d.start));</script>"""
def to_display_boxes(objects, width, height, scale): out = [] for cx, cy, w, h in objects["bbox"]: x0 = (cx - w / 2) * width * scale y0 = (cy - h / 2) * height * scale out.append([round(x0), round(y0), round(x0 + w * width * scale), round(y0 + h * height * scale)]) return out
def main(): p = argparse.ArgumentParser() p.add_argument("dataset") p.add_argument("--split", default="train") p.add_argument("--mode", default="quick", choices=["quick", "boxes"]) p.add_argument("--order", default=None, choices=["random", "rect"], help="default: random in quick mode (unbiased rate), rect in boxes mode") p.add_argument("--limit", type=int, default=None) p.add_argument("--seed", type=int, default=42) p.add_argument("--journal", default=None, help="default: ./review-<dataset>-<split>.jsonl (scoped so runs don't mix)") p.add_argument("--out", default=None, help="Hub repo id for the reviewed dataset") p.add_argument("--private", action="store_true") p.add_argument("--port", type=int, default=7860) args = p.parse_args() order = args.order or ("random" if args.mode == "quick" else "rect") journal_path = args.journal or f"./review-{args.dataset.replace('/', '--')}-{args.split}.jsonl"
from datasets import Sequence, Value, load_dataset
ds = load_dataset(args.dataset, split=args.split)
missing = [c for c in ("image", "image_id", "width", "height", "objects") if c not in ds.column_names] if missing: raise SystemExit(f"dataset is missing column(s) {missing} -- this tool reads the schema " "falcon-perception.py pushes; see the docstring.")
# a lightweight view for sorting and sniffing that never decodes the image column meta_rows = ds.select_columns(["objects"])[:]["objects"] for objects in meta_rows[: min(50, len(meta_rows))]: if any(not (0 <= v <= 1.5) for box in objects["bbox"] for v in box): raise SystemExit("objects.bbox does not look yolo-normalized (values outside [0,1]) -- " "run convert-hf-dataset.py --to yolo first.")
ids = list(range(len(ds))) if order == "random": random.Random(args.seed).shuffle(ids) elif "rectangularity" not in meta_rows[0]: print("no rectangularity column -- falling back to random order", flush=True) random.Random(args.seed).shuffle(ids) else: ids.sort(key=lambda i: min(meta_rows[i]["rectangularity"]) if meta_rows[i]["rectangularity"] else 2.0) if args.limit: ids = ids[: args.limit]
# decisions are keyed by DATASET ROW INDEX -- image_id repeats across # concatenated per-class runs, so it cannot key a decision decisions = {} if os.path.exists(journal_path): with open(journal_path) as f: for line in f: line = line.strip() if not line: continue try: rec = json.loads(line) except json.JSONDecodeError: # torn final line from a crash mid-append print("journal: skipped one torn line (crash recovery)", flush=True) continue decisions[rec["row"]] = rec print(f"resumed {len(decisions)} decisions from {journal_path}", flush=True)
img_cache = {}
def render(i): if i not in img_cache: im = ds[ids[i]]["image"].convert("RGB") scale = min(DISPLAY_W / im.width, 1.0) if scale < 1.0: im = im.resize((round(im.width * scale), round(im.height * scale))) buf = io.BytesIO() im.save(buf, format="JPEG", quality=88) img_cache[i] = (buf.getvalue(), scale) if len(img_cache) > 32: img_cache.pop(next(iter(img_cache))) return img_cache[i]
def stats_line(): n = len(decisions) if not n: return "" acc = sum(1 for d in decisions.values() if d["verdict"] == "accept") mis = sum(1 for d in decisions.values() if d["missed"]) return f"{n} decided · {acc / n:.0%} accepted · {mis} missed-flagged"
import gradio as gr
app = gr.Server(title="review-detections") done = threading.Event()
@app.get("/", response_class=HTMLResponse) def page() -> str: return PAGE.replace("__MODE__", args.mode)
@app.get("/start") def start() -> dict: first = next((i for i in range(len(ids)) if ids[i] not in decisions), 0) return {"start": first}
@app.get("/img/{i}") def img(i: int) -> Response: if not 0 <= i < len(ids): return Response(status_code=404) return Response(content=render(i)[0], media_type="image/jpeg")
@app.get("/meta/{i}") def meta(i: int) -> Response: if not 0 <= i < len(ids): return Response(status_code=404) row = ds[ids[i]] _, scale = render(i) prior = decisions.get(ids[i]) payload = { "idx": i, "total": len(ids), "boxes": to_display_boxes(row["objects"], row["width"], row["height"], scale), "verdict": prior["verdict"] if prior else None, "rejected_boxes": [j for j, k in enumerate(prior["box_keep"]) if not k] if prior else [], "stats": stats_line(), } return Response(content=json.dumps(payload), media_type="application/json")
@app.post("/decide") def decide(body: dict) -> dict: if not 0 <= body.get("idx", -1) < len(ids): return Response(status_code=400) row_idx = ids[body["idx"]] rec = { "row": row_idx, "image_id": ds[row_idx]["image_id"], "dataset": args.dataset, "split": args.split, "mode": body["mode"], "order": order, "verdict": body["verdict"], "missed": bool(body.get("missed")), "box_keep": [bool(b) for b in body.get("box_keep", [])], } with open(journal_path, "a") as f: # journal FIRST -- only report saved if it is f.write(json.dumps(rec) + "\n") f.flush() os.fsync(f.fileno()) decisions[row_idx] = rec return {"n": len(decisions)}
@app.post("/finish") def finish() -> dict: done.set() return {"ok": True}
print(f"open http://127.0.0.1:{args.port}/ (F in the browser, or Ctrl-C here, to finish)", flush=True) app.launch(server_port=args.port, inbrowser=True, quiet=True, prevent_thread_lock=True) signal.signal(signal.SIGINT, lambda *_: done.set()) # gradio installs its own handler; override AFTER launch done.wait() # review happens in the browser signal.signal(signal.SIGINT, signal.default_int_handler) # Ctrl-C must work again (e.g. to abort the push)
n = len(decisions) if not n: print("no decisions made", flush=True) return acc = sum(1 for d in decisions.values() if d["verdict"] == "accept") mis = sum(1 for d in decisions.values() if d["missed"]) quotable = order == "random" and all(d["order"] == "random" for d in decisions.values()) print(f"\n{n} decided · {acc} accepted ({acc / n:.0%}) · {mis} with missed instances ({mis / n:.0%})", flush=True) print("acceptance rate is " + ("an unbiased random-order sample -- quotable" if quotable else "from a non-random or mixed-order queue -- NOT quotable"), flush=True)
if args.out: rows = sorted(decisions) reviewed = ds.select(rows) feats = reviewed.features.copy() feats["review"] = {"verdict": Value("string"), "missed": Value("bool"), "mode": Value("string"), "box_keep": Sequence(Value("bool"))} reviewed = reviewed.map( lambda r, i: {"review": {k: decisions[rows[i]][k] for k in ("verdict", "missed", "mode", "box_keep")}}, with_indices=True, features=feats, ) reviewed.push_to_hub(args.out, private=args.private) print(f"{len(reviewed)} reviewed rows -> {args.out}", flush=True)
main()README.md+24-14
SKILL.mdAdded+162
falcon-perception-bucket.py+62-19
falcon-perception.py+143-56
review-detections.pyAdded+330