Sync from GitHub via hub-sync
Browse files- README.md +76 -1
- falcon-perception-bucket.py +239 -0
- falcon-perception.py +429 -0
README.md
CHANGED
|
@@ -5,7 +5,9 @@ tags: [uv-script, object-detection]
|
|
| 5 |
|
| 6 |
# Object Detection Dataset Scripts
|
| 7 |
|
| 8 |
-
|
|
|
|
|
|
|
| 9 |
This repository is inspired by [panlabel](https://github.com/strickvl/panlabel)
|
| 10 |
|
| 11 |
## Quick Start
|
|
@@ -29,6 +31,8 @@ That's it! The script will:
|
|
| 29 |
|
| 30 |
| Script | Description |
|
| 31 |
|--------|-------------|
|
|
|
|
|
|
|
| 32 |
| `convert-hf-dataset.py` | Convert between 6 bbox formats and push to Hub |
|
| 33 |
| `validate-hf-dataset.py` | Check annotations for errors (invalid bboxes, duplicates, bounds) |
|
| 34 |
| `stats-hf-dataset.py` | Compute statistics (counts, label histogram, area, co-occurrence) |
|
|
@@ -242,3 +246,74 @@ uv run https://huggingface.co/datasets/uv-scripts/panlabel/raw/main/convert-hf-d
|
|
| 242 |
```
|
| 243 |
|
| 244 |
Works with any Hugging Face dataset containing object detection annotations — COCO, YOLO, VOC, TFOD, or Label Studio format.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
| 12 |
|
| 13 |
## Quick Start
|
|
|
|
| 31 |
|
| 32 |
| Script | Description |
|
| 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) |
|
|
|
|
| 246 |
```
|
| 247 |
|
| 248 |
Works with any Hugging Face dataset containing object detection annotations — COCO, YOLO, VOC, TFOD, or Label Studio format.
|
| 249 |
+
|
| 250 |
+
## Making a dataset from scratch
|
| 251 |
+
|
| 252 |
+
The other scripts assume you already have annotations. `falcon-perception.py` is where they can come from — [Falcon-Perception](https://huggingface.co/tiiuae/Falcon-Perception) finds every instance of a class you name, with no label set and no training:
|
| 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.
|
| 273 |
+
|
| 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 |
+
|
| 286 |
+
Measured, not guessed — see the script docstrings for the failure each one came from.
|
| 287 |
+
|
| 288 |
+
| Limit | What to do |
|
| 289 |
+
|---|---|
|
| 290 |
+
| `--query` is a **class name**, not an instruction | `illustration` works; `the illustration, excluding captions` returns nothing |
|
| 291 |
+
| **One class per run** | A combined query returned 6 instances where three single-class runs found 24. N classes = N runs, then concatenate |
|
| 292 |
+
| **No confidence scores** — the model has no score token | Sort review by the emitted `rectangularity` (mask area ÷ bbox area, measured 0.34–1.00) and apply an area floor |
|
| 293 |
+
| `a10g-small` gets OOMKilled | The engine's auto-config sizes from the GPU and ignores host RAM — use `a10g-large` |
|
| 294 |
+
|
| 295 |
+
### Just want the numbers?
|
| 296 |
+
|
| 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.
|
| 306 |
+
|
| 307 |
+
### Bucket runs
|
| 308 |
+
|
| 309 |
+
`falcon-perception-bucket.py` reads images from an HF bucket and writes resumable parquet parts back to a bucket — kill it and re-run the same command, done keys are skipped. Publish once at the end to use the rest of this directory:
|
| 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).
|
falcon-perception-bucket.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env -S uv run --script
|
| 2 |
+
# /// script
|
| 3 |
+
# requires-python = ">=3.10"
|
| 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.0.tar.gz",
|
| 8 |
+
# "pyarrow>=18",
|
| 9 |
+
# "pycocotools>=2.0.11",
|
| 10 |
+
# ]
|
| 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
|
| 19 |
+
Engine : PagedInferenceEngine (CUDA, continuous batching)
|
| 20 |
+
Output : one parquet per batch -> out bucket; resume via completed_keys(__source_key)
|
| 21 |
+
|
| 22 |
+
Kill it at any point and re-run the same command. Done keys are skipped.
|
| 23 |
+
|
| 24 |
+
Output is parquet parts in a BUCKET, not a dataset repo — that is what makes the
|
| 25 |
+
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 |
+
|
| 35 |
+
Note the parts carry `width`/`height` but no `image` column (the images stay in
|
| 36 |
+
the source bucket), so pass --image-column accordingly if a downstream script
|
| 37 |
+
wants to decode them.
|
| 38 |
+
|
| 39 |
+
GOTCHAS (all measured, none in the model card):
|
| 40 |
+
* --query is a CLASS NAME. "illustration" works; "the illustration, excluding
|
| 41 |
+
captions" returns nothing.
|
| 42 |
+
* torch.compile breaks on per-image dynamic shapes -> compile is OFF here.
|
| 43 |
+
* engine_config_for_gpu() sizes from the GPU and ignores host RAM; on
|
| 44 |
+
a10g-small it gets OOMKilled (exit 137) before processing anything.
|
| 45 |
+
cudagraph is off by default here for the same reason.
|
| 46 |
+
* xy in the output is the NORMALISED CENTRE, not a corner.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
import argparse
|
| 50 |
+
import io
|
| 51 |
+
import json
|
| 52 |
+
import time
|
| 53 |
+
|
| 54 |
+
import pyarrow as pa
|
| 55 |
+
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([
|
| 68 |
+
("bbox", pa.list_(pa.list_(pa.float32()))), # yolo: cx, cy, w, h normalised
|
| 69 |
+
("category", pa.list_(pa.int64())), # single class per run, by design
|
| 70 |
+
("area", pa.list_(pa.float32())),
|
| 71 |
+
("rectangularity", pa.list_(pa.float32())), # triage proxy — no confidence score exists
|
| 72 |
+
])),
|
| 73 |
+
("n_instances", pa.int32()),
|
| 74 |
+
("masks_rle", pa.string()),
|
| 75 |
+
("query", pa.string()),
|
| 76 |
+
("gen_seconds", pa.float32()),
|
| 77 |
+
("error", pa.string()),
|
| 78 |
+
])
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def pair_bboxes(raw):
|
| 82 |
+
boxes, cur = [], {}
|
| 83 |
+
for e in raw:
|
| 84 |
+
if not isinstance(e, dict):
|
| 85 |
+
continue
|
| 86 |
+
cur.update(e)
|
| 87 |
+
if all(k in cur for k in ("x", "y", "h", "w")):
|
| 88 |
+
boxes.append(dict(cur)); cur = {}
|
| 89 |
+
return boxes
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def serialise(rows, fmt):
|
| 93 |
+
if fmt == "jsonl":
|
| 94 |
+
return "\n".join(json.dumps(r) for r in rows) + "\n"
|
| 95 |
+
buf = io.BytesIO()
|
| 96 |
+
pq.write_table(pa.Table.from_pylist(rows, schema=SCHEMA), buf, compression="zstd")
|
| 97 |
+
return buf.getvalue()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def main():
|
| 101 |
+
p = argparse.ArgumentParser()
|
| 102 |
+
p.add_argument("--src", required=True, help="source bucket, e.g. biglam/bl-images")
|
| 103 |
+
p.add_argument("--prefix", default=None, help="bucket prefix, e.g. full/embellishments")
|
| 104 |
+
p.add_argument("--out", required=True, help="output bucket")
|
| 105 |
+
p.add_argument("--query", default="illustration", help="a CLASS NAME, not an instruction")
|
| 106 |
+
p.add_argument("--task", default="segmentation", choices=["segmentation", "detection"])
|
| 107 |
+
p.add_argument("--limit", type=int, default=None)
|
| 108 |
+
p.add_argument("--max-dim", type=int, default=1024)
|
| 109 |
+
p.add_argument("--max-new-tokens", type=int, default=200)
|
| 110 |
+
p.add_argument("--batch-n", type=int, default=32, help="files per bucketbag batch")
|
| 111 |
+
p.add_argument("--max-bytes", type=int, default=2 * 2**30)
|
| 112 |
+
p.add_argument("--cudagraph", action="store_true", help="opt IN; off by default (host OOM)")
|
| 113 |
+
p.add_argument("--format", default="parquet", choices=["parquet", "jsonl"])
|
| 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 |
+
|
| 122 |
+
# objects=True yields BucketFile (with .size), so max_bytes is honoured.
|
| 123 |
+
# Needs bucketbag >= 0.3.0: before that, string keys made batched_files drop
|
| 124 |
+
# max_bytes silently and run unbounded against RAM-tmpfs scratch.
|
| 125 |
+
keys = [
|
| 126 |
+
f for f in iter_keys(args.src, prefix=args.prefix, objects=True)
|
| 127 |
+
if f.path.lower().endswith((".jpg", ".jpeg", ".png")) and f.path not in done
|
| 128 |
+
]
|
| 129 |
+
if args.limit:
|
| 130 |
+
keys = keys[: args.limit]
|
| 131 |
+
print(f"{len(keys)} keys to process", flush=True)
|
| 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 (
|
| 139 |
+
PagedInferenceEngine, SamplingParams, Sequence, engine_config_for_gpu,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
setup_torch_config()
|
| 143 |
+
t = time.perf_counter()
|
| 144 |
+
model, tokenizer, _ = load_and_prepare_model(
|
| 145 |
+
hf_model_id=PERCEPTION_MODEL_ID, dtype="bfloat16", compile=False, # compile breaks on dynamic shapes
|
| 146 |
+
)
|
| 147 |
+
print(f"model loaded in {time.perf_counter() - t:.1f}s", flush=True)
|
| 148 |
+
|
| 149 |
+
cfg = engine_config_for_gpu(max_image_size=args.max_dim, dtype=model.dtype)
|
| 150 |
+
print(f"paged config: {cfg}", flush=True)
|
| 151 |
+
engine = PagedInferenceEngine(
|
| 152 |
+
model, tokenizer, ImageProcessor(patch_size=16, merge_size=1),
|
| 153 |
+
max_seq_length=8192, capture_cudagraph=args.cudagraph, **cfg,
|
| 154 |
+
)
|
| 155 |
+
sp = SamplingParams(
|
| 156 |
+
args.max_new_tokens,
|
| 157 |
+
stop_token_ids=[tokenizer.eos_token_id, tokenizer.end_of_query_token_id],
|
| 158 |
+
coord_dedup_threshold=0.01,
|
| 159 |
+
)
|
| 160 |
+
prompt = build_prompt_for_task(args.query, args.task)
|
| 161 |
+
|
| 162 |
+
n, gen_total, t_all, batch_i = 0, 0.0, time.perf_counter(), 0
|
| 163 |
+
for batch in batched_files(args.src, keys=keys, n=args.batch_n, max_bytes=args.max_bytes):
|
| 164 |
+
# NOTE: never hold a LoadedItem past its batch — convert eagerly.
|
| 165 |
+
pairs = []
|
| 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:
|
| 183 |
+
engine.generate(seqs, sampling_params=sp)
|
| 184 |
+
dt = time.perf_counter() - t0
|
| 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
|
| 199 |
+
a = b["w"] * b["h"]
|
| 200 |
+
area.append(a)
|
| 201 |
+
r = 0.0
|
| 202 |
+
if i < len(masks): # rectangularity — the only triage signal; no score exists
|
| 203 |
+
try:
|
| 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) "
|
| 231 |
+
f"total {n} {rate:.2f} img/s", flush=True)
|
| 232 |
+
|
| 233 |
+
wall = time.perf_counter() - t_all
|
| 234 |
+
print(f"\n{n} images in {wall:.1f}s ({gen_total:.1f}s generation) | {n / wall:.2f} img/s", flush=True)
|
| 235 |
+
if n:
|
| 236 |
+
print(f"extrapolation: 100k images ≈ {wall / n * 100_000 / 3600:.1f} GPU-hours end-to-end", flush=True)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
main()
|
falcon-perception.py
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env -S uv run --script
|
| 2 |
+
# /// script
|
| 3 |
+
# requires-python = ">=3.10"
|
| 4 |
+
# dependencies = [
|
| 5 |
+
# "falcon-perception>=1.0.0",
|
| 6 |
+
# "datasets>=4.5.0",
|
| 7 |
+
# "huggingface-hub>=1.12.0",
|
| 8 |
+
# "pillow",
|
| 9 |
+
# ]
|
| 10 |
+
# ///
|
| 11 |
+
"""Zero-shot object detection + instance segmentation -> a YOLO detection dataset.
|
| 12 |
+
|
| 13 |
+
Falcon-Perception finds every instance of a class you name, with no training and
|
| 14 |
+
no label set. Output is a detection dataset in `yolo` format, so it feeds the
|
| 15 |
+
other recipes in this directory directly:
|
| 16 |
+
|
| 17 |
+
validate-hf-dataset.py you/first-pass --bbox-format yolo
|
| 18 |
+
stats-hf-dataset.py you/first-pass --bbox-format yolo
|
| 19 |
+
convert-hf-dataset.py you/first-pass you/for-review --from yolo --to label_studio
|
| 20 |
+
# ... a human corrects the first pass in Label Studio ...
|
| 21 |
+
diff-hf-datasets.py you/first-pass you/corrected # IoU -> zero-shot accuracy
|
| 22 |
+
|
| 23 |
+
RUNS ON YOUR LAPTOP TOO. Unusually for this repo no CUDA GPU is required: on
|
| 24 |
+
Apple Silicon it selects the MLX backend automatically. Slower (~6 s/img vs
|
| 25 |
+
~0.4 on an A10G), which is fine for the step that matters locally -- checking
|
| 26 |
+
your class name works on your images before spending GPU hours on the corpus.
|
| 27 |
+
|
| 28 |
+
# 1. does the model do the thing?
|
| 29 |
+
uv run falcon-perception.py --image page.jpg --query illustration --preview
|
| 30 |
+
|
| 31 |
+
# 2. does it work on MY data? (first rows of the real corpus)
|
| 32 |
+
uv run falcon-perception.py --dataset biglam/british-library-book-images \
|
| 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 |
+
|
| 40 |
+
Output goes wherever --out points:
|
| 41 |
+
|
| 42 |
+
--out you/plates-illustrations a Hub dataset (yolo format, feeds the scripts above)
|
| 43 |
+
--out results.json a local JSON file -- no Hub push
|
| 44 |
+
--out results.jsonl a local JSONL file -- one record per line
|
| 45 |
+
--out results.parquet a local parquet file
|
| 46 |
+
--json also print the records on stdout, for piping
|
| 47 |
+
(omit --out) print a summary and, with --preview, annotated JPEGs
|
| 48 |
+
|
| 49 |
+
For images in a bucket rather than a dataset, see falcon-perception-bucket.py.
|
| 50 |
+
|
| 51 |
+
MEASURED LIMITS -- not guesses; each one cost a failed run:
|
| 52 |
+
|
| 53 |
+
* --query takes a CLASS NAME, never an instruction. "illustration" works;
|
| 54 |
+
"the illustration, excluding captions" returns nothing at all.
|
| 55 |
+
* ONE class per run. A combined query ("illustration, map, portrait") returned
|
| 56 |
+
6 instances where three single-class passes found 24, and emitted <|absence|>
|
| 57 |
+
on the richest image. The output vocabulary has no class token either, so
|
| 58 |
+
instances could not be attributed even if the counts held. N classes = N runs.
|
| 59 |
+
* NO confidence scores -- the model has no score token. Two triage proxies are
|
| 60 |
+
emitted instead: `rectangularity` (mask area / bbox area; measured 0.34-1.00,
|
| 61 |
+
low = irregular, 1.00 = clean rectangular plate) and `area`. Sort review by
|
| 62 |
+
rectangularity ascending and apply an area floor; the smallest box seen was
|
| 63 |
+
941 px^2 and was spurious.
|
| 64 |
+
* torch.compile is OFF. Per-image dynamic shapes break Inductor
|
| 65 |
+
("ValueError: Exponent must be non-negative" after symbolic-shape recursion).
|
| 66 |
+
* CUDA graphs are OFF by default. engine_config_for_gpu() sizes itself from the
|
| 67 |
+
GPU and ignores host RAM; on a10g-small the container is OOMKilled (exit 137)
|
| 68 |
+
before one image is processed. Use a10g-large, or pass --cudagraph knowingly.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
import argparse
|
| 72 |
+
import glob as globlib
|
| 73 |
+
import io
|
| 74 |
+
import itertools
|
| 75 |
+
import json
|
| 76 |
+
import os
|
| 77 |
+
import pathlib
|
| 78 |
+
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
|
| 85 |
+
# moved with .to(device). Omitting the last fails deep inside
|
| 86 |
+
# flex_attention.create_block_mask, nowhere near the actual cause.
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def pick_backend(requested):
|
| 90 |
+
if requested != "auto":
|
| 91 |
+
return requested
|
| 92 |
+
return "mlx" if (sys.platform == "darwin" and platform.machine() == "arm64") else "torch"
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def guard_mlx_memory(frac=0.55):
|
| 96 |
+
"""MLX allocates from unified memory with NO default cap.
|
| 97 |
+
|
| 98 |
+
An oversized image through the AnyUp upsampler exhausts system RAM and hangs
|
| 99 |
+
the whole machine -- the process is never OOM-killed, because there is no
|
| 100 |
+
separate GPU pool for the kernel to reclaim. Measured: 0.22 MP ran fine;
|
| 101 |
+
5.4 MP took down a 32 GiB Mac whose MLX default ceiling was 30.4 GiB.
|
| 102 |
+
"""
|
| 103 |
+
try:
|
| 104 |
+
import mlx.core as mx
|
| 105 |
+
|
| 106 |
+
total = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
|
| 107 |
+
mx.set_memory_limit(int(total * frac))
|
| 108 |
+
print(f"mlx memory capped at {total * frac / 2**30:.1f} GiB", flush=True)
|
| 109 |
+
except Exception as e:
|
| 110 |
+
print(f"WARNING: could not cap MLX memory ({e}) -- a large image may hang this machine", flush=True)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# ── sources: every source yields (key, PIL image) ───────────────────────────
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def src_images(spec):
|
| 117 |
+
from falcon_perception.data import load_image
|
| 118 |
+
from PIL import Image
|
| 119 |
+
|
| 120 |
+
if spec.startswith(("http://", "https://")):
|
| 121 |
+
from urllib.parse import unquote
|
| 122 |
+
|
| 123 |
+
yield unquote(spec.rsplit("/", 1)[-1])[:120], load_image(spec).convert("RGB")
|
| 124 |
+
return
|
| 125 |
+
paths = sorted(globlib.glob(spec)) if any(c in spec for c in "*?[") else [spec]
|
| 126 |
+
if not paths:
|
| 127 |
+
raise SystemExit(f"no files matched {spec!r}")
|
| 128 |
+
for p in paths:
|
| 129 |
+
yield os.path.basename(p), Image.open(p).convert("RGB")
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def src_dataset(repo, config, split, image_col, id_col):
|
| 133 |
+
from datasets import load_dataset
|
| 134 |
+
from PIL import Image
|
| 135 |
+
|
| 136 |
+
ds = load_dataset(repo, config, split=split, streaming=True)
|
| 137 |
+
for idx, row in enumerate(ds):
|
| 138 |
+
im = row[image_col]
|
| 139 |
+
if isinstance(im, dict) and "bytes" in im:
|
| 140 |
+
im = Image.open(io.BytesIO(im["bytes"]))
|
| 141 |
+
yield (str(row.get(id_col)) if id_col else str(idx)), im.convert("RGB")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# ── helpers ─────────────────────────────────────────────────────────────────
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def pair_bboxes(raw):
|
| 148 |
+
"""[{x,y}, {h,w}, ...] -> [{x,y,h,w}, ...]. xy is the normalised CENTRE.
|
| 149 |
+
|
| 150 |
+
Centre-not-corner is why the output is natively `yolo` -- and why a corner
|
| 151 |
+
reading would put every box out of bounds.
|
| 152 |
+
"""
|
| 153 |
+
boxes, cur = [], {}
|
| 154 |
+
for e in raw:
|
| 155 |
+
if not isinstance(e, dict):
|
| 156 |
+
continue
|
| 157 |
+
cur.update(e)
|
| 158 |
+
if all(k in cur for k in ("x", "y", "h", "w")):
|
| 159 |
+
boxes.append(dict(cur))
|
| 160 |
+
cur = {}
|
| 161 |
+
return boxes
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def fit(im, max_dim, backend):
|
| 165 |
+
"""Downscale BEFORE the preprocessor sees it -- on MLX the full-size
|
| 166 |
+
intermediate is what exhausts memory."""
|
| 167 |
+
budget = max_dim if backend == "mlx" else max_dim * 2
|
| 168 |
+
if max(im.size) > budget:
|
| 169 |
+
im = im.copy()
|
| 170 |
+
im.thumbnail((budget, budget))
|
| 171 |
+
return im
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def save_preview(key, im, boxes, rles, out_dir):
|
| 175 |
+
import numpy as np
|
| 176 |
+
from PIL import Image, ImageDraw
|
| 177 |
+
from pycocotools import mask as mask_utils
|
| 178 |
+
|
| 179 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 180 |
+
W, H = im.size
|
| 181 |
+
canvas = np.array(im.convert("RGB"), dtype=np.float32)
|
| 182 |
+
for i, rle in enumerate(rles):
|
| 183 |
+
m = rle if isinstance(rle.get("counts"), bytes) else {**rle, "counts": str(rle["counts"]).encode()}
|
| 184 |
+
try:
|
| 185 |
+
dec = mask_utils.decode(m).astype("uint8")
|
| 186 |
+
except Exception:
|
| 187 |
+
continue
|
| 188 |
+
if dec.shape != (H, W): # mask is at model resolution -- NEAREST only
|
| 189 |
+
dec = np.array(Image.fromarray(dec).resize((W, H), Image.NEAREST))
|
| 190 |
+
col = np.array([(255, 60, 60), (60, 160, 255), (80, 200, 120)][i % 3], dtype=np.float32)
|
| 191 |
+
sel = dec > 0
|
| 192 |
+
canvas[sel] = canvas[sel] * 0.65 + col * 0.35
|
| 193 |
+
out = Image.fromarray(canvas.clip(0, 255).astype("uint8"))
|
| 194 |
+
pen = ImageDraw.Draw(out)
|
| 195 |
+
for b in boxes:
|
| 196 |
+
cx, cy, bw, bh = b["x"] * W, b["y"] * H, b["w"] * W, b["h"] * H
|
| 197 |
+
pen.rectangle([cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2], outline=(255, 220, 0), width=3)
|
| 198 |
+
safe = "".join(c if c.isalnum() or c in "._-" else "_" for c in key)[:80]
|
| 199 |
+
path = os.path.join(out_dir, f"{safe}.jpg")
|
| 200 |
+
out.save(path)
|
| 201 |
+
return path
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def batched(it, n):
|
| 205 |
+
buf = []
|
| 206 |
+
for x in it:
|
| 207 |
+
buf.append(x)
|
| 208 |
+
if len(buf) == n:
|
| 209 |
+
yield buf
|
| 210 |
+
buf = []
|
| 211 |
+
if buf:
|
| 212 |
+
yield buf
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# ── the two generation paths ────────────────────────────────────────────────
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def run_paged(model, tokenizer, items, prompt, args):
|
| 219 |
+
"""CUDA: TII's continuous-batching engine. ~0.4 s/img on an A10G."""
|
| 220 |
+
from falcon_perception.data import ImageProcessor
|
| 221 |
+
from falcon_perception.paged_inference import (
|
| 222 |
+
PagedInferenceEngine,
|
| 223 |
+
SamplingParams,
|
| 224 |
+
Sequence,
|
| 225 |
+
engine_config_for_gpu,
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
cfg = engine_config_for_gpu(max_image_size=args.max_dim, dtype=model.dtype)
|
| 229 |
+
print(f"paged config: {cfg}", flush=True)
|
| 230 |
+
engine = PagedInferenceEngine(
|
| 231 |
+
model, tokenizer, ImageProcessor(patch_size=16, merge_size=1),
|
| 232 |
+
max_seq_length=8192, capture_cudagraph=args.cudagraph, **cfg,
|
| 233 |
+
)
|
| 234 |
+
sp = SamplingParams(
|
| 235 |
+
args.max_new_tokens,
|
| 236 |
+
stop_token_ids=[tokenizer.eos_token_id, tokenizer.end_of_query_token_id],
|
| 237 |
+
coord_dedup_threshold=0.01,
|
| 238 |
+
)
|
| 239 |
+
for chunk in batched(items, args.chunk):
|
| 240 |
+
chunk = [(k, fit(im, args.max_dim, "torch")) for k, im in chunk]
|
| 241 |
+
seqs = [
|
| 242 |
+
Sequence(text=prompt, image=im, min_image_size=256,
|
| 243 |
+
max_image_size=args.max_dim, request_idx=i, task=args.task)
|
| 244 |
+
for i, (_, im) in enumerate(chunk)
|
| 245 |
+
]
|
| 246 |
+
t0 = time.perf_counter()
|
| 247 |
+
engine.generate(seqs, sampling_params=sp)
|
| 248 |
+
dt = (time.perf_counter() - t0) / len(seqs)
|
| 249 |
+
for (k, im), s in zip(chunk, seqs):
|
| 250 |
+
yield k, im, s.output_aux, dt
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def run_batch(model, tokenizer, items, prompt, args, backend, max_seq_len):
|
| 254 |
+
"""MLX (and a torch fallback): the readable reference engine. ~6 s/img on an M1 Pro."""
|
| 255 |
+
if backend == "mlx":
|
| 256 |
+
from falcon_perception.mlx.batch_inference import BatchInferenceEngine, process_batch_and_generate
|
| 257 |
+
else:
|
| 258 |
+
from falcon_perception.batch_inference import BatchInferenceEngine, process_batch_and_generate
|
| 259 |
+
|
| 260 |
+
engine = BatchInferenceEngine(model, tokenizer)
|
| 261 |
+
for chunk in batched(items, 1 if backend == "mlx" else args.chunk):
|
| 262 |
+
chunk = [(k, fit(im, args.max_dim, backend)) for k, im in chunk]
|
| 263 |
+
b = process_batch_and_generate(
|
| 264 |
+
tokenizer, [(im, prompt) for _, im in chunk],
|
| 265 |
+
max_length=max_seq_len, min_dimension=256, max_dimension=args.max_dim,
|
| 266 |
+
)
|
| 267 |
+
if backend != "mlx": # torch needs every tensor on the model's device
|
| 268 |
+
import torch
|
| 269 |
+
|
| 270 |
+
b = {k2: (v.to(model.device) if torch.is_tensor(v) else v) for k2, v in b.items()}
|
| 271 |
+
t0 = time.perf_counter()
|
| 272 |
+
_, auxes = engine.generate(
|
| 273 |
+
tokens=b["tokens"], pos_t=b["pos_t"], pos_hw=b["pos_hw"],
|
| 274 |
+
pixel_values=b["pixel_values"], pixel_mask=b["pixel_mask"],
|
| 275 |
+
max_new_tokens=args.max_new_tokens, temperature=0.0, task=args.task,
|
| 276 |
+
)
|
| 277 |
+
dt = (time.perf_counter() - t0) / len(chunk)
|
| 278 |
+
for (k, im), aux in zip(chunk, auxes):
|
| 279 |
+
yield k, im, aux, dt
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
# ── main ────────────────────────────────────────────────────────────────────
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def main():
|
| 286 |
+
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 287 |
+
s = p.add_mutually_exclusive_group(required=True)
|
| 288 |
+
s.add_argument("--image", help="path, URL, or glob ('scans/*.jpg')")
|
| 289 |
+
s.add_argument("--dataset", help="Hub dataset repo id (streamed)")
|
| 290 |
+
p.add_argument("--config")
|
| 291 |
+
p.add_argument("--split", default="train")
|
| 292 |
+
p.add_argument("--image-col", default="image")
|
| 293 |
+
p.add_argument("--id-col", default=None, help="stable id column; falls back to row index")
|
| 294 |
+
p.add_argument("--query", required=True, help="a CLASS NAME, not an instruction")
|
| 295 |
+
p.add_argument("--task", default="segmentation", choices=["segmentation", "detection"])
|
| 296 |
+
p.add_argument("--out", default=None,
|
| 297 |
+
help="where results go. A path ending .json/.jsonl/.parquet writes that file "
|
| 298 |
+
"locally; anything else is treated as a Hub dataset repo id. Omit for "
|
| 299 |
+
"stdout + previews only.")
|
| 300 |
+
p.add_argument("--json", action="store_true",
|
| 301 |
+
help="also print the records as JSON on stdout (for piping / agents)")
|
| 302 |
+
p.add_argument("--private", action="store_true")
|
| 303 |
+
p.add_argument("--limit", type=int, default=None, help="3 for a sense check")
|
| 304 |
+
p.add_argument("--preview", action="store_true", help="save annotated JPEGs")
|
| 305 |
+
p.add_argument("--preview-dir", default="./falcon-preview")
|
| 306 |
+
p.add_argument("--max-dim", type=int, default=1024)
|
| 307 |
+
p.add_argument("--max-new-tokens", type=int, default=200)
|
| 308 |
+
p.add_argument("--chunk", type=int, default=16)
|
| 309 |
+
p.add_argument("--backend", default="auto", choices=["auto", "mlx", "torch"])
|
| 310 |
+
p.add_argument("--engine", default="auto", choices=["auto", "batch", "paged"])
|
| 311 |
+
p.add_argument("--cudagraph", action="store_true", help="opt IN -- can OOM the host on small flavors")
|
| 312 |
+
p.add_argument("--mlx-mem-fraction", type=float, default=0.55)
|
| 313 |
+
args = p.parse_args()
|
| 314 |
+
|
| 315 |
+
backend = pick_backend(args.backend)
|
| 316 |
+
if backend == "mlx":
|
| 317 |
+
guard_mlx_memory(args.mlx_mem_fraction)
|
| 318 |
+
use_paged = args.engine == "paged" or (args.engine == "auto" and backend == "torch")
|
| 319 |
+
if use_paged and backend == "mlx":
|
| 320 |
+
print("paged engine is CUDA-only -- using batch", flush=True)
|
| 321 |
+
use_paged = False
|
| 322 |
+
print(f"backend={backend} engine={'paged' if use_paged else 'batch'} query={args.query!r}", flush=True)
|
| 323 |
+
|
| 324 |
+
from falcon_perception import PERCEPTION_MODEL_ID, build_prompt_for_task, load_and_prepare_model
|
| 325 |
+
from pycocotools import mask as mask_utils
|
| 326 |
+
|
| 327 |
+
kw = {}
|
| 328 |
+
if backend == "torch":
|
| 329 |
+
from falcon_perception import setup_torch_config
|
| 330 |
+
|
| 331 |
+
setup_torch_config()
|
| 332 |
+
kw = {"compile": False} # dynamic image shapes break Inductor
|
| 333 |
+
t = time.perf_counter()
|
| 334 |
+
model, tokenizer, model_args = load_and_prepare_model(
|
| 335 |
+
hf_model_id=PERCEPTION_MODEL_ID,
|
| 336 |
+
dtype="float16" if backend == "mlx" else "bfloat16",
|
| 337 |
+
backend=backend, **kw,
|
| 338 |
+
)
|
| 339 |
+
print(f"model loaded in {time.perf_counter() - t:.1f}s", flush=True)
|
| 340 |
+
prompt = build_prompt_for_task(args.query, args.task)
|
| 341 |
+
|
| 342 |
+
items = src_images(args.image) if args.image else src_dataset(
|
| 343 |
+
args.dataset, args.config, args.split, args.image_col, args.id_col)
|
| 344 |
+
if args.limit:
|
| 345 |
+
# islice STOPS the iterator; a filter would keep streaming the whole corpus.
|
| 346 |
+
items = itertools.islice(items, args.limit)
|
| 347 |
+
|
| 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),
|
| 381 |
+
"masks_rle": json.dumps([
|
| 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")),
|
| 420 |
+
"area": SeqFeat(Value("float32")),
|
| 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 |
+
|
| 429 |
+
main()
|