File size: 29,884 Bytes
b0d869f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Lossless part/whole annotation conversion, validation and loading.

Category IDs are namespaced by dataset. Pascal labels remain numeric because
its supplied archive does not contain an authoritative class-name mapping.
PACO-LVIS object/part instances keep their explicit obj_ann_id links.
"""
import argparse
from collections import Counter, defaultdict
import json
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageOps
from pycocotools import mask as coco_mask
from tqdm import tqdm

ROOT = Path(__file__).resolve().parents[1]
VERSION = '1.0'
DATASET_SPLITS = {'PartImageNet': ('train', 'val', 'test'), 'Pascal-Part': ('train', 'val'),
                  'PACO-LVIS': ('train', 'val', 'test')}
PACO_ATTRIBUTE_FIELDS = ('attribute_ids', 'dom_color_ids', 'unknown_color', 'unknown_pattern_marking',
                         'unknown_material', 'unknown_transparency')


def encode_mask(mask):
    encoded = coco_mask.encode(np.asfortranarray(mask, dtype=np.uint8))
    return {'size': encoded['size'], 'counts': encoded['counts'].decode('ascii')}


def decode_mask(rle):
    return coco_mask.decode({'size': rle['size'], 'counts': rle['counts'].encode('ascii')}).astype(bool)


def project_path(root, relative):
    path = (root / relative).resolve()
    if not path.is_relative_to(root.resolve()):
        raise ValueError(f'Path outside dataset root: {relative}')
    return path


def node(node_id, parent, category, mask, source_label, provenance):
    return {'id': node_id, 'parent_id': parent, 'level': 0 if parent is None else 1,
            'kind': 'whole' if parent is None else 'part', 'category': category,
            'source_label_id': source_label, 'provenance': provenance,
            'area': int(mask.sum()), 'mask': encode_mask(mask)}


def source_mask(coco, ann):
    segmentation = ann['segmentation']
    if isinstance(segmentation, list):
        valid = [polygon for polygon in segmentation if len(polygon) >= 6 and len(polygon) % 2 == 0]
        if len(valid) != len(segmentation) or not valid:
            im = coco.imgs[ann['image_id']]
            mask = np.zeros((im['height'], im['width']), dtype=bool)
            if valid:
                mask = coco.annToMask(dict(ann, segmentation=valid)).astype(bool)
            return mask, 'partial_invalid_source_geometry' if valid else 'invalid_source_geometry'
    return coco.annToMask(ann).astype(bool), 'valid'


def partimagenet_records(root, split):
    from pycocotools.coco import COCO
    source = root / 'datasets/PartImageNet/annotations' / (split + '.json')
    coco = COCO(str(source))
    for im in sorted(coco.imgs.values(), key=lambda item: item['id']):
        filename = im['file_name']
        image = root / 'datasets/PartImageNet/images' / split / filename[:9] / filename
        groups = defaultdict(list)
        nodes = []
        for ann in sorted(coco.imgToAnns.get(im['id'], []), key=lambda item: item['id']):
            category = coco.cats[ann['category_id']]
            parent = 'whole:' + category['supercategory']
            mask, mask_status = source_mask(coco, ann)
            groups[category['supercategory']].append(mask)
            entry = node('part:' + str(ann['id']), parent,
                         'PartImageNet/part/' + category['name'], mask,
                         ann['category_id'], 'source_coco_annotation')
            entry['source_annotation_id'] = ann['id']
            entry['source_segmentation'] = ann['segmentation']
            entry['mask_status'] = mask_status
            nodes.append(entry)
        for category, masks in sorted(groups.items()):
            nodes.insert(0, node('whole:' + category, None,
                         'PartImageNet/whole/' + category, np.logical_or.reduce(masks),
                         category, 'union_of_source_parts_same_supercategory'))
        yield {'schema_version': VERSION, 'dataset': 'PartImageNet', 'split': split,
               'image_id': str(im['id']), 'image_path': image.relative_to(root).as_posix(),
               'image_available': image.is_file(), 'width': im['width'], 'height': im['height'],
               'source_path': source.relative_to(root).as_posix(),
               'hierarchy_semantics': 'semantic_groups_not_instance_ids', 'nodes': nodes}


def pascal_records(root, split):
    base = root / 'datasets/Pascal-Part'
    images = {p.stem: p for p in (base / 'JPEGImages' / split).iterdir() if p.is_file()}
    for part_path in sorted((base / 'annotations' / split).glob('*.png')):
        whole_path = base / 'annotations' / (split + '_whole') / part_path.name
        with Image.open(part_path) as image:
            parts = np.array(image)
        with Image.open(whole_path) as image:
            wholes = np.array(image)
        if parts.ndim != 2 or parts.shape != wholes.shape:
            raise ValueError(f'Expected paired integer label maps: {part_path}')
        height, width = parts.shape
        metadata_path = part_path.with_suffix('.json')
        if metadata_path.is_file():
            metadata = json.loads(metadata_path.read_text(encoding='utf-8'))
            if (metadata['imgHeight'], metadata['imgWidth']) != parts.shape:
                raise ValueError(f'Metadata dimensions differ: {metadata_path}')
        nodes = []
        # Keep every source value, including background/void values. Intersections
        # preserve the entire part raster without inventing an instance identity.
        for label in np.unique(wholes):
            label = int(label)
            mask = wholes == label
            parent = 'whole:' + str(label)
            nodes.append(node(parent, None, f'Pascal-Part/whole/source_label_{label}',
                              mask, label, 'source_whole_label_map'))
            for part in np.unique(parts[mask]):
                part = int(part)
                nodes.append(node(f'part:{part}:whole:{label}', parent,
                                  f'Pascal-Part/part/source_label_{part}',
                                  mask & (parts == part), part, 'source_part_whole_intersection'))
        image = images[part_path.stem]
        yield {'schema_version': VERSION, 'dataset': 'Pascal-Part', 'split': split,
               'image_id': part_path.stem, 'image_path': image.relative_to(root).as_posix(),
               'image_available': True, 'width': width, 'height': height,
               'source_path': part_path.relative_to(root).as_posix(),
               'source_whole_path': whole_path.relative_to(root).as_posix(),
               'hierarchy_semantics': 'semantic_label_intersections_all_source_values',
               'nodes': nodes}


def paco_source_path(root, split):
    return root / 'datasets/PACO-LVIS/annotations' / f'paco_lvis_v1_{split}.json'


def paco_part_mask(ann, height, width):
    """PACO part masks are compressed RLE strings; return them unchanged plus the decoded raster."""
    segmentation = ann['segmentation']
    if not isinstance(segmentation, dict) or not isinstance(segmentation.get('counts'), str):
        raise ValueError(f'PACO part {ann["id"]} is not a compressed RLE string')
    if list(segmentation['size']) != [height, width]:
        raise ValueError(f'PACO part {ann["id"]} RLE size differs from its image')
    return {'size': [height, width], 'counts': segmentation['counts']}, decode_mask(segmentation)


def paco_records(root, split):
    """One record per PACO-LVIS image: LVIS object instances (level 0) and their part instances (level 1).

    Parents come only from the source obj_ann_id link, never from mask overlap. Part RLE is
    copied verbatim. Pixels of a part outside its object mask are kept and counted.
    """
    from pycocotools.coco import COCO
    source = paco_source_path(root, split)
    coco = COCO(str(source))
    for im in sorted(coco.imgs.values(), key=lambda item: item['id']):
        image = root / 'datasets/COCO' / im['file_name']
        objects, parts = [], []
        for ann in sorted(coco.imgToAnns.get(im['id'], []), key=lambda item: item['id']):
            (objects if coco.cats[ann['category_id']]['supercategory'] == 'OBJECT' else parts).append(ann)
        nodes, object_masks = [], {}
        for ann in objects:
            if ann['obj_ann_id'] != ann['id']:
                raise ValueError(f'PACO object {ann["id"]} does not link to itself')
            mask, mask_status = source_mask(coco, ann)
            object_masks[ann['id']] = mask
            entry = node('object:' + str(ann['id']), None,
                         'PACO-LVIS/whole/' + coco.cats[ann['category_id']]['name'], mask,
                         ann['category_id'], 'source_lvis_object_annotation')
            entry.update({'source_annotation_id': ann['id'], 'source_segmentation': ann['segmentation'],
                          'source_area': ann['area'], 'source_bbox': ann['bbox'], 'mask_status': mask_status,
                          'source_attributes': {key: ann[key] for key in PACO_ATTRIBUTE_FIELDS}})
            nodes.append(entry)
        for ann in parts:
            parent = coco.anns.get(ann['obj_ann_id'])
            if parent is None or parent['image_id'] != im['id'] or ann['obj_ann_id'] not in object_masks:
                raise ValueError(f'PACO part {ann["id"]} has no object parent in image {im["id"]}')
            rle, mask = paco_part_mask(ann, im['height'], im['width'])
            nodes.append({'id': 'part:' + str(ann['id']), 'parent_id': 'object:' + str(ann['obj_ann_id']),
                          'level': 1, 'kind': 'part',
                          'category': 'PACO-LVIS/part/' + coco.cats[ann['category_id']]['name'],
                          'source_label_id': ann['category_id'], 'provenance': 'source_paco_part_obj_ann_id',
                          'area': int(mask.sum()), 'mask': rle, 'mask_status': 'valid',
                          'source_annotation_id': ann['id'], 'source_area': ann['area'],
                          'source_bbox': ann['bbox'], 'source_iscrowd': ann['iscrowd'],
                          'outside_parent_area': int((mask & ~object_masks[ann['obj_ann_id']]).sum()),
                          'source_attributes': {key: ann[key] for key in PACO_ATTRIBUTE_FIELDS}})
        yield {'schema_version': VERSION, 'dataset': 'PACO-LVIS', 'split': split,
               'image_id': str(im['id']), 'image_path': image.relative_to(root).as_posix(),
               'image_available': image.is_file(), 'width': im['width'], 'height': im['height'],
               'source_path': source.relative_to(root).as_posix(),
               'hierarchy_semantics': 'instance_object_part_links_from_source_obj_ann_id',
               'source_image_metadata': {key: value for key, value in im.items()
                                         if key not in ('id', 'width', 'height')},
               'nodes': nodes}


def paco_label_metadata(root):
    """Category, part and attribute tables are identical across PACO-LVIS splits; keep one verified copy.

    joint_obj_attribute_categories exists only in val/test and must agree there. The test-only
    instance-retrieval `queries` stay in the source JSON; they are not part-whole annotations.
    """
    tables, optional = None, {}
    for split in DATASET_SPLITS['PACO-LVIS']:
        data = json.loads(paco_source_path(root, split).read_text(encoding='utf-8'))
        current = {key: data[key] for key in ('categories', 'part_categories', 'attributes', 'attr_type_to_attr_idxs')}
        for category in current['categories']:
            category.pop('image_count', None), category.pop('instance_count', None)  # split-specific counts
        if tables is not None and tables != current:
            raise ValueError(f'PACO-LVIS label tables differ in split {split}')
        tables = current
        if 'joint_obj_attribute_categories' in data:
            if optional.setdefault('joint_obj_attribute_categories', data['joint_obj_attribute_categories']) \
                    != data['joint_obj_attribute_categories']:
                raise ValueError(f'PACO-LVIS joint object-attribute table differs in split {split}')
    return {**tables, **optional}


RECORD_FACTORIES = {'PartImageNet': partimagenet_records, 'Pascal-Part': pascal_records,
                    'PACO-LVIS': paco_records}


def category_metadata(dataset, entry, names):
    if dataset == 'Pascal-Part':
        return {'kind': entry['kind'], 'source_label_id': entry['source_label_id'],
                'name_status': 'source_numeric_id_only'}
    metadata = {'kind': entry['kind'], 'source_label_id': entry['source_label_id'],
                'name_status': 'source_category_name'}
    if dataset == 'PACO-LVIS':
        source = names[entry['source_label_id']]
        metadata.update({'display_name': source['name'].replace('_', ' '), 'is_background': False,
                         'synset': source['synset'], 'frequency': source['frequency']})
    return metadata


def convert(root, datasets=None):
    """Convert the selected sources. Other sources' JSONL, categories and summary entries are kept."""
    output = root / 'datasets/unified'
    output.mkdir(parents=True, exist_ok=True)
    datasets = list(datasets or ('PartImageNet', 'Pascal-Part'))
    summary_path, categories_path = output / 'conversion_summary.json', output / 'categories.json'
    summary = json.loads(summary_path.read_text(encoding='utf-8')) if summary_path.is_file() else {}
    categories = json.loads(categories_path.read_text(encoding='utf-8')) if categories_path.is_file() else {}
    for dataset in datasets:
        categories[dataset] = {}
        names = {}
        if dataset == 'PACO-LVIS':
            tables = paco_label_metadata(root)
            names = {category['id']: category for category in tables['categories']}
            target = output / dataset / 'label_metadata.json'
            target.parent.mkdir(exist_ok=True)
            target.write_text(json.dumps(tables, indent=2) + '\n', encoding='utf-8')
        for split in DATASET_SPLITS[dataset]:
            factory = RECORD_FACTORIES[dataset]
            target = output / dataset / (split + '.jsonl')
            target.parent.mkdir(exist_ok=True)
            stats = Counter()
            with target.open('w', encoding='utf-8') as stream:
                for record in tqdm(factory(root, split), desc=f'{dataset}/{split}', mininterval=3, ascii=True):
                    stream.write(json.dumps(record, separators=(',', ':')) + '\n')
                    stats['images'] += 1
                    stats['missing_images'] += not record['image_available']
                    for entry in record['nodes']:
                        stats[entry['kind'] + '_nodes'] += 1
                        stats['empty_masks'] += entry['area'] == 0
                        stats['invalid_source_geometry'] += entry.get('mask_status', 'valid') != 'valid'
                        if 'outside_parent_area' in entry:
                            stats['parts_extending_outside_parent'] += entry['outside_parent_area'] > 0
                        categories[dataset][entry['category']] = category_metadata(dataset, entry, names)
            summary[dataset + '/' + split] = dict(stats)
    (output / 'categories.json').write_text(json.dumps(categories, indent=2) + '\n', encoding='utf-8')
    (output / 'conversion_summary.json').write_text(json.dumps(summary, indent=2) + '\n', encoding='utf-8')
    return summary


