davanstrien HF Staff commited on
Commit
f894a3c
·
verified ·
1 Parent(s): b3b36b2

Upload inspect-detections.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. inspect-detections.py +237 -0
inspect-detections.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = ["datasets>=4.0.0", "huggingface-hub", "pillow", "matplotlib"]
4
+ # ///
5
+ """
6
+ Local visual inspection for the output of qwen3vl-detect.py.
7
+
8
+ Given an output dataset (produced by qwen3vl-detect.py) and optionally its
9
+ source dataset (with ground-truth bboxes), renders side-by-side PNGs of
10
+ predicted detections vs ground truth, one per row.
11
+
12
+ Output: a /tmp/<slug>-viz/ directory of PNGs and a per-row text summary
13
+ (detection counts, label histograms, bbox value ranges).
14
+
15
+ Usage:
16
+ uv run inspect-detections.py OUTPUT_DATASET [--split SPLIT] [--source SOURCE_DATASET]
17
+
18
+ If --source is provided, the script will also load the source dataset, pull
19
+ ground-truth `objects` (bbox + category), auto-discover class names from the
20
+ ClassLabel feature, and overlay GT boxes on a second panel for comparison.
21
+ """
22
+
23
+ import argparse
24
+ import json
25
+ import os
26
+ from collections import Counter
27
+
28
+ import matplotlib.patches as mpatches
29
+ import matplotlib.pyplot as plt
30
+ from datasets import load_dataset
31
+
32
+
33
+ def render_box(ax, x1, y1, x2, y2, color, lw=1.2, label=None, fontsize=7):
34
+ rect = mpatches.Rectangle(
35
+ (x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor=color, linewidth=lw
36
+ )
37
+ ax.add_patch(rect)
38
+ if label:
39
+ ax.text(
40
+ x1,
41
+ y1,
42
+ label,
43
+ fontsize=fontsize,
44
+ color="white",
45
+ bbox=dict(
46
+ boxstyle="round,pad=0.15",
47
+ facecolor=color,
48
+ alpha=0.75,
49
+ edgecolor="none",
50
+ ),
51
+ va="bottom",
52
+ ha="left",
53
+ )
54
+
55
+
56
+ def discover_class_names(ds) -> list[str]:
57
+ """Pull class names from an `objects.category` or `objects.category_id`
58
+ ClassLabel feature on a HF dataset. Returns [] if not found."""
59
+ feats = ds.features
60
+ if "objects" not in feats:
61
+ return []
62
+ obj_feat = feats["objects"]
63
+ # objects may be List[Dict[...]] or Sequence(Dict[...]) — both expose `feature`
64
+ inner = getattr(obj_feat, "feature", None) or obj_feat
65
+ if not hasattr(inner, "keys"):
66
+ return []
67
+ for key in ("category", "category_id"):
68
+ if key in inner:
69
+ cat_feat = inner[key]
70
+ # Sequence(ClassLabel) or ClassLabel
71
+ cl = getattr(cat_feat, "feature", None) or cat_feat
72
+ names = getattr(cl, "names", None)
73
+ if names:
74
+ return list(names)
75
+ return []
76
+
77
+
78
+ def main() -> None:
79
+ parser = argparse.ArgumentParser(
80
+ description="Render Qwen3-VL detection output side-by-side with ground truth."
81
+ )
82
+ parser.add_argument("output_dataset", help="HF dataset ID with detections column")
83
+ parser.add_argument(
84
+ "--split", default="train", help="Split of output_dataset (default: train)"
85
+ )
86
+ parser.add_argument(
87
+ "--source",
88
+ default=None,
89
+ help="Optional source dataset with ground-truth `objects` for GT overlay panel.",
90
+ )
91
+ parser.add_argument(
92
+ "--source-split", default=None, help="Split of source dataset (default: same as --split)"
93
+ )
94
+ parser.add_argument(
95
+ "--max-rows", type=int, default=None, help="Render only the first N rows"
96
+ )
97
+ parser.add_argument(
98
+ "--out-dir",
99
+ default=None,
100
+ help="Output directory (default: /tmp/<output-slug>-viz/)",
101
+ )
102
+ args = parser.parse_args()
103
+
104
+ slug = args.output_dataset.split("/")[-1]
105
+ out_dir = args.out_dir or f"/tmp/{slug}-viz"
106
+ os.makedirs(out_dir, exist_ok=True)
107
+
108
+ print(f"Loading {args.output_dataset} split={args.split}…")
109
+ ds = load_dataset(args.output_dataset, split=args.split)
110
+ if args.max_rows:
111
+ ds = ds.select(range(min(args.max_rows, len(ds))))
112
+ print(f"rows={len(ds)} cols={ds.column_names}")
113
+
114
+ # qwen3vl-detect preserves the source `objects` column on each output row,
115
+ # so GT is co-located with detections (no shuffled-index join needed).
116
+ # The source dataset (if provided) is used only to recover ClassLabel names
117
+ # since push_to_hub strips the ClassLabel typing on round-trip.
118
+ gt_names: list[str] = []
119
+ if args.source:
120
+ gt_split = args.source_split or args.split
121
+ print(f"Loading source {args.source} split={gt_split} for class names…")
122
+ gt_src = load_dataset(args.source, split=gt_split)
123
+ gt_names = discover_class_names(gt_src)
124
+ print(f"GT classes ({len(gt_names)}): {gt_names}")
125
+ elif "objects" in ds.column_names:
126
+ gt_names = discover_class_names(ds)
127
+ if gt_names:
128
+ print(f"GT classes from output features: {gt_names}")
129
+
130
+ for i in range(len(ds)):
131
+ row = ds[i]
132
+ img = row["image"]
133
+ W, H = img.size
134
+ info = json.loads(row["inference_info"])
135
+ dets = row["detections"]
136
+
137
+ # GT extraction from the output row itself (qwen3vl-detect preserves
138
+ # all input columns including `objects`). Handles both list-of-dicts
139
+ # and dict-of-lists shapes.
140
+ gt_cats, gt_bbox = [], []
141
+ if "objects" in row and row["objects"] is not None:
142
+ objs = row["objects"]
143
+ if isinstance(objs, dict):
144
+ gt_cats = objs.get("category", objs.get("category_id", []))
145
+ gt_bbox = objs.get("bbox", [])
146
+ else: # list of dicts
147
+ for o in objs:
148
+ if "category" in o:
149
+ gt_cats.append(o["category"])
150
+ elif "category_id" in o:
151
+ gt_cats.append(o["category_id"])
152
+ gt_bbox.append(o["bbox"])
153
+
154
+ bbox_vals = [v for d in dets for v in d["bbox"]]
155
+ bbox_max = max(bbox_vals) if bbox_vals else 0
156
+ bbox_min = min(bbox_vals) if bbox_vals else 0
157
+ qwen_hist = Counter(d["label"] for d in dets)
158
+ gt_hist = Counter(
159
+ gt_names[c] if 0 <= c < len(gt_names) else f"#{c}" for c in gt_cats
160
+ ) if gt_names else Counter()
161
+
162
+ print(
163
+ f"\n=== row {i} image_id={row.get('image_id', '?')} orig={W}x{H} "
164
+ f"inference_image_size={info['image_size']} ==="
165
+ )
166
+ if gt_cats:
167
+ print(f" GT: {len(gt_cats)} objects {dict(gt_hist)}")
168
+ print(f" Qwen: {len(dets)} detections {dict(qwen_hist)}")
169
+ print(f" Qwen bbox range: [{bbox_min:.0f}, {bbox_max:.0f}] (image {W}x{H})")
170
+
171
+ # Render
172
+ n_panels = 2 if gt_cats else 1
173
+ fig, axes = plt.subplots(1, n_panels, figsize=(10 * n_panels, 12))
174
+ if n_panels == 1:
175
+ axes = [axes]
176
+ for ax in axes:
177
+ ax.imshow(img)
178
+ ax.set_xlim(0, W)
179
+ ax.set_ylim(H, 0)
180
+ ax.set_aspect("equal")
181
+ ax.axis("off")
182
+
183
+ # v1.1+ output stores bbox in pixel coords; v1 stored 0-1000 normalised.
184
+ needs_denorm = bbox_max <= 1001 and max(W, H) > 1001
185
+ sx = (W / 1000.0) if needs_denorm else 1.0
186
+ sy = (H / 1000.0) if needs_denorm else 1.0
187
+ title_extra = "(0-1000 → pixels)" if needs_denorm else "(pixel coords)"
188
+
189
+ axes[0].set_title(
190
+ f"Detections (n={len(dets)}) {title_extra} range [{bbox_min:.0f}, {bbox_max:.0f}]",
191
+ fontsize=11,
192
+ )
193
+ for d in dets:
194
+ b = d["bbox"]
195
+ if len(b) == 4:
196
+ render_box(axes[0], b[0] * sx, b[1] * sy, b[2] * sx, b[3] * sy, "#E03030", lw=1.0)
197
+ for d in dets[:10]:
198
+ b = d["bbox"]
199
+ if len(b) == 4:
200
+ render_box(
201
+ axes[0],
202
+ b[0] * sx,
203
+ b[1] * sy,
204
+ b[2] * sx,
205
+ b[3] * sy,
206
+ "#E03030",
207
+ lw=1.4,
208
+ label=d["label"][:18],
209
+ fontsize=8,
210
+ )
211
+
212
+ if gt_cats and len(axes) > 1:
213
+ palette = [
214
+ "#1f78b4", "#33a02c", "#ff7f00", "#6a3d9a", "#b15928",
215
+ "#e31a1c", "#fb9a99", "#a6cee3", "#b2df8a", "#fdbf6f",
216
+ "#cab2d6", "#ffff99",
217
+ ]
218
+ color_by_name: dict[str, str] = {}
219
+ axes[1].set_title(f"Ground truth (n={len(gt_cats)})", fontsize=11)
220
+ for c, b in zip(gt_cats, gt_bbox):
221
+ if len(b) != 4:
222
+ continue
223
+ name = gt_names[c] if 0 <= c < len(gt_names) else f"#{c}"
224
+ color = color_by_name.setdefault(name, palette[len(color_by_name) % len(palette)])
225
+ x, y, w_, h_ = b # COCO xywh
226
+ render_box(axes[1], x, y, x + w_, y + h_, color, lw=2.0, label=name[:18], fontsize=8)
227
+
228
+ plt.tight_layout()
229
+ path = f"{out_dir}/row{i}_id{row.get('image_id', i)}.png"
230
+ plt.savefig(path, dpi=70, bbox_inches="tight")
231
+ plt.close()
232
+
233
+ print(f"\nDone. {len(ds)} rows. Open: {out_dir}")
234
+
235
+
236
+ if __name__ == "__main__":
237
+ main()