File size: 7,025 Bytes
49349fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate a Flickr5k release locally. No credentials, network or ML models needed."""
from __future__ import annotations

import argparse
import csv
import hashlib
import json
import math
import re
from collections import Counter
from pathlib import Path, PurePosixPath

FIELDS = {
    "photo_id":"string", "owner_id":"string", "latitude":"float64", "longitude":"float64",
    "location_source":"string", "flickr_accuracy":"int32", "camera":"string", "capture_date":"string",
    "exif_gps_latitude":"float64", "exif_gps_longitude":"float64", "gps_geotag_distance_m":"float64",
    "license_id":"int32", "license_name":"string", "license_url":"string", "license_status":"string",
    "license_checked_at":"string", "license_review_category":"string",
    "source_url":"string", "review_status":"string", "country":"string", "continent":"string",
    "rights_decision":"string", "rights_note":"string", "width":"int32", "height":"int32", "bytes":"int64", "sha256":"string",
}
FIXED = {"README.md","LICENSE_NOTES.md","RELEASE.json","SHA256SUMS","benchmark.csv","ATTRIBUTION.csv",
         "RIGHTS_REVIEW.csv","RIGHTS_SUMMARY.json","FILTERING.md","REMOVED.csv","score.py",
         ".gitattributes",".gitignore","test/metadata.jsonl","tools/validate_release.py",
         "tools/audit_dataset.py","tools/audit_semantics.py","tools/audit_report.py"}


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


def validate(root,decode_images=False):
    root=Path(root).resolve()
    paths={p.relative_to(root).as_posix():p for p in root.rglob("*") if p.is_file() or p.is_symlink()}
    if not FIXED<=paths.keys():
        raise ValueError("Release is missing required files: "+", ".join(sorted(FIXED-paths.keys())))
    for relative,path in paths.items():
        if path.is_symlink():
            raise ValueError("Symlink is not allowed in release: "+relative)
        if relative not in FIXED and not re.fullmatch(r"test/images/[0-9]+\.jpg",relative):
            raise ValueError("Unexpected/private artifact in release: "+relative)
    checksums={}
    for line in (root/"SHA256SUMS").read_text().splitlines():
        match=re.fullmatch(r"([0-9a-f]{64})  (.+)",line)
        if not match or match[2] in checksums:
            raise ValueError("Invalid or duplicate checksum entry")
        relative=match[2]
        if PurePosixPath(relative).is_absolute() or ".." in PurePosixPath(relative).parts:
            raise ValueError("Unsafe checksum path")
        checksums[relative]=match[1]
    if checksums.keys()!=paths.keys()-{"SHA256SUMS"}:
        raise ValueError("Checksum manifest does not match release files")
    for relative,value in checksums.items():
        if digest(paths[relative])!=value:
            raise ValueError("Checksum mismatch: "+relative)
    rows=[]
    with (root/"test/metadata.jsonl").open(encoding="utf-8") as file:
        for line in file:
            row=json.loads(line)
            if set(row)!={"file_name",*FIELDS}:
                raise ValueError("Unexpected metadata schema")
            for field,dtype in FIELDS.items():
                value=row[field]
                if value is None:
                    if field in {"photo_id","owner_id","latitude","longitude","location_source","width","height","sha256"}:
                        raise ValueError("Required field is null: "+field)
                    continue
                if dtype=="string" and not isinstance(value,str):
                    raise ValueError("Expected string field: "+field)
                if dtype.startswith("int") and (not isinstance(value,int) or isinstance(value,bool)):
                    raise ValueError("Expected integer field: "+field)
                if dtype=="float64" and (not isinstance(value,(int,float)) or isinstance(value,bool) or not math.isfinite(value)):
                    raise ValueError("Invalid numeric field: "+field)
            if not re.fullmatch(r"[0-9]+",row["photo_id"]) or row["file_name"]!=f"images/{row['photo_id']}.jpg":
                raise ValueError("Image filename/ID mismatch")
            if not -90<=row["latitude"]<=90 or not -180<=row["longitude"]<=180:
                raise ValueError("Invalid latitude/longitude")
            if not row["source_url"].startswith("https://www.flickr.com/photos/"):
                raise ValueError("Invalid source photo page")
            relative="test/"+row["file_name"]
            if relative not in paths or checksums[relative]!=row["sha256"] or paths[relative].stat().st_size!=row["bytes"]:
                raise ValueError("Image/metadata mismatch: "+row["photo_id"])
            if min(row["width"],row["height"])<=0 or max(row["width"],row["height"])>1024:
                raise ValueError("Invalid saved image dimensions")
            if decode_images:
                from PIL import Image
                with Image.open(paths[relative]) as image:
                    image.load()
                    if image.format!="JPEG" or image.size!=(row["width"],row["height"]) or image.getexif():
                        raise ValueError("Image decode/format/EXIF check failed: "+relative)
            rows.append(row)
    ids={r["photo_id"] for r in rows}
    if len(ids)!=len(rows) or {"test/"+r["file_name"] for r in rows}!={p for p in paths if p.startswith("test/images/")}:
        raise ValueError("Duplicate metadata ID or unreferenced image")
    release=json.loads((root/"RELEASE.json").read_text())
    if release["packaged_images"]!=len(rows):
        raise ValueError("Release count mismatch")
    if max(Counter(r["owner_id"] for r in rows).values(),default=0)>3:
        raise ValueError("Photographer cap exceeded")
    with (root/"benchmark.csv").open(newline="") as file:
        benchmark=list(csv.DictReader(file))
    if len(benchmark)!=len(rows) or {r["IMG_ID"] for r in benchmark}!={r["photo_id"]+".jpg" for r in rows}:
        raise ValueError("Benchmark CSV mismatch")
    for relative,path in paths.items():
        if relative.endswith((".jsonl",".json",".md",".csv",".py")):
            text=path.read_text(encoding="utf-8")
            if re.search(r"hf_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----",text):
                raise ValueError("Credential-like content in release: "+relative)
    return dict(images=len(rows),files=len(paths),labels=dict(Counter(r["location_source"] for r in rows)),
                license_status=dict(Counter(r["license_status"] for r in rows)))


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("release",type=Path,nargs="?",default=Path.cwd())
    parser.add_argument("--decode-images",action="store_true",help="also decode every image; requires Pillow")
    args=parser.parse_args()
    print(json.dumps(validate(args.release,args.decode_images),indent=2))


if __name__=="__main__":
    main()