File size: 31,246 Bytes
89ae044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
#!/usr/bin/env python3
"""Validate the unified cross-view dataset.

Stdlib only. Run from anywhere:

    python3 scripts/validate.py                     # checks + writes quality/qc_report.md
    python3 scripts/validate.py --no-report         # checks only
    python3 scripts/validate.py --json              # machine-readable summary

Exit status: 0 when no errors were found, 1 otherwise. Warnings do not fail the
run but are listed in the report. Unresolved source object ids are errors: the
validator deliberately refuses to invent an identity that the annotator left
empty.
"""

from __future__ import annotations

import argparse
import csv
import hashlib
import json
import re
import sys
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path

CANONICAL_OBJECT_ID = re.compile(r"^OBJ_\d{3}$")
VIEW_ID_RE = re.compile(r"^(.+)_view_(\d{2,})$")
ATTR_NAMES = ("object_id", "viewpoint", "lighting", "background", "distance", "view_group")


# --------------------------------------------------------------------------- #
# Tiny JSON Schema validator (supports the keywords used by our schema)
# --------------------------------------------------------------------------- #
def _type_ok(value, expected) -> bool:
    types = expected if isinstance(expected, list) else [expected]
    checks = {
        "object": lambda v: isinstance(v, dict),
        "array": lambda v: isinstance(v, list),
        "string": lambda v: isinstance(v, str),
        "integer": lambda v: isinstance(v, int) and not isinstance(v, bool),
        "number": lambda v: isinstance(v, (int, float)) and not isinstance(v, bool),
        "boolean": lambda v: isinstance(v, bool),
        "null": lambda v: v is None,
    }
    return any(checks[t](value) for t in types)


def schema_errors(instance, schema, root, path="$rec") -> list[str]:
    errors = []
    if "$ref" in schema:
        ref = schema["$ref"]
        if not ref.startswith("#/"):
            return [f"{path}: unsupported $ref {ref}"]
        target = root
        for part in ref[2:].split("/"):
            target = target[part]
        return schema_errors(instance, target, root, path)

    if "anyOf" in schema:
        sub = [schema_errors(instance, s, root, path) for s in schema["anyOf"]]
        if not any(not e for e in sub):
            errors.append(f"{path}: value matches none of anyOf branches")
        return errors

    if "type" in schema and not _type_ok(instance, schema["type"]):
        errors.append(f"{path}: expected type {schema['type']}, got {type(instance).__name__}")
        return errors  # further keyword checks would be meaningless

    if "const" in schema and instance != schema["const"]:
        errors.append(f"{path}: expected const {schema['const']!r}, got {instance!r}")
    if "enum" in schema and instance not in schema["enum"]:
        errors.append(f"{path}: value {instance!r} not in enum")
    if "pattern" in schema and isinstance(instance, str):
        if not re.search(schema["pattern"], instance):
            errors.append(f"{path}: {instance!r} does not match pattern {schema['pattern']}")
    if isinstance(instance, (int, float)) and not isinstance(instance, bool):
        if "minimum" in schema and instance < schema["minimum"]:
            errors.append(f"{path}: {instance} < minimum {schema['minimum']}")
        if "exclusiveMinimum" in schema and instance <= schema["exclusiveMinimum"]:
            errors.append(f"{path}: {instance} <= exclusiveMinimum {schema['exclusiveMinimum']}")

    if isinstance(instance, dict):
        for key in schema.get("required", []):
            if key not in instance:
                errors.append(f"{path}: missing required key {key}")
        props = schema.get("properties", {})
        for key, value in instance.items():
            if key in props:
                errors.extend(schema_errors(value, props[key], root, f"{path}.{key}"))
            elif schema.get("additionalProperties") is False:
                errors.append(f"{path}: unexpected key {key}")
            elif isinstance(schema.get("additionalProperties"), dict):
                errors.extend(schema_errors(value, schema["additionalProperties"], root,
                                            f"{path}.{key}"))

    if isinstance(instance, list):
        item_schema = schema.get("items")
        if item_schema:
            for i, value in enumerate(instance):
                errors.extend(schema_errors(value, item_schema, root, f"{path}[{i}]"))
        if "minItems" in schema and len(instance) < schema["minItems"]:
            errors.append(f"{path}: fewer than {schema['minItems']} items")
    return errors


