File size: 7,472 Bytes
823e8e6
2f43fe3
 
 
 
e9b4ca5
2f43fe3
e9b4ca5
2f43fe3
 
 
 
 
 
 
e9b4ca5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f43fe3
e9b4ca5
823e8e6
 
e9b4ca5
 
 
 
 
 
 
 
 
 
 
823e8e6
e9b4ca5
 
 
 
 
 
823e8e6
e9b4ca5
 
823e8e6
e9b4ca5
2f43fe3
e9b4ca5
2f43fe3
823e8e6
2f43fe3
e9b4ca5
2f43fe3
 
e9b4ca5
 
 
 
 
 
 
 
 
 
823e8e6
 
 
 
e9b4ca5
 
 
 
 
 
 
823e8e6
 
2f43fe3
 
 
e9b4ca5
 
 
 
 
 
 
 
 
 
 
 
 
2f43fe3
823e8e6
e9b4ca5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f43fe3
 
 
 
 
 
e9b4ca5
 
 
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
"""Verify the dataset release without extracting images or writing temporary files."""

import argparse
import hashlib
import json
import multiprocessing
import tarfile
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path, PurePosixPath


def rows(path):
    return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]


def digest(path):
    value = hashlib.sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(4 * 1024 * 1024), b""):
            value.update(block)
    return value.hexdigest()


def check_archive(task):
    root, archive, expected, full = task
    path = root / archive["path"]
    assert path.stat().st_size == archive["bytes"]
    if full:
        assert digest(path) == archive["sha256"]
    with tarfile.open(path) as stream:
        member = stream.next()
        assert member.name == expected["path"] and member.isfile()
        assert not (member.uid or member.gid or member.mtime or member.uname or member.gname)
        content = stream.extractfile(member).read()
        assert hashlib.sha256(content).hexdigest() == expected["sha256"]
        assert len(content) == expected["bytes"] and content[:8] == b"\x89PNG\r\n\x1a\n"
    return archive["path"]


