File size: 9,605 Bytes
c00c855
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Minimal loader for the edit/dressed release subset (standard library only; PIL optional).

Yields the training inputs of every record the training kept, in index order:
    {record_id, pair_id, direction, query_image (JPEG bytes), instruction (the query text the
     trainer used), target_image (JPEG bytes), image_negative (JPEG bytes: the query image,
     as in training), dress_ed_item_id, dress_ed_filename}
Every record read is checked against the index: sha256 of the serialized record and of both
images. Shards can be a local directory or a gs:// prefix (read with `gcloud storage cat`).

    python loader_example.py --index index.jsonl.gz --shards <dir or gs://.../shards> --limit 5
    python loader_example.py ... --save-dir out/   # also write the first records' images
"""
from __future__ import annotations

import argparse
import gzip
import hashlib
import io
import json
import os
import struct
import subprocess
import sys
from typing import BinaryIO, Iterator


# ----------------------------------------------------------------- TFRecord + Example parsing
def _varint(buf: bytes, i: int) -> tuple[int, int]:
    shift = result = 0
    while True:
        b = buf[i]
        i += 1
        result |= (b & 0x7F) << shift
        if b < 0x80:
            return result, i
        shift += 7


def _fields(buf: bytes):
    i = 0
    while i < len(buf):
        key, i = _varint(buf, i)
        f, w = key >> 3, key & 7
        if w == 2:
            n, i = _varint(buf, i)
            yield f, buf[i:i + n]
            i += n
        elif w == 0:
            _, i = _varint(buf, i)
        elif w == 5:
            i += 4
        elif w == 1:
            i += 8
        else:
            raise ValueError(f"unsupported wire type {w}")


def parse_bytes_features(payload: bytes) -> dict[str, bytes]:
    """tf.train.Example -> {name: first bytes value} for bytes features."""
    out = {}
    for f, feats in _fields(payload):
        if f != 1:
            continue
        for f2, entry in _fields(feats):
            if f2 != 1:
                continue
            name, feat = "", b""
            for f3, v in _fields(entry):
                if f3 == 1:
                    name = v.decode("utf-8", "replace")
                elif f3 == 2:
                    feat = v
            for f4, lst in _fields(feat):
                if f4 == 1:                       # BytesList
                    vals = [v for f5, v in _fields(lst) if f5 == 1]
                    out[name] = vals[0] if vals else b""
    return out


def iter_frames(stream: BinaryIO) -> Iterator[bytes]:
    while True:
        head = stream.read(12)
        if not head:
            return
        if len(head) < 12:
            raise IOError("truncated TFRecord header")
        n = struct.unpack("<Q", head[:8])[0]
        payload = stream.read(n)
        if len(payload) != n or len(stream.read(4)) != 4:
            raise IOError("truncated TFRecord payload")
        yield payload


def _open(path: str) -> BinaryIO:
    if path.startswith("gs://"):
        p = subprocess.Popen(["gcloud", "storage", "cat", path], stdout=subprocess.PIPE)
        return p.stdout
    return open(path, "rb")


def _join(root: str, name: str) -> str:
    return root.rstrip("/") + "/" + name


def read_record_images(shards: str, rec: dict) -> tuple[bytes, bytes]:
    """Random access to one record (local shards: seek to its offset; gs://: byte range)."""
    path = _join(shards, rec["shard"])
    size = 16 + rec["record_len"]
    if path.startswith("gs://"):
        end = rec["offset"] + size - 1
        data = subprocess.run(["gcloud", "storage", "cat", "-r", f"{rec['offset']}-{end}", path],
                              check=True, capture_output=True).stdout
    else:
        with open(path, "rb") as fh:
            fh.seek(rec["offset"])
            data = fh.read(size)
    payload = next(iter_frames(io.BytesIO(data)))
    if hashlib.sha256(payload).hexdigest() != rec["record_sha256"]:
        raise ValueError(f"{rec['record_id']}: record sha256 differs from the index")
    ex = parse_bytes_features(payload)
    return ex.get("jpg", b""), ex.get("cand_jpg", b"")


def load_index(path: str) -> list[dict]:
    raw = _open(path).read() if path.startswith("gs://") else open(path, "rb").read()
    with gzip.open(io.BytesIO(raw), "rt", encoding="utf-8") as fh:
        return [json.loads(l) for l in fh]


def iter_training_inputs(index: list[dict], shards: str, *, only_kept: bool = True,
                         limit: int | None = None, problems: list | None = None) -> Iterator[dict]:
    """Stream the shards in order and yield training inputs; every record is verified. A record whose bytes or images
    differ from the index, or that its shard does not hold, is skipped and appended to ``problems`` (record_id, shard,
    ordinal, field, reason); without that list the iterator raises at the end, after every good record, when any was
    skipped (2026-11-12: it no longer stops at the first problem)."""
    found = problems if problems is not None else []

    def problem(rec, field, reason):
        found.append({"record_id": rec["record_id"], "shard": rec["shard"], "ordinal": rec["ordinal"], "field": field,
                      "reason": reason})
    by_shard: dict[str, list[dict]] = {}
    for r in index:
        by_shard.setdefault(r["shard"], []).append(r)
    n = 0
    for shard in sorted(by_shard):
        recs = sorted(by_shard[shard], key=lambda r: r["ordinal"])
        try:
            stream = _open(_join(shards, shard))
        except Exception as e:  # noqa: BLE001
            for rec in recs:
                problem(rec, "record", f"shard not readable: {type(e).__name__}: {str(e)[:120]}")
            continue
        with stream:
            frames = iter_frames(stream)
            for i, rec in enumerate(recs):
                try:
                    payload = next(frames)
                except StopIteration:
                    for r2 in recs[i:]:
                        problem(r2, "record", "not in the shard (it ends earlier)")
                    break
                except Exception as e:  # noqa: BLE001  (a damaged frame: the rest of the shard cannot be read)
                    for r2 in recs[i:]:
                        problem(r2, "record", f"shard unreadable from here: {type(e).__name__}: {str(e)[:120]}")
                    break
                if hashlib.sha256(payload).hexdigest() != rec["record_sha256"]:
                    problem(rec, "record", "record sha256 differs from the index")
                    continue
                keep = (rec["kept_by_adapter"] and rec["decode_ok"] and not rec["contamination_blocked"]
                        and not rec["dedup_skipped"])
                if only_kept and not keep:
                    continue
                ex = parse_bytes_features(payload)
                q, t = ex.get("jpg", b""), ex.get("cand_jpg", b"")
                bad = [f for f, b, h in (("query_image", q, rec["query_image_sha256"]), ("target_image", t, rec["target_image_sha256"]))
                       if hashlib.sha256(b).hexdigest() != h]
                if bad:
                    for f in bad:
                        problem(rec, f, "image sha256 differs from the index")
                    continue
                yield {"record_id": rec["record_id"], "pair_id": rec["pair_id"], "direction": rec["direction"],
                       "query_image": q, "instruction": rec["training_query_text"], "target_image": t,
                       "image_negative": q if rec.get("image_negative") == "query_image" else None,
                       "dress_ed_item_id": rec["dress_ed_item_id"], "dress_ed_filename": rec["dress_ed_filename"]}
                n += 1
                if limit is not None and n >= limit:
                    return
    if found and problems is None:
        raise ValueError(f"{len(found)} records skipped (see the problems list), e.g. {found[:2]}")


def main(argv=None) -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--index", required=True)
    ap.add_argument("--shards", required=True)
    ap.add_argument("--limit", type=int, default=5)
    ap.add_argument("--only-shard", default="", help="restrict to one shard name (quick test)")
    ap.add_argument("--save-dir", default="")
    ap.add_argument("--problems", default="dressed_problems.jsonl", help="where to list the records that fail a check")
    args = ap.parse_args(argv)
    index = load_index(args.index)
    if args.only_shard:
        index = [r for r in index if r["shard"] == args.only_shard]
    n, probs = 0, []
    for ex in iter_training_inputs(index, args.shards, limit=args.limit or None, problems=probs):
        n += 1
        if n <= 5:
            print(json.dumps({k: (f"<{len(v)} bytes>" if isinstance(v, bytes) else v) for k, v in ex.items()},
                             ensure_ascii=False))
        if args.save_dir and n <= 5:
            os.makedirs(args.save_dir, exist_ok=True)
            for k in ("query_image", "target_image"):
                with open(os.path.join(args.save_dir, f"{ex['record_id'].replace('#', '_')}_{k}.jpg"), "wb") as fh:
                    fh.write(ex[k])
    print(f"verified and yielded {n} records", file=sys.stderr)
    if probs:
        with open(args.problems, "w") as fh:
            for p in probs:
                fh.write(json.dumps(p) + "\n")
        print(f"INCOMPLETE: {len(probs)} problems listed in {args.problems}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())