Spaces:
Sleeping
Sleeping
Download main.py from ghstedpixel/app.py: direct link, hf CLI and curl.
- Browser
- Download file 16.2 kB
-
https://huggingface.co/spaces/ghstedpixel/app.py/resolve/4fa2fd90c00a78d4e4e68ccd489221ffc5d7362b/main.py
- Command line
-
hf download hf://spaces/ghstedpixel/app.py@4fa2fd90c00a78d4e4e68ccd489221ffc5d7362b/main.py
-
curl -L -o main.py https://huggingface.co/spaces/ghstedpixel/app.py/resolve/4fa2fd90c00a78d4e4e68ccd489221ffc5d7362b/main.py
16.2 kB
| import json | |
| import re | |
| import httpx | |
| import uvicorn | |
| import asyncio | |
| from urllib.parse import urlparse | |
| from fastapi import FastAPI, Request, Form | |
| from fastapi.responses import HTMLResponse | |
| 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 | |
| ) | |
| 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_coupons_standalone | |
| from shopping import scan_prices | |
| from ui import generate_ui | |
| app = FastAPI() | |
| def dashboard(): | |
| return generate_ui() | |
| async def handle_search( | |
| product_name: str = Form(...), | |
| product_size: str = Form(None), | |
| search_mode: str = Form("balanced"), | |
| product_gender: str = Form("unisex") | |
| ): | |
| if not HF_TOKEN: | |
| return generate_ui(error_msg="Please add a valid HF_TOKEN into Space Secrets to activate the free AI models.") | |
| 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 | |
| fallback_img = "https://placehold.co/100x100/1a1c28/9fa4b4?text=IMG" | |
| 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): | |
| 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, prev_gender=product_gender) | |
| raw_text, img_url = await extract_page_data(input_url, "product") | |
| if not raw_text: | |
| 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, prev_gender=product_gender) | |
| 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": 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": input_url, | |
| "price": local_report["price"], | |
| "image": img_url, | |
| "source": urlparse(input_url).netloc.replace("www.", ""), | |
| "size": requested_size or "Standard" | |
| } | |
| else: | |
| 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, prev_gender=product_gender) | |
| if not original_site_deal: | |
| 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, prev_gender=product_gender) | |
| except Exception as e: | |
| print(f"❌ [Link Analytics Error] Failure processing link data parsing: {e}") | |
| 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, prev_gender=product_gender) | |
| 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 & coupons...") | |
| deals, coupons = await asyncio.gather( | |
| scan_prices(target_item, requested_size, search_mode), | |
| fetch_coupons_standalone(target_item) | |
| ) | |
| if original_site_deal: | |
| if not any(d['url'] == original_site_deal['url'] for d in deals): deals.append(original_site_deal) | |
| if deals: | |
| deals.sort(key=lambda x: x['price']) | |
| current_lowest = deals[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 | |
| deals[0]['price_delta'] = round(delta, 2) | |
| set_base_price(target_item, requested_size, search_mode, current_lowest) | |
| elif base_price == current_lowest: | |
| deals[0]['price_delta'] = 0.0 | |
| else: | |
| set_base_price(target_item, requested_size, search_mode, current_lowest) | |
| deals[0]['price_delta'] = 0.0 | |
| set_cached_deals(target_item, requested_size, search_mode, deals) | |
| if coupons is not None: set_cached_coupons(target_item, coupons) | |
| size_header = f" ({requested_size})" if requested_size else "" | |
| if not deals: | |
| print("⚠️ [Finished Execution] Matrix build completed with 0 valid results.") | |
| results_html = f""" | |
| <div class="card" style="border-color: #ef4444;"> | |
| <h3>Query: <i>{target_item}{size_header}</i></h3> | |
| <p style="color: var(--text-muted); margin: 0;">⚠️ No verifiable pricing matrices were found matching this selection criteria.</p> | |
| </div> | |
| """ | |
| else: | |
| print(f"🎉 [Finished Execution] Successfully built pricing matrix with {len(deals)} results.") | |
| def render_deal_row(idx, deal): | |
| img_src = deal['image'] if deal['image'] else fallback_img | |
| domain = deal.get('source') or "link" | |
| if "google.com" not in deal['url']: | |
| try: domain = urlparse(deal['url']).netloc.replace("www.", "") | |
| except: pass | |
| matched_coupon_html = "" | |
| for coupon in coupons: | |
| coupon_source = coupon.get('source', '').lower() | |
| if coupon_source and (coupon_source in domain.lower() or coupon_source in (deal.get('source') or "").lower()): | |
| matched_coupon_html += f""" | |
| <div class="inline-coupon"> | |
| <div style="min-width: 0;"> | |
| <span style="color: var(--accent-gold); font-weight: 700; font-family: monospace; font-size: 11px; background: rgba(245, 158, 11, 0.1); padding: 2px 6px; border-radius: 4px; border: 1px dashed rgba(245, 158, 11, 0.3); text-transform: uppercase;">{coupon['code']}</span> | |
| <span style="color: #e5e7eb; margin-left: 6px; font-size: 12px;">{coupon['description']}</span> | |
| </div> | |
| </div> | |
| """ | |
| best_value_badge = "" | |
| if idx == 0: | |
| best_value_badge = """ | |
| <span class="value-badge best-value"> | |
| <svg class="icon" style="width:12px; height:12px;" viewBox="0 0 24 24"><path d="M12 23l-1.45-1.32C5.4 16.25 2 13.17 2 9.5 2 6.5 4.5 4 7.5 4c1.74 0 3.41.81 4.5 2.09C13.09 4.81 14.76 4 16.5 4 19.5 4 22 6.5 22 9.5c0 3.67-3.4 6.75-8.55 12.18L12 23z"/></svg> | |
| Best Value | |
| </span> | |
| """ | |
| verified_badge = "" | |
| if deal.get('source'): | |
| verified_badge = """ | |
| <span class="value-badge verified-retailer"> | |
| <svg class="icon" style="width:12px; height:12px;" viewBox="0 0 24 24"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg> | |
| Verified | |
| </span> | |
| """ | |
| rating_html = "" | |
| if deal.get('rating'): | |
| rating_val = deal['rating'] | |
| reviews_count = deal.get('reviews') or 0 | |
| reviews_text = f" ({int(reviews_count)})" if reviews_count else "" | |
| rating_html = f""" | |
| <span class="rating-badge"> | |
| <svg class="icon" style="width:11px; height:11px; color:var(--accent-gold); fill:currentColor;" viewBox="0 0 24 24"><path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/></svg> | |
| {rating_val}{reviews_text} | |
| </span> | |
| """ | |
| 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 "" | |
| display_title = deal.get('title') or target_item | |
| trend_html = "" | |
| if idx == 0 and deal.get('price_delta') is not None and deal['price_delta'] != 0.0: | |
| delta_val = deal['price_delta'] | |
| if delta_val < 0: | |
| trend_html = f'<span class="trend-indicator down">- $ {abs(delta_val):.2f}</span>' | |
| else: | |
| trend_html = f'<span class="trend-indicator up">+ $ {delta_val:.2f}</span>' | |
| return f""" | |
| <li class="deal-item"> | |
| <div class="deal-item-header"> | |
| <img src="{img_src}" class="product-img" onerror="this.src='{fallback_img}'" /> | |
| <div class="deal-info"> | |
| <span class="item-title">{display_title}</span> | |
| <div class="meta-container"> | |
| <span class="domain-badge">{domain}</span> | |
| <span class="size-badge">{deal.get('size', 'Standard')}</span> | |
| {rating_html} | |
| {best_value_badge} | |
| {verified_badge} | |
| <a href="{deal['url']}" target="_blank" class="small-link">{deal['url']}</a> | |
| {is_ref} | |
| </div> | |
| </div> | |
| <div style="display: flex; flex-direction: column; align-items: flex-end;"> | |
| <span class="price-tag"> | |
| <a href="{deal['url']}" target="_blank">${deal['price']:.2f}</a> | |
| </span> | |
| {trend_html} | |
| </div> | |
| </div> | |
| {matched_coupon_html} | |
| </li> | |
| """ | |
| top_results_list = "" | |
| for i, d in enumerate(deals[:10]): top_results_list += render_deal_row(i, d) | |
| additional_dropdown_html = "" | |
| if len(deals) > 10: | |
| extra_rows = "" | |
| for i, d in enumerate(deals[10:20], start=10): extra_rows += render_deal_row(i, d) | |
| additional_dropdown_html = f""" | |
| <details> | |
| <summary> | |
| <svg class="icon" viewBox="0 0 24 24" style="width:14px; height:14px;"><path d="M7 10l5 5 5-5z"/></svg> | |
| View Additional Pricing Options (+{len(deals) - 10} more variants found) | |
| </summary> | |
| <ul style="margin-top: 15px;"> | |
| {extra_rows} | |
| </ul> | |
| </details> | |
| """ | |
| results_html = f""" | |
| <div class="card" style="border-color: var(--accent-green);"> | |
| <h3>Results Matrix for: <span style="color: var(--accent-blue); margin-left: 4px;"><b>{target_item}{size_header}</b></span></h3> | |
| <p style="color:var(--accent-green); font-weight:600; margin-top:-10px; font-size:15px; margin-bottom: 20px;">🏆 Lowest verified online price: ${deals[0]['price']:.2f}</p> | |
| <ul style="margin-top: 15px;">{top_results_list}</ul> | |
| {additional_dropdown_html} | |
| </div> | |
| """ | |
| return generate_ui(results_html=results_html, prev_name=original_name_input, prev_size=original_size_input, prev_mode=search_mode, prev_gender=product_gender) | |
| if __name__ == "__main__": | |
| uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True) |