davanstrien HF Staff commited on
Commit
9f46a5e
·
verified ·
1 Parent(s): 3348442

Sync from GitHub via hub-sync

Browse files
Files changed (2) hide show
  1. README.md +45 -0
  2. wevisone-detect.py +704 -0
README.md CHANGED
@@ -19,12 +19,14 @@ Instruction-prompted object detection with vision-language models via vLLM. Desi
19
  |---|---|---|---|
20
  | `sam3/` | Class names | bbox + score | Known categories, scale |
21
  | `vlm-object-detection/` | Free-form instruction | bbox + label + sub_label | Exploratory labelling, structured per-element labels |
 
22
 
23
  ## Scripts
24
 
25
  | Script | Status | Use |
26
  |---|---|---|
27
  | `qwen3vl-detect.py` | **Stable** | Standard zero-shot detection |
 
28
  | `qwen3vl-detect-fewshot.py` | **Experimental** | One-shot in-context example — pass an example image + its labelled output to demonstrate the task |
29
  | `inspect-detections.py` | **Utility** | Render a side-by-side PNG of model detections vs ground truth (when source has GT) for each row of an output dataset. Used to generate all visual comparisons in this README. |
30
 
@@ -200,6 +202,49 @@ Or skip the dataset repo and mount a local folder directly — `-v ./example:/ex
200
 
201
  Pick an example that looks similar to your typical target page — the model anchors heavily to "what a page should look like."
202
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  ## Acknowledgements
204
 
205
  Adapted from the [`Qwen/Object-Detection-with-Qwen`](https://modelscope.cn/studios/Qwen/Object-Detection-with-Qwen) demo on ModelScope. The Qwen-VL family is from Alibaba's Qwen team; weights are available on Hugging Face under apache-2.0.
 
 
 
19
  |---|---|---|---|
20
  | `sam3/` | Class names | bbox + score | Known categories, scale |
21
  | `vlm-object-detection/` | Free-form instruction | bbox + label + sub_label | Exploratory labelling, structured per-element labels |
22
+ | `vlm-object-detection/wevisone-detect.py` | Class names | bbox + label + alt_labels | Known categories with a grounding VLM: small objects, dense pages |
23
 
24
  ## Scripts
25
 
26
  | Script | Status | Use |
27
  |---|---|---|
28
  | `qwen3vl-detect.py` | **Stable** | Standard zero-shot detection |
29
+ | `wevisone-detect.py` | **New** | Class-list detection with [WeVisOne-VL](https://huggingface.co/tencent/WeVisOne-VL-4B), a 4B grounding model. Same output schema. See [Class-list detection](#class-list-detection-with-wevisone-vl) |
30
  | `qwen3vl-detect-fewshot.py` | **Experimental** | One-shot in-context example — pass an example image + its labelled output to demonstrate the task |
31
  | `inspect-detections.py` | **Utility** | Render a side-by-side PNG of model detections vs ground truth (when source has GT) for each row of an output dataset. Used to generate all visual comparisons in this README. |
32
 
 
202
 
203
  Pick an example that looks similar to your typical target page — the model anchors heavily to "what a page should look like."
204
 
205
+ ## Class-list detection with WeVisOne-VL
206
+
207
+ `wevisone-detect.py` runs [`tencent/WeVisOne-VL-4B`](https://huggingface.co/tencent/WeVisOne-VL-4B) (or `-2B`), a Qwen3-VL model that WeChat Vision trained for grounding: open-vocabulary detection, referring, counting and pointing. You pass class names, not an instruction. It loads in stock vLLM, fits a 24 GB GPU, and writes the same `detections` column as `qwen3vl-detect.py`, so `inspect-detections.py` works on its output.
208
+
209
+ Use it when you know your classes and care about finding every instance, including small objects and dense pages. Use `qwen3vl-detect.py` when you need a free-form instruction, descriptive `sub_label`s, or fine-grained labels.
210
+
211
+ ```bash
212
+ hf jobs uv run \
213
+ https://huggingface.co/datasets/uv-scripts/vlm-object-detection/raw/main/wevisone-detect.py \
214
+ rishitdagli/cppe-5 your-username/cppe5-wevisone \
215
+ --classes "Coverall,Face_Shield,Gloves,Goggles,Mask" \
216
+ --split test --max-samples 20 --shuffle
217
+ ```
218
+
219
+ The script header supplies the image (`vllm/vllm-openai:v0.32.0`), the flavor (`a10g-small`) and the `HF_TOKEN` secret. A 20-image run takes about 4 minutes end to end, almost all of it model load; generating the 20 answers takes a few seconds.
220
+
221
+ **Smoke results** (about 20 images per dataset, a box counts when IoU ≥ 0.5 with a ground-truth box, one-to-one matching). Qwen3.6 is `qwen3vl-detect.py` with `Qwen/Qwen3.6-35B-A3B` and a prompt listing the same classes.
222
+
223
+ | Dataset (images, GT boxes) | Qwen3.6 box P / R | WeVisOne box P / R | WeVisOne `--merge-duplicates` box P / R | Label recall: Qwen3.6 / WeVisOne / merged |
224
+ |---|---|---|---|---|
225
+ | [Beyond Words](https://huggingface.co/datasets/biglam/loc_beyond_words) newspaper pages (20, 284) | 0.15 / 0.15 | 0.18 / **0.26** | 0.30 / 0.26 | 0.13 / **0.24** / 0.22 |
226
+ | [CPPE-5](https://huggingface.co/datasets/rishitdagli/cppe-5) medical PPE (20, 111) | **0.85** / 0.93 | 0.79 / 0.93 | 0.84 / 0.93 | 0.91 / **0.92** / 0.86 |
227
+ | [ENA24](https://huggingface.co/datasets/davanstrien/ena24-detection) camera traps, 23 species (20, 20) | **1.00 / 1.00** | 0.47 / 0.90 | 0.90 / 0.90 | **0.80** / 0.75 / 0.30 |
228
+ | [Cigarette litter](https://huggingface.co/datasets/lojony/cigarette-litter-street-photos) street photos, validation (19, 43) | 1.00 / 0.79 | 1.00 / **0.88** | 1.00 / 0.88 | 0.79 / **0.88** / 0.88 |
229
+ | [Mixed-traffic dashcam](https://huggingface.co/datasets/jasleen2737/vehicle-mixed-traffic-detection) frames, val (20, 71) | **0.57 / 0.70** | 0.28 / 0.68 | 0.37 / 0.68 | **0.66** / 0.55 / 0.49 |
230
+
231
+ Box P / R ignore the label; label recall also requires the right class. The cigarette set's `maybe` boxes are ignored (not scored either way). With 20 images and 20–284 ground-truth boxes, a change of one to three boxes moves a number by up to 15 points, so treat small gaps as noise. Two identical ENA24 runs gave WeVisOne label recall of 0.65 and 0.75 (vLLM output is not bit-for-bit reproducible across runs).
232
+
233
+ - The **cigarette litter** and **dashcam traffic** datasets were uploaded to the Hub in November 2026, after WeVisOne-VL's release (22 October), so they are unlikely to be in its training data.
234
+ - The traffic and Beyond Words ground truth is incomplete: both models find road users and pictures that annotators did not box, so precision is understated for both.
235
+
236
+ **Behaviour to know about**
237
+
238
+ - **One object, several classes.** The model answers each class on its own, so a fox can come back as Red Fox, Grey Fox and Coyote. Every box is kept, and each box's `alt_labels` lists the other classes given to the same region (IoU ≥ `--duplicate-iou`, default 0.8). A reviewer sees the ambiguity; nothing is thrown away. The cost is box precision on multi-class lists: each extra class name is an extra box (ENA24 0.47, dashcam 0.28 in the table).
239
+ - **`--merge-duplicates`** folds overlapping boxes of different classes into one box, labelled with the class that comes first in `--classes`. There are no scores to choose by, so this only helps when your class order is a real priority. With an arbitrary order it hurts labels: ENA24 species recall fell from 0.75 to 0.30. Before using the output as training data, merge here or dedupe downstream after review.
240
+ - **No confidence scores.** Absent classes come back as `<box>none</box>` and are skipped.
241
+ - **Whole-page boxes.** On some newspaper pages the model adds one box around the entire page. Filter by box area if that matters for your data.
242
+ - **Image size.** Images are resized to at most about 2 MP (`--max-image-tokens 2025`, the release default). Tiny objects in large photos still came through (cigarette ends in 4000×1800 street photos).
243
+ - **Class names** go into the prompt as plain phrases (`Face_Shield` is sent as "Face Shield"); the output `label` is the name exactly as you passed it. The prompt separates classes with ". ", so names cannot contain `.` or `,` (the script stops early if they do). Plain names work better than coded group names: for the traffic set, ask for "motorcycle, scooter, bicycle" and map them to "2-wheeler" afterwards.
244
+ - **Licence.** The WeVisOne-VL weights and code are Apache-2.0.
245
+
246
  ## Acknowledgements
247
 
248
  Adapted from the [`Qwen/Object-Detection-with-Qwen`](https://modelscope.cn/studios/Qwen/Object-Detection-with-Qwen) demo on ModelScope. The Qwen-VL family is from Alibaba's Qwen team; weights are available on Hugging Face under apache-2.0.
249
+
250
+ `wevisone-detect.py` uses [WeVisOne-VL](https://github.com/Tencent/WeVisOne-VL) from WeChat Vision, Tencent (Apache-2.0); its prompt template and answer parser follow that repository.
wevisone-detect.py ADDED
@@ -0,0 +1,704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets>=4.0.0",
5
+ # "huggingface-hub",
6
+ # "pillow",
7
+ # "toolz",
8
+ # "tqdm",
9
+ # ]
10
+ #
11
+ # [tool.hf-jobs]
12
+ # # vllm, torch and transformers come from the image (PYTHONPATH). Do not list them above: uv
13
+ # # would install the newest PyPI vllm deps next to the image's vllm and break it.
14
+ # image = "vllm/vllm-openai:v0.32.0"
15
+ # python = "/usr/bin/python3"
16
+ # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
17
+ # flavor = "a10g-small"
18
+ # secrets = ["HF_TOKEN"]
19
+ # timeout = "1h"
20
+ # ///
21
+
22
+ """
23
+ Class-list object detection with WeVisOne-VL via vLLM.
24
+
25
+ Give it an image dataset and a list of class names; it returns boxes for every
26
+ instance of every class and pushes the dataset back to the Hub with a
27
+ `detections` column in the same shape as qwen3vl-detect.py, so
28
+ inspect-detections.py and the downstream labelling steps work unchanged.
29
+
30
+ WeVisOne-VL (tencent/WeVisOne-VL-4B and -2B, Apache-2.0) is a Qwen3-VL model
31
+ trained for grounding: open-vocabulary detection, referring, counting and
32
+ pointing. It loads in stock vLLM. Use it when you know your classes; use
33
+ qwen3vl-detect.py when you want a free-form instruction and descriptive
34
+ sub-labels.
35
+
36
+ Example (Hugging Face Jobs; the header above supplies image, flavor and secrets):
37
+
38
+ hf jobs uv run \\
39
+ https://huggingface.co/datasets/uv-scripts/vlm-object-detection/raw/main/wevisone-detect.py \\
40
+ rishitdagli/cppe-5 your-username/cppe5-wevisone \\
41
+ --classes "Coverall,Face_Shield,Gloves,Goggles,Mask" \\
42
+ --split test --max-samples 20 --shuffle
43
+
44
+ Measured behaviour (20-image smokes, IoU >= 0.5 against ground truth):
45
+
46
+ * The model answers each class on its own, so one object can come back under
47
+ several classes (a fox as Red Fox, Grey Fox and Coyote). Every box is kept;
48
+ each box's `alt_labels` lists the other classes given to the same region
49
+ (IoU >= --duplicate-iou), so a reviewer sees the ambiguity.
50
+ * Keeping every box costs box precision on multi-class lists: each extra class
51
+ name on the same object is an extra box (ENA24: 0.47 vs 0.90 merged).
52
+ --merge-duplicates folds overlapping boxes of different classes into one box,
53
+ labelled with the class listed first in --classes (there are no scores to
54
+ choose by). Labels get worse when that order is arbitrary: ENA24 species
55
+ recall fell from 0.75 to 0.30. Merge for coarse or priority-ordered classes,
56
+ or dedupe downstream before using the boxes as training data.
57
+ * Class names go into the prompt as plain phrases ("Face_Shield" is sent as
58
+ "Face Shield"); the output label is the name exactly as you passed it. The
59
+ prompt separates classes with ". ", so names cannot contain "." or ",".
60
+ * There are no confidence scores.
61
+ * Compared with qwen3vl-detect.py on Qwen3.6-35B-A3B: higher box recall on small
62
+ objects and dense pages (cigarette ends 0.88 vs 0.79, newspaper pages 0.26 vs
63
+ 0.15), similar box recall elsewhere, lower box precision by default (see
64
+ above), and slightly weaker fine-grained labels (ENA24 species recall 0.75 vs 0.80).
65
+ """
66
+
67
+ import argparse
68
+ import io
69
+ import json
70
+ import logging
71
+ import os
72
+ import re
73
+ import shlex
74
+ import sys
75
+ from datetime import datetime
76
+ from typing import Any
77
+
78
+ from datasets import Dataset, Features, List, Value, concatenate_datasets, load_dataset
79
+ from datasets import Image as ImageFeature
80
+ from huggingface_hub import DatasetCard, login
81
+ from PIL import Image
82
+ from toolz import partition_all
83
+ from tqdm.auto import tqdm
84
+
85
+ logging.basicConfig(
86
+ level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s"
87
+ )
88
+ logger = logging.getLogger(__name__)
89
+
90
+ DEFAULT_MODEL = "tencent/WeVisOne-VL-4B"
91
+ SCRIPT_URL = "https://huggingface.co/datasets/uv-scripts/vlm-object-detection/raw/main/wevisone-detect.py"
92
+ # The released checkpoint's own system prompt and detection template
93
+ # (wevisone_vl/engine.py and wevisone_vl/prompts.py in Tencent/WeVisOne-VL).
94
+ SYSTEM_PROMPT = "You are a helpful assistant."
95
+ # Answers look like <ref>cat</ref><box><12><40><380><990>,<500><42><880><991></box>; coordinates
96
+ # are bins on a 0-1000 grid. A truncated answer may lose its closing tag. Absent classes come back
97
+ # as <box>none</box>, which yields no boxes. Follows evaluation/utils/parser.py in the same repo,
98
+ # except that the next <ref> is a lookahead, so an answer missing a closing tag does not swallow
99
+ # the following class.
100
+ REF_RE = re.compile(
101
+ r"<ref>(.*?)</ref>\s*<(box|point|polygon)>(.*?)(?:</(?:box|point|polygon)>|(?=<ref>)|$)",
102
+ re.DOTALL,
103
+ )
104
+ BIN_RE = re.compile(r"<(\d+)>")
105
+
106
+ DETECTION_FEATURES = Features(
107
+ {
108
+ "detections": List(
109
+ {
110
+ "bbox": List(Value("int64")),
111
+ "label": Value("string"),
112
+ "sub_label": Value("string"),
113
+ "alt_labels": List(Value("string")),
114
+ }
115
+ ),
116
+ "raw_response": Value("string"),
117
+ "inference_info": Value("string"),
118
+ }
119
+ )
120
+
121
+
122
+ def build_prompt(prompt_names: list[str]) -> str:
123
+ """WeVisOne's detection instruction: class phrases joined by '. '."""
124
+ return (
125
+ "Locate all the instances that match the following description: "
126
+ + ". ".join(prompt_names)
127
+ + "."
128
+ )
129
+
130
+
131
+ def to_pil(image: Image.Image | dict | str | None) -> Image.Image | None:
132
+ """Convert HF dataset image entries (PIL / dict-with-bytes / path) to PIL; None stays None."""
133
+ if image is None:
134
+ return None
135
+ if isinstance(image, Image.Image):
136
+ return image
137
+ if isinstance(image, dict) and image.get("bytes"):
138
+ return Image.open(io.BytesIO(image["bytes"]))
139
+ if isinstance(image, dict) and image.get("path"):
140
+ return Image.open(image["path"])
141
+ if isinstance(image, str):
142
+ return Image.open(image)
143
+ raise ValueError(f"Unsupported image type: {type(image)}")
144
+
145
+
146
+ def parse_detections(
147
+ text: str, width: int, height: int, label_for: dict[str, str]
148
+ ) -> list[dict]:
149
+ """Parse <ref>label</ref><box>...</box> answers into pixel-space xyxy boxes."""
150
+ text = text.split("<|im_end|>")[0]
151
+ detections = []
152
+ for phrase, shape, body in REF_RE.findall(text):
153
+ if shape != "box":
154
+ continue
155
+ phrase = phrase.strip().rstrip(".").strip()
156
+ label = label_for.get(phrase.lower(), phrase)
157
+ for segment in body.strip().rstrip(",").split(","):
158
+ values = [int(v) for v in BIN_RE.findall(segment)]
159
+ for k in range(0, len(values) - 3, 4):
160
+ x1, y1, x2, y2 = values[k : k + 4]
161
+ if x2 <= x1 or y2 <= y1:
162
+ continue
163
+ box = [
164
+ max(0, min(width, round(x1 / 1000 * width))),
165
+ max(0, min(height, round(y1 / 1000 * height))),
166
+ max(0, min(width, round(x2 / 1000 * width))),
167
+ max(0, min(height, round(y2 / 1000 * height))),
168
+ ]
169
+ if box[2] <= box[0] or box[3] <= box[1]:
170
+ continue # collapsed to zero width or height after scaling/clamping
171
+ detections.append(
172
+ {"bbox": box, "label": label, "sub_label": "", "alt_labels": []}
173
+ )
174
+ return detections
175
+
176
+
177
+ def box_iou(a: list[int], b: list[int]) -> float:
178
+ inter_w = max(0, min(a[2], b[2]) - max(a[0], b[0]))
179
+ inter_h = max(0, min(a[3], b[3]) - max(a[1], b[1]))
180
+ inter = inter_w * inter_h
181
+ union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
182
+ return inter / union if union > 0 else 0.0
183
+
184
+
185
+ def annotate_cross_class_duplicates(detections: list[dict], threshold: float) -> int:
186
+ """Fill each box's `alt_labels` with the other classes the model gave the same region.
187
+
188
+ Two boxes are the same region when their IoU is >= threshold. Every box is kept.
189
+ Returns the number of boxes with at least one alternative label.
190
+ """
191
+ if threshold <= 0:
192
+ return 0
193
+ for box in detections:
194
+ for other in detections:
195
+ if (
196
+ other is not box
197
+ and other["label"] != box["label"]
198
+ and other["label"] not in box["alt_labels"]
199
+ and box_iou(box["bbox"], other["bbox"]) >= threshold
200
+ ):
201
+ box["alt_labels"].append(other["label"])
202
+ return sum(1 for box in detections if box["alt_labels"])
203
+
204
+
205
+ def merge_cross_class_duplicates(
206
+ detections: list[dict], class_rank: dict[str, int], threshold: float
207
+ ) -> tuple[list[dict], int]:
208
+ """Merge boxes of different classes that overlap at IoU >= threshold.
209
+
210
+ The class that comes first in --classes keeps the box; the other labels are
211
+ recorded in `alt_labels`. Boxes of the same class are left alone.
212
+ Returns the kept detections and the number of boxes merged away.
213
+ """
214
+ if threshold <= 0:
215
+ return detections, 0
216
+ ordered = sorted(
217
+ detections, key=lambda d: class_rank.get(d["label"], len(class_rank))
218
+ )
219
+ kept: list[dict] = []
220
+ merged = 0
221
+ for detection in ordered:
222
+ duplicate = next(
223
+ (
224
+ k
225
+ for k in kept
226
+ if k["label"] != detection["label"]
227
+ and detection["label"] not in k["alt_labels"]
228
+ and box_iou(k["bbox"], detection["bbox"]) >= threshold
229
+ ),
230
+ None,
231
+ )
232
+ if duplicate is None:
233
+ kept.append(detection)
234
+ else:
235
+ duplicate["alt_labels"].append(detection["label"])
236
+ merged += 1
237
+ return kept, merged
238
+
239
+
240
+ def jobs_flavor() -> str:
241
+ """Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.
242
+
243
+ HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up
244
+ in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and
245
+ MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or
246
+ cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "".
247
+ """
248
+ hardware = os.environ.get("ACCELERATOR") or ""
249
+ if "-" in hardware or any(character.isdigit() for character in hardware):
250
+ return hardware # already a flavor name
251
+ try:
252
+ from huggingface_hub import HfApi
253
+
254
+ gpu_name, gpu_count = "", 0
255
+ try:
256
+ import torch
257
+
258
+ if torch.cuda.is_available():
259
+ gpu_name = torch.cuda.get_device_name(0)
260
+ gpu_count = torch.cuda.device_count()
261
+ except ImportError:
262
+ pass
263
+ if gpu_count == 0 and hardware == "gpu":
264
+ return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor
265
+
266
+ # Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100).
267
+ gpu_words = gpu_name.upper().replace("-", " ").split()
268
+ candidates = []
269
+ for flavor in HfApi(token=False).list_jobs_hardware():
270
+ accelerator = flavor.accelerator
271
+ if gpu_count == 0 and accelerator is None:
272
+ candidates.append(flavor)
273
+ elif (
274
+ gpu_count > 0
275
+ and accelerator is not None
276
+ and accelerator.model.upper() in gpu_words
277
+ and int(accelerator.quantity) == gpu_count
278
+ ):
279
+ candidates.append(flavor)
280
+ if not candidates:
281
+ return ""
282
+
283
+ cores = float(os.environ.get("CPU_CORES") or 0)
284
+ memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)
285
+
286
+ def distance(flavor) -> float:
287
+ # Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers.
288
+ listed_cores = float(flavor.cpu.split()[0])
289
+ listed_memory = float(flavor.ram.split()[0])
290
+ return (
291
+ abs(listed_cores - cores) / listed_cores
292
+ + abs(listed_memory - memory_gb) / listed_memory
293
+ )
294
+
295
+ return min(candidates, key=distance).name
296
+ except Exception:
297
+ return ""
298
+
299
+
300
+ def push_card(
301
+ args: argparse.Namespace, classes: list[str], stats: dict[str, Any]
302
+ ) -> None:
303
+ """Replace the card body with one carrying the repo's canonical provenance stamp (AGENTS.md).
304
+
305
+ The README that push_to_hub wrote is loaded first so its dataset_info/configs metadata
306
+ is kept; only the tags are extended and the body replaced.
307
+ """
308
+ on_jobs = os.environ.get("JOB_ID") is not None # set by HF Jobs in-container
309
+ hw = jobs_flavor() # flavor name, e.g. "l4x1"; "" on CPU
310
+ origin = (
311
+ (
312
+ "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
313
+ + (f" (`{hw}`)" if hw else "")
314
+ )
315
+ if on_jobs
316
+ else "Generated"
317
+ )
318
+ tags = (
319
+ ["uv-script", "hf-jobs", "object-detection"]
320
+ if on_jobs
321
+ else ["uv-script", "object-detection"]
322
+ )
323
+ card = DatasetCard.load(args.output_dataset, repo_type="dataset")
324
+ card.data["tags"] = sorted(set(card.data.get("tags") or []) | set(tags))
325
+ card.text = build_card_body(args, classes, stats, origin, hw)
326
+ card.push_to_hub(args.output_dataset)
327
+
328
+
329
+ def build_reproduce_args(args: argparse.Namespace) -> str:
330
+ """Script arguments for the card's reproduce command. Never includes --hf-token."""
331
+ parts = [shlex.quote(args.input_dataset), "<output-dataset>"]
332
+ parts += ["--classes", shlex.quote(args.classes)]
333
+ if args.split != "train":
334
+ parts += ["--split", shlex.quote(args.split)]
335
+ if args.model != DEFAULT_MODEL:
336
+ parts += ["--model", shlex.quote(args.model)]
337
+ if args.image_column != "image":
338
+ parts += ["--image-column", shlex.quote(args.image_column)]
339
+ if args.max_samples:
340
+ parts += ["--max-samples", str(args.max_samples)]
341
+ if args.shuffle:
342
+ parts += ["--shuffle", "--seed", str(args.seed)]
343
+ if args.duplicate_iou != 0.8:
344
+ parts += ["--duplicate-iou", str(args.duplicate_iou)]
345
+ if args.merge_duplicates:
346
+ parts.append("--merge-duplicates")
347
+ if args.max_image_tokens != 2025:
348
+ parts += ["--max-image-tokens", str(args.max_image_tokens)]
349
+ if args.max_model_len != 8192:
350
+ parts += ["--max-model-len", str(args.max_model_len)]
351
+ if args.max_tokens != 4096:
352
+ parts += ["--max-tokens", str(args.max_tokens)]
353
+ if args.private:
354
+ parts.append("--private")
355
+ return " ".join(parts)
356
+
357
+
358
+ def build_card_body(
359
+ args: argparse.Namespace,
360
+ classes: list[str],
361
+ stats: dict[str, Any],
362
+ origin: str,
363
+ hw: str,
364
+ ) -> str:
365
+ class_list = ", ".join(f"`{c}`" for c in classes)
366
+ if args.merge_duplicates:
367
+ duplicate_note = (
368
+ f"{stats['merged']} boxes were merged into a box of another class at IoU >= "
369
+ f"{args.duplicate_iou} (`--merge-duplicates`; the class listed first was kept)."
370
+ )
371
+ else:
372
+ duplicate_note = (
373
+ f"{stats['with_alt_labels']} boxes share their region with a box of another class "
374
+ "(see `alt_labels`)."
375
+ )
376
+ reproduce_args = build_reproduce_args(args)
377
+ return f"""
378
+ # Class-list detection with WeVisOne-VL
379
+
380
+ Boxes for {class_list} on `{args.input_dataset}` (split `{args.split}`), from
381
+ [{args.model}](https://huggingface.co/{args.model}).
382
+ {stats["rows"]} images, {stats["rows_with_detections"]} with at least one detection,
383
+ {stats["detections"]} detections. {duplicate_note}
384
+
385
+ These are **zero-shot labels**: no human checked them. Treat them as a first pass for review.
386
+
387
+ ## Columns added
388
+
389
+ - `detections`: list of `{{bbox: [x1, y1, x2, y2], label, sub_label, alt_labels}}`. `bbox` is in
390
+ original-image pixels. `sub_label` is always empty (WeVisOne gives class labels only); it is
391
+ there so the schema matches `qwen3vl-detect.py`. `alt_labels` lists other classes the model
392
+ gave the same region (IoU >= {args.duplicate_iou}); WeVisOne answers each class on its own,
393
+ so one object can carry several class names.
394
+ - `raw_response`: the model's raw answer, for re-parsing.
395
+ - `inference_info`: JSON with the model, prompt, classes, image size and settings.
396
+
397
+ ## Reproduction
398
+
399
+ {origin} with the [`wevisone-detect.py`]({SCRIPT_URL}) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
400
+
401
+ ```bash
402
+ hf jobs uv run {f"--flavor {hw} " if hw else ""}{SCRIPT_URL} \\
403
+ {reproduce_args}
404
+ ```
405
+ """
406
+
407
+
408
+ def main(args: argparse.Namespace) -> None:
409
+ classes = [c.strip() for c in args.classes.split(",") if c.strip()]
410
+ if not classes:
411
+ sys.exit(
412
+ "--classes is empty. Pass a comma-separated list, e.g. --classes 'cat,dog'."
413
+ )
414
+ with_period = [c for c in classes if "." in c]
415
+ if with_period:
416
+ sys.exit(
417
+ f"Class names cannot contain '.', which the prompt uses to separate classes: "
418
+ f"{with_period}. Rename them (e.g. 'St Bernard')."
419
+ )
420
+ if args.max_image_tokens + args.max_tokens + 256 > args.max_model_len:
421
+ sys.exit(
422
+ f"--max-image-tokens ({args.max_image_tokens}) + --max-tokens ({args.max_tokens}) "
423
+ f"does not fit in --max-model-len ({args.max_model_len}). Raise --max-model-len."
424
+ )
425
+ # A split slice such as 'train[:100]' loads fine but is not a valid name to push to.
426
+ output_split = args.split.split("[")[0]
427
+
428
+ import torch
429
+
430
+ if not torch.cuda.is_available():
431
+ sys.exit(
432
+ "CUDA is not available. This script needs a GPU (e.g. --flavor a10g-small)."
433
+ )
434
+ logger.info("GPU: %s", torch.cuda.get_device_name(0))
435
+ # The CUDA check above touches the driver in this process, so vLLM's engine process
436
+ # must be spawned, not forked ("Cannot re-initialize CUDA in forked subprocess").
437
+ os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
438
+
439
+ from transformers import AutoProcessor
440
+ from vllm import LLM, SamplingParams
441
+
442
+ if args.hf_token: # HF_TOKEN in the environment is picked up without a login call
443
+ login(token=args.hf_token)
444
+
445
+ prompt_names = [c.replace("_", " ") for c in classes]
446
+ label_for = {p.lower(): c for p, c in zip(prompt_names, classes, strict=True)}
447
+ class_rank = {c: i for i, c in enumerate(classes)}
448
+ prompt = build_prompt(prompt_names)
449
+ logger.info("Prompt: %s", prompt)
450
+
451
+ logger.info("Loading dataset: %s (split=%s)", args.input_dataset, args.split)
452
+ dataset = load_dataset(args.input_dataset, split=args.split)
453
+ if args.image_column not in dataset.column_names:
454
+ sys.exit(
455
+ f"Column '{args.image_column}' not found. Columns: {dataset.column_names}"
456
+ )
457
+ if not isinstance(dataset.features[args.image_column], ImageFeature):
458
+ # Paths or URLs would be uploaded as plain strings and the pixels lost after the Job.
459
+ logger.info("Casting column '%s' to Image", args.image_column)
460
+ dataset = dataset.cast_column(args.image_column, ImageFeature())
461
+ clashes = {"detections", "raw_response", "inference_info"} & set(
462
+ dataset.column_names
463
+ )
464
+ if clashes:
465
+ logger.warning("Replacing existing column(s): %s", sorted(clashes))
466
+ dataset = dataset.remove_columns(sorted(clashes))
467
+ if args.shuffle:
468
+ dataset = dataset.shuffle(seed=args.seed)
469
+ if args.max_samples:
470
+ dataset = dataset.select(range(min(args.max_samples, len(dataset))))
471
+ logger.info("Rows to process: %d", len(dataset))
472
+
473
+ min_pixels = args.min_image_tokens * 32 * 32
474
+ max_pixels = args.max_image_tokens * 32 * 32
475
+ llm = LLM(
476
+ model=args.model,
477
+ limit_mm_per_prompt={"image": 1},
478
+ mm_processor_kwargs={"min_pixels": min_pixels, "max_pixels": max_pixels},
479
+ max_model_len=args.max_model_len,
480
+ max_num_seqs=args.batch_size,
481
+ gpu_memory_utilization=args.gpu_memory_utilization,
482
+ )
483
+ processor = AutoProcessor.from_pretrained(args.model)
484
+ # skip_special_tokens=False keeps the <ref>/<box>/<N> coordinate tokens in the text.
485
+ sampling_params = SamplingParams(
486
+ temperature=0.0,
487
+ max_tokens=args.max_tokens,
488
+ repetition_penalty=args.repetition_penalty,
489
+ skip_special_tokens=False,
490
+ stop=["<|im_end|>"],
491
+ )
492
+ chat_prompt = processor.apply_chat_template(
493
+ [
494
+ {"role": "system", "content": SYSTEM_PROMPT},
495
+ {
496
+ "role": "user",
497
+ "content": [{"type": "image"}, {"type": "text", "text": prompt}],
498
+ },
499
+ ],
500
+ tokenize=False,
501
+ add_generation_prompt=True,
502
+ )
503
+
504
+ all_detections: list[list[dict]] = []
505
+ all_raw: list[str] = []
506
+ all_info: list[str] = []
507
+ merged_total = 0
508
+ with_alt_total = 0
509
+ started = datetime.now()
510
+ for batch_indices in tqdm(
511
+ list(partition_all(args.batch_size, range(len(dataset)))),
512
+ desc="WeVisOne detection",
513
+ ):
514
+ images = []
515
+ for i in batch_indices:
516
+ image = to_pil(dataset[i][args.image_column])
517
+ images.append(image.convert("RGB") if image is not None else None)
518
+ requests = [
519
+ {"prompt": chat_prompt, "multi_modal_data": {"image": im}}
520
+ for im in images
521
+ if im is not None
522
+ ]
523
+ generated = iter(llm.generate(requests, sampling_params, use_tqdm=False))
524
+ for image in images:
525
+ if image is None: # empty image cell: keep the row, with no detections
526
+ all_detections.append([])
527
+ all_raw.append("")
528
+ all_info.append(
529
+ json.dumps(
530
+ {
531
+ "model_id": args.model,
532
+ "image_size": None,
533
+ "error": "missing image",
534
+ }
535
+ )
536
+ )
537
+ continue
538
+ output = next(generated)
539
+ text = output.outputs[0].text if output.outputs else ""
540
+ detections = parse_detections(text, image.width, image.height, label_for)
541
+ merged = 0
542
+ if args.merge_duplicates:
543
+ detections, merged = merge_cross_class_duplicates(
544
+ detections, class_rank, args.duplicate_iou
545
+ )
546
+ with_alt = annotate_cross_class_duplicates(detections, args.duplicate_iou)
547
+ merged_total += merged
548
+ with_alt_total += with_alt
549
+ all_detections.append(detections)
550
+ all_raw.append(text)
551
+ all_info.append(
552
+ json.dumps(
553
+ {
554
+ "model_id": args.model,
555
+ "prompt": prompt,
556
+ "classes": classes,
557
+ "image_size": [image.width, image.height],
558
+ "min_pixels": min_pixels,
559
+ "max_pixels": max_pixels,
560
+ "duplicate_iou": args.duplicate_iou,
561
+ "merge_duplicates": args.merge_duplicates,
562
+ "merged_boxes": merged,
563
+ "boxes_with_alt_labels": with_alt,
564
+ "script": "wevisone-detect.py",
565
+ "timestamp": datetime.now().isoformat(timespec="seconds"),
566
+ }
567
+ )
568
+ )
569
+ elapsed_min = (datetime.now() - started).total_seconds() / 60
570
+ logger.info("Processed %d images in %.1f min", len(dataset), elapsed_min)
571
+
572
+ new_columns = Dataset.from_dict(
573
+ {
574
+ "detections": all_detections,
575
+ "raw_response": all_raw,
576
+ "inference_info": all_info,
577
+ },
578
+ features=DETECTION_FEATURES,
579
+ )
580
+ dataset = concatenate_datasets([dataset, new_columns], axis=1)
581
+
582
+ stats = {
583
+ "rows": len(all_detections),
584
+ "rows_with_detections": sum(1 for d in all_detections if d),
585
+ "detections": sum(len(d) for d in all_detections),
586
+ "merged": merged_total,
587
+ "with_alt_labels": with_alt_total,
588
+ }
589
+ logger.info("Pushing to %s", args.output_dataset)
590
+ dataset.push_to_hub(
591
+ args.output_dataset,
592
+ split=output_split,
593
+ private=args.private,
594
+ create_pr=args.create_pr,
595
+ commit_message=f"WeVisOne detection: {args.model} on {len(dataset)} rows",
596
+ )
597
+ if not args.create_pr: # with --create-pr the card would land on main, not the PR
598
+ try:
599
+ push_card(args, classes, stats)
600
+ except Exception as e:
601
+ logger.warning("Could not push dataset card: %s", e)
602
+
603
+ logger.info(
604
+ "Done. Rows with >=1 detection: %d / %d. Detections: %d. "
605
+ "With alt_labels: %d. Merged: %d.",
606
+ stats["rows_with_detections"],
607
+ stats["rows"],
608
+ stats["detections"],
609
+ stats["with_alt_labels"],
610
+ stats["merged"],
611
+ )
612
+ logger.info("Output: https://huggingface.co/datasets/%s", args.output_dataset)
613
+
614
+
615
+ def build_parser() -> argparse.ArgumentParser:
616
+ parser = argparse.ArgumentParser(
617
+ description="Class-list object detection with WeVisOne-VL via vLLM.",
618
+ formatter_class=argparse.RawDescriptionHelpFormatter,
619
+ epilog=__doc__,
620
+ )
621
+ parser.add_argument("input_dataset", help="Input dataset ID on the Hub")
622
+ parser.add_argument("output_dataset", help="Output dataset ID on the Hub")
623
+ parser.add_argument(
624
+ "--classes",
625
+ required=True,
626
+ help="Comma-separated class names (e.g. 'Coverall,Gloves,Mask'); names cannot contain ',' or '.'. "
627
+ "Order sets priority for --merge-duplicates",
628
+ )
629
+ parser.add_argument(
630
+ "--model", default=DEFAULT_MODEL, help=f"Model (default: {DEFAULT_MODEL})"
631
+ )
632
+ parser.add_argument(
633
+ "--image-column", default="image", help="Image column (default: image)"
634
+ )
635
+ parser.add_argument(
636
+ "--split", default="train", help="Dataset split (default: train)"
637
+ )
638
+ parser.add_argument(
639
+ "--max-samples", type=int, default=None, help="Cap rows processed"
640
+ )
641
+ parser.add_argument(
642
+ "--shuffle", action="store_true", help="Shuffle before --max-samples"
643
+ )
644
+ parser.add_argument(
645
+ "--seed", type=int, default=42, help="Shuffle seed (default: 42)"
646
+ )
647
+ parser.add_argument(
648
+ "--batch-size", type=int, default=32, help="Images per vLLM call (default: 32)"
649
+ )
650
+ parser.add_argument(
651
+ "--duplicate-iou",
652
+ type=float,
653
+ default=0.8,
654
+ help="IoU at which boxes of different classes count as one region; 0 disables "
655
+ "alt_labels and merging (default: 0.8)",
656
+ )
657
+ parser.add_argument(
658
+ "--merge-duplicates",
659
+ action="store_true",
660
+ help="Fold overlapping boxes of different classes into one box, labelled with the class "
661
+ "listed first in --classes (default: keep every box and fill alt_labels)",
662
+ )
663
+ parser.add_argument(
664
+ "--max-tokens", type=int, default=4096, help="Output cap (default: 4096)"
665
+ )
666
+ parser.add_argument(
667
+ "--max-model-len", type=int, default=8192, help="Context (default: 8192)"
668
+ )
669
+ parser.add_argument(
670
+ "--min-image-tokens",
671
+ type=int,
672
+ default=16,
673
+ help="Lower image-size bound in 32x32 patches (default: 16, the release default)",
674
+ )
675
+ parser.add_argument(
676
+ "--max-image-tokens",
677
+ type=int,
678
+ default=2025,
679
+ help="Upper image-size bound in 32x32 patches (default: 2025, about 2 MP, the release default)",
680
+ )
681
+ parser.add_argument(
682
+ "--gpu-memory-utilization",
683
+ type=float,
684
+ default=0.85,
685
+ help="vLLM GPU memory share (default: 0.85)",
686
+ )
687
+ parser.add_argument(
688
+ "--repetition-penalty",
689
+ type=float,
690
+ default=1.05,
691
+ help="Repetition penalty (default: 1.05)",
692
+ )
693
+ parser.add_argument("--hf-token", default=None, help="HF token (or set HF_TOKEN)")
694
+ parser.add_argument(
695
+ "--private", action="store_true", help="Make the output dataset private"
696
+ )
697
+ parser.add_argument(
698
+ "--create-pr", action="store_true", help="Push as a PR to the output repo"
699
+ )
700
+ return parser
701
+
702
+
703
+ if __name__ == "__main__":
704
+ main(build_parser().parse_args())