ghstedpixel commited on
Commit
8a11fa0
Β·
verified Β·
1 Parent(s): 1b282d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -52
app.py CHANGED
@@ -7,12 +7,15 @@ import re
7
  import asyncio
8
  import httpx
9
  import random
10
- from urllib.parse import urlparse, parse_qs, unquote
11
- from bs4 import BeautifulSoup
12
  from huggingface_hub import InferenceClient
13
  from fastapi import FastAPI, Request, Form
14
  from fastapi.responses import HTMLResponse
15
 
 
 
 
 
16
  # Try importing Redis at top level for clean architectural mapping
17
  REDIS_AVAILABLE = False
18
  try:
@@ -23,6 +26,9 @@ except ImportError:
23
 
24
  app = FastAPI()
25
 
 
 
 
26
  # --- GATHER AND VALIDATE SECRET KEYS FROM ENVIRONMENT ---
27
  HF_TOKEN = os.getenv("HF_TOKEN")
28
  if not HF_TOKEN:
@@ -121,7 +127,6 @@ async def check_url_safe(url: str, client: httpx.AsyncClient) -> bool:
121
  if not SAFE_BROWSING_API:
122
  print("⚠️ WARNING: SAFE_BROWSING_API key missing. Bypassing live link validation safety verification.")
123
  return True
124
-
125
  api_url = f"https://safebrowsing.googleapis.com/v4/threatMatches:find?key={SAFE_BROWSING_API}"
126
  payload = {
127
  "client": {"clientId": "tarz-ai-search-agent", "clientVersion": "1.1.0"},
@@ -130,8 +135,7 @@ async def check_url_safe(url: str, client: httpx.AsyncClient) -> bool:
130
  "platformTypes": ["ANY_PLATFORM"],
131
  "threatEntryTypes": ["URL"],
132
  "threatEntries": [{"url": url}]
133
- }
134
- }
135
  try:
136
  response = await client.post(api_url, json=payload, timeout=5.0)
137
  if response.status_code == 200:
@@ -154,7 +158,6 @@ def extract_universal_sizing(text: str) -> str:
154
  return ""
155
 
156
  text_norm = " " + text.upper().strip() + " "
157
-
158
  dim_match = re.search(r'(\d+(?:\.\d+)?)\s*(?:FL\.?\s*)?(OZ|ML|MM|CM|INCH|IN)\b', text_norm)
159
  if dim_match:
160
  val = dim_match.group(1)
@@ -198,7 +201,7 @@ def is_size_mismatched(target_size: str, parsed_text: str) -> bool:
198
  print(f"πŸ›‘οΈ [Size Filter] Dropped mismatched clothing variant asset: Target {clean_target} != Found {found_size}")
199
  return True
200
 
201
- return False
202
 
203
  # --- GOOGLE URL REDIRECT UNWRAPPER ENGINE ---
204
  def clean_google_link(url: str) -> str:
