ghstedpixel commited on
Commit
4fa2fd9
·
verified ·
1 Parent(s): f0e34d6

Rename coupons.py to coupon.py

Browse files
Files changed (2) hide show
  1. coupon.py +74 -0
  2. coupons.py +0 -87
coupon.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime # <-- ADD THIS TO THE TOP OF YOUR FILE
2
+
3
+ async def fetch_active_coupons(product_name: str, client: httpx.AsyncClient) -> list:
4
+ """Assembles dual-query promo indicators concurrently and parses active codes using structural validation maps"""
5
+ brand_context = _extract_brand_context(product_name)
6
+
7
+ # Dynamically generate the current month and year (e.g., "June 2026", "July 2026")
8
+ current_date_str = datetime.now().strftime("%B %Y")
9
+
10
+ # Dual-vector search targeting both the micro product model and macro brand umbrella
11
+ query_a = f"{product_name} coupon codes promo active"
12
+ query_b = f"{brand_context} discount code promo {current_date_str}" # <-- DYNAMIC STRING
13
+
14
+ results_a, results_b = await asyncio.gather(
15
+ _gather_snippets_from_query(query_a, client),
16
+ _gather_snippets_from_query(query_b, client)
17
+ )
18
+
19
+ # Merge and deduplicate textual block collections
20
+ combined_snippets = list(set(results_a + results_b))
21
+ if not combined_snippets:
22
+ return []
23
+
24
+ payload_text = "\n".join([f"[{idx}]: {s}" for idx, s in enumerate(combined_snippets)])
25
+
26
+ prompt = f"""
27
+ Analyze the following web search snippets containing active discount and voucher data.
28
+ Your goal is to extract genuine, high-veracity alphanumeric coupon codes or sitewide merchant store markdown rules.
29
+
30
+ Target Product Context: "{product_name}"
31
+ Target Brand Context: "{brand_context}"
32
+ Current Verification Window: {current_date_str} # <-- DYNAMIC WINDOW Passed to LLM
33
+
34
+ STRICT EXTRACTION HEURISTICS:
35
+ 1. ASSIGNMENT ACCURACY: The code or discount string MUST directly apply to the product "{product_name}", its brand "{brand_context}", or major legitimate online retailers selling them. Reject rewards systems from unrelated retail fields.
36
+ 2. TIMELINE VALIDATION: Ensure the data is active and currently valid for {current_date_str}. Explicitly discard codes flagged in text snippets as "expired", "historic", "deprecated", or tied to past years.
37
+ 3. DISCARD VAIN CLICKBAIT: Discard phrases that require a physical link click to activate without an actual typed code (e.g., "Click to reveal code", "Deal activated", "No code needed"). If an actual alphanumeric code (like "SAVE15", "CREED20") isn't explicitly printed in the text snippet pool below, do not manufacture it.
38
+ 4. ABSOLUTE NEGATIVE CONSTRAINT: DO NOT return, copy, or reference example text values shown in the schema template structure below. If no genuine alphanumeric promo string is visible in the data pool, output a completely clean empty array: `[]`.
39
+
40
+ Output ONLY a raw, valid JSON array of objects using the template structure below. Do not include markdown wraps or code block markers.
41
+ [
42
+ {{"code": "ALPHANUMERIC_CODE", "description": "Percentage/dollar off value and scope constraint details", "source": "Identifiable Store Name or Brand"}}
43
+ ]
44
+
45
+ Snippets Pool to Parse:
46
+ {payload_text}
47
+ """
48
+
49
+ try:
50
+ ai_res = call_free_llm(prompt, max_tokens=400)
51
+ coupons = json.loads(ai_res)
52
+ if isinstance(coupons, list):
53
+ blacklisted_tokens = {
54
+ "NONE", "N/A", "PLACEHOLDER", "ACTUAL_PROMO_CODE_FOUND", "SUMMER20", "GPC30",
55
+ "COUPON", "PROMO", "DEAL", "CLICKTOREVEAL", "NO_CODE_NEEDED", "EXPIRED"
56
+ }
57
+ clean_coupons = []
58
+ for c in coupons:
59
+ code_val = str(c.get('code', '')).strip().upper()
60
+ desc_val = str(c.get('description', ''))
61
+ source_val = str(c.get('source', ''))
62
+
63
+ if code_val and code_val not in blacklisted_tokens and len(code_val) >= 3:
64
+ if "click" in desc_val.lower() or "deal activated" in desc_val.lower():
65
+ continue
66
+ clean_coupons.append({
67
+ "code": code_val,
68
+ "description": desc_val,
69
+ "source": source_val if source_val else "Retailer"
70
+ })
71
+ return clean_coupons
72
+ except Exception as e:
73
+ print(f"⚠️ [Coupon Parsing Exception] Distillation breakdown: {e}")
74
+ return []
coupons.py DELETED
@@ -1,87 +0,0 @@
1
- import json
2
- import asyncio
3
- import httpx
4
- import random
5
- import urllib.parse
6
- from bs4 import BeautifulSoup
7
- from config import hf_client, MODEL_ID, HF_TOKEN, USER_AGENTS, DDG_SEMAPHORE
8
-
9
- def call_free_llm(prompt: str, max_tokens: int = 600) -> str:
10
- """Queries open-source models via conversational formatting layers"""
11
- if not HF_TOKEN: raise Exception("Hugging Face API Access Token (HF_TOKEN) is missing.")
12
- system_instructions = "You are a data extraction tool. Run heuristics on text to extract structured data. Output RAW JSON ONLY matching requested format. No markdown, no conversational text."
13
- try:
14
- output = hf_client.chat_completion(
15
- model=MODEL_ID,
16
- messages=[{"role": "system", "content": system_instructions}, {"role": "user", "content": prompt}],
17
- max_tokens=max_tokens,
18
- temperature=0.1
19
- )
20
- content = output.choices[0].message.content.strip()
21
- triple_backtick = "`" * 3
22
- content = content.replace(f"{triple_backtick}json", "").replace(triple_backtick, "").strip()
23
- return content
24
- except Exception as e:
25
- print(f"❌ [LLM Error] {e}")
26
- return "{}"
27
-
28
- async def fetch_active_coupons(product_name: str, client: httpx.AsyncClient) -> list:
29
- """Assembles unstructured promo indicators via DuckDuckGo and distills codes safely using execution locks"""
30
- search_q = f"{product_name} coupon codes promo active discount"
31
- url = f"https://html.duckduckgo.com/html/?q={urllib.parse.quote(search_q)}"
32
- headers = {"User-Agent": random.choice(USER_AGENTS)}
33
- snippets = []
34
-
35
- async with DDG_SEMAPHORE:
36
- try:
37
- await asyncio.sleep(random.uniform(0.4, 0.8))
38
- print(f"🎟️ [Coupon Engine] Hunting active promotional tags for '{product_name}'...")
39
- res = await client.get(url, headers=headers, timeout=6.0)
40
- if res.status_code == 200:
41
- soup = BeautifulSoup(res.text, 'html.parser')
42
- results = soup.find_all('div', class_='result')
43
- for item in results[:5]:
44
- snippet_tag = item.find('a', class_='result__snippet')
45
- if snippet_tag: snippets.append(snippet_tag.get_text())
46
- elif res.status_code == 429:
47
- print("⚠️ [Rate Alert] Coupon Engine search requests choked with a 429 rate limit error state.")
48
- return []
49
- except Exception as e:
50
- print(f"⚠️ [Coupon Fetch Error] Scraper bypass down: {e}")
51
- return []
52
-
53
- if not snippets: return []
54
- payload_text = "\n".join([f"- {s}" for s in snippets])
55
-
56
- prompt = f"""
57
- Analyze the following web search snippets containing discount and promotion indicators for '{product_name}'.
58
- Identify and extract genuine, functioning active alphanumeric coupon codes or active merchant store discount strings.
59
-
60
- STRICT EXTRACTION RULES:
61
- 1. The coupon MUST directly apply to '{product_name}', its manufacturer, or the specific online retail stores selling it. Drop third-party un-associated promo links.
62
- 2. Ensure extracted data is currently active and unexpired for June 2026. Ignore old historical descriptions.
63
- 3. NEGATIVE CONSTRAINT: DO NOT return, reuse, or hallucinate the example strings shown in the template structure below. If no genuine alphanumeric promo codes are explicitly written inside the Snippets Pool below, you MUST return a clean empty array `[]`.
64
-
65
- Output ONLY a raw valid JSON array matching the keys shown below. No markdown wrappers, no system preamble.
66
- [
67
- {{"code": "ACTUAL_PROMO_CODE_FOUND", "description": "Details of verified deal", "source": "Store Name"}}
68
- ]
69
-
70
- Snippets Pool:
71
- {payload_text}
72
- """
73
- try:
74
- ai_res = call_free_llm(prompt, max_tokens=300)
75
- coupons = json.loads(ai_res)
76
- if isinstance(coupons, list):
77
- blacklisted_tokens = ["NONE", "N/A", "PLACEHOLDER", "ACTUAL_PROMO_CODE_FOUND", "SUMMER20", "GPC30"]
78
- return [c for c in coupons if c.get('code') and c.get('code').upper() not in blacklisted_tokens]
79
- except Exception as e:
80
- print(f"⚠️ [Coupon Parsing Exception] LLM structure extraction failed: {e}")
81
- return []
82
-
83
- async def fetch_coupons_standalone(target_item: str) -> list:
84
- """Invokes isolation wrappers around keyless HTTP client structures safely"""
85
- limits = httpx.Limits(max_keepalive_connections=2, max_connections=2)
86
- async with httpx.AsyncClient(limits=limits, http2=True, trust_env=False) as client:
87
- return await fetch_active_coupons(target_item, client)