ghstedpixel commited on
Commit
7cbaf6e
·
verified ·
1 Parent(s): f82c018

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +42 -35
main.py CHANGED
@@ -192,7 +192,7 @@ async def handle_search(
192
  else:
193
  print(f"❄️ [Cache Miss] Initiating parallel engine verification sequence for pricing & deals...")
194
 
195
- # Dispatch Google Shopping (scan_prices) and Scraper engines simultaneously
196
  markdown_deals, product_offers = await asyncio.gather(
197
  fetch_deals_standalone(target_item),
198
  scan_prices(target_item)
@@ -206,39 +206,36 @@ async def handle_search(
206
  # Sort full array cleanly by lowest absolute price first
207
  product_offers.sort(key=lambda x: x.get('price', float('inf')))
208
 
209
- # Identify the market-wide maximum found across Google Shopping to use as our retail anchor
210
  market_max_price = max([x.get('price', 0) for x in product_offers if x.get('price', 0) > 0]) or 1.0
211
  processed_percentage_badges = []
212
 
213
- # --- START REAL-WORLD GOOGLE DISCOUNT & HISTORICAL ENGINE ---
214
  for item in product_offers:
215
  cur_p = item.get('price', 0)
216
  if not cur_p:
217
  continue
218
 
219
  item_source = item.get('source', 'Retailer').strip()
220
- badge_string = "SALE"
221
 
222
- # Step 1: Calculate percentage drop based on explicit original retail price if Google returns it
223
  old_p = item.get('original_price') or item.get('old_price') or item.get('regular_price')
 
 
224
  if old_p and float(old_p) > float(cur_p) and float(old_p) > 0:
225
- real_pct = int(round((1 - float(cur_p) / float(old_p)) * 100))
226
- if 0 < real_pct < 100:
227
- badge_string = f"{real_pct}% OFF"
 
 
228
  else:
229
- # Step 2: If no explicit MSRP, calculate the discount relative to the maximum observed Google market price
230
- market_pct = int(round((1 - cur_p / market_max_price) * 100))
231
- if market_pct > 10:
232
- badge_string = f"{market_pct}% OFF"
233
- # Set original price dynamically so UI cross-outs display beautifully
234
- item['original_price'] = round(market_max_price, 2)
235
- else:
236
- badge_string = "BEST PRICE"
237
- item['original_price'] = round(cur_p, 2)
238
 
239
- # Step 3: Core Redis Historical Memory Integration
240
- # Create a permanent, structured key inside Redis unique to this specific item model
241
- redis_history_key = f"hist_low:{target_item.lower().replace(' ', '_')}:{requested_size or 'std'}"
242
 
243
  historical_low = None
244
  if redis_client:
@@ -247,39 +244,49 @@ async def handle_search(
247
  if cached_low:
248
  historical_low = float(cached_low)
249
  except Exception as redis_err:
250
- print(f"⚠️ [Redis Registry Read Error] Failed tracking timeline baselines: {redis_err}")
251
 
252
- # Step 4: Evaluate if this specific store offering beats all historical search records
253
- if historical_low is None or cur_p < historical_low:
254
- # We found a new all-time pricing low! Update Redis permanently
 
 
 
 
 
 
 
 
255
  if redis_client:
256
- try:
257
- redis_client.set(redis_history_key, str(cur_p))
258
- except Exception as redis_err:
259
- print(f"⚠️ [Redis Registry Write Error] Failed updating track timeline: {redis_err}")
260
-
261
- # Override badge text to flag a historical drop event to the user
 
262
  badge_string = "🔥 HISTORICAL LOW"
263
  item['historical_low_event'] = True
264
  else:
265
  item['historical_low_event'] = False
266
- item['all_time_low_price'] = historical_low
 
267
 
268
- # Map unified properties to prevent front-end template rendering failures
269
  item['discount_percent'] = badge_string
270
  item['discount'] = badge_string
271
  item['percentage'] = badge_string
272
  item['badge'] = badge_string
273
 
274
- # Clean structural injection into global coupon array so dashed lines match card values
275
  if not any(c['description'] == badge_string and c['source'].lower() == item_source.lower() for c in processed_percentage_badges):
276
  processed_percentage_badges.append({
277
  "description": badge_string,
278
  "source": item_source
279
  })
280
- # --- END REAL-WORLD GOOGLE DISCOUNT & HISTORICAL ENGINE ---
281
 
282
- # Local tracking base delta analytics calculation
283
  current_lowest = product_offers[0]['price']
284
  base_price = get_base_price(target_item, requested_size, search_mode)
285
  if base_price is not None and base_price != current_lowest:
 
192
  else:
193
  print(f"❄️ [Cache Miss] Initiating parallel engine verification sequence for pricing & deals...")
194
 
195
+ # Parallel Engine Lookups
196
  markdown_deals, product_offers = await asyncio.gather(
197
  fetch_deals_standalone(target_item),
198
  scan_prices(target_item)
 
206
  # Sort full array cleanly by lowest absolute price first
207
  product_offers.sort(key=lambda x: x.get('price', float('inf')))
208
 
209
+ # Identify the global market-wide maximum found across Google Shopping to use as our markdown baseline
210
  market_max_price = max([x.get('price', 0) for x in product_offers if x.get('price', 0) > 0]) or 1.0
211
  processed_percentage_badges = []
212
 
213
+ # --- START REAL-WORLD GOOGLE DISCOUNT & GRANULAR HISTORICAL ENGINE ---
214
  for item in product_offers:
215
  cur_p = item.get('price', 0)
216
  if not cur_p:
217
  continue
218
 
219
  item_source = item.get('source', 'Retailer').strip()
220
+ item_title = item.get('title', 'Product Listing')
221
 
222
+ # Heuristic 1: Pre-calculate general market markdown metrics
223
  old_p = item.get('original_price') or item.get('old_price') or item.get('regular_price')
224
+ market_pct = int(round((1 - cur_p / market_max_price) * 100))
225
+
226
  if old_p and float(old_p) > float(cur_p) and float(old_p) > 0:
227
+ calculated_pct = int(round((1 - float(cur_p) / float(old_p)) * 100))
228
+ badge_string = f"{calculated_pct}% OFF"
229
+ elif market_pct > 10:
230
+ badge_string = f"{market_pct}% OFF"
231
+ item['original_price'] = round(market_max_price, 2)
232
  else:
233
+ badge_string = "BEST PRICE"
234
+ item['original_price'] = round(cur_p, 2)
 
 
 
 
 
 
 
235
 
236
+ # Heuristic 2: Generate unique keys per product variant to isolate history
237
+ sanitized_title = re.sub(r'[^a-zA-Z0-9]', '_', item_title).lower()[:50]
238
+ redis_history_key = f"hist_low:prod:{sanitized_title}"
239
 
240
  historical_low = None
241
  if redis_client:
 
244
  if cached_low:
245
  historical_low = float(cached_low)
246
  except Exception as redis_err:
247
+ print(f"⚠️ [Redis Error] Failed reading baseline matrix: {redis_err}")
248
 
249
+ # Heuristic 3: Intelligent Badge Evaluation Sequence
250
+ is_new_low = False
251
+ if historical_low is not None:
252
+ # If this store price beats the tracked index, trigger the event
253
+ if cur_p < historical_low:
254
+ is_new_low = True
255
+ if redis_client:
256
+ try: redis_client.set(redis_history_key, str(cur_p))
257
+ except: pass
258
+ else:
259
+ # First time seeing this product listing, set baseline silently
260
  if redis_client:
261
+ try: redis_client.set(redis_history_key, str(cur_p))
262
+ except: pass
263
+ # Only flag a new low on first crawl if it features a high-tier baseline market drop
264
+ if market_pct >= 30:
265
+ is_new_low = True
266
+
267
+ if is_new_low:
268
  badge_string = "🔥 HISTORICAL LOW"
269
  item['historical_low_event'] = True
270
  else:
271
  item['historical_low_event'] = False
272
+ if historical_low:
273
+ item['all_time_low_price'] = historical_low
274
 
275
+ # Map uniform parameters directly to product card context parameters
276
  item['discount_percent'] = badge_string
277
  item['discount'] = badge_string
278
  item['percentage'] = badge_string
279
  item['badge'] = badge_string
280
 
281
+ # Clean injection into global loop definitions
282
  if not any(c['description'] == badge_string and c['source'].lower() == item_source.lower() for c in processed_percentage_badges):
283
  processed_percentage_badges.append({
284
  "description": badge_string,
285
  "source": item_source
286
  })
287
+ # --- END REAL-WORLD GOOGLE DISCOUNT & GRANULAR HISTORICAL ENGINE ---
288
 
289
+ # Baseline calculations for local delta history tracker
290
  current_lowest = product_offers[0]['price']
291
  base_price = get_base_price(target_item, requested_size, search_mode)
292
  if base_price is not None and base_price != current_lowest: