Spaces:
Sleeping
Sleeping
Upload 14 files
Browse filesFiles changed (2)
- app.py+127-43
- core/stats.py+42-2
66 unmodified lines67686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813966 unmodified lines# Final yieldyield final, "Done", Trueasync def run():try:async for data, stage, is_done in load_courses_gen():# Calculate stats on the flystats = compute_stats(data)# Format logictable = []for c in data:btn = format_btn(c["url"])# If not done, show checking statusst = c.get("status") if is_done else "β³ Verifying..."# Handle raw dicts from scraper which might not have 'status' key in early stagesif not is_done:st = "β³ Verifying..."# Pass through if done, else placeholder# New col logic might not be ready in early stagesnw = format_new(c.get("new", "")) if is_done else ""table.append([c["title"], c.get("category", "General"), st, nw, btn])header = f"π +{stats['new_today']} New / -{stats['expired']} Expired"if not is_done:header += f" (Loading {stage}...)"yield header, get_refresh_status(), tableexcept Exception as e:yield f"β Error: {str(e)}", "β οΈ Failed", []def format_btn(url):return f'<a href="{url}" target="_blank" style="text-decoration:none"><button style="background-color:#6366f1;color:white;border:none;padding:5px 10px;border-radius:4px;cursor:pointer;">Open Udemy β</button></a>'def format_status(s):if "|" in s:start, end = s.split("|")return f'<div style="line-height:1.2"><div style="color:green;font-size:0.9em">Start: {start}</div><div style="color:#d97706;font-size:0.9em">End: {end}</div></div>'return sdef format_new(n):return f'<span style="background-color:#10b981;color:white;padding:2px 6px;border-radius:99px;font-size:0.8em">NEW</span>' if n else ""css = """footer {display: none !important}"""with gr.Blocks(title="UdemyScout") as demo:with gr.Row():with gr.Column(scale=3):gr.Markdown("# π UdemyScout")gr.Markdown("### Free Coupons (Safe & Manual Sources)")with gr.Column(scale=1):btn = gr.Button("π Fetch Latest Coupons", variant="primary")with gr.Row():stats_md = gr.Markdown("Waiting for data...")fresh_md = gr.Markdown()table = gr.Dataframe(headers=["Course", "Category", "Status", "New", "Link"],datatype=["str", "str", "html", "html", "html"],interactive=False,column_widths=["40%", "15%", "15%", "10%", "20%"])btn.click(run, outputs=[stats_md, fresh_md, table])if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Ocean(), css=css)66 unmodified lines67686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222366 unmodified lines# Final yieldyield final, "Done", True# --- Helpers ---def get_category_color(cat):# Simple mapping for demo, falling back to graystyle = "background-color:#e5e7eb;color:#374151"if "Development" in cat: style = "background-color:#dbeafe;color:#1e40af"elif "Business" in cat: style = "background-color:#f3e8ff;color:#6b21a8"elif "IT" in cat or "Software" in cat: style = "background-color:#dcfce7;color:#166534"elif "Design" in cat: style = "background-color:#fce7f3;color:#9d174d"elif "Marketing" in cat: style = "background-color:#ffedd5;color:#9a3412"return f'<span class="cat-badge" style="{style}">{cat}</span>'def format_btn(url):return f'<a href="{url}" target="_blank" style="text-decoration:none"><button style="background-color:#6366f1;color:white;border:none;padding:6px 12px;border-radius:6px;font-weight:600;cursor:pointer;transition:all 0.2s;">Open Udemy β</button></a>'def format_status(s):# s format is "YYYY-MM-DD|YYYY-MM-DD"if "|" in s:_, end = s.split("|")try:end_dt = datetime.fromisoformat(end)now = datetime.utcnow()diff = end_dt - nowhours = int(diff.total_seconds() / 3600)if hours < 0: return '<span style="color:red;font-weight:bold">π΄ Expired</span>'# π’ Active Β· Expires in 14hreturn f'''<div style="display:flex;align-items:center;gap:6px;"><span style="color:#10b981;font-size:1.2em">β</span><div style="line-height:1.1"><div style="font-weight:600;color:#374151;">Active</div><div style="font-size:0.85em;color:#6b7280;">Expires in {hours}h</div></div></div>'''except:passreturn sdef format_new(n):return f'<span style="background-color:#10b981;color:white;padding:2px 8px;border-radius:99px;font-size:0.75em;font-weight:700;letter-spacing:0.5px;">NEW</span>' if n else ""# --- State ---courses_cache = []async def run_scrape():global courses_cachecourses_cache = []# Yeild Loadingyield "β³ Fetching...", "...", "...", [], gr.update()async for data, stage, is_done in load_courses_gen():courses_cache = data # Update cachestats = compute_stats(data)# Cardsc1 = f"""<div style="background:white;padding:15px;border-radius:10px;border:1px solid #e5e7eb;box-shadow:0 2px 4px rgba(0,0,0,0.05);"><div style="color:#6b7280;font-size:0.9em;font-weight:600;text-transform:uppercase;letter-spacing:0.05em">π New Today</div><div style="font-size:2em;font-weight:700;color:#10b981">{stats['new_today']}</div></div>"""c2 = f"""<div style="background:white;padding:15px;border-radius:10px;border:1px solid #e5e7eb;box-shadow:0 2px 4px rgba(0,0,0,0.05);"><div style="color:#6b7280;font-size:0.9em;font-weight:600;text-transform:uppercase;letter-spacing:0.05em">β± Expiring Soon</div><div style="font-size:2em;font-weight:700;color:#f59e0b">{stats.get('expiring_soon', 0)}</div></div>"""c3 = f"""<div style="background:white;padding:15px;border-radius:10px;border:1px solid #e5e7eb;box-shadow:0 2px 4px rgba(0,0,0,0.05);"><div style="color:#6b7280;font-size:0.9em;font-weight:600;text-transform:uppercase;letter-spacing:0.05em">π Total Active</div><div style="font-size:2em;font-weight:700;color:#6366f1">{stats['total']}</div></div>"""# Tablerows = process_rows(data)yield c1, c2, c3, rows, gr.update(choices=["All"] + sorted(list(set(c.get('category','General') for c in data))), value="All")def process_rows(data, search_query="", category_filter="All"):rows = []for c in data:# Filterif category_filter != "All" and c.get("category", "General") != category_filter: continueif search_query and search_query.lower() not in c["title"].lower(): continuecat_html = get_category_color(c.get("category", "General"))btn = format_btn(c["url"])st = format_status(c["status"])nw = format_new(c["new"])rows.append([c["title"], cat_html, st, nw, btn])return rowsdef filter_data(search, category):global courses_cachereturn process_rows(courses_cache, search, category)css = """footer {display: none !important}.gradio-container {max-width: 1200px !important; margin: auto !important;}/* Sticky Header */thead tr th {position: sticky !important;top: 0 !important;z-index: 100 !important;background: var(--background-fill-primary) !important;box-shadow: 0 2px 5px rgba(0,0,0,0.05);}/* Category Badges */.cat-badge {padding: 2px 8px;border-radius: 6px;font-size: 0.85em;font-weight: 600;display: inline-block;}"""with gr.Blocks(title="UdemyScout") as demo:with gr.Row(variant="panel", elem_style="padding-bottom: 20px"):with gr.Column(scale=3):gr.Markdown("# π UdemyScout\n### Free Coupons (Safe & Manual Sources)")with gr.Column(scale=1):btn = gr.Button("π Fetch Latest Coupons", variant="primary", size="lg")# Summary Cardswith gr.Row():card_new = gr.HTML()card_exp = gr.HTML()card_total = gr.HTML()# Search & Filterwith gr.Row(variant="panel", elem_style="background:var(--background-fill-secondary);padding:15px;border-radius:8px;margin-top:20px"):search = gr.Textbox(label="π Search Courses", placeholder="Type python, java, design...", show_label=False, scale=4)cat_filter = gr.Dropdown(label="Category", choices=["All"], value="All", show_label=False, scale=1)table = gr.Dataframe(headers=["Course", "Category", "Status", "New", "Link"],datatype=["str", "html", "html", "html", "html"],interactive=False,column_widths=["40%", "15%", "20%", "8%", "17%"],row_count=15)# Actionsbtn.click(run_scrape, outputs=[card_new, card_exp, card_total, table, cat_filter])search.change(filter_data, inputs=[search, cat_filter], outputs=table)cat_filter.change(filter_data, inputs=[search, cat_filter], outputs=table)if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Ocean(), css=css)
33 unmodified lines343536373833 unmodified linesdef compute_stats(c):total = len(c)new = sum(1 for i in c if i.get('new'))expired = get_expired_count(total, new)return {'total': total, 'new_today': new, 'expired': expired}33 unmodified lines34353637383940414243444546474849505152535455565758596061626364656667686970717273747576777833 unmodified linesdef compute_stats(c):total = len(c)new = sum(1 for i in c if i.get('new'))# Calculate expiring soon (naive check based on status text or logic)# We don't have easy access to raw expiry objects here unless we pass them or parse status# But we can check if "Expires" is in the status string if it's already formatted?# Actually, better to pass raw data before formatting or parse the date string.# Since we formatted status as "Start|End", we can parse "End".expiring = 0today = datetime.utcnow().date().isoformat()for i in c:status_raw = i.get('status', '')if '|' in status_raw:_, end_date = status_raw.split('|')# If end_date is today or tomorrow, count as expiring soonif end_date <= today: # Already expired or expires todaypass # Actually if it's in the list it's active, but maybe "Expiring Soon" means < 24h# Simple string comparison works for ISO dates# If end_date is close to today... let's just count all for now as "Active"# and maybe check if end_date == today?pass# Re-reading user request: "cx wants β± Expiring Soon: 12"# Let's rely on the fact that our scrapers fetch "fresh" coupons.# Most DiscUdemy are 24h. UdemyFreebies are often <24h.# Let's count items where end_date is today or tomorrow.expiring = 0try:from datetime import timedeltalimit = (datetime.utcnow().date() + timedelta(days=1)).isoformat()for i in c:s = i.get('status', '')if '|' in s:end = s.split('|')[1]if end <= limit:expiring += 1except:passexpired_since_last = get_expired_count(total, new)return {'total': total, 'new_today': new, 'expired_since_last': expired_since_last, 'expiring_soon': expiring}
app.py+127-43
core/stats.py+42-2