Spaces:
Sleeping
Sleeping
Commit ·
f02ea7f
1
Parent(s): 3727c82
Refactor into configurable package structure
Browse files- Extract taste/ package with clean module boundaries:
taste/config.py (YAML config + user profiles)
taste/engine.py (merged v1+v2 FashionSigLIP engine)
taste/store.py (ProductStore class, db_path from config)
taste/models.py (shared Product dataclass)
taste/scrapers/ (registry + per-store scraper classes)
taste/pipeline.py (scan orchestrator)
taste/output.py (HTML generation with dynamic store filters)
- All store URLs, API keys, categories now in config.yaml
- User preferences (liked images, disliked brands) in profiles
- CLI entry point: taste scan/stats/profile
- No more hardcoded paths or user-specific data in source
- api_scrapers.py +0 -495
- app.py +0 -362
- cli.py +112 -0
- config.example.yaml +47 -0
- engine_v2.py +0 -346
- evaluate.py +0 -127
- evaluate_v2.py +0 -198
- pyproject.toml +9 -5
- scan.py +0 -386
- scraper.py +0 -798
- store.py +0 -150
- taste/__init__.py +8 -0
- taste/config.py +196 -0
- engine.py → taste/engine.py +85 -46
- taste/models.py +47 -0
- merge_results.py → taste/output.py +65 -97
- scan_v2.py → taste/pipeline.py +137 -146
- taste/scrapers/__init__.py +33 -0
- taste/scrapers/api/__init__.py +0 -0
- taste/scrapers/api/boozt.py +120 -0
- taste/scrapers/api/miinto.py +141 -0
- taste/scrapers/api/nakd.py +94 -0
- taste/scrapers/api/wakakuu.py +89 -0
- taste/scrapers/base.py +51 -0
- taste/scrapers/browser/__init__.py +0 -0
- taste/store.py +149 -0
api_scrapers.py
DELETED
|
@@ -1,495 +0,0 @@
|
|
| 1 |
-
"""Direct API scrapers — no browser needed. 100-500x faster than Playwright."""
|
| 2 |
-
|
| 3 |
-
import sys
|
| 4 |
-
import hashlib
|
| 5 |
-
import re
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
|
| 8 |
-
import httpx
|
| 9 |
-
|
| 10 |
-
sys.stdout.reconfigure(line_buffering=True)
|
| 11 |
-
|
| 12 |
-
CACHE_BASE = Path.home() / ".taste"
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
# --- Wakakuu (Algolia API) ---
|
| 16 |
-
|
| 17 |
-
def scrape_wakakuu(query: str = "", max_products: int = 2000) -> list[dict]:
|
| 18 |
-
"""Query Wakakuu's public Algolia index. Returns product dicts."""
|
| 19 |
-
cache_dir = CACHE_BASE / "products-wakakuu"
|
| 20 |
-
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 21 |
-
|
| 22 |
-
app_id = "0LM8YN9I0K"
|
| 23 |
-
api_key = "00ef309f4d1543ffdaa1d85c33111700"
|
| 24 |
-
index = "prod_products_sv"
|
| 25 |
-
url = f"https://{app_id}-dsn.algolia.net/1/indexes/{index}/query"
|
| 26 |
-
|
| 27 |
-
headers = {
|
| 28 |
-
"X-Algolia-Application-Id": app_id,
|
| 29 |
-
"X-Algolia-API-Key": api_key,
|
| 30 |
-
"Content-Type": "application/json",
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
products = []
|
| 34 |
-
page = 0
|
| 35 |
-
hits_per_page = 100
|
| 36 |
-
|
| 37 |
-
with httpx.Client(timeout=30) as client:
|
| 38 |
-
while len(products) < max_products:
|
| 39 |
-
body = {
|
| 40 |
-
"params": f"query={query}&hitsPerPage={hits_per_page}&page={page}"
|
| 41 |
-
f"&filters=categories.lvl0:Väskor"
|
| 42 |
-
}
|
| 43 |
-
resp = client.post(url, headers=headers, json=body)
|
| 44 |
-
if resp.status_code != 200:
|
| 45 |
-
print(f" Wakakuu API error: {resp.status_code}", flush=True)
|
| 46 |
-
break
|
| 47 |
-
|
| 48 |
-
data = resp.json()
|
| 49 |
-
hits = data.get("hits", [])
|
| 50 |
-
if not hits:
|
| 51 |
-
break
|
| 52 |
-
|
| 53 |
-
for hit in hits:
|
| 54 |
-
image = hit.get("imageUrl", "")
|
| 55 |
-
if not image:
|
| 56 |
-
image = hit.get("image", "")
|
| 57 |
-
|
| 58 |
-
# Extract price — nested dict by currency and user type
|
| 59 |
-
prices = hit.get("price", {})
|
| 60 |
-
price_val = 0
|
| 61 |
-
if isinstance(prices, dict):
|
| 62 |
-
for currency in ("NOK", "SEK", "EUR"):
|
| 63 |
-
bucket = prices.get(currency)
|
| 64 |
-
if bucket is None:
|
| 65 |
-
continue
|
| 66 |
-
if isinstance(bucket, dict):
|
| 67 |
-
raw = bucket.get("anonymous", bucket.get("default", 0))
|
| 68 |
-
if isinstance(raw, dict):
|
| 69 |
-
raw = raw.get("amount", raw.get("value", 0))
|
| 70 |
-
price_val = float(raw or 0)
|
| 71 |
-
if price_val:
|
| 72 |
-
break
|
| 73 |
-
elif isinstance(bucket, (int, float)):
|
| 74 |
-
price_val = float(bucket)
|
| 75 |
-
break
|
| 76 |
-
elif isinstance(bucket, str):
|
| 77 |
-
try:
|
| 78 |
-
price_val = float(bucket)
|
| 79 |
-
if price_val:
|
| 80 |
-
break
|
| 81 |
-
except ValueError:
|
| 82 |
-
continue
|
| 83 |
-
elif isinstance(prices, (int, float)):
|
| 84 |
-
price_val = float(prices)
|
| 85 |
-
|
| 86 |
-
product_url = hit.get("url", "")
|
| 87 |
-
if product_url and not product_url.startswith("http"):
|
| 88 |
-
product_url = f"https://www.wakakuu.com{product_url}"
|
| 89 |
-
|
| 90 |
-
products.append({
|
| 91 |
-
"url": product_url,
|
| 92 |
-
"image_url": image,
|
| 93 |
-
"brand": hit.get("brand", ""),
|
| 94 |
-
"name": hit.get("name", hit.get("title", "")),
|
| 95 |
-
"price_nok": price_val,
|
| 96 |
-
"price_text": f"{price_val:.0f} kr" if price_val else "",
|
| 97 |
-
"store": "Wakakuu",
|
| 98 |
-
})
|
| 99 |
-
|
| 100 |
-
print(f" Wakakuu: page {page}, +{len(hits)} hits, {len(products)} total", flush=True)
|
| 101 |
-
|
| 102 |
-
nb_pages = data.get("nbPages", 0)
|
| 103 |
-
page += 1
|
| 104 |
-
if page >= nb_pages:
|
| 105 |
-
break
|
| 106 |
-
|
| 107 |
-
_download_images(products, cache_dir)
|
| 108 |
-
return products
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
# --- Boozt (XHR JSON) ---
|
| 112 |
-
|
| 113 |
-
def scrape_boozt(categories: list[str] | None = None, max_products: int = 5000) -> list[dict]:
|
| 114 |
-
"""Scrape Boozt using their internal products API."""
|
| 115 |
-
import json as _json
|
| 116 |
-
|
| 117 |
-
cache_dir = CACHE_BASE / "products-boozt"
|
| 118 |
-
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 119 |
-
|
| 120 |
-
if categories is None:
|
| 121 |
-
categories = [
|
| 122 |
-
"/no/no/kvinner/vesker",
|
| 123 |
-
"/no/no/kvinner/vesker/skuldervesker",
|
| 124 |
-
"/no/no/kvinner/vesker/haandvesker",
|
| 125 |
-
"/no/no/kvinner/vesker/crossbody-vesker",
|
| 126 |
-
]
|
| 127 |
-
|
| 128 |
-
products = []
|
| 129 |
-
seen_urls = set()
|
| 130 |
-
|
| 131 |
-
headers = {
|
| 132 |
-
"Accept": "application/json, text/html",
|
| 133 |
-
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
|
| 134 |
-
}
|
| 135 |
-
|
| 136 |
-
with httpx.Client(timeout=30, headers=headers, follow_redirects=True) as client:
|
| 137 |
-
for cat in categories:
|
| 138 |
-
if len(products) >= max_products:
|
| 139 |
-
break
|
| 140 |
-
cat_url = cat if cat.startswith("http") else f"https://www.boozt.com{cat}"
|
| 141 |
-
|
| 142 |
-
# Step 1: Get navigationId from the category HTML page
|
| 143 |
-
try:
|
| 144 |
-
html_resp = client.get(cat_url)
|
| 145 |
-
if html_resp.status_code != 200:
|
| 146 |
-
print(f" Boozt: {cat} returned {html_resp.status_code}", flush=True)
|
| 147 |
-
continue
|
| 148 |
-
nav_match = re.search(
|
| 149 |
-
r'data-component-name="ListingPageSSR"[^>]*data-props="([^"]*)"',
|
| 150 |
-
html_resp.text,
|
| 151 |
-
)
|
| 152 |
-
if not nav_match:
|
| 153 |
-
# Try alternate: look for navigationId in script tags
|
| 154 |
-
nav_match2 = re.search(r'"baseNavigationId"\s*:\s*(\d+)', html_resp.text)
|
| 155 |
-
if not nav_match2:
|
| 156 |
-
nav_match2 = re.search(r'"navigationId"\s*:\s*(\d+)', html_resp.text)
|
| 157 |
-
if not nav_match2:
|
| 158 |
-
print(f" Boozt: no navigationId found for {cat}", flush=True)
|
| 159 |
-
continue
|
| 160 |
-
nav_id = nav_match2.group(1)
|
| 161 |
-
else:
|
| 162 |
-
import html as _html
|
| 163 |
-
props_json = _html.unescape(nav_match.group(1))
|
| 164 |
-
props = _json.loads(props_json)
|
| 165 |
-
nav_id = str(props.get("baseNavigationId", ""))
|
| 166 |
-
if not nav_id:
|
| 167 |
-
print(f" Boozt: no baseNavigationId in props for {cat}", flush=True)
|
| 168 |
-
continue
|
| 169 |
-
except Exception as e:
|
| 170 |
-
print(f" Boozt: error getting navId for {cat}: {e}", flush=True)
|
| 171 |
-
continue
|
| 172 |
-
|
| 173 |
-
print(f" Boozt: {cat.split('/')[-1]} navId={nav_id}", flush=True)
|
| 174 |
-
|
| 175 |
-
# Step 2: Fetch products (API ignores page param, use large limit)
|
| 176 |
-
try:
|
| 177 |
-
api_url = f"https://www.boozt.com/no/no/api/navigation/{nav_id}/products?limit=500&material=ekte-skinn"
|
| 178 |
-
resp = client.get(api_url)
|
| 179 |
-
if resp.status_code != 200:
|
| 180 |
-
print(f" Boozt: products API returned {resp.status_code}", flush=True)
|
| 181 |
-
continue
|
| 182 |
-
|
| 183 |
-
data = resp.json()
|
| 184 |
-
cards = data.get("product_cards", [])
|
| 185 |
-
|
| 186 |
-
new_count = 0
|
| 187 |
-
for card in cards:
|
| 188 |
-
prod_url = card.get("product_url", "")
|
| 189 |
-
if not prod_url:
|
| 190 |
-
continue
|
| 191 |
-
if not prod_url.startswith("http"):
|
| 192 |
-
prod_url = f"https://www.boozt.com{prod_url}"
|
| 193 |
-
if prod_url in seen_urls:
|
| 194 |
-
continue
|
| 195 |
-
seen_urls.add(prod_url)
|
| 196 |
-
|
| 197 |
-
# Price
|
| 198 |
-
prices = card.get("prices", {})
|
| 199 |
-
base = prices.get("base", {})
|
| 200 |
-
price_str = base.get("price", "0")
|
| 201 |
-
price_val = float(re.sub(r"[^\d.]", "", str(price_str)) or 0)
|
| 202 |
-
|
| 203 |
-
# Image
|
| 204 |
-
media = card.get("media", [])
|
| 205 |
-
image_url = media[0].get("url", "") if media else ""
|
| 206 |
-
|
| 207 |
-
products.append({
|
| 208 |
-
"url": prod_url,
|
| 209 |
-
"image_url": image_url,
|
| 210 |
-
"brand": card.get("brand_name", ""),
|
| 211 |
-
"name": card.get("display_name", ""),
|
| 212 |
-
"price_nok": price_val,
|
| 213 |
-
"price_text": base.get("formatted_price", f"{price_val:.0f} kr"),
|
| 214 |
-
"store": "Boozt",
|
| 215 |
-
})
|
| 216 |
-
new_count += 1
|
| 217 |
-
|
| 218 |
-
print(f" Boozt: {cat.split('/')[-1]} +{new_count} products, {len(products)} total", flush=True)
|
| 219 |
-
|
| 220 |
-
except Exception as e:
|
| 221 |
-
print(f" Boozt: error for {cat}: {e}", flush=True)
|
| 222 |
-
|
| 223 |
-
_download_images(products, cache_dir)
|
| 224 |
-
return products
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
# --- Miinto (SSR preloaded state) ---
|
| 228 |
-
|
| 229 |
-
def scrape_miinto(categories: list[str] | None = None, max_products: int = 5000) -> list[dict]:
|
| 230 |
-
"""Scrape Miinto by extracting __PLP_PRELOADED_STATE__ from SSR HTML."""
|
| 231 |
-
import json
|
| 232 |
-
|
| 233 |
-
cache_dir = CACHE_BASE / "products-miinto"
|
| 234 |
-
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 235 |
-
|
| 236 |
-
if categories is None:
|
| 237 |
-
categories = [
|
| 238 |
-
"/dame-skuldervesker",
|
| 239 |
-
"/dame-handvesker",
|
| 240 |
-
"/dame-clutch-vesker",
|
| 241 |
-
]
|
| 242 |
-
|
| 243 |
-
products = []
|
| 244 |
-
seen_urls = set()
|
| 245 |
-
|
| 246 |
-
headers = {
|
| 247 |
-
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
|
| 248 |
-
"Accept": "text/html",
|
| 249 |
-
"Accept-Language": "nb-NO,nb;q=0.9",
|
| 250 |
-
}
|
| 251 |
-
|
| 252 |
-
with httpx.Client(timeout=30, headers=headers, follow_redirects=True) as client:
|
| 253 |
-
for cat in categories:
|
| 254 |
-
cat_url = cat if cat.startswith("http") else f"https://www.miinto.no{cat}"
|
| 255 |
-
page_num = 1
|
| 256 |
-
|
| 257 |
-
while len(products) < max_products:
|
| 258 |
-
url = f"{cat_url}?page={page_num}"
|
| 259 |
-
resp = client.get(url)
|
| 260 |
-
|
| 261 |
-
if resp.status_code != 200:
|
| 262 |
-
break
|
| 263 |
-
|
| 264 |
-
text = resp.text
|
| 265 |
-
|
| 266 |
-
# Extract __PLP_PRELOADED_STATE__
|
| 267 |
-
# Miinto wraps it as: window.__PLP_PRELOADED_STATE__ = JSON.stringify({...});
|
| 268 |
-
state = None
|
| 269 |
-
marker = "__PLP_PRELOADED_STATE__"
|
| 270 |
-
marker_idx = text.find(marker)
|
| 271 |
-
if marker_idx != -1:
|
| 272 |
-
stringify_idx = text.find("JSON.stringify(", marker_idx)
|
| 273 |
-
if stringify_idx != -1:
|
| 274 |
-
obj_start = stringify_idx + len("JSON.stringify(")
|
| 275 |
-
# Brace-balanced extraction
|
| 276 |
-
depth = 0
|
| 277 |
-
in_str = False
|
| 278 |
-
esc = False
|
| 279 |
-
end = obj_start
|
| 280 |
-
for end in range(obj_start, min(obj_start + 500_000, len(text))):
|
| 281 |
-
c = text[end]
|
| 282 |
-
if esc:
|
| 283 |
-
esc = False
|
| 284 |
-
continue
|
| 285 |
-
if c == "\\":
|
| 286 |
-
esc = True
|
| 287 |
-
continue
|
| 288 |
-
if c == '"':
|
| 289 |
-
in_str = not in_str
|
| 290 |
-
if not in_str:
|
| 291 |
-
if c == "{":
|
| 292 |
-
depth += 1
|
| 293 |
-
elif c == "}":
|
| 294 |
-
depth -= 1
|
| 295 |
-
if depth == 0:
|
| 296 |
-
break
|
| 297 |
-
if depth == 0:
|
| 298 |
-
try:
|
| 299 |
-
state = json.loads(text[obj_start : end + 1])
|
| 300 |
-
except json.JSONDecodeError:
|
| 301 |
-
pass
|
| 302 |
-
|
| 303 |
-
if state is None:
|
| 304 |
-
break
|
| 305 |
-
|
| 306 |
-
# Navigate to products array
|
| 307 |
-
prods_data = []
|
| 308 |
-
if isinstance(state, dict):
|
| 309 |
-
# Try various paths
|
| 310 |
-
for key in ["products", "items", "results"]:
|
| 311 |
-
if key in state:
|
| 312 |
-
prods_data = state[key]
|
| 313 |
-
break
|
| 314 |
-
if not prods_data and "data" in state:
|
| 315 |
-
d = state["data"]
|
| 316 |
-
if isinstance(d, dict):
|
| 317 |
-
for key in ["products", "items"]:
|
| 318 |
-
if key in d:
|
| 319 |
-
prods_data = d[key]
|
| 320 |
-
break
|
| 321 |
-
elif isinstance(state, list):
|
| 322 |
-
prods_data = state
|
| 323 |
-
|
| 324 |
-
if not prods_data:
|
| 325 |
-
break
|
| 326 |
-
|
| 327 |
-
new_count = 0
|
| 328 |
-
for item in prods_data:
|
| 329 |
-
prod_url = item.get("url", "")
|
| 330 |
-
if prod_url and not prod_url.startswith("http"):
|
| 331 |
-
prod_url = f"https://www.miinto.no{prod_url}"
|
| 332 |
-
if prod_url in seen_urls or not prod_url:
|
| 333 |
-
continue
|
| 334 |
-
seen_urls.add(prod_url)
|
| 335 |
-
|
| 336 |
-
# Prices are in hundredths (ore) — divide by 100 for NOK
|
| 337 |
-
price_data = item.get("price", {})
|
| 338 |
-
if isinstance(price_data, dict):
|
| 339 |
-
price_raw = price_data.get("price", price_data.get("originalPrice", 0))
|
| 340 |
-
else:
|
| 341 |
-
price_raw = price_data
|
| 342 |
-
price_nok = float(price_raw or 0) / 100
|
| 343 |
-
|
| 344 |
-
# Image
|
| 345 |
-
photo = item.get("photo", {})
|
| 346 |
-
image_url = photo.get("url", "") if isinstance(photo, dict) else str(photo)
|
| 347 |
-
|
| 348 |
-
products.append({
|
| 349 |
-
"url": prod_url,
|
| 350 |
-
"image_url": image_url,
|
| 351 |
-
"brand": item.get("brand", ""),
|
| 352 |
-
"name": item.get("title", item.get("name", "")),
|
| 353 |
-
"price_nok": price_nok,
|
| 354 |
-
"price_text": f"{price_nok:.0f} kr" if price_nok else "",
|
| 355 |
-
"store": "Miinto",
|
| 356 |
-
})
|
| 357 |
-
new_count += 1
|
| 358 |
-
|
| 359 |
-
print(f" Miinto: {cat.split('/')[-1]} page {page_num}, +{new_count}, {len(products)} total", flush=True)
|
| 360 |
-
|
| 361 |
-
if new_count == 0:
|
| 362 |
-
break
|
| 363 |
-
|
| 364 |
-
page_num += 1
|
| 365 |
-
|
| 366 |
-
_download_images(products, cache_dir)
|
| 367 |
-
return products
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
# --- NA-KD (SSR JSON-LD) ---
|
| 371 |
-
|
| 372 |
-
def scrape_nakd(categories: list[str] | None = None, max_products: int = 2000) -> list[dict]:
|
| 373 |
-
"""Scrape NA-KD by extracting JSON-LD from SSR HTML."""
|
| 374 |
-
import json
|
| 375 |
-
|
| 376 |
-
cache_dir = CACHE_BASE / "products-nakd"
|
| 377 |
-
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 378 |
-
|
| 379 |
-
if categories is None:
|
| 380 |
-
categories = [
|
| 381 |
-
"/no/category/vesker",
|
| 382 |
-
"/no/category/vesker/skuldervesker",
|
| 383 |
-
]
|
| 384 |
-
|
| 385 |
-
products = []
|
| 386 |
-
seen_urls = set()
|
| 387 |
-
|
| 388 |
-
headers = {
|
| 389 |
-
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
|
| 390 |
-
"Accept": "text/html",
|
| 391 |
-
"Accept-Language": "nb-NO,nb;q=0.9",
|
| 392 |
-
}
|
| 393 |
-
|
| 394 |
-
with httpx.Client(timeout=30, headers=headers, follow_redirects=True) as client:
|
| 395 |
-
for cat in categories:
|
| 396 |
-
cat_url = cat if cat.startswith("http") else f"https://www.na-kd.com{cat}"
|
| 397 |
-
page_num = 1
|
| 398 |
-
|
| 399 |
-
while len(products) < max_products:
|
| 400 |
-
url = f"{cat_url}?page={page_num}"
|
| 401 |
-
resp = client.get(url)
|
| 402 |
-
|
| 403 |
-
if resp.status_code != 200:
|
| 404 |
-
break
|
| 405 |
-
|
| 406 |
-
text = resp.text
|
| 407 |
-
|
| 408 |
-
# Extract JSON-LD ItemList
|
| 409 |
-
ld_matches = re.findall(
|
| 410 |
-
r'<script[^>]*type="application/ld\+json"[^>]*>(.*?)</script>',
|
| 411 |
-
text, re.DOTALL
|
| 412 |
-
)
|
| 413 |
-
|
| 414 |
-
new_count = 0
|
| 415 |
-
for ld_text in ld_matches:
|
| 416 |
-
try:
|
| 417 |
-
ld = json.loads(ld_text)
|
| 418 |
-
except json.JSONDecodeError:
|
| 419 |
-
continue
|
| 420 |
-
|
| 421 |
-
items = []
|
| 422 |
-
if isinstance(ld, dict):
|
| 423 |
-
if ld.get("@type") == "ItemList":
|
| 424 |
-
items = ld.get("itemListElement", [])
|
| 425 |
-
elif ld.get("@type") in ("Product", "ProductGroup"):
|
| 426 |
-
items = [ld]
|
| 427 |
-
|
| 428 |
-
for item in items:
|
| 429 |
-
product = item.get("item", item) if "item" in item else item
|
| 430 |
-
prod_url = product.get("url", "")
|
| 431 |
-
if prod_url in seen_urls or not prod_url:
|
| 432 |
-
continue
|
| 433 |
-
seen_urls.add(prod_url)
|
| 434 |
-
|
| 435 |
-
image = product.get("image", "")
|
| 436 |
-
if isinstance(image, list):
|
| 437 |
-
image = image[0] if image else ""
|
| 438 |
-
|
| 439 |
-
offers = product.get("offers", {})
|
| 440 |
-
if isinstance(offers, list):
|
| 441 |
-
offers = offers[0] if offers else {}
|
| 442 |
-
price_val = float(offers.get("price", 0))
|
| 443 |
-
|
| 444 |
-
products.append({
|
| 445 |
-
"url": prod_url,
|
| 446 |
-
"image_url": image,
|
| 447 |
-
"brand": product.get("brand", {}).get("name", "") if isinstance(product.get("brand"), dict) else str(product.get("brand", "")),
|
| 448 |
-
"name": product.get("name", ""),
|
| 449 |
-
"price_nok": price_val,
|
| 450 |
-
"price_text": f"{price_val:.0f} kr" if price_val else "",
|
| 451 |
-
"store": "NA-KD",
|
| 452 |
-
})
|
| 453 |
-
new_count += 1
|
| 454 |
-
|
| 455 |
-
print(f" NA-KD: {cat.split('/')[-1]} page {page_num}, +{new_count}, {len(products)} total", flush=True)
|
| 456 |
-
|
| 457 |
-
if new_count == 0:
|
| 458 |
-
break
|
| 459 |
-
|
| 460 |
-
page_num += 1
|
| 461 |
-
|
| 462 |
-
_download_images(products, cache_dir)
|
| 463 |
-
return products
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
# --- Shared image downloader ---
|
| 467 |
-
|
| 468 |
-
def _download_images(products: list[dict], cache_dir: Path, concurrency: int = 20):
|
| 469 |
-
"""Download product images with connection pooling."""
|
| 470 |
-
to_download = [(p, cache_dir) for p in products if p.get("image_url") and not p.get("image_path")]
|
| 471 |
-
|
| 472 |
-
if not to_download:
|
| 473 |
-
return
|
| 474 |
-
|
| 475 |
-
with httpx.Client(
|
| 476 |
-
timeout=15,
|
| 477 |
-
follow_redirects=True,
|
| 478 |
-
limits=httpx.Limits(max_connections=concurrency, max_keepalive_connections=10),
|
| 479 |
-
) as client:
|
| 480 |
-
for p, cdir in to_download:
|
| 481 |
-
try:
|
| 482 |
-
h = hashlib.md5(p["url"].encode()).hexdigest()[:12]
|
| 483 |
-
path = cdir / f"{h}.jpg"
|
| 484 |
-
if path.exists():
|
| 485 |
-
p["image_path"] = str(path)
|
| 486 |
-
continue
|
| 487 |
-
resp = client.get(p["image_url"])
|
| 488 |
-
if resp.status_code == 200 and len(resp.content) > 1000:
|
| 489 |
-
path.write_bytes(resp.content)
|
| 490 |
-
p["image_path"] = str(path)
|
| 491 |
-
except Exception:
|
| 492 |
-
continue
|
| 493 |
-
|
| 494 |
-
downloaded = sum(1 for p in products if p.get("image_path"))
|
| 495 |
-
print(f" Downloaded {downloaded}/{len(products)} images", flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
DELETED
|
@@ -1,362 +0,0 @@
|
|
| 1 |
-
"""Taste Engine — Streamlit UI for rating, discovering, and shopping."""
|
| 2 |
-
|
| 3 |
-
import streamlit as st
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
from urllib.parse import quote
|
| 6 |
-
from engine import TasteEngine, find_images
|
| 7 |
-
|
| 8 |
-
st.set_page_config(page_title="Taste Engine", layout="wide")
|
| 9 |
-
|
| 10 |
-
REFERENCE_DIR = Path(__file__).parent / "reference-images"
|
| 11 |
-
|
| 12 |
-
ZALANDO_CATEGORIES = {
|
| 13 |
-
"All bags": "/dame-vesker/",
|
| 14 |
-
"Shoulder bags": "/dame-skulderveske/",
|
| 15 |
-
"Handbags": "/dame-handveske/",
|
| 16 |
-
"Jackets": "/dame-jakker/",
|
| 17 |
-
"Dresses": "/dame-kjoler/",
|
| 18 |
-
"Trousers": "/dame-bukser/",
|
| 19 |
-
"Skirts": "/dame-skjort/",
|
| 20 |
-
"Tops": "/dame-topper/",
|
| 21 |
-
"Knitwear": "/dame-strikk/",
|
| 22 |
-
"Shirts & blouses": "/dame-bluser-tunikaer/",
|
| 23 |
-
"Shoes": "/dame-sko/",
|
| 24 |
-
"Custom search": None,
|
| 25 |
-
}
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
@st.cache_resource
|
| 29 |
-
def get_engine():
|
| 30 |
-
engine = TasteEngine()
|
| 31 |
-
if REFERENCE_DIR.is_dir() and engine.stats()["total"] == 0:
|
| 32 |
-
engine.seed_from_references(REFERENCE_DIR)
|
| 33 |
-
return engine
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
engine = get_engine()
|
| 37 |
-
|
| 38 |
-
# --- Sidebar ---
|
| 39 |
-
st.sidebar.title("Taste Engine")
|
| 40 |
-
|
| 41 |
-
mode = st.sidebar.radio("Mode", ["Shop", "Rate", "Compare", "Discover"])
|
| 42 |
-
|
| 43 |
-
stats = engine.stats()
|
| 44 |
-
if stats["total"] > 0:
|
| 45 |
-
st.sidebar.divider()
|
| 46 |
-
st.sidebar.metric("Liked", stats["liked"])
|
| 47 |
-
st.sidebar.metric("Disliked", stats["disliked"])
|
| 48 |
-
st.sidebar.metric("Total rated", stats["total"])
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
def render_product_grid(products: list, container):
|
| 52 |
-
"""Render scored products as a grid."""
|
| 53 |
-
if not products:
|
| 54 |
-
return
|
| 55 |
-
|
| 56 |
-
scores = [p.score for p in products]
|
| 57 |
-
min_s, max_s = min(scores), max(scores)
|
| 58 |
-
score_range = max_s - min_s if max_s != min_s else 1.0
|
| 59 |
-
|
| 60 |
-
cols_per_row = 4
|
| 61 |
-
for row_start in range(0, len(products), cols_per_row):
|
| 62 |
-
row = products[row_start : row_start + cols_per_row]
|
| 63 |
-
cols = container.columns(cols_per_row)
|
| 64 |
-
for col, product in zip(cols, row):
|
| 65 |
-
with col:
|
| 66 |
-
normalized = int(100 * (product.score - min_s) / score_range)
|
| 67 |
-
|
| 68 |
-
if product.image_path and product.image_path.exists():
|
| 69 |
-
st.image(str(product.image_path), use_container_width=True)
|
| 70 |
-
elif product.image_url:
|
| 71 |
-
st.image(product.image_url, use_container_width=True)
|
| 72 |
-
|
| 73 |
-
if normalized >= 70:
|
| 74 |
-
st.success(f"Match: {normalized}%")
|
| 75 |
-
elif normalized >= 40:
|
| 76 |
-
st.info(f"Match: {normalized}%")
|
| 77 |
-
else:
|
| 78 |
-
st.warning(f"Match: {normalized}%")
|
| 79 |
-
|
| 80 |
-
st.caption(f"**{product.brand}**")
|
| 81 |
-
st.caption(product.name[:60])
|
| 82 |
-
if product.price_text:
|
| 83 |
-
st.caption(product.price_text)
|
| 84 |
-
st.link_button("View", product.url, use_container_width=True)
|
| 85 |
-
|
| 86 |
-
rc1, rc2 = st.columns(2)
|
| 87 |
-
with rc1:
|
| 88 |
-
if st.button("Like", key=f"like_{product.url}", use_container_width=True):
|
| 89 |
-
if product.image_path:
|
| 90 |
-
engine.save_rating(product.image_path, 1)
|
| 91 |
-
st.toast("Liked! Taste updated.")
|
| 92 |
-
with rc2:
|
| 93 |
-
if st.button("Nah", key=f"dis_{product.url}", use_container_width=True):
|
| 94 |
-
if product.image_path:
|
| 95 |
-
engine.save_rating(product.image_path, -1)
|
| 96 |
-
st.toast("Noted. Taste updated.")
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
# --- Shop mode ---
|
| 100 |
-
if mode == "Shop":
|
| 101 |
-
st.title("Shop")
|
| 102 |
-
|
| 103 |
-
taste = engine.build_taste_vector()
|
| 104 |
-
if taste is None:
|
| 105 |
-
st.warning("No taste profile yet. Rate some images first.")
|
| 106 |
-
st.stop()
|
| 107 |
-
|
| 108 |
-
# Controls
|
| 109 |
-
col_cat, col_q = st.columns([1, 2])
|
| 110 |
-
with col_cat:
|
| 111 |
-
category_name = st.selectbox("Category", list(ZALANDO_CATEGORIES.keys()))
|
| 112 |
-
with col_q:
|
| 113 |
-
if ZALANDO_CATEGORIES[category_name] is None:
|
| 114 |
-
query = st.text_input("Search", placeholder="linen trousers, midi skirt...")
|
| 115 |
-
else:
|
| 116 |
-
query = ""
|
| 117 |
-
|
| 118 |
-
col_max, col_price = st.columns(2)
|
| 119 |
-
with col_max:
|
| 120 |
-
max_products = st.slider("Max products to scan", 50, 10000, 500, step=50)
|
| 121 |
-
with col_price:
|
| 122 |
-
price_max = st.number_input("Max price (NOK, 0=no limit)", min_value=0, value=0, step=100)
|
| 123 |
-
|
| 124 |
-
scan_clicked = st.button("Scan", type="primary", use_container_width=True)
|
| 125 |
-
|
| 126 |
-
# Results area
|
| 127 |
-
results_header = st.empty()
|
| 128 |
-
results_area = st.container()
|
| 129 |
-
|
| 130 |
-
if scan_clicked:
|
| 131 |
-
from scraper import ZalandoScraper
|
| 132 |
-
|
| 133 |
-
scraper = ZalandoScraper()
|
| 134 |
-
|
| 135 |
-
if ZALANDO_CATEGORIES[category_name] is None and not query:
|
| 136 |
-
st.warning("Enter a search query for custom search.")
|
| 137 |
-
st.stop()
|
| 138 |
-
|
| 139 |
-
# Determine URL
|
| 140 |
-
if ZALANDO_CATEGORIES[category_name]:
|
| 141 |
-
cat_url = ZALANDO_CATEGORIES[category_name]
|
| 142 |
-
if price_max:
|
| 143 |
-
cat_url += f"?price_to={price_max}"
|
| 144 |
-
else:
|
| 145 |
-
cat_url = f"/dame/?q={quote(query)}"
|
| 146 |
-
if price_max:
|
| 147 |
-
cat_url += f"&price_to={price_max}"
|
| 148 |
-
|
| 149 |
-
all_scored: list = []
|
| 150 |
-
total_scraped = 0
|
| 151 |
-
total_scored = 0
|
| 152 |
-
|
| 153 |
-
progress = st.progress(0.0)
|
| 154 |
-
status_text = st.empty()
|
| 155 |
-
|
| 156 |
-
for batch in scraper.crawl_category(cat_url, max_products=max_products):
|
| 157 |
-
total_scraped += len(batch)
|
| 158 |
-
status_text.text(f"Scraped {total_scraped} products... downloading images...")
|
| 159 |
-
|
| 160 |
-
# Download images for this batch
|
| 161 |
-
scraper.download_images(batch)
|
| 162 |
-
with_images = [p for p in batch if p.image_path and p.image_path.exists()]
|
| 163 |
-
|
| 164 |
-
if with_images:
|
| 165 |
-
# Score with CLIP
|
| 166 |
-
status_text.text(f"Scraped {total_scraped}... scoring batch of {len(with_images)}...")
|
| 167 |
-
scored = engine.score_product_images(
|
| 168 |
-
[p.image_path for p in with_images], taste
|
| 169 |
-
)
|
| 170 |
-
score_map = {str(path): score for path, score in scored}
|
| 171 |
-
for p in with_images:
|
| 172 |
-
p.score = score_map.get(str(p.image_path), 0.0)
|
| 173 |
-
|
| 174 |
-
all_scored.extend(with_images)
|
| 175 |
-
total_scored = len(all_scored)
|
| 176 |
-
|
| 177 |
-
# Save to catalog
|
| 178 |
-
scraper.save_to_catalog(with_images)
|
| 179 |
-
|
| 180 |
-
# Update progress
|
| 181 |
-
progress.progress(min(total_scraped / max_products, 1.0))
|
| 182 |
-
|
| 183 |
-
# Re-render results sorted by score
|
| 184 |
-
all_scored.sort(key=lambda p: p.score, reverse=True)
|
| 185 |
-
results_header.subheader(
|
| 186 |
-
f"Top picks ({total_scored} scored out of {total_scraped} scraped)"
|
| 187 |
-
)
|
| 188 |
-
results_area.empty()
|
| 189 |
-
render_product_grid(all_scored[:40], results_area)
|
| 190 |
-
|
| 191 |
-
progress.progress(1.0)
|
| 192 |
-
status_text.text(f"Done! Scanned {total_scraped} products, scored {total_scored}.")
|
| 193 |
-
|
| 194 |
-
# Final render — show top 80
|
| 195 |
-
all_scored.sort(key=lambda p: p.score, reverse=True)
|
| 196 |
-
results_header.subheader(
|
| 197 |
-
f"Top picks ({total_scored} scored out of {total_scraped} scanned)"
|
| 198 |
-
)
|
| 199 |
-
results_area.empty()
|
| 200 |
-
render_product_grid(all_scored[:80], results_area)
|
| 201 |
-
|
| 202 |
-
# --- Rate mode ---
|
| 203 |
-
elif mode == "Rate":
|
| 204 |
-
st.title("Rate")
|
| 205 |
-
folder_input = st.text_input("Image folder", placeholder="/path/to/images", key="folder")
|
| 206 |
-
|
| 207 |
-
if not folder_input or not Path(folder_input).is_dir():
|
| 208 |
-
st.info("Enter a folder path to rate images from.")
|
| 209 |
-
st.stop()
|
| 210 |
-
|
| 211 |
-
folder = Path(folder_input)
|
| 212 |
-
images = find_images(folder)
|
| 213 |
-
if not images:
|
| 214 |
-
st.warning(f"No images found in `{folder}`")
|
| 215 |
-
st.stop()
|
| 216 |
-
|
| 217 |
-
ratings = engine.load_ratings()
|
| 218 |
-
unrated = [img for img in images if str(img.resolve()) not in ratings]
|
| 219 |
-
|
| 220 |
-
rated_count = len(images) - len(unrated)
|
| 221 |
-
st.progress(rated_count / len(images))
|
| 222 |
-
st.caption(f"{rated_count} / {len(images)} rated")
|
| 223 |
-
|
| 224 |
-
if not unrated:
|
| 225 |
-
st.success("All images rated!")
|
| 226 |
-
if st.button("Re-rate this folder"):
|
| 227 |
-
engine.clear_ratings(images)
|
| 228 |
-
st.rerun()
|
| 229 |
-
st.stop()
|
| 230 |
-
|
| 231 |
-
current = unrated[0]
|
| 232 |
-
|
| 233 |
-
_, col_img, _ = st.columns([1, 4, 1])
|
| 234 |
-
with col_img:
|
| 235 |
-
st.image(str(current), use_container_width=True)
|
| 236 |
-
st.caption(current.name)
|
| 237 |
-
|
| 238 |
-
col_dis, col_skip, col_like = st.columns(3)
|
| 239 |
-
with col_dis:
|
| 240 |
-
if st.button("Dislike", use_container_width=True, type="secondary"):
|
| 241 |
-
engine.save_rating(current, -1)
|
| 242 |
-
st.rerun()
|
| 243 |
-
with col_skip:
|
| 244 |
-
if st.button("Skip", use_container_width=True):
|
| 245 |
-
engine.save_rating(current, 0)
|
| 246 |
-
st.rerun()
|
| 247 |
-
with col_like:
|
| 248 |
-
if st.button("Like", use_container_width=True, type="primary"):
|
| 249 |
-
engine.save_rating(current, 1)
|
| 250 |
-
st.rerun()
|
| 251 |
-
|
| 252 |
-
# --- Compare mode ---
|
| 253 |
-
elif mode == "Compare":
|
| 254 |
-
st.title("Compare")
|
| 255 |
-
folder_input = st.text_input("Image folder", placeholder="/path/to/images", key="compare_folder")
|
| 256 |
-
|
| 257 |
-
if not folder_input or not Path(folder_input).is_dir():
|
| 258 |
-
st.info("Enter a folder path with images to compare.")
|
| 259 |
-
st.stop()
|
| 260 |
-
|
| 261 |
-
images = find_images(Path(folder_input))
|
| 262 |
-
if len(images) < 2:
|
| 263 |
-
st.warning("Need at least 2 images to compare.")
|
| 264 |
-
st.stop()
|
| 265 |
-
|
| 266 |
-
if "compare_idx" not in st.session_state:
|
| 267 |
-
st.session_state.compare_idx = 0
|
| 268 |
-
|
| 269 |
-
import random
|
| 270 |
-
|
| 271 |
-
if "compare_pairs" not in st.session_state:
|
| 272 |
-
pairs = []
|
| 273 |
-
imgs = list(images)
|
| 274 |
-
random.shuffle(imgs)
|
| 275 |
-
for i in range(0, len(imgs) - 1, 2):
|
| 276 |
-
pairs.append((imgs[i], imgs[i + 1]))
|
| 277 |
-
st.session_state.compare_pairs = pairs
|
| 278 |
-
|
| 279 |
-
pairs = st.session_state.compare_pairs
|
| 280 |
-
idx = st.session_state.compare_idx
|
| 281 |
-
|
| 282 |
-
if idx >= len(pairs):
|
| 283 |
-
st.success("All pairs compared!")
|
| 284 |
-
if st.button("New round"):
|
| 285 |
-
st.session_state.compare_idx = 0
|
| 286 |
-
imgs = list(images)
|
| 287 |
-
random.shuffle(imgs)
|
| 288 |
-
new_pairs = []
|
| 289 |
-
for i in range(0, len(imgs) - 1, 2):
|
| 290 |
-
new_pairs.append((imgs[i], imgs[i + 1]))
|
| 291 |
-
st.session_state.compare_pairs = new_pairs
|
| 292 |
-
st.rerun()
|
| 293 |
-
st.stop()
|
| 294 |
-
|
| 295 |
-
st.caption(f"Pair {idx + 1} / {len(pairs)}")
|
| 296 |
-
left, right = pairs[idx]
|
| 297 |
-
|
| 298 |
-
col_l, col_r = st.columns(2)
|
| 299 |
-
with col_l:
|
| 300 |
-
st.image(str(left), use_container_width=True)
|
| 301 |
-
if st.button("Prefer this", key="prefer_left", use_container_width=True):
|
| 302 |
-
engine.save_rating(left, 1)
|
| 303 |
-
engine.save_rating(right, -1)
|
| 304 |
-
st.session_state.compare_idx += 1
|
| 305 |
-
st.rerun()
|
| 306 |
-
with col_r:
|
| 307 |
-
st.image(str(right), use_container_width=True)
|
| 308 |
-
if st.button("Prefer this", key="prefer_right", use_container_width=True):
|
| 309 |
-
engine.save_rating(right, 1)
|
| 310 |
-
engine.save_rating(left, -1)
|
| 311 |
-
st.session_state.compare_idx += 1
|
| 312 |
-
st.rerun()
|
| 313 |
-
|
| 314 |
-
if st.button("Skip pair"):
|
| 315 |
-
st.session_state.compare_idx += 1
|
| 316 |
-
st.rerun()
|
| 317 |
-
|
| 318 |
-
# --- Discover mode ---
|
| 319 |
-
elif mode == "Discover":
|
| 320 |
-
st.title("Discover")
|
| 321 |
-
folder_input = st.text_input("Image folder", placeholder="/path/to/images", key="discover_folder")
|
| 322 |
-
|
| 323 |
-
if not folder_input or not Path(folder_input).is_dir():
|
| 324 |
-
st.info("Enter a folder path to score images from.")
|
| 325 |
-
st.stop()
|
| 326 |
-
|
| 327 |
-
images = find_images(Path(folder_input))
|
| 328 |
-
if not images:
|
| 329 |
-
st.warning("No images found.")
|
| 330 |
-
st.stop()
|
| 331 |
-
|
| 332 |
-
taste = engine.build_taste_vector()
|
| 333 |
-
if taste is None:
|
| 334 |
-
st.warning("Rate some images first to build your taste profile.")
|
| 335 |
-
st.stop()
|
| 336 |
-
|
| 337 |
-
with st.spinner("Scoring images..."):
|
| 338 |
-
ranked = engine.rank(images, taste)
|
| 339 |
-
|
| 340 |
-
if not ranked:
|
| 341 |
-
st.warning("No images could be scored.")
|
| 342 |
-
st.stop()
|
| 343 |
-
|
| 344 |
-
scores = [s for _, s in ranked]
|
| 345 |
-
min_s, max_s = min(scores), max(scores)
|
| 346 |
-
score_range = max_s - min_s if max_s != min_s else 1.0
|
| 347 |
-
|
| 348 |
-
cols_per_row = 4
|
| 349 |
-
for row_start in range(0, len(ranked), cols_per_row):
|
| 350 |
-
row = ranked[row_start : row_start + cols_per_row]
|
| 351 |
-
cols = st.columns(cols_per_row)
|
| 352 |
-
for col, (path, raw_score) in zip(cols, row):
|
| 353 |
-
with col:
|
| 354 |
-
normalized = int(100 * (raw_score - min_s) / score_range)
|
| 355 |
-
st.image(str(path), use_container_width=True)
|
| 356 |
-
if normalized >= 70:
|
| 357 |
-
st.success(f"Score: {normalized}")
|
| 358 |
-
elif normalized >= 40:
|
| 359 |
-
st.info(f"Score: {normalized}")
|
| 360 |
-
else:
|
| 361 |
-
st.warning(f"Score: {normalized}")
|
| 362 |
-
st.caption(path.name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cli.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CLI entry point for taste-engine."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def main():
|
| 9 |
+
parser = argparse.ArgumentParser(prog="taste", description="Personal visual taste engine")
|
| 10 |
+
sub = parser.add_subparsers(dest="command")
|
| 11 |
+
|
| 12 |
+
# taste scan
|
| 13 |
+
scan_p = sub.add_parser("scan", help="Run full scan pipeline")
|
| 14 |
+
scan_p.add_argument("--config", type=Path, help="Config YAML path")
|
| 15 |
+
scan_p.add_argument("--profile", default="default", help="User profile name")
|
| 16 |
+
scan_p.add_argument("--stores", help="Comma-separated store names to scrape")
|
| 17 |
+
scan_p.add_argument("--output", type=Path, help="Output HTML path")
|
| 18 |
+
|
| 19 |
+
# taste stats
|
| 20 |
+
stats_p = sub.add_parser("stats", help="Show DB stats")
|
| 21 |
+
stats_p.add_argument("--config", type=Path, help="Config YAML path")
|
| 22 |
+
stats_p.add_argument("--profile", default="default", help="User profile name")
|
| 23 |
+
|
| 24 |
+
# taste profile
|
| 25 |
+
profile_p = sub.add_parser("profile", help="Manage user profiles")
|
| 26 |
+
profile_sub = profile_p.add_subparsers(dest="profile_command")
|
| 27 |
+
profile_sub.add_parser("list", help="List profiles")
|
| 28 |
+
create_p = profile_sub.add_parser("create", help="Create a new profile")
|
| 29 |
+
create_p.add_argument("name", help="Profile name")
|
| 30 |
+
|
| 31 |
+
args = parser.parse_args()
|
| 32 |
+
|
| 33 |
+
if args.command == "scan":
|
| 34 |
+
_cmd_scan(args)
|
| 35 |
+
elif args.command == "stats":
|
| 36 |
+
_cmd_stats(args)
|
| 37 |
+
elif args.command == "profile":
|
| 38 |
+
_cmd_profile(args)
|
| 39 |
+
else:
|
| 40 |
+
parser.print_help()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _cmd_scan(args):
|
| 44 |
+
from taste.config import load_config, load_profile
|
| 45 |
+
from taste.pipeline import run_scan
|
| 46 |
+
|
| 47 |
+
config = load_config(args.config)
|
| 48 |
+
|
| 49 |
+
# Filter stores if --stores specified
|
| 50 |
+
if args.stores:
|
| 51 |
+
enabled = set(s.strip().lower() for s in args.stores.split(","))
|
| 52 |
+
for name, sc in config.stores.items():
|
| 53 |
+
sc.enabled = name.lower() in enabled
|
| 54 |
+
|
| 55 |
+
profile = load_profile(args.profile, config)
|
| 56 |
+
run_scan(config, profile, output_path=args.output)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _cmd_stats(args):
|
| 60 |
+
from taste.config import load_config, load_profile
|
| 61 |
+
from taste.store import ProductStore
|
| 62 |
+
|
| 63 |
+
config = load_config(args.config)
|
| 64 |
+
profile = load_profile(args.profile, config)
|
| 65 |
+
store = ProductStore(db_path=profile.db_path(config))
|
| 66 |
+
stats = store.get_stats()
|
| 67 |
+
|
| 68 |
+
print(f"Total products: {stats['total']}")
|
| 69 |
+
print()
|
| 70 |
+
for name, s in stats["stores"].items():
|
| 71 |
+
print(f" {name:15s} {s['count']:5d} products top={s['top']:.3f} avg={s['avg']:.3f}")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _cmd_profile(args):
|
| 75 |
+
from taste.config import load_config
|
| 76 |
+
|
| 77 |
+
config = load_config()
|
| 78 |
+
|
| 79 |
+
if args.profile_command == "list":
|
| 80 |
+
profiles_dir = config.data_dir / "profiles"
|
| 81 |
+
if not profiles_dir.exists():
|
| 82 |
+
print("No profiles found. Create one with: taste profile create <name>")
|
| 83 |
+
return
|
| 84 |
+
for f in sorted(profiles_dir.iterdir()):
|
| 85 |
+
if f.suffix in (".yaml", ".json"):
|
| 86 |
+
print(f" {f.stem}")
|
| 87 |
+
|
| 88 |
+
elif args.profile_command == "create":
|
| 89 |
+
profiles_dir = config.data_dir / "profiles"
|
| 90 |
+
profiles_dir.mkdir(parents=True, exist_ok=True)
|
| 91 |
+
path = profiles_dir / f"{args.name}.yaml"
|
| 92 |
+
if path.exists():
|
| 93 |
+
print(f"Profile '{args.name}' already exists at {path}")
|
| 94 |
+
return
|
| 95 |
+
|
| 96 |
+
template = f"""name: {args.name}
|
| 97 |
+
reference_dirs: []
|
| 98 |
+
liked_urls: []
|
| 99 |
+
disliked_brands: []
|
| 100 |
+
filters: {{}}
|
| 101 |
+
style_text_queries: []
|
| 102 |
+
"""
|
| 103 |
+
path.write_text(template)
|
| 104 |
+
print(f"Created profile: {path}")
|
| 105 |
+
print(f"Edit it to add your preferences, then run: taste scan --profile {args.name}")
|
| 106 |
+
|
| 107 |
+
else:
|
| 108 |
+
print("Usage: taste profile [list|create <name>]")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
main()
|
config.example.yaml
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
data_dir: ~/.taste
|
| 2 |
+
|
| 3 |
+
stores:
|
| 4 |
+
wakakuu:
|
| 5 |
+
enabled: true
|
| 6 |
+
type: api
|
| 7 |
+
base_url: https://www.wakakuu.com
|
| 8 |
+
algolia_app_id: "0LM8YN9I0K"
|
| 9 |
+
algolia_api_key: "00ef309f4d1543ffdaa1d85c33111700"
|
| 10 |
+
algolia_index: prod_products_sv
|
| 11 |
+
categories:
|
| 12 |
+
- "categories.lvl0:Väskor"
|
| 13 |
+
max_products: 3000
|
| 14 |
+
|
| 15 |
+
boozt:
|
| 16 |
+
enabled: true
|
| 17 |
+
type: api
|
| 18 |
+
base_url: https://www.boozt.com
|
| 19 |
+
material_filter: ekte-skinn
|
| 20 |
+
categories:
|
| 21 |
+
- /no/no/kvinner/vesker
|
| 22 |
+
- /no/no/kvinner/vesker/skuldervesker
|
| 23 |
+
- /no/no/kvinner/vesker/haandvesker
|
| 24 |
+
- /no/no/kvinner/vesker/crossbody-vesker
|
| 25 |
+
max_products: 5000
|
| 26 |
+
|
| 27 |
+
miinto:
|
| 28 |
+
enabled: true
|
| 29 |
+
type: api
|
| 30 |
+
base_url: https://www.miinto.no
|
| 31 |
+
categories:
|
| 32 |
+
- /dame-skuldervesker
|
| 33 |
+
- /dame-handvesker
|
| 34 |
+
- /dame-clutch-vesker
|
| 35 |
+
max_products: 5000
|
| 36 |
+
|
| 37 |
+
nakd:
|
| 38 |
+
enabled: true
|
| 39 |
+
type: api
|
| 40 |
+
base_url: https://www.na-kd.com
|
| 41 |
+
categories:
|
| 42 |
+
- /no/category/vesker
|
| 43 |
+
- /no/category/vesker/skuldervesker
|
| 44 |
+
max_products: 2000
|
| 45 |
+
|
| 46 |
+
batch_size: 50
|
| 47 |
+
image_download_concurrency: 20
|
engine_v2.py
DELETED
|
@@ -1,346 +0,0 @@
|
|
| 1 |
-
"""Taste Engine v2 — improved preference learning and scoring."""
|
| 2 |
-
|
| 3 |
-
import hashlib
|
| 4 |
-
import json
|
| 5 |
-
import numpy as np
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
from PIL import Image
|
| 8 |
-
|
| 9 |
-
SUPPORTED_EXT = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tiff", ".avif"}
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def find_images(folder: Path) -> list[Path]:
|
| 13 |
-
images = []
|
| 14 |
-
for f in folder.iterdir():
|
| 15 |
-
if f.suffix.lower() in SUPPORTED_EXT and not f.name.startswith("."):
|
| 16 |
-
images.append(f)
|
| 17 |
-
return sorted(images, key=lambda p: p.name.lower())
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
class TasteEngineV2:
|
| 21 |
-
"""Improved taste engine with:
|
| 22 |
-
- Marqo-FashionSigLIP model (fashion-specific)
|
| 23 |
-
- HDBSCAN multi-centroid taste (MaxSim scoring)
|
| 24 |
-
- Variance-based dimension weighting
|
| 25 |
-
- Per-store z-normalization
|
| 26 |
-
- Text-guided taste injection
|
| 27 |
-
"""
|
| 28 |
-
|
| 29 |
-
def __init__(self, data_dir: Path | None = None):
|
| 30 |
-
self.data_dir = Path(data_dir or Path.home() / ".taste-v2")
|
| 31 |
-
self.data_dir.mkdir(parents=True, exist_ok=True)
|
| 32 |
-
self.ratings_path = self.data_dir / "ratings.json"
|
| 33 |
-
self.cache_dir = self.data_dir / "embeddings"
|
| 34 |
-
self.cache_dir.mkdir(exist_ok=True)
|
| 35 |
-
self._model = None
|
| 36 |
-
self._preprocess = None
|
| 37 |
-
self._tokenizer = None
|
| 38 |
-
self._device = None
|
| 39 |
-
|
| 40 |
-
@property
|
| 41 |
-
def device(self):
|
| 42 |
-
if self._device is None:
|
| 43 |
-
import torch
|
| 44 |
-
if torch.cuda.is_available():
|
| 45 |
-
self._device = "cuda"
|
| 46 |
-
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
|
| 47 |
-
self._device = "mps"
|
| 48 |
-
else:
|
| 49 |
-
self._device = "cpu"
|
| 50 |
-
return self._device
|
| 51 |
-
|
| 52 |
-
def _load_model(self):
|
| 53 |
-
if self._model is not None:
|
| 54 |
-
return
|
| 55 |
-
import open_clip
|
| 56 |
-
import torch # noqa: F811
|
| 57 |
-
|
| 58 |
-
# Marqo FashionSigLIP — fashion-specific, +57% retrieval over generic CLIP
|
| 59 |
-
model, _, preprocess = open_clip.create_model_and_transforms(
|
| 60 |
-
"hf-hub:Marqo/marqo-fashionSigLIP"
|
| 61 |
-
)
|
| 62 |
-
self._model = model.to(self.device)
|
| 63 |
-
self._model.requires_grad_(False)
|
| 64 |
-
self._preprocess = preprocess
|
| 65 |
-
self._tokenizer = open_clip.get_tokenizer("hf-hub:Marqo/marqo-fashionSigLIP")
|
| 66 |
-
|
| 67 |
-
def _cache_key(self, path: Path) -> str:
|
| 68 |
-
stat = path.stat()
|
| 69 |
-
raw = f"v2-fashionsiglip:{path.resolve()}:{stat.st_size}:{stat.st_mtime_ns}"
|
| 70 |
-
return hashlib.blake2b(raw.encode(), digest_size=16).hexdigest()
|
| 71 |
-
|
| 72 |
-
def encode(self, path: Path) -> np.ndarray:
|
| 73 |
-
import torch
|
| 74 |
-
path = Path(path)
|
| 75 |
-
key = self._cache_key(path)
|
| 76 |
-
cache_path = self.cache_dir / f"{key}.npy"
|
| 77 |
-
|
| 78 |
-
if cache_path.exists():
|
| 79 |
-
return np.load(cache_path)
|
| 80 |
-
|
| 81 |
-
self._load_model()
|
| 82 |
-
img = Image.open(path).convert("RGB")
|
| 83 |
-
tensor = self._preprocess(img).unsqueeze(0).to(self.device)
|
| 84 |
-
with torch.no_grad():
|
| 85 |
-
emb = self._model.encode_image(tensor)
|
| 86 |
-
emb = emb / emb.norm(dim=-1, keepdim=True)
|
| 87 |
-
result = emb.squeeze().cpu().float().numpy()
|
| 88 |
-
np.save(cache_path, result)
|
| 89 |
-
return result
|
| 90 |
-
|
| 91 |
-
def encode_text(self, text: str) -> np.ndarray:
|
| 92 |
-
"""Encode text into the same embedding space as images."""
|
| 93 |
-
import torch
|
| 94 |
-
self._load_model()
|
| 95 |
-
tokens = self._tokenizer([text]).to(self.device)
|
| 96 |
-
with torch.no_grad():
|
| 97 |
-
emb = self._model.encode_text(tokens)
|
| 98 |
-
emb = emb / emb.norm(dim=-1, keepdim=True)
|
| 99 |
-
return emb.squeeze().cpu().float().numpy()
|
| 100 |
-
|
| 101 |
-
def encode_batch(self, paths: list[Path], batch_size: int = 16, progress_cb=None):
|
| 102 |
-
import torch
|
| 103 |
-
results = {}
|
| 104 |
-
to_encode = []
|
| 105 |
-
|
| 106 |
-
for p in paths:
|
| 107 |
-
key = self._cache_key(p)
|
| 108 |
-
cache_path = self.cache_dir / f"{key}.npy"
|
| 109 |
-
if cache_path.exists():
|
| 110 |
-
results[str(p)] = np.load(cache_path)
|
| 111 |
-
else:
|
| 112 |
-
to_encode.append(p)
|
| 113 |
-
|
| 114 |
-
done = len(results)
|
| 115 |
-
total = len(paths)
|
| 116 |
-
|
| 117 |
-
if to_encode:
|
| 118 |
-
self._load_model()
|
| 119 |
-
|
| 120 |
-
for i in range(0, len(to_encode), batch_size):
|
| 121 |
-
batch_paths = to_encode[i : i + batch_size]
|
| 122 |
-
tensors, valid = [], []
|
| 123 |
-
for p in batch_paths:
|
| 124 |
-
try:
|
| 125 |
-
img = Image.open(p).convert("RGB")
|
| 126 |
-
tensors.append(self._preprocess(img))
|
| 127 |
-
valid.append(p)
|
| 128 |
-
except Exception:
|
| 129 |
-
done += 1
|
| 130 |
-
continue
|
| 131 |
-
if tensors:
|
| 132 |
-
batch = torch.stack(tensors).to(self.device)
|
| 133 |
-
with torch.no_grad():
|
| 134 |
-
embs = self._model.encode_image(batch)
|
| 135 |
-
embs = embs / embs.norm(dim=-1, keepdim=True)
|
| 136 |
-
for p, emb in zip(valid, embs.cpu().float().numpy()):
|
| 137 |
-
key = self._cache_key(p)
|
| 138 |
-
np.save(self.cache_dir / f"{key}.npy", emb)
|
| 139 |
-
results[str(p)] = emb
|
| 140 |
-
done += 1
|
| 141 |
-
if progress_cb:
|
| 142 |
-
progress_cb(done / total)
|
| 143 |
-
|
| 144 |
-
return results
|
| 145 |
-
|
| 146 |
-
# --- Ratings (shared with v1) ---
|
| 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 seed_from_references(self, folder: Path):
|
| 159 |
-
ratings = self.load_ratings()
|
| 160 |
-
images = find_images(folder)
|
| 161 |
-
seeded = 0
|
| 162 |
-
for img in images:
|
| 163 |
-
key = str(img.resolve())
|
| 164 |
-
if key not in ratings:
|
| 165 |
-
self.save_rating(img, 1)
|
| 166 |
-
seeded += 1
|
| 167 |
-
return seeded
|
| 168 |
-
|
| 169 |
-
# --- Multi-centroid taste model ---
|
| 170 |
-
|
| 171 |
-
def build_taste_model(
|
| 172 |
-
self, text_queries: list[str] | None = None
|
| 173 |
-
) -> dict:
|
| 174 |
-
"""Build multi-centroid taste model with optional text injection.
|
| 175 |
-
|
| 176 |
-
Returns dict with:
|
| 177 |
-
centroids: list of taste vectors (one per cluster)
|
| 178 |
-
dim_weights: per-dimension importance weights
|
| 179 |
-
text_vectors: optional text-derived taste vectors
|
| 180 |
-
"""
|
| 181 |
-
ratings = self.load_ratings()
|
| 182 |
-
liked_embs = []
|
| 183 |
-
liked_paths = []
|
| 184 |
-
|
| 185 |
-
for path_str, rating in ratings.items():
|
| 186 |
-
p = Path(path_str)
|
| 187 |
-
if not p.exists() or rating != 1:
|
| 188 |
-
continue
|
| 189 |
-
liked_embs.append(self.encode(p))
|
| 190 |
-
liked_paths.append(p)
|
| 191 |
-
|
| 192 |
-
if not liked_embs:
|
| 193 |
-
return None
|
| 194 |
-
|
| 195 |
-
liked_arr = np.array(liked_embs)
|
| 196 |
-
|
| 197 |
-
# --- HDBSCAN clustering ---
|
| 198 |
-
centroids = self._cluster_centroids(liked_arr)
|
| 199 |
-
|
| 200 |
-
# --- Variance-based dimension weighting ---
|
| 201 |
-
dim_weights = self._compute_dim_weights(liked_arr)
|
| 202 |
-
|
| 203 |
-
# --- Text injection ---
|
| 204 |
-
text_vectors = []
|
| 205 |
-
if text_queries:
|
| 206 |
-
for q in text_queries:
|
| 207 |
-
text_vectors.append(self.encode_text(q))
|
| 208 |
-
|
| 209 |
-
return {
|
| 210 |
-
"centroids": centroids,
|
| 211 |
-
"dim_weights": dim_weights,
|
| 212 |
-
"text_vectors": text_vectors,
|
| 213 |
-
"n_liked": len(liked_embs),
|
| 214 |
-
"n_clusters": len(centroids),
|
| 215 |
-
}
|
| 216 |
-
|
| 217 |
-
def _cluster_centroids(self, embeddings: np.ndarray) -> list[np.ndarray]:
|
| 218 |
-
"""Cluster liked embeddings and return centroid per cluster."""
|
| 219 |
-
n = len(embeddings)
|
| 220 |
-
|
| 221 |
-
if n < 5:
|
| 222 |
-
# Too few for clustering, use single centroid
|
| 223 |
-
c = np.mean(embeddings, axis=0)
|
| 224 |
-
c = c / np.linalg.norm(c)
|
| 225 |
-
return [c]
|
| 226 |
-
|
| 227 |
-
try:
|
| 228 |
-
from sklearn.cluster import HDBSCAN as HDBSCANCluster
|
| 229 |
-
clusterer = HDBSCANCluster(min_cluster_size=3, min_samples=2)
|
| 230 |
-
labels = clusterer.fit_predict(embeddings)
|
| 231 |
-
except Exception:
|
| 232 |
-
# Fallback: k-means with k=2
|
| 233 |
-
from sklearn.cluster import KMeans
|
| 234 |
-
k = min(3, n // 3) if n >= 6 else 1
|
| 235 |
-
labels = KMeans(n_clusters=k, n_init=10, random_state=42).fit_predict(embeddings)
|
| 236 |
-
|
| 237 |
-
centroids = []
|
| 238 |
-
unique_labels = set(labels)
|
| 239 |
-
|
| 240 |
-
for label in unique_labels:
|
| 241 |
-
mask = labels == label
|
| 242 |
-
if label == -1:
|
| 243 |
-
# Noise points in HDBSCAN — treat each as singleton
|
| 244 |
-
for emb in embeddings[mask]:
|
| 245 |
-
c = emb / np.linalg.norm(emb)
|
| 246 |
-
centroids.append(c)
|
| 247 |
-
else:
|
| 248 |
-
cluster_embs = embeddings[mask]
|
| 249 |
-
c = np.mean(cluster_embs, axis=0)
|
| 250 |
-
c = c / np.linalg.norm(c)
|
| 251 |
-
centroids.append(c)
|
| 252 |
-
|
| 253 |
-
return centroids if centroids else [np.mean(embeddings, axis=0) / np.linalg.norm(np.mean(embeddings, axis=0))]
|
| 254 |
-
|
| 255 |
-
def _compute_dim_weights(self, embeddings: np.ndarray) -> np.ndarray:
|
| 256 |
-
"""Compute per-dimension importance from variance of liked embeddings.
|
| 257 |
-
|
| 258 |
-
Low variance = liked items agree on this dimension = more important.
|
| 259 |
-
"""
|
| 260 |
-
variances = np.var(embeddings, axis=0)
|
| 261 |
-
# Invert: low variance → high weight
|
| 262 |
-
# Add small epsilon to avoid division by zero
|
| 263 |
-
inv_var = 1.0 / (variances + 1e-8)
|
| 264 |
-
# Normalize to mean=1 so overall scale is preserved
|
| 265 |
-
weights = inv_var / np.mean(inv_var)
|
| 266 |
-
return weights
|
| 267 |
-
|
| 268 |
-
# --- Scoring ---
|
| 269 |
-
|
| 270 |
-
def score_single(self, emb: np.ndarray, taste_model: dict) -> float:
|
| 271 |
-
"""Score a single embedding against the taste model.
|
| 272 |
-
|
| 273 |
-
Uses MaxSim across centroids with dimension weighting.
|
| 274 |
-
"""
|
| 275 |
-
centroids = taste_model["centroids"]
|
| 276 |
-
dim_weights = taste_model["dim_weights"]
|
| 277 |
-
text_vectors = taste_model.get("text_vectors", [])
|
| 278 |
-
|
| 279 |
-
# Weight dimensions
|
| 280 |
-
weighted_emb = emb * np.sqrt(dim_weights)
|
| 281 |
-
|
| 282 |
-
# MaxSim across image centroids
|
| 283 |
-
max_score = -1.0
|
| 284 |
-
for c in centroids:
|
| 285 |
-
weighted_c = c * np.sqrt(dim_weights)
|
| 286 |
-
# Re-normalize after weighting
|
| 287 |
-
wc_norm = np.linalg.norm(weighted_c)
|
| 288 |
-
we_norm = np.linalg.norm(weighted_emb)
|
| 289 |
-
if wc_norm > 0 and we_norm > 0:
|
| 290 |
-
score = float(np.dot(weighted_emb / we_norm, weighted_c / wc_norm))
|
| 291 |
-
max_score = max(max_score, score)
|
| 292 |
-
|
| 293 |
-
# Blend with text vectors if available (0.3 weight for text)
|
| 294 |
-
if text_vectors:
|
| 295 |
-
text_scores = []
|
| 296 |
-
for tv in text_vectors:
|
| 297 |
-
weighted_tv = tv * np.sqrt(dim_weights)
|
| 298 |
-
tv_norm = np.linalg.norm(weighted_tv)
|
| 299 |
-
we_norm = np.linalg.norm(weighted_emb)
|
| 300 |
-
if tv_norm > 0 and we_norm > 0:
|
| 301 |
-
text_scores.append(float(np.dot(weighted_emb / we_norm, weighted_tv / tv_norm)))
|
| 302 |
-
if text_scores:
|
| 303 |
-
text_max = max(text_scores)
|
| 304 |
-
max_score = 0.7 * max_score + 0.3 * text_max
|
| 305 |
-
|
| 306 |
-
return max_score
|
| 307 |
-
|
| 308 |
-
def score_product_images(
|
| 309 |
-
self, image_paths: list[Path], taste_model: dict
|
| 310 |
-
) -> list[tuple[Path, float]]:
|
| 311 |
-
"""Score product images against taste model. Returns sorted (path, score)."""
|
| 312 |
-
embeddings = self.encode_batch(image_paths)
|
| 313 |
-
scores = []
|
| 314 |
-
for p in image_paths:
|
| 315 |
-
key = str(p)
|
| 316 |
-
if key in embeddings:
|
| 317 |
-
s = self.score_single(embeddings[key], taste_model)
|
| 318 |
-
scores.append((p, s))
|
| 319 |
-
scores.sort(key=lambda x: x[1], reverse=True)
|
| 320 |
-
return scores
|
| 321 |
-
|
| 322 |
-
# --- V1 compatibility ---
|
| 323 |
-
|
| 324 |
-
def build_taste_vector(self) -> np.ndarray | None:
|
| 325 |
-
"""V1-compatible: single taste vector (for baseline comparison)."""
|
| 326 |
-
ratings = self.load_ratings()
|
| 327 |
-
liked = []
|
| 328 |
-
for path_str, rating in ratings.items():
|
| 329 |
-
p = Path(path_str)
|
| 330 |
-
if not p.exists() or rating != 1:
|
| 331 |
-
continue
|
| 332 |
-
liked.append(self.encode(p))
|
| 333 |
-
if not liked:
|
| 334 |
-
return None
|
| 335 |
-
taste = np.mean(liked, axis=0)
|
| 336 |
-
norm = np.linalg.norm(taste)
|
| 337 |
-
if norm > 0:
|
| 338 |
-
taste = taste / norm
|
| 339 |
-
return taste
|
| 340 |
-
|
| 341 |
-
def stats(self) -> dict:
|
| 342 |
-
ratings = self.load_ratings()
|
| 343 |
-
liked = sum(1 for v in ratings.values() if v == 1)
|
| 344 |
-
disliked = sum(1 for v in ratings.values() if v == -1)
|
| 345 |
-
skipped = sum(1 for v in ratings.values() if v == 0)
|
| 346 |
-
return {"total": len(ratings), "liked": liked, "disliked": disliked, "skipped": skipped}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
evaluate.py
DELETED
|
@@ -1,127 +0,0 @@
|
|
| 1 |
-
"""Measure taste engine quality using Leave-One-Out on liked images."""
|
| 2 |
-
|
| 3 |
-
import sys
|
| 4 |
-
import time
|
| 5 |
-
import numpy as np
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
|
| 8 |
-
sys.stdout.reconfigure(line_buffering=True)
|
| 9 |
-
|
| 10 |
-
from engine import TasteEngine, SUPPORTED_EXT
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
def collect_all_product_images() -> list[Path]:
|
| 14 |
-
"""Gather all cached product images across stores."""
|
| 15 |
-
dirs = [
|
| 16 |
-
Path.home() / ".taste" / "products",
|
| 17 |
-
Path.home() / ".taste" / "products-boozt",
|
| 18 |
-
Path.home() / ".taste" / "products-miinto",
|
| 19 |
-
]
|
| 20 |
-
images = []
|
| 21 |
-
for d in dirs:
|
| 22 |
-
if d.exists():
|
| 23 |
-
images.extend(p for p in d.iterdir() if p.suffix.lower() in SUPPORTED_EXT)
|
| 24 |
-
return images
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
def collect_liked_images(engine: TasteEngine) -> list[Path]:
|
| 28 |
-
"""Get all liked image paths."""
|
| 29 |
-
ratings = engine.load_ratings()
|
| 30 |
-
return [Path(p) for p, r in ratings.items() if r == 1 and Path(p).exists()]
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def leave_one_out(engine: TasteEngine, liked: list[Path], catalog: list[Path]):
|
| 34 |
-
"""Run LOO assessment. Returns metrics dict."""
|
| 35 |
-
print(f"LOO Assessment: {len(liked)} liked images, {len(catalog)} catalog images")
|
| 36 |
-
print()
|
| 37 |
-
|
| 38 |
-
# Pre-encode all catalog images
|
| 39 |
-
print("Encoding catalog...", flush=True)
|
| 40 |
-
t0 = time.time()
|
| 41 |
-
catalog_embs = engine.encode_batch(catalog)
|
| 42 |
-
catalog_arr = np.array([catalog_embs[str(p)] for p in catalog if str(p) in catalog_embs])
|
| 43 |
-
valid_catalog = [p for p in catalog if str(p) in catalog_embs]
|
| 44 |
-
print(f" {len(valid_catalog)} images encoded in {time.time()-t0:.1f}s")
|
| 45 |
-
|
| 46 |
-
# Pre-encode all liked images
|
| 47 |
-
print("Encoding liked images...", flush=True)
|
| 48 |
-
liked_embs = {}
|
| 49 |
-
for p in liked:
|
| 50 |
-
liked_embs[str(p)] = engine.encode(p)
|
| 51 |
-
|
| 52 |
-
ranks = []
|
| 53 |
-
reciprocal_ranks = []
|
| 54 |
-
recall_at = {10: 0, 25: 0, 50: 0, 100: 0}
|
| 55 |
-
|
| 56 |
-
for i, held_out in enumerate(liked):
|
| 57 |
-
# Build taste from other liked images
|
| 58 |
-
other = [p for j, p in enumerate(liked) if j != i]
|
| 59 |
-
other_embs = np.array([liked_embs[str(p)] for p in other])
|
| 60 |
-
taste = np.mean(other_embs, axis=0)
|
| 61 |
-
norm = np.linalg.norm(taste)
|
| 62 |
-
if norm > 0:
|
| 63 |
-
taste = taste / norm
|
| 64 |
-
|
| 65 |
-
# Score the held-out image
|
| 66 |
-
held_emb = liked_embs[str(held_out)]
|
| 67 |
-
held_score = float(np.dot(held_emb, taste))
|
| 68 |
-
|
| 69 |
-
# Score all catalog images
|
| 70 |
-
catalog_scores = catalog_arr @ taste
|
| 71 |
-
|
| 72 |
-
# Rank: how many catalog images score higher than the held-out?
|
| 73 |
-
rank = int(np.sum(catalog_scores > held_score)) + 1
|
| 74 |
-
ranks.append(rank)
|
| 75 |
-
reciprocal_ranks.append(1.0 / rank)
|
| 76 |
-
|
| 77 |
-
for k in recall_at:
|
| 78 |
-
if rank <= k:
|
| 79 |
-
recall_at[k] += 1
|
| 80 |
-
|
| 81 |
-
print(f" [{i+1}/{len(liked)}] {held_out.name:30s} rank={rank:4d}/{len(valid_catalog)} score={held_score:.4f}")
|
| 82 |
-
|
| 83 |
-
# Compute metrics
|
| 84 |
-
mean_rank = np.mean(ranks)
|
| 85 |
-
median_rank = np.median(ranks)
|
| 86 |
-
mrr = np.mean(reciprocal_ranks)
|
| 87 |
-
recall_pct = {k: v / len(liked) * 100 for k, v in recall_at.items()}
|
| 88 |
-
|
| 89 |
-
print()
|
| 90 |
-
print("=" * 60)
|
| 91 |
-
print(f" Mean Rank: {mean_rank:.1f} / {len(valid_catalog)}")
|
| 92 |
-
print(f" Median Rank: {median_rank:.1f}")
|
| 93 |
-
print(f" MRR: {mrr:.4f}")
|
| 94 |
-
for k, pct in recall_pct.items():
|
| 95 |
-
print(f" Recall@{k:3d}: {pct:.0f}% ({recall_at[k]}/{len(liked)})")
|
| 96 |
-
print("=" * 60)
|
| 97 |
-
|
| 98 |
-
return {
|
| 99 |
-
"mean_rank": float(mean_rank),
|
| 100 |
-
"median_rank": float(median_rank),
|
| 101 |
-
"mrr": float(mrr),
|
| 102 |
-
"recall_at": recall_pct,
|
| 103 |
-
"ranks": ranks,
|
| 104 |
-
"n_liked": len(liked),
|
| 105 |
-
"n_catalog": len(valid_catalog),
|
| 106 |
-
}
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
def main():
|
| 110 |
-
engine = TasteEngine()
|
| 111 |
-
liked = collect_liked_images(engine)
|
| 112 |
-
catalog = collect_all_product_images()
|
| 113 |
-
|
| 114 |
-
if not liked:
|
| 115 |
-
print("No liked images found!")
|
| 116 |
-
sys.exit(1)
|
| 117 |
-
|
| 118 |
-
print(f"Liked: {len(liked)} images")
|
| 119 |
-
print(f"Catalog: {len(catalog)} images")
|
| 120 |
-
print()
|
| 121 |
-
|
| 122 |
-
results = leave_one_out(engine, liked, catalog)
|
| 123 |
-
return results
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
if __name__ == "__main__":
|
| 127 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
evaluate_v2.py
DELETED
|
@@ -1,198 +0,0 @@
|
|
| 1 |
-
"""Measure taste engine v2 quality using Leave-One-Out."""
|
| 2 |
-
|
| 3 |
-
import sys
|
| 4 |
-
import time
|
| 5 |
-
import numpy as np
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
|
| 8 |
-
sys.stdout.reconfigure(line_buffering=True)
|
| 9 |
-
|
| 10 |
-
from engine_v2 import TasteEngineV2, SUPPORTED_EXT
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
STYLE_TEXT_QUERIES = [
|
| 14 |
-
"minimalist structured leather crossbody bag in muted earth tones",
|
| 15 |
-
"soft leather shoulder bag in taupe, camel, or cream",
|
| 16 |
-
"elegant small bucket bag in warm brown leather",
|
| 17 |
-
]
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def collect_all_product_images() -> list[Path]:
|
| 21 |
-
dirs = [
|
| 22 |
-
Path.home() / ".taste" / "products",
|
| 23 |
-
Path.home() / ".taste" / "products-boozt",
|
| 24 |
-
Path.home() / ".taste" / "products-miinto",
|
| 25 |
-
]
|
| 26 |
-
images = []
|
| 27 |
-
for d in dirs:
|
| 28 |
-
if d.exists():
|
| 29 |
-
images.extend(p for p in d.iterdir() if p.suffix.lower() in SUPPORTED_EXT)
|
| 30 |
-
return images
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def collect_liked_images(engine: TasteEngineV2) -> list[Path]:
|
| 34 |
-
ratings = engine.load_ratings()
|
| 35 |
-
return [Path(p) for p, r in ratings.items() if r == 1 and Path(p).exists()]
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
def loo_simple_average(engine, liked, catalog_arr, valid_catalog, liked_embs):
|
| 39 |
-
"""Baseline: simple average taste vector, dot product scoring."""
|
| 40 |
-
print("\n--- Method: Simple Average (v1-style on v2 model) ---")
|
| 41 |
-
ranks = []
|
| 42 |
-
for i, held_out in enumerate(liked):
|
| 43 |
-
other_embs = np.array([liked_embs[str(p)] for j, p in enumerate(liked) if j != i])
|
| 44 |
-
taste = np.mean(other_embs, axis=0)
|
| 45 |
-
taste = taste / np.linalg.norm(taste)
|
| 46 |
-
|
| 47 |
-
held_score = float(np.dot(liked_embs[str(held_out)], taste))
|
| 48 |
-
catalog_scores = catalog_arr @ taste
|
| 49 |
-
rank = int(np.sum(catalog_scores > held_score)) + 1
|
| 50 |
-
ranks.append(rank)
|
| 51 |
-
print(f" [{i+1}/{len(liked)}] {held_out.name:30s} rank={rank:4d}")
|
| 52 |
-
|
| 53 |
-
report(ranks, len(valid_catalog), len(liked))
|
| 54 |
-
return ranks
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def loo_multi_centroid(engine, liked, catalog_arr, valid_catalog, liked_embs):
|
| 58 |
-
"""Multi-centroid with HDBSCAN + MaxSim."""
|
| 59 |
-
print("\n--- Method: Multi-Centroid (HDBSCAN + MaxSim) ---")
|
| 60 |
-
ranks = []
|
| 61 |
-
for i, held_out in enumerate(liked):
|
| 62 |
-
other = [p for j, p in enumerate(liked) if j != i]
|
| 63 |
-
other_embs_arr = np.array([liked_embs[str(p)] for p in other])
|
| 64 |
-
|
| 65 |
-
centroids = engine._cluster_centroids(other_embs_arr)
|
| 66 |
-
|
| 67 |
-
held_emb = liked_embs[str(held_out)]
|
| 68 |
-
held_score = max(float(np.dot(held_emb, c)) for c in centroids)
|
| 69 |
-
|
| 70 |
-
catalog_scores = np.array([
|
| 71 |
-
max(float(np.dot(e, c)) for c in centroids)
|
| 72 |
-
for e in catalog_arr
|
| 73 |
-
])
|
| 74 |
-
rank = int(np.sum(catalog_scores > held_score)) + 1
|
| 75 |
-
ranks.append(rank)
|
| 76 |
-
print(f" [{i+1}/{len(liked)}] {held_out.name:30s} rank={rank:4d} clusters={len(centroids)}")
|
| 77 |
-
|
| 78 |
-
report(ranks, len(valid_catalog), len(liked))
|
| 79 |
-
return ranks
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
def loo_multi_centroid_dimweight(engine, liked, catalog_arr, valid_catalog, liked_embs):
|
| 83 |
-
"""Multi-centroid + dimension weighting."""
|
| 84 |
-
print("\n--- Method: Multi-Centroid + Dim Weights ---")
|
| 85 |
-
ranks = []
|
| 86 |
-
for i, held_out in enumerate(liked):
|
| 87 |
-
other = [p for j, p in enumerate(liked) if j != i]
|
| 88 |
-
other_embs_arr = np.array([liked_embs[str(p)] for p in other])
|
| 89 |
-
|
| 90 |
-
centroids = engine._cluster_centroids(other_embs_arr)
|
| 91 |
-
dim_weights = engine._compute_dim_weights(other_embs_arr)
|
| 92 |
-
sqrt_w = np.sqrt(dim_weights)
|
| 93 |
-
|
| 94 |
-
held_emb = liked_embs[str(held_out)] * sqrt_w
|
| 95 |
-
held_emb = held_emb / np.linalg.norm(held_emb)
|
| 96 |
-
|
| 97 |
-
weighted_centroids = []
|
| 98 |
-
for c in centroids:
|
| 99 |
-
wc = c * sqrt_w
|
| 100 |
-
wc = wc / np.linalg.norm(wc)
|
| 101 |
-
weighted_centroids.append(wc)
|
| 102 |
-
|
| 103 |
-
held_score = max(float(np.dot(held_emb, wc)) for wc in weighted_centroids)
|
| 104 |
-
|
| 105 |
-
catalog_weighted = catalog_arr * sqrt_w[np.newaxis, :]
|
| 106 |
-
norms = np.linalg.norm(catalog_weighted, axis=1, keepdims=True)
|
| 107 |
-
norms = np.where(norms > 0, norms, 1.0)
|
| 108 |
-
catalog_weighted = catalog_weighted / norms
|
| 109 |
-
|
| 110 |
-
catalog_scores = np.array([
|
| 111 |
-
max(float(np.dot(e, wc)) for wc in weighted_centroids)
|
| 112 |
-
for e in catalog_weighted
|
| 113 |
-
])
|
| 114 |
-
rank = int(np.sum(catalog_scores > held_score)) + 1
|
| 115 |
-
ranks.append(rank)
|
| 116 |
-
print(f" [{i+1}/{len(liked)}] {held_out.name:30s} rank={rank:4d}")
|
| 117 |
-
|
| 118 |
-
report(ranks, len(valid_catalog), len(liked))
|
| 119 |
-
return ranks
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
def loo_full_model(engine, liked, catalog_arr, valid_catalog, liked_embs):
|
| 123 |
-
"""Full v2 model: multi-centroid + dim weights + text injection."""
|
| 124 |
-
print("\n--- Method: Full v2 (Multi-Centroid + Dim Weights + Text) ---")
|
| 125 |
-
ranks = []
|
| 126 |
-
for i, held_out in enumerate(liked):
|
| 127 |
-
other = [p for j, p in enumerate(liked) if j != i]
|
| 128 |
-
other_embs_arr = np.array([liked_embs[str(p)] for p in other])
|
| 129 |
-
|
| 130 |
-
centroids = engine._cluster_centroids(other_embs_arr)
|
| 131 |
-
dim_weights = engine._compute_dim_weights(other_embs_arr)
|
| 132 |
-
|
| 133 |
-
text_vectors = [engine.encode_text(q) for q in STYLE_TEXT_QUERIES]
|
| 134 |
-
|
| 135 |
-
taste_model = {
|
| 136 |
-
"centroids": centroids,
|
| 137 |
-
"dim_weights": dim_weights,
|
| 138 |
-
"text_vectors": text_vectors,
|
| 139 |
-
}
|
| 140 |
-
|
| 141 |
-
held_emb = liked_embs[str(held_out)]
|
| 142 |
-
held_score = engine.score_single(held_emb, taste_model)
|
| 143 |
-
|
| 144 |
-
catalog_scores = np.array([
|
| 145 |
-
engine.score_single(e, taste_model) for e in catalog_arr
|
| 146 |
-
])
|
| 147 |
-
rank = int(np.sum(catalog_scores > held_score)) + 1
|
| 148 |
-
ranks.append(rank)
|
| 149 |
-
print(f" [{i+1}/{len(liked)}] {held_out.name:30s} rank={rank:4d}")
|
| 150 |
-
|
| 151 |
-
report(ranks, len(valid_catalog), len(liked))
|
| 152 |
-
return ranks
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
def report(ranks, n_catalog, n_liked):
|
| 156 |
-
mean_rank = np.mean(ranks)
|
| 157 |
-
median_rank = np.median(ranks)
|
| 158 |
-
mrr = np.mean([1.0 / r for r in ranks])
|
| 159 |
-
recall = {k: sum(1 for r in ranks if r <= k) for k in [10, 25, 50, 100]}
|
| 160 |
-
|
| 161 |
-
print()
|
| 162 |
-
print(f" Mean Rank: {mean_rank:.1f} / {n_catalog}")
|
| 163 |
-
print(f" Median Rank: {median_rank:.1f}")
|
| 164 |
-
print(f" MRR: {mrr:.4f}")
|
| 165 |
-
for k, v in recall.items():
|
| 166 |
-
print(f" Recall@{k:3d}: {v/n_liked*100:.0f}% ({v}/{n_liked})")
|
| 167 |
-
print()
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
def main():
|
| 171 |
-
engine = TasteEngineV2()
|
| 172 |
-
liked = collect_liked_images(engine)
|
| 173 |
-
catalog = collect_all_product_images()
|
| 174 |
-
|
| 175 |
-
print(f"Liked: {len(liked)} images")
|
| 176 |
-
print(f"Catalog: {len(catalog)} images")
|
| 177 |
-
print(f"Model: Marqo-FashionSigLIP")
|
| 178 |
-
|
| 179 |
-
# Pre-encode everything
|
| 180 |
-
print("\nEncoding catalog...", flush=True)
|
| 181 |
-
t0 = time.time()
|
| 182 |
-
catalog_embs = engine.encode_batch(catalog)
|
| 183 |
-
catalog_arr = np.array([catalog_embs[str(p)] for p in catalog if str(p) in catalog_embs])
|
| 184 |
-
valid_catalog = [p for p in catalog if str(p) in catalog_embs]
|
| 185 |
-
print(f" {len(valid_catalog)} images in {time.time()-t0:.1f}s")
|
| 186 |
-
|
| 187 |
-
print("Encoding liked...", flush=True)
|
| 188 |
-
liked_embs = {str(p): engine.encode(p) for p in liked}
|
| 189 |
-
|
| 190 |
-
# Run all methods
|
| 191 |
-
loo_simple_average(engine, liked, catalog_arr, valid_catalog, liked_embs)
|
| 192 |
-
loo_multi_centroid(engine, liked, catalog_arr, valid_catalog, liked_embs)
|
| 193 |
-
loo_multi_centroid_dimweight(engine, liked, catalog_arr, valid_catalog, liked_embs)
|
| 194 |
-
loo_full_model(engine, liked, catalog_arr, valid_catalog, liked_embs)
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
if __name__ == "__main__":
|
| 198 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pyproject.toml
CHANGED
|
@@ -1,18 +1,22 @@
|
|
| 1 |
[project]
|
| 2 |
name = "taste-engine"
|
| 3 |
-
version = "0.
|
|
|
|
| 4 |
requires-python = ">=3.11"
|
| 5 |
dependencies = [
|
| 6 |
"open-clip-torch>=2.26",
|
| 7 |
"torch>=2.0",
|
| 8 |
"Pillow>=10.0",
|
| 9 |
"numpy>=1.24",
|
| 10 |
-
"streamlit>=1.30",
|
| 11 |
"scikit-learn>=1.3",
|
| 12 |
-
"playwright>=1.40",
|
| 13 |
"httpx>=0.27",
|
| 14 |
-
"transformers>=
|
|
|
|
| 15 |
]
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
[project.scripts]
|
| 18 |
-
taste
|
|
|
|
| 1 |
[project]
|
| 2 |
name = "taste-engine"
|
| 3 |
+
version = "0.2.0"
|
| 4 |
+
description = "Personal visual taste engine — learn aesthetic preferences from reference images"
|
| 5 |
requires-python = ">=3.11"
|
| 6 |
dependencies = [
|
| 7 |
"open-clip-torch>=2.26",
|
| 8 |
"torch>=2.0",
|
| 9 |
"Pillow>=10.0",
|
| 10 |
"numpy>=1.24",
|
|
|
|
| 11 |
"scikit-learn>=1.3",
|
|
|
|
| 12 |
"httpx>=0.27",
|
| 13 |
+
"transformers>=4.30",
|
| 14 |
+
"pyyaml>=6.0",
|
| 15 |
]
|
| 16 |
|
| 17 |
+
[project.optional-dependencies]
|
| 18 |
+
browser = ["playwright>=1.40"]
|
| 19 |
+
app = ["streamlit>=1.30"]
|
| 20 |
+
|
| 21 |
[project.scripts]
|
| 22 |
+
taste = "cli:main"
|
scan.py
DELETED
|
@@ -1,386 +0,0 @@
|
|
| 1 |
-
"""Full pipeline: download reference images → crawl Zalando bags → score → output HTML."""
|
| 2 |
-
|
| 3 |
-
import hashlib
|
| 4 |
-
import sys
|
| 5 |
-
import time
|
| 6 |
-
|
| 7 |
-
# Force unbuffered output
|
| 8 |
-
sys.stdout.reconfigure(line_buffering=True)
|
| 9 |
-
from pathlib import Path
|
| 10 |
-
|
| 11 |
-
import httpx
|
| 12 |
-
|
| 13 |
-
from engine import TasteEngine
|
| 14 |
-
from scraper import ZalandoScraper, BooztScraper, MiintoScraper, GenericScraper, Product
|
| 15 |
-
|
| 16 |
-
REFERENCE_DIR = Path(__file__).parent / "reference-images"
|
| 17 |
-
OUTPUT_HTML = Path(__file__).parent / "results.html"
|
| 18 |
-
|
| 19 |
-
# Reference product URLs to download and seed as "liked"
|
| 20 |
-
LIKED_URLS = [
|
| 21 |
-
"https://www.zalando.no/gaston-luga-splaeshini-handveske-cloud-cream-g7o51h004-b11.html",
|
| 22 |
-
"https://www.zalando.no/by-malene-birger-meela-handveske-toasted-coconut-by151h0c7-b11.html",
|
| 23 |
-
"https://www.zalando.no/seur-uma-mini-handveske-grey-sor51h014-c11.html",
|
| 24 |
-
"https://www.zalando.no/seur-suzette-skulderveske-acajou-sor51h017-o11.html",
|
| 25 |
-
"https://www.zalando.no/coach-bleecker-bucket-skulderveske-warm-brown-coh51h0zv-o11.html",
|
| 26 |
-
"https://www.zalando.no/gestuz-weda-clutch-poinsettia-ge251h00z-g11.html",
|
| 27 |
-
"https://www.zalando.no/coach-elora-top-handle-crossbody-bag-handveske-vanilla-coh51h0zr-b11.html",
|
| 28 |
-
"https://www.zalando.no/coach-bleecker-skulderveske-beige-coh51h102-b11.html",
|
| 29 |
-
"https://www.zalando.no/munthe-roluke-skulderveske-camel-muo51h002-c11.html",
|
| 30 |
-
]
|
| 31 |
-
|
| 32 |
-
# Non-Zalando reference URLs (need different scraping)
|
| 33 |
-
EXTERNAL_LIKED = [
|
| 34 |
-
"https://www.miinto.no/p-oyster-mini-bag-e1fe5ff5-6b9b-43de-8b22-0adb3017dfd0",
|
| 35 |
-
"https://jenek.store/bags/01merit-fog",
|
| 36 |
-
]
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def download_reference_images(engine: TasteEngine):
|
| 40 |
-
"""Download product images from liked URLs and seed them."""
|
| 41 |
-
from playwright.sync_api import sync_playwright
|
| 42 |
-
|
| 43 |
-
ref_dir = REFERENCE_DIR / "bags"
|
| 44 |
-
ref_dir.mkdir(parents=True, exist_ok=True)
|
| 45 |
-
|
| 46 |
-
all_urls = LIKED_URLS + EXTERNAL_LIKED
|
| 47 |
-
print(f"\n[1/4] Downloading {len(all_urls)} reference product images...")
|
| 48 |
-
|
| 49 |
-
with sync_playwright() as p:
|
| 50 |
-
browser = p.chromium.launch(headless=False, channel="chrome")
|
| 51 |
-
ctx = browser.new_context(locale="nb-NO", viewport={"width": 1440, "height": 900})
|
| 52 |
-
|
| 53 |
-
for url in all_urls:
|
| 54 |
-
slug = hashlib.md5(url.encode()).hexdigest()[:12]
|
| 55 |
-
img_path = ref_dir / f"{slug}.jpg"
|
| 56 |
-
|
| 57 |
-
if img_path.exists():
|
| 58 |
-
print(f" [cached] {url[:70]}")
|
| 59 |
-
engine.save_rating(img_path, 1)
|
| 60 |
-
continue
|
| 61 |
-
|
| 62 |
-
try:
|
| 63 |
-
page = ctx.new_page()
|
| 64 |
-
page.goto(url, wait_until="domcontentloaded", timeout=20000)
|
| 65 |
-
|
| 66 |
-
# Accept cookies
|
| 67 |
-
try:
|
| 68 |
-
page.click("button#uc-btn-accept-banner", timeout=2000)
|
| 69 |
-
except Exception:
|
| 70 |
-
pass
|
| 71 |
-
try:
|
| 72 |
-
page.click("button#onetrust-accept-btn-handler", timeout=2000)
|
| 73 |
-
except Exception:
|
| 74 |
-
pass
|
| 75 |
-
|
| 76 |
-
page.wait_for_timeout(2000)
|
| 77 |
-
|
| 78 |
-
# Extract main product image URL
|
| 79 |
-
img_url = page.evaluate("""() => {
|
| 80 |
-
// Try multiple strategies to find the main product image
|
| 81 |
-
// 1. Zalando: large images in gallery
|
| 82 |
-
const zalImg = document.querySelector('img[src*="ztat.net"][src*="spp-media"]');
|
| 83 |
-
if (zalImg) return zalImg.src;
|
| 84 |
-
|
| 85 |
-
// 2. Open Graph image
|
| 86 |
-
const ogImg = document.querySelector('meta[property="og:image"]');
|
| 87 |
-
if (ogImg) return ogImg.getAttribute('content');
|
| 88 |
-
|
| 89 |
-
// 3. Largest image on page
|
| 90 |
-
const imgs = Array.from(document.querySelectorAll('img[src]'));
|
| 91 |
-
const sorted = imgs
|
| 92 |
-
.filter(i => i.naturalWidth > 200 && !i.src.includes('logo') && !i.src.includes('icon'))
|
| 93 |
-
.sort((a, b) => (b.naturalWidth * b.naturalHeight) - (a.naturalWidth * a.naturalHeight));
|
| 94 |
-
return sorted[0]?.src || '';
|
| 95 |
-
}""")
|
| 96 |
-
|
| 97 |
-
page.close()
|
| 98 |
-
|
| 99 |
-
if not img_url:
|
| 100 |
-
print(f" [no image] {url[:70]}")
|
| 101 |
-
continue
|
| 102 |
-
|
| 103 |
-
# Download image
|
| 104 |
-
with httpx.Client(timeout=15, follow_redirects=True) as client:
|
| 105 |
-
resp = client.get(img_url)
|
| 106 |
-
if resp.status_code == 200 and len(resp.content) > 1000:
|
| 107 |
-
img_path.write_bytes(resp.content)
|
| 108 |
-
engine.save_rating(img_path, 1)
|
| 109 |
-
print(f" [ok] {url[:70]}")
|
| 110 |
-
else:
|
| 111 |
-
print(f" [download failed] {url[:70]}")
|
| 112 |
-
|
| 113 |
-
except Exception as e:
|
| 114 |
-
print(f" [error] {url[:70]}: {e}")
|
| 115 |
-
|
| 116 |
-
browser.close()
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
def crawl_and_score(engine: TasteEngine, store_queries: list[tuple[str, str, list[str]]], max_products: int = 10000):
|
| 120 |
-
"""Crawl multiple stores, score products, return sorted.
|
| 121 |
-
|
| 122 |
-
store_queries: list of (store_name, scraper_type, query_urls)
|
| 123 |
-
"""
|
| 124 |
-
taste = engine.build_taste_vector()
|
| 125 |
-
|
| 126 |
-
if taste is None:
|
| 127 |
-
print("ERROR: No taste vector — no liked images found.")
|
| 128 |
-
sys.exit(1)
|
| 129 |
-
|
| 130 |
-
total_queries = sum(len(qs) for _, _, qs in store_queries)
|
| 131 |
-
print(f"\n[2/4] Crawling bags across {len(store_queries)} stores (target: {max_products})...")
|
| 132 |
-
print(f" Taste vector built from {engine.stats()['liked']} liked images")
|
| 133 |
-
print(f" {total_queries} total queries to cover\n")
|
| 134 |
-
|
| 135 |
-
all_products: list[Product] = []
|
| 136 |
-
seen_urls: set[str] = set()
|
| 137 |
-
total_scraped = 0
|
| 138 |
-
total_scored = 0
|
| 139 |
-
query_idx = 0
|
| 140 |
-
|
| 141 |
-
scrapers = {
|
| 142 |
-
"zalando": ZalandoScraper(),
|
| 143 |
-
"boozt": BooztScraper(),
|
| 144 |
-
"miinto": MiintoScraper(),
|
| 145 |
-
"nakd": GenericScraper("NA-KD", "https://www.na-kd.com"),
|
| 146 |
-
"arket": GenericScraper("ARKET", "https://www.arket.com"),
|
| 147 |
-
"stories": GenericScraper("Other Stories", "https://www.stories.com"),
|
| 148 |
-
"cos": GenericScraper("COS", "https://www.cos.com"),
|
| 149 |
-
"wakakuu": GenericScraper("Wakakuu", "https://www.wakakuu.com"),
|
| 150 |
-
}
|
| 151 |
-
|
| 152 |
-
t0 = time.time()
|
| 153 |
-
|
| 154 |
-
for store_name, scraper_type, query_urls in store_queries:
|
| 155 |
-
if total_scored >= max_products:
|
| 156 |
-
break
|
| 157 |
-
|
| 158 |
-
scraper = scrapers[scraper_type]
|
| 159 |
-
products_per_query = max(max_products // max(len(query_urls), 1), 100)
|
| 160 |
-
|
| 161 |
-
print(f"\n === {store_name} ({len(query_urls)} queries) ===", flush=True)
|
| 162 |
-
|
| 163 |
-
for qi, query_url in enumerate(query_urls):
|
| 164 |
-
if total_scored >= max_products:
|
| 165 |
-
break
|
| 166 |
-
|
| 167 |
-
query_idx += 1
|
| 168 |
-
print(f" [{query_idx}] {query_url}", flush=True)
|
| 169 |
-
|
| 170 |
-
batch_num = 0
|
| 171 |
-
try:
|
| 172 |
-
for batch in scraper.crawl_category(query_url, max_products=products_per_query):
|
| 173 |
-
batch_num += 1
|
| 174 |
-
|
| 175 |
-
new_batch = [p for p in batch if p.url not in seen_urls]
|
| 176 |
-
for p in new_batch:
|
| 177 |
-
seen_urls.add(p.url)
|
| 178 |
-
total_scraped += len(new_batch)
|
| 179 |
-
|
| 180 |
-
if not new_batch:
|
| 181 |
-
continue
|
| 182 |
-
|
| 183 |
-
scraper.download_images(new_batch)
|
| 184 |
-
with_images = [p for p in new_batch if p.image_path and p.image_path.exists()]
|
| 185 |
-
|
| 186 |
-
if with_images:
|
| 187 |
-
scored = engine.score_product_images(
|
| 188 |
-
[p.image_path for p in with_images], taste
|
| 189 |
-
)
|
| 190 |
-
score_map = {str(path): score for path, score in scored}
|
| 191 |
-
for p in with_images:
|
| 192 |
-
p.score = score_map.get(str(p.image_path), 0.0)
|
| 193 |
-
|
| 194 |
-
all_products.extend(with_images)
|
| 195 |
-
total_scored += len(with_images)
|
| 196 |
-
|
| 197 |
-
elapsed = time.time() - t0
|
| 198 |
-
rate = total_scraped / elapsed if elapsed > 0 else 0
|
| 199 |
-
if all_products:
|
| 200 |
-
top = max(all_products, key=lambda p: p.score)
|
| 201 |
-
print(
|
| 202 |
-
f" batch {batch_num}: +{len(new_batch)} new, {total_scored} total "
|
| 203 |
-
f"({rate:.0f}/s) — top: {top.brand} [{top.score:.3f}]",
|
| 204 |
-
flush=True,
|
| 205 |
-
)
|
| 206 |
-
|
| 207 |
-
if total_scored >= max_products:
|
| 208 |
-
break
|
| 209 |
-
except Exception as e:
|
| 210 |
-
print(f" [error on {store_name} query, continuing] {e}", flush=True)
|
| 211 |
-
continue
|
| 212 |
-
|
| 213 |
-
elapsed = time.time() - t0
|
| 214 |
-
print(f"\n Done! {total_scored} unique products scored in {elapsed:.0f}s")
|
| 215 |
-
|
| 216 |
-
all_products.sort(key=lambda p: p.score, reverse=True)
|
| 217 |
-
return all_products
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
def generate_html(products: list[Product], output_path: Path, top_n: int = 200):
|
| 221 |
-
"""Generate an HTML file with ranked product results."""
|
| 222 |
-
top = products[:top_n]
|
| 223 |
-
|
| 224 |
-
if not top:
|
| 225 |
-
print("No products to display.")
|
| 226 |
-
return
|
| 227 |
-
|
| 228 |
-
scores = [p.score for p in top]
|
| 229 |
-
min_s, max_s = min(scores), max(scores)
|
| 230 |
-
score_range = max_s - min_s if max_s != min_s else 1.0
|
| 231 |
-
|
| 232 |
-
cards_html = []
|
| 233 |
-
for i, p in enumerate(top):
|
| 234 |
-
normalized = int(100 * (p.score - min_s) / score_range)
|
| 235 |
-
if normalized >= 70:
|
| 236 |
-
color = "#22c55e"
|
| 237 |
-
elif normalized >= 40:
|
| 238 |
-
color = "#3b82f6"
|
| 239 |
-
else:
|
| 240 |
-
color = "#f59e0b"
|
| 241 |
-
|
| 242 |
-
img_src = p.image_url if p.image_url else ""
|
| 243 |
-
|
| 244 |
-
if "boozt.com" in p.url:
|
| 245 |
-
store_label = "Boozt"
|
| 246 |
-
elif "miinto.no" in p.url:
|
| 247 |
-
store_label = "Miinto"
|
| 248 |
-
else:
|
| 249 |
-
store_label = "Zalando"
|
| 250 |
-
|
| 251 |
-
cards_html.append(f"""
|
| 252 |
-
<div class="card" data-store="{store_label}">
|
| 253 |
-
<span class="rank">#{i+1}</span>
|
| 254 |
-
<span class="store">{store_label}</span>
|
| 255 |
-
<a href="{p.url}" target="_blank">
|
| 256 |
-
<img src="{img_src}" loading="lazy" alt="{p.brand} {p.name}">
|
| 257 |
-
</a>
|
| 258 |
-
<div class="score" style="background:{color}">{normalized}%</div>
|
| 259 |
-
<div class="brand">{p.brand}</div>
|
| 260 |
-
<div class="name">{p.name[:50]}</div>
|
| 261 |
-
<div class="price">{p.price_text}</div>
|
| 262 |
-
<a href="{p.url}" target="_blank" class="link">View on {store_label}</a>
|
| 263 |
-
</div>""")
|
| 264 |
-
|
| 265 |
-
html = f"""<!DOCTYPE html>
|
| 266 |
-
<html lang="en">
|
| 267 |
-
<head>
|
| 268 |
-
<meta charset="UTF-8">
|
| 269 |
-
<title>Taste Engine — Top {len(top)} Bags</title>
|
| 270 |
-
<style>
|
| 271 |
-
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
|
| 272 |
-
body {{ font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: #0a0a0a; color: #e5e5e5; padding: 20px; }}
|
| 273 |
-
h1 {{ text-align: center; margin: 20px 0; font-size: 1.5em; color: #a3a3a3; }}
|
| 274 |
-
.stats {{ text-align: center; color: #737373; margin-bottom: 30px; }}
|
| 275 |
-
.grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 16px; max-width: 1400px; margin: 0 auto; }}
|
| 276 |
-
.card {{ background: #171717; border-radius: 12px; overflow: hidden; position: relative; transition: transform 0.2s; }}
|
| 277 |
-
.card:hover {{ transform: translateY(-4px); }}
|
| 278 |
-
.card img {{ width: 100%; aspect-ratio: 3/4; object-fit: cover; display: block; }}
|
| 279 |
-
.rank {{ position: absolute; top: 8px; left: 8px; background: rgba(0,0,0,0.7); color: #a3a3a3; padding: 2px 8px; border-radius: 6px; font-size: 12px; }}
|
| 280 |
-
.store {{ position: absolute; top: 8px; right: 8px; background: rgba(59,130,246,0.8); color: #fff; padding: 2px 8px; border-radius: 6px; font-size: 11px; font-weight: 600; }}
|
| 281 |
-
.score {{ display: inline-block; margin: 8px 12px 4px; padding: 2px 10px; border-radius: 6px; color: #fff; font-weight: 600; font-size: 13px; }}
|
| 282 |
-
.brand {{ padding: 0 12px; font-weight: 600; font-size: 14px; }}
|
| 283 |
-
.name {{ padding: 2px 12px; font-size: 12px; color: #a3a3a3; }}
|
| 284 |
-
.price {{ padding: 2px 12px 4px; font-size: 13px; color: #d4d4d4; }}
|
| 285 |
-
.link {{ display: block; text-align: center; padding: 8px; color: #60a5fa; text-decoration: none; font-size: 13px; border-top: 1px solid #262626; }}
|
| 286 |
-
.link:hover {{ background: #1e1e1e; }}
|
| 287 |
-
.filters {{ text-align: center; margin-bottom: 24px; display: flex; gap: 8px; justify-content: center; flex-wrap: wrap; }}
|
| 288 |
-
.filters button {{ background: #262626; color: #e5e5e5; border: 1px solid #404040; padding: 8px 20px; border-radius: 8px; cursor: pointer; font-size: 14px; transition: all 0.2s; }}
|
| 289 |
-
.filters button:hover {{ background: #333; }}
|
| 290 |
-
.filters button.active {{ background: #3b82f6; border-color: #3b82f6; color: #fff; }}
|
| 291 |
-
.card.hidden {{ display: none; }}
|
| 292 |
-
</style>
|
| 293 |
-
</head>
|
| 294 |
-
<body>
|
| 295 |
-
<h1>Taste Engine — Top {len(top)} Bags</h1>
|
| 296 |
-
<div class="stats">Scanned {len(products)} products total. Showing top {len(top)} by taste match.</div>
|
| 297 |
-
<div class="filters">
|
| 298 |
-
<button class="active" onclick="filterStore('all')">All</button>
|
| 299 |
-
<button onclick="filterStore('Zalando')">Zalando</button>
|
| 300 |
-
<button onclick="filterStore('Boozt')">Boozt</button>
|
| 301 |
-
<button onclick="filterStore('Miinto')">Miinto</button>
|
| 302 |
-
</div>
|
| 303 |
-
<div class="grid">
|
| 304 |
-
{"".join(cards_html)}
|
| 305 |
-
</div>
|
| 306 |
-
<script>
|
| 307 |
-
function filterStore(store) {{
|
| 308 |
-
document.querySelectorAll('.filters button').forEach(b => b.classList.remove('active'));
|
| 309 |
-
event.target.classList.add('active');
|
| 310 |
-
document.querySelectorAll('.card').forEach(card => {{
|
| 311 |
-
if (store === 'all' || card.dataset.store === store) {{
|
| 312 |
-
card.classList.remove('hidden');
|
| 313 |
-
}} else {{
|
| 314 |
-
card.classList.add('hidden');
|
| 315 |
-
}}
|
| 316 |
-
}});
|
| 317 |
-
}}
|
| 318 |
-
</script>
|
| 319 |
-
</body>
|
| 320 |
-
</html>"""
|
| 321 |
-
|
| 322 |
-
output_path.write_text(html)
|
| 323 |
-
print(f"\n[4/4] Results saved to {output_path}")
|
| 324 |
-
print(f" Open with: open {output_path}")
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
def main():
|
| 328 |
-
max_products = int(sys.argv[1]) if len(sys.argv) > 1 else 10000
|
| 329 |
-
|
| 330 |
-
engine = TasteEngine()
|
| 331 |
-
|
| 332 |
-
# Step 1: Download and seed reference images
|
| 333 |
-
download_reference_images(engine)
|
| 334 |
-
|
| 335 |
-
print(f"\n Taste profile: {engine.stats()}")
|
| 336 |
-
|
| 337 |
-
# Step 2-3: Crawl and score — leather bags over 1000 NOK across 3 stores
|
| 338 |
-
store_queries = [
|
| 339 |
-
("Zalando", "zalando", [
|
| 340 |
-
"/dame/?q=veske&upper_material=leather&price_from=1000",
|
| 341 |
-
"/dame/?q=skulderveske&upper_material=leather&price_from=1000",
|
| 342 |
-
"/dame/?q=handveske&upper_material=leather&price_from=1000",
|
| 343 |
-
"/dame/?q=crossbody&upper_material=leather&price_from=1000",
|
| 344 |
-
"/dame/?q=clutch&upper_material=leather&price_from=1000",
|
| 345 |
-
"/dame/?q=tote&upper_material=leather&price_from=1000",
|
| 346 |
-
"/dame/?q=bucket+bag&upper_material=leather&price_from=1000",
|
| 347 |
-
"/dame/?q=mini+bag&upper_material=leather&price_from=1000",
|
| 348 |
-
"/dame/?q=shopper&upper_material=leather&price_from=1000",
|
| 349 |
-
"/dame/?q=bag&upper_material=leather&price_from=1000",
|
| 350 |
-
]),
|
| 351 |
-
("Boozt", "boozt", [
|
| 352 |
-
"/no/no/kvinner/vesker?material=ekte-skinn",
|
| 353 |
-
"/no/no/kvinner/vesker/skuldervesker?material=ekte-skinn",
|
| 354 |
-
"/no/no/kvinner/vesker/haandvesker?material=ekte-skinn",
|
| 355 |
-
"/no/no/kvinner/vesker/crossbody-vesker?material=ekte-skinn",
|
| 356 |
-
]),
|
| 357 |
-
("Miinto", "miinto", [
|
| 358 |
-
"/dame-skuldervesker",
|
| 359 |
-
"/dame-handvesker",
|
| 360 |
-
"/dame-clutch-vesker",
|
| 361 |
-
]),
|
| 362 |
-
("NA-KD", "nakd", [
|
| 363 |
-
"https://www.na-kd.com/no/kvinner/vesker",
|
| 364 |
-
"https://www.na-kd.com/no/kvinner/vesker/skuldervesker",
|
| 365 |
-
]),
|
| 366 |
-
("ARKET", "arket", [
|
| 367 |
-
"https://www.arket.com/no/women/bags-and-wallets/",
|
| 368 |
-
]),
|
| 369 |
-
("& Other Stories", "stories", [
|
| 370 |
-
"https://www.stories.com/no/women/bags/",
|
| 371 |
-
]),
|
| 372 |
-
("COS", "cos", [
|
| 373 |
-
"https://www.cos.com/no/women/accessories/bags/",
|
| 374 |
-
]),
|
| 375 |
-
("Wakakuu", "wakakuu", [
|
| 376 |
-
"https://www.wakakuu.com/no/kvinner/vesker",
|
| 377 |
-
]),
|
| 378 |
-
]
|
| 379 |
-
products = crawl_and_score(engine, store_queries, max_products=max_products)
|
| 380 |
-
|
| 381 |
-
# Step 4: Generate HTML
|
| 382 |
-
generate_html(products, OUTPUT_HTML)
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
if __name__ == "__main__":
|
| 386 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scraper.py
DELETED
|
@@ -1,798 +0,0 @@
|
|
| 1 |
-
"""Store scrapers — pull product images + metadata from online shops."""
|
| 2 |
-
|
| 3 |
-
import hashlib
|
| 4 |
-
import json
|
| 5 |
-
import re
|
| 6 |
-
from dataclasses import dataclass
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
from typing import Generator
|
| 9 |
-
from urllib.parse import quote
|
| 10 |
-
|
| 11 |
-
import httpx
|
| 12 |
-
|
| 13 |
-
DISLIKED_BRANDS = {
|
| 14 |
-
"vagabond", "polo ralph lauren", "tommy hilfiger", "gant",
|
| 15 |
-
"ralph lauren", "tommy jeans",
|
| 16 |
-
}
|
| 17 |
-
|
| 18 |
-
ZALANDO_NOISE = {
|
| 19 |
-
"deal", "miks & match", "heart_outlined", "sponset", "nyhet",
|
| 20 |
-
"bærekraftig", "raskere leveranse", "premium", "designer",
|
| 21 |
-
}
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
@dataclass
|
| 25 |
-
class Product:
|
| 26 |
-
url: str
|
| 27 |
-
image_url: str
|
| 28 |
-
image_path: Path | None = None
|
| 29 |
-
brand: str = ""
|
| 30 |
-
name: str = ""
|
| 31 |
-
price_text: str = ""
|
| 32 |
-
price_nok: float = 0.0
|
| 33 |
-
fabric: str = ""
|
| 34 |
-
score: float = 0.0
|
| 35 |
-
|
| 36 |
-
def to_dict(self) -> dict:
|
| 37 |
-
return {
|
| 38 |
-
"url": self.url,
|
| 39 |
-
"image_url": self.image_url,
|
| 40 |
-
"image_path": str(self.image_path) if self.image_path else None,
|
| 41 |
-
"brand": self.brand,
|
| 42 |
-
"name": self.name,
|
| 43 |
-
"price_text": self.price_text,
|
| 44 |
-
"price_nok": self.price_nok,
|
| 45 |
-
"fabric": self.fabric,
|
| 46 |
-
"score": self.score,
|
| 47 |
-
}
|
| 48 |
-
|
| 49 |
-
@staticmethod
|
| 50 |
-
def from_dict(d: dict) -> "Product":
|
| 51 |
-
p = Product(url=d["url"], image_url=d["image_url"])
|
| 52 |
-
p.image_path = Path(d["image_path"]) if d.get("image_path") else None
|
| 53 |
-
p.brand = d.get("brand", "")
|
| 54 |
-
p.name = d.get("name", "")
|
| 55 |
-
p.price_text = d.get("price_text", "")
|
| 56 |
-
p.price_nok = d.get("price_nok", 0.0)
|
| 57 |
-
p.fabric = d.get("fabric", "")
|
| 58 |
-
p.score = d.get("score", 0.0)
|
| 59 |
-
return p
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
def _parse_zalando_products(raw: list[dict], base: str) -> list[Product]:
|
| 63 |
-
"""Parse raw DOM extraction into Product objects."""
|
| 64 |
-
seen = set()
|
| 65 |
-
products = []
|
| 66 |
-
|
| 67 |
-
for item in raw:
|
| 68 |
-
href = item["href"]
|
| 69 |
-
if href in seen:
|
| 70 |
-
continue
|
| 71 |
-
seen.add(href)
|
| 72 |
-
|
| 73 |
-
full_url = href if href.startswith("http") else f"{base}{href}"
|
| 74 |
-
texts = item.get("texts", [])
|
| 75 |
-
desc = item.get("desc", "")
|
| 76 |
-
|
| 77 |
-
clean = [t for t in texts if t.lower() not in ZALANDO_NOISE and not t.endswith("%")]
|
| 78 |
-
brand = clean[0] if clean else ""
|
| 79 |
-
name = clean[1] if len(clean) > 1 else desc
|
| 80 |
-
|
| 81 |
-
full_text_lower = " ".join(texts).lower()
|
| 82 |
-
if any(db in full_text_lower for db in DISLIKED_BRANDS):
|
| 83 |
-
continue
|
| 84 |
-
|
| 85 |
-
price_text, price_nok = "", 0.0
|
| 86 |
-
for t in texts:
|
| 87 |
-
m = re.search(r"([\d\s]+[,.]?\d*)\s*kr", t, re.IGNORECASE)
|
| 88 |
-
if m:
|
| 89 |
-
price_text = t
|
| 90 |
-
try:
|
| 91 |
-
price_nok = float(
|
| 92 |
-
m.group(1).replace("\xa0", "").replace(" ", "").replace(",", ".")
|
| 93 |
-
)
|
| 94 |
-
except ValueError:
|
| 95 |
-
pass
|
| 96 |
-
break
|
| 97 |
-
|
| 98 |
-
products.append(Product(
|
| 99 |
-
url=full_url,
|
| 100 |
-
image_url=item["img"],
|
| 101 |
-
brand=brand,
|
| 102 |
-
name=name,
|
| 103 |
-
price_text=price_text,
|
| 104 |
-
price_nok=price_nok,
|
| 105 |
-
))
|
| 106 |
-
|
| 107 |
-
return products
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
_EXTRACT_JS = """() => {
|
| 111 |
-
const results = [];
|
| 112 |
-
const cards = document.querySelectorAll('article');
|
| 113 |
-
for (const el of cards) {
|
| 114 |
-
const a = el.querySelector('a[href*=".html"]');
|
| 115 |
-
const img = el.querySelector('img[src*="img"]');
|
| 116 |
-
if (!a || !img) continue;
|
| 117 |
-
const descEl = el.querySelector('[descriptiontext]');
|
| 118 |
-
const desc = descEl ? descEl.getAttribute('descriptiontext') : '';
|
| 119 |
-
const texts = el.innerText.split('\\n').map(t => t.trim()).filter(Boolean);
|
| 120 |
-
results.push({
|
| 121 |
-
href: a.getAttribute('href') || '',
|
| 122 |
-
img: img.src || '',
|
| 123 |
-
texts: texts,
|
| 124 |
-
desc: desc,
|
| 125 |
-
});
|
| 126 |
-
}
|
| 127 |
-
return results;
|
| 128 |
-
}"""
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
class ZalandoScraper:
|
| 132 |
-
BASE = "https://www.zalando.no"
|
| 133 |
-
|
| 134 |
-
def __init__(self, cache_dir: Path | None = None):
|
| 135 |
-
self.cache_dir = Path(cache_dir or Path.home() / ".taste" / "products")
|
| 136 |
-
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
| 137 |
-
self.catalog_path = Path.home() / ".taste" / "catalog.jsonl"
|
| 138 |
-
|
| 139 |
-
def search(self, query: str, category: str = "dame", max_products: int = 60,
|
| 140 |
-
price_max: int = 0) -> list[Product]:
|
| 141 |
-
"""Quick search — single page, limited results."""
|
| 142 |
-
from playwright.sync_api import sync_playwright
|
| 143 |
-
|
| 144 |
-
url = f"{self.BASE}/{category}/?q={quote(query)}"
|
| 145 |
-
if price_max:
|
| 146 |
-
url += f"&price_to={price_max}"
|
| 147 |
-
|
| 148 |
-
with sync_playwright() as p:
|
| 149 |
-
browser = p.chromium.launch(headless=False, channel="chrome")
|
| 150 |
-
ctx = browser.new_context(locale="nb-NO", viewport={"width": 1440, "height": 900})
|
| 151 |
-
page = ctx.new_page()
|
| 152 |
-
page.goto(url, wait_until="domcontentloaded", timeout=30000)
|
| 153 |
-
self._accept_cookies(page)
|
| 154 |
-
page.wait_for_timeout(2000)
|
| 155 |
-
|
| 156 |
-
for _ in range(4):
|
| 157 |
-
page.keyboard.press("End")
|
| 158 |
-
page.wait_for_timeout(800)
|
| 159 |
-
|
| 160 |
-
raw = page.evaluate(_EXTRACT_JS)
|
| 161 |
-
browser.close()
|
| 162 |
-
|
| 163 |
-
products = _parse_zalando_products(raw, self.BASE)
|
| 164 |
-
return products[:max_products]
|
| 165 |
-
|
| 166 |
-
def crawl_category(
|
| 167 |
-
self,
|
| 168 |
-
category_url: str,
|
| 169 |
-
max_products: int = 10000,
|
| 170 |
-
batch_size: int = 50,
|
| 171 |
-
) -> Generator[list[Product], None, None]:
|
| 172 |
-
"""Deep crawl — aggressive scrolling + pagination, yields batches progressively."""
|
| 173 |
-
from playwright.sync_api import sync_playwright
|
| 174 |
-
|
| 175 |
-
url = category_url if category_url.startswith("http") else f"{self.BASE}{category_url}"
|
| 176 |
-
seen_hrefs: set[str] = set()
|
| 177 |
-
total_yielded = 0
|
| 178 |
-
|
| 179 |
-
with sync_playwright() as p:
|
| 180 |
-
browser = p.chromium.launch(headless=False, channel="chrome")
|
| 181 |
-
ctx = browser.new_context(locale="nb-NO", viewport={"width": 1440, "height": 900})
|
| 182 |
-
page = ctx.new_page()
|
| 183 |
-
page.goto(url, wait_until="domcontentloaded", timeout=30000)
|
| 184 |
-
self._accept_cookies(page)
|
| 185 |
-
page.wait_for_timeout(2000)
|
| 186 |
-
|
| 187 |
-
stale_rounds = 0
|
| 188 |
-
|
| 189 |
-
while total_yielded < max_products:
|
| 190 |
-
# Aggressive scrolling — scroll further each round
|
| 191 |
-
for _ in range(5):
|
| 192 |
-
page.evaluate("window.scrollBy(0, window.innerHeight * 2)")
|
| 193 |
-
page.wait_for_timeout(400)
|
| 194 |
-
# One final scroll to absolute bottom
|
| 195 |
-
page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
|
| 196 |
-
page.wait_for_timeout(800)
|
| 197 |
-
|
| 198 |
-
# Extract all currently loaded products
|
| 199 |
-
raw = page.evaluate(_EXTRACT_JS)
|
| 200 |
-
all_products = _parse_zalando_products(raw, self.BASE)
|
| 201 |
-
|
| 202 |
-
# Find new products not yet yielded
|
| 203 |
-
new_products = []
|
| 204 |
-
for prod in all_products:
|
| 205 |
-
if prod.url not in seen_hrefs:
|
| 206 |
-
seen_hrefs.add(prod.url)
|
| 207 |
-
new_products.append(prod)
|
| 208 |
-
|
| 209 |
-
if new_products:
|
| 210 |
-
stale_rounds = 0
|
| 211 |
-
for i in range(0, len(new_products), batch_size):
|
| 212 |
-
chunk = new_products[i : i + batch_size]
|
| 213 |
-
total_yielded += len(chunk)
|
| 214 |
-
yield chunk
|
| 215 |
-
if total_yielded >= max_products:
|
| 216 |
-
break
|
| 217 |
-
else:
|
| 218 |
-
stale_rounds += 1
|
| 219 |
-
|
| 220 |
-
# Try multiple "load more" button patterns
|
| 221 |
-
clicked = False
|
| 222 |
-
for selector in [
|
| 223 |
-
"button:has-text('Vis flere')",
|
| 224 |
-
"button:has-text('Load more')",
|
| 225 |
-
"button:has-text('Se flere')",
|
| 226 |
-
"a:has-text('Vis flere')",
|
| 227 |
-
"a:has-text('Neste')",
|
| 228 |
-
"[data-testid*='next']",
|
| 229 |
-
"[class*='pagination'] a:last-child",
|
| 230 |
-
]:
|
| 231 |
-
try:
|
| 232 |
-
page.click(selector, timeout=1000)
|
| 233 |
-
page.wait_for_timeout(2000)
|
| 234 |
-
clicked = True
|
| 235 |
-
stale_rounds = 0
|
| 236 |
-
break
|
| 237 |
-
except Exception:
|
| 238 |
-
continue
|
| 239 |
-
|
| 240 |
-
# If nothing to click, try URL pagination (?p=2, ?p=3...)
|
| 241 |
-
if not clicked and stale_rounds <= 2:
|
| 242 |
-
current_url = page.url
|
| 243 |
-
if "p=" in current_url:
|
| 244 |
-
import re as _re
|
| 245 |
-
next_url = _re.sub(r'p=(\d+)', lambda m: f'p={int(m.group(1))+1}', current_url)
|
| 246 |
-
else:
|
| 247 |
-
sep = "&" if "?" in current_url else "?"
|
| 248 |
-
next_url = f"{current_url}{sep}p=2"
|
| 249 |
-
try:
|
| 250 |
-
page.goto(next_url, wait_until="domcontentloaded", timeout=15000)
|
| 251 |
-
page.wait_for_timeout(2000)
|
| 252 |
-
stale_rounds = 0
|
| 253 |
-
except Exception:
|
| 254 |
-
pass
|
| 255 |
-
|
| 256 |
-
if stale_rounds >= 8:
|
| 257 |
-
break
|
| 258 |
-
|
| 259 |
-
browser.close()
|
| 260 |
-
|
| 261 |
-
def download_images(self, products: list[Product]) -> list[Product]:
|
| 262 |
-
"""Download product images for CLIP encoding."""
|
| 263 |
-
with httpx.Client(timeout=15, follow_redirects=True) as client:
|
| 264 |
-
for p in products:
|
| 265 |
-
if not p.image_url or p.image_path:
|
| 266 |
-
continue
|
| 267 |
-
try:
|
| 268 |
-
h = hashlib.md5(p.url.encode()).hexdigest()[:12]
|
| 269 |
-
path = self.cache_dir / f"{h}.jpg"
|
| 270 |
-
if path.exists():
|
| 271 |
-
p.image_path = path
|
| 272 |
-
continue
|
| 273 |
-
resp = client.get(p.image_url)
|
| 274 |
-
if resp.status_code == 200 and len(resp.content) > 1000:
|
| 275 |
-
path.write_bytes(resp.content)
|
| 276 |
-
p.image_path = path
|
| 277 |
-
except Exception:
|
| 278 |
-
continue
|
| 279 |
-
return products
|
| 280 |
-
|
| 281 |
-
def save_to_catalog(self, products: list[Product]):
|
| 282 |
-
"""Append products to persistent catalog file."""
|
| 283 |
-
existing_urls = set()
|
| 284 |
-
if self.catalog_path.exists():
|
| 285 |
-
for line in self.catalog_path.read_text().splitlines():
|
| 286 |
-
if line.strip():
|
| 287 |
-
existing_urls.add(json.loads(line)["url"])
|
| 288 |
-
|
| 289 |
-
with open(self.catalog_path, "a") as f:
|
| 290 |
-
for p in products:
|
| 291 |
-
if p.url not in existing_urls:
|
| 292 |
-
f.write(json.dumps(p.to_dict()) + "\n")
|
| 293 |
-
existing_urls.add(p.url)
|
| 294 |
-
|
| 295 |
-
def load_catalog(self) -> list[Product]:
|
| 296 |
-
"""Load all products from persistent catalog."""
|
| 297 |
-
if not self.catalog_path.exists():
|
| 298 |
-
return []
|
| 299 |
-
products = []
|
| 300 |
-
for line in self.catalog_path.read_text().splitlines():
|
| 301 |
-
if line.strip():
|
| 302 |
-
products.append(Product.from_dict(json.loads(line)))
|
| 303 |
-
return products
|
| 304 |
-
|
| 305 |
-
def _accept_cookies(self, page):
|
| 306 |
-
try:
|
| 307 |
-
page.click("button#uc-btn-accept-banner", timeout=3000)
|
| 308 |
-
except Exception:
|
| 309 |
-
pass
|
| 310 |
-
|
| 311 |
-
def check_fabric(self, product_url: str) -> str:
|
| 312 |
-
"""Visit product detail page and extract fabric/material info."""
|
| 313 |
-
from playwright.sync_api import sync_playwright
|
| 314 |
-
|
| 315 |
-
with sync_playwright() as p:
|
| 316 |
-
browser = p.chromium.launch(headless=False, channel="chrome")
|
| 317 |
-
page = browser.new_page()
|
| 318 |
-
page.goto(product_url, wait_until="domcontentloaded", timeout=15000)
|
| 319 |
-
page.wait_for_timeout(1500)
|
| 320 |
-
|
| 321 |
-
try:
|
| 322 |
-
page.click("text=/[Mm]aterial|[Dd]etaljer|[Ss]ammensetning/", timeout=2000)
|
| 323 |
-
page.wait_for_timeout(500)
|
| 324 |
-
except Exception:
|
| 325 |
-
pass
|
| 326 |
-
|
| 327 |
-
fabric = page.evaluate("""() => {
|
| 328 |
-
const text = document.body.innerText;
|
| 329 |
-
const lines = text.split('\\n');
|
| 330 |
-
for (let i = 0; i < lines.length; i++) {
|
| 331 |
-
const low = lines[i].toLowerCase();
|
| 332 |
-
if (low.includes('material') || low.includes('sammensetning') ||
|
| 333 |
-
low.includes('composition') || low.includes('stoff') ||
|
| 334 |
-
low.includes('yttermat') || low.includes('shell')) {
|
| 335 |
-
return lines.slice(i, i + 6).join(' | ').trim();
|
| 336 |
-
}
|
| 337 |
-
}
|
| 338 |
-
return '';
|
| 339 |
-
}""")
|
| 340 |
-
|
| 341 |
-
browser.close()
|
| 342 |
-
return fabric
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
class BooztScraper:
|
| 346 |
-
BASE = "https://www.boozt.com"
|
| 347 |
-
|
| 348 |
-
def __init__(self, cache_dir: Path | None = None):
|
| 349 |
-
self.cache_dir = Path(cache_dir or Path.home() / ".taste" / "products-boozt")
|
| 350 |
-
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
| 351 |
-
|
| 352 |
-
def crawl_category(
|
| 353 |
-
self, category_url: str, max_products: int = 5000, batch_size: int = 50,
|
| 354 |
-
) -> Generator[list[Product], None, None]:
|
| 355 |
-
from playwright.sync_api import sync_playwright
|
| 356 |
-
|
| 357 |
-
url = category_url if category_url.startswith("http") else f"{self.BASE}{category_url}"
|
| 358 |
-
seen_hrefs: set[str] = set()
|
| 359 |
-
total_yielded = 0
|
| 360 |
-
|
| 361 |
-
with sync_playwright() as p:
|
| 362 |
-
browser = p.chromium.launch(headless=False, channel="chrome")
|
| 363 |
-
ctx = browser.new_context(locale="nb-NO", viewport={"width": 1440, "height": 900})
|
| 364 |
-
page = ctx.new_page()
|
| 365 |
-
page.goto(url, wait_until="domcontentloaded", timeout=30000)
|
| 366 |
-
|
| 367 |
-
try:
|
| 368 |
-
page.click("button#onetrust-accept-btn-handler", timeout=3000)
|
| 369 |
-
except Exception:
|
| 370 |
-
pass
|
| 371 |
-
page.wait_for_timeout(2000)
|
| 372 |
-
|
| 373 |
-
stale_rounds = 0
|
| 374 |
-
|
| 375 |
-
while total_yielded < max_products:
|
| 376 |
-
for _ in range(5):
|
| 377 |
-
page.evaluate("window.scrollBy(0, window.innerHeight * 2)")
|
| 378 |
-
page.wait_for_timeout(400)
|
| 379 |
-
page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
|
| 380 |
-
page.wait_for_timeout(800)
|
| 381 |
-
|
| 382 |
-
raw = page.evaluate("""() => {
|
| 383 |
-
const links = Array.from(document.querySelectorAll('a[href]'));
|
| 384 |
-
const prods = links.filter(a => {
|
| 385 |
-
const img = a.querySelector('img');
|
| 386 |
-
const href = a.href;
|
| 387 |
-
return img && href.includes('/no/no/') && href.match(/\\/\\d{5,}/);
|
| 388 |
-
});
|
| 389 |
-
return prods.map(a => {
|
| 390 |
-
const img = a.querySelector('img');
|
| 391 |
-
const texts = a.innerText.split('\\n').map(t => t.trim()).filter(Boolean);
|
| 392 |
-
return {
|
| 393 |
-
href: a.href,
|
| 394 |
-
img: img ? img.src : '',
|
| 395 |
-
texts: texts,
|
| 396 |
-
};
|
| 397 |
-
});
|
| 398 |
-
}""")
|
| 399 |
-
|
| 400 |
-
new_products = []
|
| 401 |
-
for item in raw:
|
| 402 |
-
href = item["href"]
|
| 403 |
-
if href in seen_hrefs:
|
| 404 |
-
continue
|
| 405 |
-
seen_hrefs.add(href)
|
| 406 |
-
|
| 407 |
-
texts = item.get("texts", [])
|
| 408 |
-
clean = [t for t in texts if not t.endswith("Deal") and not t.startswith("Spar")]
|
| 409 |
-
brand = clean[0] if clean else ""
|
| 410 |
-
name = clean[1] if len(clean) > 1 else ""
|
| 411 |
-
|
| 412 |
-
full_text_lower = " ".join(texts).lower()
|
| 413 |
-
if any(db in full_text_lower for db in DISLIKED_BRANDS):
|
| 414 |
-
continue
|
| 415 |
-
|
| 416 |
-
price_text, price_nok = "", 0.0
|
| 417 |
-
for t in texts:
|
| 418 |
-
m = re.search(r"([\d\s]+)\s*kr", t, re.IGNORECASE)
|
| 419 |
-
if m:
|
| 420 |
-
price_text = t
|
| 421 |
-
try:
|
| 422 |
-
price_nok = float(m.group(1).replace("\xa0", "").replace(" ", ""))
|
| 423 |
-
except ValueError:
|
| 424 |
-
pass
|
| 425 |
-
break
|
| 426 |
-
|
| 427 |
-
new_products.append(Product(
|
| 428 |
-
url=href, image_url=item["img"],
|
| 429 |
-
brand=brand, name=name,
|
| 430 |
-
price_text=price_text, price_nok=price_nok,
|
| 431 |
-
))
|
| 432 |
-
|
| 433 |
-
if new_products:
|
| 434 |
-
stale_rounds = 0
|
| 435 |
-
for i in range(0, len(new_products), batch_size):
|
| 436 |
-
chunk = new_products[i : i + batch_size]
|
| 437 |
-
total_yielded += len(chunk)
|
| 438 |
-
yield chunk
|
| 439 |
-
if total_yielded >= max_products:
|
| 440 |
-
break
|
| 441 |
-
else:
|
| 442 |
-
stale_rounds += 1
|
| 443 |
-
try:
|
| 444 |
-
page.click("button:has-text('Vis flere'), button:has-text('Load more'), button:has-text('Se flere')", timeout=2000)
|
| 445 |
-
page.wait_for_timeout(1500)
|
| 446 |
-
stale_rounds = 0
|
| 447 |
-
except Exception:
|
| 448 |
-
pass
|
| 449 |
-
if stale_rounds >= 8:
|
| 450 |
-
break
|
| 451 |
-
|
| 452 |
-
browser.close()
|
| 453 |
-
|
| 454 |
-
def download_images(self, products: list[Product]) -> list[Product]:
|
| 455 |
-
with httpx.Client(timeout=15, follow_redirects=True) as client:
|
| 456 |
-
for p in products:
|
| 457 |
-
if not p.image_url or p.image_path:
|
| 458 |
-
continue
|
| 459 |
-
try:
|
| 460 |
-
h = hashlib.md5(p.url.encode()).hexdigest()[:12]
|
| 461 |
-
path = self.cache_dir / f"{h}.jpg"
|
| 462 |
-
if path.exists():
|
| 463 |
-
p.image_path = path
|
| 464 |
-
continue
|
| 465 |
-
resp = client.get(p.image_url)
|
| 466 |
-
if resp.status_code == 200 and len(resp.content) > 1000:
|
| 467 |
-
path.write_bytes(resp.content)
|
| 468 |
-
p.image_path = path
|
| 469 |
-
except Exception:
|
| 470 |
-
continue
|
| 471 |
-
return products
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
class MiintoScraper:
|
| 475 |
-
BASE = "https://www.miinto.no"
|
| 476 |
-
|
| 477 |
-
def __init__(self, cache_dir: Path | None = None):
|
| 478 |
-
self.cache_dir = Path(cache_dir or Path.home() / ".taste" / "products-miinto")
|
| 479 |
-
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
| 480 |
-
|
| 481 |
-
def crawl_category(
|
| 482 |
-
self, category_url: str, max_products: int = 5000, batch_size: int = 50,
|
| 483 |
-
) -> Generator[list[Product], None, None]:
|
| 484 |
-
from playwright.sync_api import sync_playwright
|
| 485 |
-
|
| 486 |
-
url = category_url if category_url.startswith("http") else f"{self.BASE}{category_url}"
|
| 487 |
-
seen_hrefs: set[str] = set()
|
| 488 |
-
total_yielded = 0
|
| 489 |
-
|
| 490 |
-
with sync_playwright() as p:
|
| 491 |
-
browser = p.chromium.launch(headless=False, channel="chrome")
|
| 492 |
-
ctx = browser.new_context(locale="nb-NO", viewport={"width": 1440, "height": 900})
|
| 493 |
-
page = ctx.new_page()
|
| 494 |
-
page.goto(url, wait_until="networkidle", timeout=30000)
|
| 495 |
-
page.wait_for_timeout(2000)
|
| 496 |
-
|
| 497 |
-
try:
|
| 498 |
-
page.click('button:has-text("Godta")', timeout=3000)
|
| 499 |
-
except Exception:
|
| 500 |
-
pass
|
| 501 |
-
page.wait_for_timeout(3000)
|
| 502 |
-
|
| 503 |
-
stale_rounds = 0
|
| 504 |
-
|
| 505 |
-
while total_yielded < max_products:
|
| 506 |
-
for _ in range(5):
|
| 507 |
-
page.evaluate("window.scrollBy(0, window.innerHeight * 2)")
|
| 508 |
-
page.wait_for_timeout(400)
|
| 509 |
-
page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
|
| 510 |
-
page.wait_for_timeout(800)
|
| 511 |
-
|
| 512 |
-
raw = page.evaluate(r"""() => {
|
| 513 |
-
const links = Array.from(document.querySelectorAll('a[href]'));
|
| 514 |
-
const prods = links.filter(a => {
|
| 515 |
-
return a.href.match(/\/p-[\w-]+/) && a.querySelector('img');
|
| 516 |
-
});
|
| 517 |
-
return prods.map(a => {
|
| 518 |
-
const img = a.querySelector('img');
|
| 519 |
-
const texts = a.innerText.split('\n').map(t => t.trim()).filter(Boolean);
|
| 520 |
-
return {
|
| 521 |
-
href: a.href,
|
| 522 |
-
img: img ? (img.src || img.dataset.src || '') : '',
|
| 523 |
-
texts: texts,
|
| 524 |
-
};
|
| 525 |
-
});
|
| 526 |
-
}""")
|
| 527 |
-
|
| 528 |
-
new_products = []
|
| 529 |
-
for item in raw:
|
| 530 |
-
href = item["href"]
|
| 531 |
-
if href in seen_hrefs:
|
| 532 |
-
continue
|
| 533 |
-
seen_hrefs.add(href)
|
| 534 |
-
|
| 535 |
-
texts = item.get("texts", [])
|
| 536 |
-
brand = texts[0] if texts else ""
|
| 537 |
-
name = texts[1] if len(texts) > 1 else ""
|
| 538 |
-
|
| 539 |
-
full_text_lower = " ".join(texts).lower()
|
| 540 |
-
if any(db in full_text_lower for db in DISLIKED_BRANDS):
|
| 541 |
-
continue
|
| 542 |
-
|
| 543 |
-
price_text, price_nok = "", 0.0
|
| 544 |
-
for t in texts:
|
| 545 |
-
m = re.search(r"([\d\s]+)\s*(?:kr|NOK)", t, re.IGNORECASE)
|
| 546 |
-
if m:
|
| 547 |
-
price_text = t
|
| 548 |
-
try:
|
| 549 |
-
price_nok = float(m.group(1).replace("\xa0", "").replace(" ", ""))
|
| 550 |
-
except ValueError:
|
| 551 |
-
pass
|
| 552 |
-
break
|
| 553 |
-
|
| 554 |
-
new_products.append(Product(
|
| 555 |
-
url=href, image_url=item["img"],
|
| 556 |
-
brand=brand, name=name,
|
| 557 |
-
price_text=price_text, price_nok=price_nok,
|
| 558 |
-
))
|
| 559 |
-
|
| 560 |
-
if new_products:
|
| 561 |
-
stale_rounds = 0
|
| 562 |
-
for i in range(0, len(new_products), batch_size):
|
| 563 |
-
chunk = new_products[i : i + batch_size]
|
| 564 |
-
total_yielded += len(chunk)
|
| 565 |
-
yield chunk
|
| 566 |
-
if total_yielded >= max_products:
|
| 567 |
-
break
|
| 568 |
-
else:
|
| 569 |
-
stale_rounds += 1
|
| 570 |
-
try:
|
| 571 |
-
page.click("button:has-text('Vis flere'), button:has-text('Load more')", timeout=2000)
|
| 572 |
-
page.wait_for_timeout(1500)
|
| 573 |
-
stale_rounds = 0
|
| 574 |
-
except Exception:
|
| 575 |
-
pass
|
| 576 |
-
if stale_rounds >= 8:
|
| 577 |
-
break
|
| 578 |
-
|
| 579 |
-
browser.close()
|
| 580 |
-
|
| 581 |
-
def download_images(self, products: list[Product]) -> list[Product]:
|
| 582 |
-
with httpx.Client(timeout=15, follow_redirects=True) as client:
|
| 583 |
-
for p in products:
|
| 584 |
-
if not p.image_url or p.image_path:
|
| 585 |
-
continue
|
| 586 |
-
try:
|
| 587 |
-
h = hashlib.md5(p.url.encode()).hexdigest()[:12]
|
| 588 |
-
path = self.cache_dir / f"{h}.jpg"
|
| 589 |
-
if path.exists():
|
| 590 |
-
p.image_path = path
|
| 591 |
-
continue
|
| 592 |
-
resp = client.get(p.image_url)
|
| 593 |
-
if resp.status_code == 200 and len(resp.content) > 1000:
|
| 594 |
-
path.write_bytes(resp.content)
|
| 595 |
-
p.image_path = path
|
| 596 |
-
except Exception:
|
| 597 |
-
continue
|
| 598 |
-
return products
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
class GenericScraper:
|
| 602 |
-
"""Generic store scraper — works with any e-commerce site by extracting
|
| 603 |
-
all product-like links (links with images) and parsing text."""
|
| 604 |
-
|
| 605 |
-
def __init__(self, store_name: str, base_url: str, cache_dir: Path | None = None,
|
| 606 |
-
cookie_selectors: list[str] | None = None,
|
| 607 |
-
product_link_pattern: str | None = None):
|
| 608 |
-
self.store_name = store_name
|
| 609 |
-
self.base_url = base_url.rstrip("/")
|
| 610 |
-
slug = store_name.lower().replace(" ", "-")
|
| 611 |
-
self.cache_dir = Path(cache_dir or Path.home() / ".taste" / f"products-{slug}")
|
| 612 |
-
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
| 613 |
-
self.cookie_selectors = cookie_selectors or [
|
| 614 |
-
"button#onetrust-accept-btn-handler",
|
| 615 |
-
'button:has-text("Godta")',
|
| 616 |
-
'button:has-text("Accept")',
|
| 617 |
-
'button:has-text("Aksepter")',
|
| 618 |
-
'button:has-text("OK")',
|
| 619 |
-
'[class*="accept"]',
|
| 620 |
-
]
|
| 621 |
-
self.product_link_pattern = product_link_pattern
|
| 622 |
-
|
| 623 |
-
def _accept_cookies(self, page):
|
| 624 |
-
for sel in self.cookie_selectors:
|
| 625 |
-
try:
|
| 626 |
-
page.click(sel, timeout=2000)
|
| 627 |
-
return
|
| 628 |
-
except Exception:
|
| 629 |
-
continue
|
| 630 |
-
|
| 631 |
-
def crawl_category(
|
| 632 |
-
self, category_url: str, max_products: int = 5000, batch_size: int = 50,
|
| 633 |
-
) -> Generator[list[Product], None, None]:
|
| 634 |
-
from playwright.sync_api import sync_playwright
|
| 635 |
-
|
| 636 |
-
url = category_url if category_url.startswith("http") else f"{self.base_url}{category_url}"
|
| 637 |
-
seen_hrefs: set[str] = set()
|
| 638 |
-
total_yielded = 0
|
| 639 |
-
domain = self.base_url.split("//")[-1]
|
| 640 |
-
|
| 641 |
-
# Build JS to extract products — generic: any link with an image
|
| 642 |
-
link_filter = f'a.href.includes("{domain}")' if not self.product_link_pattern else f'a.href.match(/{self.product_link_pattern}/)'
|
| 643 |
-
|
| 644 |
-
extract_js = """(domain, linkPattern) => {
|
| 645 |
-
const links = Array.from(document.querySelectorAll('a[href]'));
|
| 646 |
-
const prods = links.filter(a => {
|
| 647 |
-
const img = a.querySelector('img');
|
| 648 |
-
if (!img) return false;
|
| 649 |
-
const href = a.href;
|
| 650 |
-
// Must be on same domain and look like a product (not nav/category)
|
| 651 |
-
if (!href.includes(domain)) return false;
|
| 652 |
-
// Heuristic: product URLs tend to be longer and have specific patterns
|
| 653 |
-
const path = new URL(href).pathname;
|
| 654 |
-
if (path.split('/').length < 3 && !path.match(/[-_].*[-_]/)) return false;
|
| 655 |
-
// Exclude obvious non-products
|
| 656 |
-
if (path.includes('/search') || path.includes('/category') || path === '/') return false;
|
| 657 |
-
return true;
|
| 658 |
-
});
|
| 659 |
-
// Deduplicate by href
|
| 660 |
-
const seen = new Set();
|
| 661 |
-
return prods.filter(a => {
|
| 662 |
-
if (seen.has(a.href)) return false;
|
| 663 |
-
seen.add(a.href);
|
| 664 |
-
return true;
|
| 665 |
-
}).map(a => {
|
| 666 |
-
const img = a.querySelector('img');
|
| 667 |
-
const texts = a.innerText.split('\\n').map(t => t.trim()).filter(Boolean);
|
| 668 |
-
return {
|
| 669 |
-
href: a.href,
|
| 670 |
-
img: img ? (img.src || img.dataset.src || '') : '',
|
| 671 |
-
texts: texts,
|
| 672 |
-
};
|
| 673 |
-
});
|
| 674 |
-
}"""
|
| 675 |
-
|
| 676 |
-
with sync_playwright() as p:
|
| 677 |
-
browser = p.chromium.launch(headless=False, channel="chrome")
|
| 678 |
-
ctx = browser.new_context(locale="nb-NO", viewport={"width": 1440, "height": 900})
|
| 679 |
-
page = ctx.new_page()
|
| 680 |
-
page.goto(url, wait_until="networkidle", timeout=30000)
|
| 681 |
-
self._accept_cookies(page)
|
| 682 |
-
page.wait_for_timeout(2000)
|
| 683 |
-
|
| 684 |
-
stale_rounds = 0
|
| 685 |
-
|
| 686 |
-
while total_yielded < max_products:
|
| 687 |
-
for _ in range(5):
|
| 688 |
-
page.evaluate("window.scrollBy(0, window.innerHeight * 2)")
|
| 689 |
-
page.wait_for_timeout(400)
|
| 690 |
-
page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
|
| 691 |
-
page.wait_for_timeout(800)
|
| 692 |
-
|
| 693 |
-
raw = page.evaluate(extract_js, domain, self.product_link_pattern or "")
|
| 694 |
-
|
| 695 |
-
new_products = []
|
| 696 |
-
for item in raw:
|
| 697 |
-
href = item["href"]
|
| 698 |
-
if href in seen_hrefs:
|
| 699 |
-
continue
|
| 700 |
-
seen_hrefs.add(href)
|
| 701 |
-
|
| 702 |
-
texts = item.get("texts", [])
|
| 703 |
-
# Filter common UI noise
|
| 704 |
-
clean = [t for t in texts if len(t) > 1 and not t.startswith("Spar")
|
| 705 |
-
and t.lower() not in ZALANDO_NOISE]
|
| 706 |
-
brand = clean[0] if clean else ""
|
| 707 |
-
name = clean[1] if len(clean) > 1 else ""
|
| 708 |
-
|
| 709 |
-
full_text_lower = " ".join(texts).lower()
|
| 710 |
-
if any(db in full_text_lower for db in DISLIKED_BRANDS):
|
| 711 |
-
continue
|
| 712 |
-
|
| 713 |
-
price_text, price_nok = "", 0.0
|
| 714 |
-
for t in texts:
|
| 715 |
-
m = re.search(r"([\d\s]+[,.]?\d*)\s*(?:kr|NOK)", t, re.IGNORECASE)
|
| 716 |
-
if m:
|
| 717 |
-
price_text = t
|
| 718 |
-
try:
|
| 719 |
-
price_nok = float(
|
| 720 |
-
m.group(1).replace("\xa0", "").replace(" ", "").replace(",", ".")
|
| 721 |
-
)
|
| 722 |
-
except ValueError:
|
| 723 |
-
pass
|
| 724 |
-
break
|
| 725 |
-
|
| 726 |
-
new_products.append(Product(
|
| 727 |
-
url=href, image_url=item["img"],
|
| 728 |
-
brand=brand, name=name,
|
| 729 |
-
price_text=price_text, price_nok=price_nok,
|
| 730 |
-
))
|
| 731 |
-
|
| 732 |
-
if new_products:
|
| 733 |
-
stale_rounds = 0
|
| 734 |
-
for i in range(0, len(new_products), batch_size):
|
| 735 |
-
chunk = new_products[i : i + batch_size]
|
| 736 |
-
total_yielded += len(chunk)
|
| 737 |
-
yield chunk
|
| 738 |
-
if total_yielded >= max_products:
|
| 739 |
-
break
|
| 740 |
-
else:
|
| 741 |
-
stale_rounds += 1
|
| 742 |
-
for sel in ["button:has-text('Vis flere')", "button:has-text('Load more')",
|
| 743 |
-
"button:has-text('Se flere')", "a:has-text('Neste')","a:has-text('Next')"]:
|
| 744 |
-
try:
|
| 745 |
-
page.click(sel, timeout=1000)
|
| 746 |
-
page.wait_for_timeout(2000)
|
| 747 |
-
stale_rounds = 0
|
| 748 |
-
break
|
| 749 |
-
except Exception:
|
| 750 |
-
continue
|
| 751 |
-
if stale_rounds >= 8:
|
| 752 |
-
break
|
| 753 |
-
|
| 754 |
-
browser.close()
|
| 755 |
-
|
| 756 |
-
def download_images(self, products: list[Product]) -> list[Product]:
|
| 757 |
-
with httpx.Client(timeout=15, follow_redirects=True) as client:
|
| 758 |
-
for p in products:
|
| 759 |
-
if not p.image_url or p.image_path:
|
| 760 |
-
continue
|
| 761 |
-
try:
|
| 762 |
-
h = hashlib.md5(p.url.encode()).hexdigest()[:12]
|
| 763 |
-
path = self.cache_dir / f"{h}.jpg"
|
| 764 |
-
if path.exists():
|
| 765 |
-
p.image_path = path
|
| 766 |
-
continue
|
| 767 |
-
resp = client.get(p.image_url)
|
| 768 |
-
if resp.status_code == 200 and len(resp.content) > 1000:
|
| 769 |
-
path.write_bytes(resp.content)
|
| 770 |
-
p.image_path = path
|
| 771 |
-
except Exception:
|
| 772 |
-
continue
|
| 773 |
-
return products
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
# --- Pre-configured store instances ---
|
| 777 |
-
|
| 778 |
-
STORES = {
|
| 779 |
-
"zalando": ZalandoScraper,
|
| 780 |
-
"boozt": BooztScraper,
|
| 781 |
-
"miinto": MiintoScraper,
|
| 782 |
-
"nakd": lambda: GenericScraper("NA-KD", "https://www.na-kd.com"),
|
| 783 |
-
"arket": lambda: GenericScraper("ARKET", "https://www.arket.com"),
|
| 784 |
-
"stories": lambda: GenericScraper("Other Stories", "https://www.stories.com"),
|
| 785 |
-
"cos": lambda: GenericScraper("COS", "https://www.cos.com"),
|
| 786 |
-
"wakakuu": lambda: GenericScraper("Wakakuu", "https://www.wakakuu.com"),
|
| 787 |
-
"massimodutti": lambda: GenericScraper("Massimo Dutti", "https://www.massimodutti.com"),
|
| 788 |
-
"ellos": lambda: GenericScraper("Ellos", "https://www.ellos.no"),
|
| 789 |
-
"careofcarl": lambda: GenericScraper("Care of Carl", "https://www.careofcarl.no"),
|
| 790 |
-
"aplace": lambda: GenericScraper("Aplace", "https://www.aplace.com"),
|
| 791 |
-
}
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
def has_synthetic(fabric_text: str) -> bool:
|
| 795 |
-
"""Check if fabric contains synthetic materials. Informational only — no filtering."""
|
| 796 |
-
synthetics = ["polyester", "nylon", "akryl", "acrylic", "polyamid", "polyamide"]
|
| 797 |
-
low = fabric_text.lower()
|
| 798 |
-
return any(s in low for s in synthetics)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
store.py
DELETED
|
@@ -1,150 +0,0 @@
|
|
| 1 |
-
"""SQLite-backed product store — crash-safe, queryable, deduped."""
|
| 2 |
-
|
| 3 |
-
import sqlite3
|
| 4 |
-
import json
|
| 5 |
-
from pathlib import Path
|
| 6 |
-
from contextlib import contextmanager
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
DB_PATH = Path.home() / ".taste" / "taste.db"
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def get_db(db_path: Path = DB_PATH) -> sqlite3.Connection:
|
| 13 |
-
db_path.parent.mkdir(parents=True, exist_ok=True)
|
| 14 |
-
conn = sqlite3.connect(str(db_path))
|
| 15 |
-
conn.row_factory = sqlite3.Row
|
| 16 |
-
conn.execute("PRAGMA journal_mode=WAL")
|
| 17 |
-
conn.execute("PRAGMA synchronous=NORMAL")
|
| 18 |
-
conn.execute("""
|
| 19 |
-
CREATE TABLE IF NOT EXISTS products (
|
| 20 |
-
url TEXT PRIMARY KEY,
|
| 21 |
-
image_url TEXT,
|
| 22 |
-
image_path TEXT,
|
| 23 |
-
brand TEXT DEFAULT '',
|
| 24 |
-
name TEXT DEFAULT '',
|
| 25 |
-
price_text TEXT DEFAULT '',
|
| 26 |
-
price_nok REAL DEFAULT 0,
|
| 27 |
-
store TEXT DEFAULT '',
|
| 28 |
-
score REAL DEFAULT 0,
|
| 29 |
-
fabric TEXT DEFAULT '',
|
| 30 |
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 31 |
-
)
|
| 32 |
-
""")
|
| 33 |
-
conn.execute("""
|
| 34 |
-
CREATE INDEX IF NOT EXISTS idx_store ON products(store)
|
| 35 |
-
""")
|
| 36 |
-
conn.execute("""
|
| 37 |
-
CREATE INDEX IF NOT EXISTS idx_score ON products(score DESC)
|
| 38 |
-
""")
|
| 39 |
-
conn.commit()
|
| 40 |
-
return conn
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def upsert_product(conn: sqlite3.Connection, product: dict):
|
| 44 |
-
"""Insert or update a product. Crash-safe — committed immediately."""
|
| 45 |
-
conn.execute("""
|
| 46 |
-
INSERT INTO products (url, image_url, image_path, brand, name, price_text, price_nok, store, score, fabric)
|
| 47 |
-
VALUES (:url, :image_url, :image_path, :brand, :name, :price_text, :price_nok, :store, :score, :fabric)
|
| 48 |
-
ON CONFLICT(url) DO UPDATE SET
|
| 49 |
-
image_path = COALESCE(excluded.image_path, products.image_path),
|
| 50 |
-
score = CASE WHEN excluded.score > products.score THEN excluded.score ELSE products.score END,
|
| 51 |
-
brand = CASE WHEN excluded.brand != '' THEN excluded.brand ELSE products.brand END,
|
| 52 |
-
name = CASE WHEN excluded.name != '' THEN excluded.name ELSE products.name END,
|
| 53 |
-
price_text = CASE WHEN excluded.price_text != '' THEN excluded.price_text ELSE products.price_text END,
|
| 54 |
-
price_nok = CASE WHEN excluded.price_nok > 0 THEN excluded.price_nok ELSE products.price_nok END,
|
| 55 |
-
fabric = CASE WHEN excluded.fabric != '' THEN excluded.fabric ELSE products.fabric END
|
| 56 |
-
""", {
|
| 57 |
-
"url": product.get("url", ""),
|
| 58 |
-
"image_url": product.get("image_url", ""),
|
| 59 |
-
"image_path": product.get("image_path", ""),
|
| 60 |
-
"brand": product.get("brand", ""),
|
| 61 |
-
"name": product.get("name", ""),
|
| 62 |
-
"price_text": product.get("price_text", ""),
|
| 63 |
-
"price_nok": product.get("price_nok", 0),
|
| 64 |
-
"store": product.get("store", ""),
|
| 65 |
-
"score": product.get("score", 0),
|
| 66 |
-
"fabric": product.get("fabric", ""),
|
| 67 |
-
})
|
| 68 |
-
conn.commit()
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
def upsert_batch(conn: sqlite3.Connection, products: list[dict]):
|
| 72 |
-
"""Insert/update multiple products in one transaction."""
|
| 73 |
-
for p in products:
|
| 74 |
-
conn.execute("""
|
| 75 |
-
INSERT INTO products (url, image_url, image_path, brand, name, price_text, price_nok, store, score, fabric)
|
| 76 |
-
VALUES (:url, :image_url, :image_path, :brand, :name, :price_text, :price_nok, :store, :score, :fabric)
|
| 77 |
-
ON CONFLICT(url) DO UPDATE SET
|
| 78 |
-
image_path = COALESCE(excluded.image_path, products.image_path),
|
| 79 |
-
score = CASE WHEN excluded.score > products.score THEN excluded.score ELSE products.score END,
|
| 80 |
-
brand = CASE WHEN excluded.brand != '' THEN excluded.brand ELSE products.brand END,
|
| 81 |
-
name = CASE WHEN excluded.name != '' THEN excluded.name ELSE products.name END,
|
| 82 |
-
price_text = CASE WHEN excluded.price_text != '' THEN excluded.price_text ELSE products.price_text END,
|
| 83 |
-
price_nok = CASE WHEN excluded.price_nok > 0 THEN excluded.price_nok ELSE products.price_nok END,
|
| 84 |
-
fabric = CASE WHEN excluded.fabric != '' THEN excluded.fabric ELSE products.fabric END
|
| 85 |
-
""", {
|
| 86 |
-
"url": p.get("url", ""),
|
| 87 |
-
"image_url": p.get("image_url", ""),
|
| 88 |
-
"image_path": p.get("image_path", ""),
|
| 89 |
-
"brand": p.get("brand", ""),
|
| 90 |
-
"name": p.get("name", ""),
|
| 91 |
-
"price_text": p.get("price_text", ""),
|
| 92 |
-
"price_nok": p.get("price_nok", 0),
|
| 93 |
-
"store": p.get("store", ""),
|
| 94 |
-
"score": p.get("score", 0),
|
| 95 |
-
"fabric": p.get("fabric", ""),
|
| 96 |
-
})
|
| 97 |
-
conn.commit()
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
def get_all_products(conn: sqlite3.Connection, store: str | None = None,
|
| 101 |
-
min_score: float = 0, limit: int = 0) -> list[dict]:
|
| 102 |
-
"""Query products. Returns list of dicts."""
|
| 103 |
-
sql = "SELECT * FROM products WHERE score >= ?"
|
| 104 |
-
params: list = [min_score]
|
| 105 |
-
if store:
|
| 106 |
-
sql += " AND store = ?"
|
| 107 |
-
params.append(store)
|
| 108 |
-
sql += " ORDER BY score DESC"
|
| 109 |
-
if limit:
|
| 110 |
-
sql += " LIMIT ?"
|
| 111 |
-
params.append(limit)
|
| 112 |
-
rows = conn.execute(sql, params).fetchall()
|
| 113 |
-
return [dict(r) for r in rows]
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
def get_stats(conn: sqlite3.Connection) -> dict:
|
| 117 |
-
"""Get product counts per store."""
|
| 118 |
-
rows = conn.execute("""
|
| 119 |
-
SELECT store, COUNT(*) as count,
|
| 120 |
-
MAX(score) as top_score,
|
| 121 |
-
AVG(score) as avg_score
|
| 122 |
-
FROM products
|
| 123 |
-
GROUP BY store
|
| 124 |
-
ORDER BY count DESC
|
| 125 |
-
""").fetchall()
|
| 126 |
-
total = conn.execute("SELECT COUNT(*) FROM products").fetchone()[0]
|
| 127 |
-
return {
|
| 128 |
-
"total": total,
|
| 129 |
-
"stores": {r["store"]: {"count": r["count"], "top": r["top_score"], "avg": round(r["avg_score"], 3)} for r in rows},
|
| 130 |
-
}
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
def import_from_catalog_jsonl(conn: sqlite3.Connection, jsonl_path: Path):
|
| 134 |
-
"""Import existing catalog.jsonl into SQLite."""
|
| 135 |
-
if not jsonl_path.exists():
|
| 136 |
-
return 0
|
| 137 |
-
count = 0
|
| 138 |
-
for line in jsonl_path.read_text().splitlines():
|
| 139 |
-
if not line.strip():
|
| 140 |
-
continue
|
| 141 |
-
data = json.loads(line)
|
| 142 |
-
store = "Zalando"
|
| 143 |
-
if "boozt.com" in data.get("url", ""):
|
| 144 |
-
store = "Boozt"
|
| 145 |
-
elif "miinto.no" in data.get("url", ""):
|
| 146 |
-
store = "Miinto"
|
| 147 |
-
data["store"] = store
|
| 148 |
-
upsert_product(conn, data)
|
| 149 |
-
count += 1
|
| 150 |
-
return count
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
taste/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""taste — personal visual preference engine."""
|
| 2 |
+
|
| 3 |
+
from taste.models import Product
|
| 4 |
+
from taste.engine import TasteEngine
|
| 5 |
+
from taste.store import ProductStore
|
| 6 |
+
from taste.config import load_config, load_profile
|
| 7 |
+
|
| 8 |
+
__all__ = ["Product", "TasteEngine", "ProductStore", "load_config", "load_profile"]
|
taste/config.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration loading and profile management."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from dataclasses import dataclass, field
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class StoreConfig:
|
| 13 |
+
name: str
|
| 14 |
+
enabled: bool = True
|
| 15 |
+
type: str = "api" # "api" or "browser"
|
| 16 |
+
base_url: str = ""
|
| 17 |
+
categories: list[str] = field(default_factory=list)
|
| 18 |
+
max_products: int = 5000
|
| 19 |
+
extra: dict[str, Any] = field(default_factory=dict)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class Config:
|
| 24 |
+
data_dir: Path = field(default_factory=lambda: Path.home() / ".taste")
|
| 25 |
+
stores: dict[str, StoreConfig] = field(default_factory=dict)
|
| 26 |
+
batch_size: int = 50
|
| 27 |
+
image_download_concurrency: int = 20
|
| 28 |
+
|
| 29 |
+
def store_cache_dir(self, store_name: str) -> Path:
|
| 30 |
+
d = self.data_dir / f"products-{store_name}"
|
| 31 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 32 |
+
return d
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class UserProfile:
|
| 37 |
+
name: str = "default"
|
| 38 |
+
reference_dirs: list[Path] = field(default_factory=list)
|
| 39 |
+
liked_urls: list[str] = field(default_factory=list)
|
| 40 |
+
disliked_brands: set[str] = field(default_factory=set)
|
| 41 |
+
filters: dict[str, Any] = field(default_factory=dict)
|
| 42 |
+
style_text_queries: list[str] = field(default_factory=list)
|
| 43 |
+
|
| 44 |
+
@property
|
| 45 |
+
def profile_dir(self) -> Path:
|
| 46 |
+
"""Not used for path resolution — use config.data_dir instead."""
|
| 47 |
+
return Path()
|
| 48 |
+
|
| 49 |
+
def ratings_path(self, config: Config) -> Path:
|
| 50 |
+
return config.data_dir / "ratings.json"
|
| 51 |
+
|
| 52 |
+
def db_path(self, config: Config) -> Path:
|
| 53 |
+
return config.data_dir / "taste.db"
|
| 54 |
+
|
| 55 |
+
def embeddings_dir(self, config: Config) -> Path:
|
| 56 |
+
d = config.data_dir / "embeddings"
|
| 57 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 58 |
+
return d
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _resolve_path(p: str | Path) -> Path:
|
| 62 |
+
return Path(p).expanduser().resolve()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def load_config(path: Path | None = None) -> Config:
|
| 66 |
+
"""Load config from YAML file, or return defaults."""
|
| 67 |
+
if path is None:
|
| 68 |
+
path = Path.home() / ".taste" / "config.yaml"
|
| 69 |
+
|
| 70 |
+
if not path.exists():
|
| 71 |
+
return _default_config()
|
| 72 |
+
|
| 73 |
+
try:
|
| 74 |
+
import yaml
|
| 75 |
+
raw = yaml.safe_load(path.read_text())
|
| 76 |
+
except ImportError:
|
| 77 |
+
# No pyyaml — try JSON fallback
|
| 78 |
+
raw = json.loads(path.read_text())
|
| 79 |
+
|
| 80 |
+
if not raw:
|
| 81 |
+
return _default_config()
|
| 82 |
+
|
| 83 |
+
data_dir = _resolve_path(raw.get("data_dir", "~/.taste"))
|
| 84 |
+
|
| 85 |
+
stores = {}
|
| 86 |
+
for name, sconf in raw.get("stores", {}).items():
|
| 87 |
+
stores[name] = StoreConfig(
|
| 88 |
+
name=name,
|
| 89 |
+
enabled=sconf.get("enabled", True),
|
| 90 |
+
type=sconf.get("type", "api"),
|
| 91 |
+
base_url=sconf.get("base_url", ""),
|
| 92 |
+
categories=sconf.get("categories", []),
|
| 93 |
+
max_products=sconf.get("max_products", 5000),
|
| 94 |
+
extra={k: v for k, v in sconf.items()
|
| 95 |
+
if k not in ("enabled", "type", "base_url", "categories", "max_products")},
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
return Config(
|
| 99 |
+
data_dir=data_dir,
|
| 100 |
+
stores=stores,
|
| 101 |
+
batch_size=raw.get("batch_size", 50),
|
| 102 |
+
image_download_concurrency=raw.get("image_download_concurrency", 20),
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def load_profile(name: str = "default", config: Config | None = None) -> UserProfile:
|
| 107 |
+
"""Load a user profile from YAML, or return defaults."""
|
| 108 |
+
if config is None:
|
| 109 |
+
config = _default_config()
|
| 110 |
+
|
| 111 |
+
path = config.data_dir / "profiles" / f"{name}.yaml"
|
| 112 |
+
if not path.exists():
|
| 113 |
+
# Try JSON
|
| 114 |
+
path = config.data_dir / "profiles" / f"{name}.json"
|
| 115 |
+
|
| 116 |
+
if not path.exists():
|
| 117 |
+
return _default_profile()
|
| 118 |
+
|
| 119 |
+
try:
|
| 120 |
+
import yaml
|
| 121 |
+
raw = yaml.safe_load(path.read_text())
|
| 122 |
+
except ImportError:
|
| 123 |
+
raw = json.loads(path.read_text())
|
| 124 |
+
|
| 125 |
+
if not raw:
|
| 126 |
+
return _default_profile()
|
| 127 |
+
|
| 128 |
+
return UserProfile(
|
| 129 |
+
name=raw.get("name", name),
|
| 130 |
+
reference_dirs=[_resolve_path(p) for p in raw.get("reference_dirs", [])],
|
| 131 |
+
liked_urls=raw.get("liked_urls", []),
|
| 132 |
+
disliked_brands=set(b.lower() for b in raw.get("disliked_brands", [])),
|
| 133 |
+
filters=raw.get("filters", {}),
|
| 134 |
+
style_text_queries=raw.get("style_text_queries", []),
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _default_config() -> Config:
|
| 139 |
+
"""Sensible defaults matching the current Norwegian bag stores."""
|
| 140 |
+
return Config(
|
| 141 |
+
data_dir=Path.home() / ".taste",
|
| 142 |
+
stores={
|
| 143 |
+
"wakakuu": StoreConfig(
|
| 144 |
+
name="wakakuu", type="api",
|
| 145 |
+
base_url="https://www.wakakuu.com",
|
| 146 |
+
categories=["categories.lvl0:Väskor"],
|
| 147 |
+
max_products=3000,
|
| 148 |
+
extra={
|
| 149 |
+
"algolia_app_id": "0LM8YN9I0K",
|
| 150 |
+
"algolia_api_key": "00ef309f4d1543ffdaa1d85c33111700",
|
| 151 |
+
"algolia_index": "prod_products_sv",
|
| 152 |
+
},
|
| 153 |
+
),
|
| 154 |
+
"boozt": StoreConfig(
|
| 155 |
+
name="boozt", type="api",
|
| 156 |
+
base_url="https://www.boozt.com",
|
| 157 |
+
categories=[
|
| 158 |
+
"/no/no/kvinner/vesker",
|
| 159 |
+
"/no/no/kvinner/vesker/skuldervesker",
|
| 160 |
+
"/no/no/kvinner/vesker/haandvesker",
|
| 161 |
+
"/no/no/kvinner/vesker/crossbody-vesker",
|
| 162 |
+
],
|
| 163 |
+
max_products=5000,
|
| 164 |
+
extra={"material_filter": "ekte-skinn"},
|
| 165 |
+
),
|
| 166 |
+
"miinto": StoreConfig(
|
| 167 |
+
name="miinto", type="api",
|
| 168 |
+
base_url="https://www.miinto.no",
|
| 169 |
+
categories=[
|
| 170 |
+
"/dame-skuldervesker",
|
| 171 |
+
"/dame-handvesker",
|
| 172 |
+
"/dame-clutch-vesker",
|
| 173 |
+
],
|
| 174 |
+
max_products=5000,
|
| 175 |
+
),
|
| 176 |
+
"nakd": StoreConfig(
|
| 177 |
+
name="nakd", type="api",
|
| 178 |
+
base_url="https://www.na-kd.com",
|
| 179 |
+
categories=[
|
| 180 |
+
"/no/category/vesker",
|
| 181 |
+
"/no/category/vesker/skuldervesker",
|
| 182 |
+
],
|
| 183 |
+
max_products=2000,
|
| 184 |
+
),
|
| 185 |
+
},
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _default_profile() -> UserProfile:
|
| 190 |
+
return UserProfile(
|
| 191 |
+
name="default",
|
| 192 |
+
disliked_brands={
|
| 193 |
+
"vagabond", "polo ralph lauren", "tommy hilfiger",
|
| 194 |
+
"gant", "ralph lauren", "tommy jeans",
|
| 195 |
+
},
|
| 196 |
+
)
|
engine.py → taste/engine.py
RENAMED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Taste Engine — learn
|
| 2 |
|
| 3 |
import hashlib
|
| 4 |
import json
|
|
@@ -18,21 +18,27 @@ def find_images(folder: Path) -> list[Path]:
|
|
| 18 |
|
| 19 |
|
| 20 |
class TasteEngine:
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
self.data_dir.mkdir(parents=True, exist_ok=True)
|
| 24 |
self.ratings_path = self.data_dir / "ratings.json"
|
| 25 |
self.cache_dir = self.data_dir / "embeddings"
|
| 26 |
self.cache_dir.mkdir(exist_ok=True)
|
| 27 |
self._model = None
|
| 28 |
self._preprocess = None
|
|
|
|
| 29 |
self._device = None
|
| 30 |
|
| 31 |
@property
|
| 32 |
def device(self):
|
| 33 |
if self._device is None:
|
| 34 |
import torch
|
| 35 |
-
|
| 36 |
if torch.cuda.is_available():
|
| 37 |
self._device = "cuda"
|
| 38 |
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
|
|
@@ -53,15 +59,17 @@ class TasteEngine:
|
|
| 53 |
self._model = model.to(self.device)
|
| 54 |
self._model.requires_grad_(False)
|
| 55 |
self._preprocess = preprocess
|
|
|
|
| 56 |
|
| 57 |
def _cache_key(self, path: Path) -> str:
|
| 58 |
stat = path.stat()
|
| 59 |
-
raw = f"{path.resolve()}:{stat.st_size}:{stat.st_mtime_ns}"
|
| 60 |
return hashlib.blake2b(raw.encode(), digest_size=16).hexdigest()
|
| 61 |
|
|
|
|
|
|
|
| 62 |
def encode(self, path: Path) -> np.ndarray:
|
| 63 |
import torch
|
| 64 |
-
|
| 65 |
path = Path(path)
|
| 66 |
key = self._cache_key(path)
|
| 67 |
cache_path = self.cache_dir / f"{key}.npy"
|
|
@@ -79,11 +87,19 @@ class TasteEngine:
|
|
| 79 |
np.save(cache_path, result)
|
| 80 |
return result
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
def encode_batch(
|
| 83 |
self, paths: list[Path], batch_size: int = 16, progress_cb=None
|
| 84 |
) -> dict[str, np.ndarray]:
|
| 85 |
import torch
|
| 86 |
-
|
| 87 |
results = {}
|
| 88 |
to_encode = []
|
| 89 |
|
|
@@ -148,13 +164,30 @@ class TasteEngine:
|
|
| 148 |
ratings.pop(str(Path(p).resolve()), None)
|
| 149 |
self.ratings_path.write_text(json.dumps(ratings, indent=2))
|
| 150 |
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
def build_taste_vector(self) -> list[np.ndarray] | None:
|
| 154 |
"""Build multi-centroid taste model. Returns list of centroid vectors."""
|
| 155 |
ratings = self.load_ratings()
|
| 156 |
liked = []
|
| 157 |
-
|
| 158 |
for path_str, rating in ratings.items():
|
| 159 |
p = Path(path_str)
|
| 160 |
if not p.exists() or rating != 1:
|
|
@@ -163,12 +196,42 @@ class TasteEngine:
|
|
| 163 |
|
| 164 |
if not liked:
|
| 165 |
return None
|
|
|
|
| 166 |
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
def _cluster_centroids(self, embeddings: np.ndarray) -> list[np.ndarray]:
|
| 171 |
-
"""Cluster embeddings and return one centroid per cluster."""
|
| 172 |
n = len(embeddings)
|
| 173 |
if n < 5:
|
| 174 |
c = np.mean(embeddings, axis=0)
|
|
@@ -189,31 +252,31 @@ class TasteEngine:
|
|
| 189 |
mask = labels == label
|
| 190 |
if label == -1:
|
| 191 |
for emb in embeddings[mask]:
|
| 192 |
-
|
| 193 |
-
centroids.append(c)
|
| 194 |
else:
|
| 195 |
c = np.mean(embeddings[mask], axis=0)
|
| 196 |
-
c
|
| 197 |
-
centroids.append(c)
|
| 198 |
|
| 199 |
if not centroids:
|
| 200 |
c = np.mean(embeddings, axis=0)
|
| 201 |
-
|
| 202 |
-
centroids = [c]
|
| 203 |
-
|
| 204 |
return centroids
|
| 205 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
def score(self, path: Path, centroids: list[np.ndarray]) -> float:
|
| 207 |
-
"""Score image using MaxSim across centroids."""
|
| 208 |
emb = self.encode(path)
|
| 209 |
return max(float(np.dot(emb, c)) for c in centroids)
|
| 210 |
|
| 211 |
def score_product_images(
|
| 212 |
self, image_paths: list[Path], centroids: list[np.ndarray]
|
| 213 |
) -> list[tuple[Path, float]]:
|
| 214 |
-
"""Score product images with MaxSim. Returns sorted (path, score)."""
|
| 215 |
embeddings = self.encode_batch(image_paths)
|
| 216 |
-
# Pre-stack centroids for vectorized scoring
|
| 217 |
c_arr = np.array(centroids)
|
| 218 |
scores = []
|
| 219 |
for p in image_paths:
|
|
@@ -224,27 +287,3 @@ class TasteEngine:
|
|
| 224 |
scores.append((p, s))
|
| 225 |
scores.sort(key=lambda x: x[1], reverse=True)
|
| 226 |
return scores
|
| 227 |
-
|
| 228 |
-
def seed_from_references(self, folder: Path):
|
| 229 |
-
"""Seed taste from reference images (all rated as liked)."""
|
| 230 |
-
ratings = self.load_ratings()
|
| 231 |
-
images = find_images(folder)
|
| 232 |
-
seeded = 0
|
| 233 |
-
for img in images:
|
| 234 |
-
key = str(img.resolve())
|
| 235 |
-
if key not in ratings:
|
| 236 |
-
self.save_rating(img, 1)
|
| 237 |
-
seeded += 1
|
| 238 |
-
return seeded
|
| 239 |
-
|
| 240 |
-
def stats(self) -> dict:
|
| 241 |
-
ratings = self.load_ratings()
|
| 242 |
-
liked = sum(1 for v in ratings.values() if v == 1)
|
| 243 |
-
disliked = sum(1 for v in ratings.values() if v == -1)
|
| 244 |
-
skipped = sum(1 for v in ratings.values() if v == 0)
|
| 245 |
-
return {
|
| 246 |
-
"total": len(ratings),
|
| 247 |
-
"liked": liked,
|
| 248 |
-
"disliked": disliked,
|
| 249 |
-
"skipped": skipped,
|
| 250 |
-
}
|
|
|
|
| 1 |
+
"""Taste Engine — learn visual aesthetic from reference images using FashionSigLIP."""
|
| 2 |
|
| 3 |
import hashlib
|
| 4 |
import json
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
class TasteEngine:
|
| 21 |
+
"""FashionSigLIP-based taste engine with multi-centroid HDBSCAN + MaxSim scoring.
|
| 22 |
+
|
| 23 |
+
All paths are explicit — no defaults. The caller (CLI/pipeline) resolves
|
| 24 |
+
them from config/profile.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, data_dir: Path):
|
| 28 |
+
self.data_dir = Path(data_dir)
|
| 29 |
self.data_dir.mkdir(parents=True, exist_ok=True)
|
| 30 |
self.ratings_path = self.data_dir / "ratings.json"
|
| 31 |
self.cache_dir = self.data_dir / "embeddings"
|
| 32 |
self.cache_dir.mkdir(exist_ok=True)
|
| 33 |
self._model = None
|
| 34 |
self._preprocess = None
|
| 35 |
+
self._tokenizer = None
|
| 36 |
self._device = None
|
| 37 |
|
| 38 |
@property
|
| 39 |
def device(self):
|
| 40 |
if self._device is None:
|
| 41 |
import torch
|
|
|
|
| 42 |
if torch.cuda.is_available():
|
| 43 |
self._device = "cuda"
|
| 44 |
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
|
|
|
|
| 59 |
self._model = model.to(self.device)
|
| 60 |
self._model.requires_grad_(False)
|
| 61 |
self._preprocess = preprocess
|
| 62 |
+
self._tokenizer = open_clip.get_tokenizer("hf-hub:Marqo/marqo-fashionSigLIP")
|
| 63 |
|
| 64 |
def _cache_key(self, path: Path) -> str:
|
| 65 |
stat = path.stat()
|
| 66 |
+
raw = f"fashionsiglip:{path.resolve()}:{stat.st_size}:{stat.st_mtime_ns}"
|
| 67 |
return hashlib.blake2b(raw.encode(), digest_size=16).hexdigest()
|
| 68 |
|
| 69 |
+
# --- Encoding ---
|
| 70 |
+
|
| 71 |
def encode(self, path: Path) -> np.ndarray:
|
| 72 |
import torch
|
|
|
|
| 73 |
path = Path(path)
|
| 74 |
key = self._cache_key(path)
|
| 75 |
cache_path = self.cache_dir / f"{key}.npy"
|
|
|
|
| 87 |
np.save(cache_path, result)
|
| 88 |
return result
|
| 89 |
|
| 90 |
+
def encode_text(self, text: str) -> np.ndarray:
|
| 91 |
+
import torch
|
| 92 |
+
self._load_model()
|
| 93 |
+
tokens = self._tokenizer([text]).to(self.device)
|
| 94 |
+
with torch.no_grad():
|
| 95 |
+
emb = self._model.encode_text(tokens)
|
| 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]:
|
| 102 |
import torch
|
|
|
|
| 103 |
results = {}
|
| 104 |
to_encode = []
|
| 105 |
|
|
|
|
| 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
|
| 177 |
+
|
| 178 |
+
def stats(self) -> dict:
|
| 179 |
+
ratings = self.load_ratings()
|
| 180 |
+
liked = sum(1 for v in ratings.values() if v == 1)
|
| 181 |
+
disliked = sum(1 for v in ratings.values() if v == -1)
|
| 182 |
+
skipped = sum(1 for v in ratings.values() if v == 0)
|
| 183 |
+
return {"total": len(ratings), "liked": liked, "disliked": disliked, "skipped": skipped}
|
| 184 |
+
|
| 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():
|
| 192 |
p = Path(path_str)
|
| 193 |
if not p.exists() or rating != 1:
|
|
|
|
| 196 |
|
| 197 |
if not liked:
|
| 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)
|
| 236 |
if n < 5:
|
| 237 |
c = np.mean(embeddings, axis=0)
|
|
|
|
| 252 |
mask = labels == label
|
| 253 |
if label == -1:
|
| 254 |
for emb in embeddings[mask]:
|
| 255 |
+
centroids.append(emb / np.linalg.norm(emb))
|
|
|
|
| 256 |
else:
|
| 257 |
c = np.mean(embeddings[mask], axis=0)
|
| 258 |
+
centroids.append(c / np.linalg.norm(c))
|
|
|
|
| 259 |
|
| 260 |
if not centroids:
|
| 261 |
c = np.mean(embeddings, axis=0)
|
| 262 |
+
centroids = [c / np.linalg.norm(c)]
|
|
|
|
|
|
|
| 263 |
return centroids
|
| 264 |
|
| 265 |
+
def _compute_dim_weights(self, embeddings: np.ndarray) -> np.ndarray:
|
| 266 |
+
variances = np.var(embeddings, axis=0)
|
| 267 |
+
inv_var = 1.0 / (variances + 1e-8)
|
| 268 |
+
return inv_var / np.mean(inv_var)
|
| 269 |
+
|
| 270 |
+
# --- Scoring ---
|
| 271 |
+
|
| 272 |
def score(self, path: Path, centroids: list[np.ndarray]) -> float:
|
|
|
|
| 273 |
emb = self.encode(path)
|
| 274 |
return max(float(np.dot(emb, c)) for c in centroids)
|
| 275 |
|
| 276 |
def score_product_images(
|
| 277 |
self, image_paths: list[Path], centroids: list[np.ndarray]
|
| 278 |
) -> list[tuple[Path, float]]:
|
|
|
|
| 279 |
embeddings = self.encode_batch(image_paths)
|
|
|
|
| 280 |
c_arr = np.array(centroids)
|
| 281 |
scores = []
|
| 282 |
for p in image_paths:
|
|
|
|
| 287 |
scores.append((p, s))
|
| 288 |
scores.sort(key=lambda x: x[1], reverse=True)
|
| 289 |
return scores
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
taste/models.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared data models."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@dataclass
|
| 8 |
+
class Product:
|
| 9 |
+
url: str
|
| 10 |
+
image_url: str
|
| 11 |
+
image_path: Path | None = None
|
| 12 |
+
brand: str = ""
|
| 13 |
+
name: str = ""
|
| 14 |
+
price_text: str = ""
|
| 15 |
+
price_nok: float = 0.0
|
| 16 |
+
fabric: str = ""
|
| 17 |
+
score: float = 0.0
|
| 18 |
+
store: str = ""
|
| 19 |
+
|
| 20 |
+
def to_dict(self) -> dict:
|
| 21 |
+
return {
|
| 22 |
+
"url": self.url,
|
| 23 |
+
"image_url": self.image_url,
|
| 24 |
+
"image_path": str(self.image_path) if self.image_path else "",
|
| 25 |
+
"brand": self.brand,
|
| 26 |
+
"name": self.name,
|
| 27 |
+
"price_text": self.price_text,
|
| 28 |
+
"price_nok": self.price_nok,
|
| 29 |
+
"fabric": self.fabric,
|
| 30 |
+
"score": self.score,
|
| 31 |
+
"store": self.store,
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
@staticmethod
|
| 35 |
+
def from_dict(d: dict) -> "Product":
|
| 36 |
+
return Product(
|
| 37 |
+
url=d.get("url", ""),
|
| 38 |
+
image_url=d.get("image_url", ""),
|
| 39 |
+
image_path=Path(d["image_path"]) if d.get("image_path") else None,
|
| 40 |
+
brand=d.get("brand", ""),
|
| 41 |
+
name=d.get("name", ""),
|
| 42 |
+
price_text=d.get("price_text", ""),
|
| 43 |
+
price_nok=d.get("price_nok", 0.0),
|
| 44 |
+
fabric=d.get("fabric", ""),
|
| 45 |
+
score=d.get("score", 0.0),
|
| 46 |
+
store=d.get("store", ""),
|
| 47 |
+
)
|
merge_results.py → taste/output.py
RENAMED
|
@@ -1,108 +1,71 @@
|
|
| 1 |
-
"""
|
| 2 |
-
import sys
|
| 3 |
-
import re
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
|
| 6 |
-
sys.stdout.reconfigure(line_buffering=True)
|
| 7 |
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
"""Extract product data from generated HTML."""
|
| 11 |
-
text = html_path.read_text()
|
| 12 |
|
| 13 |
-
products = []
|
| 14 |
-
# Match each card block
|
| 15 |
-
for card_match in re.finditer(
|
| 16 |
-
r'<div class="card[^"]*">\s*'
|
| 17 |
-
r'<span class="rank">#(\d+)</span>\s*'
|
| 18 |
-
r'(?:<span class="store">(\w+)</span>\s*)?'
|
| 19 |
-
r'<a href="([^"]+)"[^>]*>\s*'
|
| 20 |
-
r'<img src="([^"]*)"[^>]*>\s*</a>\s*'
|
| 21 |
-
r'<div class="score"[^>]*>(\d+)%</div>\s*'
|
| 22 |
-
r'<div class="brand">([^<]*)</div>\s*'
|
| 23 |
-
r'<div class="name">([^<]*)</div>\s*'
|
| 24 |
-
r'<div class="price">([^<]*)</div>',
|
| 25 |
-
text,
|
| 26 |
-
):
|
| 27 |
-
rank, store, url, img, score, brand, name, price = card_match.groups()
|
| 28 |
-
if not store:
|
| 29 |
-
if "boozt.com" in url:
|
| 30 |
-
store = "Boozt"
|
| 31 |
-
elif "miinto.no" in url:
|
| 32 |
-
store = "Miinto"
|
| 33 |
-
else:
|
| 34 |
-
store = "Zalando"
|
| 35 |
-
products.append({
|
| 36 |
-
"url": url,
|
| 37 |
-
"img": img,
|
| 38 |
-
"score_pct": int(score),
|
| 39 |
-
"brand": brand,
|
| 40 |
-
"name": name,
|
| 41 |
-
"price": price,
|
| 42 |
-
"store": store,
|
| 43 |
-
})
|
| 44 |
-
return products
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
for p in products:
|
| 51 |
-
url = p["url"]
|
| 52 |
-
if url not in best or p["score_pct"] > best[url]["score_pct"]:
|
| 53 |
-
best[url] = p
|
| 54 |
-
return sorted(best.values(), key=lambda p: p["score_pct"], reverse=True)
|
| 55 |
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
bc = sum(1 for p in products if p["store"] == "Boozt")
|
| 61 |
-
mc = sum(1 for p in products if p["store"] == "Miinto")
|
| 62 |
-
total = len(products)
|
| 63 |
|
| 64 |
-
|
| 65 |
-
for i, p in enumerate(
|
| 66 |
-
|
| 67 |
-
if
|
| 68 |
color = "#22c55e"
|
| 69 |
-
elif
|
| 70 |
color = "#3b82f6"
|
| 71 |
else:
|
| 72 |
color = "#f59e0b"
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
| 76 |
<span class="rank">#{i+1}</span>
|
| 77 |
-
<span class="store">{
|
| 78 |
-
<a href="{p
|
| 79 |
-
<img src="{
|
| 80 |
</a>
|
| 81 |
-
<div class="score" style="background:{color}">{
|
| 82 |
-
<div class="brand">{p
|
| 83 |
-
<div class="name">{p
|
| 84 |
-
<div class="price">{p
|
| 85 |
-
<a href="{p
|
| 86 |
</div>""")
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
html = f"""<!DOCTYPE html>
|
| 89 |
<html lang="en">
|
| 90 |
<head>
|
| 91 |
<meta charset="UTF-8">
|
| 92 |
-
<title>Taste Engine —
|
| 93 |
<style>
|
| 94 |
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
|
| 95 |
body {{ font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: #0a0a0a; color: #e5e5e5; padding: 20px; }}
|
| 96 |
h1 {{ text-align: center; margin: 20px 0; font-size: 1.5em; color: #a3a3a3; }}
|
| 97 |
-
.stats {{ text-align: center; color: #737373; margin-bottom:
|
| 98 |
-
.filters {{ text-align: center; margin-bottom: 24px; display: flex; gap: 8px; justify-content: center; flex-wrap: wrap; position: sticky; top: 0; background: #0a0a0a; padding: 12px 0; z-index: 10; border-bottom: 1px solid #262626; }}
|
| 99 |
-
.filters button {{ background: #262626; color: #e5e5e5; border: 1px solid #404040; padding: 8px 20px; border-radius: 8px; cursor: pointer; font-size: 14px; transition: all 0.2s; }}
|
| 100 |
-
.filters button:hover {{ background: #333; }}
|
| 101 |
-
.filters button.active {{ background: #3b82f6; border-color: #3b82f6; color: #fff; }}
|
| 102 |
.grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 16px; max-width: 1400px; margin: 0 auto; }}
|
| 103 |
.card {{ background: #171717; border-radius: 12px; overflow: hidden; position: relative; transition: transform 0.2s; }}
|
| 104 |
.card:hover {{ transform: translateY(-4px); }}
|
| 105 |
-
.card.hidden {{ display: none; }}
|
| 106 |
.card img {{ width: 100%; aspect-ratio: 3/4; object-fit: cover; display: block; }}
|
| 107 |
.rank {{ position: absolute; top: 8px; left: 8px; background: rgba(0,0,0,0.7); color: #a3a3a3; padding: 2px 8px; border-radius: 6px; font-size: 12px; }}
|
| 108 |
.store {{ position: absolute; top: 8px; right: 8px; background: rgba(59,130,246,0.8); color: #fff; padding: 2px 8px; border-radius: 6px; font-size: 11px; font-weight: 600; }}
|
|
@@ -112,24 +75,26 @@ def generate_combined(products: list[dict], output: Path):
|
|
| 112 |
.price {{ padding: 2px 12px 4px; font-size: 13px; color: #d4d4d4; }}
|
| 113 |
.link {{ display: block; text-align: center; padding: 8px; color: #60a5fa; text-decoration: none; font-size: 13px; border-top: 1px solid #262626; }}
|
| 114 |
.link:hover {{ background: #1e1e1e; }}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
</style>
|
| 116 |
</head>
|
| 117 |
<body>
|
| 118 |
-
<h1>Taste Engine —
|
| 119 |
-
<div class="stats">{
|
| 120 |
<div class="filters">
|
| 121 |
-
|
| 122 |
-
<button onclick="filterStore(this, 'Zalando')">Zalando ({zc})</button>
|
| 123 |
-
<button onclick="filterStore(this, 'Boozt')">Boozt ({bc})</button>
|
| 124 |
-
<button onclick="filterStore(this, 'Miinto')">Miinto ({mc})</button>
|
| 125 |
</div>
|
| 126 |
<div class="grid">
|
| 127 |
-
{"".join(
|
| 128 |
</div>
|
| 129 |
<script>
|
| 130 |
-
function filterStore(
|
| 131 |
document.querySelectorAll('.filters button').forEach(b => b.classList.remove('active'));
|
| 132 |
-
|
| 133 |
document.querySelectorAll('.card').forEach(card => {{
|
| 134 |
if (store === 'all' || card.dataset.store === store) {{
|
| 135 |
card.classList.remove('hidden');
|
|
@@ -141,17 +106,20 @@ function filterStore(btn, store) {{
|
|
| 141 |
</script>
|
| 142 |
</body>
|
| 143 |
</html>"""
|
| 144 |
-
output.write_text(html)
|
| 145 |
-
print(f"Saved {total} products to {output}")
|
| 146 |
-
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
bm_products = extract_products(Path("results-boozt-miinto.html"))
|
| 151 |
-
print(f"Zalando: {len(z_products)}, Boozt+Miinto: {len(bm_products)}")
|
| 152 |
|
| 153 |
-
all_products = z_products + bm_products
|
| 154 |
-
deduped = deduplicate(all_products)
|
| 155 |
-
print(f"After dedup: {len(deduped)}")
|
| 156 |
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HTML result generation."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
from pathlib import Path
|
| 4 |
|
| 5 |
+
from taste.models import Product
|
|
|
|
|
|
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
def generate_html(products: list[Product], output_path: Path, top_n: int = 0):
|
| 9 |
+
"""Generate a dark-themed HTML file with ranked product results."""
|
| 10 |
+
if top_n <= 0:
|
| 11 |
+
top_n = len(products)
|
| 12 |
+
top = products[:top_n]
|
| 13 |
|
| 14 |
+
if not top:
|
| 15 |
+
print("No products to display.")
|
| 16 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
# Collect unique stores for filter buttons
|
| 19 |
+
stores = sorted(set(p.store for p in top if p.store))
|
| 20 |
|
| 21 |
+
scores = [p.score for p in top]
|
| 22 |
+
min_s, max_s = min(scores), max(scores)
|
| 23 |
+
score_range = max_s - min_s if max_s != min_s else 1.0
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
cards_html = []
|
| 26 |
+
for i, p in enumerate(top):
|
| 27 |
+
normalized = int(100 * (p.score - min_s) / score_range)
|
| 28 |
+
if normalized >= 70:
|
| 29 |
color = "#22c55e"
|
| 30 |
+
elif normalized >= 40:
|
| 31 |
color = "#3b82f6"
|
| 32 |
else:
|
| 33 |
color = "#f59e0b"
|
| 34 |
|
| 35 |
+
img_src = p.image_url or ""
|
| 36 |
+
store_label = p.store or _detect_store(p.url)
|
| 37 |
+
|
| 38 |
+
cards_html.append(f"""
|
| 39 |
+
<div class="card" data-store="{store_label}">
|
| 40 |
<span class="rank">#{i+1}</span>
|
| 41 |
+
<span class="store">{store_label}</span>
|
| 42 |
+
<a href="{p.url}" target="_blank">
|
| 43 |
+
<img src="{img_src}" loading="lazy" alt="{p.brand} {p.name}">
|
| 44 |
</a>
|
| 45 |
+
<div class="score" style="background:{color}">{normalized}%</div>
|
| 46 |
+
<div class="brand">{p.brand}</div>
|
| 47 |
+
<div class="name">{p.name[:50]}</div>
|
| 48 |
+
<div class="price">{p.price_text}</div>
|
| 49 |
+
<a href="{p.url}" target="_blank" class="link">View on {store_label}</a>
|
| 50 |
</div>""")
|
| 51 |
|
| 52 |
+
filter_buttons = '<button class="active" onclick="filterStore(\'all\')">All</button>\n'
|
| 53 |
+
for store in stores:
|
| 54 |
+
filter_buttons += f' <button onclick="filterStore(\'{store}\')">{store}</button>\n'
|
| 55 |
+
|
| 56 |
html = f"""<!DOCTYPE html>
|
| 57 |
<html lang="en">
|
| 58 |
<head>
|
| 59 |
<meta charset="UTF-8">
|
| 60 |
+
<title>Taste Engine — Top {len(top)} Bags</title>
|
| 61 |
<style>
|
| 62 |
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
|
| 63 |
body {{ font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: #0a0a0a; color: #e5e5e5; padding: 20px; }}
|
| 64 |
h1 {{ text-align: center; margin: 20px 0; font-size: 1.5em; color: #a3a3a3; }}
|
| 65 |
+
.stats {{ text-align: center; color: #737373; margin-bottom: 30px; }}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
.grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 16px; max-width: 1400px; margin: 0 auto; }}
|
| 67 |
.card {{ background: #171717; border-radius: 12px; overflow: hidden; position: relative; transition: transform 0.2s; }}
|
| 68 |
.card:hover {{ transform: translateY(-4px); }}
|
|
|
|
| 69 |
.card img {{ width: 100%; aspect-ratio: 3/4; object-fit: cover; display: block; }}
|
| 70 |
.rank {{ position: absolute; top: 8px; left: 8px; background: rgba(0,0,0,0.7); color: #a3a3a3; padding: 2px 8px; border-radius: 6px; font-size: 12px; }}
|
| 71 |
.store {{ position: absolute; top: 8px; right: 8px; background: rgba(59,130,246,0.8); color: #fff; padding: 2px 8px; border-radius: 6px; font-size: 11px; font-weight: 600; }}
|
|
|
|
| 75 |
.price {{ padding: 2px 12px 4px; font-size: 13px; color: #d4d4d4; }}
|
| 76 |
.link {{ display: block; text-align: center; padding: 8px; color: #60a5fa; text-decoration: none; font-size: 13px; border-top: 1px solid #262626; }}
|
| 77 |
.link:hover {{ background: #1e1e1e; }}
|
| 78 |
+
.filters {{ text-align: center; margin-bottom: 24px; display: flex; gap: 8px; justify-content: center; flex-wrap: wrap; }}
|
| 79 |
+
.filters button {{ background: #262626; color: #e5e5e5; border: 1px solid #404040; padding: 8px 20px; border-radius: 8px; cursor: pointer; font-size: 14px; transition: all 0.2s; }}
|
| 80 |
+
.filters button:hover {{ background: #333; }}
|
| 81 |
+
.filters button.active {{ background: #3b82f6; border-color: #3b82f6; color: #fff; }}
|
| 82 |
+
.card.hidden {{ display: none; }}
|
| 83 |
</style>
|
| 84 |
</head>
|
| 85 |
<body>
|
| 86 |
+
<h1>Taste Engine — Top {len(top)} Bags</h1>
|
| 87 |
+
<div class="stats">Scanned {len(products)} products total. Showing top {len(top)} by taste match.</div>
|
| 88 |
<div class="filters">
|
| 89 |
+
{filter_buttons}
|
|
|
|
|
|
|
|
|
|
| 90 |
</div>
|
| 91 |
<div class="grid">
|
| 92 |
+
{"".join(cards_html)}
|
| 93 |
</div>
|
| 94 |
<script>
|
| 95 |
+
function filterStore(store) {{
|
| 96 |
document.querySelectorAll('.filters button').forEach(b => b.classList.remove('active'));
|
| 97 |
+
event.target.classList.add('active');
|
| 98 |
document.querySelectorAll('.card').forEach(card => {{
|
| 99 |
if (store === 'all' || card.dataset.store === store) {{
|
| 100 |
card.classList.remove('hidden');
|
|
|
|
| 106 |
</script>
|
| 107 |
</body>
|
| 108 |
</html>"""
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
output_path.write_text(html)
|
| 111 |
+
print(f"\nResults saved to {output_path}")
|
|
|
|
|
|
|
| 112 |
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
def _detect_store(url: str) -> str:
|
| 115 |
+
if "boozt.com" in url:
|
| 116 |
+
return "Boozt"
|
| 117 |
+
elif "miinto.no" in url:
|
| 118 |
+
return "Miinto"
|
| 119 |
+
elif "wakakuu.com" in url:
|
| 120 |
+
return "Wakakuu"
|
| 121 |
+
elif "na-kd.com" in url:
|
| 122 |
+
return "NA-KD"
|
| 123 |
+
elif "zalando.no" in url:
|
| 124 |
+
return "Zalando"
|
| 125 |
+
return "Unknown"
|
scan_v2.py → taste/pipeline.py
RENAMED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Scan
|
| 2 |
|
| 3 |
import sys
|
| 4 |
import time
|
|
@@ -6,180 +6,171 @@ from pathlib import Path
|
|
| 6 |
|
| 7 |
sys.stdout.reconfigure(line_buffering=True)
|
| 8 |
|
| 9 |
-
from
|
| 10 |
-
from
|
| 11 |
-
from
|
| 12 |
-
from
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
REFERENCE_DIR = Path(__file__).parent / "reference-images"
|
| 15 |
-
OUTPUT_HTML = Path(__file__).parent / "results-all.html"
|
| 16 |
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
rows = conn.execute(
|
| 21 |
-
"SELECT url, image_path FROM products WHERE image_path != '' AND score = 0"
|
| 22 |
-
).fetchall()
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
paths.append(p)
|
| 39 |
-
urls.append(r["url"])
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
|
|
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
|
|
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
|
| 60 |
-
|
|
|
|
|
|
|
| 61 |
|
| 62 |
|
| 63 |
-
def
|
| 64 |
-
"""
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
print(f"\n {len(existing_urls)} products already in DB", flush=True)
|
| 69 |
|
| 70 |
all_new = []
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
wk = scrape_wakakuu(query="", max_products=3000)
|
| 76 |
-
new_wk = [p for p in wk if p["url"] and p["url"] not in existing_urls]
|
| 77 |
-
all_new.extend(new_wk)
|
| 78 |
-
print(f" Wakakuu: {len(wk)} total, {len(new_wk)} new", flush=True)
|
| 79 |
-
except Exception as e:
|
| 80 |
-
print(f" Wakakuu error: {e}", flush=True)
|
| 81 |
-
|
| 82 |
-
# Boozt (XHR JSON)
|
| 83 |
-
print("\n=== Boozt (XHR JSON) ===", flush=True)
|
| 84 |
-
try:
|
| 85 |
-
bz = scrape_boozt(max_products=5000)
|
| 86 |
-
new_bz = [p for p in bz if p["url"] and p["url"] not in existing_urls]
|
| 87 |
-
all_new.extend(new_bz)
|
| 88 |
-
print(f" Boozt: {len(bz)} total, {len(new_bz)} new", flush=True)
|
| 89 |
-
except Exception as e:
|
| 90 |
-
print(f" Boozt error: {e}", flush=True)
|
| 91 |
-
|
| 92 |
-
# Miinto (SSR)
|
| 93 |
-
print("\n=== Miinto (SSR preloaded state) ===", flush=True)
|
| 94 |
-
try:
|
| 95 |
-
mi = scrape_miinto(max_products=5000)
|
| 96 |
-
new_mi = [p for p in mi if p["url"] and p["url"] not in existing_urls]
|
| 97 |
-
all_new.extend(new_mi)
|
| 98 |
-
print(f" Miinto: {len(mi)} total, {len(new_mi)} new", flush=True)
|
| 99 |
-
except Exception as e:
|
| 100 |
-
print(f" Miinto error: {e}", flush=True)
|
| 101 |
-
|
| 102 |
-
# NA-KD (SSR JSON-LD)
|
| 103 |
-
print("\n=== NA-KD (SSR JSON-LD) ===", flush=True)
|
| 104 |
-
try:
|
| 105 |
-
nk = scrape_nakd(max_products=2000)
|
| 106 |
-
new_nk = [p for p in nk if p["url"] and p["url"] not in existing_urls]
|
| 107 |
-
all_new.extend(new_nk)
|
| 108 |
-
print(f" NA-KD: {len(nk)} total, {len(new_nk)} new", flush=True)
|
| 109 |
-
except Exception as e:
|
| 110 |
-
print(f" NA-KD error: {e}", flush=True)
|
| 111 |
-
|
| 112 |
-
# Save all new products to DB
|
| 113 |
-
if all_new:
|
| 114 |
-
print(f"\n Saving {len(all_new)} new products to DB...", flush=True)
|
| 115 |
-
upsert_batch(conn, all_new)
|
| 116 |
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
| 118 |
|
|
|
|
|
|
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
conn = get_db()
|
| 124 |
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
imported = import_from_catalog_jsonl(conn, catalog_path)
|
| 129 |
-
if imported:
|
| 130 |
-
print(f"[0] Imported {imported} products from catalog.jsonl", flush=True)
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
if centroids is None:
|
| 141 |
-
print("ERROR: No taste vector!", flush=True)
|
| 142 |
-
sys.exit(1)
|
| 143 |
-
print(f" {len(centroids)} taste clusters", flush=True)
|
| 144 |
|
| 145 |
-
|
| 146 |
-
print("\n[3/5] API scrapers (no browser needed)...", flush=True)
|
| 147 |
-
new_count = run_api_scrapers(conn)
|
| 148 |
|
| 149 |
-
# Step 4: Score all unscored products
|
| 150 |
-
print("\n[4/5] Scoring with FashionSigLIP...", flush=True)
|
| 151 |
-
score_unscored(engine, conn, centroids)
|
| 152 |
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
image_url=row["image_url"],
|
| 167 |
-
image_path=Path(row["image_path"]) if row.get("image_path") else None,
|
| 168 |
-
)
|
| 169 |
-
p.brand = row.get("brand", "")
|
| 170 |
-
p.name = row.get("name", "")
|
| 171 |
-
p.price_text = row.get("price_text", "")
|
| 172 |
-
p.price_nok = row.get("price_nok", 0)
|
| 173 |
-
p.score = row.get("score", 0)
|
| 174 |
-
product_objs.append(p)
|
| 175 |
|
| 176 |
-
|
| 177 |
-
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
print(f"open {OUTPUT_HTML}", flush=True)
|
| 182 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scan pipeline — orchestrates scraping, scoring, and output generation."""
|
| 2 |
|
| 3 |
import sys
|
| 4 |
import time
|
|
|
|
| 6 |
|
| 7 |
sys.stdout.reconfigure(line_buffering=True)
|
| 8 |
|
| 9 |
+
from taste.config import Config, UserProfile
|
| 10 |
+
from taste.engine import TasteEngine
|
| 11 |
+
from taste.models import Product
|
| 12 |
+
from taste.output import generate_html
|
| 13 |
+
from taste.scrapers import get_scraper
|
| 14 |
+
from taste.store import ProductStore
|
| 15 |
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
def run_scan(config: Config, profile: UserProfile, output_path: Path | None = None):
|
| 18 |
+
"""Run the full scan pipeline: seed references, build taste, scrape, score, output."""
|
| 19 |
+
t0 = time.time()
|
| 20 |
|
| 21 |
+
engine = TasteEngine(data_dir=config.data_dir)
|
| 22 |
+
store = ProductStore(db_path=profile.db_path(config))
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
# Step 0: Import existing catalog.jsonl (one-time migration)
|
| 25 |
+
catalog_path = config.data_dir / "catalog.jsonl"
|
| 26 |
+
if catalog_path.exists():
|
| 27 |
+
imported = store.import_from_catalog_jsonl(catalog_path)
|
| 28 |
+
if imported:
|
| 29 |
+
print(f"[0] Imported {imported} products from catalog.jsonl", flush=True)
|
| 30 |
|
| 31 |
+
# Step 1: Seed reference images
|
| 32 |
+
print("[1/5] Reference images...", flush=True)
|
| 33 |
+
for ref_dir in profile.reference_dirs:
|
| 34 |
+
if ref_dir.exists():
|
| 35 |
+
engine.seed_from_references(ref_dir)
|
| 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)
|
| 57 |
+
stats = store.get_stats()
|
| 58 |
+
print(f" DB stats: {stats}", flush=True)
|
| 59 |
|
| 60 |
+
all_products = store.get_all(min_score=0.01)
|
| 61 |
+
product_objs = [Product.from_dict(row) for row in all_products]
|
| 62 |
+
product_objs.sort(key=lambda p: p.score, reverse=True)
|
| 63 |
|
| 64 |
+
if output_path is None:
|
| 65 |
+
output_path = Path.cwd() / "results.html"
|
| 66 |
+
generate_html(product_objs, output_path, top_n=len(product_objs))
|
| 67 |
|
| 68 |
+
elapsed = time.time() - t0
|
| 69 |
+
print(f"\nDone in {elapsed:.0f}s! {len(product_objs)} products ranked.", flush=True)
|
| 70 |
+
print(f"open {output_path}", flush=True)
|
| 71 |
|
| 72 |
|
| 73 |
+
def _download_liked_urls(engine: TasteEngine, profile: UserProfile, config: Config):
|
| 74 |
+
"""Download product images from liked URLs and seed as references."""
|
| 75 |
+
if not profile.liked_urls:
|
| 76 |
+
return
|
| 77 |
+
|
| 78 |
+
import httpx
|
| 79 |
+
|
| 80 |
+
ref_dir = config.data_dir / "reference-images"
|
| 81 |
+
ref_dir.mkdir(parents=True, exist_ok=True)
|
| 82 |
+
|
| 83 |
+
print(f"\n Downloading {len(profile.liked_urls)} reference product images...", flush=True)
|
| 84 |
+
|
| 85 |
+
with httpx.Client(timeout=30, follow_redirects=True) as client:
|
| 86 |
+
for url in profile.liked_urls:
|
| 87 |
+
import hashlib
|
| 88 |
+
h = hashlib.md5(url.encode()).hexdigest()[:12]
|
| 89 |
+
path = ref_dir / f"{h}.jpg"
|
| 90 |
+
if path.exists():
|
| 91 |
+
print(f" [cached] {url[:80]}", flush=True)
|
| 92 |
+
engine.save_rating(path, 1)
|
| 93 |
+
continue
|
| 94 |
+
try:
|
| 95 |
+
resp = client.get(url)
|
| 96 |
+
if resp.status_code == 200 and len(resp.content) > 1000:
|
| 97 |
+
path.write_bytes(resp.content)
|
| 98 |
+
engine.save_rating(path, 1)
|
| 99 |
+
print(f" [downloaded] {url[:80]}", flush=True)
|
| 100 |
+
except Exception as e:
|
| 101 |
+
print(f" [error] {url[:60]}: {e}", flush=True)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _run_scrapers(config: Config, profile: UserProfile, store: ProductStore) -> int:
|
| 105 |
+
"""Run all enabled scrapers. Returns count of new products."""
|
| 106 |
+
existing_urls = store.get_existing_urls()
|
| 107 |
print(f"\n {len(existing_urls)} products already in DB", flush=True)
|
| 108 |
|
| 109 |
all_new = []
|
| 110 |
|
| 111 |
+
for name, store_config in config.stores.items():
|
| 112 |
+
if not store_config.enabled:
|
| 113 |
+
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
print(f"\n=== {name.title()} ===", flush=True)
|
| 116 |
+
try:
|
| 117 |
+
scraper = get_scraper(store_config)
|
| 118 |
+
products = scraper.scrape()
|
| 119 |
|
| 120 |
+
# Filter known URLs
|
| 121 |
+
new = [p for p in products if p.get("url") and p["url"] not in existing_urls]
|
| 122 |
|
| 123 |
+
# Download images
|
| 124 |
+
cache_dir = config.store_cache_dir(name)
|
| 125 |
+
scraper.download_images(new, cache_dir, config.image_download_concurrency)
|
|
|
|
| 126 |
|
| 127 |
+
# Filter disliked brands
|
| 128 |
+
if profile.disliked_brands:
|
| 129 |
+
new = [p for p in new if p.get("brand", "").lower() not in profile.disliked_brands]
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
all_new.extend(new)
|
| 132 |
+
print(f" {name.title()}: {len(products)} total, {len(new)} new", flush=True)
|
| 133 |
+
except Exception as e:
|
| 134 |
+
print(f" {name.title()} error: {e}", flush=True)
|
| 135 |
|
| 136 |
+
if all_new:
|
| 137 |
+
print(f"\n Saving {len(all_new)} new products to DB...", flush=True)
|
| 138 |
+
store.upsert_batch(all_new)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 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
|
| 149 |
+
|
| 150 |
+
print(f" Scoring {len(rows)} unscored products...", flush=True)
|
| 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 |
|
| 172 |
+
done = min(i + batch_size, len(rows))
|
| 173 |
+
if done % 200 == 0 or done == len(rows):
|
| 174 |
+
print(f" {done}/{len(rows)} scored", flush=True)
|
| 175 |
+
|
| 176 |
+
print(f" Done scoring.", flush=True)
|
taste/scrapers/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scraper registry — maps store names to scraper classes."""
|
| 2 |
+
|
| 3 |
+
from taste.config import StoreConfig
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def get_scraper(store_config: StoreConfig):
|
| 7 |
+
"""Return the right scraper instance for a store config."""
|
| 8 |
+
if store_config.type == "api":
|
| 9 |
+
return _get_api_scraper(store_config)
|
| 10 |
+
elif store_config.type == "browser":
|
| 11 |
+
return _get_browser_scraper(store_config)
|
| 12 |
+
raise ValueError(f"Unknown scraper type: {store_config.type}")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _get_api_scraper(sc: StoreConfig):
|
| 16 |
+
name = sc.name.lower()
|
| 17 |
+
if name == "wakakuu":
|
| 18 |
+
from taste.scrapers.api.wakakuu import WakakuuScraper
|
| 19 |
+
return WakakuuScraper(sc)
|
| 20 |
+
elif name == "boozt":
|
| 21 |
+
from taste.scrapers.api.boozt import BooztScraper
|
| 22 |
+
return BooztScraper(sc)
|
| 23 |
+
elif name == "miinto":
|
| 24 |
+
from taste.scrapers.api.miinto import MiintoScraper
|
| 25 |
+
return MiintoScraper(sc)
|
| 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 |
+
|
| 32 |
+
def _get_browser_scraper(sc: StoreConfig):
|
| 33 |
+
raise NotImplementedError(f"Browser scrapers not yet ported for: {sc.name}")
|
taste/scrapers/api/__init__.py
ADDED
|
File without changes
|
taste/scrapers/api/boozt.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Boozt scraper — internal products API."""
|
| 2 |
+
|
| 3 |
+
import html as _html
|
| 4 |
+
import json as _json
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
import httpx
|
| 8 |
+
|
| 9 |
+
from taste.config import StoreConfig
|
| 10 |
+
from taste.scrapers.base import BaseScraper
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class BooztScraper(BaseScraper):
|
| 14 |
+
def scrape(self, categories: list[str] | None = None, max_products: int | None = None) -> list[dict]:
|
| 15 |
+
categories = categories or self.config.categories
|
| 16 |
+
max_products = max_products or self.config.max_products
|
| 17 |
+
base_url = self.config.base_url or "https://www.boozt.com"
|
| 18 |
+
material = self.config.extra.get("material_filter", "ekte-skinn")
|
| 19 |
+
|
| 20 |
+
products = []
|
| 21 |
+
seen_urls = set()
|
| 22 |
+
|
| 23 |
+
headers = {
|
| 24 |
+
"Accept": "application/json, text/html",
|
| 25 |
+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
with httpx.Client(timeout=30, headers=headers, follow_redirects=True) as client:
|
| 29 |
+
for cat in categories:
|
| 30 |
+
if len(products) >= max_products:
|
| 31 |
+
break
|
| 32 |
+
cat_url = cat if cat.startswith("http") else f"{base_url}{cat}"
|
| 33 |
+
|
| 34 |
+
# Step 1: Get navigationId from category HTML
|
| 35 |
+
try:
|
| 36 |
+
html_resp = client.get(cat_url)
|
| 37 |
+
if html_resp.status_code != 200:
|
| 38 |
+
print(f" Boozt: {cat} returned {html_resp.status_code}", flush=True)
|
| 39 |
+
continue
|
| 40 |
+
|
| 41 |
+
nav_id = self._extract_nav_id(html_resp.text)
|
| 42 |
+
if not nav_id:
|
| 43 |
+
print(f" Boozt: no navigationId for {cat}", flush=True)
|
| 44 |
+
continue
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f" Boozt: error getting navId for {cat}: {e}", flush=True)
|
| 47 |
+
continue
|
| 48 |
+
|
| 49 |
+
print(f" Boozt: {cat.split('/')[-1]} navId={nav_id}", flush=True)
|
| 50 |
+
|
| 51 |
+
# Step 2: Fetch products (API ignores page param, use large limit)
|
| 52 |
+
try:
|
| 53 |
+
api_url = f"{base_url}/no/no/api/navigation/{nav_id}/products?limit=500"
|
| 54 |
+
if material:
|
| 55 |
+
api_url += f"&material={material}"
|
| 56 |
+
resp = client.get(api_url)
|
| 57 |
+
if resp.status_code != 200:
|
| 58 |
+
continue
|
| 59 |
+
|
| 60 |
+
data = resp.json()
|
| 61 |
+
cards = data.get("product_cards", [])
|
| 62 |
+
|
| 63 |
+
new_count = 0
|
| 64 |
+
for card in cards:
|
| 65 |
+
prod_url = card.get("product_url", "")
|
| 66 |
+
if not prod_url:
|
| 67 |
+
continue
|
| 68 |
+
if not prod_url.startswith("http"):
|
| 69 |
+
prod_url = f"{base_url}{prod_url}"
|
| 70 |
+
if prod_url in seen_urls:
|
| 71 |
+
continue
|
| 72 |
+
seen_urls.add(prod_url)
|
| 73 |
+
|
| 74 |
+
prices = card.get("prices", {})
|
| 75 |
+
base = prices.get("base", {})
|
| 76 |
+
price_str = base.get("price", "0")
|
| 77 |
+
price_val = float(re.sub(r"[^\d.]", "", str(price_str)) or 0)
|
| 78 |
+
|
| 79 |
+
media = card.get("media", [])
|
| 80 |
+
image_url = media[0].get("url", "") if media else ""
|
| 81 |
+
|
| 82 |
+
products.append({
|
| 83 |
+
"url": prod_url,
|
| 84 |
+
"image_url": image_url,
|
| 85 |
+
"brand": card.get("brand_name", ""),
|
| 86 |
+
"name": card.get("display_name", ""),
|
| 87 |
+
"price_nok": price_val,
|
| 88 |
+
"price_text": base.get("formatted_price", f"{price_val:.0f} kr"),
|
| 89 |
+
"store": "Boozt",
|
| 90 |
+
})
|
| 91 |
+
new_count += 1
|
| 92 |
+
|
| 93 |
+
print(f" Boozt: {cat.split('/')[-1]} +{new_count} products, {len(products)} total", flush=True)
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f" Boozt: error for {cat}: {e}", flush=True)
|
| 96 |
+
|
| 97 |
+
return products
|
| 98 |
+
|
| 99 |
+
@staticmethod
|
| 100 |
+
def _extract_nav_id(html_text: str) -> str | None:
|
| 101 |
+
# Try React on Rails props
|
| 102 |
+
m = re.search(
|
| 103 |
+
r'data-component-name="ListingPageSSR"[^>]*data-props="([^"]*)"',
|
| 104 |
+
html_text,
|
| 105 |
+
)
|
| 106 |
+
if m:
|
| 107 |
+
try:
|
| 108 |
+
props = _json.loads(_html.unescape(m.group(1)))
|
| 109 |
+
nav_id = props.get("baseNavigationId")
|
| 110 |
+
if nav_id:
|
| 111 |
+
return str(nav_id)
|
| 112 |
+
except Exception:
|
| 113 |
+
pass
|
| 114 |
+
|
| 115 |
+
# Fallback: regex for navigationId
|
| 116 |
+
for pattern in (r'"baseNavigationId"\s*:\s*(\d+)', r'"navigationId"\s*:\s*(\d+)'):
|
| 117 |
+
m2 = re.search(pattern, html_text)
|
| 118 |
+
if m2:
|
| 119 |
+
return m2.group(1)
|
| 120 |
+
return None
|
taste/scrapers/api/miinto.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Miinto scraper — SSR preloaded state extraction."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
import httpx
|
| 7 |
+
|
| 8 |
+
from taste.config import StoreConfig
|
| 9 |
+
from taste.scrapers.base import BaseScraper
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class MiintoScraper(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.miinto.no"
|
| 17 |
+
|
| 18 |
+
products = []
|
| 19 |
+
seen_urls = set()
|
| 20 |
+
|
| 21 |
+
headers = {
|
| 22 |
+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
|
| 23 |
+
"Accept": "text/html",
|
| 24 |
+
"Accept-Language": "nb-NO,nb;q=0.9",
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
with httpx.Client(timeout=30, headers=headers, follow_redirects=True) as client:
|
| 28 |
+
for cat in categories:
|
| 29 |
+
cat_url = cat if cat.startswith("http") else f"{base_url}{cat}"
|
| 30 |
+
page_num = 1
|
| 31 |
+
|
| 32 |
+
while len(products) < max_products:
|
| 33 |
+
url = f"{cat_url}?page={page_num}"
|
| 34 |
+
resp = client.get(url)
|
| 35 |
+
if resp.status_code != 200:
|
| 36 |
+
break
|
| 37 |
+
|
| 38 |
+
state = self._extract_state(resp.text)
|
| 39 |
+
if state is None:
|
| 40 |
+
break
|
| 41 |
+
|
| 42 |
+
prods_data = self._find_products(state)
|
| 43 |
+
if not prods_data:
|
| 44 |
+
break
|
| 45 |
+
|
| 46 |
+
new_count = 0
|
| 47 |
+
for item in prods_data:
|
| 48 |
+
prod_url = item.get("url", "")
|
| 49 |
+
if prod_url and not prod_url.startswith("http"):
|
| 50 |
+
prod_url = f"{base_url}{prod_url}"
|
| 51 |
+
if prod_url in seen_urls or not prod_url:
|
| 52 |
+
continue
|
| 53 |
+
seen_urls.add(prod_url)
|
| 54 |
+
|
| 55 |
+
price_data = item.get("price", {})
|
| 56 |
+
if isinstance(price_data, dict):
|
| 57 |
+
price_raw = price_data.get("price", price_data.get("originalPrice", 0))
|
| 58 |
+
else:
|
| 59 |
+
price_raw = price_data
|
| 60 |
+
price_nok = float(price_raw or 0) / 100
|
| 61 |
+
|
| 62 |
+
photo = item.get("photo", {})
|
| 63 |
+
image_url = photo.get("url", "") if isinstance(photo, dict) else str(photo)
|
| 64 |
+
|
| 65 |
+
products.append({
|
| 66 |
+
"url": prod_url,
|
| 67 |
+
"image_url": image_url,
|
| 68 |
+
"brand": item.get("brand", ""),
|
| 69 |
+
"name": item.get("title", item.get("name", "")),
|
| 70 |
+
"price_nok": price_nok,
|
| 71 |
+
"price_text": f"{price_nok:.0f} kr" if price_nok else "",
|
| 72 |
+
"store": "Miinto",
|
| 73 |
+
})
|
| 74 |
+
new_count += 1
|
| 75 |
+
|
| 76 |
+
print(f" Miinto: {cat.split('/')[-1]} page {page_num}, +{new_count}, {len(products)} total", flush=True)
|
| 77 |
+
|
| 78 |
+
if new_count == 0:
|
| 79 |
+
break
|
| 80 |
+
page_num += 1
|
| 81 |
+
|
| 82 |
+
return products
|
| 83 |
+
|
| 84 |
+
@staticmethod
|
| 85 |
+
def _extract_state(text: str) -> dict | None:
|
| 86 |
+
"""Extract __PLP_PRELOADED_STATE__ handling JSON.stringify wrapper."""
|
| 87 |
+
marker = "__PLP_PRELOADED_STATE__"
|
| 88 |
+
marker_idx = text.find(marker)
|
| 89 |
+
if marker_idx == -1:
|
| 90 |
+
return None
|
| 91 |
+
|
| 92 |
+
stringify_idx = text.find("JSON.stringify(", marker_idx)
|
| 93 |
+
if stringify_idx == -1:
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
obj_start = stringify_idx + len("JSON.stringify(")
|
| 97 |
+
depth = 0
|
| 98 |
+
in_str = False
|
| 99 |
+
esc = False
|
| 100 |
+
end = obj_start
|
| 101 |
+
for end in range(obj_start, min(obj_start + 500_000, len(text))):
|
| 102 |
+
c = text[end]
|
| 103 |
+
if esc:
|
| 104 |
+
esc = False
|
| 105 |
+
continue
|
| 106 |
+
if c == "\\":
|
| 107 |
+
esc = True
|
| 108 |
+
continue
|
| 109 |
+
if c == '"':
|
| 110 |
+
in_str = not in_str
|
| 111 |
+
if not in_str:
|
| 112 |
+
if c == "{":
|
| 113 |
+
depth += 1
|
| 114 |
+
elif c == "}":
|
| 115 |
+
depth -= 1
|
| 116 |
+
if depth == 0:
|
| 117 |
+
break
|
| 118 |
+
|
| 119 |
+
if depth != 0:
|
| 120 |
+
return None
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
return json.loads(text[obj_start : end + 1])
|
| 124 |
+
except json.JSONDecodeError:
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
@staticmethod
|
| 128 |
+
def _find_products(state) -> list:
|
| 129 |
+
if isinstance(state, dict):
|
| 130 |
+
for key in ("products", "items", "results"):
|
| 131 |
+
if key in state:
|
| 132 |
+
return state[key]
|
| 133 |
+
if "data" in state:
|
| 134 |
+
d = state["data"]
|
| 135 |
+
if isinstance(d, dict):
|
| 136 |
+
for key in ("products", "items"):
|
| 137 |
+
if key in d:
|
| 138 |
+
return d[key]
|
| 139 |
+
elif isinstance(state, list):
|
| 140 |
+
return state
|
| 141 |
+
return []
|
taste/scrapers/api/nakd.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""NA-KD scraper — SSR JSON-LD extraction."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
import httpx
|
| 7 |
+
|
| 8 |
+
from taste.config import StoreConfig
|
| 9 |
+
from taste.scrapers.base import BaseScraper
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class NakdScraper(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.na-kd.com"
|
| 17 |
+
|
| 18 |
+
products = []
|
| 19 |
+
seen_urls = set()
|
| 20 |
+
|
| 21 |
+
headers = {
|
| 22 |
+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
|
| 23 |
+
"Accept": "text/html",
|
| 24 |
+
"Accept-Language": "nb-NO,nb;q=0.9",
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
with httpx.Client(timeout=30, headers=headers, follow_redirects=True) as client:
|
| 28 |
+
for cat in categories:
|
| 29 |
+
cat_url = cat if cat.startswith("http") else f"{base_url}{cat}"
|
| 30 |
+
page_num = 1
|
| 31 |
+
|
| 32 |
+
while len(products) < max_products:
|
| 33 |
+
url = f"{cat_url}?page={page_num}"
|
| 34 |
+
resp = client.get(url)
|
| 35 |
+
if resp.status_code != 200:
|
| 36 |
+
break
|
| 37 |
+
|
| 38 |
+
ld_matches = re.findall(
|
| 39 |
+
r'<script[^>]*type="application/ld\+json"[^>]*>(.*?)</script>',
|
| 40 |
+
resp.text, re.DOTALL,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
new_count = 0
|
| 44 |
+
for ld_text in ld_matches:
|
| 45 |
+
try:
|
| 46 |
+
ld = json.loads(ld_text)
|
| 47 |
+
except json.JSONDecodeError:
|
| 48 |
+
continue
|
| 49 |
+
|
| 50 |
+
items = []
|
| 51 |
+
if isinstance(ld, dict):
|
| 52 |
+
if ld.get("@type") == "ItemList":
|
| 53 |
+
items = ld.get("itemListElement", [])
|
| 54 |
+
elif ld.get("@type") in ("Product", "ProductGroup"):
|
| 55 |
+
items = [ld]
|
| 56 |
+
|
| 57 |
+
for item in items:
|
| 58 |
+
product = item.get("item", item) if "item" in item else item
|
| 59 |
+
prod_url = product.get("url", "")
|
| 60 |
+
if prod_url in seen_urls or not prod_url:
|
| 61 |
+
continue
|
| 62 |
+
seen_urls.add(prod_url)
|
| 63 |
+
|
| 64 |
+
image = product.get("image", "")
|
| 65 |
+
if isinstance(image, list):
|
| 66 |
+
image = image[0] if image else ""
|
| 67 |
+
|
| 68 |
+
offers = product.get("offers", {})
|
| 69 |
+
if isinstance(offers, list):
|
| 70 |
+
offers = offers[0] if offers else {}
|
| 71 |
+
price_val = float(offers.get("price", 0))
|
| 72 |
+
|
| 73 |
+
brand = product.get("brand", "")
|
| 74 |
+
if isinstance(brand, dict):
|
| 75 |
+
brand = brand.get("name", "")
|
| 76 |
+
|
| 77 |
+
products.append({
|
| 78 |
+
"url": prod_url,
|
| 79 |
+
"image_url": image,
|
| 80 |
+
"brand": str(brand),
|
| 81 |
+
"name": product.get("name", ""),
|
| 82 |
+
"price_nok": price_val,
|
| 83 |
+
"price_text": f"{price_val:.0f} kr" if price_val else "",
|
| 84 |
+
"store": "NA-KD",
|
| 85 |
+
})
|
| 86 |
+
new_count += 1
|
| 87 |
+
|
| 88 |
+
print(f" NA-KD: {cat.split('/')[-1]} page {page_num}, +{new_count}, {len(products)} total", flush=True)
|
| 89 |
+
|
| 90 |
+
if new_count == 0:
|
| 91 |
+
break
|
| 92 |
+
page_num += 1
|
| 93 |
+
|
| 94 |
+
return products
|
taste/scrapers/api/wakakuu.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Wakakuu scraper — Algolia API."""
|
| 2 |
+
|
| 3 |
+
import httpx
|
| 4 |
+
|
| 5 |
+
from taste.config import StoreConfig
|
| 6 |
+
from taste.scrapers.base import BaseScraper
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class WakakuuScraper(BaseScraper):
|
| 10 |
+
def scrape(self, categories: list[str] | None = None, max_products: int | None = None) -> list[dict]:
|
| 11 |
+
categories = categories or self.config.categories
|
| 12 |
+
max_products = max_products or self.config.max_products
|
| 13 |
+
|
| 14 |
+
app_id = self.config.extra.get("algolia_app_id", "0LM8YN9I0K")
|
| 15 |
+
api_key = self.config.extra.get("algolia_api_key", "00ef309f4d1543ffdaa1d85c33111700")
|
| 16 |
+
index = self.config.extra.get("algolia_index", "prod_products_sv")
|
| 17 |
+
base_url = self.config.base_url or "https://www.wakakuu.com"
|
| 18 |
+
url = f"https://{app_id}-dsn.algolia.net/1/indexes/{index}/query"
|
| 19 |
+
|
| 20 |
+
headers = {
|
| 21 |
+
"X-Algolia-Application-Id": app_id,
|
| 22 |
+
"X-Algolia-API-Key": api_key,
|
| 23 |
+
"Content-Type": "application/json",
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
products = []
|
| 27 |
+
for cat_filter in categories:
|
| 28 |
+
page = 0
|
| 29 |
+
while len(products) < max_products:
|
| 30 |
+
body = {
|
| 31 |
+
"params": f"query=&hitsPerPage=100&page={page}&filters={cat_filter}"
|
| 32 |
+
}
|
| 33 |
+
with httpx.Client(timeout=30) as client:
|
| 34 |
+
resp = client.post(url, headers=headers, json=body)
|
| 35 |
+
|
| 36 |
+
if resp.status_code != 200:
|
| 37 |
+
print(f" Wakakuu API error: {resp.status_code}", flush=True)
|
| 38 |
+
break
|
| 39 |
+
|
| 40 |
+
data = resp.json()
|
| 41 |
+
hits = data.get("hits", [])
|
| 42 |
+
if not hits:
|
| 43 |
+
break
|
| 44 |
+
|
| 45 |
+
for hit in hits:
|
| 46 |
+
image = hit.get("imageUrl", "") or hit.get("image", "")
|
| 47 |
+
|
| 48 |
+
prices = hit.get("price", {})
|
| 49 |
+
price_val = 0
|
| 50 |
+
if isinstance(prices, dict):
|
| 51 |
+
for currency in ("NOK", "SEK", "EUR"):
|
| 52 |
+
bucket = prices.get(currency)
|
| 53 |
+
if bucket is None:
|
| 54 |
+
continue
|
| 55 |
+
if isinstance(bucket, dict):
|
| 56 |
+
raw = bucket.get("anonymous", bucket.get("default", 0))
|
| 57 |
+
if isinstance(raw, dict):
|
| 58 |
+
raw = raw.get("amount", raw.get("value", 0))
|
| 59 |
+
price_val = float(raw or 0)
|
| 60 |
+
if price_val:
|
| 61 |
+
break
|
| 62 |
+
elif isinstance(bucket, (int, float)):
|
| 63 |
+
price_val = float(bucket)
|
| 64 |
+
break
|
| 65 |
+
elif isinstance(prices, (int, float)):
|
| 66 |
+
price_val = float(prices)
|
| 67 |
+
|
| 68 |
+
product_url = hit.get("url", "")
|
| 69 |
+
if product_url and not product_url.startswith("http"):
|
| 70 |
+
product_url = f"{base_url}{product_url}"
|
| 71 |
+
|
| 72 |
+
products.append({
|
| 73 |
+
"url": product_url,
|
| 74 |
+
"image_url": image,
|
| 75 |
+
"brand": hit.get("brand", ""),
|
| 76 |
+
"name": hit.get("name", hit.get("title", "")),
|
| 77 |
+
"price_nok": price_val,
|
| 78 |
+
"price_text": f"{price_val:.0f} kr" if price_val else "",
|
| 79 |
+
"store": "Wakakuu",
|
| 80 |
+
})
|
| 81 |
+
|
| 82 |
+
print(f" Wakakuu: page {page}, +{len(hits)} hits, {len(products)} total", flush=True)
|
| 83 |
+
|
| 84 |
+
nb_pages = data.get("nbPages", 0)
|
| 85 |
+
page += 1
|
| 86 |
+
if page >= nb_pages:
|
| 87 |
+
break
|
| 88 |
+
|
| 89 |
+
return products
|
taste/scrapers/base.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Base scraper interface and shared image downloader."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
from abc import ABC, abstractmethod
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import httpx
|
| 10 |
+
|
| 11 |
+
from taste.config import StoreConfig
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class BaseScraper(ABC):
|
| 15 |
+
def __init__(self, store_config: StoreConfig):
|
| 16 |
+
self.config = store_config
|
| 17 |
+
|
| 18 |
+
@abstractmethod
|
| 19 |
+
def scrape(self, categories: list[str] | None = None, max_products: int | None = None) -> list[dict]:
|
| 20 |
+
"""Scrape products. Returns list of product dicts."""
|
| 21 |
+
...
|
| 22 |
+
|
| 23 |
+
def download_images(self, products: list[dict], cache_dir: Path, concurrency: int = 20) -> list[dict]:
|
| 24 |
+
"""Download product images with connection pooling."""
|
| 25 |
+
to_download = [p for p in products if p.get("image_url") and not p.get("image_path")]
|
| 26 |
+
|
| 27 |
+
if not to_download:
|
| 28 |
+
return products
|
| 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 to_download:
|
| 36 |
+
try:
|
| 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 |
+
print(f" Downloaded {downloaded}/{len(products)} images", flush=True)
|
| 51 |
+
return products
|
taste/scrapers/browser/__init__.py
ADDED
|
File without changes
|
taste/store.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SQLite-backed product store — crash-safe, queryable, deduped."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import sqlite3
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class ProductStore:
|
| 9 |
+
"""Per-profile product database. Each user gets their own db_path."""
|
| 10 |
+
|
| 11 |
+
def __init__(self, db_path: Path):
|
| 12 |
+
self.db_path = Path(db_path)
|
| 13 |
+
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
| 14 |
+
self.conn = sqlite3.connect(str(self.db_path))
|
| 15 |
+
self.conn.row_factory = sqlite3.Row
|
| 16 |
+
self.conn.execute("PRAGMA journal_mode=WAL")
|
| 17 |
+
self.conn.execute("PRAGMA synchronous=NORMAL")
|
| 18 |
+
self.conn.execute("""
|
| 19 |
+
CREATE TABLE IF NOT EXISTS products (
|
| 20 |
+
url TEXT PRIMARY KEY,
|
| 21 |
+
image_url TEXT,
|
| 22 |
+
image_path TEXT,
|
| 23 |
+
brand TEXT DEFAULT '',
|
| 24 |
+
name TEXT DEFAULT '',
|
| 25 |
+
price_text TEXT DEFAULT '',
|
| 26 |
+
price_nok REAL DEFAULT 0,
|
| 27 |
+
store TEXT DEFAULT '',
|
| 28 |
+
score REAL DEFAULT 0,
|
| 29 |
+
fabric TEXT DEFAULT '',
|
| 30 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 31 |
+
)
|
| 32 |
+
""")
|
| 33 |
+
self.conn.execute("CREATE INDEX IF NOT EXISTS idx_store ON products(store)")
|
| 34 |
+
self.conn.execute("CREATE INDEX IF NOT EXISTS idx_score ON products(score DESC)")
|
| 35 |
+
self.conn.commit()
|
| 36 |
+
|
| 37 |
+
def upsert(self, product: dict):
|
| 38 |
+
self.conn.execute("""
|
| 39 |
+
INSERT INTO products (url, image_url, image_path, brand, name, price_text, price_nok, store, score, fabric)
|
| 40 |
+
VALUES (:url, :image_url, :image_path, :brand, :name, :price_text, :price_nok, :store, :score, :fabric)
|
| 41 |
+
ON CONFLICT(url) DO UPDATE SET
|
| 42 |
+
image_path = COALESCE(excluded.image_path, products.image_path),
|
| 43 |
+
score = CASE WHEN excluded.score > products.score THEN excluded.score ELSE products.score END,
|
| 44 |
+
brand = CASE WHEN excluded.brand != '' THEN excluded.brand ELSE products.brand END,
|
| 45 |
+
name = CASE WHEN excluded.name != '' THEN excluded.name ELSE products.name END,
|
| 46 |
+
price_text = CASE WHEN excluded.price_text != '' THEN excluded.price_text ELSE products.price_text END,
|
| 47 |
+
price_nok = CASE WHEN excluded.price_nok > 0 THEN excluded.price_nok ELSE products.price_nok END,
|
| 48 |
+
fabric = CASE WHEN excluded.fabric != '' THEN excluded.fabric ELSE products.fabric END
|
| 49 |
+
""", {
|
| 50 |
+
"url": product.get("url", ""),
|
| 51 |
+
"image_url": product.get("image_url", ""),
|
| 52 |
+
"image_path": product.get("image_path", ""),
|
| 53 |
+
"brand": product.get("brand", ""),
|
| 54 |
+
"name": product.get("name", ""),
|
| 55 |
+
"price_text": product.get("price_text", ""),
|
| 56 |
+
"price_nok": product.get("price_nok", 0),
|
| 57 |
+
"store": product.get("store", ""),
|
| 58 |
+
"score": product.get("score", 0),
|
| 59 |
+
"fabric": product.get("fabric", ""),
|
| 60 |
+
})
|
| 61 |
+
self.conn.commit()
|
| 62 |
+
|
| 63 |
+
def upsert_batch(self, products: list[dict]):
|
| 64 |
+
for p in products:
|
| 65 |
+
self.conn.execute("""
|
| 66 |
+
INSERT INTO products (url, image_url, image_path, brand, name, price_text, price_nok, store, score, fabric)
|
| 67 |
+
VALUES (:url, :image_url, :image_path, :brand, :name, :price_text, :price_nok, :store, :score, :fabric)
|
| 68 |
+
ON CONFLICT(url) DO UPDATE SET
|
| 69 |
+
image_path = COALESCE(excluded.image_path, products.image_path),
|
| 70 |
+
score = CASE WHEN excluded.score > products.score THEN excluded.score ELSE products.score END,
|
| 71 |
+
brand = CASE WHEN excluded.brand != '' THEN excluded.brand ELSE products.brand END,
|
| 72 |
+
name = CASE WHEN excluded.name != '' THEN excluded.name ELSE products.name END,
|
| 73 |
+
price_text = CASE WHEN excluded.price_text != '' THEN excluded.price_text ELSE products.price_text END,
|
| 74 |
+
price_nok = CASE WHEN excluded.price_nok > 0 THEN excluded.price_nok ELSE products.price_nok END,
|
| 75 |
+
fabric = CASE WHEN excluded.fabric != '' THEN excluded.fabric ELSE products.fabric END
|
| 76 |
+
""", {
|
| 77 |
+
"url": p.get("url", ""),
|
| 78 |
+
"image_url": p.get("image_url", ""),
|
| 79 |
+
"image_path": p.get("image_path", ""),
|
| 80 |
+
"brand": p.get("brand", ""),
|
| 81 |
+
"name": p.get("name", ""),
|
| 82 |
+
"price_text": p.get("price_text", ""),
|
| 83 |
+
"price_nok": p.get("price_nok", 0),
|
| 84 |
+
"store": p.get("store", ""),
|
| 85 |
+
"score": p.get("score", 0),
|
| 86 |
+
"fabric": p.get("fabric", ""),
|
| 87 |
+
})
|
| 88 |
+
self.conn.commit()
|
| 89 |
+
|
| 90 |
+
def get_all(self, store: str | None = None, min_score: float = 0, limit: int = 0) -> list[dict]:
|
| 91 |
+
sql = "SELECT * FROM products WHERE score >= ?"
|
| 92 |
+
params: list = [min_score]
|
| 93 |
+
if store:
|
| 94 |
+
sql += " AND store = ?"
|
| 95 |
+
params.append(store)
|
| 96 |
+
sql += " ORDER BY score DESC"
|
| 97 |
+
if limit:
|
| 98 |
+
sql += " LIMIT ?"
|
| 99 |
+
params.append(limit)
|
| 100 |
+
return [dict(r) for r in self.conn.execute(sql, params).fetchall()]
|
| 101 |
+
|
| 102 |
+
def get_existing_urls(self) -> set[str]:
|
| 103 |
+
return set(r[0] for r in self.conn.execute("SELECT url FROM products").fetchall())
|
| 104 |
+
|
| 105 |
+
def get_unscored(self) -> list[dict]:
|
| 106 |
+
rows = self.conn.execute(
|
| 107 |
+
"SELECT url, image_path FROM products WHERE image_path != '' AND score = 0"
|
| 108 |
+
).fetchall()
|
| 109 |
+
return [dict(r) for r in rows]
|
| 110 |
+
|
| 111 |
+
def update_score(self, url: str, score: float):
|
| 112 |
+
self.conn.execute("UPDATE products SET score = ? WHERE url = ?", (score, url))
|
| 113 |
+
|
| 114 |
+
def commit(self):
|
| 115 |
+
self.conn.commit()
|
| 116 |
+
|
| 117 |
+
def get_stats(self) -> dict:
|
| 118 |
+
rows = self.conn.execute("""
|
| 119 |
+
SELECT store, COUNT(*) as count,
|
| 120 |
+
MAX(score) as top_score,
|
| 121 |
+
AVG(score) as avg_score
|
| 122 |
+
FROM products GROUP BY store ORDER BY count DESC
|
| 123 |
+
""").fetchall()
|
| 124 |
+
total = self.conn.execute("SELECT COUNT(*) FROM products").fetchone()[0]
|
| 125 |
+
return {
|
| 126 |
+
"total": total,
|
| 127 |
+
"stores": {
|
| 128 |
+
r["store"]: {"count": r["count"], "top": r["top_score"], "avg": round(r["avg_score"], 3)}
|
| 129 |
+
for r in rows
|
| 130 |
+
},
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
def import_from_catalog_jsonl(self, jsonl_path: Path) -> int:
|
| 134 |
+
if not jsonl_path.exists():
|
| 135 |
+
return 0
|
| 136 |
+
count = 0
|
| 137 |
+
for line in jsonl_path.read_text().splitlines():
|
| 138 |
+
if not line.strip():
|
| 139 |
+
continue
|
| 140 |
+
data = json.loads(line)
|
| 141 |
+
store = "Zalando"
|
| 142 |
+
if "boozt.com" in data.get("url", ""):
|
| 143 |
+
store = "Boozt"
|
| 144 |
+
elif "miinto.no" in data.get("url", ""):
|
| 145 |
+
store = "Miinto"
|
| 146 |
+
data["store"] = store
|
| 147 |
+
self.upsert(data)
|
| 148 |
+
count += 1
|
| 149 |
+
return count
|