mucahitkantepe commited on
Commit
7dcb597
·
1 Parent(s): f8c345c

add 5 new store scrapers, category filtering, per-category taste scoring

Browse files

Scrapers: Zalando (hydration data), COS (Centra/__NEXT_DATA__),
& Other Stories (__NEXT_DATA__), Ellos (Nuxt 3 payload),
Nelly (Voyado Elevate API). All use curl_cffi or httpx as needed.

Expand all stores to full women's clothing categories (dresses,
tops, jackets, trousers, skirts, knitwear, shoes, bags).

Add category filter UI with multilingual pattern matching backend
and pill bar in browse page.

Implement per-category taste scoring: build separate centroids per
category, score products against their own category's centroids,
fall back to unified for unseen categories. Experimentally validated
1.3-2.3x better within-category discrimination.

backend/app/routers/discover.py CHANGED
@@ -38,12 +38,14 @@ def _sync_discover_ratings():
38
  synced = 0
39
  ratings = engine.load_ratings()
40
  for r in rows:
41
- img_row = conn.execute("SELECT image_path FROM products WHERE url = ?", (r["url"],)).fetchone()
 
 
42
  if img_row and img_row["image_path"]:
43
  p = Path(img_row["image_path"])
44
  resolved = str(p.resolve())
45
  if p.exists() and resolved not in ratings:
46
- engine.save_rating(p, r["rating"])
47
  synced += 1
48
  ratings[resolved] = r["rating"]
49
 
@@ -183,14 +185,16 @@ def _save_product_rating(url: str, rating_val: int, store, engine):
183
  """Save product image as liked (1) or disliked (-1) in the taste engine.
184
 
185
  Downloads the image from image_url if the local file doesn't exist.
 
186
  """
187
  row = store.conn.execute(
188
- "SELECT image_path, image_url FROM products WHERE url = ?", (url,)
189
  ).fetchone()
190
  if not row:
191
  return
192
 
193
  p = Path(row["image_path"]) if row["image_path"] else None
 
194
 
195
  # If local file doesn't exist, download from image_url
196
  if (not p or not p.exists()) and row["image_url"]:
@@ -212,7 +216,7 @@ def _save_product_rating(url: str, rating_val: int, store, engine):
212
  store.conn.commit()
213
 
214
  if p and p.exists():
215
- engine.save_rating(p, rating_val)
216
 
217
 
218
  def _trigger_async_rescore():
@@ -227,18 +231,20 @@ def _trigger_async_rescore():
227
 
228
 
229
  def _do_rescore():
230
- """Rebuild taste model with all feedback and rescore products."""
231
  global _rescore_pending
232
  try:
233
  engine = get_engine()
234
  store = get_store()
235
 
236
- print("[discover] Rebuilding taste model...", flush=True)
237
- centroids = engine.build_taste_vector()
238
- if centroids is None:
239
  return
240
 
241
- print(f"[discover] {len(centroids)} clusters. Rescoring...", flush=True)
 
 
242
 
243
  # Mark all as processed
244
  store.conn.execute("UPDATE discover_ratings SET processed = 1 WHERE processed = 0")
@@ -246,7 +252,7 @@ def _do_rescore():
246
 
247
  # Rescore ALL products — download images on-demand if missing locally
248
  rows = store.conn.execute("""
249
- SELECT url, image_path, image_url FROM products
250
  WHERE image_url != '' AND image_url IS NOT NULL
251
  """).fetchall()
252
 
@@ -257,7 +263,7 @@ def _do_rescore():
257
  batch_size = 100
258
  total_rescored = 0
259
  dl_count = 0
260
- paths_batch, urls_batch = [], []
261
 
262
  for r in rows:
263
  p = Path(r["image_path"]) if r["image_path"] else None
@@ -281,17 +287,20 @@ def _do_rescore():
281
  )
282
 
283
  if p and p.exists():
284
- paths_batch.append(p)
 
 
 
285
  urls_batch.append(r["url"])
286
 
287
- if len(paths_batch) >= batch_size:
288
- _score_batch(engine, store, paths_batch, urls_batch, centroids)
289
- total_rescored += len(paths_batch)
290
- paths_batch, urls_batch = [], []
291
 
292
- if paths_batch:
293
- _score_batch(engine, store, paths_batch, urls_batch, centroids)
294
- total_rescored += len(paths_batch)
295
 
296
  if dl_count:
297
  store.conn.commit()
@@ -307,9 +316,9 @@ def _do_rescore():
307
  _rescore_pending = False
308
 
309
 
310
- def _score_batch(engine, store, paths, urls, centroids):
311
- scored = engine.score_product_images(paths, centroids)
312
- score_map = {str(path): score for path, score in scored}
313
- for url, path in zip(urls, paths):
314
- s = score_map.get(str(path), 0)
315
  store.update_score(url, s)
 
38
  synced = 0
39
  ratings = engine.load_ratings()
40
  for r in rows:
41
+ img_row = conn.execute(
42
+ "SELECT image_path, category FROM products WHERE url = ?", (r["url"],)
43
+ ).fetchone()
44
  if img_row and img_row["image_path"]:
45
  p = Path(img_row["image_path"])
46
  resolved = str(p.resolve())
47
  if p.exists() and resolved not in ratings:
48
+ engine.save_rating(p, r["rating"], category=img_row["category"] or "")
49
  synced += 1
50
  ratings[resolved] = r["rating"]
51
 
 
185
  """Save product image as liked (1) or disliked (-1) in the taste engine.
186
 
187
  Downloads the image from image_url if the local file doesn't exist.
188
+ Includes product category so the engine can build per-category centroids.
189
  """
190
  row = store.conn.execute(
191
+ "SELECT image_path, image_url, category FROM products WHERE url = ?", (url,)
192
  ).fetchone()
193
  if not row:
194
  return
195
 
196
  p = Path(row["image_path"]) if row["image_path"] else None
197
+ category = row["category"] or ""
198
 
199
  # If local file doesn't exist, download from image_url
200
  if (not p or not p.exists()) and row["image_url"]:
 
216
  store.conn.commit()
217
 
218
  if p and p.exists():
219
+ engine.save_rating(p, rating_val, category=category)
220
 
221
 
222
  def _trigger_async_rescore():
 
231
 
232
 
233
  def _do_rescore():
234
+ """Rebuild per-category taste model and rescore all products."""
235
  global _rescore_pending
236
  try:
237
  engine = get_engine()
238
  store = get_store()
239
 
240
+ print("[discover] Rebuilding taste model (per-category)...", flush=True)
241
+ taste = engine.build_category_taste()
242
+ if taste["unified"] is None:
243
  return
244
 
245
+ n_cats = len(taste["categories"])
246
+ n_unified = len(taste["unified"])
247
+ print(f"[discover] {n_cats} category profiles, {n_unified} unified clusters. Rescoring...", flush=True)
248
 
249
  # Mark all as processed
250
  store.conn.execute("UPDATE discover_ratings SET processed = 1 WHERE processed = 0")
 
252
 
253
  # Rescore ALL products — download images on-demand if missing locally
254
  rows = store.conn.execute("""
255
+ SELECT url, image_path, image_url, category FROM products
256
  WHERE image_url != '' AND image_url IS NOT NULL
257
  """).fetchall()
258
 
 
263
  batch_size = 100
264
  total_rescored = 0
265
  dl_count = 0
266
+ products_batch, urls_batch = [], []
267
 
268
  for r in rows:
269
  p = Path(r["image_path"]) if r["image_path"] else None
 
287
  )
288
 
289
  if p and p.exists():
290
+ products_batch.append({
291
+ "image_path": str(p),
292
+ "category": r["category"] or "",
293
+ })
294
  urls_batch.append(r["url"])
295
 
296
+ if len(products_batch) >= batch_size:
297
+ _score_batch(engine, store, products_batch, urls_batch, taste)
298
+ total_rescored += len(products_batch)
299
+ products_batch, urls_batch = [], []
300
 
301
+ if products_batch:
302
+ _score_batch(engine, store, products_batch, urls_batch, taste)
303
+ total_rescored += len(products_batch)
304
 
305
  if dl_count:
306
  store.conn.commit()
 
316
  _rescore_pending = False
317
 
318
 
319
+ def _score_batch(engine, store, products, urls, taste):
320
+ scored = engine.score_products_by_category(products, taste)
321
+ score_map = {s["image_path"]: s["score"] for s in scored}
322
+ for url, prod in zip(urls, products):
323
+ s = score_map.get(prod["image_path"], 0)
324
  store.update_score(url, s)
backend/app/routers/products.py CHANGED
@@ -12,6 +12,24 @@ router = APIRouter(prefix="/api/products", tags=["products"])
12
  # Fields to drop from DB rows before passing to ProductOut
13
  _DROP_FIELDS = {"image_path", "fabric", "created_at", "first_seen_at", "last_seen_at", "updated_at", "rn"}
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  def _row_to_product(row) -> ProductOut:
17
  """Convert a DB row to ProductOut, parsing JSON fields."""
