Sync from GitHub via hub-sync
Browse files- README.md +4 -0
- SKILL.md +66 -13
- embed-bucket-images.py +233 -0
- falcon-perception-bucket.py +58 -18
- materialize-coco.py +228 -0
- render-detections.py +150 -0
- smoke-test.py +475 -0
README.md
CHANGED
|
@@ -39,6 +39,10 @@ That's it! The script will:
|
|
| 39 |
| `stats-hf-dataset.py` | Compute statistics (counts, label histogram, area, co-occurrence) |
|
| 40 |
| `diff-hf-datasets.py` | Compare two datasets semantically (IoU-based annotation matching) |
|
| 41 |
| `sample-hf-dataset.py` | Create subsets (random or stratified) and push to Hub |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
## Supported Bbox Formats
|
| 44 |
|
|
|
|
| 39 |
| `stats-hf-dataset.py` | Compute statistics (counts, label histogram, area, co-occurrence) |
|
| 40 |
| `diff-hf-datasets.py` | Compare two datasets semantically (IoU-based annotation matching) |
|
| 41 |
| `sample-hf-dataset.py` | Create subsets (random or stratified) and push to Hub |
|
| 42 |
+
| `embed-bucket-images.py` | Join image bytes back into a bucket teacher pass — gold excluded + asserted, one final-schema write |
|
| 43 |
+
| `materialize-coco.py` | Generate a canonical COCO 2017 directory tree from the parquet, in-job, on ephemeral disk |
|
| 44 |
+
| `render-detections.py` | Render box/mask overlays and pixel-verify they actually drew (blank renders exit nonzero) |
|
| 45 |
+
| `smoke-test.py` | Free local check (~30 s) that the plumbing chain (`embed-bucket-images.py` → `materialize-coco.py` → `render-detections.py`) still produces correct output — run before any job depends on it |
|
| 46 |
|
| 47 |
## Supported Bbox Formats
|
| 48 |
|
SKILL.md
CHANGED
|
@@ -10,17 +10,38 @@ 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
|
| 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 — quick mode for
|
| 22 |
whole-image verdicts in random order with quotable rates, boxes mode for per-box rejects; pushes a
|
| 23 |
-
`review` column), fold corrections in and retrain
|
| 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.
|
|
@@ -49,7 +70,9 @@ hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \
|
|
| 49 |
|
| 50 |
Judge the result before scaling up:
|
| 51 |
- **If you can view images**, look at the rendered previews (or the pushed check dataset) — are the
|
| 52 |
-
right things boxed?
|
|
|
|
|
|
|
| 53 |
- **If you can't**, compare instance counts across candidate queries (`stats-hf-dataset.py` below works
|
| 54 |
on a pushed check dataset): near-zero instances/image means the class name is wrong for this material —
|
| 55 |
try a synonym (`photograph` / `illustration` / `figure` / `cartoon`). Suspiciously many (more than about 10/image)
|
|
@@ -77,6 +100,9 @@ hf jobs uv run --flavor a10g-large --secrets HF_TOKEN --timeout 2h \
|
|
| 77 |
--dataset <USER>/<IMAGES> --query photograph --out <USER>/<NAME>-photograph --private
|
| 78 |
```
|
| 79 |
|
|
|
|
|
|
|
|
|
|
| 80 |
- Flavor rule (all three failures measured): the engine needs a **24 GB-VRAM GPU** (16 GB T4s
|
| 81 |
CUDA-OOM during prefill) and **more than 15 GB host RAM** (the engine sizes itself from the GPU
|
| 82 |
and ignores host RAM, so `t4-small` and `a10g-small` are OOMKilled before the first image).
|
|
@@ -121,7 +147,8 @@ hf jobs uv run --flavor a10g-large --secrets HF_TOKEN --timeout 2h \
|
|
| 121 |
switch (`hf jobs hardware` for alternatives), cancel the queued copy first (`hf jobs cancel <id>`).
|
| 122 |
- For images in a [storage bucket](https://huggingface.co/docs/hub/storage-buckets) instead of a
|
| 123 |
dataset, use `falcon-perception-bucket.py` — it writes resumable parquet parts back to a bucket
|
| 124 |
-
(kill and re-run the same command; done keys are skipped)
|
|
|
|
| 125 |
|
| 126 |
```
|
| 127 |
hf jobs uv run --flavor a10g-large --secrets HF_TOKEN --timeout 2h --detach \
|
|
@@ -134,14 +161,26 @@ hf jobs uv run --flavor a10g-large --secrets HF_TOKEN --timeout 2h \
|
|
| 134 |
bare ints; the cast attaches the class name):
|
| 135 |
|
| 136 |
```python
|
| 137 |
-
from datasets import ClassLabel, Sequence, load_dataset
|
| 138 |
ds = load_dataset("parquet", data_files="hf://buckets/<namespace>/<out-bucket>/part-*.parquet",
|
| 139 |
split="train")
|
| 140 |
feats = ds.features.copy()
|
| 141 |
feats["objects"]["category"] = Sequence(ClassLabel(names=[ds[0]["query"]]))
|
|
|
|
|
|
|
| 142 |
ds.cast(feats).push_to_hub("<namespace>/<dataset>")
|
| 143 |
```
|
| 144 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
## 3. Validate the labels (free, local)
|
| 146 |
|
| 147 |
```
|
|
@@ -151,8 +190,10 @@ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/stat
|
|
| 151 |
<USER>/<NAME>-photograph --bbox-format yolo
|
| 152 |
```
|
| 153 |
|
| 154 |
-
Expect **VALID** with 0 out-of-bounds and 0 zero-area boxes. `W001` warnings on empty images are normal
|
| 155 |
-
|
|
|
|
|
|
|
| 156 |
Drop obvious junk before training: degenerate slivers (extreme aspect ratio + tiny area) and near-duplicate
|
| 157 |
boxes (IoU > 0.9 within one image).
|
| 158 |
|
|
@@ -170,7 +211,7 @@ uv run https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/conv
|
|
| 170 |
A known-good default: fine-tune
|
| 171 |
[`ustc-community/dfine-small-coco`](https://huggingface.co/ustc-community/dfine-small-coco)
|
| 172 |
(D-FINE small, 10.4M params, Apache-2.0, in `transformers`) on the step-4 COCO dataset —
|
| 173 |
-
800 images, 30 epochs, `t4-medium`, about 48
|
| 174 |
step 2's 24 GB-VRAM rule is the teacher's engine, not the student's.
|
| 175 |
|
| 176 |
The [**`huggingface-vision-trainer`**](https://github.com/huggingface/skills/tree/main/skills/huggingface-vision-trainer)
|
|
@@ -178,7 +219,9 @@ skill runs the training end to end (dataset validation,
|
|
| 178 |
augmentation, mAP eval, Hub persistence) — install it with `hf skills add huggingface-vision-trainer`
|
| 179 |
if you don't have it, and follow its object-detection path with the `<USER>/<NAME>-coco` dataset and
|
| 180 |
the settings above. Hold out the validation split — and the step-6 gold slice — BEFORE training,
|
| 181 |
-
and never train on either.
|
|
|
|
|
|
|
| 182 |
|
| 183 |
Other trainers work — the dataset is plain COCO. [RT-DETRv2](https://huggingface.co/PekingU/rtdetr_v2_r18vd)
|
| 184 |
is a comparable compact Apache-2.0 pick; [RF-DETR](https://github.com/roboflow/rf-detr) (Apache-2.0,
|
|
@@ -207,7 +250,10 @@ for rle in json.loads(row["masks_rle"]):
|
|
| 207 |
- Report mAP on the held-out slice. Be clear about what it measures: **agreement with the teacher**,
|
| 208 |
not accuracy against human truth — no human labels exist in this loop unless you make some (next
|
| 209 |
bullet).
|
| 210 |
-
- **Gold slice** (with a human in the loop): hold out about 100 random images BEFORE training
|
|
|
|
|
|
|
|
|
|
| 211 |
the human verify every box on them with `review-detections.py --mode boxes --order random`, then
|
| 212 |
correct any misses (the tool flags them with M; drawing the missing boxes is manual for now).
|
| 213 |
Then report TWO numbers: mAP vs teacher labels AND mAP vs the human gold. They
|
|
@@ -226,12 +272,19 @@ for rle in json.loads(row["masks_rle"]):
|
|
| 226 |
cannot view images, state prominently in the report that the model is **unreviewed**.
|
| 227 |
- It can make sense to run this process in a loop: predict → review (a human, or a vision-capable
|
| 228 |
agent, via `review-detections.py`) → retrain on the corrections → review again, until the acceptance
|
| 229 |
-
rate stops improving.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
## 7. Publish with honest provenance
|
| 232 |
|
| 233 |
Push the model and dataset — ask the user whether public or private; if you can't ask, default to
|
| 234 |
-
private and say so.
|
|
|
|
|
|
|
|
|
|
| 235 |
(name the script + date), which filters ran, and that **recall is unmeasured** unless you measured it
|
| 236 |
against an independent source. Say what the model is for and what it was trained on. A model trained
|
| 237 |
this way is a first pass. The review loop above is how it gets better.
|
|
|
|
| 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 |
+
## Pick your path
|
| 14 |
+
|
| 15 |
+
Five decisions cover most runs; each routes into the numbered steps below.
|
| 16 |
+
|
| 17 |
+
1. **Where are the images?** Dataset repo → `falcon-perception.py`. Bucket → `falcon-perception-bucket.py`
|
| 18 |
+
(reads `.jpg`/`.jpeg`/`.png` only — convert JPEG 2000 / TIFF first).
|
| 19 |
+
2. **Transport to the trainer**: build canonical `train.parquet` / `validation.parquet` with
|
| 20 |
+
`embed-bucket-images.py` (images embedded, gold excluded and asserted). Trainers that take HF
|
| 21 |
+
datasets read the parquet directly — including straight off a bucket; trainers that want a COCO
|
| 22 |
+
directory tree get one **generated in-job** with `materialize-coco.py` — onto a bucket mount if
|
| 23 |
+
more than one job will train on it (a complete tree is reused, not rebuilt). Never hand-assemble
|
| 24 |
+
or upload directory trees: a tree generated from the parquet cannot have missing-image
|
| 25 |
+
mismatches. Run `smoke-test.py` first (free, local, ~30 s): it proves these plumbing scripts
|
| 26 |
+
still produce correct output before a paid job depends on them.
|
| 27 |
+
3. **Boxes or masks?** Boxes → the D-FINE default in step 5. Masks → an RF-DETR-Seg-style trainer via
|
| 28 |
+
`materialize-coco.py` (RLE masks carried through and resized from the teacher's inference frame to the
|
| 29 |
+
image frame).
|
| 30 |
+
4. **Human available?** Show step-1 previews and do the step-6 gold slice. Headless → numeric proxies
|
| 31 |
+
and say **unreviewed**.
|
| 32 |
+
5. **After the first student**: run the step-6 loop — student over the teacher-empty pages at a low
|
| 33 |
+
threshold, VLM pre-triage, retrain on the corrections.
|
| 34 |
+
|
| 35 |
## Check if a human in the loop
|
| 36 |
|
| 37 |
You can use the approach outlined in this skill with or without a human in the loop.
|
| 38 |
|
| 39 |
- **With a human in the loop** (better models): show them the step-1 previews — "is the teacher boxing
|
| 40 |
+
the right things?" is the highest-value question, and its fix is the cheapest (a better query and a re-run of the teacher). Then train on a small slice first (500–1k images) and show 20 rendered
|
|
|
|
| 41 |
predictions before spending on the full corpus. If corrections are worth collecting at volume, run a
|
| 42 |
review pass with `review-detections.py` (keyboard accept/reject in the browser — quick mode for
|
| 43 |
whole-image verdicts in random order with quotable rates, boxes mode for per-box rejects; pushes a
|
| 44 |
+
`review` column), fold corrections in and retrain. Diff the corrected set against the first pass (`diff-hf-datasets.py`) to measure how
|
| 45 |
good the zero-shot pass actually was.
|
| 46 |
- **Autonomously** (headless): don't pause for review — use the numeric proxies, and say **unreviewed**
|
| 47 |
in the final report and model card.
|
|
|
|
| 70 |
|
| 71 |
Judge the result before scaling up:
|
| 72 |
- **If you can view images**, look at the rendered previews (or the pushed check dataset) — are the
|
| 73 |
+
right things boxed? `render-detections.py` renders any dataset in this schema and **pixel-verifies
|
| 74 |
+
its own output** (a page with instances whose render equals the source exits nonzero — silent
|
| 75 |
+
blank-overlay bugs are real and have been shown to humans as "done").
|
| 76 |
- **If you can't**, compare instance counts across candidate queries (`stats-hf-dataset.py` below works
|
| 77 |
on a pushed check dataset): near-zero instances/image means the class name is wrong for this material —
|
| 78 |
try a synonym (`photograph` / `illustration` / `figure` / `cartoon`). Suspiciously many (more than about 10/image)
|
|
|
|
| 100 |
--dataset <USER>/<IMAGES> --query photograph --out <USER>/<NAME>-photograph --private
|
| 101 |
```
|
| 102 |
|
| 103 |
+
- Sizing: expect a few images per second, not tens — the pass is decode-bound, so a bigger GPU
|
| 104 |
+
changes little; to go faster, shard the file list across several jobs writing to the same output
|
| 105 |
+
bucket. `--limit` on either script caps a run.
|
| 106 |
- Flavor rule (all three failures measured): the engine needs a **24 GB-VRAM GPU** (16 GB T4s
|
| 107 |
CUDA-OOM during prefill) and **more than 15 GB host RAM** (the engine sizes itself from the GPU
|
| 108 |
and ignores host RAM, so `t4-small` and `a10g-small` are OOMKilled before the first image).
|
|
|
|
| 147 |
switch (`hf jobs hardware` for alternatives), cancel the queued copy first (`hf jobs cancel <id>`).
|
| 148 |
- For images in a [storage bucket](https://huggingface.co/docs/hub/storage-buckets) instead of a
|
| 149 |
dataset, use `falcon-perception-bucket.py` — it writes resumable parquet parts back to a bucket
|
| 150 |
+
(kill and re-run the same command; done keys are skipped). It reads `.jpg` / `.jpeg` / `.png` only —
|
| 151 |
+
convert JPEG 2000 or TIFF scans first, or it will silently find zero images:
|
| 152 |
|
| 153 |
```
|
| 154 |
hf jobs uv run --flavor a10g-large --secrets HF_TOKEN --timeout 2h --detach \
|
|
|
|
| 161 |
bare ints; the cast attaches the class name):
|
| 162 |
|
| 163 |
```python
|
| 164 |
+
from datasets import ClassLabel, Image, Sequence, load_dataset
|
| 165 |
ds = load_dataset("parquet", data_files="hf://buckets/<namespace>/<out-bucket>/part-*.parquet",
|
| 166 |
split="train")
|
| 167 |
feats = ds.features.copy()
|
| 168 |
feats["objects"]["category"] = Sequence(ClassLabel(names=[ds[0]["query"]]))
|
| 169 |
+
if "image" in feats: # parts written with --embed-images: make the bytes a decodable Image column
|
| 170 |
+
feats["image"] = Image()
|
| 171 |
ds.cast(feats).push_to_hub("<namespace>/<dataset>")
|
| 172 |
```
|
| 173 |
|
| 174 |
+
The bucket path's output is **annotations-only** by default — there is no `image` column, and the
|
| 175 |
+
step-5 trainer and `review-detections.py` both need embedded images. `embed-bucket-images.py` (same
|
| 176 |
+
repo) joins the bytes back in, drops the teacher's error rows, excludes and asserts the gold slice,
|
| 177 |
+
splits train/validation, and writes the final schema exactly once — to a dataset repo, or as `train.parquet`/`validation.parquet`
|
| 178 |
+
in a bucket. (`--embed-images` on the teacher pass writes the bytes into the parts instead — storage
|
| 179 |
+
is cheap, and the join step then skips its re-fetch; the cost is a copy of the corpus in the output
|
| 180 |
+
bucket.) Trainers that want a COCO directory tree get one generated from that parquet by
|
| 181 |
+
`materialize-coco.py` — once, onto a bucket mount if several jobs will train on it — never
|
| 182 |
+
hand-assemble or upload directory trees.
|
| 183 |
+
|
| 184 |
## 3. Validate the labels (free, local)
|
| 185 |
|
| 186 |
```
|
|
|
|
| 190 |
<USER>/<NAME>-photograph --bbox-format yolo
|
| 191 |
```
|
| 192 |
|
| 193 |
+
Expect **VALID** with 0 out-of-bounds and 0 zero-area boxes. `W001` warnings on empty images are normal
|
| 194 |
+
and worth keeping as training signal — but treat them as **unverified negatives**: zero-shot teachers
|
| 195 |
+
miss real instances on a meaningful fraction of "empty" pages (a third, on one measured corpus). The
|
| 196 |
+
step-6 loop is how you find and flip them.
|
| 197 |
Drop obvious junk before training: degenerate slivers (extreme aspect ratio + tiny area) and near-duplicate
|
| 198 |
boxes (IoU > 0.9 within one image).
|
| 199 |
|
|
|
|
| 211 |
A known-good default: fine-tune
|
| 212 |
[`ustc-community/dfine-small-coco`](https://huggingface.co/ustc-community/dfine-small-coco)
|
| 213 |
(D-FINE small, 10.4M params, Apache-2.0, in `transformers`) on the step-4 COCO dataset —
|
| 214 |
+
800 images, 30 epochs, `t4-medium`, about 48 minutes (`hf jobs hardware` shows current prices). Training needs only a T4:
|
| 215 |
step 2's 24 GB-VRAM rule is the teacher's engine, not the student's.
|
| 216 |
|
| 217 |
The [**`huggingface-vision-trainer`**](https://github.com/huggingface/skills/tree/main/skills/huggingface-vision-trainer)
|
|
|
|
| 219 |
augmentation, mAP eval, Hub persistence) — install it with `hf skills add huggingface-vision-trainer`
|
| 220 |
if you don't have it, and follow its object-detection path with the `<USER>/<NAME>-coco` dataset and
|
| 221 |
the settings above. Hold out the validation split — and the step-6 gold slice — BEFORE training,
|
| 222 |
+
and never train on either. Write checkpoints **continuously to the synced `/data` mount**, not `/tmp`
|
| 223 |
+
or a local output dir: Jobs can be SIGTERM'd at any time (node reclaim, requeue), anything outside the
|
| 224 |
+
mount dies with the job, and durable checkpoints are also what make stopping at a plateau safe.
|
| 225 |
|
| 226 |
Other trainers work — the dataset is plain COCO. [RT-DETRv2](https://huggingface.co/PekingU/rtdetr_v2_r18vd)
|
| 227 |
is a comparable compact Apache-2.0 pick; [RF-DETR](https://github.com/roboflow/rf-detr) (Apache-2.0,
|
|
|
|
| 250 |
- Report mAP on the held-out slice. Be clear about what it measures: **agreement with the teacher**,
|
| 251 |
not accuracy against human truth — no human labels exist in this loop unless you make some (next
|
| 252 |
bullet).
|
| 253 |
+
- **Gold slice** (with a human in the loop): hold out about 100 random images BEFORE training — keyed
|
| 254 |
+
on a **stable image id** that is identical in every dataset you build (path prefixes from different
|
| 255 |
+
runs silently break the match) — and **assert the exclusion** before submitting any training job:
|
| 256 |
+
train count = total − gold, overlap = 0. Then have
|
| 257 |
the human verify every box on them with `review-detections.py --mode boxes --order random`, then
|
| 258 |
correct any misses (the tool flags them with M; drawing the missing boxes is manual for now).
|
| 259 |
Then report TWO numbers: mAP vs teacher labels AND mAP vs the human gold. They
|
|
|
|
| 272 |
cannot view images, state prominently in the report that the model is **unreviewed**.
|
| 273 |
- It can make sense to run this process in a loop: predict → review (a human, or a vision-capable
|
| 274 |
agent, via `review-detections.py`) → retrain on the corrections → review again, until the acceptance
|
| 275 |
+
rate stops improving. Two things make the loop cheap: point the student at the **teacher-empty pages
|
| 276 |
+
at a low threshold** first (that is where the teacher's false negatives concentrate, and flipping
|
| 277 |
+
them from negative to positive is the biggest training-signal win), and **pre-triage candidates with
|
| 278 |
+
a VLM judge** (one crop per instance, mask highlighted) so the human only reviews the uncertain
|
| 279 |
+
residue rather than every candidate.
|
| 280 |
|
| 281 |
## 7. Publish with honest provenance
|
| 282 |
|
| 283 |
Push the model and dataset — ask the user whether public or private; if you can't ask, default to
|
| 284 |
+
private and say so. Build each dataset's **final schema in memory and push once** — never stage an
|
| 285 |
+
intermediate push to the repo you will publish. A second push with different columns leaves the repo's
|
| 286 |
+
stored features stale and `load_dataset` fails with a cast error; if the schema must change, push to a
|
| 287 |
+
new repo id. The cards must state: labels are **zero-shot weak labels** from Falcon-Perception
|
| 288 |
(name the script + date), which filters ran, and that **recall is unmeasured** unless you measured it
|
| 289 |
against an independent source. Say what the model is for and what it was trained on. A model trained
|
| 290 |
this way is a first pass. The review loop above is how it gets better.
|
embed-bucket-images.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env -S uv run --script
|
| 2 |
+
# /// script
|
| 3 |
+
# requires-python = ">=3.10"
|
| 4 |
+
# dependencies = [
|
| 5 |
+
# "datasets>=4.0",
|
| 6 |
+
# "huggingface_hub>=1.27", # hf://buckets in HfFileSystem (1.6) + prefix-collision fix (1.27)
|
| 7 |
+
# "pillow", # datasets encodes Image examples through PIL in the generator path
|
| 8 |
+
# "pyarrow>=18",
|
| 9 |
+
# ]
|
| 10 |
+
# ///
|
| 11 |
+
"""Build the canonical training parquet from a bucket teacher pass -> ONE final-schema push.
|
| 12 |
+
|
| 13 |
+
Takes the parquet parts that falcon-perception-bucket.py wrote, joins the image bytes back in
|
| 14 |
+
from the source bucket (skipped when the parts already carry an `image` column, i.e. the teacher
|
| 15 |
+
ran with --embed-images), excludes (and ASSERTS the exclusion of) a gold slice, splits
|
| 16 |
+
train/validation, and writes everything in a single final-schema write -- either to a dataset
|
| 17 |
+
repo (one push_to_hub, never a second) or as train.parquet / validation.parquet in a bucket for
|
| 18 |
+
`materialize-coco.py` / direct `load_dataset` use.
|
| 19 |
+
|
| 20 |
+
Image bytes are fetched in chunks through a dataset generator, so RAM stays bounded to one
|
| 21 |
+
chunk (--chunk, default 256 images) however large the corpus is; the Arrow cache on disk holds
|
| 22 |
+
the rest.
|
| 23 |
+
|
| 24 |
+
uv run embed-bucket-images.py \\
|
| 25 |
+
--parts "hf://buckets/<ns>/<teacher-out>/part-*.parquet" \\
|
| 26 |
+
--src <ns>/<source-bucket> \\
|
| 27 |
+
--gold <ns>/<gold-dataset> \\
|
| 28 |
+
--out <ns>/<training-dataset> --private
|
| 29 |
+
|
| 30 |
+
# bucket output instead of a dataset repo:
|
| 31 |
+
... --out hf://buckets/<ns>/<training-bucket>/dataset
|
| 32 |
+
|
| 33 |
+
# local everything (smoke tests, a laptop-sized corpus): --src is a directory holding the
|
| 34 |
+
# keys as relative paths, --out an absolute or ./relative directory
|
| 35 |
+
... --parts "./parts/part-*.parquet" --src ./pages --gold ./gold.parquet --out ./dataset
|
| 36 |
+
|
| 37 |
+
Why this exists (both failure modes measured): the bucket path's output has no image column
|
| 38 |
+
by default, so every agent hand-writes this join; and staging an intermediate push then
|
| 39 |
+
re-pushing a different schema to the same repo id leaves stale repo features ->
|
| 40 |
+
load_dataset CastError. This script builds the final schema in memory and writes exactly once.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
import argparse
|
| 44 |
+
import subprocess
|
| 45 |
+
import tempfile
|
| 46 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 47 |
+
from pathlib import Path
|
| 48 |
+
|
| 49 |
+
import fsspec
|
| 50 |
+
from datasets import ClassLabel, Dataset, DatasetDict, Image, Sequence, load_dataset
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def is_local_path(s):
|
| 54 |
+
# explicit prefixes only: a repo id like ns/name must never be mistaken for a directory
|
| 55 |
+
# that happens to exist in the cwd
|
| 56 |
+
return s.startswith(("/", "./", "../", "~"))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def main():
|
| 60 |
+
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
| 61 |
+
p.add_argument(
|
| 62 |
+
"--parts",
|
| 63 |
+
required=True,
|
| 64 |
+
help='parquet glob, e.g. "hf://buckets/ns/out/part-*.parquet" (or a local glob)',
|
| 65 |
+
)
|
| 66 |
+
p.add_argument(
|
| 67 |
+
"--src",
|
| 68 |
+
default=None,
|
| 69 |
+
help="source image bucket, e.g. ns/pages (keys = __source_key), or a local directory; "
|
| 70 |
+
"not needed when the parts already carry an image column",
|
| 71 |
+
)
|
| 72 |
+
p.add_argument(
|
| 73 |
+
"--out",
|
| 74 |
+
required=True,
|
| 75 |
+
help="dataset repo id, hf://buckets/... prefix, or a local directory for parquet files",
|
| 76 |
+
)
|
| 77 |
+
p.add_argument(
|
| 78 |
+
"--gold",
|
| 79 |
+
default=None,
|
| 80 |
+
help="gold dataset repo id (or parquet glob / local path) to exclude, by image_id",
|
| 81 |
+
)
|
| 82 |
+
p.add_argument("--val-frac", type=float, default=0.1)
|
| 83 |
+
p.add_argument("--seed", type=int, default=42)
|
| 84 |
+
p.add_argument(
|
| 85 |
+
"--limit", type=int, default=None, help="debug: cap rows AFTER gold exclusion"
|
| 86 |
+
)
|
| 87 |
+
p.add_argument(
|
| 88 |
+
"--keep-errors",
|
| 89 |
+
action="store_true",
|
| 90 |
+
help="keep rows whose teacher pass errored (dropped by default: they have no usable image)",
|
| 91 |
+
)
|
| 92 |
+
p.add_argument(
|
| 93 |
+
"--allow-gold-disjoint",
|
| 94 |
+
action="store_true",
|
| 95 |
+
help="permit a gold set that shares no image_id with this corpus (a genuinely different corpus)",
|
| 96 |
+
)
|
| 97 |
+
p.add_argument("--workers", type=int, default=16)
|
| 98 |
+
p.add_argument(
|
| 99 |
+
"--chunk", type=int, default=256, help="images fetched per generator chunk"
|
| 100 |
+
)
|
| 101 |
+
p.add_argument("--private", action="store_true")
|
| 102 |
+
args = p.parse_args()
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
ds = load_dataset("parquet", data_files=args.parts, split="train")
|
| 106 |
+
except FileNotFoundError:
|
| 107 |
+
raise SystemExit(
|
| 108 |
+
f"no parquet files match {args.parts!r} — check the glob and bucket path"
|
| 109 |
+
)
|
| 110 |
+
total = len(ds)
|
| 111 |
+
if total == 0:
|
| 112 |
+
raise SystemExit(f"{args.parts!r} matched files but they contain 0 rows")
|
| 113 |
+
if args.src and args.src.startswith("hf://buckets/"):
|
| 114 |
+
args.src = args.src[len("hf://buckets/") :]
|
| 115 |
+
if (
|
| 116 |
+
not (args.out.startswith("hf://buckets/") or is_local_path(args.out))
|
| 117 |
+
and "/" not in args.out
|
| 118 |
+
):
|
| 119 |
+
raise SystemExit(
|
| 120 |
+
f"--out {args.out!r}: a dataset repo id needs a namespace (ns/name)"
|
| 121 |
+
)
|
| 122 |
+
if "error" in ds.column_names and not args.keep_errors:
|
| 123 |
+
n_err = sum(1 for e in ds["error"] if e)
|
| 124 |
+
if n_err:
|
| 125 |
+
ds = ds.filter(lambda r: not r["error"])
|
| 126 |
+
print(f"dropped {n_err} teacher error rows (--keep-errors to keep them)")
|
| 127 |
+
if not isinstance(ds.features["objects"]["category"].feature, ClassLabel):
|
| 128 |
+
feats = ds.features.copy()
|
| 129 |
+
feats["objects"]["category"] = Sequence(ClassLabel(names=[ds[0]["query"]]))
|
| 130 |
+
ds = ds.cast(feats)
|
| 131 |
+
|
| 132 |
+
# ---- gold exclusion, asserted on the stable image_id (never on path-shaped keys) ----
|
| 133 |
+
if args.gold:
|
| 134 |
+
if "://" in args.gold or is_local_path(args.gold):
|
| 135 |
+
gold = load_dataset("parquet", data_files=args.gold, split="train")
|
| 136 |
+
else:
|
| 137 |
+
gold = load_dataset(args.gold, split="train")
|
| 138 |
+
gold_ids = set(gold["image_id"])
|
| 139 |
+
before = len(ds)
|
| 140 |
+
ds = ds.filter(lambda r: r["image_id"] not in gold_ids)
|
| 141 |
+
removed = before - len(ds)
|
| 142 |
+
overlap = gold_ids & set(ds["image_id"])
|
| 143 |
+
assert not overlap, (
|
| 144 |
+
f"gold exclusion FAILED: {len(overlap)} gold ids remain, e.g. {sorted(overlap)[:3]}"
|
| 145 |
+
)
|
| 146 |
+
if removed == 0 and gold_ids and not args.allow_gold_disjoint:
|
| 147 |
+
raise SystemExit(
|
| 148 |
+
"gold exclusion matched 0 rows — the gold set and this corpus share no image_id. "
|
| 149 |
+
"That usually means the ids were built from different key prefixes. If this corpus "
|
| 150 |
+
"really is disjoint from the gold set, pass --allow-gold-disjoint."
|
| 151 |
+
)
|
| 152 |
+
print(f"gold: excluded {removed} rows; {len(gold_ids)} gold ids, overlap now 0")
|
| 153 |
+
|
| 154 |
+
if args.limit:
|
| 155 |
+
ds = ds.select(range(min(args.limit, len(ds))))
|
| 156 |
+
|
| 157 |
+
# ---- join image bytes back in from the source (unless the parts already carry them) ----
|
| 158 |
+
if "image" in ds.column_names:
|
| 159 |
+
print(
|
| 160 |
+
"parts already carry an image column (teacher ran with --embed-images) — no fetch"
|
| 161 |
+
)
|
| 162 |
+
ds = ds.cast_column("image", Image())
|
| 163 |
+
else:
|
| 164 |
+
if not args.src:
|
| 165 |
+
raise SystemExit(
|
| 166 |
+
"parts have no image column — pass --src <bucket or local dir>"
|
| 167 |
+
)
|
| 168 |
+
src_dir = Path(args.src).expanduser() if is_local_path(args.src) else None
|
| 169 |
+
|
| 170 |
+
def fetch(key):
|
| 171 |
+
if src_dir is not None:
|
| 172 |
+
return (src_dir / key).read_bytes()
|
| 173 |
+
with fsspec.open(f"hf://buckets/{args.src}/{key}", "rb") as f:
|
| 174 |
+
return f.read()
|
| 175 |
+
|
| 176 |
+
plain = ds.with_format(None)
|
| 177 |
+
features = plain.features.copy()
|
| 178 |
+
features["image"] = Image()
|
| 179 |
+
|
| 180 |
+
def rows_with_images():
|
| 181 |
+
# one chunk of bytes in RAM at a time; datasets streams the yielded rows to
|
| 182 |
+
# its Arrow cache on disk, so corpus size never sets the RAM ceiling
|
| 183 |
+
for start in range(0, len(plain), args.chunk):
|
| 184 |
+
chunk = plain[start : start + args.chunk] # dict of column -> list
|
| 185 |
+
keys = chunk["__source_key"]
|
| 186 |
+
with ThreadPoolExecutor(args.workers) as ex:
|
| 187 |
+
blobs = list(ex.map(fetch, keys))
|
| 188 |
+
bad = [k for k, b in zip(keys, blobs) if not b]
|
| 189 |
+
assert not bad, f"{len(bad)} images fetched empty, e.g. {bad[:3]}"
|
| 190 |
+
for i, blob in enumerate(blobs):
|
| 191 |
+
row = {col: chunk[col][i] for col in chunk}
|
| 192 |
+
row["image"] = {"bytes": blob, "path": None}
|
| 193 |
+
yield row
|
| 194 |
+
|
| 195 |
+
ds = Dataset.from_generator(rows_with_images, features=features)
|
| 196 |
+
|
| 197 |
+
# ---- split, then ONE write ----
|
| 198 |
+
if args.val_frac <= 0 or len(ds) < 2:
|
| 199 |
+
out = DatasetDict({"train": ds})
|
| 200 |
+
print(
|
| 201 |
+
f"rows: {total} read -> {len(ds)} kept -> train only (no validation split; "
|
| 202 |
+
"materialize-coco.py then needs --splits train)"
|
| 203 |
+
)
|
| 204 |
+
else:
|
| 205 |
+
parts = ds.train_test_split(test_size=args.val_frac, seed=args.seed)
|
| 206 |
+
out = DatasetDict({"train": parts["train"], "validation": parts["test"]})
|
| 207 |
+
print(
|
| 208 |
+
f"rows: {total} read -> {len(ds)} kept -> train {len(out['train'])} / validation {len(out['validation'])}"
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
if args.out.startswith("hf://buckets/"):
|
| 212 |
+
with tempfile.TemporaryDirectory() as td:
|
| 213 |
+
for split, d in out.items():
|
| 214 |
+
local = Path(td) / f"{split}.parquet"
|
| 215 |
+
d.to_parquet(local)
|
| 216 |
+
subprocess.run(
|
| 217 |
+
["hf", "cp", str(local), f"{args.out.rstrip('/')}/{split}.parquet"],
|
| 218 |
+
check=True,
|
| 219 |
+
)
|
| 220 |
+
print(f"wrote {' + '.join(f'{s}.parquet' for s in out)} -> {args.out}")
|
| 221 |
+
elif is_local_path(args.out):
|
| 222 |
+
out_dir = Path(args.out).expanduser()
|
| 223 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 224 |
+
for split, d in out.items():
|
| 225 |
+
d.to_parquet(out_dir / f"{split}.parquet")
|
| 226 |
+
print(f"wrote {' + '.join(f'{s}.parquet' for s in out)} -> {out_dir}")
|
| 227 |
+
else:
|
| 228 |
+
out.push_to_hub(args.out, private=args.private)
|
| 229 |
+
print(f"pushed -> https://huggingface.co/datasets/{args.out}")
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
if __name__ == "__main__":
|
| 233 |
+
main()
|
falcon-perception-bucket.py
CHANGED
|
@@ -4,7 +4,7 @@
|
|
| 4 |
# dependencies = [
|
| 5 |
# "falcon-perception>=1.0.0",
|
| 6 |
# # tarball not git+: some GPU images have no `git` for uv to shell out to
|
| 7 |
-
# "bucketbag @ https://github.com/davanstrien/bucketbag/archive/refs/tags/v0.3.
|
| 8 |
# "pyarrow>=18",
|
| 9 |
# "pycocotools>=2.0.11",
|
| 10 |
# ]
|
|
@@ -26,18 +26,22 @@ Output is parquet parts in a BUCKET, not a dataset repo — that is what makes t
|
|
| 26 |
run resumable (`completed_keys` reads the done-set back from `__source_key`).
|
| 27 |
To hand the result to the rest of this directory, publish it once at the end:
|
| 28 |
|
| 29 |
-
from datasets import ClassLabel, Sequence, load_dataset
|
| 30 |
ds = load_dataset("parquet", data_files="hf://buckets/<namespace>/<bucket>/part-*.parquet",
|
| 31 |
split="train")
|
| 32 |
feats = ds.features.copy() # parquet stores category as bare ints; name the class
|
| 33 |
feats["objects"]["category"] = Sequence(ClassLabel(names=[ds[0]["query"]]))
|
|
|
|
|
|
|
| 34 |
ds.cast(feats).push_to_hub("<namespace>/<dataset>") # a dataset repo, distinct from the bucket
|
| 35 |
|
| 36 |
uv run validate-hf-dataset.py <namespace>/<dataset> --bbox-format yolo
|
| 37 |
|
| 38 |
-
|
| 39 |
-
the source bucket
|
| 40 |
-
|
|
|
|
|
|
|
| 41 |
|
| 42 |
GOTCHAS (all measured, none in the model card):
|
| 43 |
* --query is a CLASS NAME. "illustration" works; "the illustration, excluding
|
|
@@ -56,6 +60,7 @@ import io
|
|
| 56 |
import json
|
| 57 |
import time
|
| 58 |
|
|
|
|
| 59 |
import pyarrow as pa
|
| 60 |
import pyarrow.parquet as pq
|
| 61 |
from bucketbag import batched_files, boost, completed_keys, iter_keys, put_files
|
|
@@ -102,11 +107,11 @@ def pair_bboxes(raw):
|
|
| 102 |
return boxes
|
| 103 |
|
| 104 |
|
| 105 |
-
def serialise(rows, fmt):
|
| 106 |
if fmt == "jsonl":
|
| 107 |
return "\n".join(json.dumps(r) for r in rows) + "\n"
|
| 108 |
buf = io.BytesIO()
|
| 109 |
-
pq.write_table(pa.Table.from_pylist(rows, schema=
|
| 110 |
return buf.getvalue()
|
| 111 |
|
| 112 |
|
|
@@ -121,11 +126,22 @@ def main():
|
|
| 121 |
p.add_argument("--max-dim", type=int, default=1024)
|
| 122 |
p.add_argument("--max-new-tokens", type=int, default=200)
|
| 123 |
p.add_argument("--batch-n", type=int, default=32, help="files per bucketbag batch")
|
| 124 |
-
p.add_argument("--max-bytes", type=int, default=
|
|
|
|
|
|
|
| 125 |
p.add_argument("--cudagraph", action="store_true", help="opt IN; off by default (host OOM)")
|
| 126 |
p.add_argument("--format", default="parquet", choices=["parquet", "jsonl"])
|
| 127 |
p.add_argument("--no-resume", action="store_true")
|
|
|
|
|
|
|
| 128 |
args = p.parse_args()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
if args.format == "jsonl" and not args.no_resume:
|
| 131 |
# completed_keys only reads the done-set back from .parquet parts, so jsonl
|
|
@@ -154,6 +170,20 @@ def main():
|
|
| 154 |
|
| 155 |
done = set() if args.no_resume else completed_keys(args.out)
|
| 156 |
print(f"{len(done)} keys already done", flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
# objects=True yields BucketFile (with .size), so max_bytes is honoured.
|
| 159 |
# Needs bucketbag >= 0.3.0: before that, string keys made batched_files drop
|
|
@@ -166,7 +196,11 @@ def main():
|
|
| 166 |
keys = keys[: args.limit]
|
| 167 |
print(f"{len(keys)} keys to process", flush=True)
|
| 168 |
if not keys:
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
from falcon_perception import PERCEPTION_MODEL_ID, build_prompt_for_task, load_and_prepare_model, setup_torch_config
|
| 172 |
from falcon_perception.data import ImageProcessor
|
|
@@ -204,15 +238,16 @@ def main():
|
|
| 204 |
orig_size = img.size # SOURCE dims -- the images downstream tools decode
|
| 205 |
if max(img.size) > args.max_dim * 2:
|
| 206 |
img.thumbnail((args.max_dim * 2, args.max_dim * 2))
|
| 207 |
-
|
|
|
|
| 208 |
except Exception as e:
|
| 209 |
-
pairs.append((str(it.key), e, None))
|
| 210 |
|
| 211 |
-
good = [(k, im, sz) for k, im, sz in pairs if not isinstance(im, Exception)]
|
| 212 |
seqs = [
|
| 213 |
Sequence(text=prompt, image=im, min_image_size=256,
|
| 214 |
max_image_size=args.max_dim, request_idx=i, task=args.task)
|
| 215 |
-
for i, (_, im, _) in enumerate(good)
|
| 216 |
]
|
| 217 |
t0 = time.perf_counter()
|
| 218 |
if seqs:
|
|
@@ -221,7 +256,7 @@ def main():
|
|
| 221 |
gen_total += dt
|
| 222 |
|
| 223 |
rows = []
|
| 224 |
-
for (key, im, orig_size), seq in zip(good, seqs):
|
| 225 |
aux = seq.output_aux
|
| 226 |
boxes = pair_bboxes(aux.bboxes_raw)
|
| 227 |
masks = list(aux.masks_rle)
|
|
@@ -249,14 +284,17 @@ def main():
|
|
| 249 |
except Exception:
|
| 250 |
r = 0.0
|
| 251 |
rect.append(r)
|
| 252 |
-
|
| 253 |
"__source_key": key, "image_id": stable_id(key), "width": W, "height": H,
|
| 254 |
"objects": {"bbox": bbox, "category": [0] * len(bbox),
|
| 255 |
"area": area, "rectangularity": rect},
|
| 256 |
"n_instances": len(bbox), "masks_rle": json.dumps(masks),
|
| 257 |
"query": args.query, "gen_seconds": dt / max(len(seqs), 1), "error": None,
|
| 258 |
-
}
|
| 259 |
-
|
|
|
|
|
|
|
|
|
|
| 260 |
# a durable error row, never a gap — and it counts as done so it is
|
| 261 |
# not retried forever on every re-run. objects is EMPTY, not null:
|
| 262 |
# a null struct crashes validate-hf-dataset.py after publish.
|
|
@@ -271,9 +309,11 @@ def main():
|
|
| 271 |
# counter restarts at 0 and put_files overwrites, silently destroying the first
|
| 272 |
# run's parts. A content-derived name is stable per batch and collision-free
|
| 273 |
# across resumes (a re-run of the same batch overwrites its own part, idempotent).
|
|
|
|
|
|
|
| 274 |
ext = "jsonl" if args.format == "jsonl" else "parquet"
|
| 275 |
part = hashlib.blake2b(rows[0]["__source_key"].encode(), digest_size=6).hexdigest()
|
| 276 |
-
put_files([(f"part-{part}.{ext}", serialise(rows, args.format))], args.out)
|
| 277 |
n += len(rows); batch_i += 1
|
| 278 |
rate = n / (time.perf_counter() - t_all)
|
| 279 |
print(f"batch {batch_i}: {len(rows)} rows ({dt / max(len(seqs), 1):.2f}s/img) "
|
|
|
|
| 4 |
# dependencies = [
|
| 5 |
# "falcon-perception>=1.0.0",
|
| 6 |
# # tarball not git+: some GPU images have no `git` for uv to shell out to
|
| 7 |
+
# "bucketbag @ https://github.com/davanstrien/bucketbag/archive/refs/tags/v0.3.1.tar.gz",
|
| 8 |
# "pyarrow>=18",
|
| 9 |
# "pycocotools>=2.0.11",
|
| 10 |
# ]
|
|
|
|
| 26 |
run resumable (`completed_keys` reads the done-set back from `__source_key`).
|
| 27 |
To hand the result to the rest of this directory, publish it once at the end:
|
| 28 |
|
| 29 |
+
from datasets import ClassLabel, Image, Sequence, load_dataset
|
| 30 |
ds = load_dataset("parquet", data_files="hf://buckets/<namespace>/<bucket>/part-*.parquet",
|
| 31 |
split="train")
|
| 32 |
feats = ds.features.copy() # parquet stores category as bare ints; name the class
|
| 33 |
feats["objects"]["category"] = Sequence(ClassLabel(names=[ds[0]["query"]]))
|
| 34 |
+
if "image" in feats: # --embed-images parts: make the bytes a decodable Image column
|
| 35 |
+
feats["image"] = Image()
|
| 36 |
ds.cast(feats).push_to_hub("<namespace>/<dataset>") # a dataset repo, distinct from the bucket
|
| 37 |
|
| 38 |
uv run validate-hf-dataset.py <namespace>/<dataset> --bbox-format yolo
|
| 39 |
|
| 40 |
+
By default the parts carry `width`/`height` but no `image` column: the images stay in
|
| 41 |
+
the source bucket, the parts stay small and resumable, and `embed-bucket-images.py`
|
| 42 |
+
joins the bytes back in. Pass --embed-images to write the source bytes into each part
|
| 43 |
+
instead (an `image` column datasets decodes directly) -- storage is cheap and it saves
|
| 44 |
+
the join's re-fetch of every image; the cost is a copy of the corpus in the output bucket.
|
| 45 |
|
| 46 |
GOTCHAS (all measured, none in the model card):
|
| 47 |
* --query is a CLASS NAME. "illustration" works; "the illustration, excluding
|
|
|
|
| 60 |
import json
|
| 61 |
import time
|
| 62 |
|
| 63 |
+
import fsspec
|
| 64 |
import pyarrow as pa
|
| 65 |
import pyarrow.parquet as pq
|
| 66 |
from bucketbag import batched_files, boost, completed_keys, iter_keys, put_files
|
|
|
|
| 107 |
return boxes
|
| 108 |
|
| 109 |
|
| 110 |
+
def serialise(rows, fmt, schema=SCHEMA):
|
| 111 |
if fmt == "jsonl":
|
| 112 |
return "\n".join(json.dumps(r) for r in rows) + "\n"
|
| 113 |
buf = io.BytesIO()
|
| 114 |
+
pq.write_table(pa.Table.from_pylist(rows, schema=schema), buf, compression="zstd")
|
| 115 |
return buf.getvalue()
|
| 116 |
|
| 117 |
|
|
|
|
| 126 |
p.add_argument("--max-dim", type=int, default=1024)
|
| 127 |
p.add_argument("--max-new-tokens", type=int, default=200)
|
| 128 |
p.add_argument("--batch-n", type=int, default=32, help="files per bucketbag batch")
|
| 129 |
+
p.add_argument("--max-bytes", type=int, default=None,
|
| 130 |
+
help="scratch bytes per batch (RAM tmpfs). Default 2 GiB; 256 MiB with --embed-images, "
|
| 131 |
+
"whose bytes are also held ~4x in host RAM while a part is serialised")
|
| 132 |
p.add_argument("--cudagraph", action="store_true", help="opt IN; off by default (host OOM)")
|
| 133 |
p.add_argument("--format", default="parquet", choices=["parquet", "jsonl"])
|
| 134 |
p.add_argument("--no-resume", action="store_true")
|
| 135 |
+
p.add_argument("--embed-images", action="store_true",
|
| 136 |
+
help="also write the source image bytes into each part (see docstring)")
|
| 137 |
args = p.parse_args()
|
| 138 |
+
if args.embed_images and args.format == "jsonl":
|
| 139 |
+
raise SystemExit("--embed-images writes raw image bytes, which jsonl cannot carry; use --format parquet.")
|
| 140 |
+
if args.max_bytes is None:
|
| 141 |
+
args.max_bytes = 256 * 2**20 if args.embed_images else 2 * 2**30
|
| 142 |
+
schema = SCHEMA
|
| 143 |
+
if args.embed_images:
|
| 144 |
+
schema = SCHEMA.append(pa.field("image", pa.struct([("bytes", pa.binary()), ("path", pa.string())])))
|
| 145 |
|
| 146 |
if args.format == "jsonl" and not args.no_resume:
|
| 147 |
# completed_keys only reads the done-set back from .parquet parts, so jsonl
|
|
|
|
| 170 |
|
| 171 |
done = set() if args.no_resume else completed_keys(args.out)
|
| 172 |
print(f"{len(done)} keys already done", flush=True)
|
| 173 |
+
if done and args.format == "parquet":
|
| 174 |
+
# a resume must not mix part schemas: half the parts with an image column and half
|
| 175 |
+
# without loads as nulls downstream, and the null rows crash the trainer's tree build
|
| 176 |
+
first_part = next((f for f in iter_keys(args.out, prefix="part-", objects=True)
|
| 177 |
+
if f.path.endswith(".parquet")), None)
|
| 178 |
+
if first_part is not None:
|
| 179 |
+
with fsspec.open(f"hf://buckets/{args.out}/{first_part.path}", "rb") as fh:
|
| 180 |
+
existing = pq.read_schema(fh)
|
| 181 |
+
if ("image" in existing.names) != args.embed_images:
|
| 182 |
+
raise SystemExit(
|
| 183 |
+
f"existing parts in {args.out} were written "
|
| 184 |
+
f"{'with' if 'image' in existing.names else 'without'} --embed-images; "
|
| 185 |
+
"resume with the same flag, or write to a fresh --out bucket."
|
| 186 |
+
)
|
| 187 |
|
| 188 |
# objects=True yields BucketFile (with .size), so max_bytes is honoured.
|
| 189 |
# Needs bucketbag >= 0.3.0: before that, string keys made batched_files drop
|
|
|
|
| 196 |
keys = keys[: args.limit]
|
| 197 |
print(f"{len(keys)} keys to process", flush=True)
|
| 198 |
if not keys:
|
| 199 |
+
raise SystemExit(
|
| 200 |
+
f"0 keys matched under {args.src}/{args.prefix or ''} — this script reads only "
|
| 201 |
+
".jpg/.jpeg/.png (convert JPEG 2000 / TIFF first), and already-done keys are skipped "
|
| 202 |
+
"(pass --no-resume to redo)."
|
| 203 |
+
)
|
| 204 |
|
| 205 |
from falcon_perception import PERCEPTION_MODEL_ID, build_prompt_for_task, load_and_prepare_model, setup_torch_config
|
| 206 |
from falcon_perception.data import ImageProcessor
|
|
|
|
| 238 |
orig_size = img.size # SOURCE dims -- the images downstream tools decode
|
| 239 |
if max(img.size) > args.max_dim * 2:
|
| 240 |
img.thumbnail((args.max_dim * 2, args.max_dim * 2))
|
| 241 |
+
raw = it.bytes if args.embed_images else None # read before the batch is deleted
|
| 242 |
+
pairs.append((str(it.key), img, orig_size, raw))
|
| 243 |
except Exception as e:
|
| 244 |
+
pairs.append((str(it.key), e, None, None))
|
| 245 |
|
| 246 |
+
good = [(k, im, sz, raw) for k, im, sz, raw in pairs if not isinstance(im, Exception)]
|
| 247 |
seqs = [
|
| 248 |
Sequence(text=prompt, image=im, min_image_size=256,
|
| 249 |
max_image_size=args.max_dim, request_idx=i, task=args.task)
|
| 250 |
+
for i, (_, im, _, _) in enumerate(good)
|
| 251 |
]
|
| 252 |
t0 = time.perf_counter()
|
| 253 |
if seqs:
|
|
|
|
| 256 |
gen_total += dt
|
| 257 |
|
| 258 |
rows = []
|
| 259 |
+
for (key, im, orig_size, raw), seq in zip(good, seqs):
|
| 260 |
aux = seq.output_aux
|
| 261 |
boxes = pair_bboxes(aux.bboxes_raw)
|
| 262 |
masks = list(aux.masks_rle)
|
|
|
|
| 284 |
except Exception:
|
| 285 |
r = 0.0
|
| 286 |
rect.append(r)
|
| 287 |
+
row = {
|
| 288 |
"__source_key": key, "image_id": stable_id(key), "width": W, "height": H,
|
| 289 |
"objects": {"bbox": bbox, "category": [0] * len(bbox),
|
| 290 |
"area": area, "rectangularity": rect},
|
| 291 |
"n_instances": len(bbox), "masks_rle": json.dumps(masks),
|
| 292 |
"query": args.query, "gen_seconds": dt / max(len(seqs), 1), "error": None,
|
| 293 |
+
}
|
| 294 |
+
if args.embed_images:
|
| 295 |
+
row["image"] = {"bytes": raw, "path": None}
|
| 296 |
+
rows.append(row)
|
| 297 |
+
for key, err, _, _ in [t for t in pairs if isinstance(t[1], Exception)]:
|
| 298 |
# a durable error row, never a gap — and it counts as done so it is
|
| 299 |
# not retried forever on every re-run. objects is EMPTY, not null:
|
| 300 |
# a null struct crashes validate-hf-dataset.py after publish.
|
|
|
|
| 309 |
# counter restarts at 0 and put_files overwrites, silently destroying the first
|
| 310 |
# run's parts. A content-derived name is stable per batch and collision-free
|
| 311 |
# across resumes (a re-run of the same batch overwrites its own part, idempotent).
|
| 312 |
+
if not rows: # bucketbag drops files that vanished between listing and download
|
| 313 |
+
continue
|
| 314 |
ext = "jsonl" if args.format == "jsonl" else "parquet"
|
| 315 |
part = hashlib.blake2b(rows[0]["__source_key"].encode(), digest_size=6).hexdigest()
|
| 316 |
+
put_files([(f"part-{part}.{ext}", serialise(rows, args.format, schema))], args.out)
|
| 317 |
n += len(rows); batch_i += 1
|
| 318 |
rate = n / (time.perf_counter() - t_all)
|
| 319 |
print(f"batch {batch_i}: {len(rows)} rows ({dt / max(len(seqs), 1):.2f}s/img) "
|
materialize-coco.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env -S uv run --script
|
| 2 |
+
# /// script
|
| 3 |
+
# requires-python = ">=3.10"
|
| 4 |
+
# dependencies = [
|
| 5 |
+
# "datasets>=4.0",
|
| 6 |
+
# "huggingface_hub>=1.27", # hf://buckets in HfFileSystem (1.6) + prefix-collision fix (1.27)
|
| 7 |
+
# "pillow",
|
| 8 |
+
# "numpy",
|
| 9 |
+
# "pycocotools>=2.0.11",
|
| 10 |
+
# ]
|
| 11 |
+
# ///
|
| 12 |
+
"""Materialize a COCO directory tree FROM the canonical parquet, in-job, on ephemeral disk.
|
| 13 |
+
|
| 14 |
+
Some trainers (RF-DETR and friends) refuse HF datasets and demand the canonical COCO 2017
|
| 15 |
+
layout: annotations/instances_train2017.json + train2017/*.jpg. Never hand-assemble or
|
| 16 |
+
upload that tree -- generate it from the parquet with this script instead. A generated
|
| 17 |
+
tree cannot reference images that are not there, which kills the referenced-vs-uploaded
|
| 18 |
+
mismatch class outright (it caused three paid job failures in one measured run).
|
| 19 |
+
|
| 20 |
+
# inside the training job, before the trainer starts:
|
| 21 |
+
uv run materialize-coco.py --data hf://buckets/<ns>/<training-bucket>/dataset --out /tmp/coco
|
| 22 |
+
|
| 23 |
+
# or from a dataset repo produced by embed-bucket-images.py:
|
| 24 |
+
uv run materialize-coco.py --data <ns>/<training-dataset> --out /tmp/coco
|
| 25 |
+
|
| 26 |
+
# training more than once? generate ONCE onto a bucket mount and let later jobs reuse it:
|
| 27 |
+
# hf jobs run ... -v hf://buckets/<ns>/<training-bucket>:/data ...
|
| 28 |
+
uv run materialize-coco.py --data /data/dataset --out /data/coco
|
| 29 |
+
|
| 30 |
+
A split is reused, not regenerated, when its tree is complete AND was built from the same
|
| 31 |
+
labels: the annotations file carries a fingerprint of (image ids, boxes), so a corrected
|
| 32 |
+
dataset -- the step-6 loop, same images, new labels -- rebuilds automatically. --force rebuilds
|
| 33 |
+
regardless. Rows whose image cannot be decoded (teacher error rows, truncated files) are skipped
|
| 34 |
+
and counted, never allowed to kill the job.
|
| 35 |
+
|
| 36 |
+
Boxes are converted yolo-normalized -> COCO xywh pixels (pass --bbox-format coco_xywh if your
|
| 37 |
+
parquet already stores pixels). masks_rle, when present, is carried through as COCO RLE
|
| 38 |
+
segmentation (RF-DETR-class trainers accept RLE natively).
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
import argparse
|
| 42 |
+
import hashlib
|
| 43 |
+
import io
|
| 44 |
+
import json
|
| 45 |
+
import shutil
|
| 46 |
+
from pathlib import Path
|
| 47 |
+
|
| 48 |
+
import numpy as np
|
| 49 |
+
from datasets import Image as HFImage
|
| 50 |
+
from datasets import load_dataset
|
| 51 |
+
from PIL import Image as PILImage
|
| 52 |
+
from pycocotools import mask as mask_utils
|
| 53 |
+
|
| 54 |
+
SPLIT_DIR = {"train": "train2017", "validation": "val2017"}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def to_xywh(bbox, w, h, fmt):
|
| 58 |
+
if fmt == "coco_xywh":
|
| 59 |
+
return [float(v) for v in bbox]
|
| 60 |
+
cx, cy, bw, bh = bbox # yolo normalised
|
| 61 |
+
return [(cx - bw / 2) * w, (cy - bh / 2) * h, bw * w, bh * h]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def label_fingerprint(ds):
|
| 65 |
+
"""Hash of (image_id, boxes) for every row -- changes when labels change, not when bytes do."""
|
| 66 |
+
labels = ds.select_columns(["image_id", "objects"]).with_format(None)
|
| 67 |
+
items = sorted(
|
| 68 |
+
(
|
| 69 |
+
int(row["image_id"]),
|
| 70 |
+
[[round(float(v), 6) for v in b] for b in row["objects"]["bbox"]],
|
| 71 |
+
)
|
| 72 |
+
for row in labels
|
| 73 |
+
)
|
| 74 |
+
return hashlib.sha1(json.dumps(items).encode()).hexdigest()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def load_split(data, split):
|
| 78 |
+
if data.startswith("hf://"):
|
| 79 |
+
return load_dataset(
|
| 80 |
+
"parquet", data_files=f"{data.rstrip('/')}/{split}.parquet", split="train"
|
| 81 |
+
)
|
| 82 |
+
return load_dataset(data, split=split)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def tree_is_reusable(jpath, img_dir, fingerprint):
|
| 86 |
+
if not jpath.exists():
|
| 87 |
+
return False, "no tree yet"
|
| 88 |
+
coco = json.loads(jpath.read_text())
|
| 89 |
+
stamped = coco.get("provenance", {}).get("fingerprint")
|
| 90 |
+
if stamped != fingerprint:
|
| 91 |
+
return False, "labels changed since the tree was built"
|
| 92 |
+
referenced = len(coco["images"])
|
| 93 |
+
present = len(list(img_dir.glob("*.jpg")))
|
| 94 |
+
if not referenced or referenced != present:
|
| 95 |
+
return False, f"tree incomplete ({present} files vs {referenced} referenced)"
|
| 96 |
+
return True, f"complete tree ({present} images), same labels"
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def decode_image(raw):
|
| 100 |
+
"""raw is the undecoded {bytes, path} struct (or None for error rows)."""
|
| 101 |
+
if not raw or not raw.get("bytes"):
|
| 102 |
+
return None
|
| 103 |
+
try:
|
| 104 |
+
im = PILImage.open(io.BytesIO(raw["bytes"]))
|
| 105 |
+
im.load()
|
| 106 |
+
return im.convert("RGB")
|
| 107 |
+
except Exception: # noqa: BLE001 -- any decode failure means "skip this row"
|
| 108 |
+
return None
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def main():
|
| 112 |
+
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
| 113 |
+
p.add_argument(
|
| 114 |
+
"--data",
|
| 115 |
+
required=True,
|
| 116 |
+
help="dataset repo id, hf://buckets/... prefix, or local directory holding <split>.parquet",
|
| 117 |
+
)
|
| 118 |
+
p.add_argument(
|
| 119 |
+
"--out",
|
| 120 |
+
required=True,
|
| 121 |
+
help="output dir (ephemeral disk, or a bucket mount to reuse across jobs)",
|
| 122 |
+
)
|
| 123 |
+
p.add_argument("--bbox-format", default="yolo", choices=["yolo", "coco_xywh"])
|
| 124 |
+
p.add_argument("--splits", nargs="+", default=["train", "validation"])
|
| 125 |
+
p.add_argument(
|
| 126 |
+
"--force",
|
| 127 |
+
action="store_true",
|
| 128 |
+
help="rebuild a split even if its tree is complete",
|
| 129 |
+
)
|
| 130 |
+
args = p.parse_args()
|
| 131 |
+
|
| 132 |
+
out = Path(args.out)
|
| 133 |
+
(out / "annotations").mkdir(parents=True, exist_ok=True)
|
| 134 |
+
|
| 135 |
+
for split in args.splits:
|
| 136 |
+
ds = load_split(args.data, split)
|
| 137 |
+
assert "image" in ds.column_names, (
|
| 138 |
+
"no image column — run embed-bucket-images.py first"
|
| 139 |
+
)
|
| 140 |
+
img_dir = out / SPLIT_DIR.get(split, split)
|
| 141 |
+
jpath = out / "annotations" / f"instances_{SPLIT_DIR.get(split, split)}.json"
|
| 142 |
+
|
| 143 |
+
fingerprint = label_fingerprint(ds)
|
| 144 |
+
reusable, why = tree_is_reusable(jpath, img_dir, fingerprint)
|
| 145 |
+
if reusable and not args.force:
|
| 146 |
+
print(f"{split}: reusing {why} at {img_dir} — pass --force to rebuild")
|
| 147 |
+
continue
|
| 148 |
+
print(f"{split}: building ({'--force' if args.force else why})")
|
| 149 |
+
# a rebuild starts from nothing: stale JPEGs from an older tree would fail the
|
| 150 |
+
# files == referenced assert below after all the decode work
|
| 151 |
+
shutil.rmtree(img_dir, ignore_errors=True)
|
| 152 |
+
jpath.unlink(missing_ok=True)
|
| 153 |
+
img_dir.mkdir()
|
| 154 |
+
|
| 155 |
+
cat_feature = ds.features["objects"]["category"].feature
|
| 156 |
+
names = getattr(cat_feature, "names", None) or ["object"]
|
| 157 |
+
|
| 158 |
+
# undecoded bytes so a corrupt image is OUR decision to skip, not a crash inside datasets
|
| 159 |
+
rows = ds.cast_column("image", HFImage(decode=False)).with_format(None)
|
| 160 |
+
images, annotations, ann_id, skipped = [], [], 1, []
|
| 161 |
+
for row in rows:
|
| 162 |
+
iid = int(row["image_id"])
|
| 163 |
+
im = None if row.get("error") else decode_image(row["image"])
|
| 164 |
+
if im is None:
|
| 165 |
+
skipped.append(iid)
|
| 166 |
+
continue
|
| 167 |
+
fname = f"{iid}.jpg"
|
| 168 |
+
im.save(img_dir / fname, "JPEG", quality=95)
|
| 169 |
+
# dims from the DECODED image, never metadata columns: error rows carry
|
| 170 |
+
# width/height=None, and the saved JPEG is the frame everything must match
|
| 171 |
+
w, h = im.size
|
| 172 |
+
images.append({"id": iid, "file_name": fname, "width": w, "height": h})
|
| 173 |
+
rles = json.loads(row["masks_rle"]) if row.get("masks_rle") else []
|
| 174 |
+
for i, bbox in enumerate(row["objects"]["bbox"]):
|
| 175 |
+
x, y, bw, bh = to_xywh(bbox, w, h, args.bbox_format)
|
| 176 |
+
ann = {
|
| 177 |
+
"id": ann_id,
|
| 178 |
+
"image_id": iid,
|
| 179 |
+
"category_id": int(row["objects"]["category"][i]) + 1,
|
| 180 |
+
"bbox": [x, y, bw, bh],
|
| 181 |
+
"area": bw * bh,
|
| 182 |
+
"iscrowd": 0,
|
| 183 |
+
}
|
| 184 |
+
if i < len(rles):
|
| 185 |
+
rle = rles[i]
|
| 186 |
+
# masks live in the INFERENCE frame, which diverges from the image
|
| 187 |
+
# frame whenever the teacher thumbnailed -- resize before writing
|
| 188 |
+
if rle["size"] != [h, w]:
|
| 189 |
+
seg = mask_utils.decode(
|
| 190 |
+
{**rle, "counts": rle["counts"].encode()}
|
| 191 |
+
)
|
| 192 |
+
seg = np.asarray(
|
| 193 |
+
PILImage.fromarray(seg).resize((w, h), PILImage.NEAREST)
|
| 194 |
+
)
|
| 195 |
+
enc = mask_utils.encode(np.asfortranarray(seg))
|
| 196 |
+
rle = {"size": [h, w], "counts": enc["counts"].decode("ascii")}
|
| 197 |
+
ann["segmentation"] = rle
|
| 198 |
+
annotations.append(ann)
|
| 199 |
+
ann_id += 1
|
| 200 |
+
|
| 201 |
+
coco = {
|
| 202 |
+
"images": images,
|
| 203 |
+
"annotations": annotations,
|
| 204 |
+
"categories": [{"id": i + 1, "name": n} for i, n in enumerate(names)],
|
| 205 |
+
"provenance": {
|
| 206 |
+
"source": args.data,
|
| 207 |
+
"fingerprint": fingerprint,
|
| 208 |
+
"skipped_image_ids": skipped,
|
| 209 |
+
},
|
| 210 |
+
}
|
| 211 |
+
jpath.write_text(json.dumps(coco))
|
| 212 |
+
|
| 213 |
+
n_files = len(list(img_dir.glob("*.jpg")))
|
| 214 |
+
assert n_files == len(images), (
|
| 215 |
+
f"{split}: {n_files} files != {len(images)} referenced"
|
| 216 |
+
)
|
| 217 |
+
note = (
|
| 218 |
+
f" (skipped {len(skipped)} undecodable/error rows, e.g. {skipped[:3]})"
|
| 219 |
+
if skipped
|
| 220 |
+
else ""
|
| 221 |
+
)
|
| 222 |
+
print(
|
| 223 |
+
f"{split}: {len(images)} images / {len(annotations)} annotations -> {img_dir} + {jpath.name}{note}"
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":
|
| 228 |
+
main()
|
render-detections.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env -S uv run --script
|
| 2 |
+
# /// script
|
| 3 |
+
# requires-python = ">=3.10"
|
| 4 |
+
# dependencies = [
|
| 5 |
+
# "datasets>=4.0",
|
| 6 |
+
# "huggingface_hub>=1.27", # hf://buckets in HfFileSystem (1.6) + prefix-collision fix (1.27)
|
| 7 |
+
# "pillow",
|
| 8 |
+
# "numpy",
|
| 9 |
+
# "pycocotools>=2.0.11",
|
| 10 |
+
# ]
|
| 11 |
+
# ///
|
| 12 |
+
"""Render detection overlays from a dataset in this directory's schema -- and PROVE they rendered.
|
| 13 |
+
|
| 14 |
+
Draws boxes (and masks, when masks_rle is present) over the embedded images and writes PNGs.
|
| 15 |
+
Before reporting success it pixel-diffs every render against its source image: a page with
|
| 16 |
+
instances whose render is identical to the source means the overlay silently failed (alpha
|
| 17 |
+
bugs, empty mask lists, wrong-column reads -- all observed in real runs, twice shown to a
|
| 18 |
+
human as "done"). Any blank render exits nonzero and names the file.
|
| 19 |
+
|
| 20 |
+
uv run render-detections.py <ns>/<teacher-or-training-dataset> --limit 10 --out previews/
|
| 21 |
+
uv run render-detections.py "hf://buckets/<ns>/<bucket>/dataset/train.parquet" --out previews/
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import argparse
|
| 25 |
+
import io
|
| 26 |
+
import json
|
| 27 |
+
import sys
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
from datasets import Image as HFImage
|
| 32 |
+
from datasets import load_dataset
|
| 33 |
+
from PIL import Image, ImageDraw
|
| 34 |
+
|
| 35 |
+
COLORS = [
|
| 36 |
+
(255, 210, 0),
|
| 37 |
+
(80, 200, 120),
|
| 38 |
+
(90, 160, 255),
|
| 39 |
+
(230, 90, 80),
|
| 40 |
+
(200, 120, 220),
|
| 41 |
+
(255, 150, 50),
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def main():
|
| 46 |
+
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
| 47 |
+
p.add_argument(
|
| 48 |
+
"data", help="dataset repo id, or a parquet path/glob (hf:// or local)"
|
| 49 |
+
)
|
| 50 |
+
p.add_argument("--split", default="train")
|
| 51 |
+
p.add_argument("--limit", type=int, default=10)
|
| 52 |
+
p.add_argument("--out", default="previews")
|
| 53 |
+
p.add_argument("--bbox-format", default="yolo", choices=["yolo", "coco_xywh"])
|
| 54 |
+
p.add_argument("--no-masks", action="store_true")
|
| 55 |
+
p.add_argument(
|
| 56 |
+
"--min-pixels",
|
| 57 |
+
type=int,
|
| 58 |
+
default=1,
|
| 59 |
+
help="a page with instances whose render changed fewer pixels than this is BLANK "
|
| 60 |
+
"(default 1: any drawn pixel proves the overlay; a 50x50 box on a 3000px scan is real)",
|
| 61 |
+
)
|
| 62 |
+
args = p.parse_args()
|
| 63 |
+
|
| 64 |
+
if "://" in args.data or args.data.endswith(".parquet"):
|
| 65 |
+
ds = load_dataset("parquet", data_files=args.data, split="train")
|
| 66 |
+
else:
|
| 67 |
+
ds = load_dataset(args.data, split=args.split)
|
| 68 |
+
assert "image" in ds.column_names, (
|
| 69 |
+
"no image column in this dataset — nothing to render over"
|
| 70 |
+
)
|
| 71 |
+
ds = ds.select(range(min(args.limit, len(ds))))
|
| 72 |
+
|
| 73 |
+
out = Path(args.out)
|
| 74 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 75 |
+
blank, rendered, skipped = [], 0, []
|
| 76 |
+
# undecoded bytes: a corrupt image or an error row is skipped, not a crash inside datasets
|
| 77 |
+
for row in ds.cast_column("image", HFImage(decode=False)).with_format(None):
|
| 78 |
+
raw = row["image"]
|
| 79 |
+
try:
|
| 80 |
+
src = (
|
| 81 |
+
Image.open(io.BytesIO(raw["bytes"])).convert("RGB")
|
| 82 |
+
if raw and raw.get("bytes")
|
| 83 |
+
else None
|
| 84 |
+
)
|
| 85 |
+
except Exception: # noqa: BLE001 -- any decode failure means "skip this row"
|
| 86 |
+
src = None
|
| 87 |
+
if src is None or row.get("error"):
|
| 88 |
+
skipped.append(row["image_id"])
|
| 89 |
+
continue
|
| 90 |
+
im = src.copy()
|
| 91 |
+
w, h = im.size
|
| 92 |
+
n = len(row["objects"]["bbox"])
|
| 93 |
+
|
| 94 |
+
if not args.no_masks and row.get("masks_rle"):
|
| 95 |
+
from pycocotools import mask as mask_utils
|
| 96 |
+
|
| 97 |
+
overlay = Image.new("RGBA", im.size, (0, 0, 0, 0))
|
| 98 |
+
for i, rle in enumerate(json.loads(row["masks_rle"])):
|
| 99 |
+
seg = mask_utils.decode({**rle, "counts": rle["counts"].encode()})
|
| 100 |
+
if seg.shape != (h, w):
|
| 101 |
+
seg = np.asarray(Image.fromarray(seg).resize((w, h), Image.NEAREST))
|
| 102 |
+
r, g, b = COLORS[i % len(COLORS)]
|
| 103 |
+
tint = np.zeros((h, w, 4), np.uint8)
|
| 104 |
+
tint[seg > 0] = (r, g, b, 110)
|
| 105 |
+
overlay = Image.alpha_composite(overlay, Image.fromarray(tint))
|
| 106 |
+
im = Image.alpha_composite(im.convert("RGBA"), overlay).convert("RGB")
|
| 107 |
+
|
| 108 |
+
draw = ImageDraw.Draw(im)
|
| 109 |
+
for i, bbox in enumerate(row["objects"]["bbox"]):
|
| 110 |
+
if args.bbox_format == "yolo":
|
| 111 |
+
cx, cy, bw, bh = bbox
|
| 112 |
+
box = [
|
| 113 |
+
(cx - bw / 2) * w,
|
| 114 |
+
(cy - bh / 2) * h,
|
| 115 |
+
(cx + bw / 2) * w,
|
| 116 |
+
(cy + bh / 2) * h,
|
| 117 |
+
]
|
| 118 |
+
else:
|
| 119 |
+
x, y, bw, bh = bbox
|
| 120 |
+
box = [x, y, x + bw, y + bh]
|
| 121 |
+
draw.rectangle(box, outline=COLORS[i % len(COLORS)], width=max(3, w // 400))
|
| 122 |
+
|
| 123 |
+
name = f"{row['image_id']}_{n}inst.png"
|
| 124 |
+
im.save(out / name)
|
| 125 |
+
|
| 126 |
+
# ---- the point of this script: prove the overlay exists ----
|
| 127 |
+
changed = int(np.any(np.asarray(src) != np.asarray(im), axis=-1).sum())
|
| 128 |
+
if n > 0 and changed < args.min_pixels:
|
| 129 |
+
blank.append(name)
|
| 130 |
+
elif n > 0:
|
| 131 |
+
rendered += 1
|
| 132 |
+
print(
|
| 133 |
+
f"{name}: {n} instances, {changed} pixels changed ({changed / (w * h):.2%})"
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
if blank:
|
| 137 |
+
sys.exit(
|
| 138 |
+
f"BLANK RENDERS ({len(blank)}): {blank} — overlays did not draw; do not show these to a human."
|
| 139 |
+
)
|
| 140 |
+
if skipped:
|
| 141 |
+
print(f"skipped {len(skipped)} undecodable/error rows, e.g. {skipped[:3]}")
|
| 142 |
+
if rendered == 0:
|
| 143 |
+
sys.exit(
|
| 144 |
+
"No page with instances was rendered — nothing verified; increase --limit."
|
| 145 |
+
)
|
| 146 |
+
print(f"OK: {rendered} non-empty renders verified against source pixels -> {out}/")
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
if __name__ == "__main__":
|
| 150 |
+
main()
|
smoke-test.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env -S uv run --script
|
| 2 |
+
# /// script
|
| 3 |
+
# requires-python = ">=3.10"
|
| 4 |
+
# dependencies = [
|
| 5 |
+
# "datasets>=4.0",
|
| 6 |
+
# "pillow",
|
| 7 |
+
# "numpy",
|
| 8 |
+
# "pyarrow>=18",
|
| 9 |
+
# "pycocotools>=2.0.11",
|
| 10 |
+
# ]
|
| 11 |
+
# ///
|
| 12 |
+
"""Free, local, ~30 s: prove the plumbing scripts still work BEFORE a paid job depends on them.
|
| 13 |
+
|
| 14 |
+
Builds what a teacher pass leaves behind -- annotations-only parquet parts in the
|
| 15 |
+
falcon-perception-bucket.py schema, a source directory of page images, a gold slice -- for four
|
| 16 |
+
pages: one with two instances whose masks are stored in a 2x-thumbnailed inference frame (the
|
| 17 |
+
frame-mismatch bug seen in a real run), one with a box and no mask, one empty, one teacher ERROR
|
| 18 |
+
row whose file is not a decodable image. Then it runs the plumbing chain on it and checks the
|
| 19 |
+
OUTPUT of each step, not just the exit code:
|
| 20 |
+
|
| 21 |
+
embed-bucket-images.py error row dropped, gold page excluded (and asserted), images joined
|
| 22 |
+
in, one write of train.parquet + validation.parquet; also the
|
| 23 |
+
--embed-images path (parts already carry the bytes -> no --src) and
|
| 24 |
+
--keep-errors (the undecodable row must survive to the next step)
|
| 25 |
+
materialize-coco.py COCO tree: file count == referenced count, masks resized to the
|
| 26 |
+
image frame, every mask's pixel extent agrees with its box, the
|
| 27 |
+
undecodable row skipped not crashed; a second run reuses the tree;
|
| 28 |
+
the same images with CORRECTED labels rebuild it (fingerprint);
|
| 29 |
+
--force over a tree holding a stale JPEG rebuilds clean
|
| 30 |
+
render-detections.py overlays drawn (pixel-verified), the empty page not flagged as
|
| 31 |
+
blank, the undecodable row skipped
|
| 32 |
+
|
| 33 |
+
Run it after cloning, after bumping a dependency, and before submitting any job that uses these
|
| 34 |
+
scripts. Exit 0 = green. Anything else names the failing check.
|
| 35 |
+
|
| 36 |
+
uv run smoke-test.py
|
| 37 |
+
|
| 38 |
+
Not covered: the teacher pass itself (falcon-perception-bucket.py needs a GPU); run it on a
|
| 39 |
+
--limit slice of your own bucket.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
import json
|
| 43 |
+
import subprocess
|
| 44 |
+
import sys
|
| 45 |
+
import tempfile
|
| 46 |
+
from pathlib import Path
|
| 47 |
+
|
| 48 |
+
import numpy as np
|
| 49 |
+
import pyarrow as pa
|
| 50 |
+
import pyarrow.parquet as pq
|
| 51 |
+
from datasets import load_dataset
|
| 52 |
+
from PIL import Image
|
| 53 |
+
from pycocotools import mask as mask_utils
|
| 54 |
+
|
| 55 |
+
HERE = Path(__file__).resolve().parent
|
| 56 |
+
IMAGE_W, IMAGE_H = 800, 1000 # the image frame
|
| 57 |
+
INFER_W, INFER_H = 400, 500 # the teacher's inference frame (thumbnailed 2x)
|
| 58 |
+
|
| 59 |
+
# Ground truth in image-frame pixels: (x0, y0, x1, y1). Masks are the same rectangles, but
|
| 60 |
+
# stored at half resolution so the scripts must resize them.
|
| 61 |
+
PAGE1_BOXES = [(100, 100, 300, 400), (450, 600, 750, 900)]
|
| 62 |
+
PAGE2_BOXES = [(200, 200, 600, 500)]
|
| 63 |
+
PAGE2_CORRECTED = [
|
| 64 |
+
(200, 200, 600, 500),
|
| 65 |
+
(50, 700, 250, 950),
|
| 66 |
+
] # the step-6 loop found one more
|
| 67 |
+
GOLD_IMAGE_ID = 3 # the empty page is held out as "gold" and must never reach train/val
|
| 68 |
+
ERROR_IMAGE_ID = 4 # the teacher could not open this file; its bytes are not an image
|
| 69 |
+
|
| 70 |
+
# mirrors SCHEMA in falcon-perception-bucket.py
|
| 71 |
+
PARTS_SCHEMA = pa.schema(
|
| 72 |
+
[
|
| 73 |
+
("__source_key", pa.string()),
|
| 74 |
+
("image_id", pa.int64()),
|
| 75 |
+
("width", pa.int32()),
|
| 76 |
+
("height", pa.int32()),
|
| 77 |
+
(
|
| 78 |
+
"objects",
|
| 79 |
+
pa.struct(
|
| 80 |
+
[
|
| 81 |
+
("bbox", pa.list_(pa.list_(pa.float32()))),
|
| 82 |
+
("category", pa.list_(pa.int64())),
|
| 83 |
+
("area", pa.list_(pa.float32())),
|
| 84 |
+
("rectangularity", pa.list_(pa.float32())),
|
| 85 |
+
]
|
| 86 |
+
),
|
| 87 |
+
),
|
| 88 |
+
("n_instances", pa.int32()),
|
| 89 |
+
("masks_rle", pa.string()),
|
| 90 |
+
("query", pa.string()),
|
| 91 |
+
("gen_seconds", pa.float32()),
|
| 92 |
+
("error", pa.string()),
|
| 93 |
+
]
|
| 94 |
+
)
|
| 95 |
+
IMAGE_FIELD = pa.field(
|
| 96 |
+
"image", pa.struct([("bytes", pa.binary()), ("path", pa.string())])
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def synthetic_page(seed):
|
| 101 |
+
rng = np.random.default_rng(seed)
|
| 102 |
+
noise = rng.integers(0, 10, (IMAGE_H, IMAGE_W, 1), dtype=np.uint8)
|
| 103 |
+
arr = np.full((IMAGE_H, IMAGE_W, 3), 245, np.uint8) - noise
|
| 104 |
+
return Image.fromarray(arr)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def rle_in_inference_frame(x0, y0, x1, y1):
|
| 108 |
+
m = np.zeros((INFER_H, INFER_W), np.uint8)
|
| 109 |
+
m[y0:y1, x0:x1] = 1
|
| 110 |
+
encoded = mask_utils.encode(np.asfortranarray(m))
|
| 111 |
+
return {"size": [INFER_H, INFER_W], "counts": encoded["counts"].decode("ascii")}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def yolo_box(x0, y0, x1, y1):
|
| 115 |
+
"""Pixel corners in the IMAGE frame -> yolo-normalised [cx, cy, w, h]."""
|
| 116 |
+
return [
|
| 117 |
+
(x0 + x1) / 2 / IMAGE_W,
|
| 118 |
+
(y0 + y1) / 2 / IMAGE_H,
|
| 119 |
+
(x1 - x0) / IMAGE_W,
|
| 120 |
+
(y1 - y0) / IMAGE_H,
|
| 121 |
+
]
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def teacher_row(image_id, boxes, with_masks, error=None):
|
| 125 |
+
bbox = [yolo_box(*b) for b in boxes]
|
| 126 |
+
masks = (
|
| 127 |
+
[rle_in_inference_frame(*[v // 2 for v in b]) for b in boxes]
|
| 128 |
+
if with_masks
|
| 129 |
+
else []
|
| 130 |
+
)
|
| 131 |
+
return {
|
| 132 |
+
"__source_key": f"pages/{image_id}.jpg",
|
| 133 |
+
"image_id": image_id,
|
| 134 |
+
"width": None if error else IMAGE_W,
|
| 135 |
+
"height": None if error else IMAGE_H,
|
| 136 |
+
"objects": {
|
| 137 |
+
"bbox": bbox,
|
| 138 |
+
"category": [0] * len(bbox),
|
| 139 |
+
"area": [b[2] * b[3] for b in bbox],
|
| 140 |
+
"rectangularity": [1.0] * len(bbox),
|
| 141 |
+
},
|
| 142 |
+
"n_instances": len(bbox),
|
| 143 |
+
"masks_rle": json.dumps(masks),
|
| 144 |
+
"query": "illustration",
|
| 145 |
+
"gen_seconds": 0.1,
|
| 146 |
+
"error": error,
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def build_teacher_output(root):
|
| 151 |
+
"""parts/ (annotations-only), parts-corrected/, parts-embedded/ (with bytes), pages/, gold.parquet"""
|
| 152 |
+
pages = root / "pages" / "pages"
|
| 153 |
+
pages.mkdir(parents=True)
|
| 154 |
+
rows = [
|
| 155 |
+
teacher_row(1, PAGE1_BOXES, with_masks=True),
|
| 156 |
+
teacher_row(2, PAGE2_BOXES, with_masks=False),
|
| 157 |
+
teacher_row(GOLD_IMAGE_ID, [], with_masks=False),
|
| 158 |
+
teacher_row(
|
| 159 |
+
ERROR_IMAGE_ID, [], with_masks=False, error="OSError: truncated file"
|
| 160 |
+
),
|
| 161 |
+
]
|
| 162 |
+
blobs = {}
|
| 163 |
+
for row in rows:
|
| 164 |
+
path = pages / f"{row['image_id']}.jpg"
|
| 165 |
+
if row["error"]:
|
| 166 |
+
path.write_bytes(b"this is not a jpeg")
|
| 167 |
+
else:
|
| 168 |
+
synthetic_page(row["image_id"]).save(path, "JPEG", quality=95)
|
| 169 |
+
blobs[row["image_id"]] = path.read_bytes()
|
| 170 |
+
|
| 171 |
+
(root / "parts").mkdir()
|
| 172 |
+
pq.write_table(
|
| 173 |
+
pa.Table.from_pylist(rows, schema=PARTS_SCHEMA),
|
| 174 |
+
root / "parts" / "part-a.parquet",
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
corrected = [
|
| 178 |
+
teacher_row(2, PAGE2_CORRECTED, with_masks=False) if r["image_id"] == 2 else r
|
| 179 |
+
for r in rows
|
| 180 |
+
]
|
| 181 |
+
(root / "parts-corrected").mkdir()
|
| 182 |
+
pq.write_table(
|
| 183 |
+
pa.Table.from_pylist(corrected, schema=PARTS_SCHEMA),
|
| 184 |
+
root / "parts-corrected" / "part-a.parquet",
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
# --embed-images parts: the error row carries image=None (the teacher never read its bytes)
|
| 188 |
+
embedded = [
|
| 189 |
+
{
|
| 190 |
+
**r,
|
| 191 |
+
"image": None
|
| 192 |
+
if r["error"]
|
| 193 |
+
else {"bytes": blobs[r["image_id"]], "path": None},
|
| 194 |
+
}
|
| 195 |
+
for r in rows
|
| 196 |
+
]
|
| 197 |
+
(root / "parts-embedded").mkdir()
|
| 198 |
+
pq.write_table(
|
| 199 |
+
pa.Table.from_pylist(embedded, schema=PARTS_SCHEMA.append(IMAGE_FIELD)),
|
| 200 |
+
root / "parts-embedded" / "part-a.parquet",
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
gold = pa.table({"image_id": pa.array([GOLD_IMAGE_ID], pa.int64())})
|
| 204 |
+
pq.write_table(gold, root / "gold.parquet")
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def run(script, *argv):
|
| 208 |
+
# `uv run` so each script resolves its OWN PEP 723 header -- a bad dependency line in a
|
| 209 |
+
# child script is exactly the kind of breakage this test exists to catch
|
| 210 |
+
cmd = ["uv", "run", "--quiet", str(HERE / script), *map(str, argv)]
|
| 211 |
+
proc = subprocess.run(cmd, capture_output=True, text=True, check=False)
|
| 212 |
+
if proc.returncode != 0:
|
| 213 |
+
print(proc.stdout)
|
| 214 |
+
print(proc.stderr)
|
| 215 |
+
sys.exit(f"FAIL: {script} exited {proc.returncode}")
|
| 216 |
+
return proc.stdout
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def check(condition, message):
|
| 220 |
+
if not condition:
|
| 221 |
+
sys.exit(f"FAIL: {message}")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def check_embedded(out_dir, label, expect_ids=(1, 2)):
|
| 225 |
+
files = sorted(p.name for p in out_dir.glob("*.parquet"))
|
| 226 |
+
check(files == ["train.parquet", "validation.parquet"], f"{label}: wrote {files}")
|
| 227 |
+
ds = load_dataset("parquet", data_files=str(out_dir / "*.parquet"), split="train")
|
| 228 |
+
ids = sorted(ds["image_id"])
|
| 229 |
+
check(
|
| 230 |
+
ids == list(expect_ids),
|
| 231 |
+
f"{label}: expected pages {list(expect_ids)}, got {ids}",
|
| 232 |
+
)
|
| 233 |
+
check("image" in ds.column_names, f"{label}: no image column")
|
| 234 |
+
check(
|
| 235 |
+
type(ds.features["image"]).__name__ == "Image",
|
| 236 |
+
f"{label}: image column is not an Image feature",
|
| 237 |
+
)
|
| 238 |
+
names = ds.features["objects"]["category"].feature.names
|
| 239 |
+
check(names == ["illustration"], f"{label}: category names {names}")
|
| 240 |
+
print(f"OK embed-bucket-images ({label}): pages {ids}, Image column, one write")
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def load_tree(coco_dir):
|
| 244 |
+
"""All splits merged: which page lands in train vs val depends on the shuffle, the checks don't."""
|
| 245 |
+
images, anns, files, skipped = {}, [], 0, set()
|
| 246 |
+
for split_dir in ("train2017", "val2017"):
|
| 247 |
+
ann_path = coco_dir / "annotations" / f"instances_{split_dir}.json"
|
| 248 |
+
coco = json.loads(ann_path.read_text())
|
| 249 |
+
n_files = len(list((coco_dir / split_dir).glob("*.jpg")))
|
| 250 |
+
check(
|
| 251 |
+
n_files == len(coco["images"]),
|
| 252 |
+
f"{split_dir}: {n_files} files != {len(coco['images'])} referenced",
|
| 253 |
+
)
|
| 254 |
+
check(
|
| 255 |
+
coco["categories"] == [{"id": 1, "name": "illustration"}],
|
| 256 |
+
"categories wrong",
|
| 257 |
+
)
|
| 258 |
+
files += n_files
|
| 259 |
+
images.update({im["id"]: im for im in coco["images"]})
|
| 260 |
+
anns.extend(coco["annotations"])
|
| 261 |
+
skipped |= set(coco["provenance"]["skipped_image_ids"])
|
| 262 |
+
return images, anns, files, skipped
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def check_coco(coco_dir, page2_boxes=PAGE2_BOXES, expect_skipped=()):
|
| 266 |
+
images, annotations, n_files, skipped = load_tree(coco_dir)
|
| 267 |
+
check(
|
| 268 |
+
sorted(images) == [1, 2], f"tree holds pages {sorted(images)}, expected [1, 2]"
|
| 269 |
+
)
|
| 270 |
+
check(n_files == 2, f"{n_files} JPEGs in the tree, expected 2")
|
| 271 |
+
check(
|
| 272 |
+
skipped == set(expect_skipped),
|
| 273 |
+
f"skipped ids {skipped}, expected {set(expect_skipped)}",
|
| 274 |
+
)
|
| 275 |
+
by_image = {}
|
| 276 |
+
for ann in annotations:
|
| 277 |
+
by_image.setdefault(ann["image_id"], []).append(ann)
|
| 278 |
+
check(GOLD_IMAGE_ID not in by_image, "gold page leaked into the COCO tree")
|
| 279 |
+
check(ERROR_IMAGE_ID not in by_image, "error page leaked into the COCO tree")
|
| 280 |
+
for image_id, boxes in ((1, PAGE1_BOXES), (2, page2_boxes)):
|
| 281 |
+
anns = by_image.get(image_id, [])
|
| 282 |
+
check(
|
| 283 |
+
len(anns) == len(boxes),
|
| 284 |
+
f"page {image_id}: {len(anns)} annotations, expected {len(boxes)}",
|
| 285 |
+
)
|
| 286 |
+
for ann, (x0, y0, x1, y1) in zip(anns, boxes):
|
| 287 |
+
bx, by, bw, bh = [round(v) for v in ann["bbox"]]
|
| 288 |
+
check(
|
| 289 |
+
(bx, by, bw, bh) == (x0, y0, x1 - x0, y1 - y0),
|
| 290 |
+
f"bbox mismatch: {ann['bbox']}",
|
| 291 |
+
)
|
| 292 |
+
if image_id == 1:
|
| 293 |
+
seg = ann.get("segmentation")
|
| 294 |
+
check(seg is not None, "page 1 annotation lost its mask")
|
| 295 |
+
check(
|
| 296 |
+
seg["size"] == [IMAGE_H, IMAGE_W],
|
| 297 |
+
f"mask not resized to image frame: {seg['size']}",
|
| 298 |
+
)
|
| 299 |
+
m = mask_utils.decode({**seg, "counts": seg["counts"].encode()})
|
| 300 |
+
ys, xs = np.where(m)
|
| 301 |
+
extent = (xs.min(), ys.min(), xs.max() + 1, ys.max() + 1)
|
| 302 |
+
check(
|
| 303 |
+
extent == (x0, y0, x1, y1),
|
| 304 |
+
f"mask extent {extent} != box {(x0, y0, x1, y1)}",
|
| 305 |
+
)
|
| 306 |
+
else:
|
| 307 |
+
check(
|
| 308 |
+
"segmentation" not in ann,
|
| 309 |
+
"page 2 has no mask but got a segmentation",
|
| 310 |
+
)
|
| 311 |
+
print(
|
| 312 |
+
"OK materialize-coco: files == referenced, masks resized 500x400 -> 1000x800 and aligned to boxes, "
|
| 313 |
+
f"page 2 has {len(page2_boxes)} box(es)"
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def check_render(stdout, previews):
|
| 318 |
+
names = sorted(p.name for p in previews.glob("*.png"))
|
| 319 |
+
check(
|
| 320 |
+
names == ["1_2inst.png", "2_1inst.png", "3_0inst.png"],
|
| 321 |
+
f"unexpected previews: {names}",
|
| 322 |
+
)
|
| 323 |
+
check("OK: 2 non-empty renders verified" in stdout, "render did not verify 2 pages")
|
| 324 |
+
check(
|
| 325 |
+
"skipped 1 undecodable/error rows" in stdout,
|
| 326 |
+
"render did not skip the undecodable page",
|
| 327 |
+
)
|
| 328 |
+
print(
|
| 329 |
+
"OK render-detections: 2 overlays pixel-verified, empty page not flagged, undecodable page skipped"
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def main():
|
| 334 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 335 |
+
tmp = Path(tmp)
|
| 336 |
+
build_teacher_output(tmp)
|
| 337 |
+
print(f"fixture: 4 pages of teacher output -> {tmp}")
|
| 338 |
+
|
| 339 |
+
# 1. annotations-only parts + local source dir (the default teacher output):
|
| 340 |
+
# error row dropped by default, gold page excluded
|
| 341 |
+
run(
|
| 342 |
+
"embed-bucket-images.py",
|
| 343 |
+
"--parts",
|
| 344 |
+
tmp / "parts" / "part-*.parquet",
|
| 345 |
+
"--src",
|
| 346 |
+
tmp / "pages",
|
| 347 |
+
"--gold",
|
| 348 |
+
tmp / "gold.parquet",
|
| 349 |
+
"--out",
|
| 350 |
+
tmp / "dataset",
|
| 351 |
+
"--val-frac",
|
| 352 |
+
"0.5",
|
| 353 |
+
"--chunk",
|
| 354 |
+
"1",
|
| 355 |
+
)
|
| 356 |
+
check_embedded(tmp / "dataset", "annotations-only parts + --src")
|
| 357 |
+
|
| 358 |
+
# 2. parts that already carry the bytes (teacher ran with --embed-images): no --src
|
| 359 |
+
run(
|
| 360 |
+
"embed-bucket-images.py",
|
| 361 |
+
"--parts",
|
| 362 |
+
tmp / "parts-embedded" / "part-*.parquet",
|
| 363 |
+
"--gold",
|
| 364 |
+
tmp / "gold.parquet",
|
| 365 |
+
"--out",
|
| 366 |
+
tmp / "dataset-embedded",
|
| 367 |
+
"--val-frac",
|
| 368 |
+
"0.5",
|
| 369 |
+
)
|
| 370 |
+
check_embedded(tmp / "dataset-embedded", "--embed-images parts, no --src")
|
| 371 |
+
|
| 372 |
+
# 3. --keep-errors: the undecodable page must reach the next step, which must survive it
|
| 373 |
+
run(
|
| 374 |
+
"embed-bucket-images.py",
|
| 375 |
+
"--parts",
|
| 376 |
+
tmp / "parts" / "part-*.parquet",
|
| 377 |
+
"--src",
|
| 378 |
+
tmp / "pages",
|
| 379 |
+
"--gold",
|
| 380 |
+
tmp / "gold.parquet",
|
| 381 |
+
"--out",
|
| 382 |
+
tmp / "dataset-kept",
|
| 383 |
+
"--val-frac",
|
| 384 |
+
"0.34",
|
| 385 |
+
"--keep-errors",
|
| 386 |
+
)
|
| 387 |
+
check_embedded(
|
| 388 |
+
tmp / "dataset-kept", "--keep-errors", expect_ids=(1, 2, ERROR_IMAGE_ID)
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
# 4. COCO tree (undecodable row skipped, not crashed), then a second run must reuse it
|
| 392 |
+
run(
|
| 393 |
+
"materialize-coco.py", "--data", tmp / "dataset-kept", "--out", tmp / "coco"
|
| 394 |
+
)
|
| 395 |
+
check_coco(tmp / "coco", expect_skipped=(ERROR_IMAGE_ID,))
|
| 396 |
+
again = run(
|
| 397 |
+
"materialize-coco.py", "--data", tmp / "dataset-kept", "--out", tmp / "coco"
|
| 398 |
+
)
|
| 399 |
+
check(
|
| 400 |
+
again.count("reusing complete tree") == 2,
|
| 401 |
+
f"second run rebuilt instead of reusing:\n{again}",
|
| 402 |
+
)
|
| 403 |
+
print("OK materialize-coco: second run reused both complete trees")
|
| 404 |
+
|
| 405 |
+
# 5. same images, CORRECTED labels (the step-6 loop) -> the tree must rebuild, not reuse
|
| 406 |
+
run(
|
| 407 |
+
"embed-bucket-images.py",
|
| 408 |
+
"--parts",
|
| 409 |
+
tmp / "parts-corrected" / "part-*.parquet",
|
| 410 |
+
"--src",
|
| 411 |
+
tmp / "pages",
|
| 412 |
+
"--gold",
|
| 413 |
+
tmp / "gold.parquet",
|
| 414 |
+
"--out",
|
| 415 |
+
tmp / "dataset-corrected",
|
| 416 |
+
"--val-frac",
|
| 417 |
+
"0.5",
|
| 418 |
+
)
|
| 419 |
+
rebuilt = run(
|
| 420 |
+
"materialize-coco.py",
|
| 421 |
+
"--data",
|
| 422 |
+
tmp / "dataset-corrected",
|
| 423 |
+
"--out",
|
| 424 |
+
tmp / "coco",
|
| 425 |
+
)
|
| 426 |
+
# the fingerprint is per split: only the split holding page 2 must rebuild, the other may reuse
|
| 427 |
+
check(
|
| 428 |
+
"labels changed" in rebuilt,
|
| 429 |
+
f"corrected labels did not trigger a rebuild:\n{rebuilt}",
|
| 430 |
+
)
|
| 431 |
+
check_coco(tmp / "coco", page2_boxes=PAGE2_CORRECTED)
|
| 432 |
+
print(
|
| 433 |
+
"OK materialize-coco: corrected labels rebuilt the tree (fingerprint), new box present"
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
# 6. --force over a tree holding a stale JPEG must come back clean
|
| 437 |
+
(tmp / "coco" / "train2017" / "999.jpg").write_bytes(b"stale")
|
| 438 |
+
run(
|
| 439 |
+
"materialize-coco.py",
|
| 440 |
+
"--data",
|
| 441 |
+
tmp / "dataset-corrected",
|
| 442 |
+
"--out",
|
| 443 |
+
tmp / "coco",
|
| 444 |
+
"--force",
|
| 445 |
+
)
|
| 446 |
+
check(
|
| 447 |
+
not (tmp / "coco" / "train2017" / "999.jpg").exists(),
|
| 448 |
+
"--force left a stale JPEG in the tree",
|
| 449 |
+
)
|
| 450 |
+
check_coco(tmp / "coco", page2_boxes=PAGE2_CORRECTED)
|
| 451 |
+
print("OK materialize-coco: --force cleared the stale file and rebuilt clean")
|
| 452 |
+
|
| 453 |
+
# 7. overlays over the raw teacher pages (all 4, incl. the empty and the undecodable one)
|
| 454 |
+
run(
|
| 455 |
+
"embed-bucket-images.py",
|
| 456 |
+
"--parts",
|
| 457 |
+
tmp / "parts" / "part-*.parquet",
|
| 458 |
+
"--src",
|
| 459 |
+
tmp / "pages",
|
| 460 |
+
"--out",
|
| 461 |
+
tmp / "all",
|
| 462 |
+
"--val-frac",
|
| 463 |
+
"0.25",
|
| 464 |
+
"--keep-errors",
|
| 465 |
+
)
|
| 466 |
+
out = run(
|
| 467 |
+
"render-detections.py", tmp / "all" / "*.parquet", "--out", tmp / "previews"
|
| 468 |
+
)
|
| 469 |
+
check_render(out, tmp / "previews")
|
| 470 |
+
|
| 471 |
+
print("SMOKE TEST GREEN")
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
if __name__ == "__main__":
|
| 475 |
+
main()
|