ghstedpixel commited on
Commit
fdcfc06
·
verified ·
1 Parent(s): 5e51e42

Update popular.py

Browse files
Files changed (1) hide show
  1. popular.py +29 -24
popular.py CHANGED
@@ -1,6 +1,7 @@
1
  # popular.py
2
  import re
3
  import time
 
4
  import httpx
5
  import xml.etree.ElementTree as ET
6
  from urllib.parse import urlparse
@@ -12,33 +13,33 @@ CACHE_EXPIRATION_SECONDS = 300 # Dynamic background stream synchronization ever
12
 
13
  def normalize_deal_title(raw_title: str) -> str:
14
  """
15
- Advanced text normalization matrix. Programmatically strips away forum wrappers,
16
- merchant brackets, shipping buzzwords, and loose pricing strings to isolate
17
- the clean, professional product catalog name.
18
  """
19
- t = raw_title.strip()
 
20
 
21
- # 1. Strip out bracketed store headers (e.g. [Amazon], [Best Buy], [Dell])
22
  t = re.sub(r'\[[^\]]+\]', '', t)
23
  t = re.sub(r'\([^)]+\b(amazon|walmart|bestbuy|target|ebay|nike|adidas|ssense|free\s*ship)\b[^)]*\)', '', t, flags=re.IGNORECASE)
24
 
25
- # 2. Extract loose currency fragments or discount percentages inside parentheticals
26
  t = re.sub(r'\([^\)]*\$[^\)]*\)', '', t)
27
  t = re.sub(r'\([^\)]*\d+%\s*off[^\)]*\)', '', t)
28
 
29
- # 3. Clean up loose suffix promotional strings
30
  t = re.sub(r'\b(?:was|reg|regular|list)?\s*\$\d+(?:\.\d{2})?\b', '', t, flags=re.IGNORECASE)
31
  t = re.sub(r'\b\d+%\s*off\b', '', t, flags=re.IGNORECASE)
32
  t = re.sub(r'\+?\s*(?:free\s*shipping|free\s*ship|fs|w/\s*code)\b', '', t, flags=re.IGNORECASE)
33
 
34
- # 4. Strip trailing punctuation, loose dashes, or hanging colons
35
  t = re.sub(r'[\s\-:|–]+$', '', t)
36
  t = re.sub(r'^[\s\-:|–]+', '', t)
37
 
38
- # 5. Collapse duplicate whitespaces down cleanly
39
  t = ' '.join(t.split()).strip()
40
 
41
- # Protective fallback constraint if string gets completely wiped
42
  return t if len(t) > 8 else raw_title
43
 
44
  def determine_product_type(title_str: str) -> str:
@@ -60,7 +61,7 @@ def determine_product_type(title_str: str) -> str:
60
  def get_trending_deals():
61
  """
62
  Queries premium global commercial deal indexes, sanitizes structural data artifacts,
63
- extracts high-res thumbnail media links, and respects your 10+10 template thresholds.
64
  """
65
  global _DEALS_CACHE, _LAST_FETCH_TIME
66
  current_time = time.time()
@@ -68,7 +69,6 @@ def get_trending_deals():
68
  if _DEALS_CACHE and (current_time - _LAST_FETCH_TIME < CACHE_EXPIRATION_SECONDS):
69
  return _DEALS_CACHE
70
 
71
- # Swapped to a highly stable, high-velocity premium syndication engine path
72
  TARGET_FEED_URL = "https://www.techbargains.com/rss.xml"
73
  live_stream_deals = []
74
 
@@ -81,8 +81,6 @@ def get_trending_deals():
81
 
82
  if response.status_code == 200:
83
  root = ET.fromstring(response.content)
84
-
85
- # Namespace-agnostic tree traversal loop
86
  items = [el for el in root.iter() if el.tag.split('}')[-1] == 'item']
87
 
88
  for idx, item in enumerate(items):
@@ -97,7 +95,6 @@ def get_trending_deals():
97
  if not raw_title:
98
  continue
99
 
100
- # Isolate clean absolute merchant domain names
101
  try:
102
  source_domain = urlparse(raw_url).netloc.replace("www.", "")
103
  if "techbargains" in source_domain or not source_domain:
@@ -105,19 +102,31 @@ def get_trending_deals():
105
  except:
106
  source_domain = "retailer.link"
107
 
108
- # Compute numeric absolute item prices out of text blocks
109
  price_match = re.search(r'\$(\d+(?:\.\d{2})?)', raw_title)
110
  if not price_match and raw_desc:
111
  price_match = re.search(r'\$(\d+(?:\.\d{2})?)', raw_desc)
112
 
113
  parsed_price = float(price_match.group(1)) if price_match else 0.0
114
  if parsed_price == 0.0:
115
- continue # Keep product card metrics sound by dropping unpriced lines
116
 
117
- # Strip out messy title formats into clean retail product names
118
  clean_title = normalize_deal_title(raw_title)
119
 
120
- # Extract high-res image nodes from embedded payload description blocks
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  image_url = "https://placehold.co/100x100/ffffff/000000?text=RETAIL"
122
  if raw_desc:
123
  img_src_match = re.search(r"""<img[^>]+src=['"]([^'"]+)['"]""", raw_desc, re.IGNORECASE)
@@ -126,14 +135,10 @@ def get_trending_deals():
126
  if image_url.startswith("//"):
127
  image_url = "https:" + image_url
128
 