class UnifiedDataset:
    """Random access JSONL loader, compatible with torch DataLoader (collate_fn=list)."""
    def __init__(self, annotations, root=ROOT):
        self.path = Path(annotations)
        self.root = Path(root).resolve()
        self.offsets = []
        with self.path.open('rb') as stream:
            while True:
                position = stream.tell()
                if not stream.readline():
                    break
                self.offsets.append(position)

    def __len__(self):
        return len(self.offsets)

    def record(self, index):
        with self.path.open('rb') as stream:
            stream.seek(self.offsets[index])
            return json.loads(stream.readline())

    def __getitem__(self, index):
        record = self.record(index)
        with Image.open(project_path(self.root, record['image_path'])) as image:
            image = ImageOps.exif_transpose(image).convert('RGB')
        return {'record': record, 'image': image,
                'masks': {entry['id']: decode_mask(entry['mask']) for entry in record['nodes']
                          if entry.get('mask_status', 'valid') == 'valid'},
                'invalid_node_ids': [entry['id'] for entry in record['nodes']
                                     if entry.get('mask_status', 'valid') != 'valid']}


def validate_record(record, root, check_source=True):
    errors = []
    image_path = project_path(root, record['image_path'])
    if image_path.is_file():
        with Image.open(image_path) as image:
            if ImageOps.exif_transpose(image).size != (record['width'], record['height']):
                errors.append('image_dimension_mismatch')
    else:
        errors.append('missing_image:' + record['image_path'])
    if record['image_available'] and not image_path.is_file():
        # image_available records presence at conversion time; images restored later are fine.
        errors.append('image_availability_flag_mismatch')
    entries = {entry['id']: entry for entry in record['nodes']}
    if len(entries) != len(record['nodes']):
        errors.append('duplicate_node_id')
    masks = {}
    for entry in record['nodes']:
        mask = decode_mask(entry['mask'])
        masks[entry['id']] = mask
        if mask.shape != (record['height'], record['width']):
            errors.append('mask_dimension_mismatch:' + entry['id'])
        if int(mask.sum()) != entry['area']:
            errors.append('mask_area_mismatch:' + entry['id'])
        parent = entry['parent_id']
        if parent is None and (entry['level'] != 0 or entry['kind'] != 'whole'):
            errors.append('invalid_root_node:' + entry['id'])
        if parent is not None and entry['kind'] != 'part':
            errors.append('invalid_child_node:' + entry['id'])
        if parent is not None and (parent not in entries or entries[parent]['level'] + 1 != entry['level']):
            errors.append('invalid_parent_or_level:' + entry['id'])
        seen = {entry['id']}
        while parent in entries:
            if parent in seen:
                errors.append('cycle:' + entry['id'])
                break
            seen.add(parent)
            parent = entries[parent]['parent_id']
    for entry in record['nodes']:
        parent = entry['parent_id']
        if parent in masks and masks[parent].shape == masks[entry['id']].shape:
            outside = int((masks[entry['id']] & ~masks[parent]).sum())
            if 'outside_parent_area' in entry:
                # Independently drawn source masks (PACO): overflow is a counted source property.
                if outside != entry['outside_parent_area']:
                    errors.append('outside_parent_area_mismatch:' + entry['id'])
            elif outside:
                errors.append('part_outside_parent:' + entry['id'])
    if check_source and record['dataset'] == 'Pascal-Part':
        with Image.open(project_path(root, record['source_path'])) as image:
            original_part = np.array(image)
        with Image.open(project_path(root, record['source_whole_path'])) as image:
            original_whole = np.array(image)
        for kind, original in [('part', original_part), ('whole', original_whole)]:
            restored = np.full(original.shape, -1, dtype=np.int32)
            coverage = np.zeros(original.shape, dtype=np.uint8)
            for entry in record['nodes']:
                if entry['kind'] == kind:
                    mask = masks[entry['id']]
                    restored[mask] = entry['source_label_id']
                    coverage += mask
            if not np.array_equal(restored, original) or np.any(coverage != 1):
                errors.append('source_raster_not_lossless:' + kind)
    return errors


