PS4Research commited on
Commit
382d1cb
·
verified ·
1 Parent(s): a2f3575

Remove the old local build script; the catalogue is now built by the GPU prep notebook

Browse files
Files changed (1) hide show
  1. build_catalogue.py +0 -137
build_catalogue.py DELETED
@@ -1,137 +0,0 @@
1
- """Build the workshop catalogue bundle (run once, by the speakers, before the workshop).
2
-
3
- Output: project/bundle/
4
- catalogue.csv 3,000 products: product_id, title, category, colour, gender, usage, price, image_path
5
- products.csv 500-row subset for the Part 1 starter notebook (no images needed)
6
- image_vectors.npy (3000, 512) float32, every row has length 1, same row order as catalogue.csv
7
- images.zip images/<product_id>.jpg, 240x320 JPEG
8
- manifest.json counts, model + dataset revisions, sha256 of every file
9
-
10
- The vectors are computed from the *resized JPEGs in the bundle*, so a student who
11
- encodes a bundle photo on CPU gets the stored vector back (cosine > 0.99).
12
- """
13
- import hashlib
14
- import io
15
- import json
16
- import zipfile
17
- from pathlib import Path
18
-
19
- import numpy as np
20
- import pandas as pd
21
- import pyarrow.parquet as pq
22
- import torch
23
- from huggingface_hub import snapshot_download
24
- from PIL import Image
25
- from transformers import CLIPModel, CLIPProcessor
26
-
27
- SOURCE = "benitomartin/fashion-product-images-small-384x512"
28
- MODEL = "openai/clip-vit-base-patch32"
29
- MODEL_REVISION = "3d74acf9a28c67741b2f4f2ea7635f0aaf6f0268"
30
- SEED = 12
31
- PER_CATEGORY = 150
32
- PART1_ROWS = 500
33
- IMAGE_SIZE = (240, 320)
34
-
35
- # category -> synthetic price range in US dollars (min, max)
36
- CATEGORIES = {
37
- "Tshirts": (9, 39), "Shirts": (14, 59), "Jeans": (24, 89), "Trousers": (19, 69),
38
- "Shorts": (9, 34), "Kurtas": (14, 69), "Tops": (9, 44), "Dresses": (19, 99),
39
- "Jackets": (39, 179), "Casual Shoes": (29, 119), "Sports Shoes": (39, 179), "Heels": (24, 99),
40
- "Flip Flops": (5, 24), "Sandals": (12, 59), "Watches": (19, 249), "Handbags": (19, 129),
41
- "Backpacks": (19, 99), "Wallets": (9, 49), "Sunglasses": (14, 129), "Belts": (9, 39),
42
- }
43
-
44
- OUT = Path(__file__).resolve().parent / "bundle"
45
-
46
-
47
- def sha256(path):
48
- h = hashlib.sha256()
49
- with open(path, "rb") as f:
50
- for chunk in iter(lambda: f.read(1 << 20), b""):
51
- h.update(chunk)
52
- return h.hexdigest()
53
-
54
-
55
- def demo_price(rng, lo, hi):
56
- """A plausible-looking whole-dollar price that ends in 4 or 9, e.g. $24 or $59."""
57
- raw = rng.uniform(lo, hi)
58
- return int(min(hi, max(lo, round(raw / 5) * 5 - 1)))
59
-
60
-
61
- def main():
62
- OUT.mkdir(parents=True, exist_ok=True)
63
- snap = snapshot_download(SOURCE, repo_type="dataset", allow_patterns=["data/*.parquet"])
64
- shards = sorted(Path(snap, "data").glob("*.parquet"))
65
- meta_cols = ["id", "gender", "articleType", "baseColour", "usage", "productDisplayName"]
66
- meta = pd.concat([pq.read_table(s, columns=meta_cols).to_pandas() for s in shards], ignore_index=True)
67
- meta = meta[meta.articleType.isin(CATEGORIES) & meta.productDisplayName.notna() & meta.baseColour.notna()]
68
-
69
- rng = np.random.default_rng(SEED)
70
- picked = (
71
- meta.groupby("articleType")
72
- .sample(PER_CATEGORY, random_state=SEED)
73
- .sort_values(["articleType", "id"])
74
- .reset_index(drop=True)
75
- )
76
- assert len(picked) == PER_CATEGORY * len(CATEGORIES), len(picked)
77
- wanted = set(picked.id.tolist())
78
-
79
- # pull only the chosen images out of the shards
80
- images = {}
81
- for s in shards:
82
- t = pq.read_table(s, columns=["id", "image"]).to_pandas()
83
- for pid, img in zip(t.id, t.image):
84
- if pid in wanted:
85
- raw = img["bytes"] if isinstance(img, dict) else img
86
- images[pid] = Image.open(io.BytesIO(raw)).convert("RGB").resize(IMAGE_SIZE, Image.LANCZOS)
87
- assert len(images) == len(wanted), f"missing images: {len(wanted) - len(images)}"
88
-
89
- rows = []
90
- zbuf = OUT / "images.zip"
91
- with zipfile.ZipFile(zbuf, "w", compression=zipfile.ZIP_STORED) as z:
92
- for r in picked.itertuples():
93
- name = f"images/{r.id}.jpg"
94
- b = io.BytesIO()
95
- images[r.id].save(b, format="JPEG", quality=88)
96
- z.writestr(name, b.getvalue())
97
- lo, hi = CATEGORIES[r.articleType]
98
- rows.append(dict(product_id=int(r.id), title=r.productDisplayName.strip(), category=r.articleType,
99
- colour=r.baseColour, gender=r.gender, usage=r.usage if isinstance(r.usage, str) else "",
100
- price=demo_price(rng, lo, hi), image_path=name))
101
- catalogue = pd.DataFrame(rows)
102
- catalogue.to_csv(OUT / "catalogue.csv", index=False)
103
-
104
- # Part 1 subset: 500 random rows, no images. Deliberately NOT balanced, so the SQL
105
- # exercise's COUNT(*) differs by category and flipping DESC/ASC visibly reorders rows.
106
- part1 = (catalogue.sample(PART1_ROWS, random_state=SEED)
107
- .sort_values("product_id")[["product_id", "title", "category", "colour", "price"]])
108
- part1.to_csv(OUT / "products.csv", index=False)
109
-
110
- # vectors from the bundle JPEGs themselves (decode exactly what students will decode)
111
- torch.set_num_threads(16)
112
- model = CLIPModel.from_pretrained(MODEL, revision=MODEL_REVISION).eval()
113
- processor = CLIPProcessor.from_pretrained(MODEL, revision=MODEL_REVISION)
114
- vecs = []
115
- with zipfile.ZipFile(zbuf) as z, torch.no_grad():
116
- names = catalogue.image_path.tolist()
117
- for i in range(0, len(names), 64):
118
- batch = [Image.open(io.BytesIO(z.read(n))).convert("RGB") for n in names[i:i + 64]]
119
- feats = model.get_image_features(**processor(images=batch, return_tensors="pt")).pooler_output
120
- vecs.append(feats.numpy())
121
- print(f"encoded {min(i + 64, len(names))}/{len(names)}", flush=True)
122
- V = np.concatenate(vecs).astype(np.float32)
123
- V /= np.linalg.norm(V, axis=1, keepdims=True)
124
- np.save(OUT / "image_vectors.npy", V)
125
-
126
- files = ["catalogue.csv", "products.csv", "image_vectors.npy", "images.zip"]
127
- manifest = dict(
128
- products=len(catalogue), categories=len(CATEGORIES), vector_shape=list(V.shape),
129
- source_dataset=SOURCE, model=MODEL, model_revision=MODEL_REVISION, image_size=list(IMAGE_SIZE),
130
- seed=SEED, prices="synthetic demo values", sha256={f: sha256(OUT / f) for f in files},
131
- )
132
- (OUT / "manifest.json").write_text(json.dumps(manifest, indent=2))
133
- print(json.dumps(manifest, indent=2))
134
-
135
-
136
- if __name__ == "__main__":
137
- main()