MoreGeometrico commited on
Commit
7e56503
·
verified ·
1 Parent(s): d6b42bf

Upload folder using huggingface_hub

Browse files
.DS_Store ADDED
Binary file (6.15 kB). View file
 
README.md ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: DD1 PB VQA Grounding
3
+ tags:
4
+ - visual-question-answering
5
+ - visual-grounding
6
+ - industrial
7
+ - additive-manufacturing
8
+ - sft
9
+ task_categories:
10
+ - visual-question-answering
11
+ ---
12
+
13
+ # DD1 PB VQA Grounding
14
+
15
+ Answer-only VQA-style grounding data derived deterministically from the PB
16
+ portion of `DD1_cleaned_grounding`.
17
+
18
+ ## Schema
19
+
20
+ | field | type | meaning |
21
+ |---|---|---|
22
+ | `query` | string | one of 34 deterministic LPBF PB grounding prompts |
23
+ | `image` | Image | original 1280×1024 JPEG bytes; never cropped |
24
+ | `annot` | string | JSON list `[{"bbox_xywh":[x,y,w,h]}]`, or `[]` |
25
+ | `reasoning` | null | answer-only dataset |
26
+ | `cate` | string | `B` |
27
+ | `task` | string | `T-B1` |
28
+ | `metadata` | string | JSON provenance, hashes, boxes and disclosures |
29
+
30
+ Coordinates use native pixels with top-left origin. Width and height are
31
+ `xmax-xmin` and `ymax-ymin`.
32
+
33
+ ## Counts
34
+
35
+ - Records: 2637
36
+ - Positive images: 1529
37
+ - Good/negative images: 1108
38
+ - Total boxes: 5000
39
+ - Query variants: 34
40
+ - Split: train only
41
+
42
+ ## Load
43
+
44
+ ```python
45
+ from datasets import load_dataset
46
+ ds = load_dataset(
47
+ "parquet",
48
+ data_files={"train": "data/train-00000-of-00001.parquet"},
49
+ )
50
+ ```
51
+
52
+ `annot` is the direct SFT answer. `reasoning` is null on every row.
53
+
54
+ ## Reproduce
55
+
56
+ ```bash
57
+ python3 -m pip install -r requirements.txt
58
+ python3 build_dd1_pb_vqa.py \
59
+ --source /path/to/DD1_cleaned_grounding \
60
+ --output /path/to/DD1_PB_VQA_grounding
61
+ ```
62
+
63
+ ## Disclosure
64
+
65
+ The source uses the generic class label `defects` without a subtype taxonomy.
66
+ `Good` means no author-annotated PB defect under the source labeling rule; it
67
+ does not guarantee absence of every possible manufacturing defect.
build_dd1_pb_vqa.py ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build answer-only VQA grounding data from DD1_cleaned_grounding/PB."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import shutil
10
+ import statistics
11
+ import sys
12
+ import tempfile
13
+ import xml.etree.ElementTree as ET
14
+ from collections import Counter
15
+ from io import BytesIO
16
+ from pathlib import Path
17
+ from typing import Any, Iterator
18
+
19
+
20
+ def import_dependencies() -> tuple[Any, Any, Any, Any, Any, Any]:
21
+ candidates = (
22
+ Path.cwd() / "tmp_work" / "pydeps",
23
+ Path(__file__).resolve().parent / "tmp_work" / "pydeps",
24
+ Path(__file__).resolve().parent.parent / "tmp_work" / "pydeps",
25
+ )
26
+ for candidate in candidates:
27
+ if candidate.is_dir():
28
+ sys.path.insert(0, str(candidate))
29
+ try:
30
+ from datasets import Dataset, Features, Image, Value, load_dataset
31
+ from PIL import Image as PILImage
32
+ except ModuleNotFoundError as error:
33
+ raise SystemExit(
34
+ "Missing dependencies. Install requirements.txt first."
35
+ ) from error
36
+ return Dataset, Features, Image, Value, load_dataset, PILImage
37
+
38
+
39
+ Dataset, Features, HFImage, Value, load_dataset, PILImage = import_dependencies()
40
+
41
+ WIDTH = 1280
42
+ HEIGHT = 1024
43
+ EXPECTED_IMAGES = 2637
44
+ EXPECTED_POSITIVES = 1529
45
+ EXPECTED_NEGATIVES = 1108
46
+ EXPECTED_BOXES = 5000
47
+ QUERY_SALT = "DD1_PB_VQA_QUERY_V1"
48
+
49
+ OUTPUT_DIRECTIVE = (
50
+ 'Output a JSON list [{"bbox_xywh": [x, y, w, h]}] in native pixels, '
51
+ "origin top-left, one box per annotated powder-bed defect region, sorted "
52
+ "by x then y; output [] if none."
53
+ )
54
+
55
+ QUERY_PREFIXES = (
56
+ "Inspect this LPBF powder-bed image and locate every annotated defect region.",
57
+ "Examine this laser powder bed fusion layer image and find all annotated powder-bed defects.",
58
+ "Review this LPBF powder-bed frame and localize every annotated defect.",
59
+ "Analyze this powder-bed layer image and identify all annotated defect regions.",
60
+ "Perform defect localization on this LPBF powder-bed image.",
61
+ "Check this additive-manufacturing powder-bed image and locate every annotated defect area.",
62
+ "Inspect this LPBF layer image and return all annotated powder-bed defect boxes.",
63
+ "Locate all annotated defect regions visible in this LPBF powder-bed layer.",
64
+ "Examine this powder-bed monitoring image and localize each annotated defect region.",
65
+ "Review this powder-bed frame from laser powder bed fusion and find every annotated defect.",
66
+ "Detect and localize all annotated defects in this LPBF powder-bed image.",
67
+ "Inspect this LPBF build-layer image and identify every annotated powder-bed defect.",
68
+ "Analyze this powder-bed monitoring image and locate all annotated defect areas.",
69
+ "Find every annotated defect region in this laser powder bed fusion layer image.",
70
+ "Perform visual grounding of all annotated defects in this LPBF powder-bed image.",
71
+ "Examine this powder-bed process image and return every annotated defect location.",
72
+ "Review the current LPBF powder-bed layer and localize each annotated defect.",
73
+ "Inspect this additive-manufacturing layer image and locate all annotated powder-bed defects.",
74
+ "Analyze this LPBF powder-bed frame and ground every annotated defect region.",
75
+ "Locate each annotated defect region in this powder-bed image of an LPBF build layer.",
76
+ "Check this LPBF powder-bed layer for annotations and return each corresponding defect region.",
77
+ "Inspect this powder-bed image and identify the bounding boxes of all annotated defects.",
78
+ "Examine this LPBF process image and localize all annotated powder-bed defects.",
79
+ "Review this LPBF build-layer image and find every annotated powder-bed defect region.",
80
+ "Analyze this powder-bed frame and locate all regions annotated as defects.",
81
+ "Ground every annotated defect region in this powder-bed monitoring image.",
82
+ "Inspect this LPBF powder-bed frame and return all annotated defect-region boxes.",
83
+ "Find and localize every annotated defect area in this powder-bed image.",
84
+ "Examine the current additive-manufacturing powder bed and locate all annotated defects.",
85
+ "Review this LPBF powder-bed image and identify every region annotated as defective.",
86
+ "Perform defect-region grounding in this LPBF powder-bed layer.",
87
+ "Inspect this view of the LPBF powder bed and localize all annotated defect regions.",
88
+ "Analyze this LPBF layer image and return every annotated powder-bed defect location.",
89
+ "Check this LPBF powder-bed monitoring frame and ground all annotated defect regions.",
90
+ )
91
+
92
+
93
+ def parse_args() -> argparse.Namespace:
94
+ parser = argparse.ArgumentParser()
95
+ parser.add_argument("--source", type=Path, default=None)
96
+ parser.add_argument("--output", type=Path, default=None)
97
+ return parser.parse_args()
98
+
99
+
100
+ def resolve_source(value: Path | None) -> Path:
101
+ if value is not None:
102
+ return value.resolve()
103
+ script = Path(__file__).resolve()
104
+ for candidate in (
105
+ Path.cwd() / "DD1_cleaned_grounding",
106
+ script.parent / "DD1_cleaned_grounding",
107
+ script.parent.parent / "DD1_cleaned_grounding",
108
+ ):
109
+ if (candidate / "PB").is_dir() and (candidate / "PB_label").is_dir():
110
+ return candidate.resolve()
111
+ raise SystemExit("Cannot locate DD1_cleaned_grounding; pass --source.")
112
+
113
+
114
+ def sha256_bytes(data: bytes) -> str:
115
+ return hashlib.sha256(data).hexdigest()
116
+
117
+
118
+ def sha256_file(path: Path) -> str:
119
+ digest = hashlib.sha256()
120
+ with path.open("rb") as handle:
121
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
122
+ digest.update(block)
123
+ return digest.hexdigest()
124
+
125
+
126
+ def compact_json(value: Any) -> str:
127
+ return json.dumps(
128
+ value, ensure_ascii=False, sort_keys=True, separators=(",", ":")
129
+ )
130
+
131
+
132
+ def parse_build_layer(filename: str) -> tuple[str, int]:
133
+ parts = Path(filename).stem.split("_")
134
+ if len(parts) < 3 or not parts[0].startswith("SI"):
135
+ raise ValueError(f"Cannot parse build/layer from {filename}")
136
+ return parts[0], int(parts[1])
137
+
138
+
139
+ def parse_boxes(xml_path: Path, image_name: str) -> tuple[list[dict[str, list[int]]], str]:
140
+ root = ET.parse(xml_path).getroot()
141
+ if root.find("path") is not None:
142
+ raise ValueError(f"Machine-local path remains in {xml_path}")
143
+ if root.findtext("filename") != image_name:
144
+ raise ValueError(f"XML filename mismatch in {xml_path}")
145
+ size = (
146
+ int(root.findtext("size/width", "0")),
147
+ int(root.findtext("size/height", "0")),
148
+ )
149
+ if size != (WIDTH, HEIGHT):
150
+ raise ValueError(f"Unexpected XML size {size} in {xml_path}")
151
+ boxes: list[dict[str, list[int]]] = []
152
+ for index, obj in enumerate(root.findall("object")):
153
+ label = (obj.findtext("name") or "").strip()
154
+ if label != "defects":
155
+ raise ValueError(f"Unexpected label {label!r} in {xml_path}")
156
+ box = obj.find("bndbox")
157
+ if box is None:
158
+ raise ValueError(f"Missing bbox {index} in {xml_path}")
159
+ xmin, ymin, xmax, ymax = (
160
+ int(float(box.findtext(key, "nan")))
161
+ for key in ("xmin", "ymin", "xmax", "ymax")
162
+ )
163
+ if (
164
+ xmax <= xmin
165
+ or ymax <= ymin
166
+ or xmin < 0
167
+ or ymin < 0
168
+ or xmax > WIDTH
169
+ or ymax > HEIGHT
170
+ ):
171
+ raise ValueError(
172
+ f"Invalid bbox {[xmin, ymin, xmax, ymax]} in {xml_path}"
173
+ )
174
+ boxes.append(
175
+ {"bbox_xywh": [xmin, ymin, xmax - xmin, ymax - ymin]}
176
+ )
177
+ if not boxes:
178
+ raise ValueError(f"Positive XML contains no objects: {xml_path}")
179
+ boxes.sort(key=lambda item: tuple(item["bbox_xywh"]))
180
+ return boxes, sha256_file(xml_path)
181
+
182
+
183
+ def choose_query(image_sha: str) -> tuple[str, int]:
184
+ digest = hashlib.sha256(
185
+ f"{QUERY_SALT}:{image_sha}".encode("utf-8")
186
+ ).digest()
187
+ index = int.from_bytes(digest[:8], "big") % len(QUERY_PREFIXES)
188
+ return f"{QUERY_PREFIXES[index]} {OUTPUT_DIRECTIVE}", index
189
+
190
+
191
+ def create_records(
192
+ source: Path, summary: dict[str, Any]
193
+ ) -> Iterator[dict[str, Any]]:
194
+ images = sorted((source / "PB").glob("*.jpg"))
195
+ xml_by_stem = {
196
+ path.stem: path for path in (source / "PB_label").glob("*.xml")
197
+ }
198
+ image_stems = {path.stem for path in images}
199
+ if len(images) != EXPECTED_IMAGES:
200
+ raise ValueError(f"Expected {EXPECTED_IMAGES} images, got {len(images)}")
201
+ if len(xml_by_stem) != EXPECTED_POSITIVES:
202
+ raise ValueError(
203
+ f"Expected {EXPECTED_POSITIVES} XMLs, got {len(xml_by_stem)}"
204
+ )
205
+ if not set(xml_by_stem).issubset(image_stems):
206
+ raise ValueError("A PB XML has no corresponding image")
207
+
208
+ for image_path in images:
209
+ image_bytes = image_path.read_bytes()
210
+ with PILImage.open(BytesIO(image_bytes)) as image:
211
+ if image.size != (WIDTH, HEIGHT):
212
+ raise ValueError(
213
+ f"Unexpected image size {image.size}: {image_path}"
214
+ )
215
+ image.verify()
216
+ image_sha = sha256_bytes(image_bytes)
217
+ build_id, layer_id = parse_build_layer(image_path.name)
218
+ xml_path = xml_by_stem.get(image_path.stem)
219
+ if xml_path is None:
220
+ boxes: list[dict[str, list[int]]] = []
221
+ xml_sha = None
222
+ else:
223
+ boxes, xml_sha = parse_boxes(xml_path, image_path.name)
224
+ query, query_variant = choose_query(image_sha)
225
+ negative = not boxes
226
+ metadata = {
227
+ "image_sha256": image_sha,
228
+ "negative": negative,
229
+ "n_boxes": len(boxes),
230
+ "gold_boxes_xywh": boxes,
231
+ "derivation": "manual_pascal_voc_xml_to_native_xywh",
232
+ "legibility_floor": None,
233
+ "fill_floor": None,
234
+ "gold_scope": (
235
+ "all author-annotated generic defect regions in the cleaned "
236
+ "DD1 powder-bed XML"
237
+ ),
238
+ "goods_carveout": (
239
+ "no XML in cleaned DD1 PB; [] means no author-annotated "
240
+ "powder-bed defect under the source labeling rule"
241
+ ),
242
+ "anonymous_class": True,
243
+ "object_class": "defects",
244
+ "disclosures": [
245
+ "the source uses the generic class name 'defects' without a "
246
+ "defect subtype taxonomy",
247
+ "Good means no author-annotated PB defect, not guaranteed "
248
+ "absence of every possible manufacturing defect",
249
+ ],
250
+ "family": "DD1",
251
+ "rung": "PB-grounding",
252
+ "gate_provenance": {
253
+ "builder": "build_dd1_pb_vqa.py",
254
+ "query_salt": QUERY_SALT,
255
+ "source_cleaning_report": "cleaning_report.json",
256
+ },
257
+ "modality": "PB",
258
+ "build_id": build_id,
259
+ "layer_id": layer_id,
260
+ "image_width": WIDTH,
261
+ "image_height": HEIGHT,
262
+ "source_image": f"PB/{image_path.name}",
263
+ "source_xml": (
264
+ f"PB_label/{xml_path.name}" if xml_path is not None else None
265
+ ),
266
+ "source_xml_sha256": xml_sha,
267
+ "query_variant": query_variant,
268
+ "coordinate_format": "native_pixel_xywh_top_left",
269
+ "xywh_derivation": "x=xmin,y=ymin,w=xmax-xmin,h=ymax-ymin",
270
+ "box_order": "x_then_y",
271
+ "split": "train",
272
+ }
273
+ summary["records"] += 1
274
+ summary["negative" if negative else "positive"] += 1
275
+ summary["boxes"] += len(boxes)
276
+ summary["box_counts"].append(len(boxes))
277
+ summary["query_variants"][query_variant] += 1
278
+ summary["builds"][build_id] += 1
279
+ yield {
280
+ "query": query,
281
+ "image": {"bytes": image_bytes, "path": image_path.name},
282
+ "annot": compact_json(boxes),
283
+ "reasoning": None,
284
+ "cate": "B",
285
+ "task": "T-B1",
286
+ "metadata": compact_json(metadata),
287
+ }
288
+
289
+
290
+ def validate_parquet(parquet_path: Path) -> dict[str, Any]:
291
+ cache = parquet_path.parent.parent / ".validation_cache"
292
+ dataset = load_dataset(
293
+ "parquet",
294
+ data_files={"train": str(parquet_path)},
295
+ split="train",
296
+ cache_dir=str(cache),
297
+ )
298
+ if dataset.column_names != [
299
+ "query", "image", "annot", "reasoning", "cate", "task", "metadata"
300
+ ]:
301
+ raise ValueError(f"Unexpected columns: {dataset.column_names}")
302
+ counts = Counter()
303
+ image_hashes: set[str] = set()
304
+ variants: set[int] = set()
305
+ for index, row in enumerate(dataset):
306
+ metadata = json.loads(row["metadata"])
307
+ boxes = json.loads(row["annot"])
308
+ if row["reasoning"] is not None:
309
+ raise ValueError(f"Non-null reasoning at row {index}")
310
+ if row["cate"] != "B" or row["task"] != "T-B1":
311
+ raise ValueError(f"cate/task mismatch at row {index}")
312
+ if not row["query"].endswith(OUTPUT_DIRECTIVE):
313
+ raise ValueError(f"query mismatch at row {index}")
314
+ if boxes != metadata["gold_boxes_xywh"]:
315
+ raise ValueError(f"annot/metadata mismatch at row {index}")
316
+ if len(boxes) != metadata["n_boxes"]:
317
+ raise ValueError(f"n_boxes mismatch at row {index}")
318
+ if (not boxes) != metadata["negative"]:
319
+ raise ValueError(f"negative mismatch at row {index}")
320
+ if boxes != sorted(boxes, key=lambda item: tuple(item["bbox_xywh"])):
321
+ raise ValueError(f"box ordering mismatch at row {index}")
322
+ for item in boxes:
323
+ x, y, width, height = item["bbox_xywh"]
324
+ if (
325
+ width <= 0 or height <= 0 or x < 0 or y < 0
326
+ or x + width > WIDTH or y + height > HEIGHT
327
+ ):
328
+ raise ValueError(f"Invalid box at row {index}: {item}")
329
+ image_bytes = row["image"].get("bytes")
330
+ if image_bytes is None:
331
+ raise ValueError(f"Missing image bytes at row {index}")
332
+ image_sha = sha256_bytes(image_bytes)
333
+ if image_sha != metadata["image_sha256"]:
334
+ raise ValueError(f"Image hash mismatch at row {index}")
335
+ if image_sha in image_hashes:
336
+ raise ValueError(f"Duplicate image content at row {index}")
337
+ image_hashes.add(image_sha)
338
+ counts["records"] += 1
339
+ counts["positive" if boxes else "negative"] += 1
340
+ counts["boxes"] += len(boxes)
341
+ variants.add(metadata["query_variant"])
342
+ expected = {
343
+ "records": EXPECTED_IMAGES,
344
+ "positive": EXPECTED_POSITIVES,
345
+ "negative": EXPECTED_NEGATIVES,
346
+ "boxes": EXPECTED_BOXES,
347
+ }
348
+ actual = {key: counts[key] for key in expected}
349
+ if actual != expected or len(variants) != len(QUERY_PREFIXES):
350
+ raise ValueError(
351
+ f"Aggregate validation failed: {actual}, variants={len(variants)}"
352
+ )
353
+ result = {
354
+ **actual,
355
+ "unique_images": len(image_hashes),
356
+ "query_variants_used": len(variants),
357
+ "features": str(dataset.features),
358
+ }
359
+ del dataset
360
+ shutil.rmtree(cache, ignore_errors=True)
361
+ return result
362
+
363
+
364
+ def make_readme(report: dict[str, Any]) -> str:
365
+ return f"""---
366
+ pretty_name: DD1 PB VQA Grounding
367
+ tags:
368
+ - visual-question-answering
369
+ - visual-grounding
370
+ - industrial
371
+ - additive-manufacturing
372
+ - sft
373
+ task_categories:
374
+ - visual-question-answering
375
+ ---
376
+
377
+ # DD1 PB VQA Grounding
378
+
379
+ Answer-only VQA-style grounding data derived deterministically from the PB
380
+ portion of `DD1_cleaned_grounding`.
381
+
382
+ ## Schema
383
+
384
+ | field | type | meaning |
385
+ |---|---|---|
386
+ | `query` | string | one of 34 deterministic LPBF PB grounding prompts |
387
+ | `image` | Image | original 1280×1024 JPEG bytes; never cropped |
388
+ | `annot` | string | JSON list `[{{"bbox_xywh":[x,y,w,h]}}]`, or `[]` |
389
+ | `reasoning` | null | answer-only dataset |
390
+ | `cate` | string | `B` |
391
+ | `task` | string | `T-B1` |
392
+ | `metadata` | string | JSON provenance, hashes, boxes and disclosures |
393
+
394
+ Coordinates use native pixels with top-left origin. Width and height are
395
+ `xmax-xmin` and `ymax-ymin`.
396
+
397
+ ## Counts
398
+
399
+ - Records: {report["records"]}
400
+ - Positive images: {report["positive"]}
401
+ - Good/negative images: {report["negative"]}
402
+ - Total boxes: {report["boxes"]}
403
+ - Query variants: {report["query_variants_used"]}
404
+ - Split: train only
405
+
406
+ ## Load
407
+
408
+ ```python
409
+ from datasets import load_dataset
410
+ ds = load_dataset(
411
+ "parquet",
412
+ data_files={{"train": "data/train-00000-of-00001.parquet"}},
413
+ )
414
+ ```
415
+
416
+ `annot` is the direct SFT answer. `reasoning` is null on every row.
417
+
418
+ ## Reproduce
419
+
420
+ ```bash
421
+ python3 -m pip install -r requirements.txt
422
+ python3 build_dd1_pb_vqa.py \\
423
+ --source /path/to/DD1_cleaned_grounding \\
424
+ --output /path/to/DD1_PB_VQA_grounding
425
+ ```
426
+
427
+ ## Disclosure
428
+
429
+ The source uses the generic class label `defects` without a subtype taxonomy.
430
+ `Good` means no author-annotated PB defect under the source labeling rule; it
431
+ does not guarantee absence of every possible manufacturing defect.
432
+ """
433
+
434
+
435
+ def main() -> None:
436
+ if len(QUERY_PREFIXES) != 34 or len(set(QUERY_PREFIXES)) != 34:
437
+ raise SystemExit("QUERY_PREFIXES must contain 34 unique variants")
438
+ args = parse_args()
439
+ source = resolve_source(args.source)
440
+ output = (
441
+ args.output.resolve()
442
+ if args.output is not None
443
+ else source.parent / "DD1_PB_VQA_grounding"
444
+ )
445
+ if output.exists():
446
+ raise SystemExit(f"Refusing to overwrite existing output: {output}")
447
+ if not (source / "PB").is_dir() or not (source / "PB_label").is_dir():
448
+ raise SystemExit(f"Invalid source directory: {source}")
449
+
450
+ temporary = Path(
451
+ tempfile.mkdtemp(prefix=f".{output.name}.tmp-", dir=output.parent)
452
+ )
453
+ try:
454
+ (temporary / "data").mkdir()
455
+ summary: dict[str, Any] = {
456
+ "records": 0,
457
+ "positive": 0,
458
+ "negative": 0,
459
+ "boxes": 0,
460
+ "box_counts": [],
461
+ "query_variants": Counter(),
462
+ "builds": Counter(),
463
+ }
464
+ features = Features(
465
+ {
466
+ "query": Value("string"),
467
+ "image": HFImage(decode=False),
468
+ "annot": Value("string"),
469
+ "reasoning": Value("null"),
470
+ "cate": Value("string"),
471
+ "task": Value("string"),
472
+ "metadata": Value("string"),
473
+ }
474
+ )
475
+ dataset = Dataset.from_generator(
476
+ lambda: create_records(source, summary),
477
+ features=features,
478
+ cache_dir=str(temporary / ".cache"),
479
+ )
480
+ expected = {
481
+ "records": EXPECTED_IMAGES,
482
+ "positive": EXPECTED_POSITIVES,
483
+ "negative": EXPECTED_NEGATIVES,
484
+ "boxes": EXPECTED_BOXES,
485
+ }
486
+ if {key: summary[key] for key in expected} != expected:
487
+ raise ValueError(f"Unexpected generated counts: {summary}")
488
+ if len(summary["query_variants"]) != len(QUERY_PREFIXES):
489
+ raise ValueError("Not all query variants were selected")
490
+
491
+ parquet = temporary / "data/train-00000-of-00001.parquet"
492
+ dataset.to_parquet(parquet)
493
+ shutil.rmtree(temporary / ".cache", ignore_errors=True)
494
+ validation = validate_parquet(parquet)
495
+ positives = [count for count in summary["box_counts"] if count]
496
+ report = {
497
+ "source": "DD1_cleaned_grounding",
498
+ "output": "DD1_PB_VQA_grounding",
499
+ "records": summary["records"],
500
+ "positive": summary["positive"],
501
+ "negative": summary["negative"],
502
+ "empty_answer_prior": round(
503
+ summary["negative"] / summary["records"], 8
504
+ ),
505
+ "boxes": summary["boxes"],
506
+ "boxes_per_positive_mean": round(statistics.mean(positives), 6),
507
+ "boxes_per_positive_median": statistics.median(positives),
508
+ "boxes_per_positive_max": max(positives),
509
+ "query_variants_used": len(summary["query_variants"]),
510
+ "query_variant_counts": {
511
+ str(key): value
512
+ for key, value in sorted(summary["query_variants"].items())
513
+ },
514
+ "build_counts": dict(sorted(summary["builds"].items())),
515
+ "schema": {
516
+ "query": "string",
517
+ "image": "Image",
518
+ "annot": "string",
519
+ "reasoning": "null",
520
+ "cate": "string",
521
+ "task": "string",
522
+ "metadata": "string(JSON)",
523
+ },
524
+ "coordinate_format": "native_pixel_xywh_top_left",
525
+ "parquet_sha256": sha256_file(parquet),
526
+ "builder_sha256": sha256_file(Path(__file__).resolve()),
527
+ "validation": validation,
528
+ "status": "pass",
529
+ }
530
+ (temporary / "build_report.json").write_text(
531
+ json.dumps(report, ensure_ascii=False, indent=2) + "\n",
532
+ encoding="utf-8",
533
+ )
534
+ (temporary / "query_templates.json").write_text(
535
+ json.dumps(
536
+ {
537
+ "salt": QUERY_SALT,
538
+ "output_directive": OUTPUT_DIRECTIVE,
539
+ "prefixes": list(QUERY_PREFIXES),
540
+ },
541
+ ensure_ascii=False,
542
+ indent=2,
543
+ )
544
+ + "\n",
545
+ encoding="utf-8",
546
+ )
547
+ (temporary / "README.md").write_text(
548
+ make_readme(report), encoding="utf-8"
549
+ )
550
+ (temporary / "requirements.txt").write_text(
551
+ "datasets==5.0.0\npyarrow==25.0.0\nPillow>=12.0.0\n",
552
+ encoding="utf-8",
553
+ )
554
+ shutil.copy2(
555
+ Path(__file__).resolve(), temporary / Path(__file__).name
556
+ )
557
+ temporary.rename(output)
558
+ print(json.dumps(report, ensure_ascii=False, indent=2))
559
+ except Exception:
560
+ shutil.rmtree(temporary, ignore_errors=True)
561
+ raise
562
+
563
+
564
+ if __name__ == "__main__":
565
+ main()
build_report.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": "DD1_cleaned_grounding",
3
+ "output": "DD1_PB_VQA_grounding",
4
+ "records": 2637,
5
+ "positive": 1529,
6
+ "negative": 1108,
7
+ "empty_answer_prior": 0.42017444,
8
+ "boxes": 5000,
9
+ "boxes_per_positive_mean": 3.270111,
10
+ "boxes_per_positive_median": 3,
11
+ "boxes_per_positive_max": 12,
12
+ "query_variants_used": 34,
13
+ "query_variant_counts": {
14
+ "0": 73,
15
+ "1": 67,
16
+ "2": 82,
17
+ "3": 67,
18
+ "4": 74,
19
+ "5": 86,
20
+ "6": 81,
21
+ "7": 70,
22
+ "8": 88,
23
+ "9": 96,
24
+ "10": 89,
25
+ "11": 72,
26
+ "12": 77,
27
+ "13": 76,
28
+ "14": 67,
29
+ "15": 74,
30
+ "16": 80,
31
+ "17": 80,
32
+ "18": 70,
33
+ "19": 88,
34
+ "20": 96,
35
+ "21": 77,
36
+ "22": 66,
37
+ "23": 73,
38
+ "24": 78,
39
+ "25": 78,
40
+ "26": 71,
41
+ "27": 79,
42
+ "28": 72,
43
+ "29": 72,
44
+ "30": 85,
45
+ "31": 74,
46
+ "32": 81,
47
+ "33": 78
48
+ },
49
+ "build_counts": {
50
+ "SI383820211201123521": 999,
51
+ "SI383820240226095904": 271,
52
+ "SI383820240318120348": 1367
53
+ },
54
+ "schema": {
55
+ "query": "string",
56
+ "image": "Image",
57
+ "annot": "string",
58
+ "reasoning": "null",
59
+ "cate": "string",
60
+ "task": "string",
61
+ "metadata": "string(JSON)"
62
+ },
63
+ "coordinate_format": "native_pixel_xywh_top_left",
64
+ "parquet_sha256": "7a98b1c24e7bcc0b4c4598b94e3c4bb605e607ef27f20e296c1fa3f0fd48b7d0",
65
+ "builder_sha256": "9fac7bdfe7aa71fd57d6f75436a253f2a7ae77e05e7d4fb88d6398969cc919fa",
66
+ "validation": {
67
+ "records": 2637,
68
+ "positive": 1529,
69
+ "negative": 1108,
70
+ "boxes": 5000,
71
+ "unique_images": 2637,
72
+ "query_variants_used": 34,
73
+ "features": "{'query': Value('string'), 'image': Image(mode=None, decode=False), 'annot': Value('string'), 'reasoning': Value('null'), 'cate': Value('string'), 'task': Value('string'), 'metadata': Value('string')}"
74
+ },
75
+ "status": "pass"
76
+ }
data/train-00000-of-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a98b1c24e7bcc0b4c4598b94e3c4bb605e607ef27f20e296c1fa3f0fd48b7d0
3
+ size 343539799
query_templates.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "salt": "DD1_PB_VQA_QUERY_V1",
3
+ "output_directive": "Output a JSON list [{\"bbox_xywh\": [x, y, w, h]}] in native pixels, origin top-left, one box per annotated powder-bed defect region, sorted by x then y; output [] if none.",
4
+ "prefixes": [
5
+ "Inspect this LPBF powder-bed image and locate every annotated defect region.",
6
+ "Examine this laser powder bed fusion layer image and find all annotated powder-bed defects.",
7
+ "Review this LPBF powder-bed frame and localize every annotated defect.",
8
+ "Analyze this powder-bed layer image and identify all annotated defect regions.",
9
+ "Perform defect localization on this LPBF powder-bed image.",
10
+ "Check this additive-manufacturing powder-bed image and locate every annotated defect area.",
11
+ "Inspect this LPBF layer image and return all annotated powder-bed defect boxes.",
12
+ "Locate all annotated defect regions visible in this LPBF powder-bed layer.",
13
+ "Examine this powder-bed monitoring image and localize each annotated defect region.",
14
+ "Review this powder-bed frame from laser powder bed fusion and find every annotated defect.",
15
+ "Detect and localize all annotated defects in this LPBF powder-bed image.",
16
+ "Inspect this LPBF build-layer image and identify every annotated powder-bed defect.",
17
+ "Analyze this powder-bed monitoring image and locate all annotated defect areas.",
18
+ "Find every annotated defect region in this laser powder bed fusion layer image.",
19
+ "Perform visual grounding of all annotated defects in this LPBF powder-bed image.",
20
+ "Examine this powder-bed process image and return every annotated defect location.",
21
+ "Review the current LPBF powder-bed layer and localize each annotated defect.",
22
+ "Inspect this additive-manufacturing layer image and locate all annotated powder-bed defects.",
23
+ "Analyze this LPBF powder-bed frame and ground every annotated defect region.",
24
+ "Locate each annotated defect region in this powder-bed image of an LPBF build layer.",
25
+ "Check this LPBF powder-bed layer for annotations and return each corresponding defect region.",
26
+ "Inspect this powder-bed image and identify the bounding boxes of all annotated defects.",
27
+ "Examine this LPBF process image and localize all annotated powder-bed defects.",
28
+ "Review this LPBF build-layer image and find every annotated powder-bed defect region.",
29
+ "Analyze this powder-bed frame and locate all regions annotated as defects.",
30
+ "Ground every annotated defect region in this powder-bed monitoring image.",
31
+ "Inspect this LPBF powder-bed frame and return all annotated defect-region boxes.",
32
+ "Find and localize every annotated defect area in this powder-bed image.",
33
+ "Examine the current additive-manufacturing powder bed and locate all annotated defects.",
34
+ "Review this LPBF powder-bed image and identify every region annotated as defective.",
35
+ "Perform defect-region grounding in this LPBF powder-bed layer.",
36
+ "Inspect this view of the LPBF powder bed and localize all annotated defect regions.",
37
+ "Analyze this LPBF layer image and return every annotated powder-bed defect location.",
38
+ "Check this LPBF powder-bed monitoring frame and ground all annotated defect regions."
39
+ ]
40
+ }
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ datasets==5.0.0
2
+ pyarrow==25.0.0
3
+ Pillow>=12.0.0