Spaces:
Sleeping
Sleeping
Download app.py from Brainw/UdemyScout: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/spaces/Brainw/UdemyScout/resolve/main/app.py
- Command line
-
hf download hf://spaces/Brainw/UdemyScout/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Brainw/UdemyScout/resolve/main/app.py
12.3 kB
| 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'<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) | |
| # 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 '<span style="color:red;font-weight:bold">π΄ Expired</span>' | |
| # π’ Active Β· Expires in 14h | |
| return 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: | |
| pass | |
| return s | |
| def 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_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""" | |
| <div style="background: #1f2937 !important; padding: 15px !important; border-radius: 12px !important; border: 1px solid #374151 !important; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3) !important; height: 100% !important;"> | |
| <div style="display: flex !important; align-items: center !important; gap: 8px !important; margin-bottom: 5px !important;"> | |
| <span style="font-size: 1.2em !important;">{icon}</span> | |
| <span style="color: #e5e7eb !important; font-weight: 700 !important; font-size: 16px !important; text-transform: uppercase !important; letter-spacing: 0.05em !important; font-family: ui-sans-serif, system-ui, sans-serif !important;">{label}</span> | |
| </div> | |
| <div style="font-size: 3em !important; line-height: 1 !important; font-weight: 800 !important; color: {color} !important; text-shadow: 0 4px 10px {color}40 !important;"> | |
| {value} | |
| </div> | |
| </div> | |
| """ | |
| 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) |