File size: 17,336 Bytes
c0d39e3
 
 
 
8d61cdb
0516f8f
618bff8
ac1d270
c0d39e3
 
dfe0cf8
c0d39e3
4ad8ded
 
 
c0d39e3
 
dfe0cf8
 
c0d39e3
9bcf065
4ad8ded
cbdf18c
4ad8ded
 
1199ce9
6bc5dbb
 
c0d39e3
 
0516f8f
 
dfe0cf8
1f1b7ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfe0cf8
 
f82c018
dfe0cf8
 
 
c0d39e3
dfe0cf8
 
 
d62832c
 
 
dfe0cf8
 
 
 
 
 
 
6bc5dbb
 
 
dfe0cf8
 
c0d39e3
 
 
dfe0cf8
c0d39e3
 
 
 
 
dfe0cf8
 
 
 
 
 
 
 
 
6bc5dbb
 
 
dfe0cf8
 
c0d39e3
dfe0cf8
d62832c
c0d39e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caba5fb
c0d39e3
 
 
 
 
 
dfe0cf8
d62832c
c0d39e3
 
 
dfe0cf8
d62832c
c0d39e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1277fc8
c0d39e3
 
1f1b7ad
c0d39e3
 
 
 
 
 
 
 
 
 
 
 
1f1b7ad
c0d39e3
 
 
 
 
 
dfe0cf8
d62832c
1277fc8
c0d39e3
dfe0cf8
d62832c
c0d39e3
 
dfe0cf8
d62832c
c0d39e3
 
 
 
 
 
 
 
 
7da90a5
 
 
df7da5e
36d797c
c0d39e3
 
 
7da90a5
 
c0d39e3
7da90a5
28d35b4
f82c018
 
 
9d675db
6ee5fcd
 
 
f82c018
 
7cbaf6e
6ee5fcd
9d675db
7cbaf6e
 
9d675db
7cbaf6e
 
 
 
 
f82c018
7cbaf6e
 
f82c018
7cbaf6e
 
9d675db
f82c018
 
 
 
 
 
 
7cbaf6e
6ee5fcd
7cbaf6e
6beea44
 
 
7cbaf6e
f82c018
7cbaf6e
 
 
6beea44
 
 
9d675db
f82c018
 
 
 
 
 
 
 
 
 
9d675db
28d35b4
c0d39e3
 
 
28d35b4
c0d39e3
 
28d35b4
c0d39e3
 
28d35b4
c0d39e3
28d35b4
7da90a5
 
 
c0d39e3
7da90a5
0307ba9
7da90a5
c0d39e3
 
dfe0cf8
caba5fb
dfe0cf8
1277fc8
 
 
 
 
1f1b7ad
 
 
 
 
36d797c
1f1b7ad
36d797c
1f1b7ad
 
618bff8
dfe0cf8
 
 
 
caba5fb
dfe0cf8
 
 
 
d62832c
c0d39e3
 
9bcf065
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
import json
import re
import httpx
import uvicorn
import asyncio
import os
import urllib.parse
from urllib.parse import urlparse, parse_qs, quote_plus
from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

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,
    redis_client
)
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_deals_standalone
from shopping import scan_prices

# Clean import from your data separation module file
from popular import get_trending_deals

app = FastAPI()

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
templates = Jinja2Templates(directory=BASE_DIR)

def unwrap_direct_product_url(url_str: str) -> str:
    """Recursively peels back tracking redirect strings to isolate raw retailer tokens"""
    if not url_str or not isinstance(url_str, str):
        return ""
    current_url = url_str.strip()
    for _ in range(5):
        if "google.com" not in current_url and "googleadservices.com" not in current_url:
            break
        parsed = urlparse(current_url)
        queries = parse_qs(parsed.query)
        found = False
        for key in ["adurl", "url", "q", "u", "link", "destination", "ad_url", "gclid"]:
            if queries.get(key):
                candidate = queries[key][0].strip()
                if "http" in candidate:
                    if not candidate.startswith("http"):
                        candidate = candidate[candidate.find("http"):]
                    current_url = urllib.parse.unquote(candidate)
                    found = True
                    break
        if not found:
            match = re.search(r'(?:adurl|url|q|link)=(https?%3A%2F%2F[^&]+|https?://[^&]+)', current_url, re.IGNORECASE)
            if match:
                current_url = urllib.parse.unquote(match.group(1))
                found = True
            else:
                break
    return "" if "google.com" in current_url or "googleadservices.com" in current_url else current_url

