Spaces:
Sleeping
Sleeping
Update shopping.py
Browse files- shopping.py +41 -64
shopping.py
CHANGED
|
@@ -47,61 +47,33 @@ async def fetch_serpapi_shopping(product_name: str, desired_size: str, client: h
|
|
| 47 |
if desired_size and is_size_mismatched(desired_size, combined_text): continue
|
| 48 |
|
| 49 |
price_val = item.get("extracted_price")
|
| 50 |
-
|
| 51 |
-
# --- START DIRECT PRODUCT PAGE EXTRACTION MACHINE ---
|
| 52 |
raw_link = item.get("merchant_link") or item.get("link") or item.get("product_link") or ""
|
| 53 |
|
| 54 |
-
#
|
| 55 |
if "google.com" in raw_link:
|
| 56 |
try:
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
except:
|
| 65 |
pass
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
if "google.com
|
| 69 |
-
|
| 70 |
-
if item_source and "google" not in item_source.lower():
|
| 71 |
-
src_lower = item_source.lower()
|
| 72 |
-
q_encoded = urllib.parse.quote_plus(title)
|
| 73 |
-
|
| 74 |
-
if "amazon" in src_lower:
|
| 75 |
-
raw_link = f"https://www.amazon.com/s?k={q_encoded}"
|
| 76 |
-
elif "puma" in src_lower:
|
| 77 |
-
raw_link = f"https://www.puma.com/search?q={q_encoded}"
|
| 78 |
-
elif "nike" in src_lower:
|
| 79 |
-
raw_link = f"https://www.nike.com/w?q={q_encoded}"
|
| 80 |
-
elif "adidas" in src_lower:
|
| 81 |
-
raw_link = f"https://www.adidas.com/us/search?q={q_encoded}"
|
| 82 |
-
elif "walmart" in src_lower:
|
| 83 |
-
raw_link = f"https://www.walmart.com/search?q={q_encoded}"
|
| 84 |
-
elif "ebay" in src_lower:
|
| 85 |
-
raw_link = f"https://www.ebay.com/sch/i.html?_nkw={q_encoded}"
|
| 86 |
-
elif "target" in src_lower:
|
| 87 |
-
raw_link = f"https://www.target.com/s?searchTerm={q_encoded}"
|
| 88 |
-
elif "best buy" in src_lower or "bestbuy" in src_lower:
|
| 89 |
-
raw_link = f"https://www.bestbuy.com/site/searchpage.jsp?st={q_encoded}"
|
| 90 |
-
elif "nordstrom" in src_lower:
|
| 91 |
-
raw_link = f"https://www.nordstrom.com/sr?keyword={q_encoded}"
|
| 92 |
-
elif "sephora" in src_lower:
|
| 93 |
-
raw_link = f"https://www.sephora.com/search?keyword={q_encoded}"
|
| 94 |
-
elif "jomashop" in src_lower:
|
| 95 |
-
raw_link = f"https://www.jomashop.com/search?q={q_encoded}"
|
| 96 |
-
elif "." in src_lower:
|
| 97 |
-
raw_link = f"https://www.{src_lower.replace('www.', '')}/search?q={q_encoded}"
|
| 98 |
-
else:
|
| 99 |
-
sanitized_src = re.sub(r'[^a-z0-9]', '', src_lower)
|
| 100 |
-
raw_link = f"https://www.{sanitized_src}.com/search?q={q_encoded}"
|
| 101 |
|
| 102 |
link = clean_google_link(raw_link)
|
| 103 |
-
# --- END DIRECT PRODUCT PAGE EXTRACTION MACHINE ---
|
| 104 |
-
|
| 105 |
detected_size = desired_size if desired_size else (extract_universal_sizing(title) or "Standard")
|
| 106 |
rating = item.get("rating")
|
| 107 |
reviews = item.get("reviews") or item.get("review_count")
|
|
@@ -241,7 +213,6 @@ async def scan_prices(product_name: str, desired_size: str = "", mode: str = "ba
|
|
| 241 |
limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)
|
| 242 |
|
| 243 |
async with httpx.AsyncClient(limits=limits, http2=False, trust_env=False) as client:
|
| 244 |
-
# Step 1: Fire core Google matrix and Tavily unstructured channels concurrently
|
| 245 |
deals, scraped_pages = await asyncio.gather(
|
| 246 |
fetch_serpapi_shopping(product_name, desired_size, client, mode=mode),
|
| 247 |
get_tavily_payload(product_name, desired_size, client, mode=mode)
|
|
@@ -252,10 +223,10 @@ async def scan_prices(product_name: str, desired_size: str = "", mode: str = "ba
|
|
| 252 |
scraped_pages = await fetch_ddg_backup_shopping(product_name, desired_size, client, mode=mode)
|
| 253 |
|
| 254 |
results = []
|
| 255 |
-
if scraped_pages
|
| 256 |
mode_constraint = ""
|
| 257 |
if mode == "exact":
|
| 258 |
-
mode_constraint = f"STRICT CONSTRAINT: The extracted product name MUST be a direct contextual equivalent or contain core nouns of '{product_name}'.
|
| 259 |
elif mode == "broad":
|
| 260 |
mode_constraint = "FLEXIBLE CONSTRAINT: Allow alternative variations, complete setups, categories, or similar brand designs."
|
| 261 |
|
|
@@ -316,12 +287,28 @@ async def scan_prices(product_name: str, desired_size: str = "", mode: str = "ba
|
|
| 316 |
"size": desired_size or "Standard"
|
| 317 |
})
|
| 318 |
|
| 319 |
-
|
| 320 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
|
| 322 |
print("🔒 [Safe Browsing] Pre-filtering target array matrix outputs against phishing and malware definitions...")
|
| 323 |
-
security_mask = await asyncio.gather(*[check_url_safe(item['url'], client) for item in
|
| 324 |
-
vetted_safe_deals = [item for item, is_secure in zip(
|
| 325 |
|
| 326 |
if mode == "exact" and desired_size:
|
| 327 |
vetted_safe_deals = [item for item in vetted_safe_deals if not is_size_mismatched(desired_size, item.get('size', ''))]
|
|
@@ -336,28 +323,18 @@ async def scan_prices(product_name: str, desired_size: str = "", mode: str = "ba
|
|
| 336 |
else:
|
| 337 |
item["is_third_party"] = False
|
| 338 |
|
| 339 |
-
# Calculate base descriptive markers before checking Amazon
|
| 340 |
median_price = 0.0
|
| 341 |
if len(vetted_safe_deals) >= 2:
|
| 342 |
sorted_p = sorted([d['price'] for d in vetted_safe_deals])
|
| 343 |
median_price = sorted_p[len(sorted_p) // 2]
|
| 344 |
|
| 345 |
-
# =====================================================================
|
| 346 |
-
# RATE LIMIT SAVER GATEWAY: CONDITIONAL AMAZON HOOKS
|
| 347 |
-
# =====================================================================
|
| 348 |
should_trigger_amazon = False
|
| 349 |
-
|
| 350 |
-
# Condition A: User explicitly requested an exact precision checkout verification scan
|
| 351 |
if mode == "exact":
|
| 352 |
should_trigger_amazon = True
|
| 353 |
print("🛡️ [Quota Shield] Precision match active. Routing Amazon anchor verification...")
|
| 354 |
-
|
| 355 |
-
# Condition B: Initial baseline scans flag a high potential price crater
|
| 356 |
elif vetted_safe_deals and median_price > 0:
|
| 357 |
lowest_p = vetted_safe_deals[0]['price']
|
| 358 |
next_p = vetted_safe_deals[1]['price'] if len(vetted_safe_deals) > 1 else lowest_p
|
| 359 |
-
|
| 360 |
-
# Anomaly indicators: 50% drop from standard median OR a massive cliff step to row 2
|
| 361 |
if (median_price - lowest_p) / median_price >= 0.40 or (next_p / lowest_p if lowest_p > 0 else 1) >= 2.0:
|
| 362 |
should_trigger_amazon = True
|
| 363 |
print("🚨 [Quota Shield] Price crater drop context caught. Activating Amazon validation stream...")
|
|
@@ -366,7 +343,7 @@ async def scan_prices(product_name: str, desired_size: str = "", mode: str = "ba
|
|
| 366 |
amazon_deals = await fetch_free_serpapi_amazon(product_name, desired_size, client)
|
| 367 |
if amazon_deals:
|
| 368 |
vetted_safe_deals.extend(amazon_deals)
|
| 369 |
-
vetted_safe_deals.sort(key=lambda x: x['price'])
|
| 370 |
|
| 371 |
# Upgraded Price-Cliff Anomaly Detector Math Engine
|
| 372 |
if len(vetted_safe_deals) >= 3:
|
|
|
|
| 47 |
if desired_size and is_size_mismatched(desired_size, combined_text): continue
|
| 48 |
|
| 49 |
price_val = item.get("extracted_price")
|
|
|
|
|
|
|
| 50 |
raw_link = item.get("merchant_link") or item.get("link") or item.get("product_link") or ""
|
| 51 |
|
| 52 |
+
# Multi-Pass Deep Unwrapper Loop
|
| 53 |
if "google.com" in raw_link:
|
| 54 |
try:
|
| 55 |
+
for _ in range(3):
|
| 56 |
+
parsed_query = urllib.parse.parse_qs(urllib.parse.urlparse(raw_link).query)
|
| 57 |
+
found_nested = False
|
| 58 |
+
for param_key in ["q", "url", "adurl", "u", "link"]:
|
| 59 |
+
if param_key in parsed_query:
|
| 60 |
+
candidate = parsed_query[param_key][0]
|
| 61 |
+
if "http" in candidate:
|
| 62 |
+
if not candidate.startswith("http"):
|
| 63 |
+
candidate = candidate[candidate.find("http"):]
|
| 64 |
+
raw_link = urllib.parse.unquote(candidate)
|
| 65 |
+
found_nested = True
|
| 66 |
+
break
|
| 67 |
+
if not found_nested:
|
| 68 |
+
break
|
| 69 |
except:
|
| 70 |
pass
|
| 71 |
|
| 72 |
+
# CRITICAL DIRECTIVITY GATE: Discard comparison page references entirely. No artificial search strings are forced.
|
| 73 |
+
if "google.com" in raw_link:
|
| 74 |
+
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
link = clean_google_link(raw_link)
|
|
|
|
|
|
|
| 77 |
detected_size = desired_size if desired_size else (extract_universal_sizing(title) or "Standard")
|
| 78 |
rating = item.get("rating")
|
| 79 |
reviews = item.get("reviews") or item.get("review_count")
|
|
|
|
| 213 |
limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)
|
| 214 |
|
| 215 |
async with httpx.AsyncClient(limits=limits, http2=False, trust_env=False) as client:
|
|
|
|
| 216 |
deals, scraped_pages = await asyncio.gather(
|
| 217 |
fetch_serpapi_shopping(product_name, desired_size, client, mode=mode),
|
| 218 |
get_tavily_payload(product_name, desired_size, client, mode=mode)
|
|
|
|
| 223 |
scraped_pages = await fetch_ddg_backup_shopping(product_name, desired_size, client, mode=mode)
|
| 224 |
|
| 225 |
results = []
|
| 226 |
+
if scraped_pages:
|
| 227 |
mode_constraint = ""
|
| 228 |
if mode == "exact":
|
| 229 |
+
mode_constraint = f"STRICT CONSTRAINT: The extracted product name MUST be a direct contextual equivalent or contain core nouns of '{product_name}'."
|
| 230 |
elif mode == "broad":
|
| 231 |
mode_constraint = "FLEXIBLE CONSTRAINT: Allow alternative variations, complete setups, categories, or similar brand designs."
|
| 232 |
|
|
|
|
| 287 |
"size": desired_size or "Standard"
|
| 288 |
})
|
| 289 |
|
| 290 |
+
# --- BLENDING AND DYNAMIC STREAM SELECTION ---
|
| 291 |
+
# Collect verified deep store elements first, explicitly bypassing any residual google wrappers
|
| 292 |
+
vetted_safe_deals = []
|
| 293 |
+
for d in deals:
|
| 294 |
+
if "google.com" not in d.get("url", ""):
|
| 295 |
+
vetted_safe_deals.append(d)
|
| 296 |
+
|
| 297 |
+
for r in results:
|
| 298 |
+
if not any(v['url'] == r['url'] for v in vetted_safe_deals):
|
| 299 |
+
if r.get("url") and "google.com" not in r["url"]:
|
| 300 |
+
vetted_safe_deals.append(r)
|
| 301 |
+
|
| 302 |
+
if len(vetted_safe_deals) < 3:
|
| 303 |
+
for d in deals:
|
| 304 |
+
if d not in vetted_safe_deals and "google.com" not in d.get("url", ""):
|
| 305 |
+
vetted_safe_deals.append(d)
|
| 306 |
+
|
| 307 |
+
if not vetted_safe_deals: return []
|
| 308 |
|
| 309 |
print("🔒 [Safe Browsing] Pre-filtering target array matrix outputs against phishing and malware definitions...")
|
| 310 |
+
security_mask = await asyncio.gather(*[check_url_safe(item['url'], client) for item in vetted_safe_deals])
|
| 311 |
+
vetted_safe_deals = [item for item, is_secure in zip(vetted_safe_deals, security_mask) if is_secure]
|
| 312 |
|
| 313 |
if mode == "exact" and desired_size:
|
| 314 |
vetted_safe_deals = [item for item in vetted_safe_deals if not is_size_mismatched(desired_size, item.get('size', ''))]
|
|
|
|
| 323 |
else:
|
| 324 |
item["is_third_party"] = False
|
| 325 |
|
|
|
|
| 326 |
median_price = 0.0
|
| 327 |
if len(vetted_safe_deals) >= 2:
|
| 328 |
sorted_p = sorted([d['price'] for d in vetted_safe_deals])
|
| 329 |
median_price = sorted_p[len(sorted_p) // 2]
|
| 330 |
|
|
|
|
|
|
|
|
|
|
| 331 |
should_trigger_amazon = False
|
|
|
|
|
|
|
| 332 |
if mode == "exact":
|
| 333 |
should_trigger_amazon = True
|
| 334 |
print("🛡️ [Quota Shield] Precision match active. Routing Amazon anchor verification...")
|
|
|
|
|
|
|
| 335 |
elif vetted_safe_deals and median_price > 0:
|
| 336 |
lowest_p = vetted_safe_deals[0]['price']
|
| 337 |
next_p = vetted_safe_deals[1]['price'] if len(vetted_safe_deals) > 1 else lowest_p
|
|
|
|
|
|
|
| 338 |
if (median_price - lowest_p) / median_price >= 0.40 or (next_p / lowest_p if lowest_p > 0 else 1) >= 2.0:
|
| 339 |
should_trigger_amazon = True
|
| 340 |
print("🚨 [Quota Shield] Price crater drop context caught. Activating Amazon validation stream...")
|
|
|
|
| 343 |
amazon_deals = await fetch_free_serpapi_amazon(product_name, desired_size, client)
|
| 344 |
if amazon_deals:
|
| 345 |
vetted_safe_deals.extend(amazon_deals)
|
| 346 |
+
vetted_safe_deals.sort(key=lambda x: x['price'])
|
| 347 |
|
| 348 |
# Upgraded Price-Cliff Anomaly Detector Math Engine
|
| 349 |
if len(vetted_safe_deals) >= 3:
|