app.py / schema.py
ghstedpixel's picture
Update schema.py
bc8cdbb verified
Raw History Blame Contribute Delete
9.23 kB
import re
from urllib.parse import urlparse, parse_qs, unquote
def parse_size_type_and_variants(size_str: str):
"""Identifies the explicit size category domain and outputs clean structural signatures for cross-matching"""
if not size_str: return None, []
s = size_str.upper().strip()
storage_match = re.search(r'(\d+)\s*(GB|TB)', s)
if storage_match:
val = int(storage_match.group(1))
unit = storage_match.group(2)
sig = f"{val}GB" if unit == "GB" else f"{val*1024}GB"
return "storage", [sig]
liquid_match = re.search(r'(\d+(?:\.\d+)?)\s*(?:FL\.?\s*)?(OZ|ML)', s)
if liquid_match:
num = float(liquid_match.group(1))
unit = liquid_match.group(2)
if unit in ["OZ", "FL"]:
if abs(num - 3.4) < 0.2: return "liquid", ["3.4OZ", "100ML"]
if abs(num - 1.7) < 0.2: return "liquid", ["1.7OZ", "50ML"]
if abs(num - 2.5) < 0.2: return "liquid", ["2.5OZ", "75ML"]
if abs(num - 4.2) < 0.2: return "liquid", ["4.2OZ", "125ML"]
if abs(num - 1.0) < 0.2: return "liquid", ["3.0OZ", "30ML"]
if abs(num - 6.7) < 0.3: return "liquid", ["6.7OZ", "200ML"]
return "liquid", [f"{num}OZ"]
else:
if abs(num - 100) < 6: return "liquid", ["3.4OZ", "100ML"]
if abs(num - 50) < 4: return "liquid", ["1.7OZ", "50ML"]
if abs(num - 75) < 5: return "liquid", ["2.5OZ", "75ML"]
if abs(num - 125) < 6: return "liquid", ["4.2OZ", "125ML"]
if abs(num - 30) < 3: return "liquid", ["1.0OZ", "30ML"]
if abs(num - 200) < 11: return "liquid", ["6.7OZ", "200ML"]
return "liquid", [f"{num}ML"]
clothing_map = {
"XS": "XS", "EXTRA SMALL": "XS", "EXTRASMALL": "XS",
"S": "S", "SMALL": "S", "M": "M", "MEDIUM": "M", "L": "L", "LARGE": "L",
"XL": "XL", "X-LARGE": "XL", "EXTRALARGE": "XL",
"XXL": "2XL", "2XL": "2XL", "2X-LARGE": "2XL",
"3XL": "3XL", "3X-LARGE": "3XL", "XXXL": "3XL"
}
for k, v in clothing_map.items():
if f" {k} " in f" {s} " or s == k or s.replace("-", "") == k.replace(" ", ""): return "clothing", [v]
shoe_match = re.search(r'\b(?:SIZE|SZ|US|UK|EU)?\s*(\d+(?:\.5)?)\b', s)
if shoe_match: return "numeric", [shoe_match.group(1)]
return "generic", [s.replace(" ", "")]
def is_size_mismatched(target_size: str, parsed_text: str) -> bool:
"""Scans and rejects store pages listing alternate competing product configurations automatically"""
if not target_size or not parsed_text: return False
category, target_variants = parse_size_type_and_variants(target_size)
if not category or not target_variants: return False
text_upper = " " + parsed_text.upper() + " "
for var in target_variants:
if category == "clothing":
if re.search(r'\b' + re.escape(var) + r'\b', text_upper): return False
elif category in ["storage", "liquid"]:
if var in text_upper.replace(" ", ""): return False
elif category == "numeric":
if re.search(r'\b(?:SIZE|SZ|US|UK|EU)?\s*' + re.escape(var) + r'\b', text_upper): return False
if category == "storage":
found_storage = re.findall(r'(\d+)\s*(GB|TB)', text_upper)
for val, unit in found_storage:
sig = f"{val}GB" if unit == "GB" else f"{val*1024}GB"
if sig not in target_variants: return True
elif category == "liquid":
found_liquids = re.findall(r'(\d+(?:\.\d+)?)\s*(?:FL\.?\s*)?(OZ|ML)', text_upper)
for num, unit in found_liquids:
_, found_variants = parse_size_type_and_variants(f"{num} {unit}")
if found_variants and not any(fv in target_variants for fv in found_variants): return True
elif category == "clothing":
clothing_words = ["XS", "SMALL", "MEDIUM", "LARGE", "XL", "XXL", "2XL", "3XL"]
for word in clothing_words:
_, f_vars = parse_size_type_and_variants(word)
if f_vars and f_vars[0] != target_variants[0]:
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): return True
elif category == "numeric":
found_numbers = re.findall(r'\b(?:SIZE|SZ|US|UK|EU)?\s*(\d+(?:\.5)?)\b', text_upper)
for num in found_numbers:
if num not in target_variants: return True
return False
def extract_universal_sizing(text: str) -> str:
"""Uses a normalized regex matrix to extract clean formatting standards for product layout rendering"""
if not text or len(text) > 100: return ""
text_cleaned = re.sub(r"['’]S\b", "", text.upper())
text_norm = " " + text_cleaned.strip() + " "
storage_match = re.search(r'(\d+)\s*(GB|TB)\b', text_norm)
if storage_match: return f"{storage_match.group(1)} {storage_match.group(2)}"
dim_match = re.search(r'(\d+(?:\.\d+)?)\s*(?:FL\.?\s*)?(OZ|ML)\b', text_norm)
if dim_match: return f"{dim_match.group(1)} {dim_match.group(2)}"
if "EXTRA LARGE" in text_norm or "X-LARGE" in text_norm: return "XL"
if "LARGE" in text_norm: return "L"
if "MEDIUM" in text_norm: return "M"
if "SMALL" in text_norm: return "S"
clothing_match = re.search(r'\b(XS|S|M|L|XL|2XL|XXL|3XL|4XL)\b', text_norm)
if clothing_match: return clothing_match.group(1)
shoe_match = re.search(r'\b(?:SIZE|SZ|US|UK|EU)?\s*(\d+(?:\.5)?)\b', text_norm)
if shoe_match: return shoe_match.group(1)
return ""
def clean_google_link(url: str) -> str:
"""
Aggressively strips tracking redirects from both google.com and googleadservices.com,
instantly routing users to the direct outbound merchant hosting the product.
"""
if not url:
return ""
# Catch both organic shopping gates and paid ad service redirects
if "google.com" not in url and "googleadservices.com" not in url:
return url
try:
# Step 1: Recursively unquote to clear multi-layered encoding tricks (%2F, %3A, etc.)
decoded_link = unquote(url)
while "%" in decoded_link:
prev_link = decoded_link
decoded_link = unquote(decoded_link)
if prev_link == decoded_link:
break
# Step 2: Query parameter interception gate
parsed_url = urlparse(decoded_link)
qs = parse_qs(parsed_url.query)
# 'adurl' handles googleadservices/aclk ads; 'url'/'q' handle organic redirects
for redirect_param in ['adurl', 'url', 'q', 'link', 'shopping_redirect', 'destination']:
if redirect_param in qs:
target_url = qs[redirect_param][0].strip()
if target_url.startswith(("http://", "https://")):
return target_url
# Step 3: Global Heuristic Regex Fallback
# Extract any raw embedded HTTP/HTTPS url that skips Google's tracking ecosystem entirely
found_urls = re.findall(r'(https?://[^\s&"\'<>]+)', decoded_link)
for sub_url in found_urls:
if "google.com" not in sub_url and "googleadservices.com" not in sub_url:
if "?" in sub_url:
base_part, query_part = sub_url.split("?", 1)
# Strip downstream marketing bloat tags clean
query_part = re.sub(r'&?(gclid|gclsrc|utm_[^&=]+|affp|affiliate)[^&]*', '', query_part, flags=re.IGNORECASE)
sub_url = f"{base_part}?{query_part}".rstrip('?').rstrip('&')
return sub_url
except Exception as e:
print(f"⚠️ [Link Extractor Error] Could not unwrap target metadata: {e}")
return url
def parse_price_locally(dense_text, product_name):
"""Programmatic textual parsing engine to extract valid retail pricing while isolating shipping costs and spoof values"""
print("⚙️ [Local Solver] Running regex matrix heuristic extraction on text payload...")
prices = []
tokens = dense_text.split(" | ")
keywords = [k.lower() for k in product_name.split() if len(k) > 2]
invalid_context_markers = ["shipping", "save", "off", "reduced", "per month", "/mo", "discount", "coupon"]
for token in tokens:
token_clean = token.lower()
if any(k in token_clean for k in keywords):
if any(marker in token_clean for marker in invalid_context_markers): continue
matches = re.findall(r'\$\s*([\d,]+(?:\.\d{2})?)', token)
for m in matches:
try:
clean_m = m.replace(',', '')
price_val = float(clean_m)
if 1.0 < price_val < 9000.0 and price_val not in [1.7, 3.3, 5.0, 6.8, 16.5, 18.0]: prices.append(price_val)
except: continue
if prices:
lowest_extracted = min(prices)
print(f"🎯 [Local Solver Success] Located valid competitive target minimum: ${lowest_extracted}")
return {"price": lowest_extracted, "found": True}
return {"price": None, "found": False}