import json import re import httpx import uvicorn import asyncio import os import urllib.parse from urllib.parse import urlparse, parse_qs, quote_plus from fastapi import FastAPI, Request, Form from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates 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, redis_client ) 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_deals_standalone from shopping import scan_prices # Clean import from your data separation module file from popular import get_trending_deals app = FastAPI() BASE_DIR = os.path.dirname(os.path.abspath(__file__)) templates = Jinja2Templates(directory=BASE_DIR) def unwrap_direct_product_url(url_str: str) -> str: """Recursively peels back tracking redirect strings to isolate raw retailer tokens""" if not url_str or not isinstance(url_str, str): return "" current_url = url_str.strip() for _ in range(5): if "google.com" not in current_url and "googleadservices.com" not in current_url: break parsed = urlparse(current_url) queries = parse_qs(parsed.query) found = False for key in ["adurl", "url", "q", "u", "link", "destination", "ad_url", "gclid"]: if queries.get(key): candidate = queries[key][0].strip() if "http" in candidate: if not candidate.startswith("http"): candidate = candidate[candidate.find("http"):] current_url = urllib.parse.unquote(candidate) found = True break if not found: match = re.search(r'(?:adurl|url|q|link)=(https?%3A%2F%2F[^&]+|https?://[^&]+)', current_url, re.IGNORECASE) if match: current_url = urllib.parse.unquote(match.group(1)) found = True else: break return "" if "google.com" in current_url or "googleadservices.com" in current_url else current_url def clean_retailer_url(url_str: str) -> str: """Strips click-tracking bloat parameters to present short paths safe from ad blockers""" if not url_str: return "" try: parsed = urlparse(url_str) queries = parse_qs(parsed.query) clean_queries = {} drop_params = { 'gclid', 'gclsrc', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'fbclid', '_ga', '_gl', 'srsltid' } for k, v in queries.items(): if k.lower() not in drop_params: clean_queries[k] = v new_query = urllib.parse.urlencode(clean_queries, doseq=True) return urllib.parse.urlunparse(( parsed.scheme, parsed.netloc, parsed.path, parsed.params, new_query, parsed.fragment )) except: return url_str def get_status_context(): """Generates reactive state tags for UI elements mapping cache statuses""" status_text = "Google Pricing Intelligence & Historical Tracking Active" if redis_client else "Security Protection Active | Core Memory Tracking" status_color = "var(--accent-green)" if redis_client else "#f59e0b" return status_text, status_color @app.get("/", response_class=HTMLResponse) def dashboard(request: Request): status_text, status_color = get_status_context() return templates.TemplateResponse( request=request, name="dashboard.html", context={ "status_text": status_text, "status_color": status_color, "prev_name": "", "prev_size": "", "prev_mode": "balanced", "prev_gender": "unisex", "show_results": False, "error_msg": None, "popular_deals": get_trending_deals(), "active_tab": "scan" } ) @app.post("/search", response_class=HTMLResponse) async def handle_search( request: Request, product_name: str = Form(...), product_size: str = Form(None), search_mode: str = Form("balanced"), product_gender: str = Form("unisex") ): status_text, status_color = get_status_context() base_ui_context = { "status_text": status_text, "status_color": status_color, "prev_name": product_name, "prev_size": product_size or "", "prev_mode": search_mode, "prev_gender": product_gender, "show_results": False, "error_msg": None, "popular_deals": get_trending_deals(), "active_tab": "scan" } if not HF_TOKEN: base_ui_context["error_msg"] = "Please add a valid HF_TOKEN into Space Secrets to activate the free AI models." return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context) 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 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): base_ui_context["error_msg"] = "The provided link target matches active security alert threat signatures and was isolated." return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context) raw_text, img_url = await extract_page_data(input_url, "product") if not raw_text: base_ui_context["error_msg"] = "Tarz could not parse or connect to the provided URL." return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context) 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": clean_retailer_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": clean_retailer_url(input_url), "price": local_report["price"], "image": img_url, "source": urlparse(input_url).netloc.replace("www.", ""), "size": requested_size or "Standard" } else: base_ui_context["error_msg"] = "Programmatic local parser could not identify currency text variables." return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context) if not original_site_deal: base_ui_context["error_msg"] = "Pasted link parsed, but price extraction could not resolve valid currency markers." return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context) except Exception as e: print(f"❌ [Link Analytics Error] Failure processing link data parsing: {e}") base_ui_context["error_msg"] = "Error decoding reference link metadata structure." return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context) 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 & deals...") markdown_deals, product_offers = await asyncio.gather( fetch_deals_standalone(target_item), scan_prices(target_item, requested_size, search_mode) ) if original_site_deal: if not any(d['url'] == original_site_deal['url'] for d in product_offers): product_offers.append(original_site_deal) if product_offers: product_offers.sort(key=lambda x: x.get('price', float('inf'))) market_max_price = max([x.get('price', 0) for x in product_offers if x.get('price', 0) > 0]) or 1.0 processed_percentage_badges = [] for item in product_offers: cur_p = item.get('price', 0) if not cur_p: continue item_source = item.get('source', 'Retailer').strip() item_title = item.get('title', 'Product Listing') old_p = item.get('original_price') or item.get('old_price') or item.get('regular_price') market_pct = int(round((1 - cur_p / market_max_price) * 100)) if old_p and float(old_p) > float(cur_p) and float(old_p) > 0: calculated_pct = int(round((1 - float(cur_p) / float(old_p)) * 100)) badge_string = f"{calculated_pct}% OFF" elif market_pct > 10: badge_string = f"{market_pct}% OFF" item['original_price'] = round(market_max_price, 2) else: badge_string = "BEST PRICE" item['original_price'] = round(cur_p, 2) sanitized_title = re.sub(r'[^a-zA-Z0-9]', '_', item_title).lower()[:50] redis_history_key = f"hist_low:prod:{sanitized_title}" historical_low = None if redis_client: try: cached_low = redis_client.get(redis_history_key) if cached_low: historical_low = float(cached_low) except Exception as redis_err: print(f"⚠️ [Redis Error] Failed reading baseline matrix: {redis_err}") if historical_low is not None: if cur_p < historical_low and redis_client: try: redis_client.set(redis_history_key, str(cur_p)) except: pass else: if redis_client: try: redis_client.set(redis_history_key, str(cur_p)) except: pass item['historical_low_event'] = False if historical_low: item['all_time_low_price'] = historical_low item['discount_percent'] = badge_string item['discount'] = badge_string item['percentage'] = badge_string item['badge'] = badge_string if not any(c['description'] == badge_string and c['source'].lower() == item_source.lower() for c in processed_percentage_badges): processed_percentage_badges.append({ "description": badge_string, "source": item_source }) current_lowest = product_offers[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 product_offers[0]['price_delta'] = round(delta, 2) set_base_price(target_item, requested_size, search_mode, current_lowest) elif base_price == current_lowest: product_offers[0]['price_delta'] = 0.0 else: set_base_price(target_item, requested_size, search_mode, current_lowest) product_offers[0]['price_delta'] = 0.0 deals = product_offers set_cached_deals(target_item, requested_size, search_mode, deals) else: deals = [] set_cached_deals(target_item, requested_size, search_mode, deals) coupons = [] set_cached_coupons(target_item, coupons) size_header = f" ({requested_size})" if requested_size else "" validated_deals = [] for d in deals: if "url" not in d and "link" in d: d["url"] = d["link"] elif "link" not in d and "url" in d: d["link"] = d["url"] unwrapped = unwrap_direct_product_url(d.get("url", "")) if unwrapped: cleaned_url = clean_retailer_url(unwrapped) d["url"] = cleaned_url d["link"] = cleaned_url try: d["source_domain"] = d.get("source") or urlparse(cleaned_url).netloc.replace("www.", "") except: d["source_domain"] = "retailer.link" validated_deals.append(d) base_ui_context.update({ "show_results": True, "target_item": target_item, "size_header": size_header, "deals": validated_deals, "coupons": coupons, "is_ref_url": original_site_deal["url"] if original_site_deal else None }) return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context) if __name__ == "__main__": uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)