import re import time import html from typing import List, Dict, Optional from urllib.parse import quote as urlquote from io import BytesIO import requests from bs4 import BeautifulSoup import gradio as gr USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0 Safari/537.36" HEADERS = {"User-Agent": USER_AGENT} CACHE_TTL = 60 * 5 class TimedCache: def __init__(self): self.store = {} def get(self, key): entry = self.store.get(key) if not entry: return None value, expires = entry if time.time() > expires: del self.store[key] return None return value def set(self, key, value, ttl=CACHE_TTL): self.store[key] = (value, time.time() + ttl) cache = TimedCache() def safe_get(url, params=None, timeout=12): try: r = requests.get(url, headers=HEADERS, params=params, timeout=timeout) r.raise_for_status() return r except Exception as e: print(f"safe_get error for {url}: {e}") return None def parse_cheapshark(query: Optional[str] = None) -> List[Dict]: cache_key = f"cheapshark_{query}" cached = cache.get(cache_key) if cached: return cached results = [] q = query or '' url = f"https://www.cheapshark.com/api/1.0/deals?title={urlquote(q)}&limit=60" r = safe_get(url) if not r: cache.set(cache_key, results) return results try: data = r.json() for item in data: title = item.get('title') dealID = item.get('dealID') salePrice = item.get('salePrice') normalPrice = item.get('normalPrice') savings = float(item.get('savings', 0)) discount_pct = int(round(savings)) thumb = item.get('thumb') game_url = f"https://www.cheapshark.com/redirect?dealID={dealID}" if dealID else None results.append({'title': title, 'url': game_url, 'image': thumb, 'is_free': float(salePrice) == 0.0, 'discount_pct': discount_pct, 'store': 'CheapShark', 'platform': 'PC'}) except Exception: pass cache.set(cache_key, results) return results def parse_epic_free_games() -> List[Dict]: cache_key = "epic_free_games" cached = cache.get(cache_key) if cached: return cached results = [] url = "https://www.epicgames.com/store/en-US/free-games" r = safe_get(url) if not r: cache.set(cache_key, results) return results soup = BeautifulSoup(r.text, 'lxml') cards = soup.select('a[href*="/p/"]') seen = set() for a in cards: try: href = a.get('href') title = a.get('aria-label') or (a.find('span').get_text(strip=True) if a.find('span') else None) if not href or not title: continue if href in seen: continue seen.add(href) img_tag = a.find('img') img = img_tag.get('src') if img_tag and img_tag.get('src') else None results.append({'title': title, 'url': href if href.startswith('http') else f"https://www.epicgames.com{href}", 'image': img, 'is_free': True, 'store': 'Epic Games', 'platform': 'PC'}) except Exception: continue cache.set(cache_key, results) return results def parse_steam_deals(query: Optional[str] = None) -> List[Dict]: cache_key = f"steam_{query}" cached = cache.get(cache_key) if cached: return cached results = [] base = "https://store.steampowered.com/search/" params = {'specials': 1, 'term': query or ''} r = safe_get(base, params=params) if not r: cache.set(cache_key, results) return results soup = BeautifulSoup(r.text, 'lxml') rows = soup.select('a.search_result_row') for a in rows[:80]: try: title_elem = a.select_one('.title') title = title_elem.get_text(strip=True) if title_elem else None url = a.get('href') price_div = a.select_one('.search_price') price_text = price_div.get_text(separator=' ', strip=True) if price_div else '' discount_div = a.select_one('.search_discount') discount_pct = 0 if discount_div: s = discount_div.get_text(strip=True) m = re.search(r"-(\d+)%", s) if m: discount_pct = int(m.group(1)) is_free = 'Free' in price_text or 'Free To Play' in price_text img_tag = a.select_one('img') img = img_tag.get('src') if img_tag else None results.append({'title': title, 'url': url, 'image': img, 'is_free': is_free, 'discount_pct': discount_pct, 'store': 'Steam', 'platform': 'PC'}) except Exception: continue cache.set(cache_key, results) return results def parse_itch(query: Optional[str] = None) -> List[Dict]: cache_key = f"itch_{query}" cached = cache.get(cache_key) if cached: return cached results = [] q = query or '' url = f"https://itch.io/search?q={urlquote(q)}" r = safe_get(url) if not r: cache.set(cache_key, results) return results soup = BeautifulSoup(r.text, 'lxml') items = soup.select('.game_cell') for it in items[:60]: try: title_tag = it.select_one('.thumb_link') title = title_tag.get('title') if title_tag else (it.select_one('.game_title').get_text(strip=True) if it.select_one('.game_title') else None) href = title_tag.get('href') if title_tag else None price_span = it.select_one('.price') price_text = price_span.get_text(strip=True) if price_span else '' is_free = ('Free' in price_text) or (price_text == '') img_tag = it.select_one('img') img = img_tag.get('src') if img_tag else None results.append({'title': title, 'url': href, 'image': img, 'is_free': is_free, 'store': 'Itch.io', 'platform': 'PC'}) except Exception: continue cache.set(cache_key, results) return results def parse_itunes(query: Optional[str] = None) -> List[Dict]: cache_key = f"itunes_{query}" cached = cache.get(cache_key) if cached: return cached results = [] q = query or '' url = f"https://itunes.apple.com/search?term={urlquote(q)}&entity=software&country=us&limit=50" r = safe_get(url) if not r: cache.set(cache_key, results) return results try: data = r.json() for item in data.get('results', []): name = item.get('trackName') or item.get('trackCensoredName') url_link = item.get('trackViewUrl') price = item.get('price') is_free = price == 0 artwork = item.get('artworkUrl100') results.append({'title': name, 'url': url_link, 'image': artwork, 'is_free': is_free, 'store': 'App Store', 'platform': 'Mobile'}) except Exception: pass cache.set(cache_key, results) return results def parse_play_store_scrape(query: Optional[str] = None) -> List[Dict]: cache_key = f"play_scrape_{query}" cached = cache.get(cache_key) if cached: return cached results = [] q = query or '' url = f"https://play.google.com/store/search?q={urlquote(q)}&c=apps" r = safe_get(url) if not r: cache.set(cache_key, results) return results soup = BeautifulSoup(r.text, 'lxml') cards = soup.select('div Vbfug') or soup.select('div.WHE7ib') or soup.select('div[jscontroller]') count = 0 for c in cards: if count >= 40: break try: title_tag = c.select_one('div.WsMG1c') or c.select_one('div.b8cIId') title = title_tag.get_text(strip=True) if title_tag else None link_tag = c.find('a', href=True) href = f"https://play.google.com{link_tag.get('href')}" if link_tag else None img_tag = c.select_one('img') img = img_tag.get('data-src') if img_tag and img_tag.get('data-src') else (img_tag.get('src') if img_tag and img_tag.get('src') else None) results.append({'title': title, 'url': href, 'image': img, 'is_free': True, 'store': 'Play Store', 'platform': 'Mobile'}) count += 1 except Exception: continue cache.set(cache_key, results) return results def aggregate_search(query: str, sources: List[str], tab: str, include_mobile: bool) -> List[Dict]: results = [] q = query or '' if 'cheapshark' in sources: results.extend(parse_cheapshark(q)) if 'steam' in sources: results.extend(parse_steam_deals(q)) if 'epic' in sources: results.extend(parse_epic_free_games()) if 'itch' in sources: results.extend(parse_itch(q)) if include_mobile: results.extend(parse_itunes(q)) results.extend(parse_play_store_scrape(q)) seen = set() normalized = [] for r in results: title = (r.get('title') or '').strip() store = r.get('store') or 'Unknown' key2 = (title.lower(), store.lower()) if not title: continue if key2 in seen: continue seen.add(key2) if tab == 'discounts': if r.get('is_free'): continue if not r.get('discount_pct') and r.get('store') not in ('CheapShark','Steam'): continue if tab == 'free': if not r.get('is_free'): continue normalized.append(r) return normalized CSS = """ :root{--bg:#071023;--card:#0d1220;--muted:#9fb0d1;--accent:#00e6a8;--accent2:#6f6bff} body{background:linear-gradient(180deg,var(--bg),#020612);color:#dceeff;font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,'Helvetica Neue',Arial} .app{max-width:1100px;margin:20px auto;padding:18px} .header{display:flex;align-items:center;gap:16px} .logo{width:64px;height:64px;border-radius:12px;background:linear-gradient(135deg,var(--accent2),var(--accent));display:flex;align-items:center;justify-content:center;font-weight:900;color:#021} .title{font-size:20px;font-weight:800} .controls{margin-top:14px;display:flex;gap:12px;align-items:center} .searchbox input{padding:10px 14px;border-radius:12px;border:0;background:#08101a;color:#dff0ff;width:460px} .chips{display:flex;gap:8px} .chip{padding:8px 10px;border-radius:999px;background:#081628;color:var(--muted);font-weight:700} .tabs{margin-top:18px} .results{margin-top:18px;display:grid;grid-template-columns:1fr;gap:12px} .result-card{background:linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0.01));border:1px solid rgba(255,255,255,0.03);padding:12px;border-radius:12px;display:flex;gap:12px;align-items:center} .result-card img{width:140px;height:84px;object-fit:cover;border-radius:8px} .badge{padding:6px 8px;border-radius:8px;font-weight:800} .badge-free{background:linear-gradient(90deg,#00e6a8,#00b87a);color:#032} .badge-discount{background:linear-gradient(90deg,#ff7b7b,#ff3d3d);color:#fff} .meta{color:var(--muted);font-size:13px} .grid-2{display:grid;grid-template-columns:1fr 340px;gap:18px} .sidebar{background:rgba(255,255,255,0.02);padding:12px;border-radius:12px} """ def format_result_card(item: Dict) -> str: title = html.escape(item.get('title') or 'Unknown') url = item.get('url') or '#' store = html.escape(item.get('store') or 'Store') img = item.get('image') or '' is_free = item.get('is_free', False) discount = item.get('discount_pct', None) platform = html.escape(item.get('platform') or '') badge = '' if is_free: badge = 'FREE' elif discount: badge = f'-{int(discount)}%' img_html = f'{title}' if img else '
' meta = f"{store} • {platform}" if platform else store return f"""
{img_html}
{title}
{badge}
{html.escape(meta)}
""" def render_results_html(items: List[Dict]) -> str: if not items: return '
No results found.
' blocks = [format_result_card(it) for it in items] return '
' + ''.join(blocks) + '
' def perform_search_and_return(query: str, pc_sources: bool, mobile_sources: bool): sources = ['cheapshark','steam','epic','itch'] if pc_sources else ['cheapshark'] include_mobile = mobile_sources discounts = aggregate_search(query, sources, tab='discounts', include_mobile=include_mobile) free = aggregate_search(query, sources, tab='free', include_mobile=include_mobile) return render_results_html(discounts), render_results_html(free) def build_ui(): with gr.Blocks(css=CSS) as demo: with gr.Row(elem_classes='app'): with gr.Column(): with gr.Row(): gr.HTML('
FreeDealFinder
Search Play Store, App Store, Steam, Epic and aggregators
') with gr.Row(elem_classes='controls'): query = gr.Textbox(placeholder='Search games, genres or tags (leave empty to scan all)', lines=1) pc_checkbox = gr.Checkbox(label='Include PC sources', value=True) mobile_checkbox = gr.Checkbox(label='Include Mobile sources', value=True) search_btn = gr.Button('Search the stores') with gr.Tabs(): with gr.TabItem('Discounted Games'): discounted_html = gr.HTML() with gr.TabItem('Limited-time Free Games'): free_html = gr.HTML() with gr.Column(scale=0.7): gr.HTML('') search_btn.click(perform_search_and_return, inputs=[query, pc_checkbox, mobile_checkbox], outputs=[discounted_html, free_html]) demo.load(lambda: perform_search_and_return('', True, True), outputs=[discounted_html, free_html]) return demo app = build_ui() if __name__ == '__main__': app.launch(server_name='0.0.0.0', server_port=7860)