# --------------------------------------------------------------------------- #
# helpers
# --------------------------------------------------------------------------- #
def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as fh:
        for chunk in iter(lambda: fh.read(1024 * 1024), b""):
            h.update(chunk)
    return h.hexdigest()


def md(name: str) -> str:
    """Escape a value for inclusion in a Markdown table cell."""
    return str(name).replace("|", "\\|").replace("\n", " ")


class Report:
    def __init__(self):
        self.checks: list[dict] = []

    def add(self, cid, description, errors=(), warnings=(), infos=(), ok_detail=""):
        self.checks.append({
            "id": cid,
            "description": description,
            "errors": [str(e) for e in errors],
            "warnings": [str(w) for w in warnings],
            "infos": [str(i) for i in infos],
            "ok_detail": ok_detail,
        })

    @property
    def n_errors(self):
        return sum(len(c["errors"]) for c in self.checks)

    @property
    def n_warnings(self):
        return sum(len(c["warnings"]) for c in self.checks)

    def status(self, check):
        if check["errors"]:
            return "FAIL"
        if check["warnings"]:
            return "WARN"
        return "PASS"


# --------------------------------------------------------------------------- #
# validation
# --------------------------------------------------------------------------- #
def validate(root: Path) -> tuple[Report, dict]:
    rep = Report()
    facts: dict = {}

    # ---- required files -----------------------------------------------------
    required = [
        "data/originals", "annotations/labels.jsonl", "annotations/annotation_schema.json",
        "metadata/manifest.csv", "metadata/checksums.sha256", "metadata/source_tasks.json",
        "metadata/identity_flags.json", "metadata/source_exports/batch1_annotations.xml",
        "metadata/source_exports/batch2_annotations.xml",
    ]
    missing = [p for p in required if not (root / p).exists()]
    rep.add("files.present", "All required dataset files are present", missing,
            ok_detail=f"{len(required)} required paths checked")
    if missing:
        return rep, facts

    # ---- load ---------------------------------------------------------------
    schema = json.loads((root / "annotations/annotation_schema.json").read_text(encoding="utf-8"))
    records = []
    parse_errors = []
    for lineno, line in enumerate((root / "annotations/labels.jsonl").read_text(
            encoding="utf-8").splitlines(), 1):
        if not line.strip():
            continue
        try:
            records.append(json.loads(line))
        except json.JSONDecodeError as exc:
            parse_errors.append(f"labels.jsonl line {lineno}: {exc}")
    rep.add("labels.parse", "labels.jsonl contains valid JSON on every line", parse_errors,
            ok_detail=f"{len(records)} records parsed")

    with (root / "metadata/manifest.csv").open(newline="", encoding="utf-8") as fh:
        manifest = list(csv.DictReader(fh))
    manifest_by_id = {m["image_id"]: m for m in manifest}

    checksum_lines = [l.split() for l in (root / "metadata/checksums.sha256").read_text(
        encoding="utf-8").splitlines() if l.strip() and not l.startswith("#")]
    checksums = {parts[1]: parts[0] for parts in checksum_lines if len(parts) == 2}

    flags = json.loads((root / "metadata/identity_flags.json").read_text(encoding="utf-8"))
    near_path = root / "metadata/near_duplicates.csv"
    near = list(csv.DictReader(near_path.open(newline="", encoding="utf-8"))) if near_path.exists() else []

    facts.update(records=records, manifest=manifest, schema=schema, flags=flags, near=near)

    # ---- schema -------------------------------------------------------------
    schema_errs = []
    for rec in records:
        schema_errs.extend(f"{rec.get('annotation_id', '?')}: {e}"
                           for e in schema_errors(rec, schema, schema))
    rep.add("schema.conformance", "Every record validates against annotation_schema.json",
            schema_errs, ok_detail=f"{len(records)} records checked")

    # ---- identifier uniqueness ---------------------------------------------
    ann_ids = [r.get("annotation_id") for r in records]
    dup_ann = [k for k, v in Counter(ann_ids).items() if v > 1]
    rep.add("ids.annotation_unique", "annotation_id is unique", dup_ann,
            ok_detail=f"{len(ann_ids)} annotation ids")

    image_ids = [m["image_id"] for m in manifest]
    dup_img = [k for k, v in Counter(image_ids).items() if v > 1]
    rep.add("ids.image_unique", "image_id is unique in manifest", dup_img,
            ok_detail=f"{len(image_ids)} image ids")

    view_ids = [r["view_id"] for r in records if r.get("view_id")]
    dup_view = [k for k, v in Counter(view_ids).items() if v > 1]
    rep.add("ids.view_unique", "view_id is unique across the dataset", dup_view,
            ok_detail=f"{len(view_ids)} generated view ids")

    stored_names = [m["stored_filename"] for m in manifest]
    dup_stored = [k for k, v in Counter(stored_names).items() if v > 1]
    rep.add("ids.stored_filename_unique", "Stored image filenames do not collide", dup_stored,
            ok_detail=f"{len(stored_names)} stored filenames")

    # ---- image references / existence --------------------------------------
    ref_errors = []
    for r in records:
        iid = r.get("image_id")
        if iid not in manifest_by_id:
            ref_errors.append(f"{r.get('annotation_id')}: image_id {iid} absent from manifest")
            continue
        m = manifest_by_id[iid]
        if r.get("image_path") != m["image_path"]:
            ref_errors.append(f"{r.get('annotation_id')}: image_path disagrees with manifest")
        if r.get("image_sha256") != m["sha256"]:
            ref_errors.append(f"{r.get('annotation_id')}: image_sha256 disagrees with manifest")
        if (r.get("image_width"), r.get("image_height")) != (int(m["width"]), int(m["height"])):
            ref_errors.append(f"{r.get('annotation_id')}: image dimensions disagree with manifest")
    rep.add("annotations.reference_images", "Every annotation references a manifest image",
            ref_errors, ok_detail=f"{len(records)} references checked")

    file_errors = []
    for m in manifest:
        p = root / m["image_path"]
        if not p.is_file():
            file_errors.append(f"{m['image_id']}: missing {m['image_path']}")
    rep.add("images.exist", "Every manifest image exists on disk", file_errors,
            ok_detail=f"{len(manifest)} image files")

    hash_errors = []
    for m in manifest:
        p = root / m["image_path"]
        if not p.is_file():
            continue
        got = sha256_file(p)
        if got != m["sha256"]:
            hash_errors.append(f"{m['image_path']}: manifest SHA-256 mismatch")
        if checksums.get(m["image_path"]) != got:
            hash_errors.append(f"{m['image_path']}: checksums.sha256 mismatch")
    rep.add("images.checksums", "SHA-256 hashes in manifest and checksums.sha256 match the files",
            hash_errors, ok_detail=f"{len(manifest)} files hashed")

    extra_checksums = sorted(set(checksums) - {m["image_path"] for m in manifest})
    rep.add("checksums.coverage", "checksums.sha256 covers exactly the manifest images",
            extra_checksums, ok_detail=f"{len(checksums)} checksum lines")

    # ---- bounding boxes -----------------------------------------------------
    bbox_errors = []
    for r in records:
        b, w, h = r.get("bbox", {}), r.get("image_width", 0), r.get("image_height", 0)
        xtl, ytl, xbr, ybr = (b.get(k) for k in ("xtl", "ytl", "xbr", "ybr"))
        if not all(isinstance(v, (int, float)) for v in (xtl, ytl, xbr, ybr)):
            bbox_errors.append(f"{r.get('annotation_id')}: non-numeric bbox")
            continue
        if not (0 <= xtl < xbr <= w and 0 <= ytl < ybr <= h):
            bbox_errors.append(
                f"{r.get('annotation_id')}: bbox ({xtl},{ytl},{xbr},{ybr}) outside {w}x{h}")
        if abs(b.get("width", 0) - (xbr - xtl)) > 0.01 or abs(b.get("height", 0) - (ybr - ytl)) > 0.01:
            bbox_errors.append(f"{r.get('annotation_id')}: bbox width/height inconsistent")
    rep.add("bbox.valid", "All bounding boxes are non-empty and inside their image",
            bbox_errors, ok_detail=f"{len(records)} boxes checked")

    # ---- object ids / view ids ---------------------------------------------
    missing_oid = [r for r in records if not r.get("object_id")]
    rep.add("object_id.present", "Every object annotation has a non-empty object_id",
            [f"{r['annotation_id']} ({r['image_path']}): source object_id is empty" for r in missing_oid],
            ok_detail=f"{len(records) - len(missing_oid)}/{len(records)} have an object_id")

    malformed = [r for r in records if r.get("object_id") and
                 not CANONICAL_OBJECT_ID.match(r["object_id"])]
    rep.add("object_id.canonical", "object_id follows the canonical OBJ_NNN pattern",
            [], [f"{r['annotation_id']}: raw {r['object_id']!r} preserved; "
                 f"possible typo of {r.get('suspected_object_id')}" for r in malformed],
            ok_detail="raw identities are never rewritten")

    missing_view = [r for r in records if r.get("object_id") and not r.get("view_id")]
    rep.add("view_id.present", "Every annotation with an object_id has a view_id",
            [f"{r['annotation_id']}: missing view_id" for r in missing_view],
            ok_detail=f"{len(view_ids)} view ids")

    view_errors = []
    for r in records:
        if not r.get("view_id"):
            continue
        m = VIEW_ID_RE.match(r["view_id"])
        if not m:
            view_errors.append(f"{r['annotation_id']}: malformed view_id {r['view_id']!r}")
            continue
        if m.group(1) != r["object_id"] or int(m.group(2)) != r.get("view_index"):
            view_errors.append(
                f"{r['annotation_id']}: view_id {r['view_id']!r} does not match "
                f"object_id {r['object_id']!r} / view_index {r.get('view_index')}")
    rep.add("view_id.format", "view_id equals {object_id}_view_{zero-padded index}",
            view_errors, ok_detail="prefix and index checked for every view id")

    groups = defaultdict(list)
    for r in records:
        if r.get("object_id"):
            groups[r["object_id"]].append(r)
    seq_errors = []
    for oid, recs in sorted(groups.items()):
        indices = sorted(r["view_index"] for r in recs)
        expected = list(range(1, len(recs) + 1))
        if indices != expected:
            seq_errors.append(f"{oid}: indices {indices} != {expected}")
        n_images = len({r["image_id"] for r in recs})
        n_views = len({r["view_id"] for r in recs})
        if n_views != n_images:
            seq_errors.append(f"{oid}: {n_views} views for {n_images} images")
        if any(r.get("object_view_count") != n_views for r in recs):
            seq_errors.append(f"{oid}: object_view_count mismatch")
    rep.add("views.sequential", "View indices are 1..N and sequential per physical object",
            seq_errors, ok_detail=f"{len(groups)} physical objects checked")

    per_image_object = Counter((r["image_id"], r["object_id"]) for r in records if r.get("object_id"))
    multi = [f"{iid}: {oid} annotated {n} times" for (iid, oid), n in per_image_object.items() if n > 1]
    rep.add("views.one_per_image_per_object", "At most one view per object per image",
            [], [m for m in multi],
            ok_detail="each annotation would get its own view id if an image held several objects")

    # ---- coverage -----------------------------------------------------------
    ann_per_image = Counter(r["image_id"] for r in records)
    unannotated = [m["image_id"] for m in manifest if ann_per_image[m["image_id"]] == 0]
    rep.add("images.all_annotated", "Every merged image has at least one annotation",
            unannotated, ok_detail=f"{len(ann_per_image)}/{len(manifest)} images annotated")

    # ---- lossless merge (compare with the exact source exports) -------------
    source_counts = {}
    loss_errors = []
    merged_by_key = {(r["source_batch"], r["source_image_id"], r["source_box_index"]): r
                     for r in records}
    for batch, fname in (("batch1", "batch1_annotations.xml"), ("batch2", "batch2_annotations.xml")):
        src = ET.parse(root / "metadata/source_exports" / fname).getroot()
        src_images = src.findall("image")
        src_boxes = [(im, bx, box_index) for im in src_images
                     for box_index, bx in enumerate(im.findall("box"))]
        source_counts[batch] = (len(src_images), len(src_boxes))
        merged_images = [m for m in manifest if m["source_batch"] == batch]
        merged_boxes = [r for r in records if r["source_batch"] == batch]
        if len(src_images) != len(merged_images):
            loss_errors.append(f"{batch}: {len(src_images)} source images vs {len(merged_images)} merged")
        if len(src_boxes) != len(merged_boxes):
            loss_errors.append(f"{batch}: {len(src_boxes)} source boxes vs {len(merged_boxes)} merged")
        seen = set()
        for im in src_images:
            found = [m for m in merged_images if int(m["source_image_id"]) == int(im.get("id"))]
            if len(found) != 1:
                loss_errors.append(f"{batch}/{im.get('id')}: image not merged exactly once")
            elif found[0]["original_filename"] != im.get("name"):
                loss_errors.append(f"{batch}/{im.get('id')}: filename changed")
            elif (int(found[0]["width"]), int(found[0]["height"])) != (
                    int(im.get("width")), int(im.get("height"))):
                loss_errors.append(f"{batch}/{im.get('id')}: image dimensions changed")
        for im, bx, box_index in src_boxes:
            key = (batch, int(im.get("id")), box_index)
            seen.add(key)
            rec = merged_by_key.get(key)
            if rec is None:
                loss_errors.append(f"{batch}/{im.get('id')}#{box_index}: annotation lost")
                continue
            expected_attrs = {a.get("name"): (a.text or "") for a in bx.findall("attribute")}
            got_attrs = dict(rec["attributes"])
            got_attrs["object_id"] = rec["object_id_raw"]
            if got_attrs != expected_attrs:
                loss_errors.append(f"{rec['annotation_id']}: attributes changed")
            for attr in ("xtl", "ytl", "xbr", "ybr"):
                if abs(float(bx.get(attr)) - rec["bbox"][attr]) > 0.01:
                    loss_errors.append(f"{rec['annotation_id']}: {attr} changed")
            if rec["label"] != bx.get("label") or rec["occluded"] != int(bx.get("occluded", 0)) \
                    or rec["z_order"] != int(bx.get("z_order", 0)) or rec["source"] != bx.get("source"):
                loss_errors.append(f"{rec['annotation_id']}: label/occluded/z_order/source changed")
        for key in set(merged_by_key) - seen:
            if key[0] == batch:
                loss_errors.append(f"{key}: annotation has no source counterpart")
    rep.add("merge.lossless", "Images, boxes, labels and attributes match both source exports",
            loss_errors, ok_detail=f"batch1 {source_counts.get('batch1')}, batch2 {source_counts.get('batch2')} "
                                   f"(images, boxes)")

    # ---- duplicates / identity inconsistencies -----------------------------
    by_hash = defaultdict(list)
    for m in manifest:
        by_hash[m["sha256"]].append(m["image_path"])
    exact_dups = {h: p for h, p in by_hash.items() if len(p) > 1}
    rep.add("duplicates.exact", "No two stored images are byte-identical",
            [], [f"{h[:12]}: {', '.join(p)}" for h, p in exact_dups.items()],
            ok_detail=f"{len(manifest)} distinct SHA-256 values" if not exact_dups else "")

    collisions = defaultdict(list)
    for m in manifest:
        collisions[m["original_filename"]].append(m["image_id"])
    collided = {n: ids for n, ids in collisions.items() if len(ids) > 1}
    rep.add("duplicates.filename_collisions", "Original filename collisions resolved on disk",
            [], [f"{n}: {', '.join(ids)}" for n, ids in sorted(collided.items())],
            ok_detail=f"{len(collided)} colliding names, all stored under distinct paths")

    rep.add("duplicates.perceptual", "Near-duplicate candidates reviewed",
            [], [f"{n['image_a']} / {n['image_b']}: dHash distance {n['dhash_distance']}"
                 for n in near],
            ok_detail="metadata/near_duplicates.csv lists candidates arising from burst captures")

    suspects = []
    for item in flags.get("missing_object_id", []):
        suspects.append(f"{item['annotation_id']}: empty source object_id; "
                        f"hint {item.get('suspected_object_id')} is NOT applied")
    for item in flags.get("malformed_object_id", []):
        suspects.append(f"{item['annotation_id']}: {item['object_id']} flagged; "
                        f"not merged into {item.get('suspected_object_id')}")
    rep.add("identity.flagged", "Missing/ambiguous identities are flagged, not guessed",
            [], suspects, ok_detail=f"{len(flags.get('missing_object_id', []))} missing, "
                                    f"{len(flags.get('malformed_object_id', []))} malformed")

    excluded = root / "metadata/excluded_unannotated_images.txt"
    n_excluded = sum(1 for l in excluded.read_text(encoding="utf-8").splitlines()
                     if l and not l.startswith("#")) if excluded.exists() else 0
    rep.add("scope.excluded_images", "Images outside both CVAT tasks are documented",
            ok_detail=f"{n_excluded} files listed in excluded_unannotated_images.txt")

    facts["source_counts"] = source_counts
    facts["groups"] = groups
    facts["collided"] = collided
    facts["exact_dups"] = exact_dups
    facts["n_excluded"] = n_excluded
    return rep, facts


