Yanqing0327 commited on
Commit
6ae40cb
·
verified ·
1 Parent(s): cd95b29

Add files using upload-large-folder tool

Browse files
Files changed (1) hide show
  1. editing/dressed/match_dress_ed.py +292 -0
editing/dressed/match_dress_ed.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Map our edit/dressed records to Dress-ED train rows (item_id, filename).
3
+
4
+ Rewritten on 2026-11-11. The first version matched by image bytes and kept both person images of every row without
5
+ a byte match in memory until all 133 files were read; no row can match by bytes (Dress-ED stores its person images
6
+ at about 85 KB, our training copies are re-encodes of about 50 KB), so it kept all it downloaded and ran the 18 GB
7
+ laptop out of memory twice. Instruction text alone does not single rows out either (132,201 rows, 12,689 distinct
8
+ instruction pairs). But our pairs are stored in Dress-ED's own order: pair i of index.jsonl.gz (pairs in shard
9
+ order) is row i of the train files (sorted file names, rows in file order). So this version
10
+
11
+ 1. reads only the text columns of the train files (a few KB per row group; cached per file in --work);
12
+ 2. aligns by position, pair i with row i, and accepts a position where the pair's two instructions equal the row's
13
+ instruction_forward and instruction_reverse (normalized: whitespace, one final period); the record with the
14
+ forward instruction is the forward record (forward = original_person + instruction_forward -> edited_person,
15
+ reverse = edited_person + instruction_reverse -> original_person). Our index's forward/reverse labels were
16
+ guessed when it was built; the report counts how often the guess agrees;
17
+ 3. checks the alignment by pixels on every row of --sample-groups random row groups (100 rows each): the row's
18
+ original person image must match the forward record's query image and the reverse record's target image (96x128
19
+ grey thumbnails, mean absolute difference on the 0-255 scale <= --pixel-tol). The edited person image is
20
+ compared too, but only recorded (edited_image_check "same" / "differs"): Dress-ED's repository was squashed into
21
+ one commit on 2026-08-13, after our shards were made (2026-08-03), and some of its edited images are now another
22
+ generation of the same edit (same person, same instructions, a different result). Only those row groups' person
23
+ images are read, one row group at a time, and each becomes a thumbnail at once; our images are read by byte
24
+ range from --our-shards. --details writes one line per checked row.
25
+
26
+ A position whose texts disagree, or a checked row whose original photo does not match, is left unmatched and reported. Every record and every
27
+ Dress-ED row ends in exactly one bucket; nothing is dropped.
28
+
29
+ Full run (laptop with the HF login):
30
+ python match_dress_ed.py --index index.jsonl.gz --hf-repo davidelobba/Dress-ED --revision <sha> \\
31
+ --glob 'data/paired/train/*.parquet' --our-shards shards \\
32
+ --work <dir> --out mapping.jsonl.gz --report match_report.json
33
+ A local test needs only --parquet <file> instead of --hf-repo/--glob (test_match_dress_ed.py).
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import collections
39
+ import gzip
40
+ import hashlib
41
+ import io
42
+ import json
43
+ import os
44
+ import random
45
+ import re
46
+ import sys
47
+ from concurrent.futures import ThreadPoolExecutor
48
+
49
+ TEXT_COLS = ["item_id", "filename", "split", "edit_task", "category", "instruction_forward", "instruction_reverse"]
50
+ IMG_COLS = ["original_person", "edited_person"]
51
+ KEEP = ("record_id", "shard", "offset", "record_len", "record_sha256", "pair_id", "direction", "instruction",
52
+ "query_image_sha256", "target_image_sha256")
53
+
54
+
55
+ def _img_bytes(v):
56
+ if v is None:
57
+ return b""
58
+ if isinstance(v, dict):
59
+ return v.get("bytes") or b""
60
+ return bytes(v)
61
+
62
+
63
+ def _norm(s: str | None) -> str:
64
+ s = re.sub(r"\s+", " ", (s or "").strip())
65
+ return s[:-1] if s.endswith(".") else s
66
+
67
+
68
+ def _thumb(b: bytes):
69
+ import numpy as np
70
+ from PIL import Image
71
+ with Image.open(io.BytesIO(b)) as im:
72
+ return np.asarray(im.convert("L").resize((96, 128)), dtype=np.uint8)
73
+
74
+
75
+ def _mad(a, b) -> float:
76
+ import numpy as np
77
+ return float(np.abs(a.astype(np.int16) - b.astype(np.int16)).mean())
78
+
79
+
80
+ def _open(p, fs):
81
+ return fs.open(p, "rb") if fs is not None else open(p, "rb")
82
+
83
+
84
+ def read_text(paths, fs, work, threads):
85
+ """The text columns of every row, with its file, row group and position in it (cached per file)."""
86
+ import pyarrow.parquet as pq
87
+
88
+ def one(n_p):
89
+ n, p = n_p
90
+ cache = os.path.join(work, f"rows_{n:04d}.jsonl") if work else None
91
+ if cache and os.path.exists(cache):
92
+ with open(cache) as fh:
93
+ head = json.loads(fh.readline())
94
+ if head.get("file") == p:
95
+ return [json.loads(l) for l in fh]
96
+ out = []
97
+ with _open(p, fs) as f:
98
+ pf = pq.ParquetFile(f)
99
+ cols = [c for c in TEXT_COLS if c in pf.schema_arrow.names]
100
+ for rg in range(pf.num_row_groups):
101
+ for i, row in enumerate(pf.read_row_group(rg, columns=cols).to_pylist()):
102
+ row.update({"_file": p, "_rg": rg, "_i": i})
103
+ out.append(row)
104
+ if cache:
105
+ with open(cache + ".tmp", "w") as fh:
106
+ fh.write(json.dumps({"file": p, "rows": len(out)}) + "\n")
107
+ for row in out:
108
+ fh.write(json.dumps(row) + "\n")
109
+ os.replace(cache + ".tmp", cache)
110
+ return out
111
+
112
+ rows = []
113
+ with ThreadPoolExecutor(threads) as ex:
114
+ for n, out in enumerate(ex.map(one, enumerate(paths))):
115
+ rows.extend(out)
116
+ if (n + 1) % 10 == 0 or n + 1 == len(paths):
117
+ print(f"text: {n + 1}/{len(paths)} files, {len(rows)} rows", flush=True)
118
+ return rows
119
+
120
+
121
+ def row_thumbs(rows, sel, fs):
122
+ """Thumbnails and sha256 of the two person images of the selected rows, one row group at a time."""
123
+ import pyarrow.parquet as pq
124
+ out = {}
125
+ by_file = collections.defaultdict(lambda: collections.defaultdict(list))
126
+ for j in sel:
127
+ by_file[rows[j]["_file"]][rows[j]["_rg"]].append(j)
128
+ for n, (p, groups) in enumerate(sorted(by_file.items())):
129
+ with _open(p, fs) as f:
130
+ pf = pq.ParquetFile(f)
131
+ for rg, js in sorted(groups.items()):
132
+ t = pf.read_row_group(rg, columns=IMG_COLS)
133
+ for j in js:
134
+ i = rows[j]["_i"]
135
+ op = _img_bytes(t.column("original_person")[i].as_py())
136
+ ep = _img_bytes(t.column("edited_person")[i].as_py())
137
+ out[j] = (_thumb(op), _thumb(ep), hashlib.sha256(op).hexdigest(), hashlib.sha256(ep).hexdigest())
138
+ del t
139
+ print(f"pixels: {n + 1}/{len(by_file)} files read", flush=True)
140
+ return out
141
+
142
+
143
+ def main(argv=None) -> int:
144
+ ap = argparse.ArgumentParser()
145
+ ap.add_argument("--index", required=True, help="index.jsonl.gz from pair_and_report.py")
146
+ ap.add_argument("--parquet", nargs="*", default=[], help="local parquet files (in Dress-ED's order)")
147
+ ap.add_argument("--hf-repo", default="")
148
+ ap.add_argument("--revision", default="main")
149
+ ap.add_argument("--glob", default="data/paired/train/*.parquet")
150
+ ap.add_argument("--our-shards", required=True, help="dir or gs:// prefix of our shards (pixel check)")
151
+ ap.add_argument("--work", default="", help="cache dir for the text pass")
152
+ ap.add_argument("--pixel-tol", type=float, default=4.0)
153
+ ap.add_argument("--sample-groups", type=int, default=10, help="random row groups checked by pixels")
154
+ ap.add_argument("--seed", type=int, default=0)
155
+ ap.add_argument("--threads", type=int, default=8)
156
+ ap.add_argument("--out", required=True)
157
+ ap.add_argument("--report", required=True)
158
+ ap.add_argument("--details", default="", help="one JSON line per pixel-checked row")
159
+ args = ap.parse_args(argv)
160
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
161
+ from loader_example import read_record_images
162
+
163
+ recs = []
164
+ with gzip.open(args.index, "rt", encoding="utf-8") as fh:
165
+ for line in fh:
166
+ r = json.loads(line)
167
+ recs.append({k: r.get(k) for k in KEEP})
168
+ pairs = collections.OrderedDict()
169
+ for k, r in enumerate(recs):
170
+ pairs.setdefault(r["pair_id"], []).append(k)
171
+ pairs = list(pairs.values())
172
+
173
+ fs, paths = None, list(args.parquet)
174
+ if args.hf_repo:
175
+ from huggingface_hub import HfFileSystem
176
+ fs = HfFileSystem()
177
+ paths = sorted(fs.glob(f"datasets/{args.hf_repo}@{args.revision}/{args.glob}"))
178
+ if args.work:
179
+ os.makedirs(args.work, exist_ok=True)
180
+ rows = read_text(paths, fs, args.work, args.threads)
181
+
182
+ # 1. align by position: pair i <-> row i, where the instructions agree
183
+ row_out, unmatched_rows = collections.Counter(), []
184
+ aligned = {} # row index -> (forward record, reverse record)
185
+ for j, row in enumerate(rows):
186
+ if j >= len(pairs):
187
+ row_out["unmatched_no_pair_at_position"] += 1
188
+ unmatched_rows.append((row["item_id"], row["filename"], "no pair of ours at this position"))
189
+ continue
190
+ p = pairs[j]
191
+ f_, r_ = _norm(row.get("instruction_forward")), _norm(row.get("instruction_reverse"))
192
+ ins = [_norm(recs[k]["instruction"]) for k in p]
193
+ if len(p) == 2 and ins == [f_, r_]:
194
+ aligned[j] = (p[0], p[1])
195
+ elif len(p) == 2 and ins == [r_, f_]:
196
+ aligned[j] = (p[1], p[0])
197
+ else:
198
+ row_out["unmatched_text_differs"] += 1
199
+ unmatched_rows.append((row["item_id"], row["filename"], f"pair {recs[p[0]]['pair_id']}: instructions differ"))
200
+ print(f"aligned by position and text: {len(aligned)} of {len(rows)} rows ({len(pairs)} pairs of ours)", flush=True)
201
+
202
+ # 2. pixels on every aligned row of a few random row groups
203
+ groups = sorted({(rows[j]["_file"], rows[j]["_rg"]) for j in aligned})
204
+ pick = set(random.Random(args.seed).sample(groups, min(args.sample_groups, len(groups))))
205
+ sample = [j for j in aligned if (rows[j]["_file"], rows[j]["_rg"]) in pick]
206
+ thumbs = row_thumbs(rows, sample, fs) if sample else {}
207
+
208
+ def ours(k):
209
+ q, t = read_record_images(args.our_shards, recs[k])
210
+ return k, (_thumb(q), _thumb(t))
211
+ with ThreadPoolExecutor(args.threads) as ex:
212
+ our = dict(ex.map(ours, sorted({k for j in sample for k in aligned[j]})))
213
+ st = {"rows": len(sample), "row_groups": len(pick), "original_matches": 0, "failed": [], "original_mad_max": 0.0,
214
+ "edited_same": 0, "edited_differs": 0, "edited_mad_max": 0.0, "edited_differs_by_row_group": {},
215
+ "bytes_equal_images": 0}
216
+ failed, edited_check = set(), {}
217
+ details = open(args.details, "w") if args.details else None
218
+ for j in sample:
219
+ f, r = aligned[j]
220
+ top, tep, hop, hep = thumbs[j]
221
+ d = (_mad(our[f][0], top), _mad(our[f][1], tep), _mad(our[r][0], tep), _mad(our[r][1], top))
222
+ orig, edit = max(d[0], d[3]), max(d[1], d[2])
223
+ st["original_mad_max"] = max(st["original_mad_max"], orig)
224
+ st["edited_mad_max"] = max(st["edited_mad_max"], edit)
225
+ st["bytes_equal_images"] += (hop == recs[f]["query_image_sha256"]) + (hep == recs[f]["target_image_sha256"])
226
+ g = f"{rows[j]['_file'].rsplit('/', 1)[-1]}#{rows[j]['_rg']}"
227
+ st["edited_differs_by_row_group"].setdefault(g, 0)
228
+ if details:
229
+ details.write(json.dumps({"item_id": rows[j]["item_id"], "filename": rows[j]["filename"], "row_group": g,
230
+ "row_in_group": rows[j]["_i"], "mad": [round(x, 3) for x in d]}) + "\n")
231
+ if orig > args.pixel_tol:
232
+ failed.add(j)
233
+ st["failed"].append((rows[j]["item_id"], rows[j]["filename"], [round(x, 2) for x in d]))
234
+ row_out["unmatched_failed_pixels"] += 1
235
+ unmatched_rows.append((rows[j]["item_id"], rows[j]["filename"], "aligned by text but the original photo differs"))
236
+ continue
237
+ st["original_matches"] += 1
238
+ if edit <= args.pixel_tol:
239
+ st["edited_same"] += 1
240
+ edited_check[j] = "same"
241
+ else:
242
+ st["edited_differs"] += 1
243
+ st["edited_differs_by_row_group"][g] += 1
244
+ edited_check[j] = "differs"
245
+ if details:
246
+ details.close()
247
+ sample = set(sample)
248
+
249
+ assigned = {} # our record index -> (row index, direction, how)
250
+ for j, (f, r) in aligned.items():
251
+ if j in failed:
252
+ continue
253
+ how = "order+text+pixels" if j in sample else "order+text"
254
+ row_out["matched_" + how] += 1
255
+ assigned[f], assigned[r] = (j, "forward", how), (j, "reverse", how)
256
+ print(f"pixels: {st['original_matches']} of {len(sample)} checked rows match by the original photo; "
257
+ f"edited image same {st['edited_same']}, differs {st['edited_differs']}", flush=True)
258
+
259
+ rec_out = collections.Counter()
260
+ with gzip.open(args.out, "wt", encoding="utf-8") as fh:
261
+ for k, r in enumerate(recs):
262
+ a = assigned.get(k)
263
+ if a is None:
264
+ fh.write(json.dumps({"record_id": r["record_id"], "dress_ed_item_id": None, "dress_ed_filename": None,
265
+ "match": "unmatched", "direction": None, "parquet_file": None,
266
+ "edited_image_check": None}) + "\n")
267
+ rec_out["unmatched"] += 1
268
+ continue
269
+ j, d, how = a
270
+ row = rows[j]
271
+ rec_out[how] += 1
272
+ if r.get("direction") and r["direction"] != d:
273
+ rec_out["direction_differs_from_index_guess"] += 1
274
+ fh.write(json.dumps({"record_id": r["record_id"], "dress_ed_item_id": row["item_id"],
275
+ "dress_ed_filename": row["filename"], "match": f"{how}:{d}", "direction": d,
276
+ "parquet_file": row["_file"], "row_group": row["_rg"], "row_in_group": row["_i"],
277
+ "dress_ed_edit_task": row.get("edit_task"), "dress_ed_category": row.get("category"),
278
+ "edited_image_check": edited_check.get(j)}) + "\n")
279
+ st["original_mad_max"] = round(st["original_mad_max"], 3)
280
+ st["edited_mad_max"] = round(st["edited_mad_max"], 3)
281
+ st["failed"] = st["failed"][:20]
282
+ report = {"parquet_files": len(paths), "dress_ed_rows": len(rows), "our_pairs": len(pairs), "our_records": len(recs),
283
+ "rows": dict(row_out), "records": dict(rec_out), "pixel_tol": args.pixel_tol, "pixel_check": st,
284
+ "unmatched_rows_first_50": unmatched_rows[:50]}
285
+ with open(args.report, "w") as fh:
286
+ json.dump(report, fh, indent=1)
287
+ print(json.dumps(report, indent=1)[:3000], flush=True)
288
+ return 0
289
+
290
+
291
+ if __name__ == "__main__":
292
+ sys.exit(main())