import json import asyncio import httpx import random import urllib.parse import re from datetime import datetime from bs4 import BeautifulSoup from config import hf_client, MODEL_ID, HF_TOKEN, USER_AGENTS, DDG_SEMAPHORE def _extract_brand_context(product_name: str) -> str: """Helper to extract the presumptive brand/manufacturer noun to catch store-wide promos""" clean = re.sub(r'(?i)\b(men\'s|women\'s|kids\'|unisex|size|with|for|perfume|eau de|edp|edt|shorts|shoes|t-shirt|pants|jacket)\b', '', product_name) tokens = clean.strip().split() if len(tokens) >= 2: # Take the first two prominent nouns as the brand core (e.g., "Lattafa Fakhar" or "Creed") return f"{tokens[0]} {tokens[1]}" elif len(tokens) == 1: return tokens[0] return product_name async def _gather_snippets_from_query(search_query: str, client: httpx.AsyncClient) -> list: """Safely executes a single DuckDuckGo HTML context capture sweep under the instance throttle""" url = f"https://html.duckduckgo.com/html/?q={urllib.parse.quote(search_query)}" headers = {"User-Agent": random.choice(USER_AGENTS)} snippets = [] async with DDG_SEMAPHORE: try: await asyncio.sleep(random.uniform(0.5, 1.0)) # Polite spacing interval print(f"📡 [Deal Scraper] Scraping source nodes for: '{search_query}'") res = await client.get(url, headers=headers, timeout=7.0) if res.status_code == 200: soup = BeautifulSoup(res.text, 'html.parser') results = soup.find_all('div', class_='result') for item in results[:6]: snippet_tag = item.find('a', class_='result__snippet') if snippet_tag: text = snippet_tag.get_text().strip() if text: snippets.append(text) elif res.status_code == 429: print(f"⚠️ [Rate Alert] Scraper Engine choked (429) on query: '{search_query}'") except Exception as e: print(f"⚠️ [Scraper Exception] Failed fetching snippets for '{search_query}': {e}") return snippets def call_free_llm(prompt: str, max_tokens: int = 600) -> str: """Queries open-source models via conversational formatting layers""" if not HF_TOKEN: raise Exception("Hugging Face API Access Token (HF_TOKEN) is missing.") system_instructions = "You are an elite e-commerce verification tool. Run strict heuristics on text blocks to distill valid retail deals, clearances, and variation-specific markdowns. Output RAW JSON ONLY matching requested format. No markdown syntax wrappers, no preamble text." try: output = hf_client.chat_completion( model=MODEL_ID, messages=[{"role": "system", "content": system_instructions}, {"role": "user", "content": prompt}], max_tokens=max_tokens, temperature=0.1 ) content = output.choices[0].message.content.strip() triple_backtick = "`" * 3 content = content.replace(f"{triple_backtick}json", "").replace(triple_backtick, "").strip() return content except Exception as e: print(f"❌ [LLM Error] {e}") return "[]" async def fetch_active_deals(product_name: str, client: httpx.AsyncClient) -> list: """Assembles multi-vector price drop indicators concurrently and parses active variation-specific deals""" brand_context = _extract_brand_context(product_name) current_date_str = datetime.now().strftime("%B %Y") # Triple-vector search targeting localized product markdowns, macro-brand clearances, and variant variations query_a = f"{product_name} sale clearance price drop deals" query_b = f"{brand_context} retail discounts promotions {current_date_str}" query_c = f"{product_name} markdown colors variations size stock pricing" results_a, results_b, results_c = await asyncio.gather( _gather_snippets_from_query(query_a, client), _gather_snippets_from_query(query_b, client), _gather_snippets_from_query(query_c, client) ) # Merge and deduplicate textual block collections combined_snippets = list(set(results_a + results_b + results_c)) if not combined_snippets: return [] payload_text = "\n".join([f"[{idx}]: {s}" for idx, s in enumerate(combined_snippets)]) prompt = f""" Analyze the following web search snippets containing retail price markdown, store clearances, and active price drops. Your goal is to extract genuine, high-veracity retail deals and specific variation markdowns (e.g., where a specific color, size, or model has a targeted reduction). Target Product Context: "{product_name}" Target Brand Context: "{brand_context}" Current Verification Window: {current_date_str} STRICT EXTRACTION HEURISTICS: 1. ASSIGNMENT & VARIANT ACCURACY: Check closely for variant discrepancies. If a specific option (e.g., 'Red', 'Size 10', 'Wi-Fi Model') is flagged with a price cut that other variations lack, cleanly capture that variant constraint. 2. CATEGORY CLASSIFICATION: Identify the deal structure into one of these strict buckets: - 'clearance': For end-of-season, closeouts, or inventory liquidations. - 'price_drop': For targeted, temporary, or permanent retail price cuts. - 'sale': For standard promotions, holiday events, or sitewide retail reductions. 3. TIMELINE VALIDATION: Ensure the deal data is active and currently valid for {current_date_str}. Explicitly discard markdowns explicitly flagged in text snippets as "ended", "expired", or tied to past seasons. 4. DISCARD GENERIC AFFILIATE CLICKBAIT: Discard phrases that are purely vague affiliate hooks ("Click for best deal", "Lowest price guaranteed") without citing a hard reduction structure, specific markdown percentage, or concrete clearance rule. 5. ABSOLUTE NEGATIVE CONSTRAINT: DO NOT return example text placeholder values. If no genuine retail sale or variant drop is visible, output an empty array: `[]`. Output ONLY a raw, valid JSON array of objects using the template structure below. Do not include markdown wraps or code block markers. [ {{ "deal_type": "clearance" or "price_drop" or "sale", "applicable_variant": "Specific color/size/model if limited to a variant, otherwise 'All'", "description": "Percentage/dollar off value, clearance final pricing, or exact variant constraints", "source": "Identifiable Store Name or Brand" }} ] Snippets Pool to Parse: {payload_text} """ try: ai_res = call_free_llm(prompt, max_tokens=500) deals = json.loads(ai_res) if isinstance(deals, list): clean_deals = [] for d in deals: deal_type = str(d.get('deal_type', 'sale')).strip().lower() variant_val = str(d.get('applicable_variant', 'All')).strip() desc_val = str(d.get('description', '')).strip() source_val = str(d.get('source', '')).strip() # Sanitize deal type fallbacks if deal_type not in ["clearance", "price_drop", "sale"]: deal_type = "sale" # Filter out lazy clickbait affiliate phrases or empty descriptions if "click" in desc_val.lower() and len(desc_val) < 15: continue if desc_val and desc_val.upper() not in {"PLACEHOLDER", "N/A"}: clean_deals.append({ "deal_type": deal_type, "applicable_variant": variant_val, "description": desc_val, "source": source_val if source_val else "Retailer" }) return clean_deals except Exception as e: print(f"⚠️ [Parsing Exception] Deal distillation breakdown: {e}") return [] async def fetch_deals_standalone(target_item: str) -> list: """Invokes isolation wrappers around keyless HTTP client structures safely""" limits = httpx.Limits(max_keepalive_connections=2, max_connections=4) async with httpx.AsyncClient(limits=limits, http2=False, trust_env=False) as client: return await fetch_active_deals(target_item, client)