Spaces:
Sleeping
Sleeping
Commit ·
d7f92a4
1
Parent(s): 2ba670a
add price/sale bias, multi-image, text fusion to scoring
Browse files- derive_user_metadata_profile: price band + sale_pref from rated products
- multiplicative price_bias (floor 0.7) and sale_bias (±0.05)
- encode_product fuses mean-pooled image embs with text at tw=0.3
- store: new image_paths column + get_user_profile_inputs helper
- scrapers/base: download up to 3 images per product
- backend/app/routers/discover.py +33 -5
- taste/engine.py +165 -26
- taste/pipeline.py +34 -4
- taste/scrapers/base.py +50 -18
- taste/store.py +26 -3
backend/app/routers/discover.py
CHANGED
|
@@ -250,9 +250,18 @@ def _do_rescore():
|
|
| 250 |
store.conn.execute("UPDATE discover_ratings SET processed = 1 WHERE processed = 0")
|
| 251 |
store.conn.commit()
|
| 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
|
|
|
|
|
|
|
| 256 |
WHERE image_url != '' AND image_url IS NOT NULL
|
| 257 |
""").fetchall()
|
| 258 |
|
|
@@ -287,19 +296,36 @@ def _do_rescore():
|
|
| 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:
|
|
@@ -316,8 +342,10 @@ def _do_rescore():
|
|
| 316 |
_rescore_pending = False
|
| 317 |
|
| 318 |
|
| 319 |
-
def _score_batch(engine, store, products, urls, taste):
|
| 320 |
-
scored = engine.score_products_by_category(
|
|
|
|
|
|
|
| 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)
|
|
|
|
| 250 |
store.conn.execute("UPDATE discover_ratings SET processed = 1 WHERE processed = 0")
|
| 251 |
store.conn.commit()
|
| 252 |
|
| 253 |
+
# Derive user profile (price band, sale preference) from rated products
|
| 254 |
+
user_profile = engine.derive_user_metadata_profile(store.get_user_profile_inputs())
|
| 255 |
+
price_band = user_profile.get("price_band")
|
| 256 |
+
sale_pref = user_profile.get("sale_pref", 0.0)
|
| 257 |
+
if price_band:
|
| 258 |
+
print(f"[discover] price_band median={price_band.get('p50'):.0f} NOK, sale_pref={sale_pref:+.2f}", flush=True)
|
| 259 |
+
|
| 260 |
# Rescore ALL products — download images on-demand if missing locally
|
| 261 |
rows = store.conn.execute("""
|
| 262 |
+
SELECT url, image_path, image_paths, image_url, category, brand, name, color, material,
|
| 263 |
+
price_nok, on_sale
|
| 264 |
+
FROM products
|
| 265 |
WHERE image_url != '' AND image_url IS NOT NULL
|
| 266 |
""").fetchall()
|
| 267 |
|
|
|
|
| 296 |
)
|
| 297 |
|
| 298 |
if p and p.exists():
|
| 299 |
+
try:
|
| 300 |
+
multi_paths = json.loads(r["image_paths"] or "[]")
|
| 301 |
+
if not isinstance(multi_paths, list):
|
| 302 |
+
multi_paths = []
|
| 303 |
+
except Exception:
|
| 304 |
+
multi_paths = []
|
| 305 |
+
multi_paths = [mp for mp in multi_paths if mp and Path(mp).exists()]
|
| 306 |
+
if not multi_paths:
|
| 307 |
+
multi_paths = [str(p)]
|
| 308 |
+
text = " ".join(filter(None, [
|
| 309 |
+
r["brand"] or "", r["name"] or "",
|
| 310 |
+
r["color"] or "", r["material"] or "",
|
| 311 |
+
])).strip()
|
| 312 |
products_batch.append({
|
| 313 |
"image_path": str(p),
|
| 314 |
+
"image_paths": multi_paths,
|
| 315 |
"category": r["category"] or "",
|
| 316 |
+
"text": text,
|
| 317 |
+
"price_nok": r["price_nok"] or 0,
|
| 318 |
+
"on_sale": bool(r["on_sale"]),
|
| 319 |
})
|
| 320 |
urls_batch.append(r["url"])
|
| 321 |
|
| 322 |
if len(products_batch) >= batch_size:
|
| 323 |
+
_score_batch(engine, store, products_batch, urls_batch, taste, price_band, sale_pref)
|
| 324 |
total_rescored += len(products_batch)
|
| 325 |
products_batch, urls_batch = [], []
|
| 326 |
|
| 327 |
if products_batch:
|
| 328 |
+
_score_batch(engine, store, products_batch, urls_batch, taste, price_band, sale_pref)
|
| 329 |
total_rescored += len(products_batch)
|
| 330 |
|
| 331 |
if dl_count:
|
|
|
|
| 342 |
_rescore_pending = False
|
| 343 |
|
| 344 |
|
| 345 |
+
def _score_batch(engine, store, products, urls, taste, price_band=None, sale_pref=0.0):
|
| 346 |
+
scored = engine.score_products_by_category(
|
| 347 |
+
products, taste, price_band=price_band, sale_pref=sale_pref,
|
| 348 |
+
)
|
| 349 |
score_map = {s["image_path"]: s["score"] for s in scored}
|
| 350 |
for url, prod in zip(urls, products):
|
| 351 |
s = score_map.get(prod["image_path"], 0)
|
taste/engine.py
CHANGED
|
@@ -96,6 +96,56 @@ class TasteEngine:
|
|
| 96 |
emb = emb / emb.norm(dim=-1, keepdim=True)
|
| 97 |
return emb.squeeze().cpu().float().numpy()
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
def encode_batch(
|
| 100 |
self, paths: list[Path], batch_size: int = 16, progress_cb=None
|
| 101 |
) -> dict[str, np.ndarray]:
|
|
@@ -339,55 +389,144 @@ class TasteEngine:
|
|
| 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 |
-
|
| 350 |
-
|
| 351 |
-
|
|
|
|
|
|
|
| 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 |
-
|
| 362 |
-
|
| 363 |
for p in products:
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
path_to_cat[str(img)] = self._normalize_category(raw_cat)
|
| 369 |
|
| 370 |
-
if
|
| 371 |
-
|
|
|
|
|
|
|
| 372 |
|
| 373 |
-
embeddings = self.encode_batch(paths)
|
| 374 |
unified_arr = np.array(unified)
|
| 375 |
|
| 376 |
results = []
|
| 377 |
-
for p in
|
| 378 |
-
|
| 379 |
-
if
|
|
|
|
| 380 |
continue
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
else:
|
| 388 |
-
|
| 389 |
|
|
|
|
|
|
|
| 390 |
s = float(np.max(emb @ c_arr.T))
|
| 391 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
|
| 393 |
return results
|
|
|
|
| 96 |
emb = emb / emb.norm(dim=-1, keepdim=True)
|
| 97 |
return emb.squeeze().cpu().float().numpy()
|
| 98 |
|
| 99 |
+
def encode_text_batch(
|
| 100 |
+
self, texts: list[str], batch_size: int = 32
|
| 101 |
+
) -> dict[str, np.ndarray]:
|
| 102 |
+
"""Encode many texts. Returns {text: emb}. Skips empty strings."""
|
| 103 |
+
import torch
|
| 104 |
+
unique = sorted({t.strip() for t in texts if t and t.strip()})
|
| 105 |
+
if not unique:
|
| 106 |
+
return {}
|
| 107 |
+
self._load_model()
|
| 108 |
+
results = {}
|
| 109 |
+
for i in range(0, len(unique), batch_size):
|
| 110 |
+
batch = unique[i : i + batch_size]
|
| 111 |
+
tokens = self._tokenizer(batch).to(self.device)
|
| 112 |
+
with torch.no_grad():
|
| 113 |
+
embs = self._model.encode_text(tokens)
|
| 114 |
+
embs = embs / embs.norm(dim=-1, keepdim=True)
|
| 115 |
+
for t, emb in zip(batch, embs.cpu().float().numpy()):
|
| 116 |
+
results[t] = emb
|
| 117 |
+
return results
|
| 118 |
+
|
| 119 |
+
def encode_product(
|
| 120 |
+
self,
|
| 121 |
+
image_paths: list[Path],
|
| 122 |
+
text: str = "",
|
| 123 |
+
text_weight: float = 0.2,
|
| 124 |
+
) -> np.ndarray | None:
|
| 125 |
+
"""Fused product embedding: mean of image embs + optional text emb.
|
| 126 |
+
|
| 127 |
+
text_weight=0 disables text fusion. Empirically 0.2 is the sweet spot
|
| 128 |
+
(validated on Boozt multi-angle retrieval, top-1 0.95→1.00).
|
| 129 |
+
"""
|
| 130 |
+
valid_paths = [Path(p) for p in image_paths if Path(p).exists()]
|
| 131 |
+
if not valid_paths and not text.strip():
|
| 132 |
+
return None
|
| 133 |
+
if valid_paths:
|
| 134 |
+
embs = [self.encode(p) for p in valid_paths]
|
| 135 |
+
img_emb = np.mean(embs, axis=0)
|
| 136 |
+
img_emb = img_emb / np.linalg.norm(img_emb)
|
| 137 |
+
else:
|
| 138 |
+
img_emb = None
|
| 139 |
+
|
| 140 |
+
text = text.strip()[:200]
|
| 141 |
+
if img_emb is None:
|
| 142 |
+
return self.encode_text(text)
|
| 143 |
+
if not text or text_weight <= 0:
|
| 144 |
+
return img_emb
|
| 145 |
+
txt_emb = self.encode_text(text)
|
| 146 |
+
fused = (1 - text_weight) * img_emb + text_weight * txt_emb
|
| 147 |
+
return fused / np.linalg.norm(fused)
|
| 148 |
+
|
| 149 |
def encode_batch(
|
| 150 |
self, paths: list[Path], batch_size: int = 16, progress_cb=None
|
| 151 |
) -> dict[str, np.ndarray]:
|
|
|
|
| 389 |
scores.sort(key=lambda x: x[1], reverse=True)
|
| 390 |
return scores
|
| 391 |
|
| 392 |
+
@staticmethod
|
| 393 |
+
def derive_user_metadata_profile(rated_products: list[dict]) -> dict:
|
| 394 |
+
"""Derive user's price band + sale preference from rated products.
|
| 395 |
+
|
| 396 |
+
Args:
|
| 397 |
+
rated_products: list of {price_nok, on_sale, rating} where rating in {-1, 0, 1}.
|
| 398 |
+
|
| 399 |
+
Returns:
|
| 400 |
+
{"price_band": {p10,p25,p50,p75,p90} or None, "sale_pref": float in [-1,1]}
|
| 401 |
+
"""
|
| 402 |
+
liked = [p for p in rated_products if p.get("rating", 0) > 0 and (p.get("price_nok") or 0) > 0]
|
| 403 |
+
if len(liked) < 3:
|
| 404 |
+
price_band = None
|
| 405 |
+
else:
|
| 406 |
+
prices = sorted(p["price_nok"] for p in liked)
|
| 407 |
+
price_band = {
|
| 408 |
+
"p10": float(np.percentile(prices, 10)),
|
| 409 |
+
"p25": float(np.percentile(prices, 25)),
|
| 410 |
+
"p50": float(np.percentile(prices, 50)),
|
| 411 |
+
"p75": float(np.percentile(prices, 75)),
|
| 412 |
+
"p90": float(np.percentile(prices, 90)),
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
rated_with_sale = [p for p in rated_products if "on_sale" in p and p.get("rating", 0) != 0]
|
| 416 |
+
if len(rated_with_sale) >= 4:
|
| 417 |
+
liked_sale = sum(1 for p in rated_with_sale if p["rating"] > 0 and p.get("on_sale"))
|
| 418 |
+
liked_full = sum(1 for p in rated_with_sale if p["rating"] > 0 and not p.get("on_sale"))
|
| 419 |
+
disliked_sale = sum(1 for p in rated_with_sale if p["rating"] < 0 and p.get("on_sale"))
|
| 420 |
+
disliked_full = sum(1 for p in rated_with_sale if p["rating"] < 0 and not p.get("on_sale"))
|
| 421 |
+
n_liked = liked_sale + liked_full
|
| 422 |
+
n_disliked = disliked_sale + disliked_full
|
| 423 |
+
if n_liked > 0 and n_disliked > 0:
|
| 424 |
+
sale_pref = (liked_sale / n_liked) - (disliked_sale / n_disliked)
|
| 425 |
+
else:
|
| 426 |
+
sale_pref = 0.0
|
| 427 |
+
else:
|
| 428 |
+
sale_pref = 0.0
|
| 429 |
+
|
| 430 |
+
return {"price_band": price_band, "sale_pref": float(sale_pref)}
|
| 431 |
+
|
| 432 |
+
@staticmethod
|
| 433 |
+
def _price_bias(price: float, band: dict | None) -> float:
|
| 434 |
+
"""Price-distribution alignment in [0.7, 1.0].
|
| 435 |
+
|
| 436 |
+
Returns 1.0 if price is within the user's [p25, p75] of liked items;
|
| 437 |
+
decays linearly to 0.7 outside [p10, p90]. Floor 0.7 — never zero out.
|
| 438 |
+
"""
|
| 439 |
+
if not band or not price or price <= 0:
|
| 440 |
+
return 1.0
|
| 441 |
+
p25, p75 = band.get("p25", 0), band.get("p75", 0)
|
| 442 |
+
p10, p90 = band.get("p10", 0), band.get("p90", 0)
|
| 443 |
+
if p25 <= price <= p75:
|
| 444 |
+
return 1.0
|
| 445 |
+
if price < p25 and p10 < p25:
|
| 446 |
+
x = max(0.0, (price - p10) / (p25 - p10))
|
| 447 |
+
return 0.7 + 0.3 * x
|
| 448 |
+
if price > p75 and p90 > p75:
|
| 449 |
+
x = max(0.0, (p90 - price) / (p90 - p75))
|
| 450 |
+
return 0.7 + 0.3 * x
|
| 451 |
+
return 0.7
|
| 452 |
+
|
| 453 |
+
@staticmethod
|
| 454 |
+
def _sale_bias(on_sale: bool, sale_pref: float) -> float:
|
| 455 |
+
"""Sale preference bias. sale_pref ∈ [-1, 1] from user history.
|
| 456 |
+
Returns multiplier in [0.95, 1.05]."""
|
| 457 |
+
if sale_pref == 0:
|
| 458 |
+
return 1.0
|
| 459 |
+
if on_sale:
|
| 460 |
+
return 1.0 + 0.05 * sale_pref
|
| 461 |
+
return 1.0 - 0.05 * sale_pref
|
| 462 |
+
|
| 463 |
def score_products_by_category(
|
| 464 |
self,
|
| 465 |
products: list[dict],
|
| 466 |
taste: dict,
|
| 467 |
+
text_weight: float = 0.3,
|
| 468 |
+
price_band: dict | None = None,
|
| 469 |
+
sale_pref: float = 0.0,
|
| 470 |
) -> list[dict]:
|
| 471 |
"""Score products using per-category centroids with unified fallback.
|
| 472 |
|
| 473 |
+
Each product dict supports:
|
| 474 |
+
image_path: str (single primary image)
|
| 475 |
+
image_paths: list[str] (optional — multi-image, takes precedence)
|
| 476 |
+
category: str
|
| 477 |
+
text: str (optional — fused with image at text_weight)
|
| 478 |
|
| 479 |
+
Returns: list of {image_path, score} (image_path = first available).
|
|
|
|
| 480 |
"""
|
| 481 |
cat_centroids = taste.get("categories", {})
|
| 482 |
unified = taste.get("unified")
|
| 483 |
if not unified:
|
| 484 |
return []
|
| 485 |
|
| 486 |
+
# Collect all images and texts up front for batched encoding
|
| 487 |
+
all_image_paths: set[str] = set()
|
| 488 |
for p in products:
|
| 489 |
+
paths = p.get("image_paths") or [p.get("image_path", "")]
|
| 490 |
+
for ip in paths:
|
| 491 |
+
if ip and Path(ip).exists():
|
| 492 |
+
all_image_paths.add(str(ip))
|
|
|
|
| 493 |
|
| 494 |
+
img_embs = self.encode_batch([Path(s) for s in all_image_paths]) if all_image_paths else {}
|
| 495 |
+
|
| 496 |
+
texts = [p.get("text", "") for p in products]
|
| 497 |
+
text_embs = self.encode_text_batch(texts) if text_weight > 0 else {}
|
| 498 |
|
|
|
|
| 499 |
unified_arr = np.array(unified)
|
| 500 |
|
| 501 |
results = []
|
| 502 |
+
for p in products:
|
| 503 |
+
paths = p.get("image_paths") or [p.get("image_path", "")]
|
| 504 |
+
valid = [ip for ip in paths if ip and str(Path(ip)) in img_embs]
|
| 505 |
+
if not valid:
|
| 506 |
continue
|
| 507 |
+
# Preserve caller's identity — return the original image_path key
|
| 508 |
+
ret_key = p.get("image_path") or str(Path(valid[0]))
|
| 509 |
+
embs = [img_embs[str(Path(ip))] for ip in valid]
|
| 510 |
+
img_emb = np.mean(embs, axis=0)
|
| 511 |
+
img_emb = img_emb / np.linalg.norm(img_emb)
|
| 512 |
+
|
| 513 |
+
text = (p.get("text", "") or "").strip()
|
| 514 |
+
if text and text_weight > 0 and text in text_embs:
|
| 515 |
+
fused = (1 - text_weight) * img_emb + text_weight * text_embs[text]
|
| 516 |
+
emb = fused / np.linalg.norm(fused)
|
| 517 |
else:
|
| 518 |
+
emb = img_emb
|
| 519 |
|
| 520 |
+
cat = self._normalize_category(p.get("category", ""))
|
| 521 |
+
c_arr = np.array(cat_centroids[cat]) if cat in cat_centroids else unified_arr
|
| 522 |
s = float(np.max(emb @ c_arr.T))
|
| 523 |
+
|
| 524 |
+
# Apply metadata biases (multiplicative, transparent, ablatable)
|
| 525 |
+
if price_band is not None:
|
| 526 |
+
s *= self._price_bias(float(p.get("price_nok") or 0), price_band)
|
| 527 |
+
if sale_pref:
|
| 528 |
+
s *= self._sale_bias(bool(p.get("on_sale", False)), sale_pref)
|
| 529 |
+
|
| 530 |
+
results.append({"image_path": ret_key, "score": s})
|
| 531 |
|
| 532 |
return results
|
taste/pipeline.py
CHANGED
|
@@ -153,20 +153,50 @@ def _score_unscored(engine: TasteEngine, store: ProductStore, taste: dict, batch
|
|
| 153 |
|
| 154 |
print(f" Scoring {len(rows)} unscored products...", flush=True)
|
| 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 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
if not products:
|
| 167 |
continue
|
| 168 |
|
| 169 |
-
scored = engine.score_products_by_category(
|
|
|
|
|
|
|
| 170 |
score_map = {s["image_path"]: s["score"] for s in scored}
|
| 171 |
|
| 172 |
for url, prod in zip(urls, products):
|
|
|
|
| 153 |
|
| 154 |
print(f" Scoring {len(rows)} unscored products...", flush=True)
|
| 155 |
|
| 156 |
+
user_profile = engine.derive_user_metadata_profile(store.get_user_profile_inputs())
|
| 157 |
+
price_band = user_profile.get("price_band")
|
| 158 |
+
sale_pref = user_profile.get("sale_pref", 0.0)
|
| 159 |
+
if price_band:
|
| 160 |
+
print(f" Using price_band median={price_band.get('p50'):.0f} NOK, sale_pref={sale_pref:+.2f}", flush=True)
|
| 161 |
+
|
| 162 |
+
import json as _json
|
| 163 |
for i in range(0, len(rows), batch_size):
|
| 164 |
batch = rows[i : i + batch_size]
|
| 165 |
products = []
|
| 166 |
urls = []
|
| 167 |
for r in batch:
|
| 168 |
p = Path(r["image_path"])
|
| 169 |
+
if not p.exists():
|
| 170 |
+
continue
|
| 171 |
+
try:
|
| 172 |
+
paths = _json.loads(r.get("image_paths") or "[]")
|
| 173 |
+
if not isinstance(paths, list):
|
| 174 |
+
paths = []
|
| 175 |
+
except Exception:
|
| 176 |
+
paths = []
|
| 177 |
+
paths = [pp for pp in paths if pp and Path(pp).exists()]
|
| 178 |
+
if not paths:
|
| 179 |
+
paths = [r["image_path"]]
|
| 180 |
+
text = " ".join(filter(None, [
|
| 181 |
+
r.get("brand", ""), r.get("name", ""),
|
| 182 |
+
r.get("color", ""), r.get("material", ""),
|
| 183 |
+
])).strip()
|
| 184 |
+
products.append({
|
| 185 |
+
"image_path": r["image_path"],
|
| 186 |
+
"image_paths": paths,
|
| 187 |
+
"category": r.get("category", ""),
|
| 188 |
+
"text": text,
|
| 189 |
+
"price_nok": r.get("price_nok") or 0,
|
| 190 |
+
"on_sale": bool(r.get("on_sale", False)),
|
| 191 |
+
})
|
| 192 |
+
urls.append(r["url"])
|
| 193 |
|
| 194 |
if not products:
|
| 195 |
continue
|
| 196 |
|
| 197 |
+
scored = engine.score_products_by_category(
|
| 198 |
+
products, taste, price_band=price_band, sale_pref=sale_pref,
|
| 199 |
+
)
|
| 200 |
score_map = {s["image_path"]: s["score"] for s in scored}
|
| 201 |
|
| 202 |
for url, prod in zip(urls, products):
|
taste/scrapers/base.py
CHANGED
|
@@ -20,32 +20,64 @@ class BaseScraper(ABC):
|
|
| 20 |
"""Scrape products. Returns list of product dicts."""
|
| 21 |
...
|
| 22 |
|
| 23 |
-
def download_images(
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
|
|
|
| 29 |
|
| 30 |
with httpx.Client(
|
| 31 |
timeout=15,
|
| 32 |
follow_redirects=True,
|
| 33 |
limits=httpx.Limits(max_connections=concurrency, max_keepalive_connections=10),
|
| 34 |
) as client:
|
| 35 |
-
for p in
|
| 36 |
-
|
| 37 |
-
h = hashlib.md5(p["url"].encode()).hexdigest()[:12]
|
| 38 |
-
path = cache_dir / f"{h}.jpg"
|
| 39 |
-
if path.exists():
|
| 40 |
-
p["image_path"] = str(path)
|
| 41 |
-
continue
|
| 42 |
-
resp = client.get(p["image_url"])
|
| 43 |
-
if resp.status_code == 200 and len(resp.content) > 1000:
|
| 44 |
-
path.write_bytes(resp.content)
|
| 45 |
-
p["image_path"] = str(path)
|
| 46 |
-
except Exception:
|
| 47 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
downloaded = sum(1 for p in products if p.get("image_path"))
|
| 50 |
-
|
|
|
|
|
|
|
| 51 |
return products
|
|
|
|
| 20 |
"""Scrape products. Returns list of product dicts."""
|
| 21 |
...
|
| 22 |
|
| 23 |
+
def download_images(
|
| 24 |
+
self,
|
| 25 |
+
products: list[dict],
|
| 26 |
+
cache_dir: Path,
|
| 27 |
+
concurrency: int = 20,
|
| 28 |
+
max_per_product: int = 3,
|
| 29 |
+
) -> list[dict]:
|
| 30 |
+
"""Download up to `max_per_product` images per product, with connection pooling.
|
| 31 |
|
| 32 |
+
Sets `image_path` (primary) and `image_paths` (JSON list of all local paths).
|
| 33 |
+
"""
|
| 34 |
+
import json as _json
|
| 35 |
|
| 36 |
with httpx.Client(
|
| 37 |
timeout=15,
|
| 38 |
follow_redirects=True,
|
| 39 |
limits=httpx.Limits(max_connections=concurrency, max_keepalive_connections=10),
|
| 40 |
) as client:
|
| 41 |
+
for p in products:
|
| 42 |
+
if p.get("image_path") and p.get("image_paths"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
continue
|
| 44 |
+
urls: list[str] = []
|
| 45 |
+
primary = p.get("image_url") or ""
|
| 46 |
+
if primary:
|
| 47 |
+
urls.append(primary)
|
| 48 |
+
extras = p.get("image_urls") or []
|
| 49 |
+
if isinstance(extras, str):
|
| 50 |
+
try:
|
| 51 |
+
extras = _json.loads(extras)
|
| 52 |
+
except Exception:
|
| 53 |
+
extras = []
|
| 54 |
+
if isinstance(extras, list):
|
| 55 |
+
for u in extras:
|
| 56 |
+
if isinstance(u, str) and u and u not in urls:
|
| 57 |
+
urls.append(u)
|
| 58 |
+
urls = urls[:max_per_product]
|
| 59 |
+
|
| 60 |
+
local_paths: list[str] = []
|
| 61 |
+
for u in urls:
|
| 62 |
+
try:
|
| 63 |
+
h = hashlib.md5(u.encode()).hexdigest()[:14]
|
| 64 |
+
path = cache_dir / f"{h}.jpg"
|
| 65 |
+
if path.exists() and path.stat().st_size > 1000:
|
| 66 |
+
local_paths.append(str(path))
|
| 67 |
+
continue
|
| 68 |
+
resp = client.get(u)
|
| 69 |
+
if resp.status_code == 200 and len(resp.content) > 1000:
|
| 70 |
+
path.write_bytes(resp.content)
|
| 71 |
+
local_paths.append(str(path))
|
| 72 |
+
except Exception:
|
| 73 |
+
continue
|
| 74 |
+
|
| 75 |
+
if local_paths:
|
| 76 |
+
p["image_path"] = local_paths[0]
|
| 77 |
+
p["image_paths"] = _json.dumps(local_paths)
|
| 78 |
|
| 79 |
downloaded = sum(1 for p in products if p.get("image_path"))
|
| 80 |
+
multi = sum(1 for p in products
|
| 81 |
+
if p.get("image_paths") and p["image_paths"] not in ("[]", ""))
|
| 82 |
+
print(f" Downloaded {downloaded}/{len(products)} primary, {multi} multi-image", flush=True)
|
| 83 |
return products
|
taste/store.py
CHANGED
|
@@ -30,6 +30,7 @@ CREATE TABLE IF NOT EXISTS products (
|
|
| 30 |
|
| 31 |
score REAL,
|
| 32 |
image_path TEXT DEFAULT '',
|
|
|
|
| 33 |
|
| 34 |
first_seen_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
| 35 |
last_seen_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
@@ -75,6 +76,7 @@ class ProductStore:
|
|
| 75 |
"currency": "TEXT DEFAULT 'NOK'",
|
| 76 |
"on_sale": "BOOLEAN DEFAULT 0",
|
| 77 |
"image_urls": "TEXT DEFAULT '[]'",
|
|
|
|
| 78 |
"in_stock": "BOOLEAN DEFAULT 1",
|
| 79 |
"sizes": "TEXT DEFAULT '[]'",
|
| 80 |
"first_seen_at": "TIMESTAMP DEFAULT ''",
|
|
@@ -156,17 +158,20 @@ class ProductStore:
|
|
| 156 |
sizes = p.get("sizes", "[]")
|
| 157 |
if not isinstance(sizes, str):
|
| 158 |
sizes = json.dumps(sizes if isinstance(sizes, list) else [])
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
self.conn.execute("""
|
| 161 |
INSERT INTO products (
|
| 162 |
url, external_id, store, brand, name, color, material, category,
|
| 163 |
price_nok, original_price_nok, price_text, currency, on_sale,
|
| 164 |
-
image_url, image_urls, in_stock, sizes, score, image_path,
|
| 165 |
first_seen_at, last_seen_at, updated_at
|
| 166 |
) VALUES (
|
| 167 |
:url, :external_id, :store, :brand, :name, :color, :material, :category,
|
| 168 |
:price_nok, :original_price_nok, :price_text, :currency, :on_sale,
|
| 169 |
-
:image_url, :image_urls, :in_stock, :sizes, :score, :image_path,
|
| 170 |
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
| 171 |
)
|
| 172 |
ON CONFLICT(url) DO UPDATE SET
|
|
@@ -186,6 +191,7 @@ class ProductStore:
|
|
| 186 |
in_stock = excluded.in_stock,
|
| 187 |
sizes = CASE WHEN excluded.sizes != '[]' THEN excluded.sizes ELSE products.sizes END,
|
| 188 |
image_path = COALESCE(NULLIF(excluded.image_path, ''), products.image_path),
|
|
|
|
| 189 |
last_seen_at = CURRENT_TIMESTAMP,
|
| 190 |
updated_at = CURRENT_TIMESTAMP
|
| 191 |
""", {
|
|
@@ -208,6 +214,7 @@ class ProductStore:
|
|
| 208 |
"sizes": sizes,
|
| 209 |
"score": p.get("score"),
|
| 210 |
"image_path": p.get("image_path", ""),
|
|
|
|
| 211 |
})
|
| 212 |
|
| 213 |
# --- Sync (idempotent scrape ingestion) ---
|
|
@@ -268,10 +275,26 @@ class ProductStore:
|
|
| 268 |
|
| 269 |
def get_unscored_with_category(self) -> list[dict]:
|
| 270 |
rows = self.conn.execute(
|
| 271 |
-
"SELECT url, image_path, category
|
|
|
|
|
|
|
| 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 |
|
|
|
|
| 30 |
|
| 31 |
score REAL,
|
| 32 |
image_path TEXT DEFAULT '',
|
| 33 |
+
image_paths TEXT DEFAULT '[]',
|
| 34 |
|
| 35 |
first_seen_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
| 36 |
last_seen_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
|
|
| 76 |
"currency": "TEXT DEFAULT 'NOK'",
|
| 77 |
"on_sale": "BOOLEAN DEFAULT 0",
|
| 78 |
"image_urls": "TEXT DEFAULT '[]'",
|
| 79 |
+
"image_paths": "TEXT DEFAULT '[]'",
|
| 80 |
"in_stock": "BOOLEAN DEFAULT 1",
|
| 81 |
"sizes": "TEXT DEFAULT '[]'",
|
| 82 |
"first_seen_at": "TIMESTAMP DEFAULT ''",
|
|
|
|
| 158 |
sizes = p.get("sizes", "[]")
|
| 159 |
if not isinstance(sizes, str):
|
| 160 |
sizes = json.dumps(sizes if isinstance(sizes, list) else [])
|
| 161 |
+
image_paths = p.get("image_paths", "[]")
|
| 162 |
+
if not isinstance(image_paths, str):
|
| 163 |
+
image_paths = json.dumps(image_paths if isinstance(image_paths, list) else [])
|
| 164 |
|
| 165 |
self.conn.execute("""
|
| 166 |
INSERT INTO products (
|
| 167 |
url, external_id, store, brand, name, color, material, category,
|
| 168 |
price_nok, original_price_nok, price_text, currency, on_sale,
|
| 169 |
+
image_url, image_urls, in_stock, sizes, score, image_path, image_paths,
|
| 170 |
first_seen_at, last_seen_at, updated_at
|
| 171 |
) VALUES (
|
| 172 |
:url, :external_id, :store, :brand, :name, :color, :material, :category,
|
| 173 |
:price_nok, :original_price_nok, :price_text, :currency, :on_sale,
|
| 174 |
+
:image_url, :image_urls, :in_stock, :sizes, :score, :image_path, :image_paths,
|
| 175 |
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
| 176 |
)
|
| 177 |
ON CONFLICT(url) DO UPDATE SET
|
|
|
|
| 191 |
in_stock = excluded.in_stock,
|
| 192 |
sizes = CASE WHEN excluded.sizes != '[]' THEN excluded.sizes ELSE products.sizes END,
|
| 193 |
image_path = COALESCE(NULLIF(excluded.image_path, ''), products.image_path),
|
| 194 |
+
image_paths = CASE WHEN excluded.image_paths != '[]' THEN excluded.image_paths ELSE products.image_paths END,
|
| 195 |
last_seen_at = CURRENT_TIMESTAMP,
|
| 196 |
updated_at = CURRENT_TIMESTAMP
|
| 197 |
""", {
|
|
|
|
| 214 |
"sizes": sizes,
|
| 215 |
"score": p.get("score"),
|
| 216 |
"image_path": p.get("image_path", ""),
|
| 217 |
+
"image_paths": image_paths,
|
| 218 |
})
|
| 219 |
|
| 220 |
# --- Sync (idempotent scrape ingestion) ---
|
|
|
|
| 275 |
|
| 276 |
def get_unscored_with_category(self) -> list[dict]:
|
| 277 |
rows = self.conn.execute(
|
| 278 |
+
"SELECT url, image_path, image_paths, category, brand, name, color, material, "
|
| 279 |
+
"price_nok, on_sale "
|
| 280 |
+
"FROM products WHERE image_path != '' AND score IS NULL"
|
| 281 |
).fetchall()
|
| 282 |
return [dict(r) for r in rows]
|
| 283 |
|
| 284 |
+
def get_user_profile_inputs(self) -> list[dict]:
|
| 285 |
+
"""Return rated products with metadata for derive_user_metadata_profile()."""
|
| 286 |
+
try:
|
| 287 |
+
rows = self.conn.execute("""
|
| 288 |
+
SELECT dr.rating, p.price_nok, p.on_sale
|
| 289 |
+
FROM discover_ratings dr JOIN products p ON p.url = dr.url
|
| 290 |
+
WHERE dr.rating != 0
|
| 291 |
+
""").fetchall()
|
| 292 |
+
return [{"rating": r["rating"],
|
| 293 |
+
"price_nok": r["price_nok"],
|
| 294 |
+
"on_sale": bool(r["on_sale"])} for r in rows]
|
| 295 |
+
except Exception:
|
| 296 |
+
return []
|
| 297 |
+
|
| 298 |
def update_score(self, url: str, score: float):
|
| 299 |
self.conn.execute("UPDATE products SET score = ?, updated_at = CURRENT_TIMESTAMP WHERE url = ?", (score, url))
|
| 300 |
|