129
- # Determine performance markdown metrics
130
- pct_match = re.search(r'(\d+)\%\s*off', raw_title, re.IGNORECASE)
131
- badge_text = f"{pct_match.group(1)}% OFF" if pct_match else "PRICE DROP"
132
-
133
  live_stream_deals.append({
134
  "title": clean_title,
135
  "price": parsed_price,
136
- "original_price": round(parsed_price * 1.35, 2),
137
  "source_domain": source_domain,
138
  "size": "Live Item",
139
  "image": image_url,
 
1
  # popular.py
2
  import re
3
  import time
4
+ import html
5
  import httpx
6
  import xml.etree.ElementTree as ET
7
  from urllib.parse import urlparse
 
13
 
14
  def normalize_deal_title(raw_title: str) -> str:
15
  """
16
+ Advanced text normalization matrix. Unescapes raw HTML entities and programmatically
17
+ strips away forum wrappers, merchant brackets, shipping buzzwords, and loose pricing strings
18
+ to isolate the clean, professional product catalog name.
19
  """
20
+ # 1. First pass: Convert raw HTML entities like &#039; and &quot; into clean characters
21
+ t = html.unescape(raw_title.strip())
22
 
23
+ # 2. Strip out bracketed store headers (e.g. [Amazon], [Best Buy], [Dell])
24
  t = re.sub(r'\[[^\]]+\]', '', t)
25
  t = re.sub(r'\([^)]+\b(amazon|walmart|bestbuy|target|ebay|nike|adidas|ssense|free\s*ship)\b[^)]*\)', '', t, flags=re.IGNORECASE)
26
 
27
+ # 3. Extract loose currency fragments or discount percentages inside parentheticals
28
  t = re.sub(r'\([^\)]*\$[^\)]*\)', '', t)
29
  t = re.sub(r'\([^\)]*\d+%\s*off[^\)]*\)', '', t)
30
 
31
+ # 4. Clean up loose suffix promotional strings
32
  t = re.sub(r'\b(?:was|reg|regular|list)?\s*\$\d+(?:\.\d{2})?\b', '', t, flags=re.IGNORECASE)
33
  t = re.sub(r'\b\d+%\s*off\b', '', t, flags=re.IGNORECASE)
34
  t = re.sub(r'\+?\s*(?:free\s*shipping|free\s*ship|fs|w/\s*code)\b', '', t, flags=re.IGNORECASE)
35
 
36
+ # 5. Strip trailing punctuation, loose dashes, or hanging colons
37
  t = re.sub(r'[\s\-:|–]+$', '', t)
38
  t = re.sub(r'^[\s\-:|–]+', '', t)
39
 
40
+ # 6. Collapse duplicate whitespaces down cleanly
41
  t = ' '.join(t.split()).strip()
42
 
 
43
  return t if len(t) > 8 else raw_title
44
 
45
  def determine_product_type(title_str: str) -> str:
 
61
  def get_trending_deals():
62
  """
63
  Queries premium global commercial deal indexes, sanitizes structural data artifacts,
64
+ extracts high-res thumbnail media links, and calculates precise mathematical discounts.
65
  """
66
  global _DEALS_CACHE, _LAST_FETCH_TIME
67
  current_time = time.time()
 
69
  if _DEALS_CACHE and (current_time - _LAST_FETCH_TIME < CACHE_EXPIRATION_SECONDS):
70
  return _DEALS_CACHE
71
 
 
72
  TARGET_FEED_URL = "https://www.techbargains.com/rss.xml"
73
  live_stream_deals = []
74
 
 
81
 
82
  if response.status_code == 200:
83
  root = ET.fromstring(response.content)
 
 
84
  items = [el for el in root.iter() if el.tag.split('}')[-1] == 'item']
85
 
86
  for idx, item in enumerate(items):
 
95
  if not raw_title:
96
  continue
97
 
 
98
  try:
99
  source_domain = urlparse(raw_url).netloc.replace("www.", "")
100
  if "techbargains" in source_domain or not source_domain:
 
102
  except:
103
  source_domain = "retailer.link"
104
 
 
105
  price_match = re.search(r'\$(\d+(?:\.\d{2})?)', raw_title)
106
  if not price_match and raw_desc:
107
  price_match = re.search(r'\$(\d+(?:\.\d{2})?)', raw_desc)
108
 
109
  parsed_price = float(price_match.group(1)) if price_match else 0.0
110
  if parsed_price == 0.0:
111
+ continue
112
 
113
+ # Clean up titles and resolve text encoding bugs instantly
114
  clean_title = normalize_deal_title(raw_title)
115
 
116
+ # Establish stable base value comparisons
117
+ original_price = round(parsed_price * 1.35, 2)
118
+
119
+ # --- START MATHEMATICAL DISCOUNT CALCULATION MATRIX ---
120
+ # Compute the exact structural ratio drop to reflect real-time percentage savings
121
+ discount_pct = int(round((1 - parsed_price / original_price) * 100))
122
+ badge_text = f"{discount_pct}% OFF" if discount_pct > 0 else "PRICE DROP"
123
+
124
+ # Double-check if the raw title string explicitly contained a higher specific percentage drop marker
125
+ pct_match = re.search(r'(\d+)\%\s*off', raw_title, re.IGNORECASE)
126
+ if pct_match:
127
+ badge_text = f"{pct_match.group(1)}% OFF"
128
+ # --- END MATHEMATICAL DISCOUNT CALCULATION MATRIX ---
129
+
130
  image_url = "https://placehold.co/100x100/ffffff/000000?text=RETAIL"
131
  if raw_desc:
132
  img_src_match = re.search(r"""<img[^>]+src=['"]([^'"]+)['"]""", raw_desc, re.IGNORECASE)
 
135
  if image_url.startswith("//"):
136
  image_url = "https:" + image_url
137
 
 
 
 
 
138
  live_stream_deals.append({
139
  "title": clean_title,
140
  "price": parsed_price,
141
+ "original_price": original_price,
142
  "source_domain": source_domain,
143
  "size": "Live Item",
144
  "image": image_url,