import gradio as gr import asyncio from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.interval import IntervalTrigger from scraper.sources import scrape_discudemy from scraper.batch_meta import fetch_meta_batch from core.aggregator import deduplicate from core.expiry import estimate_expiry from core.time_utils import get_expiry_status from core.storage import load_cache, save_cache, save_course_to_db from core.db import get_active_courses from core.stats import compute_stats from core.sorters import sort_by_rating from core.freshness import update_refresh_time, get_refresh_status from datetime import datetime, timezone from core.stats import compute_stats, save_daily_stats # --- Scheduler Setup --- scheduler = BackgroundScheduler() scheduler.start() async def background_scrape_job(): print(f"[{datetime.now()}] Starting Background Scrape...") # Re-use the generator but simply consume it async for data, stage, is_done in load_courses_gen(is_background=True): if is_done: print(f"[{datetime.now()}] Background Scrape Complete. Found {len(data)} items.") def run_bg_sync(): asyncio.run(background_scrape_job()) def toggle_automation(enabled): job_id = "auto_scrape" if enabled: if not scheduler.get_job(job_id): scheduler.add_job(run_bg_sync, IntervalTrigger(hours=4), id=job_id) return "โœ… Background Scraping ENABLED (Every 4h)" else: if scheduler.get_job(job_id): scheduler.remove_job(job_id) return "โŒ Background Scraping DISABLED" return "โš ๏ธ Usage: Toggle Switch" # --- Core Logic --- async def load_courses_gen(is_background=False): # Stage 1: DiscUdemy s1 = await scrape_discudemy() if not is_background: yield s1, "DiscUdemy", False # Stage 2: Metadata & Final Processing courses = deduplicate(s1) # This acts as the final "enriched" data yield courses = await fetch_meta_batch(courses) # Load seen data from DB now (via cache shim or direct) # Actually, we should check DB for "new" status # But for now let's stick to existing logic structure but use DB helper final = [] for c in courses: expiry = estimate_expiry(c["source"]) # New Status Logic: Start & End Dates start_date = datetime.now(timezone.utc).strftime("%Y-%m-%d") end_date = expiry.strftime("%Y-%m-%d") status_data = f"{start_date}|{end_date}" c['status'] = status_data # Save to DB (UPSERT) # Returns True if it was a new insert is_new_insert = save_course_to_db(c) final.append({ "title": c["title"], "category": c.get("category", "General"), "status": status_data, "new": "๐Ÿ†• New Today" if is_new_insert else "", "url": c["url"] }) update_refresh_time() # Save daily stats for next run save_daily_stats(len(final)) # Final yield yield final, "Done", True # --- Helpers --- def get_category_color(cat): # Simple mapping for demo, falling back to gray style = "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'{cat}' def format_btn(url): return f'' 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) # Make naive datetime timezone-aware (UTC) for comparison if needed # Or just use naive now if end_dt is naive. # estimate_expiry returns naive or aware? Usually naive in older code. # safe assumption: compare both as naive or both as aware. # let's assume end_dt is naive (from YYYY-MM-DD string) # now = datetime.now() # local naive # actually better to use utcnow/utc now = datetime.now(timezone.utc) # But end_dt is likely naive (fromisoformat "YYYY-MM-DD" -> 00:00:00 naive) # So we should make end_dt aware or now naive. # Let's settle on naive UTC for simplicity if we can't be sure # Actually, standardizing on UTC aware is best. if end_dt.tzinfo is None: end_dt = end_dt.replace(tzinfo=timezone.utc) diff = end_dt - now hours = int(diff.total_seconds() / 3600) if hours < 0: return '๐Ÿ”ด Expired' # ๐ŸŸข Active ยท Expires in 14h return f'''
โ—
Active
Expires in {hours}h
''' except: pass return s def format_new(n): return f'NEW' if n else "" # --- State --- courses_cache = [] async def run_scrape(): global courses_cache courses_cache = [] # Yeild Loading yield "โณ Fetching...", "...", "...", [], gr.update() async for data, stage, is_done in load_courses_gen(): courses_cache = data # Update cache stats = compute_stats(data) # Cards # Style: Dark BG (matching theme), Shadow, Light labels, Vibrant numbers def card_html(label, value, color, icon): return f"""
{icon} {label}
{value}
""" c1 = card_html("New Today", stats['new_today'], "#34d399", "๐Ÿ†•") # Emerald-400 c2 = card_html("Expiring Soon", stats.get('expiring_soon', 0), "#fbbf24", "โฑ") # Amber-400 c3 = card_html("Total Active", stats['total'], "#818cf8", "๐Ÿ“š") # Indigo-400 # Table rows = 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: # Filter if category_filter != "All" and c.get("category", "General") != category_filter: continue if search_query and search_query.lower() not in c["title"].lower(): continue cat_html = get_category_color(c.get("category", "General")) btn = format_btn(c["url"]) # Safe access for progressive loading stages st = format_status(c.get("status", "โณ Verifying...")) nw = format_new(c.get("new", "")) rows.append([c["title"], cat_html, st, nw, btn]) return rows def filter_data(search, category): global courses_cache return process_rows(courses_cache, search, category) def load_initial_data(): """Load data from DB on startup""" global courses_cache db_courses = get_active_courses(limit=100) # Convert DB rows to UI format ui_courses = [] for c in db_courses: ui_courses.append({ "title": c["title"], "category": c["category"], "status": c["status"], "new": "๐Ÿ†• New Today" if c["is_new"] else "", "url": c["url"] }) courses_cache = ui_courses stats = compute_stats(ui_courses) rows = process_rows(ui_courses) # Return initial values for UI components (Cards, Table, Filter) # We need to construct card HTMLs manually or reuse the helper if we can access it. # We will just return empty or placeholder and let user click refresh, # OR we make the generic 'update' function reusable. return courses_cache # Initial load load_initial_data() 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; } /* Custom Rows */ #header-row { padding-bottom: 20px; } #filter-row { background: var(--background-fill-secondary); padding: 15px; border-radius: 8px; margin-top: 20px; display: flex; align-items: center; } """ with gr.Blocks(title="UdemyScout") as demo: with gr.Row(variant="panel", elem_id="header-row"): 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 Cards with gr.Row(): card_new = gr.HTML() card_exp = gr.HTML() card_total = gr.HTML() # Search & Filter & Automation with gr.Row(variant="panel", elem_id="filter-row"): search = gr.Textbox(label="๐Ÿ” Search Courses", placeholder="Type python, java, design...", show_label=False, scale=3) cat_filter = gr.Dropdown(label="Category", choices=["All"], value="All", show_label=False, scale=1) auto_chk = gr.Checkbox(label="Auto-Scrape (4h)", value=False, scale=1) auto_status = gr.Markdown("", visible=False) # Hidden status for feedback 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 ) # Actions btn.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) auto_chk.change(toggle_automation, inputs=[auto_chk], outputs=[auto_status]) # On load - optionally populate # demo.load(fn=...) logic if we want to show cached data immediately. # For now, we leave it empty until Fetch is clicked or we implement a 'render_initial' function. if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Ocean(), css=css)