# --------------------------------------------------------------------------- #
# reporting
# --------------------------------------------------------------------------- #
def write_report(root: Path, rep: Report, facts: dict) -> Path:
    out = root / "quality/qc_report.md"
    out.parent.mkdir(parents=True, exist_ok=True)
    records = facts.get("records", [])
    manifest = facts.get("manifest", [])
    groups = facts.get("groups", {})
    near = facts.get("near", [])
    flags = facts.get("flags", {})
    collided = facts.get("collided", {})
    now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")

    lines = [
        "# Quality control report — unified cross-view dataset",
        "",
        f"Generated: {now}",
        "",
        "## Summary",
        "",
        "| Metric | Value |",
        "| --- | --- |",
        f"| Images in merged dataset | {len(manifest)} |",
        f"| Annotations | {len(records)} |",
        f"| Physical objects (distinct source object_id values, excluding empty) | {len(groups)} |",
        f"| Generated view ids | {sum(1 for r in records if r.get('view_id'))} |",
        f"| Unresolved annotations (empty source object_id) | {len(flags.get('missing_object_id', []))} |",
        f"| Malformed object ids (identity preserved) | {len(flags.get('malformed_object_id', []))} |",
        f"| Filename collisions resolved | {len(collided)} |",
        f"| Exact duplicate images | {len(facts.get('exact_dups', {}))} |",
        f"| Near-duplicate candidates | {len(near)} |",
        f"| Unannotated images documented as out of scope | {facts.get('n_excluded', 0)} |",
        f"| **Errors** | **{rep.n_errors}** |",
        f"| **Warnings** | **{rep.n_warnings}** |",
        "",
        "Verdict: " + ("PASS" if rep.n_errors == 0 else
                       "PASS WITH UNRESOLVED SOURCE IDENTITY ISSUES — human input required"),
        "",
        "## Checks",
        "",
        "| Check | Result | Details |",
        "| --- | --- | --- |",
    ]
    for c in rep.checks:
        details = c["ok_detail"]
        for e in c["errors"]:
            details += ("; " if details else "") + f"ERROR: {md(e)}"
        for w in c["warnings"]:
            details += ("; " if details else "") + f"WARNING: {md(w)}"
        lines.append(f"| `{c['id']}` | {rep.status(c)} | {md(details)} |")

    lines += [
        "",
        "## Merge reconciliation",
        "",
        "| Source task | Source images | Merged images | Source boxes | Merged annotations |",
        "| --- | --- | --- | --- | --- |",
    ]
    for batch in ("batch1", "batch2"):
        si, sb = facts.get("source_counts", {}).get(batch, ("?", "?"))
        mi = sum(1 for m in manifest if m["source_batch"] == batch)
        ma = sum(1 for r in records if r["source_batch"] == batch)
        lines.append(f"| {batch} | {si} | {mi} | {sb} | {ma} |")

    lines += ["", "## Identity issues (not auto-corrected)", ""]
    if flags.get("missing_object_id"):
        lines += ["### Empty source `object_id`", "",
                  "These boxes are retained verbatim with `object_id: null`, `view_id: null` and "
                  "`status: unresolved_missing_object_id`. The hints below are derived from "
                  "adjacent frames only and were **not** applied.", "",
                  "| Annotation | Image | Source id | Non-authoritative hint |",
                  "| --- | --- | --- | --- |"]
        for x in flags["missing_object_id"]:
            lines.append(f"| {x['annotation_id']} | {md(x['image_path'])} | "
                         f"{x['source_batch']}/{x['source_image_id']} | "
                         f"{x.get('suspected_object_id') or 'n/a'} |")
        lines.append("")
    if flags.get("malformed_object_id"):
        lines += ["### Non-canonical `object_id`", "",
                  "The raw value is preserved as a separate physical object; it is **not** "
                  "silently merged into the suspected object.", "",
                  "| Annotation | Raw object_id | Suspected | Status |",
                  "| --- | --- | --- | --- |"]
        for x in flags["malformed_object_id"]:
            lines.append(f"| {x['annotation_id']} | {md(x['object_id'])} | "
                         f"{x.get('suspected_object_id') or 'n/a'} | review |")
        lines.append("")

    lines += ["## Duplicate / collision review", ""]
    if collided:
        lines += ["### Filename collisions", "",
                  "Both exports contain images with identical original filenames. They are "
                  "different photos (different devices, dimensions and annotated object "
                  "identities), so both were kept. Every colliding copy was stored with a "
                  "`__batch1` / `__batch2` suffix; `manifest.csv` keeps the original name.", "",
                  "| Original filename | Merged image ids |", "| --- | --- |"]
        for n, ids in sorted(collided.items()):
            lines.append(f"| {md(n)} | {', '.join(ids)} |")
        lines.append("")
    if near:
        lines += ["### Near-duplicate candidates", "",
                  "Detected with a 64-bit difference hash (Hamming distance <= 8) over "
                  "EXIF-oriented thumbnails. These are burst captures with different "
                  "bounding boxes and viewpoint labels; they were retained.", "",
                  "| Image A | Image B | dHash distance | Objects |", "| --- | --- | --- | --- |"]
        for n in near:
            lines.append(f"| {n['image_a']} | {n['image_b']} | {n['dhash_distance']} | "
                         f"{md(n['object_a'])} / {md(n['object_b'])} |")
        lines.append("")
    if not facts.get("exact_dups"):
        lines += ["No byte-identical duplicate images were found.", ""]

    lines += ["## Views per object", "",
              "| Object | Views | Annotations | View ids |", "| --- | ---: | ---: | --- |"]
    for oid in sorted(groups):
        recs = groups[oid]
        vids = sorted({r["view_id"] for r in recs if r["view_id"]})
        lines.append(f"| {md(oid)} | {len(vids)} | {len(recs)} | {md(' '.join(vids))} |")
    lines += ["", f"Unassigned annotations (no object_id): "
                  f"{sum(1 for r in records if not r.get('object_id'))}.", "",
              "## Reproducing this report", "",
              "```bash", "python3 scripts/validate.py", "```", "",
              "Exit code is 1 while any error remains (currently the empty source "
              "`object_id` cases). Fixing those boxes in CVAT and rebuilding will clear "
              "the errors without touching any other annotation.", ""]

    out.write_text("\n".join(lines), encoding="utf-8")
    return out