def verify(root, full=False, checksums=True, workers=2):
    assert 1 <= workers <= 16
    summary = json.loads((root / "dataset.json").read_text())
    assert summary["complete"] and summary["layout_version"] == 2
    allowed_roots = set(summary["datasets"])
    assert all((root / name).is_dir() for name in allowed_roots)
    if checksums:
        for line in (root / "SHA256SUMS").read_text().splitlines():
            expected, relative = line.split("  ", 1)
            path = PurePosixPath(relative)
            assert not path.is_absolute() and ".." not in path.parts
            if path.suffix != ".tar":
                assert digest(root / relative) == expected
    catalog_rows = rows(root / "files.jsonl")
    files = {r["path"]: r for r in catalog_rows}
    assert len(files) == len(catalog_rows) == summary["unique_images"]
    referenced, groups, scenes, counts = set(), {}, {}, {}
    gopro_groups = {}
    manifests = [
        (f"rawmoment_data/{split}/{stage}.jsonl", split, stage)
        for split in ("train", "val") for stage in ("stage1", "stage2")
    ] + [("rawmoment_data/test/manifest.jsonl", "test", "test")]
    manifests += [(f"realblur_processed_data/{split}/manifest.jsonl", split, "realblur")
                  for split in ("train", "test")]
    manifests += [(f"gopro_processed_data/{split}/manifest.jsonl", split, "gopro") for split in ("train", "test")]
    for name, split, kind in manifests:
        records = rows(root / name)
        assert len({r.get("record_id", r["sample_id"]) for r in records}) == len(records)
        parent = PurePosixPath(name).parent
        for row in records:
            assert row["split"] == split
            for relative in row["files"].values():
                path = PurePosixPath(relative["path"] if isinstance(relative, dict) else relative)
                assert not path.is_absolute() and ".." not in path.parts
                public_path = (parent / path).as_posix()
                assert public_path in files
                referenced.add(public_path)
            if kind == "realblur":
                scenes.setdefault(split, set()).add(row["scene"])
                assert row["official_split"] == split
                assert (row["black_level"], row["white_level"]) == (512, 16383)
                assert row["bin_factor"] == 4 and row["noise_scale"] == 1 / 16
                height, width = row["size_hw"]
                y, x, h, w = row["eval_crop_yxhw"]
                assert h == w == 512 and y >= 0 and x >= 0
                assert y + h <= height and x + w <= width and y % 16 == x % 16 == 0
                assert [y, x] in row["valid_crop_origins_512"]
            elif kind == "gopro":
                gopro_groups.setdefault(split, set()).add(row["group"])
                assert set(row["files"]) == {"RAW", "RGB", "BLUR_RGB"}
                assert (row["height"], row["width"]) == (512, 512)
            else:
                groups.setdefault(split, set()).add(row["group"])
                if kind == "stage1":
                    assert set(row["files"]) == {"BLUR_RAW", "BLUR_RGB", "CLEAN_RAW", "CLEAN_RGB"}
                elif kind == "stage2":
                    assert set(row["files"]) == {"RAW", "RGB"}
        counts[name] = len(records)
    assert not gopro_groups["train"] & gopro_groups["test"]
    assert {k: len(v) for k, v in gopro_groups.items()} == {"train":22,"test":11}
    assert referenced == set(files)
    assert not groups["train"] & groups["val"]
    assert not (groups["train"] | groups["val"]) & groups["test"]
    assert not scenes["train"] & scenes["test"]
    datasets = summary["datasets"]
    assert {k: len(v) for k, v in scenes.items()} == datasets["realblur_processed_data"]["scene_counts"]
    raw_counts = datasets["rawmoment_data"]["records"]
    real_counts = datasets["realblur_processed_data"]["records"]
    expected_counts = {
        "rawmoment_data/train/stage1.jsonl": raw_counts["train"],
        "rawmoment_data/train/stage2.jsonl": raw_counts["train"],
        "rawmoment_data/val/stage1.jsonl": raw_counts["val"],
        "rawmoment_data/val/stage2.jsonl": raw_counts["val"],
        "rawmoment_data/test/manifest.jsonl": raw_counts["test"],
        "realblur_processed_data/train/manifest.jsonl": real_counts["train"],
        "realblur_processed_data/test/manifest.jsonl": real_counts["test"],
    }
    expected_counts.update({f"gopro_processed_data/{s}/manifest.jsonl":n for s,n in summary["datasets"]["gopro_processed_data"]["records"].items()})
    assert counts == expected_counts
    archives = json.loads((root / "archives.json").read_text())
    assert len(archives) == summary["archives"]
    assert sum(a["bytes"] for a in archives) == summary["archive_bytes"]
    assert sum(f["bytes"] for f in files.values()) == summary["image_bytes"]
    assert {f["archive"] for f in files.values()} == {a["path"] for a in archives}
    first_images = {}
    for row in catalog_rows:
        first_images.setdefault(row["archive"], row)
    tasks = [(root, archive, first_images[archive["path"]], full) for archive in archives]
    if full and workers > 1:
        with ProcessPoolExecutor(max_workers=workers, mp_context=multiprocessing.get_context("spawn")) as pool:
            verified = list(pool.map(check_archive, tasks))
    else:
        verified = [check_archive(task) for task in tasks]
    assert len(verified) == len(archives)
    return {"passed": True, "layout_version": 2, "archives": len(archives),
            "full_archive_hashes": full, "sampled_images": len(archives),
            "verification_workers": workers if full else 1,
            "unique_images": len(files), "referenced_images": len(referenced),
            "records": counts, "rawmoment_video_group_overlap": 0, "realblur_scene_overlap": 0}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parent)
    parser.add_argument("--full", action="store_true")
    parser.add_argument("--workers", type=int, default=2)
    options = parser.parse_args()
    print(json.dumps(verify(options.root, options.full, workers=options.workers), indent=2))