Spaces:
Sleeping
Sleeping
Commit ·
0fba372
1
Parent(s): d40f9ef
standardize data collection: new schema, rewrite scrapers, lifecycle tracking
Browse filesSchema: added color, material, category, external_id, original_price,
currency, on_sale, in_stock, sizes, first/last_seen_at, updated_at.
Score is now nullable (NULL = unscored). Auto-migration from v1.
Scrapers: all 4 rewritten for full field capture:
- Boozt: 5 images, color, stock, sizes, sale pricing
- Miinto: UUID external_id, category, sizes, sale detection
- NA-KD: switched to CURRENT_PAGE extraction, fixed brand/price (was 0)
- Wakakuu: fixed price extraction (was 0), color, stock, sizes
Store: new sync() method — idempotent upsert + marks missing products
as out-of-stock. Running twice produces same result.
Frontend: sale badges, sold-out overlay, color display, original price
with strikethrough.
- backend/app/routers/discover.py +4 -24
- backend/app/routers/products.py +32 -20
- backend/app/schemas.py +10 -1
- frontend/src/index.css +46 -0
- frontend/src/pages/BrowsePage.tsx +10 -2
- frontend/src/types.ts +9 -0
- taste/models.py +57 -29
- taste/scrapers/api/boozt.py +40 -11
- taste/scrapers/api/miinto.py +30 -10
- taste/scrapers/api/nakd.py +193 -55
- taste/scrapers/api/wakakuu.py +71 -31
- taste/store.py +222 -81
backend/app/routers/discover.py
CHANGED
|
@@ -10,6 +10,7 @@ from fastapi import APIRouter, Body
|
|
| 10 |
|
| 11 |
from backend.app.deps import get_store, get_engine, get_config
|
| 12 |
from backend.app.schemas import ProductOut
|
|
|
|
| 13 |
|
| 14 |
router = APIRouter(prefix="/api/discover", tags=["discover"])
|
| 15 |
|
|
@@ -69,7 +70,7 @@ def get_next_products(count: int = 10):
|
|
| 69 |
PARTITION BY brand, name, store ORDER BY score DESC
|
| 70 |
) AS rn
|
| 71 |
FROM products
|
| 72 |
-
WHERE image_url != '' AND score > 0
|
| 73 |
) WHERE rn = 1
|
| 74 |
ORDER BY score DESC
|
| 75 |
""").fetchall()
|
|
@@ -77,17 +78,7 @@ def get_next_products(count: int = 10):
|
|
| 77 |
results = []
|
| 78 |
for r in rows:
|
| 79 |
if r["url"] not in rated_urls:
|
| 80 |
-
|
| 81 |
-
raw = d.pop("image_urls", "[]")
|
| 82 |
-
try:
|
| 83 |
-
image_urls = json.loads(raw) if isinstance(raw, str) else raw
|
| 84 |
-
except (json.JSONDecodeError, TypeError):
|
| 85 |
-
image_urls = []
|
| 86 |
-
d.pop("image_path", None)
|
| 87 |
-
d.pop("fabric", None)
|
| 88 |
-
d.pop("created_at", None)
|
| 89 |
-
d.pop("rn", None)
|
| 90 |
-
results.append(ProductOut(**d, image_urls=image_urls if isinstance(image_urls, list) else []))
|
| 91 |
if len(results) >= count:
|
| 92 |
break
|
| 93 |
|
|
@@ -156,18 +147,7 @@ def undo_last_rating():
|
|
| 156 |
|
| 157 |
# Get the undone product to return to frontend
|
| 158 |
product_row = conn.execute("SELECT * FROM products WHERE url = ?", (url,)).fetchone()
|
| 159 |
-
product = None
|
| 160 |
-
if product_row:
|
| 161 |
-
d = dict(product_row)
|
| 162 |
-
raw = d.pop("image_urls", "[]")
|
| 163 |
-
try:
|
| 164 |
-
image_urls = json.loads(raw) if isinstance(raw, str) else raw
|
| 165 |
-
except (json.JSONDecodeError, TypeError):
|
| 166 |
-
image_urls = []
|
| 167 |
-
d.pop("image_path", None)
|
| 168 |
-
d.pop("fabric", None)
|
| 169 |
-
d.pop("created_at", None)
|
| 170 |
-
product = ProductOut(**d, image_urls=image_urls if isinstance(image_urls, list) else [])
|
| 171 |
|
| 172 |
return {"ok": True, "product": product, "stats": _get_stats(conn)}
|
| 173 |
|
|
|
|
| 10 |
|
| 11 |
from backend.app.deps import get_store, get_engine, get_config
|
| 12 |
from backend.app.schemas import ProductOut
|
| 13 |
+
from backend.app.routers.products import _row_to_product
|
| 14 |
|
| 15 |
router = APIRouter(prefix="/api/discover", tags=["discover"])
|
| 16 |
|
|
|
|
| 70 |
PARTITION BY brand, name, store ORDER BY score DESC
|
| 71 |
) AS rn
|
| 72 |
FROM products
|
| 73 |
+
WHERE image_url != '' AND score IS NOT NULL AND score > 0
|
| 74 |
) WHERE rn = 1
|
| 75 |
ORDER BY score DESC
|
| 76 |
""").fetchall()
|
|
|
|
| 78 |
results = []
|
| 79 |
for r in rows:
|
| 80 |
if r["url"] not in rated_urls:
|
| 81 |
+
results.append(_row_to_product(r))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
if len(results) >= count:
|
| 83 |
break
|
| 84 |
|
|
|
|
| 147 |
|
| 148 |
# Get the undone product to return to frontend
|
| 149 |
product_row = conn.execute("SELECT * FROM products WHERE url = ?", (url,)).fetchone()
|
| 150 |
+
product = _row_to_product(product_row) if product_row else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
return {"ok": True, "product": product, "stats": _get_stats(conn)}
|
| 153 |
|
backend/app/routers/products.py
CHANGED
|
@@ -9,22 +9,32 @@ from backend.app.schemas import ProductOut, ProductsResponse
|
|
| 9 |
|
| 10 |
router = APIRouter(prefix="/api/products", tags=["products"])
|
| 11 |
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
def _row_to_product(row) -> ProductOut:
|
| 14 |
-
"""Convert a DB row to ProductOut, parsing
|
| 15 |
d = dict(row)
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
|
| 30 |
@router.get("", response_model=ProductsResponse)
|
|
@@ -33,11 +43,12 @@ def list_products(
|
|
| 33 |
page_size: int = Query(48, ge=1, le=200),
|
| 34 |
store: str | None = None,
|
| 35 |
brand: str | None = None,
|
| 36 |
-
min_score: float = 0
|
| 37 |
min_price: float | None = None,
|
| 38 |
max_price: float | None = None,
|
| 39 |
sort: str = "score",
|
| 40 |
search: str | None = None,
|
|
|
|
| 41 |
):
|
| 42 |
db = get_store()
|
| 43 |
conn = db.conn
|
|
@@ -52,7 +63,7 @@ def list_products(
|
|
| 52 |
)
|
| 53 |
""")
|
| 54 |
|
| 55 |
-
where = ["score >= ?", "url NOT IN (SELECT url FROM discover_ratings)"]
|
| 56 |
params: list = [min_score]
|
| 57 |
|
| 58 |
if store:
|
|
@@ -70,6 +81,9 @@ def list_products(
|
|
| 70 |
if search:
|
| 71 |
where.append("(brand LIKE ? OR name LIKE ?)")
|
| 72 |
params.extend([f"%{search}%", f"%{search}%"])
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
where_sql = " AND ".join(where)
|
| 75 |
|
|
@@ -81,7 +95,7 @@ def list_products(
|
|
| 81 |
"-price": "price_nok DESC",
|
| 82 |
"price_desc": "price_nok DESC",
|
| 83 |
"name": "name ASC",
|
| 84 |
-
"newest": "
|
| 85 |
}.get(sort, "score DESC")
|
| 86 |
|
| 87 |
dedup_sql = f"""
|
|
@@ -122,11 +136,10 @@ def list_stores():
|
|
| 122 |
|
| 123 |
@router.get("/brands")
|
| 124 |
def list_brands():
|
| 125 |
-
"""Top brands by product count."""
|
| 126 |
db = get_store()
|
| 127 |
rows = db.conn.execute("""
|
| 128 |
SELECT brand, COUNT(*) as cnt FROM products
|
| 129 |
-
WHERE brand != '' AND score
|
| 130 |
GROUP BY brand ORDER BY cnt DESC LIMIT 100
|
| 131 |
""").fetchall()
|
| 132 |
return [{"name": r["brand"], "count": r["cnt"]} for r in rows]
|
|
@@ -134,10 +147,9 @@ def list_brands():
|
|
| 134 |
|
| 135 |
@router.get("/price-range")
|
| 136 |
def price_range():
|
| 137 |
-
"""Min and max price across all products."""
|
| 138 |
db = get_store()
|
| 139 |
row = db.conn.execute("""
|
| 140 |
SELECT MIN(price_nok) as min_price, MAX(price_nok) as max_price
|
| 141 |
-
FROM products WHERE price_nok > 0 AND score
|
| 142 |
""").fetchone()
|
| 143 |
return {"min": row["min_price"] or 0, "max": row["max_price"] or 0}
|
|
|
|
| 9 |
|
| 10 |
router = APIRouter(prefix="/api/products", tags=["products"])
|
| 11 |
|
| 12 |
+
# Fields to drop from DB rows before passing to ProductOut
|
| 13 |
+
_DROP_FIELDS = {"image_path", "fabric", "created_at", "first_seen_at", "last_seen_at", "updated_at", "rn"}
|
| 14 |
+
|
| 15 |
|
| 16 |
def _row_to_product(row) -> ProductOut:
|
| 17 |
+
"""Convert a DB row to ProductOut, parsing JSON fields."""
|
| 18 |
d = dict(row)
|
| 19 |
+
|
| 20 |
+
# Parse JSON array fields
|
| 21 |
+
for field in ("image_urls", "sizes"):
|
| 22 |
+
raw = d.pop(field, "[]")
|
| 23 |
+
try:
|
| 24 |
+
parsed = json.loads(raw) if isinstance(raw, str) else raw
|
| 25 |
+
d[field] = parsed if isinstance(parsed, list) else []
|
| 26 |
+
except (json.JSONDecodeError, TypeError):
|
| 27 |
+
d[field] = []
|
| 28 |
+
|
| 29 |
+
# Drop fields not in ProductOut
|
| 30 |
+
for f in _DROP_FIELDS:
|
| 31 |
+
d.pop(f, None)
|
| 32 |
+
|
| 33 |
+
# Handle nullable score — default to 0 for display
|
| 34 |
+
if d.get("score") is None:
|
| 35 |
+
d["score"] = 0
|
| 36 |
+
|
| 37 |
+
return ProductOut(**d)
|
| 38 |
|
| 39 |
|
| 40 |
@router.get("", response_model=ProductsResponse)
|
|
|
|
| 43 |
page_size: int = Query(48, ge=1, le=200),
|
| 44 |
store: str | None = None,
|
| 45 |
brand: str | None = None,
|
| 46 |
+
min_score: float = 0,
|
| 47 |
min_price: float | None = None,
|
| 48 |
max_price: float | None = None,
|
| 49 |
sort: str = "score",
|
| 50 |
search: str | None = None,
|
| 51 |
+
in_stock: bool | None = None,
|
| 52 |
):
|
| 53 |
db = get_store()
|
| 54 |
conn = db.conn
|
|
|
|
| 63 |
)
|
| 64 |
""")
|
| 65 |
|
| 66 |
+
where = ["(score IS NOT NULL AND score >= ?)", "url NOT IN (SELECT url FROM discover_ratings)"]
|
| 67 |
params: list = [min_score]
|
| 68 |
|
| 69 |
if store:
|
|
|
|
| 81 |
if search:
|
| 82 |
where.append("(brand LIKE ? OR name LIKE ?)")
|
| 83 |
params.extend([f"%{search}%", f"%{search}%"])
|
| 84 |
+
if in_stock is not None:
|
| 85 |
+
where.append("in_stock = ?")
|
| 86 |
+
params.append(int(in_stock))
|
| 87 |
|
| 88 |
where_sql = " AND ".join(where)
|
| 89 |
|
|
|
|
| 95 |
"-price": "price_nok DESC",
|
| 96 |
"price_desc": "price_nok DESC",
|
| 97 |
"name": "name ASC",
|
| 98 |
+
"newest": "first_seen_at DESC",
|
| 99 |
}.get(sort, "score DESC")
|
| 100 |
|
| 101 |
dedup_sql = f"""
|
|
|
|
| 136 |
|
| 137 |
@router.get("/brands")
|
| 138 |
def list_brands():
|
|
|
|
| 139 |
db = get_store()
|
| 140 |
rows = db.conn.execute("""
|
| 141 |
SELECT brand, COUNT(*) as cnt FROM products
|
| 142 |
+
WHERE brand != '' AND score IS NOT NULL
|
| 143 |
GROUP BY brand ORDER BY cnt DESC LIMIT 100
|
| 144 |
""").fetchall()
|
| 145 |
return [{"name": r["brand"], "count": r["cnt"]} for r in rows]
|
|
|
|
| 147 |
|
| 148 |
@router.get("/price-range")
|
| 149 |
def price_range():
|
|
|
|
| 150 |
db = get_store()
|
| 151 |
row = db.conn.execute("""
|
| 152 |
SELECT MIN(price_nok) as min_price, MAX(price_nok) as max_price
|
| 153 |
+
FROM products WHERE price_nok > 0 AND score IS NOT NULL
|
| 154 |
""").fetchone()
|
| 155 |
return {"min": row["min_price"] or 0, "max": row["max_price"] or 0}
|
backend/app/schemas.py
CHANGED
|
@@ -9,10 +9,19 @@ class ProductOut(BaseModel):
|
|
| 9 |
image_urls: list[str] = []
|
| 10 |
brand: str
|
| 11 |
name: str
|
|
|
|
|
|
|
|
|
|
| 12 |
price_text: str
|
| 13 |
price_nok: float
|
|
|
|
|
|
|
|
|
|
| 14 |
store: str
|
| 15 |
-
score: float
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
class ProductsResponse(BaseModel):
|
|
|
|
| 9 |
image_urls: list[str] = []
|
| 10 |
brand: str
|
| 11 |
name: str
|
| 12 |
+
color: str = ""
|
| 13 |
+
material: str = ""
|
| 14 |
+
category: str = ""
|
| 15 |
price_text: str
|
| 16 |
price_nok: float
|
| 17 |
+
original_price_nok: float = 0
|
| 18 |
+
currency: str = "NOK"
|
| 19 |
+
on_sale: bool = False
|
| 20 |
store: str
|
| 21 |
+
score: float | None = None
|
| 22 |
+
in_stock: bool = True
|
| 23 |
+
sizes: list[str] = []
|
| 24 |
+
external_id: str = ""
|
| 25 |
|
| 26 |
|
| 27 |
class ProductsResponse(BaseModel):
|
frontend/src/index.css
CHANGED
|
@@ -318,6 +318,7 @@ select:focus {
|
|
| 318 |
}
|
| 319 |
|
| 320 |
.product-card {
|
|
|
|
| 321 |
background: var(--card);
|
| 322 |
border: 1px solid var(--border);
|
| 323 |
border-radius: var(--radius);
|
|
@@ -425,6 +426,51 @@ select:focus {
|
|
| 425 |
color: var(--accent);
|
| 426 |
}
|
| 427 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
/* ---------- Pagination ---------- */
|
| 429 |
.pagination {
|
| 430 |
display: flex;
|
|
|
|
| 318 |
}
|
| 319 |
|
| 320 |
.product-card {
|
| 321 |
+
position: relative;
|
| 322 |
background: var(--card);
|
| 323 |
border: 1px solid var(--border);
|
| 324 |
border-radius: var(--radius);
|
|
|
|
| 426 |
color: var(--accent);
|
| 427 |
}
|
| 428 |
|
| 429 |
+
/* ---------- Product card badges ---------- */
|
| 430 |
+
.product-card-sale-badge {
|
| 431 |
+
position: absolute;
|
| 432 |
+
top: 8px;
|
| 433 |
+
left: 8px;
|
| 434 |
+
background: #ef4444;
|
| 435 |
+
color: #fff;
|
| 436 |
+
font-size: 11px;
|
| 437 |
+
font-weight: 600;
|
| 438 |
+
padding: 2px 8px;
|
| 439 |
+
border-radius: 4px;
|
| 440 |
+
z-index: 2;
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
.product-card-oos-badge {
|
| 444 |
+
position: absolute;
|
| 445 |
+
top: 8px;
|
| 446 |
+
left: 8px;
|
| 447 |
+
background: rgba(0,0,0,0.7);
|
| 448 |
+
color: #fff;
|
| 449 |
+
font-size: 11px;
|
| 450 |
+
font-weight: 600;
|
| 451 |
+
padding: 2px 8px;
|
| 452 |
+
border-radius: 4px;
|
| 453 |
+
z-index: 2;
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
.product-card-color {
|
| 457 |
+
font-size: 12px;
|
| 458 |
+
color: var(--text-muted);
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
.product-card-original-price {
|
| 462 |
+
text-decoration: line-through;
|
| 463 |
+
color: var(--text-muted);
|
| 464 |
+
margin-right: 6px;
|
| 465 |
+
font-size: 12px;
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
.product-card .product-card-price {
|
| 469 |
+
display: flex;
|
| 470 |
+
align-items: baseline;
|
| 471 |
+
gap: 0;
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
/* ---------- Pagination ---------- */
|
| 475 |
.pagination {
|
| 476 |
display: flex;
|
frontend/src/pages/BrowsePage.tsx
CHANGED
|
@@ -40,11 +40,19 @@ function ProductCard({ product: p }: { product: Product }) {
|
|
| 40 |
</div>
|
| 41 |
)}
|
| 42 |
</div>
|
|
|
|
|
|
|
| 43 |
<div className="product-card-body">
|
| 44 |
-
<span className="product-card-brand">{p.brand}</span>
|
| 45 |
<span className="product-card-name">{p.name}</span>
|
|
|
|
| 46 |
<div className="product-card-footer">
|
| 47 |
-
<span className="product-card-price">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
<span className={scoreBadgeClass(matchPct)}>{matchPct}%</span>
|
| 49 |
</div>
|
| 50 |
</div>
|
|
|
|
| 40 |
</div>
|
| 41 |
)}
|
| 42 |
</div>
|
| 43 |
+
{p.on_sale && <div className="product-card-sale-badge">Sale</div>}
|
| 44 |
+
{!p.in_stock && <div className="product-card-oos-badge">Sold Out</div>}
|
| 45 |
<div className="product-card-body">
|
| 46 |
+
<span className="product-card-brand">{p.brand || p.store}</span>
|
| 47 |
<span className="product-card-name">{p.name}</span>
|
| 48 |
+
{p.color && <span className="product-card-color">{p.color}</span>}
|
| 49 |
<div className="product-card-footer">
|
| 50 |
+
<span className="product-card-price">
|
| 51 |
+
{p.on_sale && p.original_price_nok > 0 && (
|
| 52 |
+
<span className="product-card-original-price">{p.original_price_nok} kr</span>
|
| 53 |
+
)}
|
| 54 |
+
{p.price_text || `${p.price_nok} kr`}
|
| 55 |
+
</span>
|
| 56 |
<span className={scoreBadgeClass(matchPct)}>{matchPct}%</span>
|
| 57 |
</div>
|
| 58 |
</div>
|
frontend/src/types.ts
CHANGED
|
@@ -1,13 +1,22 @@
|
|
| 1 |
export interface Product {
|
| 2 |
name: string;
|
| 3 |
brand: string;
|
|
|
|
|
|
|
|
|
|
| 4 |
price_text: string;
|
| 5 |
price_nok: number;
|
|
|
|
|
|
|
|
|
|
| 6 |
image_url: string;
|
| 7 |
image_urls: string[];
|
| 8 |
url: string;
|
| 9 |
store: string;
|
| 10 |
score: number;
|
|
|
|
|
|
|
|
|
|
| 11 |
}
|
| 12 |
|
| 13 |
export interface ProductsResponse {
|
|
|
|
| 1 |
export interface Product {
|
| 2 |
name: string;
|
| 3 |
brand: string;
|
| 4 |
+
color: string;
|
| 5 |
+
material: string;
|
| 6 |
+
category: string;
|
| 7 |
price_text: string;
|
| 8 |
price_nok: number;
|
| 9 |
+
original_price_nok: number;
|
| 10 |
+
currency: string;
|
| 11 |
+
on_sale: boolean;
|
| 12 |
image_url: string;
|
| 13 |
image_urls: string[];
|
| 14 |
url: string;
|
| 15 |
store: string;
|
| 16 |
score: number;
|
| 17 |
+
in_stock: boolean;
|
| 18 |
+
sizes: string[];
|
| 19 |
+
external_id: string;
|
| 20 |
}
|
| 21 |
|
| 22 |
export interface ProductsResponse {
|
taste/models.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
"""Shared data models."""
|
| 2 |
|
|
|
|
| 3 |
from dataclasses import dataclass, field
|
| 4 |
from pathlib import Path
|
| 5 |
|
|
@@ -7,54 +8,81 @@ from pathlib import Path
|
|
| 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 |
-
|
|
|
|
|
|
|
| 15 |
price_nok: float = 0.0
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def to_dict(self) -> dict:
|
| 22 |
-
import json
|
| 23 |
return {
|
| 24 |
"url": self.url,
|
| 25 |
-
"
|
| 26 |
-
"
|
| 27 |
"brand": self.brand,
|
| 28 |
"name": self.name,
|
| 29 |
-
"
|
|
|
|
|
|
|
| 30 |
"price_nok": self.price_nok,
|
| 31 |
-
"
|
| 32 |
-
"
|
| 33 |
-
"
|
|
|
|
|
|
|
| 34 |
"image_urls": json.dumps(self.image_urls) if self.image_urls else "[]",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
}
|
| 36 |
|
| 37 |
@staticmethod
|
| 38 |
def from_dict(d: dict) -> "Product":
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
return Product(
|
| 49 |
url=d.get("url", ""),
|
| 50 |
-
|
| 51 |
-
|
| 52 |
brand=d.get("brand", ""),
|
| 53 |
name=d.get("name", ""),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
price_text=d.get("price_text", ""),
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
| 60 |
)
|
|
|
|
| 1 |
"""Shared data models."""
|
| 2 |
|
| 3 |
+
import json
|
| 4 |
from dataclasses import dataclass, field
|
| 5 |
from pathlib import Path
|
| 6 |
|
|
|
|
| 8 |
@dataclass
|
| 9 |
class Product:
|
| 10 |
url: str
|
| 11 |
+
image_url: str = ""
|
| 12 |
+
image_urls: list[str] = field(default_factory=list)
|
| 13 |
image_path: Path | None = None
|
| 14 |
+
external_id: str = ""
|
| 15 |
+
store: str = ""
|
| 16 |
brand: str = ""
|
| 17 |
name: str = ""
|
| 18 |
+
color: str = ""
|
| 19 |
+
material: str = ""
|
| 20 |
+
category: str = ""
|
| 21 |
price_nok: float = 0.0
|
| 22 |
+
original_price_nok: float = 0.0
|
| 23 |
+
price_text: str = ""
|
| 24 |
+
currency: str = "NOK"
|
| 25 |
+
on_sale: bool = False
|
| 26 |
+
in_stock: bool = True
|
| 27 |
+
sizes: list[str] = field(default_factory=list)
|
| 28 |
+
score: float | None = None
|
| 29 |
|
| 30 |
def to_dict(self) -> dict:
|
|
|
|
| 31 |
return {
|
| 32 |
"url": self.url,
|
| 33 |
+
"external_id": self.external_id,
|
| 34 |
+
"store": self.store,
|
| 35 |
"brand": self.brand,
|
| 36 |
"name": self.name,
|
| 37 |
+
"color": self.color,
|
| 38 |
+
"material": self.material,
|
| 39 |
+
"category": self.category,
|
| 40 |
"price_nok": self.price_nok,
|
| 41 |
+
"original_price_nok": self.original_price_nok,
|
| 42 |
+
"price_text": self.price_text,
|
| 43 |
+
"currency": self.currency,
|
| 44 |
+
"on_sale": int(self.on_sale),
|
| 45 |
+
"image_url": self.image_url,
|
| 46 |
"image_urls": json.dumps(self.image_urls) if self.image_urls else "[]",
|
| 47 |
+
"image_path": str(self.image_path) if self.image_path else "",
|
| 48 |
+
"in_stock": int(self.in_stock),
|
| 49 |
+
"sizes": json.dumps(self.sizes) if self.sizes else "[]",
|
| 50 |
+
"score": self.score,
|
| 51 |
}
|
| 52 |
|
| 53 |
@staticmethod
|
| 54 |
def from_dict(d: dict) -> "Product":
|
| 55 |
+
def _parse_json_list(val, default=None):
|
| 56 |
+
if default is None:
|
| 57 |
+
default = []
|
| 58 |
+
if isinstance(val, list):
|
| 59 |
+
return val
|
| 60 |
+
if isinstance(val, str):
|
| 61 |
+
try:
|
| 62 |
+
parsed = json.loads(val)
|
| 63 |
+
return parsed if isinstance(parsed, list) else default
|
| 64 |
+
except (json.JSONDecodeError, TypeError):
|
| 65 |
+
return default
|
| 66 |
+
return default
|
| 67 |
+
|
| 68 |
return Product(
|
| 69 |
url=d.get("url", ""),
|
| 70 |
+
external_id=d.get("external_id", ""),
|
| 71 |
+
store=d.get("store", ""),
|
| 72 |
brand=d.get("brand", ""),
|
| 73 |
name=d.get("name", ""),
|
| 74 |
+
color=d.get("color", ""),
|
| 75 |
+
material=d.get("material", ""),
|
| 76 |
+
category=d.get("category", ""),
|
| 77 |
+
price_nok=float(d.get("price_nok", 0) or 0),
|
| 78 |
+
original_price_nok=float(d.get("original_price_nok", 0) or 0),
|
| 79 |
price_text=d.get("price_text", ""),
|
| 80 |
+
currency=d.get("currency", "NOK"),
|
| 81 |
+
on_sale=bool(d.get("on_sale", False)),
|
| 82 |
+
image_url=d.get("image_url", ""),
|
| 83 |
+
image_urls=_parse_json_list(d.get("image_urls", "[]")),
|
| 84 |
+
image_path=Path(d["image_path"]) if d.get("image_path") else None,
|
| 85 |
+
in_stock=bool(d.get("in_stock", True)),
|
| 86 |
+
sizes=_parse_json_list(d.get("sizes", "[]")),
|
| 87 |
+
score=d.get("score"),
|
| 88 |
)
|
taste/scrapers/api/boozt.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Boozt scraper — internal products API."""
|
| 2 |
|
| 3 |
import html as _html
|
| 4 |
import json as _json
|
|
@@ -6,7 +6,6 @@ import re
|
|
| 6 |
|
| 7 |
import httpx
|
| 8 |
|
| 9 |
-
from taste.config import StoreConfig
|
| 10 |
from taste.scrapers.base import BaseScraper
|
| 11 |
|
| 12 |
|
|
@@ -15,7 +14,7 @@ class BooztScraper(BaseScraper):
|
|
| 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", "
|
| 19 |
|
| 20 |
products = []
|
| 21 |
seen_urls = set()
|
|
@@ -37,7 +36,6 @@ class BooztScraper(BaseScraper):
|
|
| 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)
|
|
@@ -48,7 +46,7 @@ class BooztScraper(BaseScraper):
|
|
| 48 |
|
| 49 |
print(f" Boozt: {cat.split('/')[-1]} navId={nav_id}", flush=True)
|
| 50 |
|
| 51 |
-
# Step 2: Fetch products
|
| 52 |
try:
|
| 53 |
api_url = f"{base_url}/no/no/api/navigation/{nav_id}/products?limit=500"
|
| 54 |
if material:
|
|
@@ -71,23 +69,49 @@ class BooztScraper(BaseScraper):
|
|
| 71 |
continue
|
| 72 |
seen_urls.add(prod_url)
|
| 73 |
|
| 74 |
-
|
| 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_urls = [m.get("url", "") for m in media if m.get("url")]
|
| 81 |
image_url = image_urls[0] if image_urls else ""
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
products.append({
|
| 84 |
"url": prod_url,
|
|
|
|
| 85 |
"image_url": image_url,
|
| 86 |
"image_urls": image_urls,
|
| 87 |
"brand": card.get("brand_name", ""),
|
| 88 |
"name": card.get("display_name", ""),
|
|
|
|
|
|
|
| 89 |
"price_nok": price_val,
|
| 90 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
"store": "Boozt",
|
| 92 |
})
|
| 93 |
new_count += 1
|
|
@@ -100,6 +124,11 @@ class BooztScraper(BaseScraper):
|
|
| 100 |
|
| 101 |
@staticmethod
|
| 102 |
def _extract_nav_id(html_text: str) -> str | None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
# Try React on Rails props
|
| 104 |
m = re.search(
|
| 105 |
r'data-component-name="ListingPageSSR"[^>]*data-props="([^"]*)"',
|
|
|
|
| 1 |
+
"""Boozt scraper — internal products API with full field extraction."""
|
| 2 |
|
| 3 |
import html as _html
|
| 4 |
import json as _json
|
|
|
|
| 6 |
|
| 7 |
import httpx
|
| 8 |
|
|
|
|
| 9 |
from taste.scrapers.base import BaseScraper
|
| 10 |
|
| 11 |
|
|
|
|
| 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.boozt.com"
|
| 17 |
+
material = self.config.extra.get("material_filter", "")
|
| 18 |
|
| 19 |
products = []
|
| 20 |
seen_urls = set()
|
|
|
|
| 36 |
if html_resp.status_code != 200:
|
| 37 |
print(f" Boozt: {cat} returned {html_resp.status_code}", flush=True)
|
| 38 |
continue
|
|
|
|
| 39 |
nav_id = self._extract_nav_id(html_resp.text)
|
| 40 |
if not nav_id:
|
| 41 |
print(f" Boozt: no navigationId for {cat}", flush=True)
|
|
|
|
| 46 |
|
| 47 |
print(f" Boozt: {cat.split('/')[-1]} navId={nav_id}", flush=True)
|
| 48 |
|
| 49 |
+
# Step 2: Fetch products
|
| 50 |
try:
|
| 51 |
api_url = f"{base_url}/no/no/api/navigation/{nav_id}/products?limit=500"
|
| 52 |
if material:
|
|
|
|
| 69 |
continue
|
| 70 |
seen_urls.add(prod_url)
|
| 71 |
|
| 72 |
+
# Images — collect all from media array
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
media = card.get("media", [])
|
| 74 |
image_urls = [m.get("url", "") for m in media if m.get("url")]
|
| 75 |
image_url = image_urls[0] if image_urls else ""
|
| 76 |
|
| 77 |
+
# Pricing
|
| 78 |
+
prices = card.get("prices", {})
|
| 79 |
+
base_price = prices.get("base", {})
|
| 80 |
+
sale_price = prices.get("sale") or prices.get("optin")
|
| 81 |
+
price_str = base_price.get("price", "0")
|
| 82 |
+
price_val = float(re.sub(r"[^\d.]", "", str(price_str)) or 0)
|
| 83 |
+
|
| 84 |
+
original_price = price_val
|
| 85 |
+
on_sale = False
|
| 86 |
+
if sale_price:
|
| 87 |
+
sale_str = sale_price.get("price", "0")
|
| 88 |
+
sale_val = float(re.sub(r"[^\d.]", "", str(sale_str)) or 0)
|
| 89 |
+
if sale_val > 0 and sale_val < price_val:
|
| 90 |
+
original_price = price_val
|
| 91 |
+
price_val = sale_val
|
| 92 |
+
on_sale = True
|
| 93 |
+
|
| 94 |
+
# Stock, sizes, color
|
| 95 |
+
in_stock = card.get("in_stock", True)
|
| 96 |
+
sizes = card.get("sizes", [])
|
| 97 |
+
color = card.get("color_name", "")
|
| 98 |
+
|
| 99 |
products.append({
|
| 100 |
"url": prod_url,
|
| 101 |
+
"external_id": str(card.get("id", card.get("ean_id", ""))),
|
| 102 |
"image_url": image_url,
|
| 103 |
"image_urls": image_urls,
|
| 104 |
"brand": card.get("brand_name", ""),
|
| 105 |
"name": card.get("display_name", ""),
|
| 106 |
+
"color": color,
|
| 107 |
+
"category": cat.split("/")[-1] if "/" in cat else "",
|
| 108 |
"price_nok": price_val,
|
| 109 |
+
"original_price_nok": original_price if on_sale else 0,
|
| 110 |
+
"price_text": base_price.get("formatted_price", f"{price_val:.0f} kr"),
|
| 111 |
+
"currency": "NOK",
|
| 112 |
+
"on_sale": on_sale,
|
| 113 |
+
"in_stock": in_stock,
|
| 114 |
+
"sizes": sizes if isinstance(sizes, list) else [],
|
| 115 |
"store": "Boozt",
|
| 116 |
})
|
| 117 |
new_count += 1
|
|
|
|
| 124 |
|
| 125 |
@staticmethod
|
| 126 |
def _extract_nav_id(html_text: str) -> str | None:
|
| 127 |
+
# Try GA tracking variable first
|
| 128 |
+
m = re.search(r'App\.Config\.GaTrackingPage\.nav_id\s*=\s*(\d+)', html_text)
|
| 129 |
+
if m:
|
| 130 |
+
return m.group(1)
|
| 131 |
+
|
| 132 |
# Try React on Rails props
|
| 133 |
m = re.search(
|
| 134 |
r'data-component-name="ListingPageSSR"[^>]*data-props="([^"]*)"',
|
taste/scrapers/api/miinto.py
CHANGED
|
@@ -1,11 +1,10 @@
|
|
| 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 |
|
|
@@ -52,31 +51,52 @@ class MiintoScraper(BaseScraper):
|
|
| 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 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
products.append({
|
| 73 |
"url": prod_url,
|
|
|
|
| 74 |
"image_url": image_url,
|
| 75 |
-
"image_urls":
|
| 76 |
"brand": item.get("brand", ""),
|
| 77 |
"name": item.get("title", item.get("name", "")),
|
|
|
|
|
|
|
|
|
|
| 78 |
"price_nok": price_nok,
|
|
|
|
| 79 |
"price_text": f"{price_nok:.0f} kr" if price_nok else "",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
"store": "Miinto",
|
| 81 |
})
|
| 82 |
new_count += 1
|
|
|
|
| 1 |
+
"""Miinto scraper — SSR preloaded state extraction with full field capture."""
|
| 2 |
|
| 3 |
import json
|
| 4 |
import re
|
| 5 |
|
| 6 |
import httpx
|
| 7 |
|
|
|
|
| 8 |
from taste.scrapers.base import BaseScraper
|
| 9 |
|
| 10 |
|
|
|
|
| 51 |
continue
|
| 52 |
seen_urls.add(prod_url)
|
| 53 |
|
| 54 |
+
# Price (stored in ore/cents — divide by 100)
|
| 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 |
+
original_raw = price_data.get("originalPrice", 0)
|
| 59 |
else:
|
| 60 |
price_raw = price_data
|
| 61 |
+
original_raw = 0
|
| 62 |
price_nok = float(price_raw or 0) / 100
|
| 63 |
+
original_nok = float(original_raw or 0) / 100
|
| 64 |
|
| 65 |
+
on_sale = item.get("isOnSale", False)
|
| 66 |
+
discount = item.get("discountPercent", 0)
|
| 67 |
+
|
| 68 |
+
# Image — PLP has single photo
|
| 69 |
photo = item.get("photo", {})
|
| 70 |
image_url = photo.get("url", "") if isinstance(photo, dict) else str(photo)
|
| 71 |
+
|
| 72 |
+
# Sizes
|
| 73 |
+
sizes = item.get("sizes", [])
|
| 74 |
+
if isinstance(sizes, list):
|
| 75 |
+
sizes = [s if isinstance(s, str) else str(s) for s in sizes]
|
| 76 |
+
|
| 77 |
+
# Category
|
| 78 |
+
category = item.get("category", "")
|
| 79 |
+
|
| 80 |
+
# External ID (UUID)
|
| 81 |
+
external_id = item.get("id", "")
|
| 82 |
|
| 83 |
products.append({
|
| 84 |
"url": prod_url,
|
| 85 |
+
"external_id": str(external_id),
|
| 86 |
"image_url": image_url,
|
| 87 |
+
"image_urls": [image_url] if image_url else [],
|
| 88 |
"brand": item.get("brand", ""),
|
| 89 |
"name": item.get("title", item.get("name", "")),
|
| 90 |
+
"color": "", # not available on PLP
|
| 91 |
+
"material": "", # only on PDP
|
| 92 |
+
"category": category,
|
| 93 |
"price_nok": price_nok,
|
| 94 |
+
"original_price_nok": original_nok if on_sale else 0,
|
| 95 |
"price_text": f"{price_nok:.0f} kr" if price_nok else "",
|
| 96 |
+
"currency": "NOK",
|
| 97 |
+
"on_sale": on_sale,
|
| 98 |
+
"in_stock": True, # PLP only shows in-stock products
|
| 99 |
+
"sizes": sizes,
|
| 100 |
"store": "Miinto",
|
| 101 |
})
|
| 102 |
new_count += 1
|
taste/scrapers/api/nakd.py
CHANGED
|
@@ -1,11 +1,10 @@
|
|
| 1 |
-
"""NA-KD scraper — SSR
|
| 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 |
|
|
@@ -28,68 +27,46 @@ class NakdScraper(BaseScraper):
|
|
| 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 |
-
|
| 34 |
-
resp = client.get(url)
|
| 35 |
if resp.status_code != 200:
|
| 36 |
break
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 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 =
|
| 59 |
-
|
| 60 |
-
if prod_url in seen_urls or not prod_url:
|
| 61 |
continue
|
| 62 |
-
seen_urls.add(
|
| 63 |
-
|
| 64 |
-
raw_image = product.get("image", "")
|
| 65 |
-
if isinstance(raw_image, list):
|
| 66 |
-
image_urls = [u for u in raw_image if u]
|
| 67 |
-
image = image_urls[0] if image_urls else ""
|
| 68 |
-
else:
|
| 69 |
-
image = raw_image
|
| 70 |
-
image_urls = [image] if image else []
|
| 71 |
-
|
| 72 |
-
offers = product.get("offers", {})
|
| 73 |
-
if isinstance(offers, list):
|
| 74 |
-
offers = offers[0] if offers else {}
|
| 75 |
-
price_val = float(offers.get("price", 0))
|
| 76 |
-
|
| 77 |
-
brand = product.get("brand", "")
|
| 78 |
-
if isinstance(brand, dict):
|
| 79 |
-
brand = brand.get("name", "")
|
| 80 |
-
|
| 81 |
-
products.append({
|
| 82 |
-
"url": prod_url,
|
| 83 |
-
"image_url": image,
|
| 84 |
-
"image_urls": image_urls,
|
| 85 |
-
"brand": str(brand),
|
| 86 |
-
"name": product.get("name", ""),
|
| 87 |
-
"price_nok": price_val,
|
| 88 |
-
"price_text": f"{price_val:.0f} kr" if price_val else "",
|
| 89 |
-
"store": "NA-KD",
|
| 90 |
-
})
|
| 91 |
new_count += 1
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
print(f" NA-KD: {cat.split('/')[-1]} page {page_num}, +{new_count}, {len(products)} total", flush=True)
|
| 94 |
|
| 95 |
if new_count == 0:
|
|
@@ -97,3 +74,164 @@ class NakdScraper(BaseScraper):
|
|
| 97 |
page_num += 1
|
| 98 |
|
| 99 |
return products
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""NA-KD scraper — window.CURRENT_PAGE SSR state extraction."""
|
| 2 |
|
| 3 |
import json
|
| 4 |
import re
|
| 5 |
|
| 6 |
import httpx
|
| 7 |
|
|
|
|
| 8 |
from taste.scrapers.base import BaseScraper
|
| 9 |
|
| 10 |
|
|
|
|
| 27 |
for cat in categories:
|
| 28 |
cat_url = cat if cat.startswith("http") else f"{base_url}{cat}"
|
| 29 |
page_num = 1
|
| 30 |
+
next_url = cat_url
|
| 31 |
|
| 32 |
+
while len(products) < max_products and next_url:
|
| 33 |
+
resp = client.get(next_url)
|
|
|
|
| 34 |
if resp.status_code != 200:
|
| 35 |
break
|
| 36 |
|
| 37 |
+
# Try CURRENT_PAGE first (newer NA-KD SSR)
|
| 38 |
+
state = self._extract_current_page(resp.text)
|
| 39 |
+
if state:
|
| 40 |
+
prods_data = state.get("products", {})
|
| 41 |
+
items = prods_data.get("items", prods_data.get("products", []))
|
| 42 |
+
if isinstance(prods_data, list):
|
| 43 |
+
items = prods_data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
new_count = 0
|
| 46 |
for item in items:
|
| 47 |
+
product = self._parse_current_page_item(item, base_url)
|
| 48 |
+
if not product or product["url"] in seen_urls:
|
|
|
|
| 49 |
continue
|
| 50 |
+
seen_urls.add(product["url"])
|
| 51 |
+
products.append(product)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
new_count += 1
|
| 53 |
|
| 54 |
+
# Get next page URL
|
| 55 |
+
next_page_url = state.get("nextPageUrl", "")
|
| 56 |
+
if next_page_url and new_count > 0:
|
| 57 |
+
if not next_page_url.startswith("http"):
|
| 58 |
+
next_page_url = f"{base_url}{next_page_url}"
|
| 59 |
+
next_url = next_page_url
|
| 60 |
+
else:
|
| 61 |
+
next_url = None
|
| 62 |
+
|
| 63 |
+
else:
|
| 64 |
+
# Fallback: JSON-LD extraction (older pages)
|
| 65 |
+
new_count = self._extract_jsonld(resp.text, base_url, seen_urls, products)
|
| 66 |
+
# Simple page increment for JSON-LD
|
| 67 |
+
page_num += 1
|
| 68 |
+
next_url = f"{cat_url}?page={page_num}" if new_count > 0 else None
|
| 69 |
+
|
| 70 |
print(f" NA-KD: {cat.split('/')[-1]} page {page_num}, +{new_count}, {len(products)} total", flush=True)
|
| 71 |
|
| 72 |
if new_count == 0:
|
|
|
|
| 74 |
page_num += 1
|
| 75 |
|
| 76 |
return products
|
| 77 |
+
|
| 78 |
+
@staticmethod
|
| 79 |
+
def _extract_current_page(text: str) -> dict | None:
|
| 80 |
+
"""Extract window.CURRENT_PAGE from SSR HTML."""
|
| 81 |
+
m = re.search(r'window\.CURRENT_PAGE\s*=\s*(\{.*?\});\s*(?:window\.|</script>)', text, re.DOTALL)
|
| 82 |
+
if not m:
|
| 83 |
+
return None
|
| 84 |
+
try:
|
| 85 |
+
return json.loads(m.group(1))
|
| 86 |
+
except json.JSONDecodeError:
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
@staticmethod
|
| 90 |
+
def _parse_current_page_item(item: dict, base_url: str) -> dict | None:
|
| 91 |
+
"""Parse a product item from CURRENT_PAGE state."""
|
| 92 |
+
url = item.get("url", "")
|
| 93 |
+
if not url:
|
| 94 |
+
return None
|
| 95 |
+
if not url.startswith("http"):
|
| 96 |
+
url = f"{base_url}{url}"
|
| 97 |
+
|
| 98 |
+
# Images
|
| 99 |
+
image_urls = item.get("imageUrls", [])
|
| 100 |
+
if not image_urls:
|
| 101 |
+
img = item.get("imageUrl", "")
|
| 102 |
+
image_urls = [img] if img else []
|
| 103 |
+
image_url = image_urls[0] if image_urls else ""
|
| 104 |
+
|
| 105 |
+
# Brand
|
| 106 |
+
brand = item.get("brandName", "")
|
| 107 |
+
|
| 108 |
+
# Name
|
| 109 |
+
variation = item.get("variation", {})
|
| 110 |
+
if isinstance(variation, dict):
|
| 111 |
+
name_data = variation.get("displayName", {})
|
| 112 |
+
name = name_data.get("$c", "") if isinstance(name_data, dict) else str(name_data)
|
| 113 |
+
color_data = variation.get("itemColorName", {})
|
| 114 |
+
color = color_data.get("$c", "") if isinstance(color_data, dict) else str(color_data)
|
| 115 |
+
code_data = variation.get("code", {})
|
| 116 |
+
external_id = code_data.get("$c", "") if isinstance(code_data, dict) else str(code_data)
|
| 117 |
+
else:
|
| 118 |
+
name = item.get("name", item.get("displayName", ""))
|
| 119 |
+
color = ""
|
| 120 |
+
external_id = ""
|
| 121 |
+
|
| 122 |
+
# Price from sizes array
|
| 123 |
+
sizes_data = item.get("sizes", [])
|
| 124 |
+
price_nok = 0
|
| 125 |
+
original_nok = 0
|
| 126 |
+
size_list = []
|
| 127 |
+
in_stock = not item.get("isSoldOut", False)
|
| 128 |
+
|
| 129 |
+
for s in sizes_data:
|
| 130 |
+
if isinstance(s, dict):
|
| 131 |
+
size_name = s.get("sizeName", "")
|
| 132 |
+
if size_name:
|
| 133 |
+
size_list.append(size_name)
|
| 134 |
+
price_obj = s.get("price", {})
|
| 135 |
+
if isinstance(price_obj, dict):
|
| 136 |
+
current = float(price_obj.get("current", 0) or 0)
|
| 137 |
+
original = float(price_obj.get("original", 0) or 0)
|
| 138 |
+
if current > 0 and price_nok == 0:
|
| 139 |
+
price_nok = current
|
| 140 |
+
original_nok = original
|
| 141 |
+
|
| 142 |
+
on_sale = original_nok > 0 and price_nok < original_nok
|
| 143 |
+
|
| 144 |
+
# Color families
|
| 145 |
+
if not color:
|
| 146 |
+
families = item.get("colorFamilies", [])
|
| 147 |
+
if families:
|
| 148 |
+
color = families[0]
|
| 149 |
+
|
| 150 |
+
return {
|
| 151 |
+
"url": url,
|
| 152 |
+
"external_id": external_id,
|
| 153 |
+
"image_url": image_url,
|
| 154 |
+
"image_urls": image_urls,
|
| 155 |
+
"brand": brand,
|
| 156 |
+
"name": name or item.get("name", ""),
|
| 157 |
+
"color": color,
|
| 158 |
+
"material": "",
|
| 159 |
+
"category": "",
|
| 160 |
+
"price_nok": price_nok,
|
| 161 |
+
"original_price_nok": original_nok if on_sale else 0,
|
| 162 |
+
"price_text": f"{price_nok:.0f} kr" if price_nok else "",
|
| 163 |
+
"currency": "NOK",
|
| 164 |
+
"on_sale": on_sale,
|
| 165 |
+
"in_stock": in_stock,
|
| 166 |
+
"sizes": size_list,
|
| 167 |
+
"store": "NA-KD",
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
def _extract_jsonld(self, text: str, base_url: str, seen_urls: set, products: list) -> int:
|
| 171 |
+
"""Fallback: extract from JSON-LD script tags."""
|
| 172 |
+
ld_matches = re.findall(
|
| 173 |
+
r'<script[^>]*type="application/ld\+json"[^>]*>(.*?)</script>',
|
| 174 |
+
text, re.DOTALL,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
new_count = 0
|
| 178 |
+
for ld_text in ld_matches:
|
| 179 |
+
try:
|
| 180 |
+
ld = json.loads(ld_text)
|
| 181 |
+
except json.JSONDecodeError:
|
| 182 |
+
continue
|
| 183 |
+
|
| 184 |
+
items = []
|
| 185 |
+
if isinstance(ld, dict):
|
| 186 |
+
if ld.get("@type") == "ItemList":
|
| 187 |
+
items = ld.get("itemListElement", [])
|
| 188 |
+
elif ld.get("@type") in ("Product", "ProductGroup"):
|
| 189 |
+
items = [ld]
|
| 190 |
+
|
| 191 |
+
for item in items:
|
| 192 |
+
product = item.get("item", item) if "item" in item else item
|
| 193 |
+
prod_url = product.get("url", "")
|
| 194 |
+
if prod_url in seen_urls or not prod_url:
|
| 195 |
+
continue
|
| 196 |
+
seen_urls.add(prod_url)
|
| 197 |
+
|
| 198 |
+
raw_image = product.get("image", "")
|
| 199 |
+
if isinstance(raw_image, list):
|
| 200 |
+
image_urls = [u for u in raw_image if u]
|
| 201 |
+
image = image_urls[0] if image_urls else ""
|
| 202 |
+
else:
|
| 203 |
+
image = raw_image
|
| 204 |
+
image_urls = [image] if image else []
|
| 205 |
+
|
| 206 |
+
offers = product.get("offers", {})
|
| 207 |
+
if isinstance(offers, list):
|
| 208 |
+
offers = offers[0] if offers else {}
|
| 209 |
+
price_val = float(offers.get("price", 0) or 0)
|
| 210 |
+
currency = offers.get("priceCurrency", "NOK")
|
| 211 |
+
|
| 212 |
+
brand = product.get("brand", "")
|
| 213 |
+
if isinstance(brand, dict):
|
| 214 |
+
brand = brand.get("name", "")
|
| 215 |
+
|
| 216 |
+
products.append({
|
| 217 |
+
"url": prod_url,
|
| 218 |
+
"external_id": product.get("sku", ""),
|
| 219 |
+
"image_url": image,
|
| 220 |
+
"image_urls": image_urls,
|
| 221 |
+
"brand": str(brand),
|
| 222 |
+
"name": product.get("name", ""),
|
| 223 |
+
"color": "",
|
| 224 |
+
"material": product.get("material", "") or "",
|
| 225 |
+
"category": "",
|
| 226 |
+
"price_nok": price_val,
|
| 227 |
+
"original_price_nok": 0,
|
| 228 |
+
"price_text": f"{price_val:.0f} kr" if price_val else "",
|
| 229 |
+
"currency": currency,
|
| 230 |
+
"on_sale": False,
|
| 231 |
+
"in_stock": offers.get("availability", "").endswith("InStock"),
|
| 232 |
+
"sizes": [],
|
| 233 |
+
"store": "NA-KD",
|
| 234 |
+
})
|
| 235 |
+
new_count += 1
|
| 236 |
+
|
| 237 |
+
return new_count
|
taste/scrapers/api/wakakuu.py
CHANGED
|
@@ -1,8 +1,7 @@
|
|
| 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 |
|
|
@@ -43,45 +42,60 @@ class WakakuuScraper(BaseScraper):
|
|
| 43 |
break
|
| 44 |
|
| 45 |
for hit in hits:
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
product_url = hit.get("url", "")
|
| 74 |
if product_url and not product_url.startswith("http"):
|
| 75 |
product_url = f"{base_url}{product_url}"
|
| 76 |
|
| 77 |
products.append({
|
| 78 |
"url": product_url,
|
| 79 |
-
"
|
|
|
|
| 80 |
"image_urls": image_urls,
|
| 81 |
"brand": hit.get("brand", ""),
|
| 82 |
-
"name": hit.get("name", hit.get("title", "")),
|
|
|
|
|
|
|
|
|
|
| 83 |
"price_nok": price_val,
|
|
|
|
| 84 |
"price_text": f"{price_val:.0f} kr" if price_val else "",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
"store": "Wakakuu",
|
| 86 |
})
|
| 87 |
|
|
@@ -93,3 +107,29 @@ class WakakuuScraper(BaseScraper):
|
|
| 93 |
break
|
| 94 |
|
| 95 |
return products
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Wakakuu scraper — Algolia API with full field extraction."""
|
| 2 |
|
| 3 |
import httpx
|
| 4 |
|
|
|
|
| 5 |
from taste.scrapers.base import BaseScraper
|
| 6 |
|
| 7 |
|
|
|
|
| 42 |
break
|
| 43 |
|
| 44 |
for hit in hits:
|
| 45 |
+
# Images
|
| 46 |
+
image_url = hit.get("imageUrl", "") or hit.get("image", "")
|
| 47 |
+
hover_image = hit.get("hoverImageUrl", "")
|
| 48 |
+
image_urls = [u for u in [image_url, hover_image] if u]
|
| 49 |
+
|
| 50 |
+
# Price — extract NOK first, fallback to SEK
|
| 51 |
+
price_val, currency = self._extract_price(hit)
|
| 52 |
+
on_sale = hit.get("hasDiscount", False) or hit.get("hasDiscountAnonymous", False)
|
| 53 |
+
|
| 54 |
+
# Stock
|
| 55 |
+
in_stock = hit.get("inStock", True)
|
| 56 |
+
|
| 57 |
+
# Color
|
| 58 |
+
color = hit.get("colorName", "")
|
| 59 |
+
|
| 60 |
+
# Sizes from variants
|
| 61 |
+
variants = hit.get("variants", [])
|
| 62 |
+
sizes = []
|
| 63 |
+
for v in variants:
|
| 64 |
+
if isinstance(v, dict):
|
| 65 |
+
size = v.get("size", "")
|
| 66 |
+
if size:
|
| 67 |
+
sizes.append(size)
|
| 68 |
+
|
| 69 |
+
# Category
|
| 70 |
+
cats = hit.get("categories", {})
|
| 71 |
+
category = ""
|
| 72 |
+
if isinstance(cats, dict):
|
| 73 |
+
category = cats.get("lvl1", cats.get("lvl0", ""))
|
| 74 |
+
if isinstance(category, list):
|
| 75 |
+
category = category[0] if category else ""
|
| 76 |
+
|
| 77 |
+
# URL
|
| 78 |
product_url = hit.get("url", "")
|
| 79 |
if product_url and not product_url.startswith("http"):
|
| 80 |
product_url = f"{base_url}{product_url}"
|
| 81 |
|
| 82 |
products.append({
|
| 83 |
"url": product_url,
|
| 84 |
+
"external_id": hit.get("objectID", ""),
|
| 85 |
+
"image_url": image_url,
|
| 86 |
"image_urls": image_urls,
|
| 87 |
"brand": hit.get("brand", ""),
|
| 88 |
+
"name": hit.get("styleName", hit.get("name", hit.get("title", ""))),
|
| 89 |
+
"color": color,
|
| 90 |
+
"material": "",
|
| 91 |
+
"category": category,
|
| 92 |
"price_nok": price_val,
|
| 93 |
+
"original_price_nok": 0,
|
| 94 |
"price_text": f"{price_val:.0f} kr" if price_val else "",
|
| 95 |
+
"currency": currency,
|
| 96 |
+
"on_sale": on_sale,
|
| 97 |
+
"in_stock": in_stock,
|
| 98 |
+
"sizes": sizes,
|
| 99 |
"store": "Wakakuu",
|
| 100 |
})
|
| 101 |
|
|
|
|
| 107 |
break
|
| 108 |
|
| 109 |
return products
|
| 110 |
+
|
| 111 |
+
@staticmethod
|
| 112 |
+
def _extract_price(hit: dict) -> tuple[float, str]:
|
| 113 |
+
"""Extract price from Algolia hit, preferring NOK."""
|
| 114 |
+
prices = hit.get("price", {})
|
| 115 |
+
if not isinstance(prices, dict):
|
| 116 |
+
return (float(prices) if isinstance(prices, (int, float)) else 0, "NOK")
|
| 117 |
+
|
| 118 |
+
# Try currencies in preference order
|
| 119 |
+
for currency in ("NOK", "SEK", "EUR"):
|
| 120 |
+
bucket = prices.get(currency)
|
| 121 |
+
if bucket is None:
|
| 122 |
+
continue
|
| 123 |
+
if isinstance(bucket, dict):
|
| 124 |
+
anon = bucket.get("anonymous", bucket.get("default", {}))
|
| 125 |
+
if isinstance(anon, dict):
|
| 126 |
+
val = anon.get("actualPrice", anon.get("amount", anon.get("value", 0)))
|
| 127 |
+
else:
|
| 128 |
+
val = anon
|
| 129 |
+
price = float(val or 0)
|
| 130 |
+
if price > 0:
|
| 131 |
+
return (price, currency)
|
| 132 |
+
elif isinstance(bucket, (int, float)):
|
| 133 |
+
return (float(bucket), currency)
|
| 134 |
+
|
| 135 |
+
return (0, "NOK")
|
taste/store.py
CHANGED
|
@@ -2,11 +2,44 @@
|
|
| 2 |
|
| 3 |
import json
|
| 4 |
import sqlite3
|
|
|
|
| 5 |
from pathlib import Path
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
class ProductStore:
|
| 9 |
-
"""Per-profile product database.
|
| 10 |
|
| 11 |
def __init__(self, db_path: Path):
|
| 12 |
self.db_path = Path(db_path)
|
|
@@ -15,99 +48,205 @@ class ProductStore:
|
|
| 15 |
self.conn.row_factory = sqlite3.Row
|
| 16 |
self.conn.execute("PRAGMA journal_mode=WAL")
|
| 17 |
self.conn.execute("PRAGMA synchronous=NORMAL")
|
| 18 |
-
self.
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
)
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
self.conn.commit()
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
def upsert(self, product: dict):
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
if isinstance(image_urls, list):
|
| 49 |
image_urls = json.dumps(image_urls)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
self.conn.execute("""
|
| 51 |
-
INSERT INTO products (
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
ON CONFLICT(url) DO UPDATE SET
|
| 54 |
-
|
| 55 |
-
score = CASE WHEN excluded.score > products.score THEN excluded.score ELSE products.score END,
|
| 56 |
brand = CASE WHEN excluded.brand != '' THEN excluded.brand ELSE products.brand END,
|
| 57 |
name = CASE WHEN excluded.name != '' THEN excluded.name ELSE products.name END,
|
| 58 |
-
|
|
|
|
|
|
|
| 59 |
price_nok = CASE WHEN excluded.price_nok > 0 THEN excluded.price_nok ELSE products.price_nok END,
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
""", {
|
| 63 |
-
"url":
|
| 64 |
-
"
|
| 65 |
-
"
|
| 66 |
-
"brand":
|
| 67 |
-
"name":
|
| 68 |
-
"
|
| 69 |
-
"
|
| 70 |
-
"
|
| 71 |
-
"
|
| 72 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
"image_urls": image_urls,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
})
|
| 75 |
-
self.conn.commit()
|
| 76 |
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
for p in products:
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
"
|
| 97 |
-
|
| 98 |
-
"brand": p.get("brand", ""),
|
| 99 |
-
"name": p.get("name", ""),
|
| 100 |
-
"price_text": p.get("price_text", ""),
|
| 101 |
-
"price_nok": p.get("price_nok", 0),
|
| 102 |
-
"store": p.get("store", ""),
|
| 103 |
-
"score": p.get("score", 0),
|
| 104 |
-
"fabric": p.get("fabric", ""),
|
| 105 |
-
"image_urls": image_urls,
|
| 106 |
-
})
|
| 107 |
self.conn.commit()
|
| 108 |
|
|
|
|
|
|
|
| 109 |
def get_all(self, store: str | None = None, min_score: float = 0, limit: int = 0) -> list[dict]:
|
| 110 |
-
sql = "SELECT * FROM products WHERE score >= ?"
|
| 111 |
params: list = [min_score]
|
| 112 |
if store:
|
| 113 |
sql += " AND store = ?"
|
|
@@ -123,12 +262,12 @@ class ProductStore:
|
|
| 123 |
|
| 124 |
def get_unscored(self) -> list[dict]:
|
| 125 |
rows = self.conn.execute(
|
| 126 |
-
"SELECT url, image_path FROM products WHERE image_path != '' AND score
|
| 127 |
).fetchall()
|
| 128 |
return [dict(r) for r in rows]
|
| 129 |
|
| 130 |
def update_score(self, url: str, score: float):
|
| 131 |
-
self.conn.execute("UPDATE products SET score = ? WHERE url = ?", (score, url))
|
| 132 |
|
| 133 |
def commit(self):
|
| 134 |
self.conn.commit()
|
|
@@ -138,13 +277,14 @@ class ProductStore:
|
|
| 138 |
SELECT store, COUNT(*) as count,
|
| 139 |
MAX(score) as top_score,
|
| 140 |
AVG(score) as avg_score
|
| 141 |
-
FROM products
|
|
|
|
| 142 |
""").fetchall()
|
| 143 |
-
total = self.conn.execute("SELECT COUNT(*) FROM products").fetchone()[0]
|
| 144 |
return {
|
| 145 |
"total": total,
|
| 146 |
"stores": {
|
| 147 |
-
r["store"]: {"count": r["count"], "top": r["top_score"], "avg": round(r["avg_score"], 3)}
|
| 148 |
for r in rows
|
| 149 |
},
|
| 150 |
}
|
|
@@ -163,6 +303,7 @@ class ProductStore:
|
|
| 163 |
elif "miinto.no" in data.get("url", ""):
|
| 164 |
store = "Miinto"
|
| 165 |
data["store"] = store
|
| 166 |
-
self.
|
| 167 |
count += 1
|
|
|
|
| 168 |
return count
|
|
|
|
| 2 |
|
| 3 |
import json
|
| 4 |
import sqlite3
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
from pathlib import Path
|
| 7 |
|
| 8 |
+
_SCHEMA_V2 = """
|
| 9 |
+
CREATE TABLE IF NOT EXISTS products (
|
| 10 |
+
url TEXT PRIMARY KEY,
|
| 11 |
+
external_id TEXT DEFAULT '',
|
| 12 |
+
store TEXT NOT NULL DEFAULT '',
|
| 13 |
+
brand TEXT NOT NULL DEFAULT '',
|
| 14 |
+
name TEXT NOT NULL DEFAULT '',
|
| 15 |
+
color TEXT DEFAULT '',
|
| 16 |
+
material TEXT DEFAULT '',
|
| 17 |
+
category TEXT DEFAULT '',
|
| 18 |
+
|
| 19 |
+
price_nok REAL DEFAULT 0,
|
| 20 |
+
original_price_nok REAL DEFAULT 0,
|
| 21 |
+
price_text TEXT DEFAULT '',
|
| 22 |
+
currency TEXT DEFAULT 'NOK',
|
| 23 |
+
on_sale BOOLEAN DEFAULT 0,
|
| 24 |
+
|
| 25 |
+
image_url TEXT DEFAULT '',
|
| 26 |
+
image_urls TEXT DEFAULT '[]',
|
| 27 |
+
|
| 28 |
+
in_stock BOOLEAN DEFAULT 1,
|
| 29 |
+
sizes TEXT DEFAULT '[]',
|
| 30 |
+
|
| 31 |
+
score REAL,
|
| 32 |
+
image_path TEXT DEFAULT '',
|
| 33 |
+
|
| 34 |
+
first_seen_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
| 35 |
+
last_seen_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
| 36 |
+
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 37 |
+
)
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
|
| 41 |
class ProductStore:
|
| 42 |
+
"""Per-profile product database."""
|
| 43 |
|
| 44 |
def __init__(self, db_path: Path):
|
| 45 |
self.db_path = Path(db_path)
|
|
|
|
| 48 |
self.conn.row_factory = sqlite3.Row
|
| 49 |
self.conn.execute("PRAGMA journal_mode=WAL")
|
| 50 |
self.conn.execute("PRAGMA synchronous=NORMAL")
|
| 51 |
+
self._ensure_schema()
|
| 52 |
+
|
| 53 |
+
def _ensure_schema(self):
|
| 54 |
+
"""Create table or migrate from v1 schema."""
|
| 55 |
+
cols = set()
|
| 56 |
+
try:
|
| 57 |
+
cols = {r[1] for r in self.conn.execute("PRAGMA table_info(products)").fetchall()}
|
| 58 |
+
except Exception:
|
| 59 |
+
pass
|
| 60 |
+
|
| 61 |
+
if not cols:
|
| 62 |
+
# Fresh DB — create v2 schema
|
| 63 |
+
self.conn.executescript(_SCHEMA_V2)
|
| 64 |
+
self._create_indexes()
|
| 65 |
+
self.conn.commit()
|
| 66 |
+
return
|
| 67 |
+
|
| 68 |
+
# Migrate from v1 if needed
|
| 69 |
+
new_cols = {
|
| 70 |
+
"external_id": "TEXT DEFAULT ''",
|
| 71 |
+
"color": "TEXT DEFAULT ''",
|
| 72 |
+
"material": "TEXT DEFAULT ''",
|
| 73 |
+
"category": "TEXT DEFAULT ''",
|
| 74 |
+
"original_price_nok": "REAL DEFAULT 0",
|
| 75 |
+
"currency": "TEXT DEFAULT 'NOK'",
|
| 76 |
+
"on_sale": "BOOLEAN DEFAULT 0",
|
| 77 |
+
"image_urls": "TEXT DEFAULT '[]'",
|
| 78 |
+
"in_stock": "BOOLEAN DEFAULT 1",
|
| 79 |
+
"sizes": "TEXT DEFAULT '[]'",
|
| 80 |
+
"first_seen_at": "TIMESTAMP DEFAULT ''",
|
| 81 |
+
"last_seen_at": "TIMESTAMP DEFAULT ''",
|
| 82 |
+
"updated_at": "TIMESTAMP DEFAULT ''",
|
| 83 |
+
}
|
| 84 |
+
for col_name, col_def in new_cols.items():
|
| 85 |
+
if col_name not in cols:
|
| 86 |
+
try:
|
| 87 |
+
self.conn.execute(f"ALTER TABLE products ADD COLUMN {col_name} {col_def}")
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f"[store] Warning: could not add {col_name}: {e}", flush=True)
|
| 90 |
+
|
| 91 |
+
# Migrate timestamps
|
| 92 |
+
try:
|
| 93 |
+
if "created_at" in cols:
|
| 94 |
+
self.conn.execute("""
|
| 95 |
+
UPDATE products SET first_seen_at = created_at
|
| 96 |
+
WHERE first_seen_at IS NULL OR first_seen_at = ''
|
| 97 |
+
""")
|
| 98 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 99 |
+
self.conn.execute(
|
| 100 |
+
"UPDATE products SET last_seen_at = ? WHERE last_seen_at IS NULL OR last_seen_at = ''",
|
| 101 |
+
(now,),
|
| 102 |
)
|
| 103 |
+
self.conn.execute(
|
| 104 |
+
"UPDATE products SET updated_at = ? WHERE updated_at IS NULL OR updated_at = ''",
|
| 105 |
+
(now,),
|
| 106 |
+
)
|
| 107 |
+
self.conn.execute(
|
| 108 |
+
"UPDATE products SET first_seen_at = ? WHERE first_seen_at IS NULL OR first_seen_at = ''",
|
| 109 |
+
(now,),
|
| 110 |
+
)
|
| 111 |
+
except Exception as e:
|
| 112 |
+
print(f"[store] Warning: timestamp migration: {e}", flush=True)
|
| 113 |
+
|
| 114 |
+
# Disambiguate score: 0 → NULL (unscored)
|
| 115 |
+
try:
|
| 116 |
+
self.conn.execute("UPDATE products SET score = NULL WHERE score = 0")
|
| 117 |
+
except Exception:
|
| 118 |
+
pass
|
| 119 |
+
|
| 120 |
+
# Remove dead fabric column if present (replace with material)
|
| 121 |
+
# SQLite can't drop columns easily, so just leave it — it's harmless
|
| 122 |
+
|
| 123 |
+
self._create_indexes()
|
| 124 |
self.conn.commit()
|
| 125 |
|
| 126 |
+
def _create_indexes(self):
|
| 127 |
+
for stmt in [
|
| 128 |
+
"CREATE INDEX IF NOT EXISTS idx_store ON products(store)",
|
| 129 |
+
"CREATE INDEX IF NOT EXISTS idx_score ON products(score DESC)",
|
| 130 |
+
"CREATE INDEX IF NOT EXISTS idx_in_stock ON products(in_stock, store)",
|
| 131 |
+
"CREATE INDEX IF NOT EXISTS idx_last_seen ON products(last_seen_at)",
|
| 132 |
+
"CREATE INDEX IF NOT EXISTS idx_brand ON products(brand)",
|
| 133 |
+
]:
|
| 134 |
+
try:
|
| 135 |
+
self.conn.execute(stmt)
|
| 136 |
+
except Exception:
|
| 137 |
+
pass
|
| 138 |
+
|
| 139 |
+
# --- Upsert ---
|
| 140 |
+
|
| 141 |
def upsert(self, product: dict):
|
| 142 |
+
"""Insert or update a single product."""
|
| 143 |
+
self._do_upsert(product)
|
| 144 |
+
self.conn.commit()
|
| 145 |
+
|
| 146 |
+
def upsert_batch(self, products: list[dict]):
|
| 147 |
+
"""Insert or update a batch of products."""
|
| 148 |
+
for p in products:
|
| 149 |
+
self._do_upsert(p)
|
| 150 |
+
self.conn.commit()
|
| 151 |
+
|
| 152 |
+
def _do_upsert(self, p: dict):
|
| 153 |
+
image_urls = p.get("image_urls", "[]")
|
| 154 |
if isinstance(image_urls, list):
|
| 155 |
image_urls = json.dumps(image_urls)
|
| 156 |
+
sizes = p.get("sizes", "[]")
|
| 157 |
+
if isinstance(sizes, list):
|
| 158 |
+
sizes = json.dumps(sizes)
|
| 159 |
+
|
| 160 |
self.conn.execute("""
|
| 161 |
+
INSERT INTO products (
|
| 162 |
+
url, external_id, store, brand, name, color, material, category,
|
| 163 |
+
price_nok, original_price_nok, price_text, currency, on_sale,
|
| 164 |
+
image_url, image_urls, in_stock, sizes, score, image_path,
|
| 165 |
+
first_seen_at, last_seen_at, updated_at
|
| 166 |
+
) VALUES (
|
| 167 |
+
:url, :external_id, :store, :brand, :name, :color, :material, :category,
|
| 168 |
+
:price_nok, :original_price_nok, :price_text, :currency, :on_sale,
|
| 169 |
+
:image_url, :image_urls, :in_stock, :sizes, :score, :image_path,
|
| 170 |
+
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
| 171 |
+
)
|
| 172 |
ON CONFLICT(url) DO UPDATE SET
|
| 173 |
+
external_id = CASE WHEN excluded.external_id != '' THEN excluded.external_id ELSE products.external_id END,
|
|
|
|
| 174 |
brand = CASE WHEN excluded.brand != '' THEN excluded.brand ELSE products.brand END,
|
| 175 |
name = CASE WHEN excluded.name != '' THEN excluded.name ELSE products.name END,
|
| 176 |
+
color = CASE WHEN excluded.color != '' THEN excluded.color ELSE products.color END,
|
| 177 |
+
material = CASE WHEN excluded.material != '' THEN excluded.material ELSE products.material END,
|
| 178 |
+
category = CASE WHEN excluded.category != '' THEN excluded.category ELSE products.category END,
|
| 179 |
price_nok = CASE WHEN excluded.price_nok > 0 THEN excluded.price_nok ELSE products.price_nok END,
|
| 180 |
+
original_price_nok = CASE WHEN excluded.original_price_nok > 0 THEN excluded.original_price_nok ELSE products.original_price_nok END,
|
| 181 |
+
price_text = CASE WHEN excluded.price_text != '' THEN excluded.price_text ELSE products.price_text END,
|
| 182 |
+
currency = excluded.currency,
|
| 183 |
+
on_sale = excluded.on_sale,
|
| 184 |
+
image_url = CASE WHEN excluded.image_url != '' THEN excluded.image_url ELSE products.image_url END,
|
| 185 |
+
image_urls = CASE WHEN excluded.image_urls != '[]' THEN excluded.image_urls ELSE products.image_urls END,
|
| 186 |
+
in_stock = excluded.in_stock,
|
| 187 |
+
sizes = CASE WHEN excluded.sizes != '[]' THEN excluded.sizes ELSE products.sizes END,
|
| 188 |
+
image_path = COALESCE(NULLIF(excluded.image_path, ''), products.image_path),
|
| 189 |
+
last_seen_at = CURRENT_TIMESTAMP,
|
| 190 |
+
updated_at = CURRENT_TIMESTAMP
|
| 191 |
""", {
|
| 192 |
+
"url": p.get("url", ""),
|
| 193 |
+
"external_id": p.get("external_id", ""),
|
| 194 |
+
"store": p.get("store", ""),
|
| 195 |
+
"brand": p.get("brand", ""),
|
| 196 |
+
"name": p.get("name", ""),
|
| 197 |
+
"color": p.get("color", ""),
|
| 198 |
+
"material": p.get("material", ""),
|
| 199 |
+
"category": p.get("category", ""),
|
| 200 |
+
"price_nok": p.get("price_nok", 0),
|
| 201 |
+
"original_price_nok": p.get("original_price_nok", 0),
|
| 202 |
+
"price_text": p.get("price_text", ""),
|
| 203 |
+
"currency": p.get("currency", "NOK"),
|
| 204 |
+
"on_sale": int(p.get("on_sale", False)),
|
| 205 |
+
"image_url": p.get("image_url", ""),
|
| 206 |
"image_urls": image_urls,
|
| 207 |
+
"in_stock": int(p.get("in_stock", True)),
|
| 208 |
+
"sizes": sizes,
|
| 209 |
+
"score": p.get("score"),
|
| 210 |
+
"image_path": p.get("image_path", ""),
|
| 211 |
})
|
|
|
|
| 212 |
|
| 213 |
+
# --- Sync (idempotent scrape ingestion) ---
|
| 214 |
+
|
| 215 |
+
def sync(self, products: list[dict], store: str):
|
| 216 |
+
"""Idempotent sync: upsert products, mark missing ones as out-of-stock.
|
| 217 |
+
|
| 218 |
+
Call this after a complete scrape of a store. Products from this store
|
| 219 |
+
that are NOT in the batch will have in_stock set to 0.
|
| 220 |
+
"""
|
| 221 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 222 |
+
|
| 223 |
+
# Upsert all products
|
| 224 |
for p in products:
|
| 225 |
+
p["store"] = store
|
| 226 |
+
self._do_upsert(p)
|
| 227 |
+
|
| 228 |
+
# Mark products from this store not in this batch as out-of-stock
|
| 229 |
+
if products:
|
| 230 |
+
seen_urls = {p["url"] for p in products}
|
| 231 |
+
existing = self.conn.execute(
|
| 232 |
+
"SELECT url FROM products WHERE store = ? AND in_stock = 1",
|
| 233 |
+
(store,),
|
| 234 |
+
).fetchall()
|
| 235 |
+
stale_urls = [r["url"] for r in existing if r["url"] not in seen_urls]
|
| 236 |
+
if stale_urls:
|
| 237 |
+
placeholders = ",".join("?" * len(stale_urls))
|
| 238 |
+
self.conn.execute(
|
| 239 |
+
f"UPDATE products SET in_stock = 0, updated_at = ? WHERE url IN ({placeholders})",
|
| 240 |
+
[now] + stale_urls,
|
| 241 |
+
)
|
| 242 |
+
print(f"[store] Marked {len(stale_urls)} {store} products as out-of-stock", flush=True)
|
| 243 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
self.conn.commit()
|
| 245 |
|
| 246 |
+
# --- Queries ---
|
| 247 |
+
|
| 248 |
def get_all(self, store: str | None = None, min_score: float = 0, limit: int = 0) -> list[dict]:
|
| 249 |
+
sql = "SELECT * FROM products WHERE (score IS NOT NULL AND score >= ?)"
|
| 250 |
params: list = [min_score]
|
| 251 |
if store:
|
| 252 |
sql += " AND store = ?"
|
|
|
|
| 262 |
|
| 263 |
def get_unscored(self) -> list[dict]:
|
| 264 |
rows = self.conn.execute(
|
| 265 |
+
"SELECT url, image_path FROM products WHERE image_path != '' AND score IS NULL"
|
| 266 |
).fetchall()
|
| 267 |
return [dict(r) for r in rows]
|
| 268 |
|
| 269 |
def update_score(self, url: str, score: float):
|
| 270 |
+
self.conn.execute("UPDATE products SET score = ?, updated_at = CURRENT_TIMESTAMP WHERE url = ?", (score, url))
|
| 271 |
|
| 272 |
def commit(self):
|
| 273 |
self.conn.commit()
|
|
|
|
| 277 |
SELECT store, COUNT(*) as count,
|
| 278 |
MAX(score) as top_score,
|
| 279 |
AVG(score) as avg_score
|
| 280 |
+
FROM products WHERE score IS NOT NULL
|
| 281 |
+
GROUP BY store ORDER BY count DESC
|
| 282 |
""").fetchall()
|
| 283 |
+
total = self.conn.execute("SELECT COUNT(*) FROM products WHERE score IS NOT NULL").fetchone()[0]
|
| 284 |
return {
|
| 285 |
"total": total,
|
| 286 |
"stores": {
|
| 287 |
+
r["store"]: {"count": r["count"], "top": r["top_score"], "avg": round(r["avg_score"] or 0, 3)}
|
| 288 |
for r in rows
|
| 289 |
},
|
| 290 |
}
|
|
|
|
| 303 |
elif "miinto.no" in data.get("url", ""):
|
| 304 |
store = "Miinto"
|
| 305 |
data["store"] = store
|
| 306 |
+
self._do_upsert(data)
|
| 307 |
count += 1
|
| 308 |
+
self.conn.commit()
|
| 309 |
return count
|