Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -24,7 +24,6 @@ except ImportError:
|
|
| 24 |
app = FastAPI()
|
| 25 |
|
| 26 |
# --- RATE LIMIT PROTECTION CONTEXTS ---
|
| 27 |
-
# Restricts concurrent DuckDuckGo scraping loops across the entire server instance
|
| 28 |
DDG_SEMAPHORE = asyncio.Semaphore(2)
|
| 29 |
|
| 30 |
# --- GATHER AND VALIDATE SECRET KEYS FROM ENVIRONMENT ---
|
|
@@ -64,17 +63,17 @@ if REDIS_AVAILABLE and REDIS_URL:
|
|
| 64 |
print(f"⚠️ [Cache Setup] Redis connection failed ({e}). Defaulting to internal memory arrays.")
|
| 65 |
redis_client = None
|
| 66 |
|
| 67 |
-
def get_cache_key(product_name: str, size: str = "") -> str:
|
| 68 |
-
"""Generates a unique deterministic cache key combining name and
|
| 69 |
clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip())
|
| 70 |
clean_size = re.sub(r'[^a-z0-9 ]', '', size.lower().strip()) if size else "nosize"
|
| 71 |
clean_name = clean_name.replace(" ", "_")
|
| 72 |
clean_size = clean_size.replace(" ", "_")
|
| 73 |
-
return f"tarz:cache:{clean_name}:{clean_size}"
|
| 74 |
|
| 75 |
-
def get_cached_deals(product_name: str, size: str = "") -> list:
|
| 76 |
"""Retrieves cached pricing data array if available and unexpired"""
|
| 77 |
-
key = get_cache_key(product_name, size)
|
| 78 |
if redis_client:
|
| 79 |
try:
|
| 80 |
data = redis_client.get(key)
|
|
@@ -91,11 +90,11 @@ def get_cached_deals(product_name: str, size: str = "") -> list:
|
|
| 91 |
del IN_MEMORY_EXPIRY[key]
|
| 92 |
return None
|
| 93 |
|
| 94 |
-
def set_cached_deals(product_name: str, size: str, deals: list):
|
| 95 |
"""Caches product list matrix with strict 2-hour sliding validation lifetime"""
|
| 96 |
if not deals:
|
| 97 |
return
|
| 98 |
-
key = get_cache_key(product_name, size)
|
| 99 |
if redis_client:
|
| 100 |
try:
|
| 101 |
redis_client.setex(key, 7200, json.dumps(deals))
|
|
@@ -124,10 +123,7 @@ def set_cached_coupons(product_name: str, coupons: list):
|
|
| 124 |
"""Caches discovered active promo strings (saves empty results for 15 mins to prevent loop spam)"""
|
| 125 |
clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip()).replace(" ", "_")
|
| 126 |
key = f"tarz:coupons:{clean_name}"
|
| 127 |
-
|
| 128 |
-
# Negative caching mitigation strategy: if empty list, lower expiration duration
|
| 129 |
duration = 7200 if coupons else 900
|
| 130 |
-
|
| 131 |
if redis_client:
|
| 132 |
try:
|
| 133 |
redis_client.setex(key, duration, json.dumps(coupons))
|
|
@@ -331,12 +327,12 @@ def extract_page_data(url, product_name):
|
|
| 331 |
except: return None, None
|
| 332 |
|
| 333 |
# --- SERPAPI GOOGLE SHOPPING ENGINE ---
|
| 334 |
-
async def fetch_serpapi_shopping(product_name: str, desired_size: str, client: httpx.AsyncClient) -> list:
|
| 335 |
"""Queries SerpApi Google Shopping engine for pristine structured retail data"""
|
| 336 |
if not SERPAPI_KEY: return []
|
| 337 |
|
| 338 |
search_query = f"{product_name} {desired_size}".strip() if desired_size else product_name
|
| 339 |
-
print(f"🛍️ [SerpApi] Dispatching Shopping query vector: '{search_query}'")
|
| 340 |
|
| 341 |
params = {
|
| 342 |
"engine": "google_shopping",
|
|
@@ -355,7 +351,8 @@ async def fetch_serpapi_shopping(product_name: str, desired_size: str, client: h
|
|
| 355 |
title = item.get("title", "")
|
| 356 |
snippet = item.get("snippet", "")
|
| 357 |
|
| 358 |
-
|
|
|
|
| 359 |
continue
|
| 360 |
|
| 361 |
price_val = item.get("extracted_price")
|
|
@@ -376,7 +373,7 @@ async def fetch_serpapi_shopping(product_name: str, desired_size: str, client: h
|
|
| 376 |
return []
|
| 377 |
|
| 378 |
# --- TEXT PAYLOAD RETRIEVAL VIA TAVILY ---
|
| 379 |
-
async def get_tavily_payload(query: str, desired_size: str, client: httpx.AsyncClient) -> list:
|
| 380 |
"""Queries Tavily to assemble unstructured fallback content blocks with image assets unblocked"""
|
| 381 |
scraped_pages = []
|
| 382 |
if not TAVILY_API_KEY: return scraped_pages
|
|
@@ -398,7 +395,7 @@ async def get_tavily_payload(query: str, desired_size: str, client: httpx.AsyncC
|
|
| 398 |
url_str = item.get("url", "")
|
| 399 |
content_str = item.get("content", "")
|
| 400 |
|
| 401 |
-
if desired_size and is_size_mismatched(desired_size, f"{content_str}"):
|
| 402 |
continue
|
| 403 |
|
| 404 |
img_url = item.get("raw_data", {}).get("og:image") if isinstance(item.get("raw_data"), dict) else None
|
|
@@ -414,19 +411,16 @@ async def get_tavily_payload(query: str, desired_size: str, client: httpx.AsyncC
|
|
| 414 |
return scraped_pages
|
| 415 |
|
| 416 |
# --- 100% FREE ROUTER ROUTE: DUCKDUCKGO HTML KEYLESS FALLBACK ENGINE ---
|
| 417 |
-
async def fetch_ddg_backup_shopping(product_name: str, desired_size: str, client: httpx.AsyncClient) -> list:
|
| 418 |
"""Performs structured context harvesting via DuckDuckGo with instance traffic safety throttles applied"""
|
| 419 |
scraped_pages = []
|
| 420 |
search_q = f"buy {product_name} {desired_size} retail price".strip()
|
| 421 |
url = f"https://html.duckduckgo.com/html/?q={requests.utils.quote(search_q)}"
|
| 422 |
headers = {"User-Agent": random.choice(USER_AGENTS)}
|
| 423 |
|
| 424 |
-
# Secure execution context block utilizing instances limits to preserve outbound IP sanity
|
| 425 |
async with DDG_SEMAPHORE:
|
| 426 |
try:
|
| 427 |
-
# Inject anti-bot break jitter (avoids systematic linear timing blocks)
|
| 428 |
await asyncio.sleep(random.uniform(0.3, 0.7))
|
| 429 |
-
|
| 430 |
print(f"🦆 [DuckDuckGo Fallback] Routing zero-cost backup query pipeline for '{search_q}'")
|
| 431 |
res = await client.get(url, headers=headers, timeout=8.0)
|
| 432 |
if res.status_code == 200:
|
|
@@ -438,7 +432,7 @@ async def fetch_ddg_backup_shopping(product_name: str, desired_size: str, client
|
|
| 438 |
if a_tag and snippet_tag:
|
| 439 |
snippet_text = snippet_tag.get_text()
|
| 440 |
|
| 441 |
-
if desired_size and is_size_mismatched(desired_size, snippet_text):
|
| 442 |
continue
|
| 443 |
|
| 444 |
raw_href = a_tag.get('href', '')
|
|
@@ -468,12 +462,9 @@ async def fetch_active_coupons(product_name: str, client: httpx.AsyncClient) ->
|
|
| 468 |
headers = {"User-Agent": random.choice(USER_AGENTS)}
|
| 469 |
snippets = []
|
| 470 |
|
| 471 |
-
# Enforces explicit queuing to stop multiple requests from combining into single burst vectors
|
| 472 |
async with DDG_SEMAPHORE:
|
| 473 |
try:
|
| 474 |
-
# Humanizing pipeline pacing delay
|
| 475 |
await asyncio.sleep(random.uniform(0.4, 0.8))
|
| 476 |
-
|
| 477 |
print(f"🎟️ [Coupon Engine] Hunting active promotional tags for '{product_name}'...")
|
| 478 |
res = await client.get(url, headers=headers, timeout=6.0)
|
| 479 |
if res.status_code == 200:
|
|
@@ -497,11 +488,12 @@ async def fetch_active_coupons(product_name: str, client: httpx.AsyncClient) ->
|
|
| 497 |
prompt = f"""
|
| 498 |
Analyze the following search snippets containing discount indicators for '{product_name}'.
|
| 499 |
Identify and isolate any specific, functioning alphanumeric promo codes, coupon tokens, or active structural store discount descriptions.
|
|
|
|
| 500 |
|
| 501 |
Return ONLY a raw JSON array string matching the explicit syntax structure below. No explanation, no markdown text wrappers.
|
| 502 |
[
|
| 503 |
-
{{"code": "SUMMER20", "description": "20% off all items storewide", "source": "Target
|
| 504 |
-
{{"code": "
|
| 505 |
]
|
| 506 |
|
| 507 |
Snippets Pool:
|
|
@@ -517,28 +509,36 @@ async def fetch_active_coupons(product_name: str, client: httpx.AsyncClient) ->
|
|
| 517 |
return []
|
| 518 |
|
| 519 |
# --- MASTER PRICE SWEEPER SEQUENCE (CASCADING MULTI-ENGINE ROUTER) ---
|
| 520 |
-
async def scan_prices(product_name, desired_size=""):
|
| 521 |
"""Orchestrates structured arrays across all endpoints concurrently while bypassing broken environment proxies"""
|
| 522 |
limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)
|
| 523 |
|
| 524 |
async with httpx.AsyncClient(limits=limits, http2=True, trust_env=False) as client:
|
| 525 |
-
deals = await fetch_serpapi_shopping(product_name, desired_size, client)
|
| 526 |
|
| 527 |
scraped_pages = []
|
| 528 |
if not deals:
|
| 529 |
print("🔄 [Engine Cascader] Primary structured inventory returned empty. Initiating Tavily content harvesting channels...")
|
| 530 |
-
scraped_pages = await get_tavily_payload(product_name, desired_size, client)
|
| 531 |
|
| 532 |
if not scraped_pages:
|
| 533 |
print("🦆 [Engine Cascader] Secondary API pools empty. Initiating 100% free open DuckDuckGo scrape clusters...")
|
| 534 |
-
scraped_pages = await fetch_ddg_backup_shopping(product_name, desired_size, client)
|
| 535 |
|
| 536 |
results = []
|
| 537 |
if scraped_pages and not deals:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 538 |
batch_instructions = f"""
|
| 539 |
Analyze the text blocks extracted from up to 5 separate websites.
|
| 540 |
Find if the product '{product_name}' is explicitly sold on each site and extract its current numerical retail price.
|
| 541 |
Also check if a specific sizing variant is being sold on the page.
|
|
|
|
| 542 |
|
| 543 |
Return ONLY a raw JSON array matching the structure below. Do not include markdown blocks or text wrappers.
|
| 544 |
Format example string to output:
|
|
@@ -643,20 +643,23 @@ def generate_ui(results_html="", error_msg=""):
|
|
| 643 |
|
| 644 |
.input-flex {{ display: flex; gap: 16px; margin-bottom: 20px; }}
|
| 645 |
.input-group {{ display: flex; flex-direction: column; flex-grow: 1; min-width: 0; }}
|
| 646 |
-
.input-group.size-group {{ flex-grow: 0; width:
|
|
|
|
| 647 |
|
| 648 |
label {{ margin-bottom: 8px; font-weight: 500; color: var(--text-muted); font-size: 13px; }}
|
| 649 |
-
input[type="text"] {{ background: var(--input-bg); border: 1px solid var(--border-color); color: white; padding: 14px 16px; border-radius: 10px; font-size: 15px; transition: all 0.3s ease; font-family: inherit; width: 100%; }}
|
| 650 |
-
|
|
|
|
| 651 |
|
| 652 |
button {{ background: var(--accent-gradient); color: white; border: none; padding: 14px 24px; border-radius: 10px; cursor: pointer; font-weight: 600; font-size: 15px; transition: all 0.2s ease; display: inline-flex; align-items: center; justify-content: center; gap: 8px; width: 100%; box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2); font-family: inherit; }}
|
| 653 |
button:hover {{ transform: translateY(-1px); box-shadow: 0 6px 16px rgba(59, 130, 246, 0.3); }}
|
| 654 |
|
| 655 |
ul {{ list-style-type: none; padding: 0; margin: 0; }}
|
| 656 |
-
li {{ background: rgba(255, 255, 255, 0.02); padding: 14px 18px; border-radius: 12px; margin-bottom: 12px; border: 1px solid var(--border-color); display: flex;
|
| 657 |
li:hover {{ border-color: rgba(255, 255, 255, 0.15); background: rgba(255, 255, 255, 0.04); }}
|
| 658 |
|
| 659 |
-
.deal-item {{
|
|
|
|
| 660 |
.product-img {{ width: 52px; height: 52px; min-width: 52px; border-radius: 6px; object-fit: contain; aspect-ratio: 1 / 1; background: #0f111a; border: 1px solid var(--border-color); padding: 2px; }}
|
| 661 |
|
| 662 |
.deal-info {{ flex-grow: 1; min-width: 0; display: flex; flex-direction: column; gap: 4px; }}
|
|
@@ -676,19 +679,21 @@ def generate_ui(results_html="", error_msg=""):
|
|
| 676 |
.price-tag {{ background: var(--accent-green); color: white; padding: 8px 14px; border-radius: 8px; font-weight: 700; font-size: 16px; text-align: center; white-space: nowrap; min-width: 80px; box-shadow: 0 4px 10px rgba(16, 185, 129, 0.15); }}
|
| 677 |
.error {{ color: #ef4444; background: rgba(239, 68, 68, 0.08); padding: 14px; border-radius: 10px; margin-bottom: 20px; border: 1px solid rgba(239, 68, 68, 0.2); font-size: 14px; font-weight: 500; display: flex; align-items: center; gap: 8px; }}
|
| 678 |
|
|
|
|
|
|
|
| 679 |
.loader-box {{ display: none; margin-top: 20px; }}
|
| 680 |
.skeleton {{ background: linear-gradient(90deg, #1b1f32 25%, #252b47 50%, #1b1f32 75%); background-size: 200% 100%; animation: loading-shimmer 1.4s infinite linear; border-radius: 8px; }}
|
| 681 |
@keyframes loading-shimmer {{ 0% {{ background-position: 200% 0; }} 100% {{ background-position: -200% 0; }} }}
|
| 682 |
|
| 683 |
svg.icon {{ width: 16px; height: 16px; fill: currentColor; flex-shrink: 0; }}
|
| 684 |
|
| 685 |
-
@media (max-width:
|
| 686 |
body {{ padding: 20px 12px; }}
|
| 687 |
h2 {{ font-size: 22px; }}
|
| 688 |
.card {{ padding: 16px; border-radius: 12px; margin-bottom: 16px; }}
|
| 689 |
.input-flex {{ flex-direction: column; gap: 12px; margin-bottom: 16px; }}
|
| 690 |
-
.input-group.size-group {{ width: 100%; }}
|
| 691 |
-
|
| 692 |
.product-img {{ width: 48px; height: 48px; min-width: 48px; }}
|
| 693 |
.deal-info {{ width: 100%; }}
|
| 694 |
.item-title {{ white-space: normal; font-size: 14px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }}
|
|
@@ -729,7 +734,15 @@ def generate_ui(results_html="", error_msg=""):
|
|
| 729 |
</div>
|
| 730 |
<div class="input-group size-group">
|
| 731 |
<label>Size / Variant</label>
|
| 732 |
-
<input type="text" name="product_size" placeholder="e.g., 3.4 oz, XL
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 733 |
</div>
|
| 734 |
</div>
|
| 735 |
<button type="submit" id="submit-btn">
|
|
@@ -764,7 +777,7 @@ def dashboard():
|
|
| 764 |
return generate_ui()
|
| 765 |
|
| 766 |
@app.post("/search", response_class=HTMLResponse)
|
| 767 |
-
async def handle_search(product_name: str = Form(...), product_size: str = Form(None)):
|
| 768 |
if not HF_TOKEN:
|
| 769 |
return generate_ui(error_msg="Please add a valid HF_TOKEN into Space Secrets to activate the free AI models.")
|
| 770 |
|
|
@@ -841,21 +854,21 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
|
|
| 841 |
print(f"❌ [Link Analytics Error] Failure processing link data parsing: {e}")
|
| 842 |
return generate_ui(error_msg="Error decoding reference link metadata structure.")
|
| 843 |
|
| 844 |
-
cached_deals = None if force_refresh else get_cached_deals(target_item, requested_size)
|
| 845 |
cached_coupons = None if force_refresh else get_cached_coupons(target_item)
|
| 846 |
|
| 847 |
if cached_deals is not None:
|
| 848 |
-
print(f"⚡ [Cache Hit] Found unexpired retail pricing matrix for '{target_item}'. Skipping live queries.")
|
| 849 |
deals = cached_deals
|
| 850 |
coupons = cached_coupons or []
|
| 851 |
else:
|
| 852 |
print(f"❄️ [Cache Miss] Initiating parallel engine verification sequence for pricing & coupons...")
|
| 853 |
deals, coupons = await asyncio.gather(
|
| 854 |
-
scan_prices(target_item, requested_size),
|
| 855 |
fetch_coupons_standalone(target_item)
|
| 856 |
)
|
| 857 |
if deals:
|
| 858 |
-
set_cached_deals(target_item, requested_size, deals)
|
| 859 |
if coupons is not None:
|
| 860 |
set_cached_coupons(target_item, coupons)
|
| 861 |
|
|
@@ -876,9 +889,32 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
|
|
| 876 |
else:
|
| 877 |
print(f"🎉 [Finished Execution] Successfully built pricing matrix with {len(deals)} results.")
|
| 878 |
|
|
|
|
|
|
|
| 879 |
results_list = ""
|
|
|
|
| 880 |
for idx, deal in enumerate(deals):
|
| 881 |
img_src = deal['image'] if deal['image'] else fallback_img
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 882 |
|
| 883 |
best_value_badge = ""
|
| 884 |
if idx == 0:
|
|
@@ -899,49 +935,48 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
|
|
| 899 |
"""
|
| 900 |
|
| 901 |
is_ref = '<span class="size-badge" style="background:rgba(59,130,246,0.1); color:#60a5fa; border-color:rgba(59,130,246,0.2)">⭐ Ref Target</span>' if original_site_deal and deal['url'] == original_site_deal['url'] else ""
|
| 902 |
-
|
| 903 |
-
domain = deal.get('source') or "link"
|
| 904 |
-
if "google.com" not in deal['url']:
|
| 905 |
-
try: domain = urlparse(deal['url']).netloc.replace("www.", "")
|
| 906 |
-
except: pass
|
| 907 |
|
| 908 |
results_list += f"""
|
| 909 |
<li class="deal-item">
|
| 910 |
-
<
|
| 911 |
-
|
| 912 |
-
<
|
| 913 |
-
|
| 914 |
-
<
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
|
|
|
|
|
|
| 920 |
</div>
|
|
|
|
| 921 |
</div>
|
| 922 |
-
|
| 923 |
</li>
|
| 924 |
"""
|
| 925 |
|
| 926 |
-
# --- BUILD
|
|
|
|
| 927 |
coupon_html = ""
|
| 928 |
-
if
|
| 929 |
coupon_items = ""
|
| 930 |
-
for c in
|
| 931 |
coupon_items += f"""
|
| 932 |
<div style="background: rgba(245, 158, 11, 0.04); border: 1px dashed rgba(245, 158, 11, 0.25); padding: 12px 16px; border-radius: 10px; display: flex; justify-content: space-between; align-items: center; gap: 12px;">
|
| 933 |
<div style="min-width: 0;">
|
| 934 |
-
<span style="color: var(--accent-gold); font-weight: 700; font-family: monospace; font-size:
|
| 935 |
<p style="margin: 6px 0 0 0; color: #e5e7eb; font-size: 13px; line-height: 1.4;">{c['description']}</p>
|
| 936 |
</div>
|
| 937 |
-
<span class="domain-badge" style="background: rgba(245, 158, 11, 0.08); color: var(--accent-gold); border-color: rgba(245, 158, 11, 0.15);">{c.get('source', '
|
| 938 |
</div>
|
| 939 |
"""
|
| 940 |
coupon_html = f"""
|
| 941 |
<div style="margin-bottom: 24px; background: rgba(20, 15, 10, 0.3); border: 1px solid rgba(245, 158, 11, 0.15); padding: 20px; border-radius: 14px;">
|
| 942 |
<h4 style="margin: 0 0 16px 0; color: var(--accent-gold); font-size: 15px; display: flex; align-items: center; gap: 8px; font-weight: 600;">
|
| 943 |
<svg class="icon" style="color: var(--accent-gold); width: 18px; height: 18px;" viewBox="0 0 24 24"><path d="M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58.55 0 1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41 0-.55-.23-1.06-.59-1.42zM5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7z"/></svg>
|
| 944 |
-
|
| 945 |
</h4>
|
| 946 |
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 12px;">
|
| 947 |
{coupon_items}
|
|
|
|
| 24 |
app = FastAPI()
|
| 25 |
|
| 26 |
# --- RATE LIMIT PROTECTION CONTEXTS ---
|
|
|
|
| 27 |
DDG_SEMAPHORE = asyncio.Semaphore(2)
|
| 28 |
|
| 29 |
# --- GATHER AND VALIDATE SECRET KEYS FROM ENVIRONMENT ---
|
|
|
|
| 63 |
print(f"⚠️ [Cache Setup] Redis connection failed ({e}). Defaulting to internal memory arrays.")
|
| 64 |
redis_client = None
|
| 65 |
|
| 66 |
+
def get_cache_key(product_name: str, size: str = "", mode: str = "balanced") -> str:
|
| 67 |
+
"""Generates a unique deterministic cache key combining name, size, and search mode"""
|
| 68 |
clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip())
|
| 69 |
clean_size = re.sub(r'[^a-z0-9 ]', '', size.lower().strip()) if size else "nosize"
|
| 70 |
clean_name = clean_name.replace(" ", "_")
|
| 71 |
clean_size = clean_size.replace(" ", "_")
|
| 72 |
+
return f"tarz:cache:{clean_name}:{clean_size}:{mode}"
|
| 73 |
|
| 74 |
+
def get_cached_deals(product_name: str, size: str = "", mode: str = "balanced") -> list:
|
| 75 |
"""Retrieves cached pricing data array if available and unexpired"""
|
| 76 |
+
key = get_cache_key(product_name, size, mode)
|
| 77 |
if redis_client:
|
| 78 |
try:
|
| 79 |
data = redis_client.get(key)
|
|
|
|
| 90 |
del IN_MEMORY_EXPIRY[key]
|
| 91 |
return None
|
| 92 |
|
| 93 |
+
def set_cached_deals(product_name: str, size: str, mode: str, deals: list):
|
| 94 |
"""Caches product list matrix with strict 2-hour sliding validation lifetime"""
|
| 95 |
if not deals:
|
| 96 |
return
|
| 97 |
+
key = get_cache_key(product_name, size, mode)
|
| 98 |
if redis_client:
|
| 99 |
try:
|
| 100 |
redis_client.setex(key, 7200, json.dumps(deals))
|
|
|
|
| 123 |
"""Caches discovered active promo strings (saves empty results for 15 mins to prevent loop spam)"""
|
| 124 |
clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip()).replace(" ", "_")
|
| 125 |
key = f"tarz:coupons:{clean_name}"
|
|
|
|
|
|
|
| 126 |
duration = 7200 if coupons else 900
|
|
|
|
| 127 |
if redis_client:
|
| 128 |
try:
|
| 129 |
redis_client.setex(key, duration, json.dumps(coupons))
|
|
|
|
| 327 |
except: return None, None
|
| 328 |
|
| 329 |
# --- SERPAPI GOOGLE SHOPPING ENGINE ---
|
| 330 |
+
async def fetch_serpapi_shopping(product_name: str, desired_size: str, client: httpx.AsyncClient, mode: str = "balanced") -> list:
|
| 331 |
"""Queries SerpApi Google Shopping engine for pristine structured retail data"""
|
| 332 |
if not SERPAPI_KEY: return []
|
| 333 |
|
| 334 |
search_query = f"{product_name} {desired_size}".strip() if desired_size else product_name
|
| 335 |
+
print(f"🛍️ [SerpApi] Dispatching Shopping query vector: '{search_query}' (Strategy: {mode})")
|
| 336 |
|
| 337 |
params = {
|
| 338 |
"engine": "google_shopping",
|
|
|
|
| 351 |
title = item.get("title", "")
|
| 352 |
snippet = item.get("snippet", "")
|
| 353 |
|
| 354 |
+
# MODE STRATEGY BYPASS: If mode is broad, we skip strict mismatch eliminations
|
| 355 |
+
if mode != "broad" and clean_target_size and is_size_mismatched(desired_size, f"{title} {snippet}"):
|
| 356 |
continue
|
| 357 |
|
| 358 |
price_val = item.get("extracted_price")
|
|
|
|
| 373 |
return []
|
| 374 |
|
| 375 |
# --- TEXT PAYLOAD RETRIEVAL VIA TAVILY ---
|
| 376 |
+
async def get_tavily_payload(query: str, desired_size: str, client: httpx.AsyncClient, mode: str = "balanced") -> list:
|
| 377 |
"""Queries Tavily to assemble unstructured fallback content blocks with image assets unblocked"""
|
| 378 |
scraped_pages = []
|
| 379 |
if not TAVILY_API_KEY: return scraped_pages
|
|
|
|
| 395 |
url_str = item.get("url", "")
|
| 396 |
content_str = item.get("content", "")
|
| 397 |
|
| 398 |
+
if mode != "broad" and desired_size and is_size_mismatched(desired_size, f"{content_str}"):
|
| 399 |
continue
|
| 400 |
|
| 401 |
img_url = item.get("raw_data", {}).get("og:image") if isinstance(item.get("raw_data"), dict) else None
|
|
|
|
| 411 |
return scraped_pages
|
| 412 |
|
| 413 |
# --- 100% FREE ROUTER ROUTE: DUCKDUCKGO HTML KEYLESS FALLBACK ENGINE ---
|
| 414 |
+
async def fetch_ddg_backup_shopping(product_name: str, desired_size: str, client: httpx.AsyncClient, mode: str = "balanced") -> list:
|
| 415 |
"""Performs structured context harvesting via DuckDuckGo with instance traffic safety throttles applied"""
|
| 416 |
scraped_pages = []
|
| 417 |
search_q = f"buy {product_name} {desired_size} retail price".strip()
|
| 418 |
url = f"https://html.duckduckgo.com/html/?q={requests.utils.quote(search_q)}"
|
| 419 |
headers = {"User-Agent": random.choice(USER_AGENTS)}
|
| 420 |
|
|
|
|
| 421 |
async with DDG_SEMAPHORE:
|
| 422 |
try:
|
|
|
|
| 423 |
await asyncio.sleep(random.uniform(0.3, 0.7))
|
|
|
|
| 424 |
print(f"🦆 [DuckDuckGo Fallback] Routing zero-cost backup query pipeline for '{search_q}'")
|
| 425 |
res = await client.get(url, headers=headers, timeout=8.0)
|
| 426 |
if res.status_code == 200:
|
|
|
|
| 432 |
if a_tag and snippet_tag:
|
| 433 |
snippet_text = snippet_tag.get_text()
|
| 434 |
|
| 435 |
+
if mode != "broad" and desired_size and is_size_mismatched(desired_size, snippet_text):
|
| 436 |
continue
|
| 437 |
|
| 438 |
raw_href = a_tag.get('href', '')
|
|
|
|
| 462 |
headers = {"User-Agent": random.choice(USER_AGENTS)}
|
| 463 |
snippets = []
|
| 464 |
|
|
|
|
| 465 |
async with DDG_SEMAPHORE:
|
| 466 |
try:
|
|
|
|
| 467 |
await asyncio.sleep(random.uniform(0.4, 0.8))
|
|
|
|
| 468 |
print(f"🎟️ [Coupon Engine] Hunting active promotional tags for '{product_name}'...")
|
| 469 |
res = await client.get(url, headers=headers, timeout=6.0)
|
| 470 |
if res.status_code == 200:
|
|
|
|
| 488 |
prompt = f"""
|
| 489 |
Analyze the following search snippets containing discount indicators for '{product_name}'.
|
| 490 |
Identify and isolate any specific, functioning alphanumeric promo codes, coupon tokens, or active structural store discount descriptions.
|
| 491 |
+
Ensure you capture the identity of the specific store/retailer name or website it belongs to in the "source" field.
|
| 492 |
|
| 493 |
Return ONLY a raw JSON array string matching the explicit syntax structure below. No explanation, no markdown text wrappers.
|
| 494 |
[
|
| 495 |
+
{{"code": "SUMMER20", "description": "20% off all items storewide", "source": "Target"}},
|
| 496 |
+
{{"code": "GPC30", "description": "$30 off custom prebuilts", "source": "Best Buy"}}
|
| 497 |
]
|
| 498 |
|
| 499 |
Snippets Pool:
|
|
|
|
| 509 |
return []
|
| 510 |
|
| 511 |
# --- MASTER PRICE SWEEPER SEQUENCE (CASCADING MULTI-ENGINE ROUTER) ---
|
| 512 |
+
async def scan_prices(product_name, desired_size="", mode: str = "balanced"):
|
| 513 |
"""Orchestrates structured arrays across all endpoints concurrently while bypassing broken environment proxies"""
|
| 514 |
limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)
|
| 515 |
|
| 516 |
async with httpx.AsyncClient(limits=limits, http2=True, trust_env=False) as client:
|
| 517 |
+
deals = await fetch_serpapi_shopping(product_name, desired_size, client, mode=mode)
|
| 518 |
|
| 519 |
scraped_pages = []
|
| 520 |
if not deals:
|
| 521 |
print("🔄 [Engine Cascader] Primary structured inventory returned empty. Initiating Tavily content harvesting channels...")
|
| 522 |
+
scraped_pages = await get_tavily_payload(product_name, desired_size, client, mode=mode)
|
| 523 |
|
| 524 |
if not scraped_pages:
|
| 525 |
print("🦆 [Engine Cascader] Secondary API pools empty. Initiating 100% free open DuckDuckGo scrape clusters...")
|
| 526 |
+
scraped_pages = await fetch_ddg_backup_shopping(product_name, desired_size, client, mode=mode)
|
| 527 |
|
| 528 |
results = []
|
| 529 |
if scraped_pages and not deals:
|
| 530 |
+
# MODE STRATEGY IMPLEMENTATION IN LLM INSTRUCTIONS
|
| 531 |
+
mode_constraint = ""
|
| 532 |
+
if mode == "exact":
|
| 533 |
+
mode_constraint = f"STRICT CONSTRAINT: The extracted product name MUST be a direct contextual equivalent or contain core nouns of '{product_name}'. Drop loose accessories."
|
| 534 |
+
elif mode == "broad":
|
| 535 |
+
mode_constraint = "FLEXIBLE CONSTRAINT: Allow alternative variations, complete setups, categories, or similar brand designs."
|
| 536 |
+
|
| 537 |
batch_instructions = f"""
|
| 538 |
Analyze the text blocks extracted from up to 5 separate websites.
|
| 539 |
Find if the product '{product_name}' is explicitly sold on each site and extract its current numerical retail price.
|
| 540 |
Also check if a specific sizing variant is being sold on the page.
|
| 541 |
+
{mode_constraint}
|
| 542 |
|
| 543 |
Return ONLY a raw JSON array matching the structure below. Do not include markdown blocks or text wrappers.
|
| 544 |
Format example string to output:
|
|
|
|
| 643 |
|
| 644 |
.input-flex {{ display: flex; gap: 16px; margin-bottom: 20px; }}
|
| 645 |
.input-group {{ display: flex; flex-direction: column; flex-grow: 1; min-width: 0; }}
|
| 646 |
+
.input-group.size-group {{ flex-grow: 0; width: 140px; }}
|
| 647 |
+
.input-group.mode-group {{ flex-grow: 0; width: 180px; }}
|
| 648 |
|
| 649 |
label {{ margin-bottom: 8px; font-weight: 500; color: var(--text-muted); font-size: 13px; }}
|
| 650 |
+
input[type="text"], select {{ background: var(--input-bg); border: 1px solid var(--border-color); color: white; padding: 14px 16px; border-radius: 10px; font-size: 15px; transition: all 0.3s ease; font-family: inherit; width: 100%; }}
|
| 651 |
+
select {{ cursor: pointer; -webkit-appearance: none; appearance: none; background-image: url('data:image/svg+xml;utf8,<svg fill="white" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/></svg>'); background-repeat: no-repeat; background-position: right 12px center; padding-right: 32px; }}
|
| 652 |
+
input[type="text"]:focus, select:focus {{ border-color: var(--accent-blue); outline: none; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15); }}
|
| 653 |
|
| 654 |
button {{ background: var(--accent-gradient); color: white; border: none; padding: 14px 24px; border-radius: 10px; cursor: pointer; font-weight: 600; font-size: 15px; transition: all 0.2s ease; display: inline-flex; align-items: center; justify-content: center; gap: 8px; width: 100%; box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2); font-family: inherit; }}
|
| 655 |
button:hover {{ transform: translateY(-1px); box-shadow: 0 6px 16px rgba(59, 130, 246, 0.3); }}
|
| 656 |
|
| 657 |
ul {{ list-style-type: none; padding: 0; margin: 0; }}
|
| 658 |
+
li {{ background: rgba(255, 255, 255, 0.02); padding: 14px 18px; border-radius: 12px; margin-bottom: 12px; border: 1px solid var(--border-color); display: flex; flex-direction: column; gap: 12px; transition: all 0.2s ease; }}
|
| 659 |
li:hover {{ border-color: rgba(255, 255, 255, 0.15); background: rgba(255, 255, 255, 0.04); }}
|
| 660 |
|
| 661 |
+
.deal-item-header {{ display: flex; align-items: center; justify-content: space-between; width: 100%; gap: 16px; }}
|
| 662 |
+
.deal-item {{ border-left: 4px solid var(--accent-green); background: #161c2a; overflow: hidden; }}
|
| 663 |
.product-img {{ width: 52px; height: 52px; min-width: 52px; border-radius: 6px; object-fit: contain; aspect-ratio: 1 / 1; background: #0f111a; border: 1px solid var(--border-color); padding: 2px; }}
|
| 664 |
|
| 665 |
.deal-info {{ flex-grow: 1; min-width: 0; display: flex; flex-direction: column; gap: 4px; }}
|
|
|
|
| 679 |
.price-tag {{ background: var(--accent-green); color: white; padding: 8px 14px; border-radius: 8px; font-weight: 700; font-size: 16px; text-align: center; white-space: nowrap; min-width: 80px; box-shadow: 0 4px 10px rgba(16, 185, 129, 0.15); }}
|
| 680 |
.error {{ color: #ef4444; background: rgba(239, 68, 68, 0.08); padding: 14px; border-radius: 10px; margin-bottom: 20px; border: 1px solid rgba(239, 68, 68, 0.2); font-size: 14px; font-weight: 500; display: flex; align-items: center; gap: 8px; }}
|
| 681 |
|
| 682 |
+
.inline-coupon {{ background: rgba(245, 158, 11, 0.05); border: 1px dashed rgba(245, 158, 11, 0.3); padding: 8px 12px; border-radius: 8px; display: flex; align-items: center; justify-content: space-between; font-size: 12px; width: 100%; margin-top: 4px; }}
|
| 683 |
+
|
| 684 |
.loader-box {{ display: none; margin-top: 20px; }}
|
| 685 |
.skeleton {{ background: linear-gradient(90deg, #1b1f32 25%, #252b47 50%, #1b1f32 75%); background-size: 200% 100%; animation: loading-shimmer 1.4s infinite linear; border-radius: 8px; }}
|
| 686 |
@keyframes loading-shimmer {{ 0% {{ background-position: 200% 0; }} 100% {{ background-position: -200% 0; }} }}
|
| 687 |
|
| 688 |
svg.icon {{ width: 16px; height: 16px; fill: currentColor; flex-shrink: 0; }}
|
| 689 |
|
| 690 |
+
@media (max-width: 700px) {{
|
| 691 |
body {{ padding: 20px 12px; }}
|
| 692 |
h2 {{ font-size: 22px; }}
|
| 693 |
.card {{ padding: 16px; border-radius: 12px; margin-bottom: 16px; }}
|
| 694 |
.input-flex {{ flex-direction: column; gap: 12px; margin-bottom: 16px; }}
|
| 695 |
+
.input-group.size-group, .input-group.mode-group {{ width: 100%; }}
|
| 696 |
+
.deal-item-header {{ flex-direction: column; align-items: flex-start; gap: 12px; }}
|
| 697 |
.product-img {{ width: 48px; height: 48px; min-width: 48px; }}
|
| 698 |
.deal-info {{ width: 100%; }}
|
| 699 |
.item-title {{ white-space: normal; font-size: 14px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }}
|
|
|
|
| 734 |
</div>
|
| 735 |
<div class="input-group size-group">
|
| 736 |
<label>Size / Variant</label>
|
| 737 |
+
<input type="text" name="product_size" placeholder="e.g., 3.4 oz, XL" autocomplete="off">
|
| 738 |
+
</div>
|
| 739 |
+
<div class="input-group mode-group">
|
| 740 |
+
<label>Search Strategy</label>
|
| 741 |
+
<select name="search_mode">
|
| 742 |
+
<option value="broad">Broad Exploration</option>
|
| 743 |
+
<option value="balanced" selected>Standard Balanced</option>
|
| 744 |
+
<option value="exact">Precision Match</option>
|
| 745 |
+
</select>
|
| 746 |
</div>
|
| 747 |
</div>
|
| 748 |
<button type="submit" id="submit-btn">
|
|
|
|
| 777 |
return generate_ui()
|
| 778 |
|
| 779 |
@app.post("/search", response_class=HTMLResponse)
|
| 780 |
+
async def handle_search(product_name: str = Form(...), product_size: str = Form(None), search_mode: str = Form("balanced")):
|
| 781 |
if not HF_TOKEN:
|
| 782 |
return generate_ui(error_msg="Please add a valid HF_TOKEN into Space Secrets to activate the free AI models.")
|
| 783 |
|
|
|
|
| 854 |
print(f"❌ [Link Analytics Error] Failure processing link data parsing: {e}")
|
| 855 |
return generate_ui(error_msg="Error decoding reference link metadata structure.")
|
| 856 |
|
| 857 |
+
cached_deals = None if force_refresh else get_cached_deals(target_item, requested_size, search_mode)
|
| 858 |
cached_coupons = None if force_refresh else get_cached_coupons(target_item)
|
| 859 |
|
| 860 |
if cached_deals is not None:
|
| 861 |
+
print(f"⚡ [Cache Hit] Found unexpired retail pricing matrix for '{target_item}' | Mode: '{search_mode}'. Skipping live queries.")
|
| 862 |
deals = cached_deals
|
| 863 |
coupons = cached_coupons or []
|
| 864 |
else:
|
| 865 |
print(f"❄️ [Cache Miss] Initiating parallel engine verification sequence for pricing & coupons...")
|
| 866 |
deals, coupons = await asyncio.gather(
|
| 867 |
+
scan_prices(target_item, requested_size, search_mode),
|
| 868 |
fetch_coupons_standalone(target_item)
|
| 869 |
)
|
| 870 |
if deals:
|
| 871 |
+
set_cached_deals(target_item, requested_size, search_mode, deals)
|
| 872 |
if coupons is not None:
|
| 873 |
set_cached_coupons(target_item, coupons)
|
| 874 |
|
|
|
|
| 889 |
else:
|
| 890 |
print(f"🎉 [Finished Execution] Successfully built pricing matrix with {len(deals)} results.")
|
| 891 |
|
| 892 |
+
# TRACK UNUSED COUPONS TO RENDER GLOBAL SECTION ONLY IF NECESSARY
|
| 893 |
+
used_coupons_indices = set()
|
| 894 |
results_list = ""
|
| 895 |
+
|
| 896 |
for idx, deal in enumerate(deals):
|
| 897 |
img_src = deal['image'] if deal['image'] else fallback_img
|
| 898 |
+
domain = deal.get('source') or "link"
|
| 899 |
+
if "google.com" not in deal['url']:
|
| 900 |
+
try: domain = urlparse(deal['url']).netloc.replace("www.", "")
|
| 901 |
+
except: pass
|
| 902 |
+
|
| 903 |
+
# --- DETECT RELEVANT COUPONS BELONGING TO THIS SPECIFIC SEARCH OPTION ---
|
| 904 |
+
matched_coupon_html = ""
|
| 905 |
+
for c_idx, coupon in enumerate(coupons):
|
| 906 |
+
coupon_source = coupon.get('source', '').lower()
|
| 907 |
+
# Cross-reference source strings cleanly against item data fields
|
| 908 |
+
if coupon_source and (coupon_source in domain.lower() or coupon_source in (deal.get('source') or "").lower()):
|
| 909 |
+
used_coupons_indices.add(c_idx)
|
| 910 |
+
matched_coupon_html += f"""
|
| 911 |
+
<div class="inline-coupon">
|
| 912 |
+
<div style="min-width: 0;">
|
| 913 |
+
<span style="color: var(--accent-gold); font-weight: 700; font-family: monospace; font-size: 11px; background: rgba(245, 158, 11, 0.1); padding: 2px 6px; border-radius: 4px; border: 1px dashed rgba(245, 158, 11, 0.3); text-transform: uppercase;">{coupon['code']}</span>
|
| 914 |
+
<span style="color: #e5e7eb; margin-left: 6px; font-size: 12px;">{coupon['description']}</span>
|
| 915 |
+
</div>
|
| 916 |
+
</div>
|
| 917 |
+
"""
|
| 918 |
|
| 919 |
best_value_badge = ""
|
| 920 |
if idx == 0:
|
|
|
|
| 935 |
"""
|
| 936 |
|
| 937 |
is_ref = '<span class="size-badge" style="background:rgba(59,130,246,0.1); color:#60a5fa; border-color:rgba(59,130,246,0.2)">⭐ Ref Target</span>' if original_site_deal and deal['url'] == original_site_deal['url'] else ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 938 |
|
| 939 |
results_list += f"""
|
| 940 |
<li class="deal-item">
|
| 941 |
+
<div class="deal-item-header">
|
| 942 |
+
<img src="{img_src}" class="product-img" onerror="this.src='{fallback_img}'" />
|
| 943 |
+
<div class="deal-info">
|
| 944 |
+
<span class="item-title">{target_item}</span>
|
| 945 |
+
<div class="meta-container">
|
| 946 |
+
<span class="domain-badge">{domain}</span>
|
| 947 |
+
<span class="size-badge">{deal.get('size', 'Standard')}</span>
|
| 948 |
+
{best_value_badge}
|
| 949 |
+
{verified_badge}
|
| 950 |
+
<a href="{deal['url']}" target="_blank" class="small-link">{deal['url']}</a>
|
| 951 |
+
{is_ref}
|
| 952 |
+
</div>
|
| 953 |
</div>
|
| 954 |
+
<span class="price-tag">${deal['price']:.2f}</span>
|
| 955 |
</div>
|
| 956 |
+
{matched_coupon_html}
|
| 957 |
</li>
|
| 958 |
"""
|
| 959 |
|
| 960 |
+
# --- BUILD GLOBAL MATRIX COMPONENT WRAPPERS FOR UNMATCHED OFFERS ---
|
| 961 |
+
unmatched_coupons = [c for c_i, c in enumerate(coupons) if c_i not in used_coupons_indices]
|
| 962 |
coupon_html = ""
|
| 963 |
+
if unmatched_coupons:
|
| 964 |
coupon_items = ""
|
| 965 |
+
for c in unmatched_coupons:
|
| 966 |
coupon_items += f"""
|
| 967 |
<div style="background: rgba(245, 158, 11, 0.04); border: 1px dashed rgba(245, 158, 11, 0.25); padding: 12px 16px; border-radius: 10px; display: flex; justify-content: space-between; align-items: center; gap: 12px;">
|
| 968 |
<div style="min-width: 0;">
|
| 969 |
+
<span style="color: var(--accent-gold); font-weight: 700; font-family: monospace; font-size: 13px; background: rgba(245, 158, 11, 0.12); padding: 3px 8px; border-radius: 5px; border: 1px dashed rgba(245, 158, 11, 0.4); text-transform: uppercase; letter-spacing: 0.05em; display: inline-block;">{c['code']}</span>
|
| 970 |
<p style="margin: 6px 0 0 0; color: #e5e7eb; font-size: 13px; line-height: 1.4;">{c['description']}</p>
|
| 971 |
</div>
|
| 972 |
+
<span class="domain-badge" style="background: rgba(245, 158, 11, 0.08); color: var(--accent-gold); border-color: rgba(245, 158, 11, 0.15);">{c.get('source', 'General')}</span>
|
| 973 |
</div>
|
| 974 |
"""
|
| 975 |
coupon_html = f"""
|
| 976 |
<div style="margin-bottom: 24px; background: rgba(20, 15, 10, 0.3); border: 1px solid rgba(245, 158, 11, 0.15); padding: 20px; border-radius: 14px;">
|
| 977 |
<h4 style="margin: 0 0 16px 0; color: var(--accent-gold); font-size: 15px; display: flex; align-items: center; gap: 8px; font-weight: 600;">
|
| 978 |
<svg class="icon" style="color: var(--accent-gold); width: 18px; height: 18px;" viewBox="0 0 24 24"><path d="M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58.55 0 1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41 0-.55-.23-1.06-.59-1.42zM5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7z"/></svg>
|
| 979 |
+
Additional General Promo Offers Found
|
| 980 |
</h4>
|
| 981 |
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 12px;">
|
| 982 |
{coupon_items}
|