def clean_retailer_url(url_str: str) -> str:
    """Strips click-tracking bloat parameters to present short paths safe from ad blockers"""
    if not url_str:
        return ""
    try:
        parsed = urlparse(url_str)
        queries = parse_qs(parsed.query)
        clean_queries = {}
        drop_params = {
            'gclid', 'gclsrc', 'utm_source', 'utm_medium', 'utm_campaign', 
            'utm_content', 'utm_term', 'fbclid', '_ga', '_gl', 'srsltid'
        }
        for k, v in queries.items():
            if k.lower() not in drop_params:
                clean_queries[k] = v
        new_query = urllib.parse.urlencode(clean_queries, doseq=True)
        return urllib.parse.urlunparse((
            parsed.scheme, parsed.netloc, parsed.path, 
            parsed.params, new_query, parsed.fragment
        ))
    except:
        return url_str

def get_status_context():
    """Generates reactive state tags for UI elements mapping cache statuses"""
    status_text = "Google Pricing Intelligence & Historical Tracking Active" if redis_client else "Security Protection Active | Core Memory Tracking"
    status_color = "var(--accent-green)" if redis_client else "#f59e0b"
    return status_text, status_color

@app.get("/", response_class=HTMLResponse)
def dashboard(request: Request):
    status_text, status_color = get_status_context()
    return templates.TemplateResponse(
        request=request,
        name="dashboard.html", 
        context={
            "status_text": status_text,
            "status_color": status_color,
            "prev_name": "",
            "prev_size": "",
            "prev_mode": "balanced",
            "prev_gender": "unisex",
            "show_results": False,
            "error_msg": None,
            "popular_deals": get_trending_deals(),
            "active_tab": "scan"
        }
    )

