Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -177,56 +177,149 @@ async def check_url_safe(url: str, client: httpx.AsyncClient) -> bool:
|
|
| 177 |
print(f"❌ [Safe Browsing Exception] Connection failed: {e}. Isolation fallback activated.")
|
| 178 |
return False
|
| 179 |
|
| 180 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
def extract_universal_sizing(text: str) -> str:
|
| 182 |
-
"""Uses a normalized regex matrix to extract
|
| 183 |
if not text or len(text) > 100:
|
| 184 |
return ""
|
| 185 |
|
| 186 |
text_norm = " " + text.upper().strip() + " "
|
| 187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
if dim_match:
|
| 189 |
-
|
| 190 |
-
unit = dim_match.group(2)
|
| 191 |
-
return f"{val} {unit}"
|
| 192 |
|
|
|
|
| 193 |
if "EXTRA LARGE" in text_norm or "X-LARGE" in text_norm: return "XL"
|
| 194 |
if "LARGE" in text_norm: return "L"
|
| 195 |
if "MEDIUM" in text_norm: return "M"
|
| 196 |
if "SMALL" in text_norm: return "S"
|
| 197 |
-
|
| 198 |
clothing_match = re.search(r'\b(XS|S|M|L|XL|2XL|XXL|3XL|4XL)\b', text_norm)
|
| 199 |
-
if clothing_match:
|
| 200 |
-
return clothing_match.group(1)
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
for tag in ['US', 'UK', 'EU']:
|
| 206 |
-
if tag in text_norm:
|
| 207 |
-
context = tag + " "
|
| 208 |
-
return f"{context}{shoe_match.group(1)}"
|
| 209 |
-
|
| 210 |
-
if "ONE SIZE" in text_norm or "ONE-SIZE" in text_norm:
|
| 211 |
-
return "OSFA"
|
| 212 |
|
| 213 |
return text.strip()
|
| 214 |
|
| 215 |
-
# --- ADVANCED SIZE-MATCHING CROSS-FILTERS ---
|
| 216 |
-
def is_size_mismatched(target_size: str, parsed_text: str) -> bool:
|
| 217 |
-
"""Verifies text blocks to ensure alternative size variants do not cross-contaminate results universally"""
|
| 218 |
-
if not target_size or not parsed_text:
|
| 219 |
-
return False
|
| 220 |
-
|
| 221 |
-
clean_target = target_size.upper().replace(" ", "")
|
| 222 |
-
found_size = extract_universal_sizing(parsed_text).upper().replace(" ", "")
|
| 223 |
-
|
| 224 |
-
# CRITICAL BUG FIX: Enforce size rejections globally instead of constraining filtering to clothing standards.
|
| 225 |
-
if found_size and clean_target != found_size:
|
| 226 |
-
return True
|
| 227 |
-
|
| 228 |
-
return False
|
| 229 |
-
|
| 230 |
# --- GOOGLE URL REDIRECT UNWRAPPER ENGINE ---
|
| 231 |
def clean_google_link(url: str) -> str:
|
| 232 |
"""Extracts raw outbound seller targets from Google tracking wrappers safely"""
|
|
@@ -343,23 +436,21 @@ async def fetch_serpapi_shopping(product_name: str, desired_size: str, client: h
|
|
| 343 |
if response.status_code == 200:
|
| 344 |
data = response.json()
|
| 345 |
formatted_deals = []
|
| 346 |
-
clean_target_size = desired_size.upper().replace(" ", "") if desired_size else ""
|
| 347 |
|
| 348 |
for item in data.get("shopping_results", []):
|
| 349 |
title = item.get("title", "")
|
| 350 |
snippet = item.get("snippet", "")
|
| 351 |
combined_text = f"{title} {snippet}"
|
| 352 |
|
| 353 |
-
# STRENGTHENED MATCHING FOR PRECISION MATCH MODE
|
| 354 |
if mode == "exact":
|
| 355 |
title_clean = title.lower()
|
| 356 |
-
req_tokens = [t for t in product_name.lower().split() if
|
| 357 |
if not all(token in title_clean for token in req_tokens):
|
| 358 |
continue
|
| 359 |
-
if
|
| 360 |
continue
|
| 361 |
elif mode == "balanced":
|
| 362 |
-
if
|
| 363 |
continue
|
| 364 |
|
| 365 |
price_val = item.get("extracted_price")
|
|
@@ -368,6 +459,7 @@ async def fetch_serpapi_shopping(product_name: str, desired_size: str, client: h
|
|
| 368 |
|
| 369 |
if price_val and link:
|
| 370 |
formatted_deals.append({
|
|
|
|
| 371 |
"url": link,
|
| 372 |
"price": round(float(price_val), 2),
|
| 373 |
"image": item.get("thumbnail"),
|
|
@@ -569,12 +661,12 @@ async def scan_prices(product_name, desired_size="", mode: str = "balanced"):
|
|
| 569 |
if source_page:
|
| 570 |
det_size = extract_universal_sizing(report.get('size')) or report.get('size') or desired_size or "Standard"
|
| 571 |
|
| 572 |
-
# EXACT MODE ADDED FILTER IN HARVEST BLOCK
|
| 573 |
if mode == "exact" and desired_size:
|
| 574 |
if is_size_mismatched(desired_size, det_size):
|
| 575 |
continue
|
| 576 |
|
| 577 |
results.append({
|
|
|
|
| 578 |
"url": source_page['url'],
|
| 579 |
"price": round(float(report['price']), 2),
|
| 580 |
"image": source_page['image'],
|
|
@@ -590,6 +682,7 @@ async def scan_prices(product_name, desired_size="", mode: str = "balanced"):
|
|
| 590 |
report = parse_price_locally(page['text'], product_name)
|
| 591 |
if report["found"]:
|
| 592 |
results.append({
|
|
|
|
| 593 |
"url": page['url'],
|
| 594 |
"price": report["price"],
|
| 595 |
"image": page['image'],
|
|
@@ -606,7 +699,6 @@ async def scan_prices(product_name, desired_size="", mode: str = "balanced"):
|
|
| 606 |
|
| 607 |
vetted_safe_deals = [item for item, is_secure in zip(combined_output, security_mask) if is_secure]
|
| 608 |
|
| 609 |
-
# FINAL SECURITY FILTER LAYER FOR STRATEGIC EXACT MODES
|
| 610 |
if mode == "exact" and desired_size:
|
| 611 |
vetted_safe_deals = [item for item in vetted_safe_deals if not is_size_mismatched(desired_size, item.get('size', ''))]
|
| 612 |
|
|
@@ -672,7 +764,7 @@ def generate_ui(results_html="", error_msg="", prev_name="", prev_size="", prev_
|
|
| 672 |
button:hover {{ transform: translateY(-1px); box-shadow: 0 6px 16px rgba(59, 130, 246, 0.3); }}
|
| 673 |
|
| 674 |
ul {{ list-style-type: none; padding: 0; margin: 0; }}
|
| 675 |
-
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-
|
| 676 |
li:hover {{ border-color: rgba(255, 255, 255, 0.15); background: rgba(255, 255, 255, 0.04); }}
|
| 677 |
|
| 678 |
.deal-item-header {{ display: flex; align-items: center; justify-content: space-between; width: 100%; gap: 16px; }}
|
|
@@ -751,7 +843,7 @@ def generate_ui(results_html="", error_msg="", prev_name="", prev_size="", prev_
|
|
| 751 |
</div>
|
| 752 |
<div class="input-group size-group">
|
| 753 |
<label>Size / Variant</label>
|
| 754 |
-
<input type="text" name="product_size" value="{prev_size}" placeholder="e.g., 3.4 oz, XL" autocomplete="off">
|
| 755 |
</div>
|
| 756 |
<div class="input-group mode-group">
|
| 757 |
<label>Search Strategy</label>
|
|
@@ -798,13 +890,32 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
|
|
| 798 |
if not HF_TOKEN:
|
| 799 |
return generate_ui(error_msg="Please add a valid HF_TOKEN into Space Secrets to activate the free AI models.")
|
| 800 |
|
|
|
|
|
|
|
| 801 |
raw_input = product_name.strip()
|
| 802 |
-
|
| 803 |
-
|
| 804 |
force_refresh = raw_input.endswith("*")
|
| 805 |
if force_refresh:
|
| 806 |
-
|
| 807 |
-
print(f"⚡ [Force Refresh] Evicting active cache entries for query mapping context: '{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 808 |
else:
|
| 809 |
target_item = raw_input
|
| 810 |
|
|
@@ -820,11 +931,11 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
|
|
| 820 |
|
| 821 |
async with httpx.AsyncClient(trust_env=False) as safety_client:
|
| 822 |
if not await check_url_safe(input_url, safety_client):
|
| 823 |
-
return generate_ui(error_msg="The provided link target matches active security alert threat signatures and was isolated.", prev_name=
|
| 824 |
|
| 825 |
raw_text, img_url = extract_page_data(input_url, "product")
|
| 826 |
if not raw_text:
|
| 827 |
-
return generate_ui(error_msg="Tarz could not parse or connect to the provided URL.", prev_name=
|
| 828 |
|
| 829 |
try:
|
| 830 |
url_prompt = f"""
|
|
@@ -844,6 +955,7 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
|
|
| 844 |
requested_size = extract_universal_sizing(url_data.get('size'))
|
| 845 |
|
| 846 |
original_site_deal = {
|
|
|
|
| 847 |
"url": input_url,
|
| 848 |
"price": round(float(url_data['price']), 2),
|
| 849 |
"image": img_url,
|
|
@@ -856,6 +968,7 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
|
|
| 856 |
if local_report["found"]:
|
| 857 |
target_item = "Extracted Product Deal"
|
| 858 |
original_site_deal = {
|
|
|
|
| 859 |
"url": input_url,
|
| 860 |
"price": local_report["price"],
|
| 861 |
"image": img_url,
|
|
@@ -863,13 +976,13 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
|
|
| 863 |
"size": requested_size or "Standard"
|
| 864 |
}
|
| 865 |
else:
|
| 866 |
-
return generate_ui(error_msg="Programmatic local parser could not identify currency text variables.", prev_name=
|
| 867 |
|
| 868 |
if not original_site_deal:
|
| 869 |
-
return generate_ui(error_msg="Pasted link parsed, but price extraction could not resolve valid currency markers.", prev_name=
|
| 870 |
except Exception as e:
|
| 871 |
print(f"❌ [Link Analytics Error] Failure processing link data parsing: {e}")
|
| 872 |
-
return generate_ui(error_msg="Error decoding reference link metadata structure.", prev_name=
|
| 873 |
|
| 874 |
cached_deals = None if force_refresh else get_cached_deals(target_item, requested_size, search_mode)
|
| 875 |
cached_coupons = None if force_refresh else get_cached_coupons(target_item)
|
|
@@ -900,7 +1013,7 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
|
|
| 900 |
results_html = f"""
|
| 901 |
<div class="card" style="border-color: #ef4444;">
|
| 902 |
<h3>Query: <i>{target_item}{size_header}</i></h3>
|
| 903 |
-
<p style="color: var(--text-muted); margin: 0;">⚠️ No verifiable pricing matrices were found
|
| 904 |
</div>
|
| 905 |
"""
|
| 906 |
else:
|
|
@@ -949,13 +1062,14 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
|
|
| 949 |
"""
|
| 950 |
|
| 951 |
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 ""
|
|
|
|
| 952 |
|
| 953 |
results_list += f"""
|
| 954 |
<li class="deal-item">
|
| 955 |
<div class="deal-item-header">
|
| 956 |
<img src="{img_src}" class="product-img" onerror="this.src='{fallback_img}'" />
|
| 957 |
<div class="deal-info">
|
| 958 |
-
<span class="item-title">{
|
| 959 |
<div class="meta-container">
|
| 960 |
<span class="domain-badge">{domain}</span>
|
| 961 |
<span class="size-badge">{deal.get('size', 'Standard')}</span>
|
|
@@ -1008,7 +1122,7 @@ async def handle_search(product_name: str = Form(...), product_size: str = Form(
|
|
| 1008 |
</div>
|
| 1009 |
"""
|
| 1010 |
|
| 1011 |
-
return generate_ui(results_html=results_html, prev_name=
|
| 1012 |
|
| 1013 |
if __name__ == "__main__":
|
| 1014 |
import uvicorn
|
|
|
|
| 177 |
print(f"❌ [Safe Browsing Exception] Connection failed: {e}. Isolation fallback activated.")
|
| 178 |
return False
|
| 179 |
|
| 180 |
+
# --- OMNI-CATEGORY SIZE CLASSIFIER AND PARSER ---
|
| 181 |
+
def parse_size_type_and_variants(size_str: str):
|
| 182 |
+
"""Identifies the explicit size category domain and outputs clean structural signatures for cross-matching"""
|
| 183 |
+
if not size_str:
|
| 184 |
+
return None, []
|
| 185 |
+
|
| 186 |
+
s = size_str.upper().strip()
|
| 187 |
+
|
| 188 |
+
# 1. Digital Memory Storage (PCs, Consoles, Phones, Components)
|
| 189 |
+
storage_match = re.search(r'(\d+)\s*(GB|TB)', s)
|
| 190 |
+
if storage_match:
|
| 191 |
+
val = int(storage_match.group(1))
|
| 192 |
+
unit = storage_match.group(2)
|
| 193 |
+
sig = f"{val}GB" if unit == "GB" else f"{val*1024}GB"
|
| 194 |
+
return "storage", [sig]
|
| 195 |
+
|
| 196 |
+
# 2. Volumetric Fluid Liquids (Fragrances, Liquids)
|
| 197 |
+
liquid_match = re.search(r'(\d+(?:\.\d+)?)\s*(?:FL\.?\s*)?(OZ|ML)', s)
|
| 198 |
+
if liquid_match:
|
| 199 |
+
num = float(liquid_match.group(1))
|
| 200 |
+
unit = liquid_match.group(2)
|
| 201 |
+
if unit in ["OZ", "FL"]:
|
| 202 |
+
if abs(num - 3.4) < 0.2: return "liquid", ["3.4OZ", "100ML"]
|
| 203 |
+
if abs(num - 1.7) < 0.2: return "liquid", ["1.7OZ", "50ML"]
|
| 204 |
+
if abs(num - 2.5) < 0.2: return "liquid", ["2.5OZ", "75ML"]
|
| 205 |
+
if abs(num - 4.2) < 0.2: return "liquid", ["4.2OZ", "125ML"]
|
| 206 |
+
if abs(num - 1.0) < 0.2: return "liquid", ["1.0OZ", "30ML"]
|
| 207 |
+
if abs(num - 6.7) < 0.3: return "liquid", ["6.7OZ", "200ML"]
|
| 208 |
+
return "liquid", [f"{num}OZ"]
|
| 209 |
+
else:
|
| 210 |
+
if abs(num - 100) < 6: return "liquid", ["3.4OZ", "100ML"]
|
| 211 |
+
if abs(num - 50) < 4: return "liquid", ["1.7OZ", "50ML"]
|
| 212 |
+
if abs(num - 75) < 5: return "liquid", ["2.5OZ", "75ML"]
|
| 213 |
+
if abs(num - 125) < 6: return "liquid", ["4.2OZ", "125ML"]
|
| 214 |
+
if abs(num - 30) < 3: return "liquid", ["1.0OZ", "30ML"]
|
| 215 |
+
if abs(num - 200) < 11: return "liquid", ["6.7OZ", "200ML"]
|
| 216 |
+
return "liquid", [f"{num}ML"]
|
| 217 |
+
|
| 218 |
+
# 3. Structural Clothing Standards
|
| 219 |
+
clothing_map = {
|
| 220 |
+
"XS": "XS", "EXTRA SMALL": "XS", "EXTRASMALL": "XS",
|
| 221 |
+
"S": "S", "SMALL": "S",
|
| 222 |
+
"M": "M", "MEDIUM": "M",
|
| 223 |
+
"L": "L", "LARGE": "L",
|
| 224 |
+
"XL": "XL", "X-LARGE": "XL", "EXTRALARGE": "XL",
|
| 225 |
+
"XXL": "2XL", "2XL": "2XL", "2X-LARGE": "2XL",
|
| 226 |
+
"3XL": "3XL", "3X-LARGE": "3XL", "XXXL": "3XL"
|
| 227 |
+
}
|
| 228 |
+
for k, v in clothing_map.items():
|
| 229 |
+
if f" {k} " in f" {s} " or s == k or s.replace("-", "") == k.replace(" ", ""):
|
| 230 |
+
return "clothing", [v]
|
| 231 |
+
|
| 232 |
+
# 4. Shoe Sizes or Pure Numeric Standalones
|
| 233 |
+
shoe_match = re.search(r'\b(?:SIZE|SZ|US|UK|EU)?\s*(\d+(?:\.5)?)\b', s)
|
| 234 |
+
if shoe_match:
|
| 235 |
+
return "numeric", [shoe_match.group(1)]
|
| 236 |
+
|
| 237 |
+
return "generic", [s.replace(" ", "")]
|
| 238 |
+
|
| 239 |
+
# --- UNIVERSAL COMPETING-SIZE MISMATCH ENGINE ---
|
| 240 |
+
def is_size_mismatched(target_size: str, parsed_text: str) -> bool:
|
| 241 |
+
"""Scans and rejects store pages listing alternate competing product configurations automatically"""
|
| 242 |
+
if not target_size or not parsed_text:
|
| 243 |
+
return False
|
| 244 |
+
|
| 245 |
+
category, target_variants = parse_size_type_and_variants(target_size)
|
| 246 |
+
if not category or not target_variants:
|
| 247 |
+
return False
|
| 248 |
+
|
| 249 |
+
text_upper = " " + parsed_text.upper() + " "
|
| 250 |
+
|
| 251 |
+
# 1. POSITIVE LAYER CROSS-CHECK: If our exact target variant is listed, pass it cleanly
|
| 252 |
+
for var in target_variants:
|
| 253 |
+
if category == "clothing":
|
| 254 |
+
if re.search(r'\b' + re.escape(var) + r'\b', text_upper): return False
|
| 255 |
+
elif category in ["storage", "liquid"]:
|
| 256 |
+
if var in text_upper.replace(" ", ""): return False
|
| 257 |
+
elif category == "numeric":
|
| 258 |
+
if re.search(r'\b(?:SIZE|SZ|US|UK|EU)?\s*' + re.escape(var) + r'\b', text_upper): return False
|
| 259 |
+
|
| 260 |
+
# 2. COMPETITOR SCAN LAYER: If not matched, look for conflicting size layouts of the same type
|
| 261 |
+
if category == "storage":
|
| 262 |
+
found_storage = re.findall(r'(\d+)\s*(GB|TB)', text_upper)
|
| 263 |
+
for val, unit in found_storage:
|
| 264 |
+
sig = f"{val}GB" if unit == "GB" else f"{val*1024}GB"
|
| 265 |
+
if sig not in target_variants:
|
| 266 |
+
return True
|
| 267 |
+
|
| 268 |
+
elif category == "liquid":
|
| 269 |
+
found_liquids = re.findall(r'(\d+(?:\.\d+)?)\s*(?:FL\.?\s*)?(OZ|ML)', text_upper)
|
| 270 |
+
for num, unit in found_liquids:
|
| 271 |
+
_, found_variants = parse_size_type_and_variants(f"{num} {unit}")
|
| 272 |
+
if found_variants and not any(fv in target_variants for fv in found_variants):
|
| 273 |
+
return True
|
| 274 |
+
|
| 275 |
+
elif category == "clothing":
|
| 276 |
+
clothing_words = ["XS", "SMALL", "MEDIUM", "LARGE", "XL", "XXL", "2XL", "3XL"]
|
| 277 |
+
for word in clothing_words:
|
| 278 |
+
_, f_vars = parse_size_type_and_variants(word)
|
| 279 |
+
if f_vars and f_vars[0] != target_variants[0]:
|
| 280 |
+
if re.search(r'\b' + re.escape(word) + r'\b', text_upper) or re.search(r'\b' + re.escape(f_vars[0]) + r'\b', text_upper):
|
| 281 |
+
return True
|
| 282 |
+
|
| 283 |
+
elif category == "numeric":
|
| 284 |
+
found_numbers = re.findall(r'\b(?:SIZE|SZ|US|UK|EU)?\s*(\d+(?:\.5)?)\b', text_upper)
|
| 285 |
+
for num in found_numbers:
|
| 286 |
+
if num not in target_variants:
|
| 287 |
+
return True
|
| 288 |
+
|
| 289 |
+
return False
|
| 290 |
+
|
| 291 |
+
# --- HEURISTIC UNIVERSAL SIZING EXTRACTION ENGINE FOR METADATA BADGES ---
|
| 292 |
def extract_universal_sizing(text: str) -> str:
|
| 293 |
+
"""Uses a normalized regex matrix to extract clean formatting standards for product layout rendering"""
|
| 294 |
if not text or len(text) > 100:
|
| 295 |
return ""
|
| 296 |
|
| 297 |
text_norm = " " + text.upper().strip() + " "
|
| 298 |
+
|
| 299 |
+
# 1. Digital Memory Storage
|
| 300 |
+
storage_match = re.search(r'(\d+)\s*(GB|TB)\b', text_norm)
|
| 301 |
+
if storage_match:
|
| 302 |
+
return f"{storage_match.group(1)} {storage_match.group(2)}"
|
| 303 |
+
|
| 304 |
+
# 2. Volumetric Fluids
|
| 305 |
+
dim_match = re.search(r'(\d+(?:\.\d+)?)\s*(?:FL\.?\s*)?(OZ|ML)\b', text_norm)
|
| 306 |
if dim_match:
|
| 307 |
+
return f"{dim_match.group(1)} {dim_match.group(2)}"
|
|
|
|
|
|
|
| 308 |
|
| 309 |
+
# 3. Clothing
|
| 310 |
if "EXTRA LARGE" in text_norm or "X-LARGE" in text_norm: return "XL"
|
| 311 |
if "LARGE" in text_norm: return "L"
|
| 312 |
if "MEDIUM" in text_norm: return "M"
|
| 313 |
if "SMALL" in text_norm: return "S"
|
|
|
|
| 314 |
clothing_match = re.search(r'\b(XS|S|M|L|XL|2XL|XXL|3XL|4XL)\b', text_norm)
|
| 315 |
+
if clothing_match: return clothing_match.group(1)
|
|
|
|
| 316 |
|
| 317 |
+
# 4. Footwear Shoes
|
| 318 |
+
shoe_match = re.search(r'\b(?:SIZE|SZ|US|UK|EU)?\s*(\d+(?:\.5)?)\b', text_norm)
|
| 319 |
+
if shoe_match: return shoe_match.group(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
|
| 321 |
return text.strip()
|
| 322 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
# --- GOOGLE URL REDIRECT UNWRAPPER ENGINE ---
|
| 324 |
def clean_google_link(url: str) -> str:
|
| 325 |
"""Extracts raw outbound seller targets from Google tracking wrappers safely"""
|
|
|
|
| 436 |
if response.status_code == 200:
|
| 437 |
data = response.json()
|
| 438 |
formatted_deals = []
|
|
|
|
| 439 |
|
| 440 |
for item in data.get("shopping_results", []):
|
| 441 |
title = item.get("title", "")
|
| 442 |
snippet = item.get("snippet", "")
|
| 443 |
combined_text = f"{title} {snippet}"
|
| 444 |
|
|
|
|
| 445 |
if mode == "exact":
|
| 446 |
title_clean = title.lower()
|
| 447 |
+
req_tokens = [t for t in product_name.lower().split() if t not in ["buy", "cheap", "online", "sale", "price"] and len(t) >= 2]
|
| 448 |
if not all(token in title_clean for token in req_tokens):
|
| 449 |
continue
|
| 450 |
+
if desired_size and is_size_mismatched(desired_size, combined_text):
|
| 451 |
continue
|
| 452 |
elif mode == "balanced":
|
| 453 |
+
if desired_size and is_size_mismatched(desired_size, combined_text):
|
| 454 |
continue
|
| 455 |
|
| 456 |
price_val = item.get("extracted_price")
|
|
|
|
| 459 |
|
| 460 |
if price_val and link:
|
| 461 |
formatted_deals.append({
|
| 462 |
+
"title": title,
|
| 463 |
"url": link,
|
| 464 |
"price": round(float(price_val), 2),
|
| 465 |
"image": item.get("thumbnail"),
|
|
|
|
| 661 |
if source_page:
|
| 662 |
det_size = extract_universal_sizing(report.get('size')) or report.get('size') or desired_size or "Standard"
|
| 663 |
|
|
|
|
| 664 |
if mode == "exact" and desired_size:
|
| 665 |
if is_size_mismatched(desired_size, det_size):
|
| 666 |
continue
|
| 667 |
|
| 668 |
results.append({
|
| 669 |
+
"title": product_name,
|
| 670 |
"url": source_page['url'],
|
| 671 |
"price": round(float(report['price']), 2),
|
| 672 |
"image": source_page['image'],
|
|
|
|
| 682 |
report = parse_price_locally(page['text'], product_name)
|
| 683 |
if report["found"]:
|
| 684 |
results.append({
|
| 685 |
+
"title": product_name,
|
| 686 |
"url": page['url'],
|
| 687 |
"price": report["price"],
|
| 688 |
"image": page['image'],
|
|
|
|
| 699 |
|
| 700 |
vetted_safe_deals = [item for item, is_secure in zip(combined_output, security_mask) if is_secure]
|
| 701 |
|
|
|
|
| 702 |
if mode == "exact" and desired_size:
|
| 703 |
vetted_safe_deals = [item for item in vetted_safe_deals if not is_size_mismatched(desired_size, item.get('size', ''))]
|
| 704 |
|
|
|
|
| 764 |
button:hover {{ transform: translateY(-1px); box-shadow: 0 6px 16px rgba(59, 130, 246, 0.3); }}
|
| 765 |
|
| 766 |
ul {{ list-style-type: none; padding: 0; margin: 0; }}
|
| 767 |
+
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; }}
|
| 768 |
li:hover {{ border-color: rgba(255, 255, 255, 0.15); background: rgba(255, 255, 255, 0.04); }}
|
| 769 |
|
| 770 |
.deal-item-header {{ display: flex; align-items: center; justify-content: space-between; width: 100%; gap: 16px; }}
|
|
|
|
| 843 |
</div>
|
| 844 |
<div class="input-group size-group">
|
| 845 |
<label>Size / Variant</label>
|
| 846 |
+
<input type="text" name="product_size" value="{prev_size}" placeholder="e.g., 3.4 oz, 512 GB, XL, 10.5" autocomplete="off">
|
| 847 |
</div>
|
| 848 |
<div class="input-group mode-group">
|
| 849 |
<label>Search Strategy</label>
|
|
|
|
| 890 |
if not HF_TOKEN:
|
| 891 |
return generate_ui(error_msg="Please add a valid HF_TOKEN into Space Secrets to activate the free AI models.")
|
| 892 |
|
| 893 |
+
original_name_input = product_name
|
| 894 |
+
original_size_input = product_size or ""
|
| 895 |
raw_input = product_name.strip()
|
| 896 |
+
|
|
|
|
| 897 |
force_refresh = raw_input.endswith("*")
|
| 898 |
if force_refresh:
|
| 899 |
+
raw_input = raw_input.rstrip("*").strip()
|
| 900 |
+
print(f"⚡ [Force Refresh] Evicting active cache entries for query mapping context: '{raw_input}'")
|
| 901 |
+
|
| 902 |
+
extracted_size_from_name = extract_universal_sizing(raw_input)
|
| 903 |
+
if original_size_input:
|
| 904 |
+
requested_size = extract_universal_sizing(original_size_input)
|
| 905 |
+
else:
|
| 906 |
+
requested_size = extracted_size_from_name
|
| 907 |
+
|
| 908 |
+
if not original_size_input and extracted_size_from_name:
|
| 909 |
+
patterns_to_strip = [
|
| 910 |
+
r'(\d+(?:\.\d+)?)\s*(?:FL\.?\s*)?(OZ|ML|GB|TB)\b',
|
| 911 |
+
r'\b(EXTRA\s*LARGE|X-LARGE|LARGE|MEDIUM|SMALL)\b',
|
| 912 |
+
r'\b(XS|S|M|L|XL|2XL|XXL|3XL|4XL)\b',
|
| 913 |
+
r'\b(?:SIZE|SZ|US|UK|EU)?\s*(\d+(?:\.5)?)\b'
|
| 914 |
+
]
|
| 915 |
+
target_item = raw_input
|
| 916 |
+
for pattern in patterns_to_strip:
|
| 917 |
+
target_item = re.sub(pattern, "", target_item, flags=re.IGNORECASE).strip()
|
| 918 |
+
target_item = " ".join(target_item.split())
|
| 919 |
else:
|
| 920 |
target_item = raw_input
|
| 921 |
|
|
|
|
| 931 |
|
| 932 |
async with httpx.AsyncClient(trust_env=False) as safety_client:
|
| 933 |
if not await check_url_safe(input_url, safety_client):
|
| 934 |
+
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)
|
| 935 |
|
| 936 |
raw_text, img_url = extract_page_data(input_url, "product")
|
| 937 |
if not raw_text:
|
| 938 |
+
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)
|
| 939 |
|
| 940 |
try:
|
| 941 |
url_prompt = f"""
|
|
|
|
| 955 |
requested_size = extract_universal_sizing(url_data.get('size'))
|
| 956 |
|
| 957 |
original_site_deal = {
|
| 958 |
+
"title": target_item,
|
| 959 |
"url": input_url,
|
| 960 |
"price": round(float(url_data['price']), 2),
|
| 961 |
"image": img_url,
|
|
|
|
| 968 |
if local_report["found"]:
|
| 969 |
target_item = "Extracted Product Deal"
|
| 970 |
original_site_deal = {
|
| 971 |
+
"title": "Extracted Product Deal",
|
| 972 |
"url": input_url,
|
| 973 |
"price": local_report["price"],
|
| 974 |
"image": img_url,
|
|
|
|
| 976 |
"size": requested_size or "Standard"
|
| 977 |
}
|
| 978 |
else:
|
| 979 |
+
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)
|
| 980 |
|
| 981 |
if not original_site_deal:
|
| 982 |
+
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)
|
| 983 |
except Exception as e:
|
| 984 |
print(f"❌ [Link Analytics Error] Failure processing link data parsing: {e}")
|
| 985 |
+
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)
|
| 986 |
|
| 987 |
cached_deals = None if force_refresh else get_cached_deals(target_item, requested_size, search_mode)
|
| 988 |
cached_coupons = None if force_refresh else get_cached_coupons(target_item)
|
|
|
|
| 1013 |
results_html = f"""
|
| 1014 |
<div class="card" style="border-color: #ef4444;">
|
| 1015 |
<h3>Query: <i>{target_item}{size_header}</i></h3>
|
| 1016 |
+
<p style="color: var(--text-muted); margin: 0;">⚠️ No verifiable pricing matrices were found matching this selection criteria.</p>
|
| 1017 |
</div>
|
| 1018 |
"""
|
| 1019 |
else:
|
|
|
|
| 1062 |
"""
|
| 1063 |
|
| 1064 |
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 ""
|
| 1065 |
+
display_title = deal.get('title') or target_item
|
| 1066 |
|
| 1067 |
results_list += f"""
|
| 1068 |
<li class="deal-item">
|
| 1069 |
<div class="deal-item-header">
|
| 1070 |
<img src="{img_src}" class="product-img" onerror="this.src='{fallback_img}'" />
|
| 1071 |
<div class="deal-info">
|
| 1072 |
+
<span class="item-title">{display_title}</span>
|
| 1073 |
<div class="meta-container">
|
| 1074 |
<span class="domain-badge">{domain}</span>
|
| 1075 |
<span class="size-badge">{deal.get('size', 'Standard')}</span>
|
|
|
|
| 1122 |
</div>
|
| 1123 |
"""
|
| 1124 |
|
| 1125 |
+
return generate_ui(results_html=results_html, prev_name=original_name_input, prev_size=original_size_input, prev_mode=search_mode)
|
| 1126 |
|
| 1127 |
if __name__ == "__main__":
|
| 1128 |
import uvicorn
|