def validate_paco_sources(record, source_coco, errors, summary):
    """Every PACO source annotation is present once, with its category, link and geometry unchanged."""
    source_annotations = {ann['id']: ann for ann in source_coco.imgToAnns[int(record['image_id'])]}
    converted = {entry['source_annotation_id']: entry for entry in record['nodes']}
    if set(converted) != set(source_annotations) or len(converted) != len(record['nodes']):
        errors.append('source_annotation_id_coverage_mismatch')
        return
    image = source_coco.imgs[int(record['image_id'])]
    expected_metadata = {key: value for key, value in image.items() if key not in ('id', 'width', 'height')}
    if record.get('source_image_metadata') != expected_metadata:
        errors.append('source_image_metadata_not_preserved')
    for ann_id, entry in converted.items():
        ann = source_annotations[ann_id]
        if entry['source_label_id'] != ann['category_id']:
            errors.append('source_category_id_not_preserved:' + entry['id'])
        if any(entry['source_attributes'][key] != ann[key] for key in PACO_ATTRIBUTE_FIELDS):
            errors.append('source_attributes_not_preserved:' + entry['id'])
        if entry['kind'] == 'whole':
            expected, mask_status = source_mask(source_coco, ann)
            if entry.get('source_segmentation') != ann['segmentation']:
                errors.append('raw_source_geometry_not_preserved:' + entry['id'])
            if mask_status != 'valid':
                summary['source_geometry_issues'].append({'dataset': record['dataset'], 'split': record['split'],
                    'image_id': record['image_id'], 'annotation_id': ann_id, 'status': mask_status})
            if not np.array_equal(decode_mask(entry['mask']), expected):
                errors.append('source_coco_mask_not_lossless:' + entry['id'])
        else:
            if entry['parent_id'] != 'object:' + str(ann['obj_ann_id']):
                errors.append('source_obj_ann_id_not_preserved:' + entry['id'])
            if entry['mask'] != {'size': ann['segmentation']['size'], 'counts': ann['segmentation']['counts']}:
                errors.append('source_rle_not_verbatim:' + entry['id'])


