mucahitkantepe commited on
Commit
bf6e8ac
·
1 Parent(s): aff4ca6

deduplicate color variants + multi-image support

Browse files

Products: group by (brand, name, store) using ROW_NUMBER window,
pick highest-scoring variant. Reduces ~1766 duplicates to unique models.

Multi-image: scrapers now collect all image URLs (Boozt media array,
NA-KD image list, Miinto photos, Wakakuu imageUrls). Full stack:
schema image_urls column, Product model, API, TypeScript types.

UI: Discover card has tap-to-navigate image zones with dot indicators.
Browse cards cycle images on hover with zone-based navigation.

backend/app/routers/discover.py CHANGED
@@ -1,6 +1,7 @@
1
  """Discover / swipe endpoints — product rating with async taste model updates."""
2
 
3
  import hashlib
 
4
  import threading
5
  from pathlib import Path
6
 
@@ -61,16 +62,32 @@ def get_next_products(count: int = 10):
61
  r[0] for r in conn.execute("SELECT url FROM discover_ratings").fetchall()
62
  )
63
 
 
64
  rows = conn.execute("""
65
- SELECT * FROM products
66
- WHERE image_url != '' AND score > 0
 
 
 
 
 
67
  ORDER BY score DESC
68
  """).fetchall()
69
 
70
  results = []
71
  for r in rows:
72
  if r["url"] not in rated_urls:
73
- results.append(ProductOut(**dict(r)))
 
 
 
 
 
 
 
 
 
 
74
  if len(results) >= count:
75
  break
76
 
@@ -139,7 +156,18 @@ def undo_last_rating():
139
 
140
  # Get the undone product to return to frontend
141
  product_row = conn.execute("SELECT * FROM products WHERE url = ?", (url,)).fetchone()
142
- product = ProductOut(**dict(product_row)) if product_row else None
 
 
 
 
 
 
 
 
 
 
 
143
 
144
  return {"ok": True, "product": product, "stats": _get_stats(conn)}
145
 
 
1
  """Discover / swipe endpoints — product rating with async taste model updates."""
2
 
3
  import hashlib
4
+ import json
5
  import threading
6
  from pathlib import Path
7
 
 
62
  r[0] for r in conn.execute("SELECT url FROM discover_ratings").fetchall()
63
  )
64
 
