File size: 4,361 Bytes
d639863
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
validate.py -- integrity check for data/artists.json + images/.

Run this after adding or editing artists to confirm the dataset and the
images/ directory agree.

Checks (all must pass):
  1. data/artists.json parses as valid JSON (a plain array).
  2. All `id`s are unique.
  3. No empty/blank `name` fields.
  4. Every record's `images` integer exactly matches what's on disk:
       - images == 0  -> no images/{id}/ directory
       - images == N>0 -> images/{id}/thumb.webp exists AND 01.webp..NN.webp
         (zero-padded 2 digits) exist, and there are exactly N such numbered
         files (no more, no less).

Exit code 0 and "ALL CHECKS PASSED" on success; non-zero + failure list otherwise.
"""

import json
import os
import re
import sys

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
DATA_JSON = os.path.join(PROJECT_ROOT, "data", "artists.json")
IMAGES_DIR = os.path.join(PROJECT_ROOT, "images")

NUMBERED_RE = re.compile(r"^(\d{2})\.webp$")


def main():
    errors = []

    with open(DATA_JSON, encoding="utf-8") as fh:
        records = json.load(fh)  # raises on invalid JSON
    print("JSON parses OK: {} records".format(len(records)))

    if not isinstance(records, list):
        print("FATAL: top-level artists.json is not a JSON array")
        sys.exit(1)

    ids = [r.get("id") for r in records]
    dupe_ids = {i for i in ids if ids.count(i) > 1}
    if dupe_ids:
        errors.append("Duplicate ids: {}".format(sorted(dupe_ids)[:20]))
    else:
        print("All {} ids unique: OK".format(len(ids)))

    blank_names = [r["id"] for r in records if not (r.get("name") or "").strip()]
    if blank_names:
        errors.append("Blank names for ids: {}".format(blank_names[:20]))
    else:
        print("No blank names: OK")

    mismatches = []
    for r in records:
        aid = r["id"]
        n = r["images"]
        out_dir = os.path.join(IMAGES_DIR, aid)
        exists = os.path.isdir(out_dir)

        if n == 0:
            if exists:
                mismatches.append("{}: images=0 but {} exists".format(aid, out_dir))
            continue

        if not exists:
            mismatches.append("{}: images={} but no directory".format(aid, n))
            continue

        thumb = os.path.join(out_dir, "thumb.webp")
        if not os.path.isfile(thumb):
            mismatches.append("{}: missing thumb.webp".format(aid))

        numbered = sorted(
            f for f in os.listdir(out_dir) if NUMBERED_RE.match(f)
        )
        if len(numbered) != n:
            mismatches.append(
                "{}: images={} but found {} numbered files ({})".format(
                    aid, n, len(numbered), numbered
                )
            )
        else:
            expected = ["{:02d}.webp".format(i) for i in range(1, n + 1)]
            if numbered != expected:
                mismatches.append(
                    "{}: numbered files {} != expected {}".format(aid, numbered, expected)
                )

        # Flag any extra, unexpected files in the directory.
        extra = [
            f for f in os.listdir(out_dir)
            if f != "thumb.webp" and not NUMBERED_RE.match(f)
        ]
        if extra:
            mismatches.append("{}: unexpected extra files {}".format(aid, extra))

    if mismatches:
        errors.append("Image count/disk mismatches ({} total):\n  ".format(len(mismatches))
                       + "\n  ".join(mismatches[:40]))
    else:
        print("Every record's `images` count matches files on disk: OK")

    # Check for stray directories under images/ with no matching record.
    known_ids = set(ids)
    stray = []
    if os.path.isdir(IMAGES_DIR):
        for d in os.listdir(IMAGES_DIR):
            if d not in known_ids and os.path.isdir(os.path.join(IMAGES_DIR, d)):
                stray.append(d)
    if stray:
        errors.append("Stray image directories with no matching id ({}): {}".format(
            len(stray), stray[:20]))
    else:
        print("No stray image directories: OK")

    print()
    if errors:
        print("VALIDATION FAILED ({} error groups):".format(len(errors)))
        for e in errors:
            print(" - " + e)
        sys.exit(1)
    else:
        print("ALL CHECKS PASSED")
        sys.exit(0)


if __name__ == "__main__":
    main()