def validate(root, datasets=None):
    """Validate all unified splits, or only the named datasets (report written to a dataset-specific file)."""
    from jsonschema import Draft202012Validator
    schema = json.loads((root / 'datasets/unified/schema.json').read_text(encoding='utf-8-sig'))
    schema_validator = Draft202012Validator(schema)
    summary = {'splits': {}, 'issues': [], 'source_geometry_issues': [], 'duplicate_image_paths_across_splits': []}
    paths = {}
    image_ids = set()
    selected = sorted((root / 'datasets/unified').glob('*/*.jsonl'))
    if datasets:
        selected = [path for path in selected if path.parent.name in datasets]
        summary['datasets'] = sorted(datasets)
    for path in selected:
        dataset = UnifiedDataset(path, root)
        stats = Counter()
        source_coco = None
        for index in tqdm(range(len(dataset)), desc=path.parent.name + '/' + path.stem, mininterval=3, ascii=True):
            record = dataset.record(index)
            errors = [error.message for error in schema_validator.iter_errors(record)]
            errors += validate_record(record, root)
            if record['dataset'] != path.parent.name or record['split'] != path.stem:
                errors.append('split_or_dataset_mismatch')
            image_key = (record['dataset'], record['split'], record['image_id'])
            if image_key in image_ids:
                errors.append('duplicate_image_id')
            image_ids.add(image_key)
            key = (record['dataset'], Path(record['image_path']).name)
            if key in paths:
                summary['duplicate_image_paths_across_splits'].append([paths[key], record['image_path']])
            paths[key] = record['image_path']
            if record['dataset'] == 'PartImageNet':
                if source_coco is None:
                    from pycocotools.coco import COCO
                    source_coco = COCO(str(project_path(root, record['source_path'])))
                source_annotations = {ann['id']: ann for ann in source_coco.imgToAnns[int(record['image_id'])]}
                converted_ids = {entry['source_annotation_id'] for entry in record['nodes'] if entry['kind'] == 'part'}
                if converted_ids != set(source_annotations):
                    errors.append('source_annotation_id_coverage_mismatch')
                for entry in record['nodes']:
                    if entry['kind'] == 'part':
                        ann = source_annotations[entry['source_annotation_id']]
                        expected, mask_status = source_mask(source_coco, ann)
                        if entry['source_label_id'] != ann['category_id']:
                            errors.append('source_category_id_not_preserved:' + entry['id'])
                        if entry.get('source_segmentation') != ann['segmentation']:
                            errors.append('raw_source_geometry_not_preserved:' + entry['id'])
                        if mask_status != 'valid':
                            summary['source_geometry_issues'].append({'split': record['split'], 'image_id': record['image_id'], 'annotation_id': ann['id'], 'status': mask_status})
                        if not np.array_equal(decode_mask(entry['mask']), expected):
                            errors.append('source_coco_mask_not_lossless:' + entry['id'])
            if record['dataset'] == 'PACO-LVIS':
                if source_coco is None:
                    from pycocotools.coco import COCO
                    source_coco = COCO(str(project_path(root, record['source_path'])))
                validate_paco_sources(record, source_coco, errors, summary)
                for entry in record['nodes']:
                    if entry['kind'] == 'part':
                        stats['parts'] += 1
                        stats['parts_extending_outside_parent'] += entry['outside_parent_area'] > 0
                        stats['part_pixels'] += entry['area']
                        stats['part_pixels_outside_parent'] += entry['outside_parent_area']
            stats['images'] += 1
            stats['valid_images'] += not errors
            stats['issues'] += len(errors)
            if errors:
                summary['issues'].append({'dataset': record['dataset'], 'split': record['split'],
                                          'image_id': record['image_id'], 'errors': errors})
        summary['splits'][path.parent.name + '/' + path.stem] = dict(stats)
    summary['conversion_integrity_passed'] = not any(any(not error.startswith('missing_image:') for error in issue['errors']) for issue in summary['issues']) and not summary['duplicate_image_paths_across_splits']
    summary['passed'] = not summary['issues'] and not summary['source_geometry_issues'] and not summary['duplicate_image_paths_across_splits']
    name = 'validation_report.json' if not datasets else 'validation_report_' + '_'.join(sorted(datasets)) + '.json'
    target = root / 'results/preparation' / name
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(json.dumps(summary, indent=2) + '\n', encoding='utf-8')
    return summary


