Spaces:
Sleeping
Sleeping
Create Coupons.py
Browse files- Coupons.py +87 -0
Coupons.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import asyncio
|
| 3 |
+
import httpx
|
| 4 |
+
import random
|
| 5 |
+
import urllib.parse
|
| 6 |
+
from bs4 import BeautifulSoup
|
| 7 |
+
from app.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)
|