@@ -43,6 +61,7 @@ def list_products(
43
  page_size: int = Query(48, ge=1, le=200),
44
  store: str | None = None,
45
  brand: str | None = None,
 
46
  min_score: float = 0,
47
  min_price: float | None = None,
48
  max_price: float | None = None,
@@ -78,6 +97,14 @@ def list_products(
78
  if max_price is not None:
79
  where.append("price_nok <= ?")
80
  params.append(max_price)
 
 
 
 
 
 
 
 
81
  if search:
82
  where.append("(brand LIKE ? OR name LIKE ?)")
83
  params.extend([f"%{search}%", f"%{search}%"])
@@ -145,6 +172,29 @@ def list_brands():
145
  return [{"name": r["brand"], "count": r["cnt"]} for r in rows]
146
 
147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  @router.get("/price-range")
149
  def price_range():
150
  db = get_store()
 
12
  # Fields to drop from DB rows before passing to ProductOut
13
  _DROP_FIELDS = {"image_path", "fabric", "created_at", "first_seen_at", "last_seen_at", "updated_at", "rn"}
14
 
15
+ # Maps UI category labels to search patterns (covers EN, NO, SV, and Zalando silhouettes)
16
+ _CATEGORY_MAP: dict[str, list[str]] = {
17
+ "dresses": ["dress", "kjoler", "kjole", "klänning"],
18
+ "tops": ["top", "blouse", "t-shirt", "t_shirt", "topper", "blus", "shirt", "skjorte"],
19
+ "jackets": ["jacket", "coat", "jakke", "kåpe", "jacka", "blazer", "outerwear"],
20
+ "trousers": ["trouser", "pant", "bukse", "byxor", "jean", "short"],
21
+ "skirts": ["skirt", "skjørt", "kjol"],
22
+ "knitwear": ["knit", "sweater", "cardigan", "strikk", "genser"],
23
+ "shoes": ["shoe", "boot", "sandal", "sneaker", "heel", "loafer", "sko", "ballerina", "skor"],
24
+ "bags": ["bag", "veske", "väsk", "tote", "clutch", "wallet", "purse"],
25
+ }
26
+
27
+
28
+ def _category_patterns(category: str) -> list[str]:
29
+ """Return search patterns for a category label."""
30
+ key = category.lower().strip()
31
+ return _CATEGORY_MAP.get(key, [key])
32
+
33
 
34
  def _row_to_product(row) -> ProductOut:
35
  """Convert a DB row to ProductOut, parsing JSON fields."""
 
61
  page_size: int = Query(48, ge=1, le=200),
62
  store: str | None = None,
63
  brand: str | None = None,
64
+ category: str | None = None,
65
  min_score: float = 0,
66
  min_price: float | None = None,
67
  max_price: float | None = None,
 
97
  if max_price is not None:
98
  where.append("price_nok <= ?")
99
  params.append(max_price)
100
+ if category:
101
+ cat_patterns = _category_patterns(category)
102
+ cat_clauses = " OR ".join(
103
+ "(LOWER(category) LIKE ? OR LOWER(name) LIKE ?)" for _ in cat_patterns
104
+ )
105
+ where.append(f"({cat_clauses})")
106
+ for pat in cat_patterns:
107
+ params.extend([f"%{pat}%", f"%{pat}%"])
108
  if search:
109
  where.append("(brand LIKE ? OR name LIKE ?)")
110
  params.extend([f"%{search}%", f"%{search}%"])
 
172
  return [{"name": r["brand"], "count": r["cnt"]} for r in rows]
173
 
174
 
175
+ @router.get("/categories")
176
+ def list_categories():
177
+ """Return curated category list with estimated product counts."""
178
+ db = get_store()
179
+ conn = db.conn
180
+ results = []
181
+ for label, patterns in _CATEGORY_MAP.items():
182
+ clauses = " OR ".join(
183
+ "(LOWER(category) LIKE ? OR LOWER(name) LIKE ?)" for _ in patterns
184
+ )
185
+ params = []
186
+ for pat in patterns:
187
+ params.extend([f"%{pat}%", f"%{pat}%"])
188
+ count = conn.execute(
189
+ f"SELECT COUNT(*) FROM products WHERE score IS NOT NULL AND in_stock = 1 AND ({clauses})",
190
+ params,
191
+ ).fetchone()[0]
192
+ if count > 0:
193
+ results.append({"name": label, "count": count})
194
+ results.sort(key=lambda x: x["count"], reverse=True)
195
+ return results
196
+
197
+
198
  @router.get("/price-range")
199
  def price_range():
200
  db = get_store()
frontend/src/api.ts CHANGED
@@ -24,6 +24,7 @@ export async function getProducts(params: {
24
  page_size?: number;
25
  store?: string;
26
  brand?: string;
 
27
  sort?: string;
28
  min_score?: number;
29
  min_price?: number;
@@ -35,6 +36,7 @@ export async function getProducts(params: {
35
  if (params.page_size) sp.set("page_size", String(params.page_size));
36
  if (params.store) sp.set("store", params.store);
37
  if (params.brand) sp.set("brand", params.brand);
 
38
  if (params.sort) sp.set("sort", params.sort);
39
  if (params.min_score !== undefined) sp.set("min_score", String(params.min_score));
40
  if (params.min_price !== undefined) sp.set("min_price", String(params.min_price));
@@ -51,6 +53,10 @@ export async function getBrands(): Promise<{ name: string; count: number }[]> {
51
  return request("/products/brands");
52
  }
53
 
 
 
 
 
54
  export async function getPriceRange(): Promise<{ min: number; max: number }> {
55
  return request("/products/price-range");
56
  }
 
24
  page_size?: number;
25
  store?: string;
26
  brand?: string;
27
+ category?: string;
28
  sort?: string;
29
  min_score?: number;
30
  min_price?: number;
 
36
  if (params.page_size) sp.set("page_size", String(params.page_size));
37
  if (params.store) sp.set("store", params.store);
38
  if (params.brand) sp.set("brand", params.brand);
39
+ if (params.category) sp.set("category", params.category);
40
  if (params.sort) sp.set("sort", params.sort);
41
  if (params.min_score !== undefined) sp.set("min_score", String(params.min_score));
42
  if (params.min_price !== undefined) sp.set("min_price", String(params.min_price));
 
53
  return request("/products/brands");
54
  }
55
 
56
+ export async function getCategories(): Promise<{ name: string; count: number }[]> {
57
+ return request("/products/categories");
58
+ }
59
+
60
  export async function getPriceRange(): Promise<{ min: number; max: number }> {
61
  return request("/products/price-range");
62
  }
frontend/src/index.css CHANGED
@@ -310,6 +310,30 @@ select:focus {
310
  color: #fff;
311
  }
312
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
  /* ---------- Product grid ---------- */
314
  .product-grid {
315
  display: grid;
 
310
  color: #fff;
311
  }
312
 
313
+ /* ---------- Category pills ---------- */
314
+ .category-pills {
315
+ display: flex;
316
+ flex-wrap: wrap;
317
+ gap: 6px;
318
+ margin-bottom: 20px;
319
+ }
320
+
321
+ .pill-category {
322
+ display: inline-flex;
323
+ align-items: center;
324
+ gap: 6px;
325
+ }
326
+
327
+ .pill-count {
328
+ font-size: 11px;
329
+ color: var(--text-muted);
330
+ font-weight: 400;
331
+ }
332
+
333
+ .pill-category.active .pill-count {
334
+ color: rgba(255, 255, 255, 0.7);
335
+ }
336
+
337
  /* ---------- Product grid ---------- */
338
  .product-grid {
339
  display: grid;
frontend/src/pages/BrowsePage.tsx CHANGED
@@ -1,5 +1,5 @@
1
  import { useState, useEffect, useCallback } from "react";
2
- import { getProducts, getStores, getBrands, getPriceRange } from "../api";
3
  import type { Product, StoreInfo } from "../types";
4
 
5
  function scoreBadgeClass(score: number): string {
@@ -69,6 +69,7 @@ export function BrowsePage() {
69
  const [page, setPage] = useState(1);
70
  const [pageSize] = useState(48);
71
  const [store, setStore] = useState("");
 
72
  const [brand, setBrand] = useState("");
73
  const [sort, setSort] = useState("score");
74
  const [search, setSearch] = useState("");
@@ -76,6 +77,7 @@ export function BrowsePage() {
76
  const [minPrice, setMinPrice] = useState<number | undefined>(undefined);
77
  const [maxPrice, setMaxPrice] = useState<number | undefined>(undefined);
78
  const [stores, setStores] = useState<StoreInfo[]>([]);
 
79
  const [brands, setBrands] = useState<{ name: string; count: number }[]>([]);
80
  const [priceRange, setPriceRange] = useState({ min: 0, max: 50000 });
81
  const [loading, setLoading] = useState(true);
@@ -83,6 +85,7 @@ export function BrowsePage() {
83
 
84
  useEffect(() => {
85
  getStores().then(setStores).catch(console.error);
 
86
  getBrands().then(setBrands).catch(console.error);
87
  getPriceRange().then(setPriceRange).catch(console.error);
88
  }, []);
@@ -95,6 +98,7 @@ export function BrowsePage() {
95
  page_size: pageSize,
96
  store: store || undefined,
97
  brand: brand || undefined,
 
98
  sort,
99
  min_score: 0.01,
100
  min_price: minPrice,
@@ -108,7 +112,7 @@ export function BrowsePage() {
108
  } finally {
109
  setLoading(false);
110
  }
111
- }, [page, pageSize, store, brand, sort, search, minPrice, maxPrice]);
112
 
113
  useEffect(() => {
114
  fetchProducts();
@@ -116,10 +120,11 @@ export function BrowsePage() {
116
 
117
  const totalPages = Math.ceil(total / pageSize);
118
 
119
- const activeFilterCount = [store, brand, minPrice, maxPrice].filter(Boolean).length;
120
 
121
  function resetFilters() {
122
  setStore("");
 
123
  setBrand("");
124
  setMinPrice(undefined);
125
  setMaxPrice(undefined);
@@ -160,6 +165,28 @@ export function BrowsePage() {
160
  ))}
161
  </div>
162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  {/* Search + sort + filter toggle */}
164
  <div className="controls">
165
  <form onSubmit={handleSearch} style={{ display: "contents" }}>
 
1
  import { useState, useEffect, useCallback } from "react";
2
+ import { getProducts, getStores, getBrands, getCategories, getPriceRange } from "../api";
3
  import type { Product, StoreInfo } from "../types";
4
 
5
  function scoreBadgeClass(score: number): string {
 
69
  const [page, setPage] = useState(1);
70
  const [pageSize] = useState(48);
71
  const [store, setStore] = useState("");
72
+ const [category, setCategory] = useState("");
73
  const [brand, setBrand] = useState("");
74
  const [sort, setSort] = useState("score");
75
  const [search, setSearch] = useState("");
 
77
  const [minPrice, setMinPrice] = useState<number | undefined>(undefined);
78
  const [maxPrice, setMaxPrice] = useState<number | undefined>(undefined);
79
  const [stores, setStores] = useState<StoreInfo[]>([]);
80
+ const [categories, setCategories] = useState<{ name: string; count: number }[]>([]);
81
  const [brands, setBrands] = useState<{ name: string; count: number }[]>([]);
82
  const [priceRange, setPriceRange] = useState({ min: 0, max: 50000 });
83
  const [loading, setLoading] = useState(true);
 
85
 
86
  useEffect(() => {
87
  getStores().then(setStores).catch(console.error);
88
+ getCategories().then(setCategories).catch(console.error);
89
  getBrands().then(setBrands).catch(console.error);
90
  getPriceRange().then(setPriceRange).catch(console.error);
91
  }, []);
 
98
  page_size: pageSize,
99
  store: store || undefined,
100
  brand: brand || undefined,
101
+ category: category || undefined,
102
  sort,
103
  min_score: 0.01,
104
  min_price: minPrice,
 
112
  } finally {
113
  setLoading(false);
114
  }
115
+ }, [page, pageSize, store, brand, category, sort, search, minPrice, maxPrice]);
116
 
117
  useEffect(() => {
118
  fetchProducts();
 
120
 
121
  const totalPages = Math.ceil(total / pageSize);
122
 
123
+ const activeFilterCount = [store, brand, category, minPrice, maxPrice].filter(Boolean).length;
124
 
125
  function resetFilters() {
126
  setStore("");
127
+ setCategory("");
128
  setBrand("");
129
  setMinPrice(undefined);
130
  setMaxPrice(undefined);
 
165
  ))}
166
  </div>
167
 
168
+ {/* Category pills */}
169
+ {categories.length > 0 && (
170
+ <div className="category-pills">
171
+ <button
172
+ className={`pill pill-category ${category === "" ? "active" : ""}`}
173
+ onClick={() => { setCategory(""); setPage(1); }}
174
+ >
175
+ All
176
+ </button>
177
+ {categories.map((c) => (
178
+ <button
179
+ key={c.name}
180
+ className={`pill pill-category ${category === c.name ? "active" : ""}`}
181
+ onClick={() => { setCategory(c.name); setPage(1); }}
182
+ >
183
+ {c.name.charAt(0).toUpperCase() + c.name.slice(1)}
184
+ <span className="pill-count">{c.count.toLocaleString()}</span>
185
+ </button>
186
+ ))}
187
+ </div>
188
+ )}
189
+
190
  {/* Search + sort + filter toggle */}
191
  <div className="controls">
192
  <form onSubmit={handleSearch} style={{ display: "contents" }}>
pyproject.toml CHANGED
@@ -15,6 +15,7 @@ dependencies = [
15
  "fastapi>=0.110",
16
  "uvicorn[standard]>=0.27",
17
  "python-multipart>=0.0.6",
 
18
  ]
19
 
20
  [project.optional-dependencies]
 
15
  "fastapi>=0.110",
16
  "uvicorn[standard]>=0.27",
17
  "python-multipart>=0.0.6",
18
+ "curl-cffi>=0.15.0",
19
  ]
20
 
21
  [project.optional-dependencies]
taste/config.py CHANGED
@@ -145,15 +145,23 @@ def load_profile(name: str = "default", config: Config | None = None) -> UserPro
145
 
146
 
147
  def _default_config() -> Config:
148
- """Sensible defaults matching the current Norwegian bag stores."""
149
  return Config(
150
  data_dir=_default_data_dir(),
151
  stores={
152
  "wakakuu": StoreConfig(
153
  name="wakakuu", type="api",
154
  base_url="https://www.wakakuu.com",
155
- categories=["categories.lvl0:Väskor"],
156
- max_products=3000,
 
 
 
 
 
 
 
 
157
  extra={
158
  "algolia_app_id": "0LM8YN9I0K",
159
  "algolia_api_key": "00ef309f4d1543ffdaa1d85c33111700",
@@ -165,12 +173,15 @@ def _default_config() -> Config:
165
  base_url="https://www.boozt.com",
166
  categories=[
167
  "/no/no/kvinner/vesker",
168
- "/no/no/kvinner/vesker/skuldervesker",
169
- "/no/no/kvinner/vesker/haandvesker",
170
- "/no/no/kvinner/vesker/crossbody-vesker",
 
 
 
 
171
  ],
172
  max_products=5000,
173
- extra={"material_filter": "ekte-skinn"},
174
  ),
175
  "miinto": StoreConfig(
176
  name="miinto", type="api",
@@ -178,7 +189,12 @@ def _default_config() -> Config:
178
  categories=[
179
  "/dame-skuldervesker",
180
  "/dame-handvesker",
181
- "/dame-clutch-vesker",
 
 
 
 
 
182
  ],
183
  max_products=5000,
184
  ),
@@ -187,9 +203,78 @@ def _default_config() -> Config:
187
  base_url="https://www.na-kd.com",
188
  categories=[
189
  "/no/category/vesker",
190
- "/no/category/vesker/skuldervesker",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  ],
192
- max_products=2000,
193
  ),
194
  },
195
  )
 
145
 
146
 
147
  def _default_config() -> Config:
148
+ """Sensible defaults — Norwegian women's fashion stores."""
149
  return Config(
150
  data_dir=_default_data_dir(),
151
  stores={
152
  "wakakuu": StoreConfig(
153
  name="wakakuu", type="api",
154
  base_url="https://www.wakakuu.com",
155
+ categories=[
156
+ "categories.lvl0:Väskor",
157
+ "categories.lvl0:Klänningar",
158
+ "categories.lvl0:Jackor",
159
+ "categories.lvl0:Toppar",
160
+ "categories.lvl0:Byxor",
161
+ "categories.lvl0:Kjolar",
162
+ "categories.lvl0:Skor",
163
+ ],
164
+ max_products=5000,
165
  extra={
166
  "algolia_app_id": "0LM8YN9I0K",
167
  "algolia_api_key": "00ef309f4d1543ffdaa1d85c33111700",
 
173
  base_url="https://www.boozt.com",
174
  categories=[
175
  "/no/no/kvinner/vesker",
176
+ "/no/no/kvinner/klaer/kjoler",
177
+ "/no/no/kvinner/klaer/jakker-og-kaaper",
178
+ "/no/no/kvinner/klaer/topper",
179
+ "/no/no/kvinner/klaer/bukser",
180
+ "/no/no/kvinner/klaer/skjoert",
181
+ "/no/no/kvinner/klaer/strikk",
182
+ "/no/no/kvinner/sko",
183
  ],
184
  max_products=5000,
 
185
  ),
186
  "miinto": StoreConfig(
187
  name="miinto", type="api",
 
189
  categories=[
190
  "/dame-skuldervesker",
191
  "/dame-handvesker",
192
+ "/dame-kjoler",
193
+ "/dame-jakker",
194
+ "/dame-bluser-og-topper",
195
+ "/dame-bukser",
196
+ "/dame-skjort",
197
+ "/dame-sko",
198
  ],
199
  max_products=5000,
200
  ),
 
203
  base_url="https://www.na-kd.com",
204
  categories=[
205
  "/no/category/vesker",
206
+ "/no/category/kjoler",
207
+ "/no/category/jakker-og-kaper",
208
+ "/no/category/topper",
209
+ "/no/category/bukser",
210
+ "/no/category/skjort",
211
+ "/no/category/sko",
212
+ ],
213
+ max_products=5000,
214
+ ),
215
+ "stories": StoreConfig(
216
+ name="stories", type="api",
217
+ base_url="https://www.stories.com",
218
+ categories=[
219
+ "/en-no/bags/",
220
+ "/en-no/clothing/dresses/",
221
+ "/en-no/clothing/jackets-coats/",
222
+ "/en-no/clothing/tops/",
223
+ "/en-no/clothing/trousers/",
224
+ "/en-no/clothing/skirts/",
225
+ "/en-no/clothing/knitwear/",
226
+ "/en-no/shoes/",
227
+ ],
228
+ max_products=5000,
229
+ ),
230
+ "cos": StoreConfig(
231
+ name="cos", type="api",
232
+ base_url="https://www.cos.com",
233
+ categories=[
234
+ "/en-no/women/view-all",
235
+ ],
236
+ max_products=5000,
237
+ ),
238
+ "zalando": StoreConfig(
239
+ name="zalando", type="api",
240
+ base_url="https://www.zalando.no",
241
+ categories=[
242
+ "/dameklaer/",
243
+ "/damesko/",
244
+ "/vesker/",
245
+ ],
246
+ max_products=5000,
247
+ ),
248
+ "ellos": StoreConfig(
249
+ name="ellos", type="api",
250
+ base_url="https://www.ellos.no",
251
+ categories=[
252
+ "/dame/kjoler",
253
+ "/dame/bukser",
254
+ "/dame/topper-singleter",
255
+ "/dame/jakker-kaper",
256
+ "/dame/skjorter-bluser",
257
+ "/dame/gensere-cardigans",
258
+ "/dame/skjort",
259
+ "/dame/sko",
260
+ "/dame/vesker-accessoirer",
261
+ ],
262
+ max_products=5000,
263
+ ),
264
+ "nelly": StoreConfig(
265
+ name="nelly", type="api",
266
+ base_url="https://nelly.com",
267
+ categories=[
268
+ "/kjoler/",
269
+ "/topper-t-shirts/",
270
+ "/bukser/",
271
+ "/jakker/",
272
+ "/skjort/",
273
+ "/gensere/",
274
+ "/bluser-og-skjorter/",
275
+ "/sko/",
276
  ],
277
+ max_products=5000,
278
  ),
279
  },
280
  )
taste/engine.py CHANGED
@@ -144,33 +144,54 @@ class TasteEngine:
144
  return results
145
 
146
  # --- Ratings ---
 
147
 
148
  def load_ratings(self) -> dict[str, int]:
 
 
 
 
 
149
  if self.ratings_path.exists():
150
  return json.loads(self.ratings_path.read_text())
151
  return {}
152
 
153
- def save_rating(self, path: Path, rating: int):
154
- ratings = self.load_ratings()
155
- ratings[str(Path(path).resolve())] = rating
156
- self.ratings_path.write_text(json.dumps(ratings, indent=2))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  def clear_ratings(self, paths: list[Path] | None = None):
159
  if paths is None:
160
  self.ratings_path.write_text("{}")
161
  return
162
- ratings = self.load_ratings()
163
  for p in paths:
164
- ratings.pop(str(Path(p).resolve()), None)
165
- self.ratings_path.write_text(json.dumps(ratings, indent=2))
166
 
167
  def seed_from_references(self, folder: Path):
168
- ratings = self.load_ratings()
169
  images = find_images(folder)
170
  seeded = 0
171
  for img in images:
172
  key = str(img.resolve())
173
- if key not in ratings:
174
  self.save_rating(img, 1)
175
  seeded += 1
176
  return seeded
@@ -185,7 +206,7 @@ class TasteEngine:
185
  # --- Taste model (multi-centroid HDBSCAN + MaxSim) ---
186
 
187
  def build_taste_vector(self) -> list[np.ndarray] | None:
188
- """Build multi-centroid taste model. Returns list of centroid vectors."""
189
  ratings = self.load_ratings()
190
  liked = []
191
  for path_str, rating in ratings.items():
@@ -198,38 +219,68 @@ class TasteEngine:
198
  return None
199
  return self._cluster_centroids(np.array(liked))
200
 
201
- def build_taste_model(self, text_queries: list[str] | None = None) -> dict | None:
202
- """Build full taste model with optional text injection.
203
 
204
- Returns dict with centroids, dim_weights, text_vectors, metadata.
 
 
205
  """
206
- ratings = self.load_ratings()
207
- liked_embs = []
208
- for path_str, rating in ratings.items():
 
 
209
  p = Path(path_str)
210
- if not p.exists() or rating != 1:
211
  continue
212
- liked_embs.append(self.encode(p))
213
-
214
- if not liked_embs:
215
- return None
216
-
217
- liked_arr = np.array(liked_embs)
218
- centroids = self._cluster_centroids(liked_arr)
219
- dim_weights = self._compute_dim_weights(liked_arr)
220
-
221
- text_vectors = []
222
- if text_queries:
223
- for q in text_queries:
224
- text_vectors.append(self.encode_text(q))
225
-
226
- return {
227
- "centroids": centroids,
228
- "dim_weights": dim_weights,
229
- "text_vectors": text_vectors,
230
- "n_liked": len(liked_embs),
231
- "n_clusters": len(centroids),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  }
 
 
 
 
233
 
234
  def _cluster_centroids(self, embeddings: np.ndarray) -> list[np.ndarray]:
235
  n = len(embeddings)
@@ -287,3 +338,56 @@ class TasteEngine:
287
  scores.append((p, s))
288
  scores.sort(key=lambda x: x[1], reverse=True)
289
  return scores
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  return results
145
 
146
  # --- Ratings ---
147
+ # Each entry is either an int (legacy) or {"rating": int, "category": str}.
148
 
149
  def load_ratings(self) -> dict[str, int]:
150
+ """Load ratings as a flat {path: int} dict (legacy-compatible)."""
151
+ raw = self._load_ratings_raw()
152
+ return {k: self._rating_val(v) for k, v in raw.items()}
153
+
154
+ def _load_ratings_raw(self) -> dict:
155
  if self.ratings_path.exists():
156
  return json.loads(self.ratings_path.read_text())
157
  return {}
158
 
159
+ @staticmethod
160
+ def _rating_val(entry) -> int:
161
+ if isinstance(entry, int):
162
+ return entry
163
+ if isinstance(entry, dict):
164
+ return entry.get("rating", 0)
165
+ return 0
166
+
167
+ @staticmethod
168
+ def _rating_cat(entry) -> str:
169
+ if isinstance(entry, dict):
170
+ return entry.get("category", "")
171
+ return ""
172
+
173
+ def save_rating(self, path: Path, rating: int, category: str = ""):
174
+ raw = self._load_ratings_raw()
175
+ key = str(Path(path).resolve())
176
+ raw[key] = {"rating": rating, "category": category}
177
+ self.ratings_path.write_text(json.dumps(raw, indent=2))
178
 
179
  def clear_ratings(self, paths: list[Path] | None = None):
180
  if paths is None:
181
  self.ratings_path.write_text("{}")
182
  return
183
+ raw = self._load_ratings_raw()
184
  for p in paths:
185
+ raw.pop(str(Path(p).resolve()), None)
186
+ self.ratings_path.write_text(json.dumps(raw, indent=2))
187
 
188
  def seed_from_references(self, folder: Path):
189
+ raw = self._load_ratings_raw()
190
  images = find_images(folder)
191
  seeded = 0
192
  for img in images:
193
  key = str(img.resolve())
194
+ if key not in raw:
195
  self.save_rating(img, 1)
196
  seeded += 1
197
  return seeded
 
206
  # --- Taste model (multi-centroid HDBSCAN + MaxSim) ---
207
 
208
  def build_taste_vector(self) -> list[np.ndarray] | None:
209
+ """Build unified multi-centroid taste model. Returns list of centroid vectors."""
210
  ratings = self.load_ratings()
211
  liked = []
212
  for path_str, rating in ratings.items():
 
219
  return None
220
  return self._cluster_centroids(np.array(liked))
221
 
222
+ def build_category_taste(self) -> dict:
223
+ """Build per-category centroids + unified fallback.
224
 
225
+ Returns {"categories": {cat: [centroids]}, "unified": [centroids]}
226
+ where unified is built from ALL liked images across categories.
227
+ Categories with no liked images won't have an entry.
228
  """
229
+ raw = self._load_ratings_raw()
230
+ all_liked = []
231
+ by_cat: dict[str, list[np.ndarray]] = {}
232
+
233
+ for path_str, entry in raw.items():
234
  p = Path(path_str)
235
+ if not p.exists() or self._rating_val(entry) != 1:
236
  continue
237
+ emb = self.encode(p)
238
+ all_liked.append(emb)
239
+
240
+ cat = self._normalize_category(self._rating_cat(entry))
241
+ if cat:
242
+ by_cat.setdefault(cat, []).append(emb)
243
+
244
+ if not all_liked:
245
+ return {"categories": {}, "unified": None}
246
+
247
+ # Per-category centroids (simple mean — categories typically have few examples)
248
+ cat_centroids = {}
249
+ for cat, embs in by_cat.items():
250
+ arr = np.array(embs)
251
+ if len(arr) >= 3:
252
+ cat_centroids[cat] = self._cluster_centroids(arr)
253
+ else:
254
+ c = np.mean(arr, axis=0)
255
+ cat_centroids[cat] = [c / np.linalg.norm(c)]
256
+
257
+ # Unified fallback from all liked images
258
+ unified = self._cluster_centroids(np.array(all_liked))
259
+
260
+ return {"categories": cat_centroids, "unified": unified}
261
+
262
+ @staticmethod
263
+ def _normalize_category(raw_cat: str) -> str:
264
+ """Map raw category strings to canonical names for centroid grouping."""
265
+ if not raw_cat:
266
+ return ""
267
+ low = raw_cat.lower()
268
+ # Map common patterns to canonical category names
269
+ _PATTERNS = {
270
+ "bags": ["bag", "veske", "väsk", "tote", "clutch", "wallet", "purse", "shoulder"],
271
+ "dresses": ["dress", "kjoler", "kjole", "klänning"],
272
+ "tops": ["top", "blouse", "t-shirt", "t_shirt", "topper", "blus", "shirt", "skjorte"],
273
+ "jackets": ["jacket", "coat", "jakke", "kåpe", "jacka", "blazer", "outerwear", "trench"],
274
+ "trousers": ["trouser", "pant", "bukse", "byxor", "jean", "short"],
275
+ "skirts": ["skirt", "skjørt", "kjol"],
276
+ "knitwear": ["knit", "sweater", "cardigan", "strikk", "genser"],
277
+ "shoes": ["shoe", "boot", "sandal", "sneaker", "heel", "loafer", "sko",
278
+ "ballerina", "skor", "pump"],
279
  }
280
+ for canonical, patterns in _PATTERNS.items():
281
+ if any(p in low for p in patterns):
282
+ return canonical
283
+ return raw_cat.strip().lower()
284
 
285
  def _cluster_centroids(self, embeddings: np.ndarray) -> list[np.ndarray]:
286
  n = len(embeddings)
 
338
  scores.append((p, s))
339
  scores.sort(key=lambda x: x[1], reverse=True)
340
  return scores
341
+
342
+ def score_products_by_category(
343
+ self,
344
+ products: list[dict],
345
+ taste: dict,
346
+ ) -> list[dict]:
347
+ """Score products using per-category centroids with unified fallback.
348
+
349
+ Args:
350
+ products: list of dicts with at least 'image_path' and 'category' keys.
351
+ taste: output of build_category_taste().
352
+
353
+ Returns:
354
+ list of dicts with 'image_path' and 'score' keys.
355
+ """
356
+ cat_centroids = taste.get("categories", {})
357
+ unified = taste.get("unified")
358
+ if not unified:
359
+ return []
360
+
361
+ paths = []
362
+ path_to_cat = {}
363
+ for p in products:
364
+ img = Path(p["image_path"])
365
+ if img.exists():
366
+ paths.append(img)
367
+ raw_cat = p.get("category", "")
368
+ path_to_cat[str(img)] = self._normalize_category(raw_cat)
369
+
370
+ if not paths:
371
+ return []
372
+
373
+ embeddings = self.encode_batch(paths)
374
+ unified_arr = np.array(unified)
375
+
376
+ results = []
377
+ for p in paths:
378
+ key = str(p)
379
+ if key not in embeddings:
380
+ continue
381
+ emb = embeddings[key]
382
+ cat = path_to_cat.get(key, "")
383
+
384
+ # Use category-specific centroids if available, else unified
385
+ if cat and cat in cat_centroids:
386
+ c_arr = np.array(cat_centroids[cat])
387
+ else:
388
+ c_arr = unified_arr
389
+
390
+ s = float(np.max(emb @ c_arr.T))
391
+ results.append({"image_path": key, "score": s})
392
+
393
+ return results
taste/pipeline.py CHANGED
@@ -36,21 +36,25 @@ def run_scan(config: Config, profile: UserProfile, output_path: Path | None = No
36
  _download_liked_urls(engine, profile, config)
37
  print(f" Taste profile: {engine.stats()}", flush=True)
38
 
39
- # Step 2: Build taste model
40
  print("\n[2/5] Building taste model...", flush=True)
41
- centroids = engine.build_taste_vector()
42
- if centroids is None:
43
  print("ERROR: No taste vector! Add reference images first.", flush=True)
44
  sys.exit(1)
45
- print(f" {len(centroids)} taste clusters", flush=True)
 
 
 
 
46
 
47
  # Step 3: Scrape enabled stores
48
  print("\n[3/5] Scraping stores...", flush=True)
49
  new_count = _run_scrapers(config, profile, store)
50
 
51
- # Step 4: Score unscored products
52
- print("\n[4/5] Scoring with FashionSigLIP...", flush=True)
53
- _score_unscored(engine, store, centroids, config.batch_size)
54
 
55
  # Step 5: Generate HTML
56
  print("\n[5/5] Generating results...", flush=True)
@@ -140,9 +144,9 @@ def _run_scrapers(config: Config, profile: UserProfile, store: ProductStore) ->
140
  return len(all_new)
141
 
142
 
143
- def _score_unscored(engine: TasteEngine, store: ProductStore, centroids: list, batch_size: int = 50):
144
- """Score products that have images but no score."""
145
- rows = store.get_unscored()
146
  if not rows:
147
  print(" No unscored products.", flush=True)
148
  return
@@ -151,21 +155,22 @@ def _score_unscored(engine: TasteEngine, store: ProductStore, centroids: list, b
151
 
152
  for i in range(0, len(rows), batch_size):
153
  batch = rows[i : i + batch_size]
154
- paths, urls = [], []
 
155
  for r in batch:
156
  p = Path(r["image_path"])
157
  if p.exists():
158
- paths.append(p)
159
  urls.append(r["url"])
160
 
161
- if not paths:
162
  continue
163
 
164
- scored = engine.score_product_images(paths, centroids)
165
- score_map = {str(path): score for path, score in scored}
166
 
167
- for url, path in zip(urls, paths):
168
- s = score_map.get(str(path), 0)
169
  store.update_score(url, s)
170
  store.commit()
171
 
 
36
  _download_liked_urls(engine, profile, config)
37
  print(f" Taste profile: {engine.stats()}", flush=True)
38
 
39
+ # Step 2: Build taste model (per-category + unified fallback)
40
  print("\n[2/5] Building taste model...", flush=True)
41
+ taste = engine.build_category_taste()
42
+ if taste["unified"] is None:
43
  print("ERROR: No taste vector! Add reference images first.", flush=True)
44
  sys.exit(1)
45
+ n_cats = len(taste["categories"])
46
+ n_unified = len(taste["unified"])
47
+ print(f" {n_cats} category profiles, {n_unified} unified clusters", flush=True)
48
+ for cat, cents in taste["categories"].items():
49
+ print(f" {cat}: {len(cents)} centroids", flush=True)
50
 
51
  # Step 3: Scrape enabled stores
52
  print("\n[3/5] Scraping stores...", flush=True)
53
  new_count = _run_scrapers(config, profile, store)
54
 
55
+ # Step 4: Score unscored products (per-category)
56
+ print("\n[4/5] Scoring with FashionSigLIP (per-category)...", flush=True)
57
+ _score_unscored(engine, store, taste, config.batch_size)
58
 
59
  # Step 5: Generate HTML
60
  print("\n[5/5] Generating results...", flush=True)
 
144
  return len(all_new)
145
 
146
 
147
+ def _score_unscored(engine: TasteEngine, store: ProductStore, taste: dict, batch_size: int = 50):
148
+ """Score products using per-category centroids with unified fallback."""
149
+ rows = store.get_unscored_with_category()
150
  if not rows:
151
  print(" No unscored products.", flush=True)
152
  return
 
155
 
156
  for i in range(0, len(rows), batch_size):
157
  batch = rows[i : i + batch_size]
158
+ products = []
159
+ urls = []
160
  for r in batch:
161
  p = Path(r["image_path"])
162
  if p.exists():
163
+ products.append({"image_path": r["image_path"], "category": r.get("category", "")})
164
  urls.append(r["url"])
165
 
166
+ if not products:
167
  continue
168
 
169
+ scored = engine.score_products_by_category(products, taste)
170
+ score_map = {s["image_path"]: s["score"] for s in scored}
171
 
172
+ for url, prod in zip(urls, products):
173
+ s = score_map.get(prod["image_path"], 0)
174
  store.update_score(url, s)
175
  store.commit()
176
 
taste/scrapers/__init__.py CHANGED
@@ -26,6 +26,21 @@ def _get_api_scraper(sc: StoreConfig):
26
  elif name == "nakd":
27
  from taste.scrapers.api.nakd import NakdScraper
28
  return NakdScraper(sc)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  raise ValueError(f"No API scraper for store: {sc.name}")
30
 
31
 
 
26
  elif name == "nakd":
27
  from taste.scrapers.api.nakd import NakdScraper
28
  return NakdScraper(sc)
29
+ elif name == "stories" or name == "& other stories":
30
+ from taste.scrapers.api.stories import StoriesScraper
31
+ return StoriesScraper(sc)
32
+ elif name == "cos":
33
+ from taste.scrapers.api.cos import CosScraper
34
+ return CosScraper(sc)
35
+ elif name == "zalando":
36
+ from taste.scrapers.api.zalando import ZalandoScraper
37
+ return ZalandoScraper(sc)
38
+ elif name == "ellos":
39
+ from taste.scrapers.api.ellos import EllosScraper
40
+ return EllosScraper(sc)
41
+ elif name == "nelly":
42
+ from taste.scrapers.api.nelly import NellyScraper
43
+ return NellyScraper(sc)
44
  raise ValueError(f"No API scraper for store: {sc.name}")
45
 
46
 
taste/scrapers/api/cos.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """COS scraper — Centra platform, __NEXT_DATA__ extraction via curl_cffi."""
2
+
3
+ import json
4
+ import re
5
+ import time
6
+
7
+ from curl_cffi import requests as curl_requests
8
+
9
+ from taste.scrapers.base import BaseScraper
10
+
11
+
12
+ class CosScraper(BaseScraper):
13
+ def scrape(self, categories: list[str] | None = None, max_products: int | None = None) -> list[dict]:
14
+ categories = categories or self.config.categories
15
+ max_products = max_products or self.config.max_products
16
+ base_url = self.config.base_url or "https://www.cos.com"
17
+
18
+ products = []
19
+ seen_urls = set()
20
+
21
+ session = curl_requests.Session(impersonate="safari_ios")
22
+ try:
23
+ # Warm up session with homepage cookies
24
+ session.get(f"{base_url}/en-no/", timeout=30)
25
+ time.sleep(0.3)
26
+
27
+ for cat in categories:
28
+ cat_url = cat if cat.startswith("http") else f"{base_url}{cat}"
29
+ page_num = 1
30
+ total_pages = None
31
+
32
+ while len(products) < max_products:
33
+ url = f"{cat_url}?page={page_num}" if page_num > 1 else cat_url
34
+ try:
35
+ resp = session.get(url, timeout=30)
36
+ if resp.status_code != 200:
37
+ print(f" COS: {cat} page {page_num} returned {resp.status_code}", flush=True)
38
+ break
39
+ except Exception as e:
40
+ print(f" COS: error fetching {cat} page {page_num}: {e}", flush=True)
41
+ break
42
+
43
+ next_data = self._extract_next_data(resp.text)
44
+ if not next_data:
45
+ print(f" COS: no __NEXT_DATA__ for {cat} page {page_num}", flush=True)
46
+ break
47
+
48
+ page_props = next_data.get("props", {}).get("pageProps", {})
49
+ items, total_count, per_page = self._find_products(page_props)
50
+
51
+ if total_pages is None and per_page and total_count:
52
+ total_pages = -(-total_count // per_page)
53
+
54
+ if not items:
55
+ break
56
+
57
+ new_count = 0
58
+ for item in items:
59
+ product = self._parse_product(item, base_url)
60
+ if not product or product["url"] in seen_urls:
61
+ continue
62
+ seen_urls.add(product["url"])
63
+ products.append(product)
64
+ new_count += 1
65
+
66
+ cat_name = cat.rstrip("/").split("/")[-1] or "root"
67
+ print(f" COS: {cat_name} page {page_num}/{total_pages or '?'}, +{new_count}, {len(products)} total", flush=True)
68
+
69
+ if new_count == 0:
70
+ break
71
+ page_num += 1
72
+ if total_pages and page_num > total_pages:
73
+ break
74
+
75
+ time.sleep(0.3)
76
+ finally:
77
+ session.close()
78
+
79
+ return products
80
+
81
+ @staticmethod
82
+ def _extract_next_data(html: str) -> dict | None:
83
+ m = re.search(r'<script[^>]*id="__NEXT_DATA__"[^>]*>(.*?)</script>', html, re.DOTALL)
84
+ if not m:
85
+ return None
86
+ try:
87
+ return json.loads(m.group(1))
88
+ except json.JSONDecodeError:
89
+ return None
90
+
91
+ @staticmethod
92
+ def _find_products(page_props: dict) -> tuple[list, int, int]:
93
+ """Find product list in category-page-block."""
94
+ blocks = page_props.get("blocks", [])
95
+ for block in blocks:
96
+ if block.get("component") == "category-page-block":
97
+ result = block.get("initialResult", {})
98
+ items = result.get("items", [])
99
+ total = int(result.get("totalItems", 0) or 0)
100
+ per_page = len(items) if items else 10
101
+ return (items, total, per_page)
102
+ return ([], 0, 0)
103
+
104
+ @staticmethod
105
+ def _parse_product(item: dict, base_url: str) -> dict | None:
106
+ uri = item.get("uri", "")
107
+ if not uri:
108
+ return None
109
+ url = f"{base_url}/en-no/product/{uri}"
110
+
111
+ # Images
112
+ images_raw = item.get("images", [])
113
+ image_urls = [img["src"] for img in images_raw if isinstance(img, dict) and img.get("src")]
114
+ primary = item.get("primaryImage", "")
115
+ if primary and primary not in image_urls:
116
+ image_urls.insert(0, primary)
117
+ image_url = image_urls[0] if image_urls else ""
118
+
119
+ # Price
120
+ price = float(item.get("priceAsNumber", 0) or 0)
121
+ original_price = float(item.get("priceBeforeDiscountAsNumber", 0) or 0)
122
+ on_sale = item.get("isOnSale", False) or (original_price > 0 and price < original_price)
123
+
124
+ # Color
125
+ color = item.get("variantName", "")
126
+
127
+ # Material from sustainabilityComposition
128
+ material = ""
129
+ composition = item.get("sustainabilityComposition")
130
+ if composition and isinstance(composition, list):
131
+ parts = []
132
+ for comp in composition:
133
+ comp_type = comp.get("type", "")
134
+ mats = comp.get("materials", [])
135
+ for mat in mats:
136
+ name = mat.get("material", "")
137
+ pct = mat.get("percentage", "")
138
+ if name:
139
+ parts.append(f"{pct}% {name}" if pct else name)
140
+ material = ", ".join(parts)
141
+
142
+ # Sizes
143
+ sizes_raw = item.get("sizes", "")
144
+ if isinstance(sizes_raw, list):
145
+ sizes = [s for s in sizes_raw if isinstance(s, str)]
146
+ elif isinstance(sizes_raw, str) and sizes_raw:
147
+ sizes = [s.strip() for s in sizes_raw.split(",") if s.strip()]
148
+ else:
149
+ sizes = []
150
+
151
+ # Stock
152
+ total_stock = item.get("totalStock", 0)
153
+ in_stock = int(total_stock or 0) > 0
154
+
155
+ # Category
156
+ category = item.get("categoryUri", "")
157
+
158
+ # External ID
159
+ sku = item.get("product_sku", item.get("sku", item.get("id", "")))
160
+
161
+ return {
162
+ "url": url,
163
+ "external_id": str(sku),
164
+ "image_url": image_url,
165
+ "image_urls": image_urls,
166
+ "brand": "COS",
167
+ "name": item.get("name", ""),
168
+ "color": color,
169
+ "material": material,
170
+ "category": category,
171
+ "price_nok": price,
172
+ "original_price_nok": original_price if on_sale else 0,
173
+ "price_text": f"{price:.0f} kr" if price else "",
174
+ "currency": "NOK",
175
+ "on_sale": on_sale,
176
+ "in_stock": in_stock,
177
+ "sizes": sizes,
178
+ "store": "COS",
179
+ }
taste/scrapers/api/ellos.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ellos.no scraper — Nuxt 3 SSR payload extraction."""
2
+
3
+ import json
4
+ import re
5
+ from urllib.parse import quote
6
+
7
+ import httpx
8
+
9
+ from taste.scrapers.base import BaseScraper
10
+
11
+ _HEADERS = {
12
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
13
+ }
14
+
15
+
16
+ class EllosScraper(BaseScraper):
17
+ def scrape(self, categories: list[str] | None = None, max_products: int | None = None) -> list[dict]:
18
+ categories = categories or self.config.categories
19
+ max_products = max_products or self.config.max_products
20
+ base_url = self.config.base_url or "https://www.ellos.no"
21
+
22
+ products = []
23
+ seen_urls = set()
24
+
25
+ with httpx.Client(timeout=30, headers=_HEADERS, follow_redirects=True) as client:
26
+ for cat in categories:
27
+ cat_url = cat if cat.startswith("http") else f"{base_url}{cat}"
28
+ page_num = 1
29
+ total_pages = None
30
+
31
+ while len(products) < max_products:
32
+ url = f"{cat_url}?page={page_num}" if page_num > 1 else cat_url
33
+ try:
34
+ resp = client.get(url)
35
+ if resp.status_code != 200:
36
+ print(f" Ellos: {cat} page {page_num} returned {resp.status_code}", flush=True)
37
+ break
38
+ except Exception as e:
39
+ print(f" Ellos: error fetching {cat} page {page_num}: {e}", flush=True)
40
+ break
41
+
42
+ payload = self._extract_payload(resp.text)
43
+ if not payload:
44
+ print(f" Ellos: no payload for {cat} page {page_num}", flush=True)
45
+ break
46
+
47
+ listing_key = f"display=full&path={quote(cat, safe='')}"
48
+ listing_ref = payload[3].get(listing_key)
49
+ if listing_ref is None:
50
+ # Try without encoding
51
+ for k in payload[3]:
52
+ if "display=full" in k and cat.strip("/") in k:
53
+ listing_ref = payload[3][k]
54
+ break
55
+ if listing_ref is None:
56
+ print(f" Ellos: no listing key for {cat}", flush=True)
57
+ break
58
+
59
+ def deref(val):
60
+ if isinstance(val, int) and 0 <= val < len(payload):
61
+ return payload[val]
62
+ return val
63
+
64
+ listing = deref(listing_ref)
65
+ if not isinstance(listing, dict):
66
+ break
67
+
68
+ articles = deref(listing.get("articles", []))
69
+ if not isinstance(articles, list) or not articles:
70
+ break
71
+
72
+ if total_pages is None:
73
+ pag = deref(listing.get("pagination", {}))
74
+ if isinstance(pag, dict):
75
+ total_pages = deref(pag.get("last", 1))
76
+
77
+ new_count = 0
78
+ for art_ref in articles:
79
+ art = deref(art_ref)
80
+ if not isinstance(art, dict):
81
+ continue
82
+ product = self._parse_product(art, deref, base_url)
83
+ if not product or product["url"] in seen_urls:
84
+ continue
85
+ seen_urls.add(product["url"])
86
+ products.append(product)
87
+ new_count += 1
88
+
89
+ cat_name = cat.strip("/").split("/")[-1] or "root"
90
+ print(f" Ellos: {cat_name} page {page_num}/{total_pages or '?'}, +{new_count}, {len(products)} total", flush=True)
91
+
92
+ if new_count == 0:
93
+ break
94
+ page_num += 1
95
+ if total_pages and page_num > total_pages:
96
+ break
97
+
98
+ return products
99
+
100
+ @staticmethod
101
+ def _extract_payload(html: str) -> list | None:
102
+ """Extract the Nuxt 3 JSON payload from the largest inline script."""
103
+ scripts = re.findall(r"<script[^>]*>(.*?)</script>", html, re.DOTALL)
104
+ if not scripts:
105
+ return None
106
+ largest = max(scripts, key=len)
107
+ if len(largest) < 10000:
108
+ return None
109
+ try:
110
+ data = json.loads(largest)
111
+ if isinstance(data, list) and len(data) > 4 and isinstance(data[3], dict):
112
+ return data
113
+ except (json.JSONDecodeError, IndexError):
114
+ pass
115
+ return None
116
+
117
+ @staticmethod
118
+ def _parse_product(art: dict, deref, base_url: str) -> dict | None:
119
+ url_path = deref(art.get("url", ""))
120
+ if not url_path:
121
+ return None
122
+ url = f"{base_url}{url_path}" if not url_path.startswith("http") else url_path
123
+
124
+ name = deref(art.get("name", ""))
125
+ brand = deref(art.get("brand", ""))
126
+ color = deref(art.get("color", ""))
127
+ sku = deref(art.get("id", ""))
128
+
129
+ # Images
130
+ image_urls = []
131
+ for img_key in ["imageFront", "imageAlternative", "imageFs"]:
132
+ img = deref(art.get(img_key))
133
+ if isinstance(img, dict):
134
+ card = deref(img.get("card", ""))
135
+ if card and isinstance(card, str):
136
+ image_urls.append(card.replace("{size}", "800"))
137
+ image_url = image_urls[0] if image_urls else ""
138
+
139
+ # Price and sizes from variants
140
+ variants = deref(art.get("variants", []))
141
+ if isinstance(variants, int):
142
+ variants = []
143
+ sizes = []
144
+ price = 0
145
+ original_price = 0
146
+ in_stock = False
147
+
148
+ if isinstance(variants, list):
149
+ for vr in variants:
150
+ v = deref(vr)
151
+ if not isinstance(v, dict):
152
+ continue
153
+ size = deref(v.get("size", ""))
154
+ if size and isinstance(size, str):
155
+ sizes.append(size)
156
+ stock = deref(v.get("inStock", False))
157
+ if stock:
158
+ in_stock = True
159
+ if not price:
160
+ p = deref(v.get("currentPrice", 0))
161
+ o = deref(v.get("originalPrice", 0))
162
+ if isinstance(p, (int, float)) and p > 0:
163
+ price = float(p)
164
+ if isinstance(o, (int, float)) and o > 0:
165
+ original_price = float(o)
166
+
167
+ on_sale = original_price > 0 and price < original_price
168
+
169
+ # Category from URL
170
+ parts = url_path.strip("/").split("/")
171
+ category = parts[1] if len(parts) > 2 else (parts[0] if parts else "")
172
+
173
+ return {
174
+ "url": url,
175
+ "external_id": str(sku),
176
+ "image_url": image_url,
177
+ "image_urls": image_urls,
178
+ "brand": brand or "Ellos",
179
+ "name": name,
180
+ "color": color,
181
+ "material": "",
182
+ "category": category,
183
+ "price_nok": price,
184
+ "original_price_nok": original_price if on_sale else 0,
185
+ "price_text": f"{price:.0f} kr" if price else "",
186
+ "currency": "NOK",
187
+ "on_sale": on_sale,
188
+ "in_stock": in_stock,
189
+ "sizes": sizes,
190
+ "store": "Ellos",
191
+ }
taste/scrapers/api/nelly.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Nelly.com scraper — Voyado Elevate API."""
2
+
3
+ import httpx
4
+
5
+ from taste.scrapers.base import BaseScraper
6
+
7
+ _API_BASE = "https://w67A8630F.api.esales.apptus.cloud/api/storefront/v3/queries"
8
+
9
+
10
+ class NellyScraper(BaseScraper):
11
+ def scrape(self, categories: list[str] | None = None, max_products: int | None = None) -> list[dict]:
12
+ categories = categories or self.config.categories
13
+ max_products = max_products or self.config.max_products
14
+ base_url = self.config.base_url or "https://nelly.com"
15
+
16
+ products = []
17
+ seen_urls = set()
18
+
19
+ with httpx.Client(timeout=30, follow_redirects=True) as client:
20
+ for cat in categories:
21
+ skip = 0
22
+ limit = 100
23
+
24
+ while len(products) < max_products:
25
+ try:
26
+ resp = client.post(
27
+ f"{_API_BASE}/landing-page",
28
+ params={
29
+ "market": "Nelly_Norway",
30
+ "sessionKey": "scraper",
31
+ "customerKey": "scraper",
32
+ "locale": "nb-NO",
33
+ "touchpoint": "desktop",
34
+ "pageReference": cat,
35
+ "limit": limit,
36
+ "skip": skip,
37
+ "presentPrices": "member",
38
+ "presentCustom": "filterColor|swatch|filterColorHex|categoryNode|isSellable",
39
+ },
40
+ content='{"navigation": {"include": false}, "recommendationLists": []}',
41
+ headers={"Content-Type": "text/plain"},
42
+ )
43
+ if resp.status_code != 200:
44
+ print(f" Nelly: {cat} skip={skip} returned {resp.status_code}", flush=True)
45
+ break
46
+ except Exception as e:
47
+ print(f" Nelly: error fetching {cat}: {e}", flush=True)
48
+ break
49
+
50
+ data = resp.json()
51
+ primary = data.get("primaryList", {})
52
+ total_hits = primary.get("totalHits", 0)
53
+ groups = primary.get("productGroups", [])
54
+
55
+ if not groups:
56
+ break
57
+
58
+ new_count = 0
59
+ for group in groups:
60
+ group_products = group.get("products", [])
61
+ if not group_products:
62
+ continue
63
+ item = group_products[0]
64
+ product = self._parse_product(item, base_url, cat)
65
+ if not product or product["url"] in seen_urls:
66
+ continue
67
+ seen_urls.add(product["url"])
68
+ products.append(product)
69
+ new_count += 1
70
+
71
+ cat_name = cat.strip("/").split("/")[-1] or "root"
72
+ total_pages = -(-total_hits // limit) if total_hits else "?"
73
+ current_page = skip // limit + 1
74
+ print(f" Nelly: {cat_name} page {current_page}/{total_pages}, +{new_count}, {len(products)} total", flush=True)
75
+
76
+ if new_count == 0:
77
+ break
78
+ skip += limit
79
+ if skip >= total_hits:
80
+ break
81
+
82
+ return products
83
+
84
+ @staticmethod
85
+ def _parse_product(item: dict, base_url: str, category: str) -> dict | None:
86
+ link = item.get("link", "")
87
+ if not link:
88
+ return None
89
+ url = f"{base_url}{link}" if not link.startswith("http") else link
90
+
91
+ key = item.get("key", "")
92
+ brand = item.get("brand", "")
93
+ name = item.get("title", "")
94
+
95
+ # Price
96
+ selling = item.get("sellingPrice", {})
97
+ listing = item.get("listPrice", {})
98
+ price = float(selling.get("min", 0) or 0)
99
+ original_price = float(listing.get("min", 0) or 0)
100
+ on_sale = original_price > 0 and price < original_price
101
+
102
+ # Images — nested under sources[0].url
103
+ image_info = item.get("imageInfo", {})
104
+ images_raw = image_info.get("images", [])
105
+ image_urls = []
106
+ for img in images_raw:
107
+ sources = img.get("sources", [])
108
+ if sources and isinstance(sources, list):
109
+ src = sources[0].get("url", "")
110
+ if src:
111
+ # Replace format=medium with format=large for better quality
112
+ src = src.replace("format=medium", "format=large")
113
+ image_urls.append(src)
114
+ image_url = image_urls[0] if image_urls else ""
115
+
116
+ # Color
117
+ color = ""
118
+ custom = item.get("custom", {})
119
+ filter_color = custom.get("filterColor", [])
120
+ if filter_color and isinstance(filter_color, list):
121
+ first = filter_color[0]
122
+ color = first.get("label", "") if isinstance(first, dict) else str(first)
123
+
124
+ # Sizes from variants
125
+ sizes = []
126
+ in_stock = item.get("inStock", False)
127
+ variants = item.get("variants", [])
128
+ for v in variants:
129
+ size = v.get("label", "")
130
+ if size and isinstance(size, str):
131
+ sizes.append(size)
132
+
133
+ # Category from path
134
+ cat_clean = category.strip("/")
135
+
136
+ return {
137
+ "url": url,
138
+ "external_id": str(key),
139
+ "image_url": image_url,
140
+ "image_urls": image_urls,
141
+ "brand": brand or "Nelly",
142
+ "name": name,
143
+ "color": color,
144
+ "material": "",
145
+ "category": cat_clean,
146
+ "price_nok": price,
147
+ "original_price_nok": original_price if on_sale else 0,
148
+ "price_text": f"{price:.0f} kr" if price else "",
149
+ "currency": "NOK",
150
+ "on_sale": on_sale,
151
+ "in_stock": in_stock,
152
+ "sizes": sizes,
153
+ "store": "Nelly",
154
+ }
taste/scrapers/api/stories.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """& Other Stories scraper — Next.js __NEXT_DATA__ extraction via curl_cffi."""
2
+
3
+ import json
4
+ import re
5
+ import time
6
+
7
+ from curl_cffi import requests as curl_requests
8
+
9
+ from taste.scrapers.base import BaseScraper
10
+
11
+
12
+ class StoriesScraper(BaseScraper):
13
+ def scrape(self, categories: list[str] | None = None, max_products: int | None = None) -> list[dict]:
14
+ categories = categories or self.config.categories
15
+ max_products = max_products or self.config.max_products
16
+ base_url = self.config.base_url or "https://www.stories.com"
17
+
18
+ products = []
19
+ seen_urls = set()
20
+
21
+ session = curl_requests.Session(impersonate="chrome")
22
+ try:
23
+ # Warm up session with homepage cookies
24
+ session.get(f"{base_url}/en-no/", timeout=30)
25
+ time.sleep(0.3)
26
+
27
+ for cat in categories:
28
+ cat_url = cat if cat.startswith("http") else f"{base_url}{cat}"
29
+ page_num = 1
30
+ total_pages = None
31
+
32
+ while len(products) < max_products:
33
+ url = f"{cat_url}?page={page_num}" if page_num > 1 else cat_url
34
+ try:
35
+ resp = session.get(url, timeout=30)
36
+ if resp.status_code != 200:
37
+ print(f" Stories: {cat} page {page_num} returned {resp.status_code}", flush=True)
38
+ break
39
+ except Exception as e:
40
+ print(f" Stories: error fetching {cat} page {page_num}: {e}", flush=True)
41
+ break
42
+
43
+ next_data = self._extract_next_data(resp.text)
44
+ if not next_data:
45
+ print(f" Stories: no __NEXT_DATA__ for {cat} page {page_num}", flush=True)
46
+ break
47
+
48
+ page_props = next_data.get("props", {}).get("pageProps", {})
49
+ items, total_count, per_page = self._find_products(page_props)
50
+
51
+ if total_pages is None and per_page and total_count:
52
+ total_pages = -(-total_count // per_page) # ceil division
53
+
54
+ if not items:
55
+ break
56
+
57
+ new_count = 0
58
+ for item in items:
59
+ product = self._parse_product(item, base_url)
60
+ if not product or product["url"] in seen_urls:
61
+ continue
62
+ seen_urls.add(product["url"])
63
+ products.append(product)
64
+ new_count += 1
65
+
66
+ cat_name = cat.rstrip("/").split("/")[-1] or "root"
67
+ print(f" Stories: {cat_name} page {page_num}/{total_pages or '?'}, +{new_count}, {len(products)} total", flush=True)
68
+
69
+ if new_count == 0:
70
+ break
71
+ page_num += 1
72
+ if total_pages and page_num > total_pages:
73
+ break
74
+
75
+ finally:
76
+ session.close()
77
+
78
+ return products
79
+
80
+ @staticmethod
81
+ def _extract_next_data(html: str) -> dict | None:
82
+ m = re.search(r'<script[^>]*id="__NEXT_DATA__"[^>]*>(.*?)</script>', html, re.DOTALL)
83
+ if not m:
84
+ return None
85
+ try:
86
+ return json.loads(m.group(1))
87
+ except json.JSONDecodeError:
88
+ return None
89
+
90
+ @staticmethod
91
+ def _find_products(page_props: dict) -> tuple[list, int, int]:
92
+ """Find product list in page props blocks."""
93
+ blocks = page_props.get("blocks", [])
94
+ for block in blocks:
95
+ if block.get("component") == "productList":
96
+ return (
97
+ block.get("products", []),
98
+ int(block.get("productsCount", 0) or 0),
99
+ int(block.get("itemsPerPage", 36) or 36),
100
+ )
101
+ return ([], 0, 0)
102
+
103
+ @staticmethod
104
+ def _parse_product(item: dict, base_url: str) -> dict | None:
105
+ href = item.get("href", "")
106
+ if not href:
107
+ return None
108
+ url = f"{base_url}{href}" if not href.startswith("http") else href
109
+
110
+ # Images
111
+ images = item.get("images", [])
112
+ image_url_field = item.get("_imageurl", "")
113
+ if not images and image_url_field:
114
+ images = [image_url_field]
115
+ image_url = images[0] if images else ""
116
+
117
+ # Price
118
+ price = float(item.get("priceAsNumber", 0) or 0)
119
+ original_price = float(item.get("priceBeforeDiscountAsNumber", 0) or 0)
120
+ on_sale = original_price > 0 and price < original_price
121
+
122
+ # Color
123
+ color = item.get("variantName", "")
124
+ if not color:
125
+ color_names = item.get("color_name", [])
126
+ if color_names and isinstance(color_names, list):
127
+ first = color_names[0]
128
+ color = first.get("value", "") if isinstance(first, dict) else str(first)
129
+
130
+ # Sizes
131
+ sizes = item.get("sizes", [])
132
+ if isinstance(sizes, list):
133
+ sizes = [s for s in sizes if isinstance(s, str)]
134
+
135
+ # Stock
136
+ available = item.get("available", True)
137
+ total_stock = item.get("totalStock", "0")
138
+ in_stock = available and str(total_stock) != "0"
139
+
140
+ # External ID
141
+ sku = item.get("product_sku", item.get("sku", item.get("product", "")))
142
+
143
+ # Category
144
+ category = ""
145
+ cat_uris = item.get("categoryUris", [])
146
+ if cat_uris and isinstance(cat_uris, list):
147
+ category = cat_uris[0] if cat_uris else ""
148
+
149
+ # Name
150
+ name = item.get("name", "")
151
+
152
+ return {
153
+ "url": url,
154
+ "external_id": str(sku),
155
+ "image_url": image_url,
156
+ "image_urls": images,
157
+ "brand": "& Other Stories",
158
+ "name": name,
159
+ "color": color,
160
+ "material": "",
161
+ "category": category,
162
+ "price_nok": price,
163
+ "original_price_nok": original_price if on_sale else 0,
164
+ "price_text": f"{price:.0f} kr" if price else "",
165
+ "currency": "NOK",
166
+ "on_sale": on_sale,
167
+ "in_stock": in_stock,
168
+ "sizes": sizes,
169
+ "store": "& Other Stories",
170
+ }
taste/scrapers/api/zalando.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Zalando.no scraper — SSR hydration data extraction via curl_cffi."""
2
+
3
+ import json
4
+ import re
5
+ import time
6
+
7
+ from curl_cffi import requests as curl_requests
8
+
9
+ from taste.scrapers.base import BaseScraper
10
+
11
+
12
+ class ZalandoScraper(BaseScraper):
13
+ def scrape(self, categories: list[str] | None = None, max_products: int | None = None) -> list[dict]:
14
+ categories = categories or self.config.categories
15
+ max_products = max_products or self.config.max_products
16
+ base_url = self.config.base_url or "https://www.zalando.no"
17
+
18
+ products = []
19
+ seen_urls = set()
20
+
21
+ session = curl_requests.Session(impersonate="safari_ios")
22
+ try:
23
+ for cat in categories:
24
+ cat_url = cat if cat.startswith("http") else f"{base_url}{cat}"
25
+ page_num = 1
26
+ total_pages = None
27
+
28
+ while len(products) < max_products:
29
+ url = f"{cat_url}?p={page_num}" if page_num > 1 else cat_url
30
+ try:
31
+ resp = session.get(url, timeout=30)
32
+ if resp.status_code == 400:
33
+ # Beyond last page
34
+ break
35
+ if resp.status_code != 200:
36
+ print(f" Zalando: {cat} page {page_num} returned {resp.status_code}", flush=True)
37
+ break
38
+ except Exception as e:
39
+ print(f" Zalando: error fetching {cat} page {page_num}: {e}", flush=True)
40
+ break
41
+
42
+ hydration = self._extract_hydration(resp.text)
43
+ if not hydration:
44
+ print(f" Zalando: no hydration data for {cat} page {page_num}", flush=True)
45
+ break
46
+
47
+ if total_pages is None:
48
+ m = re.search(r"Side \d+ av (\d+)", resp.text)
49
+ if m:
50
+ total_pages = int(m.group(1))
51
+
52
+ items = self._extract_products(hydration)
53
+ if not items:
54
+ break
55
+
56
+ new_count = 0
57
+ for item in items:
58
+ product = self._parse_product(item)
59
+ if not product or product["url"] in seen_urls:
60
+ continue
61
+ seen_urls.add(product["url"])
62
+ products.append(product)
63
+ new_count += 1
64
+
65
+ cat_name = cat.strip("/").split("/")[-1] or "root"
66
+ print(f" Zalando: {cat_name} page {page_num}/{total_pages or '?'}, +{new_count}, {len(products)} total", flush=True)
67
+
68
+ if new_count == 0:
69
+ break
70
+ page_num += 1
71
+ if total_pages and page_num > total_pages:
72
+ break
73
+
74
+ time.sleep(0.5)
75
+ finally:
76
+ session.close()
77
+
78
+ return products
79
+
80
+ @staticmethod
81
+ def _extract_hydration(html: str) -> dict | None:
82
+ """Extract window.__hydrationDataConsume(...) JSON."""
83
+ matches = list(re.finditer(r"window\.__hydrationDataConsume\(", html))
84
+ if not matches:
85
+ return None
86
+ start = matches[0].end()
87
+ depth = 1
88
+ pos = start
89
+ while pos < len(html) and depth > 0:
90
+ if html[pos] == "(":
91
+ depth += 1
92
+ elif html[pos] == ")":
93
+ depth -= 1
94
+ pos += 1
95
+ try:
96
+ return json.loads(html[start : pos - 1])
97
+ except json.JSONDecodeError:
98
+ return None
99
+
100
+ @staticmethod
101
+ def _extract_products(hydration: dict) -> list[dict]:
102
+ """Pull product dicts from graphqlCache."""
103
+ gc = hydration.get("graphqlCache", {})
104
+ products = []
105
+ for value in gc.values():
106
+ data = value.get("data", {})
107
+ if isinstance(data, dict) and data.get("product"):
108
+ products.append(data["product"])
109
+ return products
110
+
111
+ @staticmethod
112
+ def _parse_product(item: dict) -> dict | None:
113
+ uri = item.get("uri", "")
114
+ if not uri:
115
+ return None
116
+ url = uri if uri.startswith("http") else f"https://www.zalando.no{uri}"
117
+
118
+ sku = item.get("sku", "")
119
+ brand = item.get("brand", {}).get("name", "")
120
+ raw_name = item.get("name", "")
121
+
122
+ # Name often has format "Product Type - color" in Norwegian
123
+ # Split to get name and color
124
+ name = raw_name
125
+ color = ""
126
+ if " - " in raw_name:
127
+ parts = raw_name.rsplit(" - ", 1)
128
+ if len(parts) == 2:
129
+ # First part is category/type, color is last
130
+ # But sometimes it's "Category - Subcategory - color"
131
+ name = parts[0]
132
+ color = parts[1]
133
+
134
+ # Price (amounts in ore/cents)
135
+ dp = item.get("displayPrice", {}) or {}
136
+ promo = dp.get("promotional") or {}
137
+ orig = dp.get("original") or {}
138
+ price_cents = promo.get("amount") or orig.get("amount", 0) or 0
139
+ orig_cents = orig.get("amount", 0) or 0
140
+ price = price_cents / 100
141
+ original_price = orig_cents / 100
142
+ on_sale = dp.get("displayMode") == "TWO_PRICES" and price < original_price
143
+
144
+ # Gallery images (use largest resolution)
145
+ gallery = item.get("gallery", [])
146
+ image_urls = []
147
+ for g in gallery:
148
+ xl = g.get("galleryExtraLarge", {})
149
+ if isinstance(xl, dict) and xl.get("uri"):
150
+ image_urls.append(xl["uri"])
151
+ image_url = image_urls[0] if image_urls else ""
152
+
153
+ # Sizes from simples
154
+ simples = item.get("simples", [])
155
+ sizes = [s.get("size", "") for s in simples if s.get("size")]
156
+
157
+ # Category from silhouette
158
+ category = item.get("silhouette", "")
159
+
160
+ return {
161
+ "url": url,
162
+ "external_id": sku,
163
+ "image_url": image_url,
164
+ "image_urls": image_urls,
165
+ "brand": brand,
166
+ "name": name,
167
+ "color": color,
168
+ "material": "",
169
+ "category": category,
170
+ "price_nok": price,
171
+ "original_price_nok": original_price if on_sale else 0,
172
+ "price_text": f"{price:.0f} kr" if price else "",
173
+ "currency": "NOK",
174
+ "on_sale": on_sale,
175
+ "in_stock": True,
176
+ "sizes": sizes,
177
+ "store": "Zalando",
178
+ }
taste/store.py CHANGED
@@ -266,6 +266,12 @@ class ProductStore:
266
  ).fetchall()
267
  return [dict(r) for r in rows]
268
 
 
 
 
 
 
 
269
  def update_score(self, url: str, score: float):
270
  self.conn.execute("UPDATE products SET score = ?, updated_at = CURRENT_TIMESTAMP WHERE url = ?", (score, url))
271
 
 
266
  ).fetchall()
267
  return [dict(r) for r in rows]
268
 
269
+ def get_unscored_with_category(self) -> list[dict]:
270
+ rows = self.conn.execute(
271
+ "SELECT url, image_path, category FROM products WHERE image_path != '' AND score IS NULL"
272
+ ).fetchall()
273
+ return [dict(r) for r in rows]
274
+
275
  def update_score(self, url: str, score: float):
276
  self.conn.execute("UPDATE products SET score = ?, updated_at = CURRENT_TIMESTAMP WHERE url = ?", (score, url))
277