mucahitkantepe commited on
Commit
0e3696c
·
1 Parent(s): 343fd3b

Fix discover ratings not persisting + smoother swipe animation

Browse files

- Download product image from image_url when rating if local file missing
(fixes deployed version where image_path pointed to local machine)
- Updates image_path in DB so rescore can find images
- Fixes Profile page not showing discover likes/dislikes
- Fixes taste model not updating after swipes
- Remove behind-card flash during swipe, add scale-in for new card

backend/app/routers/discover.py CHANGED
@@ -1,8 +1,10 @@
1
  """Discover / swipe endpoints — product rating with async taste model updates."""
2
 
 
3
  import threading
4
  from pathlib import Path
5
 
 
6
  from fastapi import APIRouter, Body
7
 
8
  from backend.app.deps import get_store, get_engine, get_config
@@ -170,14 +172,39 @@ def _ensure_discover_table(conn):
170
 
171
 
172
  def _save_product_rating(url: str, rating_val: int, store, engine):
173
- """Save product image as liked (1) or disliked (-1) in the taste engine."""
 
 
 
174
  row = store.conn.execute(
175
- "SELECT image_path FROM products WHERE url = ?", (url,)
176
  ).fetchone()
177
- if row and row["image_path"]:
178
- p = Path(row["image_path"])
179
- if p.exists():
180
- engine.save_rating(p, rating_val)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
 
182
 
183
  def _trigger_async_rescore():
@@ -209,7 +236,7 @@ def _do_rescore():
209
  store.conn.execute("UPDATE discover_ratings SET processed = 1 WHERE processed = 0")
210
  store.conn.commit()
211
 
212
- # Rescore ALL products (not just low scores — taste changed)
213
  rows = store.conn.execute("""
214
  SELECT url, image_path FROM products WHERE image_path != ''
215
  """).fetchall()
@@ -219,6 +246,8 @@ def _do_rescore():
219
  paths_batch, urls_batch = [], []
220
 
221
  for r in rows:
 
 
222
  p = Path(r["image_path"])
223
  if p.exists():
224
  paths_batch.append(p)
 
1
  """Discover / swipe endpoints — product rating with async taste model updates."""
2
 
3
+ import hashlib
4
  import threading
5
  from pathlib import Path
6
 
7
+ import httpx
8
  from fastapi import APIRouter, Body
9
 
10
  from backend.app.deps import get_store, get_engine, get_config
 
172
 
173
 
174
  def _save_product_rating(url: str, rating_val: int, store, engine):
175
+ """Save product image as liked (1) or disliked (-1) in the taste engine.
176
+
177
+ Downloads the image from image_url if the local file doesn't exist.
178
+ """
179
  row = store.conn.execute(
180
+ "SELECT image_path, image_url FROM products WHERE url = ?", (url,)
181
  ).fetchone()
182
+ if not row:
183
+ return
184
+
185
+ p = Path(row["image_path"]) if row["image_path"] else None
186
+
187
+ # If local file doesn't exist, download from image_url
188
+ if (not p or not p.exists()) and row["image_url"]:
189
+ config = get_config()
190
+ dl_dir = config.data_dir / "discover-images"
191
+ dl_dir.mkdir(parents=True, exist_ok=True)
192
+ h = hashlib.md5(row["image_url"].encode()).hexdigest()[:12]
193
+ p = dl_dir / f"{h}.jpg"
194
+ if not p.exists():
195
+ try:
196
+ resp = httpx.get(row["image_url"], timeout=15, follow_redirects=True)
197
+ resp.raise_for_status()
198
+ p.write_bytes(resp.content)
199
+ except Exception as e:
200
+ print(f"[discover] Failed to download image: {e}", flush=True)
201
+ return
202
+ # Update image_path in DB so future operations find it
203
+ store.conn.execute("UPDATE products SET image_path = ? WHERE url = ?", (str(p), url))
204
+ store.conn.commit()
205
+
206
+ if p and p.exists():
207
+ engine.save_rating(p, rating_val)
208
 
209
 
210
  def _trigger_async_rescore():
 
236
  store.conn.execute("UPDATE discover_ratings SET processed = 1 WHERE processed = 0")
237
  store.conn.commit()
238
 
239
+ # Rescore ALL products that have local images
240
  rows = store.conn.execute("""
241
  SELECT url, image_path FROM products WHERE image_path != ''
242
  """).fetchall()
 
246
  paths_batch, urls_batch = [], []
247
 
248
  for r in rows:
249
+ if not r["image_path"]:
250
+ continue
251
  p = Path(r["image_path"])
252
  if p.exists():
253
  paths_batch.append(p)
frontend/src/pages/DiscoverPage.tsx CHANGED
@@ -8,6 +8,7 @@ export function DiscoverPage() {
8
  const [stats, setStats] = useState<DiscoverStats>({ total: 0, likes: 0, dislikes: 0, skips: 0 });
9
  const [loading, setLoading] = useState(true);
10
  const [swiping, setSwiping] = useState<"left" | "right" | "up" | null>(null);
 
11
  const [dragX, setDragX] = useState(0);
12
  const [dragY, setDragY] = useState(0);
13
  const [dragging, setDragging] = useState(false);
@@ -34,7 +35,6 @@ export function DiscoverPage() {
34
  }, [loadProducts]);
