File size: 4,094 Bytes
07c2d0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Extract the supplied archives without changing their original split layout."""
import argparse
import json
import os
from pathlib import Path, PurePosixPath
import shutil
import tempfile
import zipfile
from tqdm import tqdm

ROOT = Path(__file__).resolve().parents[2]


def extract(archive, target, strip=None):
    count = 0
    for item in tqdm(archive.infolist(), desc=target.name, mininterval=3, ascii=True):
        path = PurePosixPath(item.filename)
        if '__MACOSX' in path.parts or path.name in {'.DS_Store', 'Thumbs.db'} or path.name.startswith('._') or item.is_dir():
            continue
        if path.is_absolute() or '..' in path.parts or '\\' in item.filename:
            raise ValueError(f'Unsafe archive member: {item.filename}')
        parts = path.parts
        if strip and parts[0] == strip:
            parts = parts[1:]
        out = target.joinpath(*parts).resolve()
        if not out.is_relative_to(target.resolve()):
            raise ValueError(f'Archive member escapes destination: {item.filename}')
        if out.exists():
            if out.stat().st_size != item.file_size:
                raise FileExistsError(out)
        else:
            out.parent.mkdir(parents=True, exist_ok=True)
            with archive.open(item) as src, out.open('xb') as dst:
                shutil.copyfileobj(src, dst)
        count += 1
    return count


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root', type=Path, default=ROOT)
    args = parser.parse_args()
    root = args.root.resolve()
    data = root / 'datasets/PartImageNet'
    report = {}
    with zipfile.ZipFile(root / 'datasets/archives/PartImageNet_OOD.zip') as outer:
        (data / 'annotations').mkdir(parents=True, exist_ok=True)
        for split in ('train', 'val', 'test'):
            payload = outer.read(split + '.json')
            (data / 'annotations' / (split + '.json')).write_bytes(payload)
            with tempfile.TemporaryDirectory(prefix='partimagenet-') as tmp:
                nested = Path(tmp) / (split + '.zip')
                with outer.open(split + '.zip') as src, nested.open('wb') as dst:
                    shutil.copyfileobj(src, dst)
                with zipfile.ZipFile(nested) as archive:
                    count = extract(archive, data / 'images' / split, strip=split)
            annotation = json.loads(payload)
            image_root = data / 'images' / split
            missing = [im['file_name'] for im in annotation['images']
                       if not (image_root / im['file_name'][:9] / im['file_name']).is_file()]
            if missing:
                print(f'INCOMPLETE SOURCE ARCHIVE: {split}: {missing}')
            report['PartImageNet/' + split] = {'images': len(annotation['images']),
                'annotations': len(annotation['annotations']), 'extracted_files': count,
                'missing_images': len(missing), 'missing_filenames': missing}
    with zipfile.ZipFile(root / 'datasets/archives/Pascal_Part.zip') as archive:
        extract(archive, root / 'datasets/Pascal-Part', strip='Pascal_Part')
    for split in ('train', 'val'):
        base = root / 'datasets/Pascal-Part'
        parts = sorted((base / 'annotations' / split).glob('*.png'))
        images = {p.stem: p for p in (base / 'JPEGImages' / split).iterdir() if p.is_file()}
        for part in parts:
            if part.stem not in images or not (base / 'annotations' / (split + '_whole') / part.name).is_file():
                raise FileNotFoundError(part)
        report['Pascal-Part/' + split] = {'images': len(images), 'part_masks': len(parts),
            'whole_masks': len(list((base / 'annotations' / (split + '_whole')).glob('*.png')))}
    output = root / 'results/preparation'
    output.mkdir(parents=True, exist_ok=True)
    (output / 'data_inventory.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
    print(json.dumps(report, indent=2))


if __name__ == '__main__':
    main()