65
+ # Deduplicated: best variant per (brand, name, store), exclude already rated
66
  rows = conn.execute("""
67
+ SELECT * FROM (
68
+ SELECT *, ROW_NUMBER() OVER (
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()
76
 
77
  results = []
78
  for r in rows:
79
  if r["url"] not in rated_urls:
80
+ d = dict(r)
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
 
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
 
backend/app/routers/products.py CHANGED
@@ -1,5 +1,7 @@
1
  """Product browsing endpoints."""
2
 
 
 
3
  from fastapi import APIRouter, Query
4
 
5
  from backend.app.deps import get_store
@@ -8,6 +10,22 @@ from backend.app.schemas import ProductOut, ProductsResponse
8
  router = APIRouter(prefix="/api/products", tags=["products"])
9
 
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  @router.get("", response_model=ProductsResponse)
12
  def list_products(
13
  page: int = Query(1, ge=1),
@@ -36,7 +54,7 @@ def list_products(
36
 
37
  where_sql = " AND ".join(where)
38
 
39
- order = {
40
  "score": "score DESC",
41
  "-score": "score ASC",
42
  "price": "price_nok ASC",
@@ -47,15 +65,31 @@ def list_products(
47
  "newest": "created_at DESC",
48
  }.get(sort, "score DESC")
49
 
50
- total = conn.execute(f"SELECT COUNT(*) FROM products WHERE {where_sql}", params).fetchone()[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  offset = (page - 1) * page_size
53
  rows = conn.execute(
54
- f"SELECT * FROM products WHERE {where_sql} ORDER BY {order} LIMIT ? OFFSET ?",
55
  params + [page_size, offset],
56
  ).fetchall()
57
 
58
- items = [ProductOut(**dict(r)) for r in rows]
59
  return ProductsResponse(items=items, total=total, page=page, page_size=page_size)
60
 
61
 
 
1
  """Product browsing endpoints."""
2
 
3
+ import json
4
+
5
  from fastapi import APIRouter, Query
6
 
7
  from backend.app.deps import get_store
 
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 image_urls JSON."""
15
+ d = dict(row)
16
+ raw = d.pop("image_urls", "[]")
17
+ try:
18
+ image_urls = json.loads(raw) if isinstance(raw, str) else raw
19
+ except (json.JSONDecodeError, TypeError):
20
+ image_urls = []
21
+ if not isinstance(image_urls, list):
22
+ image_urls = []
23
+ d.pop("image_path", None)
24
+ d.pop("fabric", None)
25
+ d.pop("created_at", None)
26
+ return ProductOut(**d, image_urls=image_urls)
27
+
28
+
29
  @router.get("", response_model=ProductsResponse)
30
  def list_products(
31
  page: int = Query(1, ge=1),
 
54
 
55
  where_sql = " AND ".join(where)
56
 
57
+ order_col = {
58
  "score": "score DESC",
59
  "-score": "score ASC",
60
  "price": "price_nok ASC",
 
65
  "newest": "created_at DESC",
66
  }.get(sort, "score DESC")
67
 
68
+ # Deduplicate: pick the highest-scoring variant per (brand, name, store) group
69
+ # ROW_NUMBER partitions by the group and orders by score DESC — row 1 is the best
70
+ dedup_sql = f"""
71
+ SELECT * FROM (
72
+ SELECT *, ROW_NUMBER() OVER (
73
+ PARTITION BY brand, name, store ORDER BY score DESC
74
+ ) AS rn
75
+ FROM products
76
+ WHERE {where_sql}
77
+ ) WHERE rn = 1
78
+ ORDER BY {order_col}
79
+ """
80
+
81
+ total = conn.execute(
82
+ f"SELECT COUNT(DISTINCT brand || '|||' || name || '|||' || store) FROM products WHERE {where_sql}",
83
+ params,
84
+ ).fetchone()[0]
85
 
86
  offset = (page - 1) * page_size
87
  rows = conn.execute(
88
+ f"{dedup_sql} LIMIT ? OFFSET ?",
89
  params + [page_size, offset],
90
  ).fetchall()
91
 
92
+ items = [_row_to_product(r) for r in rows]
93
  return ProductsResponse(items=items, total=total, page=page, page_size=page_size)
94
 
95
 
backend/app/schemas.py CHANGED
@@ -6,6 +6,7 @@ from pydantic import BaseModel
6
  class ProductOut(BaseModel):
7
  url: str
8
  image_url: str
 
9
  brand: str
10
  name: str
11
  price_text: str
 
6
  class ProductOut(BaseModel):
7
  url: str
8
  image_url: str
9
+ image_urls: list[str] = []
10
  brand: str
11
  name: str
12
  price_text: str
frontend/src/index.css CHANGED
@@ -222,6 +222,11 @@ select:focus {
222
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
223
  }
224
 
 
 
 
 
 
225
  .product-card-img {
226
  width: 100%;
227
  aspect-ratio: 1;
@@ -230,6 +235,17 @@ select:focus {
230
  padding: 12px;
231
  }
232
 
 
 
 
 
 
 
 
 
 
 
 
233
  .product-card-body {
234
  padding: 12px;
235
  flex: 1;
@@ -776,6 +792,47 @@ select:focus {
776
  opacity: 0.7;
777
  }
778
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
779
  .swipe-buttons {
780
  display: flex;
781
  gap: 20px;
 
222
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
223
  }
224
 
225
+ .product-card-img-wrap {
226
+ position: relative;
227
+ overflow: hidden;
228
+ }
229
+
230
  .product-card-img {
231
  width: 100%;
232
  aspect-ratio: 1;
 
235
  padding: 12px;
236
  }
237
 
238
+ .product-card-img-zones {
239
+ position: absolute;
240
+ inset: 0;
241
+ display: flex;
242
+ }
243
+
244
+ .product-card-img-zone {
245
+ flex: 1;
246
+ cursor: pointer;
247
+ }
248
+
249
  .product-card-body {
250
  padding: 12px;
251
  flex: 1;
 
792
  opacity: 0.7;
793
  }
794
 
795
+ /* Multi-image navigation */
796
+ .swipe-image-wrap {
797
+ position: relative;
798
+ overflow: hidden;
799
+ }
800
+
801
+ .img-nav {
802
+ position: absolute;
803
+ top: 0;
804
+ bottom: 0;
805
+ width: 35%;
806
+ cursor: pointer;
807
+ z-index: 2;
808
+ }
809
+ .img-nav-prev { left: 0; }
810
+ .img-nav-next { right: 0; }
811
+
812
+ .img-dots {
813
+ position: absolute;
814
+ bottom: 8px;
815
+ left: 50%;
816
+ transform: translateX(-50%);
817
+ display: flex;
818
+ gap: 5px;
819
+ z-index: 3;
820
+ }
821
+ .img-dots.browse-dots {
822
+ bottom: 6px;
823
+ }
824
+ .img-dot {
825
+ width: 6px;
826
+ height: 6px;
827
+ border-radius: 50%;
828
+ background: rgba(255,255,255,0.4);
829
+ transition: background 0.15s;
830
+ }
831
+ .img-dot.active {
832
+ background: #fff;
833
+ box-shadow: 0 0 3px rgba(0,0,0,0.3);
834
+ }
835
+
836
  .swipe-buttons {
837
  display: flex;
838
  gap: 20px;
frontend/src/pages/BrowsePage.tsx CHANGED
@@ -8,6 +8,60 @@ function scoreBadgeClass(score: number): string {
8
  return "score-badge amber";
9
  }
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  export function BrowsePage() {
12
  const [products, setProducts] = useState<Product[]>([]);
13
  const [total, setTotal] = useState(0);
@@ -124,38 +178,9 @@ export function BrowsePage() {
124
  ) : (
125
  <>
126
  <div className="product-grid">
127
- {products.map((p, i) => {
128
- const matchPct = Math.round(p.score * 100);
129
- return (
130
- <div className="product-card" key={`${p.store}-${p.name}-${i}`}>
131
- <img
132
- className="product-card-img"
133
- src={p.image_url}
134
- alt={p.name}
135
- loading="lazy"
136
- onError={(e) => {
137
- (e.target as HTMLImageElement).src =
138
- "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect fill='%23262626' width='100' height='100'/%3E%3Ctext x='50' y='55' text-anchor='middle' fill='%23737373' font-size='12'%3ENo Image%3C/text%3E%3C/svg%3E";
139
- }}
140
- />
141
- <div className="product-card-body">
142
- <span className="product-card-brand">{p.brand}</span>
143
- <span className="product-card-name">{p.name}</span>
144
- <div className="product-card-footer">
145
- <span className="product-card-price">{p.price_text || `${p.price_nok} kr`}</span>
146
- <span className={scoreBadgeClass(matchPct)}>
147
- {matchPct}%
148
- </span>
149
- </div>
150
- </div>
151
- <div className="product-card-store">
152
- <a href={p.url} target="_blank" rel="noopener noreferrer">
153
- {p.store} &#8599;
154
- </a>
155
- </div>
156
- </div>
157
- );
158
- })}
159
  </div>
160
 
161
  {totalPages > 1 && (
 
8
  return "score-badge amber";
9
  }
10
 
11
+ const PLACEHOLDER = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect fill='%23262626' width='100' height='100'/%3E%3Ctext x='50' y='55' text-anchor='middle' fill='%23737373' font-size='12'%3ENo Image%3C/text%3E%3C/svg%3E";
12
+
13
+ function ProductCard({ product: p }: { product: Product }) {
14
+ const [hoverIdx, setHoverIdx] = useState(0);
15
+ const imgs = p.image_urls?.length > 0 ? p.image_urls : [p.image_url];
16
+ const matchPct = Math.round(p.score * 100);
17
+
18
+ return (
19
+ <div
20
+ className="product-card"
21
+ onMouseLeave={() => setHoverIdx(0)}
22
+ >
23
+ <div className="product-card-img-wrap">
24
+ <img
25
+ className="product-card-img"
26
+ src={imgs[hoverIdx] || p.image_url}
27
+ alt={p.name}
28
+ loading="lazy"
29
+ onError={(e) => { (e.target as HTMLImageElement).src = PLACEHOLDER; }}
30
+ />
31
+ {imgs.length > 1 && (
32
+ <div className="product-card-img-zones">
33
+ {imgs.map((_, i) => (
34
+ <div
35
+ key={i}
36
+ className="product-card-img-zone"
37
+ onMouseEnter={() => setHoverIdx(i)}
38
+ />
39
+ ))}
40
+ </div>
41
+ )}
42
+ {imgs.length > 1 && (
43
+ <div className="img-dots browse-dots">
44
+ {imgs.map((_, i) => (
45
+ <span key={i} className={`img-dot${i === hoverIdx ? " active" : ""}`} />
46
+ ))}
47
+ </div>
48
+ )}
49
+ </div>
50
+ <div className="product-card-body">
51
+ <span className="product-card-brand">{p.brand}</span>
52
+ <span className="product-card-name">{p.name}</span>
53
+ <div className="product-card-footer">
54
+ <span className="product-card-price">{p.price_text || `${p.price_nok} kr`}</span>
55
+ <span className={scoreBadgeClass(matchPct)}>{matchPct}%</span>
56
+ </div>
57
+ </div>
58
+ <div className="product-card-store">
59
+ <a href={p.url} target="_blank" rel="noopener noreferrer">{p.store} &#8599;</a>
60
+ </div>
61
+ </div>
62
+ );
63
+ }
64
+
65
  export function BrowsePage() {
66
  const [products, setProducts] = useState<Product[]>([]);
67
  const [total, setTotal] = useState(0);
 
178
  ) : (
179
  <>
180
  <div className="product-grid">
181
+ {products.map((p, i) => (
182
+ <ProductCard key={`${p.store}-${p.name}-${i}`} product={p} />
183
+ ))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  </div>
185
 
186
  {totalPages > 1 && (
frontend/src/pages/DiscoverPage.tsx CHANGED
@@ -15,6 +15,7 @@ export function DiscoverPage() {
15
  const [dragMoved, setDragMoved] = useState(false);
16
  const [startPos, setStartPos] = useState({ x: 0, y: 0 });
17
  const [history, setHistory] = useState<Product[]>([]);
 
18
 
19
  const cardRef = useRef<HTMLDivElement>(null);
20
 
@@ -57,6 +58,7 @@ export function DiscoverPage() {
57
  setDragX(0);
58
  setDragY(0);
59
  setEntering(true);
 
60
  if (currentIndex + 1 >= products.length) {
61
  loadProducts();
62
  } else {
@@ -217,13 +219,41 @@ export function DiscoverPage() {
217
  {matchPct}% match
218
  </div>
219
 
220
- <img
221
- src={current.image_url}
222
- alt={current.name}
223
- draggable={false}
224
- onClick={handleCardClick}
225
- style={{ cursor: "pointer" }}
226
- />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
 
228
  <div className="swipe-card-info" onClick={handleCardClick} style={{ cursor: "pointer" }}>
229
  <div className="swipe-brand">{current.brand}</div>
 
15
  const [dragMoved, setDragMoved] = useState(false);
16
  const [startPos, setStartPos] = useState({ x: 0, y: 0 });
17
  const [history, setHistory] = useState<Product[]>([]);
18
+ const [imgIdx, setImgIdx] = useState(0);
19
 
20
  const cardRef = useRef<HTMLDivElement>(null);
21
 
 
58
  setDragX(0);
59
  setDragY(0);
60
  setEntering(true);
61
+ setImgIdx(0);
62
  if (currentIndex + 1 >= products.length) {
63
  loadProducts();
64
  } else {
 
219
  {matchPct}% match
220
  </div>
221
 
222
+ {/* Image area with multi-image navigation */}
223
+ {(() => {
224
+ const imgs = current.image_urls?.length > 0 ? current.image_urls : [current.image_url];
225
+ const src = imgs[imgIdx] || current.image_url;
226
+ return (
227
+ <div className="swipe-image-wrap" style={{ position: "relative" }}>
228
+ <img
229
+ src={src}
230
+ alt={current.name}
231
+ draggable={false}
232
+ onClick={handleCardClick}
233
+ style={{ cursor: "pointer" }}
234
+ />
235
+ {imgs.length > 1 && (
236
+ <>
237
+ {/* Tap zones for prev/next */}
238
+ <div
239
+ className="img-nav img-nav-prev"
240
+ onClick={(e) => { e.stopPropagation(); setImgIdx((i) => (i - 1 + imgs.length) % imgs.length); }}
241
+ />
242
+ <div
243
+ className="img-nav img-nav-next"
244
+ onClick={(e) => { e.stopPropagation(); setImgIdx((i) => (i + 1) % imgs.length); }}
245
+ />
246
+ {/* Dot indicators */}
247
+ <div className="img-dots">
248
+ {imgs.map((_, i) => (
249
+ <span key={i} className={`img-dot${i === imgIdx ? " active" : ""}`} />
250
+ ))}
251
+ </div>
252
+ </>
253
+ )}
254
+ </div>
255
+ );
256
+ })()}
257
 
258
  <div className="swipe-card-info" onClick={handleCardClick} style={{ cursor: "pointer" }}>
259
  <div className="swipe-brand">{current.brand}</div>
frontend/src/types.ts CHANGED
@@ -4,6 +4,7 @@ export interface Product {
4
  price_text: string;
5
  price_nok: number;
6
  image_url: string;
 
7
  url: string;
8
  store: string;
9
  score: number;
 
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;
taste/models.py CHANGED
@@ -16,8 +16,10 @@ class Product:
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,
@@ -29,10 +31,20 @@ class Product:
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", ""),
@@ -44,4 +56,5 @@ class Product:
44
  fabric=d.get("fabric", ""),
45
  score=d.get("score", 0.0),
46
  store=d.get("store", ""),
 
47
  )
 
16
  fabric: str = ""
17
  score: float = 0.0
18
  store: str = ""
19
+ image_urls: list[str] = field(default_factory=list)
20
 
21
  def to_dict(self) -> dict:
22
+ import json
23
  return {
24
  "url": self.url,
25
  "image_url": self.image_url,
 
31
  "fabric": self.fabric,
32
  "score": self.score,
33
  "store": self.store,
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
+ import json
40
+ raw_urls = d.get("image_urls", "[]")
41
+ if isinstance(raw_urls, str):
42
+ try:
43
+ image_urls = json.loads(raw_urls)
44
+ except (json.JSONDecodeError, TypeError):
45
+ image_urls = []
46
+ else:
47
+ image_urls = raw_urls if isinstance(raw_urls, list) else []
48
  return Product(
49
  url=d.get("url", ""),
50
  image_url=d.get("image_url", ""),
 
56
  fabric=d.get("fabric", ""),
57
  score=d.get("score", 0.0),
58
  store=d.get("store", ""),
59
+ image_urls=image_urls,
60
  )
taste/scrapers/api/boozt.py CHANGED
@@ -77,11 +77,13 @@ class BooztScraper(BaseScraper):
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,
 
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,
taste/scrapers/api/miinto.py CHANGED
@@ -61,10 +61,18 @@ class MiintoScraper(BaseScraper):
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,
 
61
 
62
  photo = item.get("photo", {})
63
  image_url = photo.get("url", "") if isinstance(photo, dict) else str(photo)
64
+ # Collect all photos if available
65
+ photos = item.get("photos", [])
66
+ if photos and isinstance(photos, list):
67
+ image_urls = [p.get("url", "") if isinstance(p, dict) else str(p) for p in photos]
68
+ image_urls = [u for u in image_urls if u]
69
+ else:
70
+ image_urls = [image_url] if image_url else []
71
 
72
  products.append({
73
  "url": prod_url,
74
  "image_url": image_url,
75
+ "image_urls": image_urls,
76
  "brand": item.get("brand", ""),
77
  "name": item.get("title", item.get("name", "")),
78
  "price_nok": price_nok,
taste/scrapers/api/nakd.py CHANGED
@@ -61,9 +61,13 @@ class NakdScraper(BaseScraper):
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):
@@ -77,6 +81,7 @@ class NakdScraper(BaseScraper):
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,
 
61
  continue
62
  seen_urls.add(prod_url)
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):
 
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,
taste/scrapers/api/wakakuu.py CHANGED
@@ -44,6 +44,11 @@ class WakakuuScraper(BaseScraper):
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
@@ -72,6 +77,7 @@ class WakakuuScraper(BaseScraper):
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,
 
44
 
45
  for hit in hits:
46
  image = hit.get("imageUrl", "") or hit.get("image", "")
47
+ raw_images = hit.get("imageUrls", hit.get("images", []))
48
+ if raw_images and isinstance(raw_images, list):
49
+ image_urls = [u for u in raw_images if u]
50
+ else:
51
+ image_urls = [image] if image else []
52
 
53
  prices = hit.get("price", {})
54
  price_val = 0
 
77
  products.append({
78
  "url": product_url,
79
  "image_url": image,
80
+ "image_urls": image_urls,
81
  "brand": hit.get("brand", ""),
82
  "name": hit.get("name", hit.get("title", "")),
83
  "price_nok": price_val,
taste/store.py CHANGED
@@ -27,17 +27,25 @@ class ProductStore:
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,
@@ -45,7 +53,8 @@ class ProductStore:
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", ""),
@@ -57,14 +66,18 @@ class ProductStore:
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,
@@ -72,7 +85,8 @@ class ProductStore:
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", ""),
@@ -84,6 +98,7 @@ class ProductStore:
84
  "store": p.get("store", ""),
85
  "score": p.get("score", 0),
86
  "fabric": p.get("fabric", ""),
 
87
  })
88
  self.conn.commit()
89
 
 
27
  store TEXT DEFAULT '',
28
  score REAL DEFAULT 0,
29
  fabric TEXT DEFAULT '',
30
+ image_urls TEXT DEFAULT '[]',
31
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
32
  )
33
  """)
34
+ # Migration: add image_urls column if missing
35
+ cols = {r[1] for r in self.conn.execute("PRAGMA table_info(products)").fetchall()}
36
+ if "image_urls" not in cols:
37
+ self.conn.execute("ALTER TABLE products ADD COLUMN image_urls TEXT DEFAULT '[]'")
38
  self.conn.execute("CREATE INDEX IF NOT EXISTS idx_store ON products(store)")
39
  self.conn.execute("CREATE INDEX IF NOT EXISTS idx_score ON products(score DESC)")
40
  self.conn.commit()
41
 
42
  def upsert(self, product: dict):
43
+ image_urls = product.get("image_urls", "[]")
44
+ if isinstance(image_urls, list):
45
+ image_urls = json.dumps(image_urls)
46
  self.conn.execute("""
47
+ INSERT INTO products (url, image_url, image_path, brand, name, price_text, price_nok, store, score, fabric, image_urls)
48
+ VALUES (:url, :image_url, :image_path, :brand, :name, :price_text, :price_nok, :store, :score, :fabric, :image_urls)
49
  ON CONFLICT(url) DO UPDATE SET
50
  image_path = COALESCE(excluded.image_path, products.image_path),
51
  score = CASE WHEN excluded.score > products.score THEN excluded.score ELSE products.score END,
 
53
  name = CASE WHEN excluded.name != '' THEN excluded.name ELSE products.name END,
54
  price_text = CASE WHEN excluded.price_text != '' THEN excluded.price_text ELSE products.price_text END,
55
  price_nok = CASE WHEN excluded.price_nok > 0 THEN excluded.price_nok ELSE products.price_nok END,
56
+ fabric = CASE WHEN excluded.fabric != '' THEN excluded.fabric ELSE products.fabric END,
57
+ image_urls = CASE WHEN excluded.image_urls != '[]' THEN excluded.image_urls ELSE products.image_urls END
58
  """, {
59
  "url": product.get("url", ""),
60
  "image_url": product.get("image_url", ""),
 
66
  "store": product.get("store", ""),
67
  "score": product.get("score", 0),
68
  "fabric": product.get("fabric", ""),
69
+ "image_urls": image_urls,
70
  })
71
  self.conn.commit()
72
 
73
  def upsert_batch(self, products: list[dict]):
74
  for p in products:
75
+ image_urls = p.get("image_urls", "[]")
76
+ if isinstance(image_urls, list):
77
+ image_urls = json.dumps(image_urls)
78
  self.conn.execute("""
79
+ INSERT INTO products (url, image_url, image_path, brand, name, price_text, price_nok, store, score, fabric, image_urls)
80
+ VALUES (:url, :image_url, :image_path, :brand, :name, :price_text, :price_nok, :store, :score, :fabric, :image_urls)
81
  ON CONFLICT(url) DO UPDATE SET
82
  image_path = COALESCE(excluded.image_path, products.image_path),
83
  score = CASE WHEN excluded.score > products.score THEN excluded.score ELSE products.score END,
 
85
  name = CASE WHEN excluded.name != '' THEN excluded.name ELSE products.name END,
86
  price_text = CASE WHEN excluded.price_text != '' THEN excluded.price_text ELSE products.price_text END,
87
  price_nok = CASE WHEN excluded.price_nok > 0 THEN excluded.price_nok ELSE products.price_nok END,
88
+ fabric = CASE WHEN excluded.fabric != '' THEN excluded.fabric ELSE products.fabric END,
89
+ image_urls = CASE WHEN excluded.image_urls != '[]' THEN excluded.image_urls ELSE products.image_urls END
90
  """, {
91
  "url": p.get("url", ""),
92
  "image_url": p.get("image_url", ""),
 
98
  "store": p.get("store", ""),
99
  "score": p.get("score", 0),
100
  "fabric": p.get("fabric", ""),
101
+ "image_urls": image_urls,
102
  })
103
  self.conn.commit()
104