@app.post("/search", response_class=HTMLResponse)
async def handle_search(
    request: Request,
    product_name: str = Form(...), 
    product_size: str = Form(None), 
    search_mode: str = Form("balanced"), 
    product_gender: str = Form("unisex")
):
    status_text, status_color = get_status_context()
    base_ui_context = {
        "status_text": status_text,
        "status_color": status_color,
        "prev_name": product_name,
        "prev_size": product_size or "",
        "prev_mode": search_mode,
        "prev_gender": product_gender,
        "show_results": False,
        "error_msg": None,
        "popular_deals": get_trending_deals(),
        "active_tab": "scan"
    }

    if not HF_TOKEN:
        base_ui_context["error_msg"] = "Please add a valid HF_TOKEN into Space Secrets to activate the free AI models."
        return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context)
                
    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
    
    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):
                base_ui_context["error_msg"] = "The provided link target matches active security alert threat signatures and was isolated."
                return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context)
                        
        raw_text, img_url = await extract_page_data(input_url, "product")
        if not raw_text:
            base_ui_context["error_msg"] = "Tarz could not parse or connect to the provided URL."
            return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context)
                            
        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": clean_retailer_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": clean_retailer_url(input_url), 
                        "price": local_report["price"], 
                        "image": img_url,
                        "source": urlparse(input_url).netloc.replace("www.", ""),
                        "size": requested_size or "Standard"
                    }
                else:
                    base_ui_context["error_msg"] = "Programmatic local parser could not identify currency text variables."
                    return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context)
                                                                                                            
            if not original_site_deal:
                base_ui_context["error_msg"] = "Pasted link parsed, but price extraction could not resolve valid currency markers."
                return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context)
        except Exception as e:
            print(f"❌ [Link Analytics Error] Failure processing link data parsing: {e}")
            base_ui_context["error_msg"] = "Error decoding reference link metadata structure."
            return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context)
                    
    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 & deals...")
        
        markdown_deals, product_offers = await asyncio.gather(
            fetch_deals_standalone(target_item),
            scan_prices(target_item, requested_size, search_mode)
        )
        
        if original_site_deal:
            if not any(d['url'] == original_site_deal['url'] for d in product_offers): 
                product_offers.append(original_site_deal)
        
        if product_offers:
            product_offers.sort(key=lambda x: x.get('price', float('inf')))
            market_max_price = max([x.get('price', 0) for x in product_offers if x.get('price', 0) > 0]) or 1.0
            processed_percentage_badges = []
            
            for item in product_offers:
                cur_p = item.get('price', 0)
                if not cur_p:
                    continue
                    
                item_source = item.get('source', 'Retailer').strip()
                item_title = item.get('title', 'Product Listing')
                
                old_p = item.get('original_price') or item.get('old_price') or item.get('regular_price')
                market_pct = int(round((1 - cur_p / market_max_price) * 100))
                
                if old_p and float(old_p) > float(cur_p) and float(old_p) > 0:
                    calculated_pct = int(round((1 - float(cur_p) / float(old_p)) * 100))
                    badge_string = f"{calculated_pct}% OFF"
                elif market_pct > 10:
                    badge_string = f"{market_pct}% OFF"
                    item['original_price'] = round(market_max_price, 2)
                else:
                    badge_string = "BEST PRICE"
                    item['original_price'] = round(cur_p, 2)

                sanitized_title = re.sub(r'[^a-zA-Z0-9]', '_', item_title).lower()[:50]
                redis_history_key = f"hist_low:prod:{sanitized_title}"
                
                historical_low = None
                if redis_client:
                    try:
                        cached_low = redis_client.get(redis_history_key)
                        if cached_low:
                            historical_low = float(cached_low)
                    except Exception as redis_err:
                        print(f"⚠️ [Redis Error] Failed reading baseline matrix: {redis_err}")

                if historical_low is not None:
                    if cur_p < historical_low and redis_client:
                        try: redis_client.set(redis_history_key, str(cur_p))
                        except: pass
                else:
                    if redis_client:
                        try: redis_client.set(redis_history_key, str(cur_p))
                        except: pass

                item['historical_low_event'] = False
                if historical_low:
                    item['all_time_low_price'] = historical_low

                item['discount_percent'] = badge_string
                item['discount'] = badge_string
                item['percentage'] = badge_string
                item['badge'] = badge_string
                
                if not any(c['description'] == badge_string and c['source'].lower() == item_source.lower() for c in processed_percentage_badges):
                    processed_percentage_badges.append({
                        "description": badge_string,
                        "source": item_source
                    })

            current_lowest = product_offers[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
                product_offers[0]['price_delta'] = round(delta, 2)
                set_base_price(target_item, requested_size, search_mode, current_lowest)
            elif base_price == current_lowest:
                product_offers[0]['price_delta'] = 0.0
            else:
                set_base_price(target_item, requested_size, search_mode, current_lowest)
                product_offers[0]['price_delta'] = 0.0
                
            deals = product_offers
            set_cached_deals(target_item, requested_size, search_mode, deals)
        else:
            deals = []
            set_cached_deals(target_item, requested_size, search_mode, deals)
            
        coupons = []
        set_cached_coupons(target_item, coupons)
                    
    size_header = f" ({requested_size})" if requested_size else ""
    
    validated_deals = []
    for d in deals:
        if "url" not in d and "link" in d:
            d["url"] = d["link"]
        elif "link" not in d and "url" in d:
            d["link"] = d["url"]

        unwrapped = unwrap_direct_product_url(d.get("url", ""))
        if unwrapped:
            cleaned_url = clean_retailer_url(unwrapped)
            d["url"] = cleaned_url
            d["link"] = cleaned_url
            try:
                d["source_domain"] = d.get("source") or urlparse(cleaned_url).netloc.replace("www.", "")
            except:
                d["source_domain"] = "retailer.link"
            validated_deals.append(d)

    base_ui_context.update({
        "show_results": True,
        "target_item": target_item,
        "size_header": size_header,
        "deals": validated_deals,
        "coupons": coupons,
        "is_ref_url": original_site_deal["url"] if original_site_deal else None
    })
    
    return templates.TemplateResponse(request=request, name="dashboard.html", context=base_ui_context)

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)