# --------------------------------------------------------------------------- #
def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--dataset-root", type=Path, default=Path(__file__).resolve().parent.parent)
    ap.add_argument("--no-report", action="store_true")
    ap.add_argument("--json", action="store_true", dest="as_json")
    args = ap.parse_args()
    root = args.dataset_root.resolve()

    rep, facts = validate(root)

    if not args.as_json:
        for c in rep.checks:
            print(f"[{rep.status(c):4}] {c['id']}: {c['description']}")
            for e in c["errors"]:
                print(f"         ERROR: {e}")
            for w in c["warnings"][:8]:
                print(f"         WARN:  {w}")
            if len(c["warnings"]) > 8:
                print(f"         ... {len(c['warnings']) - 8} more warnings")
        print()
        print(f"images={len(facts.get('manifest', []))} "
              f"annotations={len(facts.get('records', []))} "
              f"objects={len(facts.get('groups', {}))} "
              f"errors={rep.n_errors} warnings={rep.n_warnings}")

    if not args.no_report:
        path = write_report(root, rep, facts)
        if not args.as_json:
            print(f"report: {path}")

    if args.as_json:
        print(json.dumps({
            "images": len(facts.get("manifest", [])),
            "annotations": len(facts.get("records", [])),
            "objects": len(facts.get("groups", {})),
            "errors": rep.n_errors,
            "warnings": rep.n_warnings,
            "checks": rep.checks,
        }, indent=2))

    return 1 if rep.n_errors else 0


if __name__ == "__main__":
    raise SystemExit(main())