@@ -381,14 +384,22 @@ async def get_tavily_payload(query: str, desired_size: str, client: httpx.AsyncC
381
  return scraped_pages
382
 
383
  # --- 100% FREE ROUTER ROUTE: DUCKDUCKGO HTML KEYLESS FALLBACK ENGINE ---
384
- async def fetch_ddg_backup_shopping(product_name: str, desired_size: str, client: httpx.AsyncClient) -> list:
385
- """Performs structured context harvesting directly from DuckDuckGo organic text clusters with zero tokens spent"""
 
 
 
386
  scraped_pages = []
387
- search_q = f"buy {product_name} {desired_size} retail price".strip()
 
 
 
 
 
388
  url = f"https://html.duckduckgo.com/html/?q={requests.utils.quote(search_q)}"
389
  headers = {"User-Agent": random.choice(USER_AGENTS)}
390
  try:
391
- print(f"πŸ¦† [DuckDuckGo Fallback] Routing zero-cost backup query pipeline for '{search_q}'")
392
  res = await client.get(url, headers=headers, timeout=8.0)
393
  if res.status_code == 200:
394
  soup = BeautifulSoup(res.text, 'html.parser')
@@ -399,14 +410,15 @@ async def fetch_ddg_backup_shopping(product_name: str, desired_size: str, client
399
  if a_tag and snippet_tag:
400
  snippet_text = snippet_tag.get_text()
401
 
402
- if desired_size and is_size_mismatched(desired_size, snippet_text):
 
403
  continue
404
 
405
  raw_href = a_tag.get('href', '')
406
  if "duckduckgo.com" in raw_href and "uddg=" in raw_href:
407
  qs = parse_qs(urlparse(raw_href).query)
408
  if "uddg" in qs: raw_href = unquote(qs["uddg"][0])
409
-
410
  if raw_href.startswith("http"):
411
  scraped_pages.append({
412
  "id": len(scraped_pages),
@@ -418,6 +430,30 @@ async def fetch_ddg_backup_shopping(product_name: str, desired_size: str, client
418
  print(f"❌ [DuckDuckGo Engine Failure] Processing bypassed: {e}")
419
  return scraped_pages
420
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421
  # --- MASTER PRICE SWEEPER SEQUENCE (CASCADING MULTI-ENGINE ROUTER) ---
422
  async def scan_prices(product_name, desired_size=""):
423
  """Orchestrates structured arrays across all endpoints concurrently while bypassing broken environment proxies"""
@@ -425,7 +461,6 @@ async def scan_prices(product_name, desired_size=""):
425
 
426
  # Critical Fix: trust_env=False strips out un-prefixed platform infrastructure proxy errors completely
427
  async with httpx.AsyncClient(limits=limits, http2=True, trust_env=False) as client:
428
-
429
  deals = await fetch_serpapi_shopping(product_name, desired_size, client)
430
 
431
  scraped_pages = []
@@ -436,7 +471,7 @@ async def scan_prices(product_name, desired_size=""):
436
  if not scraped_pages:
437
  print("πŸ¦† [Engine Cascader] Secondary API pools empty. Initiating 100% free open DuckDuckGo scrape clusters...")
438
  scraped_pages = await fetch_ddg_backup_shopping(product_name, desired_size, client)
439
-
440
  results = []
441
  if scraped_pages and not deals:
442
  batch_instructions = f"""
@@ -488,11 +523,11 @@ async def scan_prices(product_name, desired_size=""):
488
  "source": urlparse(page['url']).netloc.replace("www.", ""),
489
  "size": desired_size or "Standard"
490
  })
491
-
492
  combined_output = deals if deals else results
493
  if not combined_output:
494
  return []
495
-
496
  print("πŸ”’ [Safe Browsing] Pre-filtering target array matrix outputs against phishing and malware definitions...")
497
  security_mask = await asyncio.gather(*[check_url_safe(item['url'], client) for item in combined_output])
498
 
@@ -527,14 +562,14 @@ def generate_ui(results_html="", error_msg=""):
527
  * {{ box-sizing: border-box; }}
528
 
529
  body {{
530
- font-family: 'Inter', -apple-system, sans-serif;
531
- padding: 40px 20px;
532
- background: var(--bg-main);
533
- color: var(--text-main);
534
- max-width: 850px;
535
- margin: auto;
536
- line-height: 1.5;
537
- -webkit-text-size-adjust: 100%;
538
  }}
539
 
540
  h2 {{ font-size: 28px; font-weight: 700; letter-spacing: -0.025em; margin-bottom: 4px; color: #ffffff; display: flex; align-items: center; gap: 12px; }}
@@ -606,6 +641,34 @@ def generate_ui(results_html="", error_msg=""):
606
  document.getElementById("submit-btn").style.display = "none";
607
  document.getElementById("loader-zone").style.display = "block";
608
  }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609
  </script>
610
  </head>
611
  <body>
@@ -617,7 +680,7 @@ def generate_ui(results_html="", error_msg=""):
617
  <div class="status-pill"></div>
618
  <span>{status_text}</span>
619
  </div>
620
-
621
  {error_html}
622
  <div class="card">
623
  <h3>
@@ -640,7 +703,7 @@ def generate_ui(results_html="", error_msg=""):
640
  <svg class="icon" viewBox="0 0 24 24"><path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"/></svg>
641
  Execute Price Scout Sweep
642
  </button>
643
-
644
  <div id="loader-zone" class="loader-box">
645
  <p style="color: var(--text-muted); font-size: 14px; margin-bottom: 15px; text-align: center;">⚑ Price Scout is assembling structural pricing matrices across real-time storage nodes...</p>
646
  <div style="height: 64px; width: 100%; margin-bottom: 12px;" class="skeleton"></div>
@@ -649,7 +712,7 @@ def generate_ui(results_html="", error_msg=""):
649
  </div>
650
  </form>
651
  </div>
652
-
653
  {results_html}
654
  </body>
655
  </html>
@@ -664,36 +727,34 @@ def dashboard():
664
  async def handle_search(product_name: str = Form(...), product_size: str = Form(None)):
665
  if not HF_TOKEN:
666
  return generate_ui(error_msg="Please add a valid HF_TOKEN into Space Secrets to activate the free AI models.")
667
-
668
  raw_input = product_name.strip()
669
  requested_size = extract_universal_sizing(product_size) if product_size else ""
670
-
671
  force_refresh = raw_input.endswith("*")
672
  if force_refresh:
673
  target_item = raw_input.rstrip("*").strip()
674
  print(f"⚑ [Force Refresh] Evicting active cache entries for query mapping context: '{target_item}'")
675
  else:
676
  target_item = raw_input
677
-
678
  target_item = scrub_conversational_bloat(target_item) if not target_item.startswith(("http", "https")) else target_item
679
-
680
  deals = []
681
  original_site_deal = None
682
  fallback_img = "https://placehold.co/100x100/1a1c28/9fa4b4?text=IMG"
683
-
684
  if target_item.startswith(("http://", "https://")):
685
  input_url = target_item
686
  print(f"πŸ”— [Input URL] Pasted hyperlink reference intercepted: {input_url}")
687
-
688
- # Fixed: Added trust_env=False here to clear potential platform proxy drops
689
  async with httpx.AsyncClient(trust_env=False) as safety_client:
690
  if not await check_url_safe(input_url, safety_client):
691
  return generate_ui(error_msg="The provided link target matches active security alert threat signatures and was isolated.")
692
-
693
  raw_text, img_url = extract_page_data(input_url, "product")
694
  if not raw_text:
695
  return generate_ui(error_msg="Tarz could not parse or connect to the provided URL.")
696
-
697
  try:
698
  url_prompt = f"""
699
  Identify the exact product name, find its listed retail numerical price, and sizing text from the block:
@@ -710,7 +771,7 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
710
  target_item = url_data['product_name']
711
  if not requested_size:
712
  requested_size = extract_universal_sizing(url_data.get('size'))
713
-
714
  original_site_deal = {
715
  "url": input_url,
716
  "price": round(float(url_data['price']), 2),
@@ -732,15 +793,14 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
732
  }
733
  else:
734
  return generate_ui(error_msg="Programmatic local parser could not identify currency text variables.")
735
-
736
  if not original_site_deal:
737
  return generate_ui(error_msg="Pasted link parsed, but price extraction could not resolve valid currency markers.")
738
  except Exception as e:
739
  print(f"❌ [Link Analytics Error] Failure processing link data parsing: {e}")
740
  return generate_ui(error_msg="Error decoding reference link metadata structure.")
741
-
742
  cached_deals = None if force_refresh else get_cached_deals(target_item, requested_size)
743
-
744
  if cached_deals:
745
  print(f"⚑ [Cache Hit] Found unexpired retail pricing matrix for '{target_item}' | Size: '{requested_size}'. Skipping live queries.")
746
  deals = cached_deals
@@ -749,12 +809,12 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
749
  deals = await scan_prices(target_item, requested_size)
750
  if deals:
751
  set_cached_deals(target_item, requested_size, deals)
752
-
753
  if original_site_deal:
754
  if not any(d['url'] == original_site_deal['url'] for d in deals):
755
  deals.append(original_site_deal)
756
  deals.sort(key=lambda x: x['price'])
757
-
758
  size_header = f" ({requested_size})" if requested_size else ""
759
  if not deals:
760
  print("⚠️ [Finished Execution] Matrix build completed with 0 valid results.")
@@ -766,11 +826,11 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
766
  """
767
  else:
768
  print(f"πŸŽ‰ [Finished Execution] Successfully built pricing matrix with {len(deals)} results.")
769
-
770
  results_list = ""
771
  for idx, deal in enumerate(deals):
772
  img_src = deal['image'] if deal['image'] else fallback_img
773
-
774
  best_value_badge = ""
775
  if idx == 0:
776
  best_value_badge = """
@@ -779,7 +839,7 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
779
  Best Value
780
  </span>
781
  """
782
-
783
  verified_badge = ""
784
  if deal.get('source'):
785
  verified_badge = """
@@ -788,14 +848,14 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
788
  Verified
789
  </span>
790
  """
791
-
792
  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 ""
793
-
794
  domain = deal.get('source') or "link"
795
  if "google.com" not in deal['url']:
796
  try: domain = urlparse(deal['url']).netloc.replace("www.", "")
797
  except: pass
798
-
799
  results_list += f"""
800
  <li class="deal-item">
801
  <img src="{img_src}" class="product-img" onerror="this.src='{fallback_img}'" />
@@ -813,17 +873,107 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
813
  <span class="price-tag">${deal['price']:.2f}</span>
814
  </li>
815
  """
816
-
817
  results_html = f"""
818
  <div class="card" style="border-color: var(--accent-green);">
819
  <h3>Results Matrix for: <span style="color: var(--accent-blue); margin-left: 4px;"><b>{target_item}{size_header}</b></span></h3>
820
- <p style="color:var(--accent-green); font-weight:600; margin-top:-10px; font-size:15px;">πŸ† Lowest verified price found: ${deals[0]['price']:.2f}</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
821
  <ul style="margin-top: 15px;">{results_list}</ul>
822
  </div>
823
  """
824
-
825
  return generate_ui(results_html=results_html)
826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
827
  if __name__ == "__main__":
828
  import uvicorn
829
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
7
  import asyncio
8
  import httpx
9
  import random
10
+ from urllib.parse import urlparse, parse_qs, unquotefrom bs4 import BeautifulSoup
 
11
  from huggingface_hub import InferenceClient
12
  from fastapi import FastAPI, Request, Form
13
  from fastapi.responses import HTMLResponse
14
 
15
+ # --- NEW LOCALIZATION IMPORTS ---
16
+ from geopy.geocoders import Nominatim
17
+ from geopy.exc import GeocoderTimedOut, GeocoderServiceError
18
+
19
  # Try importing Redis at top level for clean architectural mapping
20
  REDIS_AVAILABLE = False
21
  try:
 
26
 
27
  app = FastAPI()
28
 
29
+ # Initialize free geolocator - Specific User-Agent requested per OSM naming policy
30
+ geolocator = Nominatim(user_agent="tarz_price_scout_v1")
31
+
32
  # --- GATHER AND VALIDATE SECRET KEYS FROM ENVIRONMENT ---
33
  HF_TOKEN = os.getenv("HF_TOKEN")
34
  if not HF_TOKEN:
 
127
  if not SAFE_BROWSING_API:
128
  print("⚠️ WARNING: SAFE_BROWSING_API key missing. Bypassing live link validation safety verification.")
129
  return True
 
130
  api_url = f"https://safebrowsing.googleapis.com/v4/threatMatches:find?key={SAFE_BROWSING_API}"
131
  payload = {
132
  "client": {"clientId": "tarz-ai-search-agent", "clientVersion": "1.1.0"},
 
135
  "platformTypes": ["ANY_PLATFORM"],
136
  "threatEntryTypes": ["URL"],
137
  "threatEntries": [{"url": url}]
138
+ } }
 
139
  try:
140
  response = await client.post(api_url, json=payload, timeout=5.0)
141
  if response.status_code == 200:
 
158
  return ""
159
 
160
  text_norm = " " + text.upper().strip() + " "
 
161
  dim_match = re.search(r'(\d+(?:\.\d+)?)\s*(?:FL\.?\s*)?(OZ|ML|MM|CM|INCH|IN)\b', text_norm)
162
  if dim_match:
163
  val = dim_match.group(1)
 
201
  print(f"πŸ›‘οΈ [Size Filter] Dropped mismatched clothing variant asset: Target {clean_target} != Found {found_size}")
202
  return True
203
 
204
+ return False
205
 
206
  # --- GOOGLE URL REDIRECT UNWRAPPER ENGINE ---
207
  def clean_google_link(url: str) -> str:
 
384
  return scraped_pages
385
 
386
  # --- 100% FREE ROUTER ROUTE: DUCKDUCKGO HTML KEYLESS FALLBACK ENGINE ---
387
+ async def fetch_ddg_backup_shopping(product_name: str, desired_size: str, client: httpx.AsyncClient, override_query: str = None) -> list:
388
+ """
389
+ Performs structured context harvesting directly from DuckDuckGo organic text clusters with zero tokens spent.
390
+ Supports an optional override_query parameter for targeted local proximity routing.
391
+ """
392
  scraped_pages = []
393
+
394
+ if override_query:
395
+ search_q = override_query
396
+ else:
397
+ search_q = f"buy {product_name} {desired_size} retail price".strip()
398
+
399
  url = f"https://html.duckduckgo.com/html/?q={requests.utils.quote(search_q)}"
400
  headers = {"User-Agent": random.choice(USER_AGENTS)}
401
  try:
402
+ print(f"πŸ¦† [DuckDuckGo Engine] Routing fallback query pipeline for '{search_q}'")
403
  res = await client.get(url, headers=headers, timeout=8.0)
404
  if res.status_code == 200:
405
  soup = BeautifulSoup(res.text, 'html.parser')
 
410
  if a_tag and snippet_tag:
411
  snippet_text = snippet_tag.get_text()
412
 
413
+ # Nuance adjustment: Skip size validation thresholds for override mapping sequences
414
+ if not override_query and desired_size and is_size_mismatched(desired_size, snippet_text):
415
  continue
416
 
417
  raw_href = a_tag.get('href', '')
418
  if "duckduckgo.com" in raw_href and "uddg=" in raw_href:
419
  qs = parse_qs(urlparse(raw_href).query)
420
  if "uddg" in qs: raw_href = unquote(qs["uddg"][0])
421
+
422
  if raw_href.startswith("http"):
423
  scraped_pages.append({
424
  "id": len(scraped_pages),
 
430
  print(f"❌ [DuckDuckGo Engine Failure] Processing bypassed: {e}")
431
  return scraped_pages
432
 
433
+ # --- FREE GEOLOCATION REVERSE LOOKUP UTILITY ---
434
+ def get_location_name(lat, lon):
435
+ """Converts latitude/longitude to a City, State or Zip string via OpenStreetMap nodes"""
436
+ try:
437
+ query = f"{lat}, {lon}"
438
+ location = geolocator.reverse(query, timeout=5)
439
+ if location:
440
+ address = location.raw.get('address', {})
441
+ city = address.get('city') or address.get('town') or address.get('village')
442
+ state = address.get('state')
443
+ postcode = address.get('postcode')
444
+
445
+ if city and state:
446
+ return f"{city}, {state}"
447
+ elif postcode:
448
+ return f"Zip {postcode}"
449
+ else:
450
+ return location.address.split(',')[0]
451
+ except (GeocoderTimedOut, GeocoderServiceError) as e:
452
+ print(f"⚠️ [Geopy Error] Service timed out or grew unavailable: {e}")
453
+ except Exception as e:
454
+ print(f"❌ [Geocoding Error] {e}")
455
+ return None
456
+
457
  # --- MASTER PRICE SWEEPER SEQUENCE (CASCADING MULTI-ENGINE ROUTER) ---
458
  async def scan_prices(product_name, desired_size=""):
459
  """Orchestrates structured arrays across all endpoints concurrently while bypassing broken environment proxies"""
 
461
 
462
  # Critical Fix: trust_env=False strips out un-prefixed platform infrastructure proxy errors completely
463
  async with httpx.AsyncClient(limits=limits, http2=True, trust_env=False) as client:
 
464
  deals = await fetch_serpapi_shopping(product_name, desired_size, client)
465
 
466
  scraped_pages = []
 
471
  if not scraped_pages:
472
  print("πŸ¦† [Engine Cascader] Secondary API pools empty. Initiating 100% free open DuckDuckGo scrape clusters...")
473
  scraped_pages = await fetch_ddg_backup_shopping(product_name, desired_size, client)
474
+
475
  results = []
476
  if scraped_pages and not deals:
477
  batch_instructions = f"""
 
523
  "source": urlparse(page['url']).netloc.replace("www.", ""),
524
  "size": desired_size or "Standard"
525
  })
526
+
527
  combined_output = deals if deals else results
528
  if not combined_output:
529
  return []
530
+
531
  print("πŸ”’ [Safe Browsing] Pre-filtering target array matrix outputs against phishing and malware definitions...")
532
  security_mask = await asyncio.gather(*[check_url_safe(item['url'], client) for item in combined_output])
533
 
 
562
  * {{ box-sizing: border-box; }}
563
 
564
  body {{
565
+ font-family: 'Inter', -apple-system, sans-serif;
566
+ padding: 40px 20px;
567
+ background: var(--bg-main);
568
+ color: var(--text-main);
569
+ max-width: 850px;
570
+ margin: auto;
571
+ line-height: 1.5;
572
+ -webkit-text-size-adjust: 100%;
573
  }}
574
 
575
  h2 {{ font-size: 28px; font-weight: 700; letter-spacing: -0.025em; margin-bottom: 4px; color: #ffffff; display: flex; align-items: center; gap: 12px; }}
 
641
  document.getElementById("submit-btn").style.display = "none";
642
  document.getElementById("loader-zone").style.display = "block";
643
  }}
644
+
645
+ function triggerLocalDiscovery() {{
646
+ const btn = document.getElementById('local-submit-btn');
647
+ btn.innerText = "⏳ Requesting Location...";
648
+ btn.disabled = true;
649
+
650
+ if ("geolocation" in navigator) {{
651
+ navigator.geolocation.getCurrentPosition(
652
+ function(position) {{
653
+ document.getElementById('local_lat').value = position.coords.latitude;
654
+ document.getElementById('local_lon').value = position.coords.longitude;
655
+
656
+ btn.innerText = "⚑ Initializing Proximity Sweep...";
657
+ document.getElementById("loader-zone").style.display = "block";
658
+ document.getElementById('nearby-form').submit();
659
+ }},
660
+ function(error) {{
661
+ btn.innerText = "❌ Location Permission Denied";
662
+ btn.style.background = "#ef4444";
663
+ console.error(error);
664
+ btn.disabled = false;
665
+ }},
666
+ {{ timeout: 8000 }}
667
+ );
668
+ }} else {{
669
+ btn.innerText = "❌ Browser Location Unsupported";
670
+ }}
671
+ }}
672
  </script>
673
  </head>
674
  <body>
 
680
  <div class="status-pill"></div>
681
  <span>{status_text}</span>
682
  </div>
683
+
684
  {error_html}
685
  <div class="card">
686
  <h3>
 
703
  <svg class="icon" viewBox="0 0 24 24"><path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"/></svg>
704
  Execute Price Scout Sweep
705
  </button>
706
+
707
  <div id="loader-zone" class="loader-box">
708
  <p style="color: var(--text-muted); font-size: 14px; margin-bottom: 15px; text-align: center;">⚑ Price Scout is assembling structural pricing matrices across real-time storage nodes...</p>
709
  <div style="height: 64px; width: 100%; margin-bottom: 12px;" class="skeleton"></div>
 
712
  </div>
713
  </form>
714
  </div>
715
+
716
  {results_html}
717
  </body>
718
  </html>
 
727
  async def handle_search(product_name: str = Form(...), product_size: str = Form(None)):
728
  if not HF_TOKEN:
729
  return generate_ui(error_msg="Please add a valid HF_TOKEN into Space Secrets to activate the free AI models.")
730
+
731
  raw_input = product_name.strip()
732
  requested_size = extract_universal_sizing(product_size) if product_size else ""
733
+
734
  force_refresh = raw_input.endswith("*")
735
  if force_refresh:
736
  target_item = raw_input.rstrip("*").strip()
737
  print(f"⚑ [Force Refresh] Evicting active cache entries for query mapping context: '{target_item}'")
738
  else:
739
  target_item = raw_input
740
+
741
  target_item = scrub_conversational_bloat(target_item) if not target_item.startswith(("http", "https")) else target_item
 
742
  deals = []
743
  original_site_deal = None
744
  fallback_img = "https://placehold.co/100x100/1a1c28/9fa4b4?text=IMG"
745
+
746
  if target_item.startswith(("http://", "https://")):
747
  input_url = target_item
748
  print(f"πŸ”— [Input URL] Pasted hyperlink reference intercepted: {input_url}")
749
+
 
750
  async with httpx.AsyncClient(trust_env=False) as safety_client:
751
  if not await check_url_safe(input_url, safety_client):
752
  return generate_ui(error_msg="The provided link target matches active security alert threat signatures and was isolated.")
753
+
754
  raw_text, img_url = extract_page_data(input_url, "product")
755
  if not raw_text:
756
  return generate_ui(error_msg="Tarz could not parse or connect to the provided URL.")
757
+
758
  try:
759
  url_prompt = f"""
760
  Identify the exact product name, find its listed retail numerical price, and sizing text from the block:
 
771
  target_item = url_data['product_name']
772
  if not requested_size:
773
  requested_size = extract_universal_sizing(url_data.get('size'))
774
+
775
  original_site_deal = {
776
  "url": input_url,
777
  "price": round(float(url_data['price']), 2),
 
793
  }
794
  else:
795
  return generate_ui(error_msg="Programmatic local parser could not identify currency text variables.")
796
+
797
  if not original_site_deal:
798
  return generate_ui(error_msg="Pasted link parsed, but price extraction could not resolve valid currency markers.")
799
  except Exception as e:
800
  print(f"❌ [Link Analytics Error] Failure processing link data parsing: {e}")
801
  return generate_ui(error_msg="Error decoding reference link metadata structure.")
802
+
803
  cached_deals = None if force_refresh else get_cached_deals(target_item, requested_size)
 
804
  if cached_deals:
805
  print(f"⚑ [Cache Hit] Found unexpired retail pricing matrix for '{target_item}' | Size: '{requested_size}'. Skipping live queries.")
806
  deals = cached_deals
 
809
  deals = await scan_prices(target_item, requested_size)
810
  if deals:
811
  set_cached_deals(target_item, requested_size, deals)
812
+
813
  if original_site_deal:
814
  if not any(d['url'] == original_site_deal['url'] for d in deals):
815
  deals.append(original_site_deal)
816
  deals.sort(key=lambda x: x['price'])
817
+
818
  size_header = f" ({requested_size})" if requested_size else ""
819
  if not deals:
820
  print("⚠️ [Finished Execution] Matrix build completed with 0 valid results.")
 
826
  """
827
  else:
828
  print(f"πŸŽ‰ [Finished Execution] Successfully built pricing matrix with {len(deals)} results.")
829
+
830
  results_list = ""
831
  for idx, deal in enumerate(deals):
832
  img_src = deal['image'] if deal['image'] else fallback_img
833
+
834
  best_value_badge = ""
835
  if idx == 0:
836
  best_value_badge = """
 
839
  Best Value
840
  </span>
841
  """
842
+
843
  verified_badge = ""
844
  if deal.get('source'):
845
  verified_badge = """
 
848
  Verified
849
  </span>
850
  """
851
+
852
  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 ""
853
+
854
  domain = deal.get('source') or "link"
855
  if "google.com" not in deal['url']:
856
  try: domain = urlparse(deal['url']).netloc.replace("www.", "")
857
  except: pass
858
+
859
  results_list += f"""
860
  <li class="deal-item">
861
  <img src="{img_src}" class="product-img" onerror="this.src='{fallback_img}'" />
 
873
  <span class="price-tag">${deal['price']:.2f}</span>
874
  </li>
875
  """
876
+
877
  results_html = f"""
878
  <div class="card" style="border-color: var(--accent-green);">
879
  <h3>Results Matrix for: <span style="color: var(--accent-blue); margin-left: 4px;"><b>{target_item}{size_header}</b></span></h3>
880
+ <p style="color:var(--accent-green); font-weight:600; margin-top:-10px; font-size:15px;">πŸ† Lowest verified online price: ${deals[0]['price']:.2f}</p>
881
+
882
+ <div style="background: rgba(59, 130, 246, 0.05); border: 1px dashed rgba(59, 130, 246, 0.3); padding: 15px; border-radius: 10px; margin: 20px 0; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
883
+ <div>
884
+ <h4 style="margin: 0; color: #fff; font-size: 14px;">Looking for this item locally?</h4>
885
+ <p style="margin: 2px 0 0 0; color: var(--text-muted); font-size: 12px;">Scan brick-and-mortar retailers around your current city.</p>
886
+ </div>
887
+ <form action="/search-nearby" method="post" id="nearby-form" style="margin:0;">
888
+ <input type="hidden" name="local_product" value="{target_item}">
889
+ <input type="hidden" name="local_size" value="{requested_size}">
890
+ <input type="hidden" name="lat" id="local_lat" value="">
891
+ <input type="hidden" name="lon" id="local_lon" value="">
892
+ <button type="button" id="local-submit-btn" onclick="triggerLocalDiscovery()" style="background: var(--accent-blue); padding: 10px 16px; font-size: 13px; width: auto; box-shadow: none;">
893
+ πŸ“ Check Local Stores
894
+ </button>
895
+ </form>
896
+ </div>
897
+
898
  <ul style="margin-top: 15px;">{results_list}</ul>
899
  </div>
900
  """
901
+
902
  return generate_ui(results_html=results_html)
903
 
904
+ # --- ISOLATED ON-DEMAND PROXIMITY DISCOVERY ROUTE ---
905
+ @app.post("/search-nearby", response_class=HTMLResponse)
906
+ async def handle_nearby_search(
907
+ local_product: str = Form(...),
908
+ local_size: str = Form(None),
909
+ lat: str = Form(...),
910
+ lon: str = Form(...)
911
+ ):
912
+ if not lat or not lon or lat == "undefined" or lon == "undefined":
913
+ return generate_ui(error_msg="Could not determine proximity data coordinates. Check browser permissions.")
914
+
915
+ location_string = "Your Area"
916
+ try:
917
+ location = geolocator.reverse(f"{lat}, {lon}", timeout=4)
918
+ if location:
919
+ address = location.raw.get('address', {})
920
+ city = address.get('city') or address.get('town') or address.get('village')
921
+ state = address.get('state')
922
+ if city and state:
923
+ location_string = f"{city}, {state}"
924
+ except Exception as e:
925
+ print(f"⚠️ Geocoding reverse operation failed: {e}")
926
+
927
+ # Build targeted brick-and-mortar local discovery string
928
+ proximity_query = f"{local_product} {local_size or ''} in-store near {location_string}".strip()
929
+ print(f"πŸ“ [Proximity Run] Launching isolated engine task: '{proximity_query}'")
930
+
931
+ limits = httpx.Limits(max_keepalive_connections=5, max_connections=5)
932
+ async with httpx.AsyncClient(limits=limits, http2=True, trust_env=False) as client:
933
+ raw_pages = await fetch_ddg_backup_shopping(
934
+ product_name=local_product,
935
+ desired_size=local_size or "",
936
+ client=client,
937
+ override_query=proximity_query
938
+ )
939
+
940
+ if not raw_pages:
941
+ local_html = f"""
942
+ <div class="card" style="border-color: #f59e0b;">
943
+ <h3>Proximity Search: <i>{local_product}</i></h3>
944
+ <p style="color: var(--text-muted);">No brick-and-mortar store matches or inventory footprints were found indexed near <b>{location_string}</b>.</p>
945
+ <a href="/" style="color: var(--accent-blue); text-decoration: none; font-size: 14px;">← Back to Online Search</a>
946
+ </div>
947
+ """
948
+ else:
949
+ results_list = ""
950
+ for idx, page in enumerate(raw_pages):
951
+ domain = urlparse(page['url']).netloc.replace("www.", "")
952
+ results_list += f"""
953
+ <li class="deal-item" style="border-left-color: var(--accent-blue); background: #121824;">
954
+ <div class="deal-info">
955
+ <span class="item-title">{local_product}</span>
956
+ <div class="meta-container">
957
+ <span class="domain-badge" style="background:rgba(59,130,246,0.1); color:#60a5fa; border-color:rgba(59,130,246,0.2)">πŸ“ {domain}</span>
958
+ <span class="size-badge">{local_size or 'Standard'}</span>
959
+ <a href="{page['url']}" target="_blank" class="small-link">{page['url']}</a>
960
+ </div>
961
+ </div>
962
+ <span class="price-tag" style="background: var(--accent-blue); box-shadow: 0 4px 10px rgba(59, 130, 246, 0.2);">Local Store</span>
963
+ </li>
964
+ """
965
+
966
+ local_html = f"""
967
+ <div class="card" style="border-color: var(--accent-blue);">
968
+ <h3>πŸ“ Local Footprint Near: <span style="color: #60a5fa;">{location_string}</span></h3>
969
+ <p style="color: var(--text-muted); font-size: 14px; margin-top: -10px;">Showing matching brick-and-mortar references for: <b>{local_product}</b></p>
970
+ <ul style="margin-top: 15px;">{results_list}</ul>
971
+ <div style="margin-top: 20px;"><a href="/" style="color: var(--text-muted); text-decoration: none; font-size: 13px;">← Return to Main Dashboard</a></div>
972
+ </div>
973
+ """
974
+
975
+ return generate_ui(results_html=local_html)
976
+
977
  if __name__ == "__main__":
978
  import uvicorn
979
  uvicorn.run(app, host="0.0.0.0", port=7860)