35
 
36
  const current = products[currentIndex];
37
- const next = products[currentIndex + 1];
38
 
39
  const handleRate = async (rating: "like" | "dislike" | "skip") => {
40
  if (!current || swiping) return;
@@ -56,12 +56,17 @@ export function DiscoverPage() {
56
  setSwiping(null);
57
  setDragX(0);
58
  setDragY(0);
 
59
  if (currentIndex + 1 >= products.length) {
60
  loadProducts();
61
  } else {
62
  setCurrentIndex((i) => i + 1);
63
  }
64
- }, 300);
 
 
 
 
65
  };
66
 
67
  const handleUndo = async () => {
@@ -136,15 +141,16 @@ export function DiscoverPage() {
136
  return () => window.removeEventListener("keydown", handler);
137
  });
138
 
139
- const getCardStyle = () => {
140
- if (swiping === "right") return { transform: "translateX(120%) rotate(20deg)", opacity: 0, transition: "all 0.3s ease-out" };
141
- if (swiping === "left") return { transform: "translateX(-120%) rotate(-20deg)", opacity: 0, transition: "all 0.3s ease-out" };
142
- if (swiping === "up") return { transform: "translateY(-120%)", opacity: 0, transition: "all 0.3s ease-out" };
143
  if (dragging || dragX !== 0 || dragY !== 0) {
144
  const rotate = dragX * 0.1;
145
  return { transform: `translate(${dragX}px, ${dragY}px) rotate(${rotate}deg)`, transition: dragging ? "none" : "all 0.3s ease-out" };
146
  }
147
- return { transform: "translate(0, 0) rotate(0deg)", transition: "all 0.3s ease-out" };
 
148
  };
149
 
150
  const getIndicator = () => {
@@ -189,12 +195,6 @@ export function DiscoverPage() {
189
  </div>
190
 
191
  <div className="swipe-area">
192
- {next && (
193
- <div className="swipe-card swipe-card-behind">
194
- <img src={next.image_url} alt={next.name} />
195
- </div>
196
- )}
197
-
198
  <div
199
  ref={cardRef}
200
  className="swipe-card swipe-card-active"
 
8
  const [stats, setStats] = useState<DiscoverStats>({ total: 0, likes: 0, dislikes: 0, skips: 0 });
9
  const [loading, setLoading] = useState(true);
10
  const [swiping, setSwiping] = useState<"left" | "right" | "up" | null>(null);
11
+ const [entering, setEntering] = useState(false);
12
  const [dragX, setDragX] = useState(0);
13
  const [dragY, setDragY] = useState(0);
14
  const [dragging, setDragging] = useState(false);
 
35
  }, [loadProducts]);
36
 
37
  const current = products[currentIndex];
 
38
 
39
  const handleRate = async (rating: "like" | "dislike" | "skip") => {
40
  if (!current || swiping) return;
 
56
  setSwiping(null);
57
  setDragX(0);
58
  setDragY(0);
59
+ setEntering(true);
60
  if (currentIndex + 1 >= products.length) {
61
  loadProducts();
62
  } else {
63
  setCurrentIndex((i) => i + 1);
64
  }
65
+ // Let the new card appear, then animate it in
66
+ requestAnimationFrame(() => {
67
+ requestAnimationFrame(() => setEntering(false));
68
+ });
69
+ }, 250);
70
  };
71
 
72
  const handleUndo = async () => {
 
141
  return () => window.removeEventListener("keydown", handler);
142
  });
143
 
144
+ const getCardStyle = (): React.CSSProperties => {
145
+ if (swiping === "right") return { transform: "translateX(120%) rotate(20deg)", opacity: 0, transition: "all 0.25s ease-out" };
146
+ if (swiping === "left") return { transform: "translateX(-120%) rotate(-20deg)", opacity: 0, transition: "all 0.25s ease-out" };
147
+ if (swiping === "up") return { transform: "translateY(-120%)", opacity: 0, transition: "all 0.25s ease-out" };
148
  if (dragging || dragX !== 0 || dragY !== 0) {
149
  const rotate = dragX * 0.1;
150
  return { transform: `translate(${dragX}px, ${dragY}px) rotate(${rotate}deg)`, transition: dragging ? "none" : "all 0.3s ease-out" };
151
  }
152
+ if (entering) return { transform: "scale(0.95)", opacity: 0, transition: "none" };
153
+ return { transform: "translate(0, 0) rotate(0deg) scale(1)", opacity: 1, transition: "all 0.2s ease-out" };
154
  };
155
 
156
  const getIndicator = () => {
 
195
  </div>
196
 
197
  <div className="swipe-area">
 
 
 
 
 
 
198
  <div
199
  ref={cardRef}
200
  className="swipe-card swipe-card-active"