davanstrien HF Staff commited on
Commit
853d8c9
·
verified ·
1 Parent(s): 149c236

Sync from GitHub via hub-sync

Browse files
Files changed (5) hide show
  1. README.md +24 -14
  2. SKILL.md +162 -0
  3. falcon-perception-bucket.py +62 -19
  4. falcon-perception.py +143 -56
  5. review-detections.py +330 -0
README.md CHANGED
@@ -5,7 +5,7 @@ tags: [uv-script, object-detection]
5
 
6
  # Object Detection Dataset Scripts
7
 
8
- 7 scripts to **create**, convert, validate, inspect, diff, and sample object detection datasets on the Hub. Supports 6 bbox formats — no setup required.
9
 
10
  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.
11
  This repository is inspired by [panlabel](https://github.com/strickvl/panlabel)
@@ -33,6 +33,7 @@ That's it! The script will:
33
  |--------|-------------|
34
  | `falcon-perception.py` | **Create** a detection dataset zero-shot from any image dataset — name a class, get boxes + masks (runs on Apple Silicon too) |
35
  | `falcon-perception-bucket.py` | Same, reading images from an HF bucket, resumable across restarts |
 
36
  | `convert-hf-dataset.py` | Convert between 6 bbox formats and push to Hub |
37
  | `validate-hf-dataset.py` | Check annotations for errors (invalid bboxes, duplicates, bounds) |
38
  | `stats-hf-dataset.py` | Compute statistics (counts, label histogram, area, co-occurrence) |
@@ -253,20 +254,21 @@ The other scripts assume you already have annotations. `falcon-perception.py` is
253
 
254
  ```bash
255
  # 1. does the model do the thing? (your laptop — no GPU needed)
256
- uv run falcon-perception.py --image page.jpg --query illustration --preview
257
 
258
  # 2. does it work on YOUR data? (first rows of the real corpus)
259
- uv run falcon-perception.py --dataset biglam/british-library-book-images \
260
  --config plates --limit 3 --preview
261
 
262
  # 3. the whole corpus, on a GPU
263
- hf jobs uv run --flavor a10g-large --secrets HF_TOKEN falcon-perception.py -- \
 
264
  --dataset biglam/british-library-book-images --config plates \
265
  --id-col fname --query illustration --out you/plates-illustrations
266
 
267
  # 4. it is already in `yolo` format — the rest of this directory just works
268
- uv run validate-hf-dataset.py you/plates-illustrations --bbox-format yolo
269
- uv run stats-hf-dataset.py you/plates-illustrations --bbox-format yolo
270
  ```
271
 
272
  Falcon emits boxes as normalised centre x,y + w,h, which *is* the `yolo` format above, so no conversion step is needed.
@@ -274,12 +276,12 @@ Falcon emits boxes as normalised centre x,y + w,h, which *is* the `yolo` format
274
  **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:
275
 
276
  ```bash
277
- uv run convert-hf-dataset.py you/plates-illustrations you/for-review --from yolo --to label_studio
278
  # ... correct in Label Studio, push as you/corrected ...
279
- uv run diff-hf-datasets.py you/plates-illustrations you/corrected # IoU match = zero-shot accuracy
280
  ```
281
 
282
- **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.
283
 
284
  ### Known limits
285
 
@@ -297,9 +299,9 @@ Measured, not guessed — see the script docstrings for the failure each one cam
297
  `--out` takes a file path as readily as a repo id — no Hub push, nothing to clean up:
298
 
299
  ```bash
300
- uv run falcon-perception.py --image page.jpg --query illustration --out results.json
301
- uv run falcon-perception.py --image "scans/*.jpg" --query illustration --out results.jsonl
302
- uv run falcon-perception.py --image page.jpg --query illustration --json | jq '.[0].objects.bbox'
303
  ```
304
 
305
  Anything ending `.json`, `.jsonl` or `.parquet` is written locally; anything else is treated as a Hub dataset repo id.
@@ -310,10 +312,18 @@ Anything ending `.json`, `.jsonl` or `.parquet` is written locally; anything els
310
 
311
  ```python
312
  from datasets import load_dataset
313
- load_dataset("parquet", data_files=["hf://buckets/you/bl-masks/part-000000.parquet", ...],
314
  split="train").push_to_hub("you/bl-masks")
315
  ```
316
 
317
  ### Output columns
318
 
319
- `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).
 
 
 
 
 
 
 
 
 
5
 
6
  # Object Detection Dataset Scripts
7
 
8
+ 8 scripts to **create**, convert, review, validate, inspect, diff, and sample object detection datasets on the Hub. Supports 6 bbox formats — no setup required.
9
 
10
  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.
11
  This repository is inspired by [panlabel](https://github.com/strickvl/panlabel)
 
33
  |--------|-------------|
34
  | `falcon-perception.py` | **Create** a detection dataset zero-shot from any image dataset — name a class, get boxes + masks (runs on Apple Silicon too) |
35
  | `falcon-perception-bucket.py` | Same, reading images from an HF bucket, resumable across restarts |
36
+ | `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 |
37
  | `convert-hf-dataset.py` | Convert between 6 bbox formats and push to Hub |
38
  | `validate-hf-dataset.py` | Check annotations for errors (invalid bboxes, duplicates, bounds) |
39
  | `stats-hf-dataset.py` | Compute statistics (counts, label histogram, area, co-occurrence) |
 
254
 
255
  ```bash
256
  # 1. does the model do the thing? (your laptop — no GPU needed)
257
+ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py --image page.jpg --query illustration --preview
258
 
259
  # 2. does it work on YOUR data? (first rows of the real corpus)
260
+ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py --dataset biglam/british-library-book-images \
261
  --config plates --limit 3 --preview
262
 
263
  # 3. the whole corpus, on a GPU
264
+ hf jobs uv run --flavor a10g-large --secrets HF_TOKEN \
265
+ https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py \
266
  --dataset biglam/british-library-book-images --config plates \
267
  --id-col fname --query illustration --out you/plates-illustrations
268
 
269
  # 4. it is already in `yolo` format — the rest of this directory just works
270
+ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/validate-hf-dataset.py you/plates-illustrations --bbox-format yolo
271
+ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/stats-hf-dataset.py you/plates-illustrations --bbox-format yolo
272
  ```
273
 
274
  Falcon emits boxes as normalised centre x,y + w,h, which *is* the `yolo` format above, so no conversion step is needed.
 
276
  **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:
277
 
278
  ```bash
279
+ uv 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
280
  # ... correct in Label Studio, push as you/corrected ...
281
+ 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
282
  ```
283
 
284
+ **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.
285
 
286
  ### Known limits
287
 
 
299
  `--out` takes a file path as readily as a repo id — no Hub push, nothing to clean up:
300
 
301
  ```bash
302
+ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py --image page.jpg --query illustration --out results.json
303
+ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py --image "scans/*.jpg" --query illustration --out results.jsonl
304
+ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py --image page.jpg --query illustration --json | jq '.[0].objects.bbox'
305
  ```
306
 
307
  Anything ending `.json`, `.jsonl` or `.parquet` is written locally; anything else is treated as a Hub dataset repo id.
 
312
 
313
  ```python
314
  from datasets import load_dataset
315
+ load_dataset("parquet", data_files="hf://buckets/you/bl-masks/part-*.parquet",
316
  split="train").push_to_hub("you/bl-masks")
317
  ```
318
 
319
  ### Output columns
320
 
321
+ `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).
322
+
323
+ ### Train on the output
324
+
325
+ Convert 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:
326
+
327
+ ```bash
328
+ uv 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
329
+ ```
SKILL.md ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: detection-bootstrap
3
+ description: 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.
4
+ ---
5
+
6
+ # Bootstrap a detector from unlabeled images
7
+
8
+ The loop: **zero-shot teacher labels → validate → convert → train a small student → evaluate → publish.**
9
+ Every step is a self-contained UV script from
10
+ [`uv-scripts/object-detection`](https://huggingface.co/datasets/uv-scripts/object-detection) on the
11
+ Hugging Face Hub, or a `hf jobs` command. `--help` works on every script.
12
+
13
+ ## Check if a human in the loop
14
+
15
+ You can use the approach outlined in this skill with or without a human in the loop.
16
+
17
+ - **With a human in the loop** (better models): show them the step-1 previews — "is the teacher boxing
18
+ the right things?" is the highest-value question, and its fix is the cheapest (a better query, about $2 to
19
+ re-run the teacher). Then train on a small slice first (500–1k images, about $1) and show 20 rendered
20
+ predictions before spending on the full corpus. If corrections are worth collecting at volume, run a
21
+ review pass with `review-detections.py` (keyboard accept/reject in the browser, per image or per box;
22
+ prints the quotable acceptance + missed rates and pushes a `review` column), fold corrections in and
23
+ retrain (about $1). Diff the corrected set against the first pass (`diff-hf-datasets.py`) to measure how
24
+ good the zero-shot pass actually was.
25
+ - **Autonomously** (headless): don't pause for review — use the numeric proxies, and say **unreviewed**
26
+ in the final report and model card.
27
+
28
+ ## 1. Sense-check the class name before spending GPU money (free)
29
+
30
+ Falcon-Perception queries are **class names, not instructions** ("photograph" works; "the photographs,
31
+ excluding captions" returns nothing), and **one class per run** (combined queries collapse — run per
32
+ class and merge on `image_id`). Model details: `hf models card tiiuae/Falcon-Perception`.
33
+
34
+ Check cheaply on 3 images before any full pass. The teacher (Falcon-Perception) is a **0.6B model,
35
+ 1.3 GB download** — it runs on a CUDA GPU (fast), Apple Silicon (MLX backend auto-selected, about 6 s/image),
36
+ or plain CPU (slow, but fine for 3 images). Run the check wherever is practical for you:
37
+
38
+ ```
39
+ # locally, if your machine can:
40
+ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py \
41
+ --dataset <USER>/<IMAGES> --limit 3 --query photograph --preview
42
+
43
+ # or the same check as a small job (previews don't persist on Jobs — push a tiny dataset instead):
44
+ hf jobs uv run --flavor t4-small --secrets HF_TOKEN \
45
+ https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py \
46
+ --dataset <USER>/<IMAGES> --limit 3 --query photograph --out <USER>/<NAME>-check --private
47
+ ```
48
+
49
+ Judge the result before scaling up:
50
+ - **If you can view images**, look at the rendered previews (or the pushed check dataset) — are the
51
+ right things boxed?
52
+ - **If you can't**, compare instance counts across candidate queries (`stats-hf-dataset.py` below works
53
+ on a pushed check dataset): near-zero instances/image means the class name is wrong for this material —
54
+ try a synonym (`photograph` / `illustration` / `figure` / `cartoon`). Suspiciously many (more than about 10/image)
55
+ usually means the query is matching layout blocks, not pictures.
56
+ - **No vision at all?** A vision-capable subagent can judge the previews if you can spawn one;
57
+ otherwise tell the user the check ran unviewed.
58
+
59
+ (Falcon-Perception has a custom architecture, so it can't be served as an OpenAI-compatible endpoint —
60
+ iterate via the batch script. If you swap in a teacher that vLLM can serve, a temporary hot server on
61
+ Jobs is the faster way to iterate on queries: see
62
+ [Serve Models on Jobs](https://huggingface.co/docs/hub/jobs-serving).)
63
+
64
+ ## 2. Teacher pass on Jobs
65
+
66
+ ```
67
+ hf jobs uv run --flavor a10g-large --secrets HF_TOKEN --timeout 2h \
68
+ https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py \
69
+ --dataset <USER>/<IMAGES> --query photograph --out <USER>/<NAME>-photograph --private
70
+ ```
71
+
72
+ - Avoid `a10g-small` — the engine sizes itself from the GPU and ignores host RAM, so it gets
73
+ OOM-killed. `hf jobs hardware` lists current options and prices.
74
+ - One job per class (step 1's rule). Merge per-class outputs by concatenating the `objects` entries of
75
+ rows with the same `image_id`.
76
+ - Output schema: `objects.bbox` in **YOLO format** (normalized center x, y, w, h), `objects.category`,
77
+ `objects.area`, `objects.rectangularity`, plus `image`, `image_id`, `width`, `height`.
78
+ - There are **no confidence scores** (the model has none). `rectangularity` (mask area ÷ box area) is the
79
+ triage proxy: values near 0 are usually junk, 0.785 is a circle, 1.0 a full rectangle.
80
+ - Submit with `--detach` (returns the job id immediately), then block on completion with
81
+ `hf jobs wait <id> [<id> ...] --timeout 2h` — it exits 0 only if every job succeeded, so it
82
+ chains cleanly into the next step. `hf jobs logs <id>` / `hf jobs inspect <id>` for progress and errors.
83
+ - A job can sit in SCHEDULING while the flavor queue drains — that is a queue, not a failure.
84
+ **Don't resubmit**: a second copy racing to the same `--out` just doubles the bill. If you do
85
+ switch (`hf jobs hardware` for alternatives), cancel the queued copy first (`hf jobs cancel <id>`).
86
+ - For images in a [storage bucket](https://huggingface.co/docs/hub/storage-buckets) instead of a
87
+ dataset, use `falcon-perception-bucket.py` from the same repo (resumable).
88
+
89
+ ## 3. Validate the labels (free, local)
90
+
91
+ ```
92
+ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/validate-hf-dataset.py \
93
+ <USER>/<NAME>-photograph --bbox-format yolo
94
+ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/stats-hf-dataset.py \
95
+ <USER>/<NAME>-photograph --bbox-format yolo
96
+ ```
97
+
98
+ Expect **VALID** with 0 out-of-bounds and 0 zero-area boxes. `W001` warnings on empty images are normal —
99
+ they are true negatives (pages with no instance), and they are useful training signal; keep them.
100
+ Drop obvious junk before training: degenerate slivers (extreme aspect ratio + tiny area) and near-duplicate
101
+ boxes (IoU > 0.9 within one image).
102
+
103
+ ## 4. Convert YOLO → COCO for training (free, local)
104
+
105
+ Trainers expect COCO `xywh` pixels; the teacher emits YOLO normalized. One command:
106
+
107
+ ```
108
+ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/convert-hf-dataset.py \
109
+ <USER>/<NAME>-photograph <USER>/<NAME>-coco --from yolo --to coco_xywh
110
+ ```
111
+
112
+ ## 5. Train a small detector
113
+
114
+ Good starting points: [D-FINE](https://huggingface.co/ustc-community/dfine-small-coco) or
115
+ [RT-DETRv2](https://huggingface.co/PekingU/rtdetr_v2_r18vd) — compact, Apache-2.0, in `transformers`
116
+ (boxes only; for masks see the RF-DETR note below). Check the license fits the use —
117
+ `hf models card <id>` shows it; flag restrictive licenses (e.g. ultralytics/YOLO is AGPL) to the user
118
+ rather than deciding for them. Explore further:
119
+ [transformers object-detection models](https://huggingface.co/models?pipeline_tag=object-detection&library=transformers&sort=trending) ·
120
+ [ultralytics-library models](https://huggingface.co/models?library=ultralytics).
121
+
122
+ The **`huggingface-vision-trainer`** skill covers the training end to end (dataset validation,
123
+ augmentation, mAP eval, Hub persistence) — install it with `hf skills add huggingface-vision-trainer`
124
+ if you don't have it, and follow its object-detection path with the `<USER>/<NAME>-coco` dataset from
125
+ step 4. Before training, decide a pragmatic validation split and never train on it.
126
+
127
+ Other trainers work too — the dataset is plain COCO. [RF-DETR](https://github.com/roboflow/rf-detr)
128
+ (Apache-2.0, DINOv2 backbone) is a good starter, and its Seg variant can learn from the teacher's
129
+ `masks_rle` masks. Decode them like this — each RLE lives in its own frame, which never matches the
130
+ recorded width/height:
131
+
132
+ ```python
133
+ import json, numpy as np
134
+ from PIL import Image
135
+ from pycocotools import mask as mask_utils
136
+
137
+ for rle in json.loads(row["masks_rle"]):
138
+ seg = mask_utils.decode({**rle, "counts": rle["counts"].encode()}) # frame = rle["size"]
139
+ if seg.shape != (row["height"], row["width"]):
140
+ seg = np.asarray(Image.fromarray(seg).resize((row["width"], row["height"]), Image.NEAREST))
141
+ ```
142
+
143
+ ## 6. Evaluate honestly
144
+
145
+ - Report mAP on the held-out slice. Be clear about what it measures: **agreement with the teacher**,
146
+ not accuracy against human truth — no human labels exist in this loop.
147
+ - The student can at best match its teacher (measured on a comparable loop: student 97.4% vs teacher
148
+ 95.0% human-acceptable on the same sample). The point of distilling is **throughput and cost**
149
+ (10–100× cheaper per image than the teacher), not accuracy gains.
150
+ - Spot-check 20 or so predictions visually before calling it done — or, if running without a human and you
151
+ cannot view images, state prominently in the report that the model is **unreviewed**.
152
+ - It can make sense to run this process in a loop: predict → review (a human, or a vision-capable
153
+ agent, via `review-detections.py`) → retrain on the corrections → review again, until the acceptance
154
+ rate stops improving.
155
+
156
+ ## 7. Publish with honest provenance
157
+
158
+ Push the model and dataset — ask the user whether public or private; if you can't ask, default to
159
+ private and say so. The cards must state: labels are **zero-shot weak labels** from Falcon-Perception
160
+ (name the script + date), which filters ran, and that **recall is unmeasured** unless you measured it
161
+ against an independent source. Say what the model is for and what it was trained on. A model trained
162
+ this way is a first pass. The review loop above is how it gets better.
falcon-perception-bucket.py CHANGED
@@ -11,8 +11,9 @@
11
  # ///
12
  """Falcon-Perception over a whole HF bucket, resumable.
13
 
14
- hf jobs uv run --flavor a10g-large --secrets HF_TOKEN falcon-bucket.py -- \
15
- --src biglam/bl-images --include 'full/embellishments/**/*.jpg' \
 
16
  --out davanstrien/bl-masks --query illustration
17
 
18
  Input : bucketbag batched_files — bounded scratch, files deleted as the loop advances
@@ -26,9 +27,8 @@ run resumable (`completed_keys` reads the done-set back from `__source_key`).
26
  To hand the result to the rest of this directory, publish it once at the end:
27
 
28
  from datasets import load_dataset
29
- load_dataset("parquet", data_files=[
30
- "hf://buckets/you/bl-masks/part-000000.parquet", ...
31
- ], split="train").push_to_hub("you/bl-masks")
32
 
33
  uv run validate-hf-dataset.py you/bl-masks --bbox-format yolo
34
 
@@ -47,6 +47,7 @@ GOTCHAS (all measured, none in the model card):
47
  """
48
 
49
  import argparse
 
50
  import io
51
  import json
52
  import time
@@ -56,12 +57,18 @@ import pyarrow.parquet as pq
56
  from bucketbag import batched_files, boost, completed_keys, iter_keys, put_files
57
  from pycocotools import mask as mask_utils
58
 
 
 
 
 
 
 
59
  # Same YOLO column layout as falcon-perception.py, so both outputs validate with
60
  # `validate-hf-dataset.py --bbox-format yolo` and can be concatenated.
61
  # `__source_key` is bucketbag's resume column — the name is load-bearing.
62
  SCHEMA = pa.schema([
63
  ("__source_key", pa.string()),
64
- ("image_id", pa.string()),
65
  ("width", pa.int32()),
66
  ("height", pa.int32()),
67
  ("objects", pa.struct([
@@ -114,8 +121,31 @@ def main():
114
  p.add_argument("--no-resume", action="store_true")
115
  args = p.parse_args()
116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  boost() # raise xet small-file concurrency — the whole point on many small objects
118
 
 
 
 
 
 
 
119
  done = set() if args.no_resume else completed_keys(args.out)
120
  print(f"{len(done)} keys already done", flush=True)
121
 
@@ -132,7 +162,6 @@ def main():
132
  if not keys:
133
  return
134
 
135
- import torch # noqa: F401
136
  from falcon_perception import PERCEPTION_MODEL_ID, build_prompt_for_task, load_and_prepare_model, setup_torch_config
137
  from falcon_perception.data import ImageProcessor
138
  from falcon_perception.paged_inference import (
@@ -166,17 +195,18 @@ def main():
166
  for it in batch:
167
  try:
168
  img = it.image.convert("RGB") # convert() forces the load off disk
 
169
  if max(img.size) > args.max_dim * 2:
170
  img.thumbnail((args.max_dim * 2, args.max_dim * 2))
171
- pairs.append((str(it.key), img))
172
  except Exception as e:
173
- pairs.append((str(it.key), e))
174
 
175
- good = [(k, im) for k, im in pairs if not isinstance(im, Exception)]
176
  seqs = [
177
  Sequence(text=prompt, image=im, min_image_size=256,
178
  max_image_size=args.max_dim, request_idx=i, task=args.task)
179
- for i, (_, im) in enumerate(good)
180
  ]
181
  t0 = time.perf_counter()
182
  if seqs:
@@ -185,14 +215,16 @@ def main():
185
  gen_total += dt
186
 
187
  rows = []
188
- for (key, im), seq in zip(good, seqs):
189
  aux = seq.output_aux
190
  boxes = pair_bboxes(aux.bboxes_raw)
191
  masks = list(aux.masks_rle)
192
  for m in masks:
193
  if isinstance(m.get("counts"), bytes):
194
  m["counts"] = m["counts"].decode()
195
- W, H = im.size
 
 
196
  bbox, area, rect = [], [], []
197
  for i, b in enumerate(boxes):
198
  bbox.append([b["x"], b["y"], b["w"], b["h"]]) # yolo: cx, cy, w, h normalised
@@ -204,27 +236,38 @@ def main():
204
  m = masks[i]
205
  if isinstance(m.get("counts"), str):
206
  m = {**m, "counts": m["counts"].encode()}
207
- r = min(float(mask_utils.area(m)) / max(a * W * H, 1.0), 1.0)
 
 
 
208
  except Exception:
209
  r = 0.0
210
  rect.append(r)
211
  rows.append({
212
- "__source_key": key, "image_id": key, "width": W, "height": H,
213
  "objects": {"bbox": bbox, "category": [0] * len(bbox),
214
  "area": area, "rectangularity": rect},
215
  "n_instances": len(bbox), "masks_rle": json.dumps(masks),
216
  "query": args.query, "gen_seconds": dt / max(len(seqs), 1), "error": None,
217
  })
218
- for key, err in [(k, v) for k, v in pairs if isinstance(v, Exception)]:
219
  # a durable error row, never a gap — and it counts as done so it is
220
- # not retried forever on every re-run
 
221
  rows.append({k: None for k in SCHEMA.names} | {
222
- "__source_key": key, "image_id": key, "query": args.query,
 
 
223
  "error": f"{type(err).__name__}: {err}",
224
  })
225
 
 
 
 
 
226
  ext = "jsonl" if args.format == "jsonl" else "parquet"
227
- put_files([(f"part-{batch_i:06d}.{ext}", serialise(rows, args.format))], args.out)
 
228
  n += len(rows); batch_i += 1
229
  rate = n / (time.perf_counter() - t_all)
230
  print(f"batch {batch_i}: {len(rows)} rows ({dt / max(len(seqs), 1):.2f}s/img) "
 
11
  # ///
12
  """Falcon-Perception over a whole HF bucket, resumable.
13
 
14
+ hf jobs uv run --flavor a10g-large --secrets HF_TOKEN \
15
+ https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception-bucket.py \
16
+ --src biglam/bl-images --prefix full/embellishments \
17
  --out davanstrien/bl-masks --query illustration
18
 
19
  Input : bucketbag batched_files — bounded scratch, files deleted as the loop advances
 
27
  To hand the result to the rest of this directory, publish it once at the end:
28
 
29
  from datasets import load_dataset
30
+ load_dataset("parquet", data_files="hf://buckets/you/bl-masks/part-*.parquet",
31
+ split="train").push_to_hub("you/bl-masks")
 
32
 
33
  uv run validate-hf-dataset.py you/bl-masks --bbox-format yolo
34
 
 
47
  """
48
 
49
  import argparse
50
+ import hashlib
51
  import io
52
  import json
53
  import time
 
57
  from bucketbag import batched_files, boost, completed_keys, iter_keys, put_files
58
  from pycocotools import mask as mask_utils
59
 
60
+
61
+ def stable_id(key):
62
+ """Deterministic int64 image_id from the source key (COCO consumers need an int;
63
+ a hash, not a running index, keeps ids identical across resumed runs)."""
64
+ return int.from_bytes(hashlib.blake2b(str(key).encode(), digest_size=8).digest(), "big") >> 1
65
+
66
  # Same YOLO column layout as falcon-perception.py, so both outputs validate with
67
  # `validate-hf-dataset.py --bbox-format yolo` and can be concatenated.
68
  # `__source_key` is bucketbag's resume column — the name is load-bearing.
69
  SCHEMA = pa.schema([
70
  ("__source_key", pa.string()),
71
+ ("image_id", pa.int64()), # int, not str: COCO-style trainers tensorise it
72
  ("width", pa.int32()),
73
  ("height", pa.int32()),
74
  ("objects", pa.struct([
 
121
  p.add_argument("--no-resume", action="store_true")
122
  args = p.parse_args()
123
 
124
+ if args.format == "jsonl" and not args.no_resume:
125
+ # completed_keys only reads the done-set back from .parquet parts, so jsonl
126
+ # output silently reprocesses EVERYTHING on every re-run.
127
+ raise SystemExit("--format jsonl is not resumable; pass --no-resume to run it anyway.")
128
+
129
+ try:
130
+ import torch
131
+
132
+ has_cuda = torch.cuda.is_available()
133
+ except ImportError: # falcon-perception pins torch off-darwin, so it may be absent
134
+ has_cuda = False
135
+ if not has_cuda:
136
+ raise SystemExit(
137
+ "This script needs a CUDA GPU (PagedInferenceEngine). "
138
+ "For MLX/CPU-capable runs use falcon-perception.py instead."
139
+ )
140
+
141
  boost() # raise xet small-file concurrency — the whole point on many small objects
142
 
143
+ from huggingface_hub import HfApi
144
+
145
+ # first run: the out bucket may not exist yet — completed_keys 404s on a
146
+ # missing bucket, killing the job before anything happens
147
+ HfApi().create_bucket(args.out, private=True, exist_ok=True)
148
+
149
  done = set() if args.no_resume else completed_keys(args.out)
150
  print(f"{len(done)} keys already done", flush=True)
151
 
 
162
  if not keys:
163
  return
164
 
 
165
  from falcon_perception import PERCEPTION_MODEL_ID, build_prompt_for_task, load_and_prepare_model, setup_torch_config
166
  from falcon_perception.data import ImageProcessor
167
  from falcon_perception.paged_inference import (
 
195
  for it in batch:
196
  try:
197
  img = it.image.convert("RGB") # convert() forces the load off disk
198
+ orig_size = img.size # SOURCE dims -- the images downstream tools decode
199
  if max(img.size) > args.max_dim * 2:
200
  img.thumbnail((args.max_dim * 2, args.max_dim * 2))
201
+ pairs.append((str(it.key), img, orig_size))
202
  except Exception as e:
203
+ pairs.append((str(it.key), e, None))
204
 
205
+ good = [(k, im, sz) for k, im, sz in pairs if not isinstance(im, Exception)]
206
  seqs = [
207
  Sequence(text=prompt, image=im, min_image_size=256,
208
  max_image_size=args.max_dim, request_idx=i, task=args.task)
209
+ for i, (_, im, _) in enumerate(good)
210
  ]
211
  t0 = time.perf_counter()
212
  if seqs:
 
215
  gen_total += dt
216
 
217
  rows = []
218
+ for (key, im, orig_size), seq in zip(good, seqs):
219
  aux = seq.output_aux
220
  boxes = pair_bboxes(aux.bboxes_raw)
221
  masks = list(aux.masks_rle)
222
  for m in masks:
223
  if isinstance(m.get("counts"), bytes):
224
  m["counts"] = m["counts"].decode()
225
+ # width/height are the SOURCE image's dims: boxes are normalised (frame-free),
226
+ # and downstream pixel conversions run against the untouched bucket images.
227
+ W, H = orig_size
228
  bbox, area, rect = [], [], []
229
  for i, b in enumerate(boxes):
230
  bbox.append([b["x"], b["y"], b["w"], b["h"]]) # yolo: cx, cy, w, h normalised
 
236
  m = masks[i]
237
  if isinstance(m.get("counts"), str):
238
  m = {**m, "counts": m["counts"].encode()}
239
+ # box area measured in the MASK's own frame (rle size) — mixing
240
+ # frames skews r
241
+ mh, mw = (m.get("size") or [H, W])[:2]
242
+ r = min(float(mask_utils.area(m)) / max(a * mw * mh, 1.0), 1.0)
243
  except Exception:
244
  r = 0.0
245
  rect.append(r)
246
  rows.append({
247
+ "__source_key": key, "image_id": stable_id(key), "width": W, "height": H,
248
  "objects": {"bbox": bbox, "category": [0] * len(bbox),
249
  "area": area, "rectangularity": rect},
250
  "n_instances": len(bbox), "masks_rle": json.dumps(masks),
251
  "query": args.query, "gen_seconds": dt / max(len(seqs), 1), "error": None,
252
  })
253
+ for key, err, _ in [(k, v, s) for k, v, s in pairs if isinstance(v, Exception)]:
254
  # a durable error row, never a gap — and it counts as done so it is
255
+ # not retried forever on every re-run. objects is EMPTY, not null:
256
+ # a null struct crashes validate-hf-dataset.py after publish.
257
  rows.append({k: None for k in SCHEMA.names} | {
258
+ "__source_key": key, "image_id": stable_id(key), "query": args.query,
259
+ "objects": {"bbox": [], "category": [], "area": [], "rectangularity": []},
260
+ "n_instances": 0, "masks_rle": "[]",
261
  "error": f"{type(err).__name__}: {err}",
262
  })
263
 
264
+ # part name derives from batch CONTENT, not a run-local counter: a resumed run's
265
+ # counter restarts at 0 and put_files overwrites, silently destroying the first
266
+ # run's parts. A content-derived name is stable per batch and collision-free
267
+ # across resumes (a re-run of the same batch overwrites its own part, idempotent).
268
  ext = "jsonl" if args.format == "jsonl" else "parquet"
269
+ part = hashlib.blake2b(rows[0]["__source_key"].encode(), digest_size=6).hexdigest()
270
+ put_files([(f"part-{part}.{ext}", serialise(rows, args.format))], args.out)
271
  n += len(rows); batch_i += 1
272
  rate = n / (time.perf_counter() - t_all)
273
  print(f"batch {batch_i}: {len(rows)} rows ({dt / max(len(seqs), 1):.2f}s/img) "
falcon-perception.py CHANGED
@@ -33,7 +33,8 @@ your class name works on your images before spending GPU hours on the corpus.
33
  --config plates --limit 3 --preview
34
 
35
  # 3. the whole corpus, on a GPU
36
- hf jobs uv run --flavor a10g-large --secrets HF_TOKEN falcon-perception.py -- \
 
37
  --dataset biglam/british-library-book-images --config plates \
38
  --id-col fname --query illustration --out you/plates-illustrations
39
 
@@ -70,6 +71,7 @@ MEASURED LIMITS -- not guesses; each one cost a failed run:
70
 
71
  import argparse
72
  import glob as globlib
 
73
  import io
74
  import itertools
75
  import json
@@ -79,6 +81,17 @@ import platform
79
  import sys
80
  import time
81
 
 
 
 
 
 
 
 
 
 
 
 
82
  # ── backend / engine selection ──────────────────────────────────────────────
83
  # The MLX and torch APIs match parameter-for-parameter, but are NOT drop-in:
84
  # torch also needs setup_torch_config(), a compile= kwarg, and every batch tensor
@@ -212,6 +225,50 @@ def batched(it, n):
212
  yield buf
213
 
214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  # ── the two generation paths ────────────────────────────────────────────────
216
 
217
 
@@ -348,33 +405,44 @@ def main():
348
  gen = (run_paged(model, tokenizer, items, prompt, args) if use_paged
349
  else run_batch(model, tokenizer, items, prompt, args, backend, model_args.max_seq_len))
350
 
351
- records, n, t0 = [], 0, time.perf_counter()
352
- for key, im, aux, dt in gen:
353
- W, H = im.size
354
- boxes = pair_bboxes(aux.bboxes_raw)
355
- rles = list(aux.masks_rle)
356
- bbox, area, rect = [], [], []
357
- for i, b in enumerate(boxes):
358
- bbox.append([b["x"], b["y"], b["w"], b["h"]]) # yolo: cx, cy, w, h normalised
359
- a = b["w"] * b["h"]
360
- area.append(a)
361
- r = 0.0
362
- if i < len(rles): # rectangularity -- the only triage signal available
363
- try:
364
- m = rles[i]
365
- if isinstance(m.get("counts"), str):
366
- m = {**m, "counts": m["counts"].encode()}
367
- r = min(float(mask_utils.area(m)) / max(a * W * H, 1.0), 1.0)
368
- except Exception:
369
- r = 0.0
370
- rect.append(r)
371
- n += 1
372
- print(f"[{n}] {key[:55]:55s} {len(bbox):2d} inst {dt:.2f}s", flush=True)
373
- if args.preview:
374
- print(f" -> {save_preview(key, im, boxes, rles, args.preview_dir)}", flush=True)
375
- if args.out or args.json:
376
- records.append({
377
- "image": im, "image_id": key, "width": W, "height": H,
 
 
 
 
 
 
 
 
 
 
 
378
  "objects": {"bbox": bbox, "category": [0] * len(bbox),
379
  "area": area, "rectangularity": rect},
380
  "n_instances": len(bbox),
@@ -382,38 +450,21 @@ def main():
382
  {**m, "counts": m["counts"].decode() if isinstance(m.get("counts"), bytes) else m.get("counts")}
383
  for m in rles
384
  ]),
385
- })
 
 
 
386
 
387
- wall = time.perf_counter() - t0
388
- print(f"\n{n} images in {wall:.1f}s ({n / max(wall, 1e-9):.2f} img/s)", flush=True)
389
 
390
- # --- local file output: everything except the PIL image, which is not serialisable
391
- def plain(recs):
392
- return [{k: v for k, v in r.items() if k != "image"} for r in recs]
393
 
394
- if args.json:
395
- print(json.dumps(plain(records), indent=2), flush=True)
396
-
397
- if args.out and args.out.endswith((".json", ".jsonl", ".parquet")):
398
- rows = plain(records)
399
- if args.out.endswith(".json"):
400
- pathlib.Path(args.out).write_text(json.dumps(rows, indent=2))
401
- elif args.out.endswith(".jsonl"):
402
- pathlib.Path(args.out).write_text("".join(json.dumps(r) + "\n" for r in rows))
403
- else:
404
- import pyarrow as pa
405
- import pyarrow.parquet as pq
406
-
407
- pq.write_table(pa.Table.from_pylist(rows), args.out, compression="zstd")
408
- total = sum(r["n_instances"] for r in rows)
409
- print(f"{total} instances -> {args.out}", flush=True)
410
- return
411
-
412
- if args.out:
413
  from datasets import Dataset, Features, Image as ImageFeat, Sequence as SeqFeat, Value
414
 
415
  feats = Features({
416
- "image": ImageFeat(), "image_id": Value("string"),
417
  "width": Value("int32"), "height": Value("int32"),
418
  "objects": {"bbox": SeqFeat(SeqFeat(Value("float32"))),
419
  "category": SeqFeat(Value("int64")),
@@ -421,8 +472,44 @@ def main():
421
  "rectangularity": SeqFeat(Value("float32"))},
422
  "n_instances": Value("int32"), "masks_rle": Value("string"),
423
  })
424
- Dataset.from_list(records, features=feats).push_to_hub(args.out, private=args.private)
425
- print(f"{sum(r['n_instances'] for r in records)} instances -> {args.out}", flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426
  print(f"\nNEXT: validate-hf-dataset.py {args.out} --bbox-format yolo", flush=True)
427
 
428
 
 
33
  --config plates --limit 3 --preview
34
 
35
  # 3. the whole corpus, on a GPU
36
+ hf jobs uv run --flavor a10g-large --secrets HF_TOKEN \
37
+ https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py \
38
  --dataset biglam/british-library-book-images --config plates \
39
  --id-col fname --query illustration --out you/plates-illustrations
40
 
 
71
 
72
  import argparse
73
  import glob as globlib
74
+ import hashlib
75
  import io
76
  import itertools
77
  import json
 
81
  import sys
82
  import time
83
 
84
+
85
+ def stable_id(key):
86
+ """Deterministic int64 image_id from the source key.
87
+
88
+ COCO-style consumers (transformers RT-DETR / D-FINE annotation prep) require an
89
+ INTEGER image_id -- a string crashes them with "ValueError: too many dimensions
90
+ 'str'". A content hash (not a running index) keeps ids identical across separate
91
+ runs over the same source, so per-class runs merge on image_id cleanly.
92
+ """
93
+ return int.from_bytes(hashlib.blake2b(str(key).encode(), digest_size=8).digest(), "big") >> 1
94
+
95
  # ── backend / engine selection ──────────────────────────────────────────────
96
  # The MLX and torch APIs match parameter-for-parameter, but are NOT drop-in:
97
  # torch also needs setup_torch_config(), a compile= kwarg, and every batch tensor
 
225
  yield buf
226
 
227
 
228
+ SCRIPT_URL = "https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception.py"
229
+
230
+
231
+ def push_card(repo_id, query, counters):
232
+ """Dataset card with the repo's canonical provenance stamp (see AGENTS.md)."""
233
+ from huggingface_hub import DatasetCard
234
+
235
+ on_jobs = os.environ.get("JOB_ID") is not None # set by HF Jobs in-container
236
+ hw = os.environ.get("ACCELERATOR") or "" # e.g. "a10g-large"; empty on CPU
237
+ origin = (
238
+ f"Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
239
+ + (f" (`{hw}`)" if hw else "")
240
+ ) if on_jobs else "Generated"
241
+ tags = "\n".join(f"- {t}" for t in (["uv-script", "hf-jobs"] if on_jobs else ["uv-script"]))
242
+ args_summary = " ".join(sys.argv[1:])
243
+ card = DatasetCard(f"""---
244
+ tags:
245
+ {tags}
246
+ ---
247
+
248
+ # Zero-shot detection: `{query}`
249
+
250
+ {counters["images"]} images, {counters["instances"]} instances. Labels are **zero-shot weak
251
+ labels** from [Falcon-Perception](https://huggingface.co/tiiuae/Falcon-Perception) -- no human
252
+ annotated anything, and recall against human truth is unmeasured. `objects.bbox` is `yolo`
253
+ format (normalised centre x, y, w, h); `objects.rectangularity` (mask area / box area) is the
254
+ triage proxy -- the model emits no confidence scores.
255
+
256
+ ## Reproduction
257
+
258
+ {origin} with the [`falcon-perception.py`]({SCRIPT_URL}) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
259
+
260
+ ```bash
261
+ hf jobs uv run --flavor a10g-large --secrets HF_TOKEN \\
262
+ {SCRIPT_URL} \\
263
+ {args_summary}
264
+ ```
265
+ """)
266
+ try:
267
+ card.push_to_hub(repo_id)
268
+ except Exception as e:
269
+ print(f"WARNING: could not push dataset card ({e})", flush=True)
270
+
271
+
272
  # ── the two generation paths ────────────────────────────────────────────────
273
 
274
 
 
405
  gen = (run_paged(model, tokenizer, items, prompt, args) if use_paged
406
  else run_batch(model, tokenizer, items, prompt, args, backend, model_args.max_seq_len))
407
 
408
+ # Records are STREAMED, never accumulated: a whole-corpus run used to hold every
409
+ # decoded PIL image in a list until the final push (~3-12 MB each -> tens of GB
410
+ # RSS -> OOM-killed before anything was pushed).
411
+ counters = {"images": 0, "instances": 0}
412
+ json_rows = [] # populated only when --json; records here are image-free
413
+ t0 = time.perf_counter()
414
+
415
+ def iter_records():
416
+ for key, im, aux, dt in gen:
417
+ W, H = im.size
418
+ boxes = pair_bboxes(aux.bboxes_raw)
419
+ rles = list(aux.masks_rle)
420
+ bbox, area, rect = [], [], []
421
+ for i, b in enumerate(boxes):
422
+ bbox.append([b["x"], b["y"], b["w"], b["h"]]) # yolo: cx, cy, w, h normalised
423
+ a = b["w"] * b["h"]
424
+ area.append(a)
425
+ r = 0.0
426
+ if i < len(rles): # rectangularity -- the only triage signal available
427
+ try:
428
+ m = rles[i]
429
+ if isinstance(m.get("counts"), str):
430
+ m = {**m, "counts": m["counts"].encode()}
431
+ # measure box area in the MASK's own frame (rle size), not the
432
+ # fitted image's -- the two never match, and mixing frames skews r
433
+ mh, mw = (m.get("size") or [H, W])[:2]
434
+ r = min(float(mask_utils.area(m)) / max(a * mw * mh, 1.0), 1.0)
435
+ except Exception:
436
+ r = 0.0
437
+ rect.append(r)
438
+ counters["images"] += 1
439
+ counters["instances"] += len(bbox)
440
+ print(f"[{counters['images']}] {key[:55]:55s} {len(bbox):2d} inst {dt:.2f}s", flush=True)
441
+ if args.preview:
442
+ print(f" -> {save_preview(key, im, boxes, rles, args.preview_dir)}", flush=True)
443
+ rec = {
444
+ "image": im, "image_id": stable_id(key), "source_id": key,
445
+ "width": W, "height": H,
446
  "objects": {"bbox": bbox, "category": [0] * len(bbox),
447
  "area": area, "rectangularity": rect},
448
  "n_instances": len(bbox),
 
450
  {**m, "counts": m["counts"].decode() if isinstance(m.get("counts"), bytes) else m.get("counts")}
451
  for m in rles
452
  ]),
453
+ }
454
+ if args.json:
455
+ json_rows.append(plain(rec))
456
+ yield rec
457
 
458
+ def plain(r): # everything except the PIL image, which is not serialisable
459
+ return {k: v for k, v in r.items() if k != "image"}
460
 
461
+ hub_out = args.out and not args.out.endswith((".json", ".jsonl", ".parquet"))
 
 
462
 
463
+ if hub_out:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464
  from datasets import Dataset, Features, Image as ImageFeat, Sequence as SeqFeat, Value
465
 
466
  feats = Features({
467
+ "image": ImageFeat(), "image_id": Value("int64"), "source_id": Value("string"),
468
  "width": Value("int32"), "height": Value("int32"),
469
  "objects": {"bbox": SeqFeat(SeqFeat(Value("float32"))),
470
  "category": SeqFeat(Value("int64")),
 
472
  "rectangularity": SeqFeat(Value("float32"))},
473
  "n_instances": Value("int32"), "masks_rle": Value("string"),
474
  })
475
+ # Stream through an ArrowWriter: accumulating records in RAM OOMs whole-corpus
476
+ # runs, and the from_generator APIs pickle their callable, which this closure
477
+ # (live generator, loaded model) cannot survive. The writer flushes to disk per
478
+ # batch; from_file memory-maps the result back for the push.
479
+ import tempfile
480
+
481
+ from datasets.arrow_writer import ArrowWriter
482
+
483
+ arrow_path = os.path.join(tempfile.mkdtemp(prefix="falcon-out-"), "data.arrow")
484
+ with ArrowWriter(features=feats, path=arrow_path, writer_batch_size=100) as writer:
485
+ for rec in iter_records():
486
+ writer.write(feats.encode_example(rec))
487
+ writer.finalize()
488
+ ds = Dataset.from_file(arrow_path)
489
+ ds.push_to_hub(args.out, private=args.private)
490
+ push_card(args.out, args.query, counters)
491
+ if args.json:
492
+ print(json.dumps(json_rows, indent=2), flush=True)
493
+ else:
494
+ rows = [plain(r) for r in iter_records()]
495
+ if args.json:
496
+ print(json.dumps(rows, indent=2), flush=True)
497
+ if args.out and args.out.endswith(".json"):
498
+ pathlib.Path(args.out).write_text(json.dumps(rows, indent=2))
499
+ elif args.out and args.out.endswith(".jsonl"):
500
+ pathlib.Path(args.out).write_text("".join(json.dumps(r) + "\n" for r in rows))
501
+ elif args.out:
502
+ import pyarrow as pa
503
+ import pyarrow.parquet as pq
504
+
505
+ pq.write_table(pa.Table.from_pylist(rows), args.out, compression="zstd")
506
+
507
+ wall = time.perf_counter() - t0
508
+ n = counters["images"]
509
+ print(f"\n{n} images in {wall:.1f}s ({n / max(wall, 1e-9):.2f} img/s)", flush=True)
510
+ if args.out:
511
+ print(f"{counters['instances']} instances -> {args.out}", flush=True)
512
+ if hub_out:
513
  print(f"\nNEXT: validate-hf-dataset.py {args.out} --bbox-format yolo", flush=True)
514
 
515
 
review-detections.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env -S uv run --script
2
+ # /// script
3
+ # requires-python = ">=3.10"
4
+ # dependencies = [
5
+ # "gradio>=6,<7",
6
+ # "fastapi",
7
+ # "datasets>=4.5.0",
8
+ # "pillow",
9
+ # ]
10
+ # ///
11
+ """Human triage for a detection dataset -> an accept/reject verdict per image or per box.
12
+
13
+ A minimal keyboard-first review UI for datasets in THIS DIRECTORY'S schema
14
+ (yolo-normalized `objects.bbox` + `image`, `image_id`, `width`, `height` -- what
15
+ falcon-perception.py pushes; run convert-hf-dataset.py first for anything else).
16
+ Zero-shot teacher labels are suggestions, not ground truth: this is where a
17
+ human turns them into something you can quote. Runs locally, opens your
18
+ browser, journals every decision, pushes the reviewed rows back to the Hub.
19
+
20
+ # quick first pass: accept/reject whole images (A / R keys) on a random sample
21
+ uv run review-detections.py you/plates-illustrations --limit 200 \
22
+ --out you/plates-illustrations-reviewed
23
+
24
+ # detail pass: click boxes to reject them individually
25
+ uv run review-detections.py you/plates-illustrations --mode boxes \
26
+ --out you/plates-illustrations-reviewed
27
+
28
+ Modes:
29
+ quick whole-image verdict. A=accept R=reject M=accept-but-teacher-missed-something
30
+ F=finish arrows=skip/back. Defaults to RANDOM order, so the summary's
31
+ acceptance rate is an unbiased sample statistic you can quote.
32
+ boxes click a box to toggle it rejected; A keeps the rest, R rejects the whole
33
+ image (all boxes). Defaults to rectangularity-ASCENDING order (irregular
34
+ instances first) -- best use of effort, but a biased sample: the summary
35
+ says so and its rate should not be quoted.
36
+
37
+ Two numbers come out, measuring two different things: the ACCEPTANCE rate (are
38
+ the boxes that were drawn correct?) and the MISSED rate (how often did the
39
+ teacher skip an instance? -- the M key). Quote them separately; neither implies
40
+ the other.
41
+
42
+ The journal (default ./review-<dataset>-<split>.jsonl) is appended per decision
43
+ and tolerates a torn final line; re-running resumes at the first undecided image.
44
+ --out pushes decided rows with a `review` column ({verdict, missed, box_keep,
45
+ mode}) alongside the original schema.
46
+ """
47
+
48
+ import argparse
49
+ import io
50
+ import json
51
+ import os
52
+ import random
53
+ import signal
54
+ import threading
55
+
56
+ from fastapi.responses import HTMLResponse, Response
57
+
58
+ DISPLAY_W = 980
59
+
60
+ PAGE = """<!doctype html>
61
+ <title>review-detections</title>
62
+ <style>
63
+ body { margin:0; background:#181818; color:#ddd; font:14px system-ui; }
64
+ #bar { padding:8px 14px; display:flex; gap:18px; align-items:center; }
65
+ #bar b { color:#fff; } #keys { color:#888; margin-left:auto; }
66
+ #stage { position:relative; margin:0 auto; width:max-content; }
67
+ #img { display:block; }
68
+ .box { position:absolute; border:3px solid #ffd200; cursor:pointer; }
69
+ .box.rej { border-color:#f33; border-style:dashed; }
70
+ #flash { position:fixed; inset:0; display:none; align-items:center; justify-content:center;
71
+ font-size:80px; pointer-events:none; }
72
+ #err { display:none; padding:6px 14px; background:#611; color:#fbb; }
73
+ </style>
74
+ <div id=bar><b id=pos></b><span id=stats></span><span id=verdict></span><span id=keys></span></div>
75
+ <div id=err></div>
76
+ <div id=stage><img id=img><div id=boxes></div></div>
77
+ <div id=flash></div>
78
+ <script>
79
+ const MODE = "__MODE__"; // substituted by the server
80
+ document.getElementById("keys").textContent =
81
+ MODE === "quick" ? "A accept · R reject · M missed · ←/→ move · F finish"
82
+ : "click box = reject it · A accept rest · R reject all · M missed · ←/→ · F finish";
83
+ let idx = 0, meta = null, rejected = new Set();
84
+
85
+ async function load(i) {
86
+ const r = await fetch(`/meta/${i}`);
87
+ if (!r.ok) return;
88
+ meta = await r.json();
89
+ idx = meta.idx; rejected = new Set(meta.rejected_boxes);
90
+ document.getElementById("img").src = `/img/${idx}`;
91
+ document.getElementById("pos").textContent = `${idx + 1} / ${meta.total}`;
92
+ document.getElementById("stats").textContent = meta.stats;
93
+ document.getElementById("verdict").textContent = meta.verdict ? `decided: ${meta.verdict}` : "";
94
+ const holder = document.getElementById("boxes");
95
+ holder.innerHTML = "";
96
+ meta.boxes.forEach(([x0, y0, x1, y1], j) => {
97
+ const d = document.createElement("div");
98
+ d.className = "box" + (rejected.has(j) ? " rej" : "");
99
+ Object.assign(d.style, {left: x0 + "px", top: y0 + "px",
100
+ width: (x1 - x0) + "px", height: (y1 - y0) + "px"});
101
+ if (MODE === "boxes") d.onclick = () => { rejected.has(j) ? rejected.delete(j) : rejected.add(j);
102
+ d.classList.toggle("rej"); };
103
+ holder.appendChild(d);
104
+ });
105
+ }
106
+ function flash(t, c) {
107
+ const f = document.getElementById("flash");
108
+ f.textContent = t; f.style.color = c; f.style.display = "flex";
109
+ setTimeout(() => f.style.display = "none", 180);
110
+ }
111
+ async function decide(verdict, missed) {
112
+ if (!meta) return;
113
+ const box_keep = verdict === "reject" ? meta.boxes.map(() => false)
114
+ : meta.boxes.map((_, j) => !rejected.has(j));
115
+ const r = await fetch("/decide", {method: "POST", headers: {"Content-Type": "application/json"},
116
+ body: JSON.stringify({idx, verdict, missed, box_keep, mode: MODE})});
117
+ if (!r.ok) { // do NOT advance on failure -- the journal write did not happen
118
+ const e = document.getElementById("err");
119
+ e.textContent = `decision NOT saved (server error ${r.status}) — fix the problem and retry`;
120
+ e.style.display = "block";
121
+ return;
122
+ }
123
+ document.getElementById("err").style.display = "none";
124
+ flash(verdict === "accept" ? (missed ? "+?" : "✓") : "✗",
125
+ verdict === "accept" ? (missed ? "#fa3" : "#3c3") : "#f33");
126
+ load(idx + 1);
127
+ }
128
+ document.addEventListener("keydown", (e) => {
129
+ if (e.key === "ArrowRight") load(idx + 1);
130
+ else if (e.key === "ArrowLeft") load(idx - 1);
131
+ else if (e.key === "a" || e.key === "A") decide("accept", false);
132
+ else if (e.key === "r" || e.key === "R") decide("reject", false);
133
+ else if (e.key === "m" || e.key === "M") decide("accept", true);
134
+ else if (e.key === "f" || e.key === "F") {
135
+ fetch("/finish", {method: "POST"});
136
+ document.getElementById("keys").textContent = "finished — see the terminal; you can close this tab";
137
+ }
138
+ });
139
+ fetch("/start").then(r => r.json()).then(d => load(d.start));
140
+ </script>
141
+ """
142
+
143
+
144
+ def to_display_boxes(objects, width, height, scale):
145
+ out = []
146
+ for cx, cy, w, h in objects["bbox"]:
147
+ x0 = (cx - w / 2) * width * scale
148
+ y0 = (cy - h / 2) * height * scale
149
+ out.append([round(x0), round(y0), round(x0 + w * width * scale), round(y0 + h * height * scale)])
150
+ return out
151
+
152
+
153
+ def main():
154
+ p = argparse.ArgumentParser()
155
+ p.add_argument("dataset")
156
+ p.add_argument("--split", default="train")
157
+ p.add_argument("--mode", default="quick", choices=["quick", "boxes"])
158
+ p.add_argument("--order", default=None, choices=["random", "rect"],
159
+ help="default: random in quick mode (unbiased rate), rect in boxes mode")
160
+ p.add_argument("--limit", type=int, default=None)
161
+ p.add_argument("--seed", type=int, default=42)
162
+ p.add_argument("--journal", default=None,
163
+ help="default: ./review-<dataset>-<split>.jsonl (scoped so runs don't mix)")
164
+ p.add_argument("--out", default=None, help="Hub repo id for the reviewed dataset")
165
+ p.add_argument("--private", action="store_true")
166
+ p.add_argument("--port", type=int, default=7860)
167
+ args = p.parse_args()
168
+ order = args.order or ("random" if args.mode == "quick" else "rect")
169
+ journal_path = args.journal or f"./review-{args.dataset.replace('/', '--')}-{args.split}.jsonl"
170
+
171
+ from datasets import Sequence, Value, load_dataset
172
+
173
+ ds = load_dataset(args.dataset, split=args.split)
174
+
175
+ missing = [c for c in ("image", "image_id", "width", "height", "objects") if c not in ds.column_names]
176
+ if missing:
177
+ raise SystemExit(f"dataset is missing column(s) {missing} -- this tool reads the schema "
178
+ "falcon-perception.py pushes; see the docstring.")
179
+
180
+ # a lightweight view for sorting and sniffing that never decodes the image column
181
+ meta_rows = ds.select_columns(["objects"])[:]["objects"]
182
+ for objects in meta_rows[: min(50, len(meta_rows))]:
183
+ if any(not (0 <= v <= 1.5) for box in objects["bbox"] for v in box):
184
+ raise SystemExit("objects.bbox does not look yolo-normalized (values outside [0,1]) -- "
185
+ "run convert-hf-dataset.py --to yolo first.")
186
+
187
+ ids = list(range(len(ds)))
188
+ if order == "random":
189
+ random.Random(args.seed).shuffle(ids)
190
+ elif "rectangularity" not in meta_rows[0]:
191
+ print("no rectangularity column -- falling back to random order", flush=True)
192
+ random.Random(args.seed).shuffle(ids)
193
+ else:
194
+ ids.sort(key=lambda i: min(meta_rows[i]["rectangularity"]) if meta_rows[i]["rectangularity"] else 2.0)
195
+ if args.limit:
196
+ ids = ids[: args.limit]
197
+
198
+ # decisions are keyed by DATASET ROW INDEX -- image_id repeats across
199
+ # concatenated per-class runs, so it cannot key a decision
200
+ decisions = {}
201
+ if os.path.exists(journal_path):
202
+ with open(journal_path) as f:
203
+ for line in f:
204
+ line = line.strip()
205
+ if not line:
206
+ continue
207
+ try:
208
+ rec = json.loads(line)
209
+ except json.JSONDecodeError: # torn final line from a crash mid-append
210
+ print("journal: skipped one torn line (crash recovery)", flush=True)
211
+ continue
212
+ decisions[rec["row"]] = rec
213
+ print(f"resumed {len(decisions)} decisions from {journal_path}", flush=True)
214
+
215
+ img_cache = {}
216
+
217
+ def render(i):
218
+ if i not in img_cache:
219
+ im = ds[ids[i]]["image"].convert("RGB")
220
+ scale = min(DISPLAY_W / im.width, 1.0)
221
+ if scale < 1.0:
222
+ im = im.resize((round(im.width * scale), round(im.height * scale)))
223
+ buf = io.BytesIO()
224
+ im.save(buf, format="JPEG", quality=88)
225
+ img_cache[i] = (buf.getvalue(), scale)
226
+ if len(img_cache) > 32:
227
+ img_cache.pop(next(iter(img_cache)))
228
+ return img_cache[i]
229
+
230
+ def stats_line():
231
+ n = len(decisions)
232
+ if not n:
233
+ return ""
234
+ acc = sum(1 for d in decisions.values() if d["verdict"] == "accept")
235
+ mis = sum(1 for d in decisions.values() if d["missed"])
236
+ return f"{n} decided · {acc / n:.0%} accepted · {mis} missed-flagged"
237
+
238
+ import gradio as gr
239
+
240
+ app = gr.Server(title="review-detections")
241
+ done = threading.Event()
242
+
243
+ @app.get("/", response_class=HTMLResponse)
244
+ def page() -> str:
245
+ return PAGE.replace("__MODE__", args.mode)
246
+
247
+ @app.get("/start")
248
+ def start() -> dict:
249
+ first = next((i for i in range(len(ids)) if ids[i] not in decisions), 0)
250
+ return {"start": first}
251
+
252
+ @app.get("/img/{i}")
253
+ def img(i: int) -> Response:
254
+ if not 0 <= i < len(ids):
255
+ return Response(status_code=404)
256
+ return Response(content=render(i)[0], media_type="image/jpeg")
257
+
258
+ @app.get("/meta/{i}")
259
+ def meta(i: int) -> Response:
260
+ if not 0 <= i < len(ids):
261
+ return Response(status_code=404)
262
+ row = ds[ids[i]]
263
+ _, scale = render(i)
264
+ prior = decisions.get(ids[i])
265
+ payload = {
266
+ "idx": i, "total": len(ids),
267
+ "boxes": to_display_boxes(row["objects"], row["width"], row["height"], scale),
268
+ "verdict": prior["verdict"] if prior else None,
269
+ "rejected_boxes": [j for j, k in enumerate(prior["box_keep"]) if not k] if prior else [],
270
+ "stats": stats_line(),
271
+ }
272
+ return Response(content=json.dumps(payload), media_type="application/json")
273
+
274
+ @app.post("/decide")
275
+ def decide(body: dict) -> dict:
276
+ if not 0 <= body.get("idx", -1) < len(ids):
277
+ return Response(status_code=400)
278
+ row_idx = ids[body["idx"]]
279
+ rec = {
280
+ "row": row_idx, "image_id": ds[row_idx]["image_id"],
281
+ "dataset": args.dataset, "split": args.split,
282
+ "mode": body["mode"], "order": order, "verdict": body["verdict"],
283
+ "missed": bool(body.get("missed")), "box_keep": [bool(b) for b in body.get("box_keep", [])],
284
+ }
285
+ with open(journal_path, "a") as f: # journal FIRST -- only report saved if it is
286
+ f.write(json.dumps(rec) + "\n")
287
+ f.flush()
288
+ os.fsync(f.fileno())
289
+ decisions[row_idx] = rec
290
+ return {"n": len(decisions)}
291
+
292
+ @app.post("/finish")
293
+ def finish() -> dict:
294
+ done.set()
295
+ return {"ok": True}
296
+
297
+ print(f"open http://127.0.0.1:{args.port}/ (F in the browser, or Ctrl-C here, to finish)", flush=True)
298
+ app.launch(server_port=args.port, inbrowser=True, quiet=True, prevent_thread_lock=True)
299
+ signal.signal(signal.SIGINT, lambda *_: done.set()) # gradio installs its own handler; override AFTER launch
300
+ done.wait() # review happens in the browser
301
+ signal.signal(signal.SIGINT, signal.default_int_handler) # Ctrl-C must work again (e.g. to abort the push)
302
+
303
+ n = len(decisions)
304
+ if not n:
305
+ print("no decisions made", flush=True)
306
+ return
307
+ acc = sum(1 for d in decisions.values() if d["verdict"] == "accept")
308
+ mis = sum(1 for d in decisions.values() if d["missed"])
309
+ quotable = order == "random" and all(d["order"] == "random" for d in decisions.values())
310
+ print(f"\n{n} decided · {acc} accepted ({acc / n:.0%}) · {mis} with missed instances ({mis / n:.0%})",
311
+ flush=True)
312
+ print("acceptance rate is " + ("an unbiased random-order sample -- quotable"
313
+ if quotable else "from a non-random or mixed-order queue -- NOT quotable"),
314
+ flush=True)
315
+
316
+ if args.out:
317
+ rows = sorted(decisions)
318
+ reviewed = ds.select(rows)
319
+ feats = reviewed.features.copy()
320
+ feats["review"] = {"verdict": Value("string"), "missed": Value("bool"),
321
+ "mode": Value("string"), "box_keep": Sequence(Value("bool"))}
322
+ reviewed = reviewed.map(
323
+ lambda r, i: {"review": {k: decisions[rows[i]][k] for k in ("verdict", "missed", "mode", "box_keep")}},
324
+ with_indices=True, features=feats,
325
+ )
326
+ reviewed.push_to_hub(args.out, private=args.private)
327
+ print(f"{len(reviewed)} reviewed rows -> {args.out}", flush=True)
328
+
329
+
330
+ main()