import json import re import httpx import uvicorn import asyncio from urllib.parse import urlparse from fastapi import FastAPI, Request, Form from fastapi.responses import HTMLResponse from config import HF_TOKEN from security import scrub_conversational_bloat, check_url_safe from database import ( get_cached_deals, set_cached_deals, get_cached_coupons, set_cached_coupons, get_base_price, set_base_price ) from schema import extract_universal_sizing, is_size_mismatched, parse_price_locally from network import extract_page_data from coupons import call_free_llm, fetch_coupons_standalone from shopping import scan_prices from ui import generate_ui app = FastAPI() @app.get("/", response_class=HTMLResponse) def dashboard(): return generate_ui() @app.post("/search", response_class=HTMLResponse) async def handle_search( product_name: str = Form(...), product_size: str = Form(None), search_mode: str = Form("balanced"), product_gender: str = Form("unisex") ): if not HF_TOKEN: return generate_ui(error_msg="Please add a valid HF_TOKEN into Space Secrets to activate the free AI models.") original_name_input = product_name original_size_input = product_size or "" raw_input = product_name.strip() force_refresh = raw_input.endswith("*") if force_refresh: raw_input = raw_input.rstrip("*").strip() print(f"⚡ [Force Refresh] Evicting active cache entries for query mapping context: '{raw_input}'") extracted_size_from_name = extract_universal_sizing(raw_input) if original_size_input: requested_size = extract_universal_sizing(original_size_input) or original_size_input.strip() else: requested_size = extracted_size_from_name if not original_size_input and extracted_size_from_name: patterns_to_strip = [ r'(\d+(?:\.\d+)?)\s*(?:FL\.?\s*)?(OZ|ML|GB|TB)\b', r'\b(EXTRA\s*LARGE|X-LARGE|LARGE|MEDIUM|SMALL)\b', r'\b(XS|S|M|L|XL|2XL|XXL|3XL|4XL)\b', r'\b(?:SIZE|SZ|US|UK|EU)?\s*(\d+(?:\.5)?)\b' ] target_item = raw_input for pattern in patterns_to_strip: target_item = re.sub(pattern, "", target_item, flags=re.IGNORECASE).strip() target_item = " ".join(target_item.split()) else: target_item = raw_input target_item = scrub_conversational_bloat(target_item) if not target_item.startswith(("http", "https")) else target_item gender_prefix = "" if product_gender == "mens": gender_prefix = "men's " elif product_gender == "womens": gender_prefix = "women's " elif product_gender == "kids": gender_prefix = "kids' " if gender_prefix and not target_item.startswith(("http://", "https://")): if gender_prefix.strip().lower() not in target_item.lower(): target_item = f"{gender_prefix}{target_item}" deals = [] coupons = [] original_site_deal = None fallback_img = "https://placehold.co/100x100/1a1c28/9fa4b4?text=IMG" if target_item.startswith(("http://", "https://")): input_url = target_item print(f"🔗 [Input URL] Pasted hyperlink reference intercepted: {input_url}") async with httpx.AsyncClient(trust_env=False) as safety_client: if not await check_url_safe(input_url, safety_client): return generate_ui(error_msg="The provided link target matches active security alert threat signatures and was isolated.", prev_name=original_name_input, prev_size=original_size_input, prev_mode=search_mode, prev_gender=product_gender) raw_text, img_url = await extract_page_data(input_url, "product") if not raw_text: return generate_ui(error_msg="Tarz could not parse or connect to the provided URL.", prev_name=original_name_input, prev_size=original_size_input, prev_mode=search_mode, prev_gender=product_gender) try: url_prompt = f""" Identify the exact product name, find its listed retail numerical price, and sizing text from the block: {raw_text} Return ONLY raw JSON. No text wraps or explanations. Format structure: {{"product_name": "exact brand name", "price": 49.99, "size": "3.4 oz", "found": true}} """ try: ai_res = call_free_llm(url_prompt, max_tokens=150) url_data = json.loads(ai_res) if url_data.get('found') and url_data.get('price') is not None: target_item = url_data['product_name'] if not requested_size: requested_size = extract_universal_sizing(url_data.get('size')) original_site_deal = { "title": target_item, "url": input_url, "price": round(float(url_data['price']), 2), "image": img_url, "source": urlparse(input_url).netloc.replace("www.", ""), "size": requested_size or "Standard" } except Exception as api_err: print(f"⚠️ [Link Solver Fallback] API unavailable. Parsing pasted link via heuristics...") local_report = parse_price_locally(raw_text, "product") if local_report["found"]: target_item = "Extracted Product Deal" original_site_deal = { "title": "Extracted Product Deal", "url": input_url, "price": local_report["price"], "image": img_url, "source": urlparse(input_url).netloc.replace("www.", ""), "size": requested_size or "Standard" } else: return generate_ui(error_msg="Programmatic local parser could not identify currency text variables.", prev_name=original_name_input, prev_size=original_size_input, prev_mode=search_mode, prev_gender=product_gender) if not original_site_deal: return generate_ui(error_msg="Pasted link parsed, but price extraction could not resolve valid currency markers.", prev_name=original_name_input, prev_size=original_size_input, prev_mode=search_mode, prev_gender=product_gender) except Exception as e: print(f"❌ [Link Analytics Error] Failure processing link data parsing: {e}") return generate_ui(error_msg="Error decoding reference link metadata structure.", prev_name=original_name_input, prev_size=original_size_input, prev_mode=search_mode, prev_gender=product_gender) cached_deals = None if force_refresh else get_cached_deals(target_item, requested_size, search_mode) cached_coupons = None if force_refresh else get_cached_coupons(target_item) if cached_deals is not None: print(f"⚡ [Cache Hit] Found unexpired retail pricing matrix for '{target_item}' | Mode: '{search_mode}'. Skipping live queries.") deals = cached_deals coupons = cached_coupons or [] else: print(f"❄️ [Cache Miss] Initiating parallel engine verification sequence for pricing & coupons...") deals, coupons = await asyncio.gather( scan_prices(target_item, requested_size, search_mode), fetch_coupons_standalone(target_item) ) if original_site_deal: if not any(d['url'] == original_site_deal['url'] for d in deals): deals.append(original_site_deal) if deals: deals.sort(key=lambda x: x['price']) current_lowest = deals[0]['price'] base_price = get_base_price(target_item, requested_size, search_mode) if base_price is not None and base_price != current_lowest: delta = current_lowest - base_price deals[0]['price_delta'] = round(delta, 2) set_base_price(target_item, requested_size, search_mode, current_lowest) elif base_price == current_lowest: deals[0]['price_delta'] = 0.0 else: set_base_price(target_item, requested_size, search_mode, current_lowest) deals[0]['price_delta'] = 0.0 set_cached_deals(target_item, requested_size, search_mode, deals) if coupons is not None: set_cached_coupons(target_item, coupons) size_header = f" ({requested_size})" if requested_size else "" if not deals: print("⚠️ [Finished Execution] Matrix build completed with 0 valid results.") results_html = f"""

Query: {target_item}{size_header}

⚠️ No verifiable pricing matrices were found matching this selection criteria.

""" else: print(f"🎉 [Finished Execution] Successfully built pricing matrix with {len(deals)} results.") def render_deal_row(idx, deal): img_src = deal['image'] if deal['image'] else fallback_img domain = deal.get('source') or "link" if "google.com" not in deal['url']: try: domain = urlparse(deal['url']).netloc.replace("www.", "") except: pass matched_coupon_html = "" for coupon in coupons: coupon_source = coupon.get('source', '').lower() if coupon_source and (coupon_source in domain.lower() or coupon_source in (deal.get('source') or "").lower()): matched_coupon_html += f"""
{coupon['code']} {coupon['description']}
""" best_value_badge = "" if idx == 0: best_value_badge = """ Best Value """ verified_badge = "" if deal.get('source'): verified_badge = """ Verified """ rating_html = "" if deal.get('rating'): rating_val = deal['rating'] reviews_count = deal.get('reviews') or 0 reviews_text = f" ({int(reviews_count)})" if reviews_count else "" rating_html = f""" {rating_val}{reviews_text} """ is_ref = '⭐ Ref Target' if original_site_deal and deal['url'] == original_site_deal['url'] else "" display_title = deal.get('title') or target_item trend_html = "" if idx == 0 and deal.get('price_delta') is not None and deal['price_delta'] != 0.0: delta_val = deal['price_delta'] if delta_val < 0: trend_html = f'- $ {abs(delta_val):.2f}' else: trend_html = f'+ $ {delta_val:.2f}' return f"""
  • {display_title}
    {domain} {deal.get('size', 'Standard')} {rating_html} {best_value_badge} {verified_badge} {deal['url']} {is_ref}
    ${deal['price']:.2f} {trend_html}
    {matched_coupon_html}
  • """ top_results_list = "" for i, d in enumerate(deals[:10]): top_results_list += render_deal_row(i, d) additional_dropdown_html = "" if len(deals) > 10: extra_rows = "" for i, d in enumerate(deals[10:20], start=10): extra_rows += render_deal_row(i, d) additional_dropdown_html = f"""
    View Additional Pricing Options (+{len(deals) - 10} more variants found)
    """ results_html = f"""

    Results Matrix for: {target_item}{size_header}

    🏆 Lowest verified online price: ${deals[0]['price']:.2f}

    {additional_dropdown_html}
    """ return generate_ui(results_html=results_html, prev_name=original_name_input, prev_size=original_size_input, prev_mode=search_mode, prev_gender=product_gender) if __name__ == "__main__": uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)