def visualize(root, annotation_path, index, output):
    sample = UnifiedDataset(annotation_path, root)[index]
    image = sample['image']
    record = sample['record']
    panels = [image.copy()]
    colors = [(230, 90, 60), (40, 170, 180), (210, 180, 30), (120, 100, 200), (70, 180, 80)]
    for kind in ('whole', 'part'):
        array = np.array(image).astype(float)
        for position, entry in enumerate(record['nodes']):
            if entry['kind'] == kind:
                mask = sample['masks'].get(entry['id'])
                if mask is None:
                    continue
                array[mask] = 0.45 * array[mask] + 0.55 * np.array(colors[position % len(colors)])
        panels.append(Image.fromarray(array.astype(np.uint8)))
    canvas = Image.new('RGB', (image.width * 3, image.height + 30), 'white')
    draw = ImageDraw.Draw(canvas)
    for position, (panel, title) in enumerate(zip(panels, ('Image', 'Whole groups', 'Part groups'))):
        canvas.paste(panel, (position * image.width, 30))
        draw.text((position * image.width + 8, 8), title, fill='black')
    output.parent.mkdir(parents=True, exist_ok=True)
    canvas.save(output)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('command', choices=['convert', 'validate', 'visualize'])
    parser.add_argument('--root', type=Path, default=ROOT)
    parser.add_argument('--annotations', type=Path)
    parser.add_argument('--index', type=int, default=0)
    parser.add_argument('--output', type=Path)
    parser.add_argument('--datasets', nargs='+', choices=sorted(DATASET_SPLITS),
                        help='convert/validate only these sources (default: PartImageNet and Pascal-Part '
                             'for convert, every unified split for validate)')
    args = parser.parse_args()
    if args.command == 'convert':
        print(json.dumps(convert(args.root.resolve(), args.datasets), indent=2))
    elif args.command == 'validate':
        report = validate(args.root.resolve(), args.datasets)
        print(json.dumps(report, indent=2))
        raise SystemExit(0 if report['passed'] else 1)
    else:
        if args.annotations is None or args.output is None:
            parser.error('visualize requires --annotations and --output')
        visualize(args.root.resolve(), args.annotations, args.index, args.output)


if __name__ == '__main__':
    main()