Spaces:
Sleeping
Sleeping
Download app.py from kcmandable/RIBBIT: direct link, hf CLI and curl.
- Browser
- Download file 20.1 kB
-
https://huggingface.co/spaces/kcmandable/RIBBIT/resolve/main/app.py
- Command line
-
hf download hf://spaces/kcmandable/RIBBIT/app.py
-
curl -L -o app.py https://huggingface.co/spaces/kcmandable/RIBBIT/resolve/main/app.py
20.1 kB
| #!/usr/bin/env python3 | |
| import sys | |
| import traceback | |
| print("=== Starting ProPlanner ===", flush=True) | |
| print(f"Python version: {sys.version}", flush=True) | |
| try: | |
| print("Importing modules...", flush=True) | |
| import tempfile | |
| import os | |
| import re | |
| import pdfplumber | |
| import gradio as gr | |
| import pandas as pd | |
| import logging | |
| import requests | |
| import json | |
| from typing import List, Dict | |
| print("β All imports successful", flush=True) | |
| # Set up logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| print("Setting up API keys...", flush=True) | |
| # API Keys | |
| GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY") | |
| GROQ_API_KEY = os.environ.get("GROQ_API_KEY") | |
| if GEMINI_API_KEY: | |
| print("β Gemini API key found", flush=True) | |
| if GROQ_API_KEY: | |
| print("β Groq API key found", flush=True) | |
| if not GEMINI_API_KEY and not GROQ_API_KEY: | |
| print("β No API keys found - will use regex only", flush=True) | |
| # --------------------------------------- | |
| # LLM API Functions | |
| # --------------------------------------- | |
| def query_gemini(prompt: str): | |
| """Query Google Gemini API (FREE - 15 req/min)""" | |
| if not GEMINI_API_KEY: | |
| return None | |
| # Try the latest API endpoint | |
| url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key={GEMINI_API_KEY}" | |
| payload = { | |
| "contents": [{ | |
| "parts": [{ | |
| "text": prompt | |
| }] | |
| }], | |
| "generationConfig": { | |
| "temperature": 0.1, | |
| "maxOutputTokens": 2000 | |
| } | |
| } | |
| try: | |
| response = requests.post(url, json=payload, timeout=30) | |
| response.raise_for_status() | |
| result = response.json() | |
| if "candidates" in result and len(result["candidates"]) > 0: | |
| text = result["candidates"][0]["content"]["parts"][0]["text"] | |
| return text.strip() | |
| return None | |
| except Exception as e: | |
| logger.error(f"Gemini API error: {e}") | |
| return None | |
| def query_groq(prompt: str): | |
| """Query Groq API (FREE - fast Llama models)""" | |
| if not GROQ_API_KEY: | |
| return None | |
| url = "https://api.groq.com/openai/v1/chat/completions" | |
| headers = { | |
| "Authorization": f"Bearer {GROQ_API_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| payload = { | |
| "model": "llama-3.3-70b-versatile", | |
| "messages": [{"role": "user", "content": prompt}], | |
| "temperature": 0.1, | |
| "max_tokens": 2000 | |
| } | |
| try: | |
| response = requests.post(url, headers=headers, json=payload, timeout=30) | |
| response.raise_for_status() | |
| result = response.json() | |
| if "choices" in result and len(result["choices"]) > 0: | |
| return result["choices"][0]["message"]["content"].strip() | |
| return None | |
| except Exception as e: | |
| logger.error(f"Groq API error: {e}") | |
| return None | |
| # --------------------------------------- | |
| # Validation helpers | |
| # --------------------------------------- | |
| def is_valid_date(date_str): | |
| """Check if a date string looks valid""" | |
| if not date_str or len(date_str) < 3: | |
| return False | |
| months = ['january', 'february', 'march', 'april', 'may', 'june', | |
| 'july', 'august', 'september', 'october', 'november', 'december', | |
| 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] | |
| has_month = any(month in date_str.lower() for month in months) | |
| has_date_pattern = re.search(r'\d{1,2}[/-]\d{1,2}', date_str) | |
| return has_month or has_date_pattern | |
| # --------------------------------------- | |
| # LLM Extraction | |
| # --------------------------------------- | |
| def extract_schedule_with_llm(text): | |
| """Extract class schedule using free APIs""" | |
| text_chunk = text[:2500] | |
| prompt = f"""Extract the class meeting times and office hours from this syllabus. | |
| Return ONLY a JSON array like this: | |
| [ | |
| {{"event": "Class", "datetime": "MW 3:30pm-4:50pm", "location": "Room 101"}}, | |
| {{"event": "Office Hours", "datetime": "T 2:00pm-3:00pm", "location": "Office 205"}} | |
| ] | |
| Syllabus excerpt: | |
| {text_chunk} | |
| Return ONLY the JSON array, nothing else.""" | |
| if GEMINI_API_KEY: | |
| logger.info("Trying Gemini API for schedule...") | |
| result = query_gemini(prompt) | |
| if result: | |
| events = parse_llm_response(result, "schedule") | |
| if events: | |
| logger.info(f"β Gemini extracted {len(events)} schedule events") | |
| return events | |
| if GROQ_API_KEY: | |
| logger.info("Trying Groq API for schedule...") | |
| result = query_groq(prompt) | |
| if result: | |
| events = parse_llm_response(result, "schedule") | |
| if events: | |
| logger.info(f"β Groq extracted {len(events)} schedule events") | |
| return events | |
| logger.warning("No LLM API available or all failed for schedule") | |
| return [] | |
| def extract_deadlines_with_llm(text): | |
| """Extract assignment deadlines using free APIs""" | |
| keywords = ["due dates", "assignment", "schedule", "calendar", "deadlines", "grading"] | |
| start_pos = len(text) | |
| for keyword in keywords: | |
| pos = text.lower().find(keyword) | |
| if pos != -1 and pos < start_pos: | |
| start_pos = pos | |
| text_chunk = text[max(0, start_pos - 500):start_pos + 5000] | |
| prompt = f"""Extract ALL assignment deadlines, exams, and project due dates from this syllabus. | |
| IMPORTANT: Look for dates in ALL formats: | |
| - Full dates: "September 15", "Oct 20, 2024" | |
| - Short dates: "9/15", "10-20" | |
| - Relative: "Week 5", "by Monday" | |
| - Month only: "November", "Dec" | |
| Return ONLY a JSON array like this: | |
| [ | |
| {{"event": "Assignment 1", "datetime": "September 15"}}, | |
| {{"event": "Midterm Exam", "datetime": "October 20"}}, | |
| {{"event": "Final Project", "datetime": "December 10"}} | |
| ] | |
| If you find an assignment but NO specific date is mentioned, still include it with datetime as "Not specified". | |
| Include EVERY assignment, paper, exam, project, presentation, and deadline you find. | |
| Syllabus excerpt: | |
| {text_chunk} | |
| Return ONLY the JSON array, nothing else.""" | |
| if GEMINI_API_KEY: | |
| logger.info("Trying Gemini API for deadlines...") | |
| result = query_gemini(prompt) | |
| if result: | |
| events = parse_llm_response(result, "deadline") | |
| if events: | |
| logger.info(f"β Gemini extracted {len(events)} deadlines") | |
| return events | |
| if GROQ_API_KEY: | |
| logger.info("Trying Groq API for deadlines...") | |
| result = query_groq(prompt) | |
| if result: | |
| events = parse_llm_response(result, "deadline") | |
| if events: | |
| logger.info(f"β Groq extracted {len(events)} deadlines") | |
| return events | |
| logger.warning("No LLM API available or all failed for deadlines") | |
| return [] | |
| def parse_llm_response(response: str, event_type: str) -> List[Dict]: | |
| """Parse LLM response and extract events""" | |
| json_match = re.search(r'\[.*?\]', response, re.DOTALL) | |
| if not json_match: | |
| return [] | |
| try: | |
| json_str = json_match.group() | |
| json_str = json_str.replace("'", '"') | |
| json_str = re.sub(r',\s*}', '}', json_str) | |
| json_str = re.sub(r',\s*]', ']', json_str) | |
| events_data = json.loads(json_str) | |
| events = [] | |
| for item in events_data: | |
| if not isinstance(item, dict): | |
| continue | |
| if event_type == "schedule": | |
| if 'event' in item and 'datetime' in item: | |
| events.append({ | |
| "Event": item['event'], | |
| "Date/Time": item['datetime'], | |
| "Location": item.get('location', '') | |
| }) | |
| else: | |
| if 'event' in item and 'datetime' in item: | |
| events.append({ | |
| "Event": item['event'], | |
| "Date/Time": item['datetime'] | |
| }) | |
| return events | |
| except json.JSONDecodeError as e: | |
| logger.warning(f"JSON parse error: {e}") | |
| return [] | |
| # --------------------------------------- | |
| # Regex Fallback | |
| # --------------------------------------- | |
| def regex_extract_schedule(text): | |
| """Comprehensive regex for schedule""" | |
| events = [] | |
| text_header = text[:3000] | |
| patterns = [ | |
| r"\b([MTWRFS]{2,5})[:\s,]+(\d{1,2}:\d{2}\s*(?:AM|PM|am|pm)\s*[-βto]+\s*\d{1,2}:\d{2}\s*(?:AM|PM|am|pm))", | |
| r"((?:Monday|Tuesday|Wednesday|Thursday|Friday)s?(?:\s*[&and,]\s*(?:Monday|Tuesday|Wednesday|Thursday|Friday)s?)*)[,\s]+(\d{1,2}:\d{2}\s*(?:AM|PM|am|pm)\s*[-β]\s*\d{1,2}:\d{2}\s*(?:AM|PM|am|pm))", | |
| r"((?:Monday|Tuesday|Wednesday|Thursday|Friday)(?:/(?:Monday|Tuesday|Wednesday|Thursday|Friday))+)\s+(\d{1,2}:\d{2}\s*(?:AM|PM|am|pm)\s*[-β]\s*\d{1,2}:\d{2}\s*(?:AM|PM|am|pm))", | |
| ] | |
| for pattern in patterns: | |
| for match in re.finditer(pattern, text_header, re.IGNORECASE): | |
| events.append({ | |
| "Event": "Class", | |
| "Date/Time": f"{match.group(1)} {match.group(2)}", | |
| "Location": "" | |
| }) | |
| return events | |
| def regex_extract_deadlines(text): | |
| """Comprehensive regex for deadlines""" | |
| events = [] | |
| patterns = [ | |
| (r'([A-Z]+\d+(?:\s*-\s*[A-Z]+\d+)?)\s{2,}((?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{1,2}(?:st|nd|rd|th)?(?:,?\s+\d{1,2}:\d{2}\s*(?:AM|PM|am|pm))?)', 1), | |
| (r'([A-Z]+\d+(?:\s*-\s*[A-Z]+\d+)?)[:\s]+(?:due\s+)?((?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{1,2}(?:st|nd|rd|th)?(?:,?\s+\d{1,2}:\d{2}\s*(?:AM|PM|am|pm))?)', 1), | |
| (r'(PMS\d+)[:\s]+(?:due\s+)?((?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{1,2}(?:st|nd|rd|th)?(?:,?\s+\d{1,2}:\d{2}\s*(?:AM|PM|am|pm))?)', 1), | |
| (r'(PMS\d+)\s{2,}((?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{1,2}(?:st|nd|rd|th)?(?:,?\s+\d{1,2}:\d{2}\s*(?:AM|PM|am|pm))?)', 1), | |
| (r'(Assignment|Paper|Homework|Lab|Project|Quiz)\s+(\d+)[:\s]+(?:due\s+)?(?:on\s+)?((?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{1,2}(?:st|nd|rd|th)?)', 2), | |
| (r'(Midterm|Final|Exam)[:\s]+((?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{1,2})', 1), | |
| (r'(\d{1,2}/\d{1,2})\s*\([A-Z]\)\s*[-β]\s*([^\n]+?)(?=\n\d{1,2}/\d{1,2}|\n\n|$)', 0), | |
| (r'(Assignment|Paper|Homework|Project|Quiz)\s+(\d+)\s*\((\d{1,2}/\d{1,2})\)', 3), | |
| (r'(Assignment|Paper|Project|Homework)\s+(\d+).*?due\s+(?:in\s+)?((?:January|February|March|April|May|June|July|August|September|October|November|December))', 2), | |
| (r'(Assignment|Paper|Homework)\s+(\d+).*?due\s+(\d{1,2}/\d{1,2})', 2), | |
| ] | |
| for pattern, group_count in patterns: | |
| for match in re.finditer(pattern, text, re.IGNORECASE): | |
| try: | |
| if group_count == 3: | |
| event_name = f"{match.group(1)} {match.group(2)}" | |
| date = match.group(3) | |
| elif group_count == 2: | |
| event_name = f"{match.group(1)} {match.group(2)}" | |
| date = match.group(3) | |
| elif group_count == 1: | |
| event_name = match.group(1) | |
| date = match.group(2) | |
| else: | |
| date = match.group(1) | |
| event_name = match.group(2).strip() | |
| if not any(kw in event_name.lower() for kw in ['assignment', 'submit', 'due', 'present', 'proposal', 'project', 'paper', 'exam']): | |
| continue | |
| if (is_valid_date(date) or re.match(r'\d{1,2}/\d{1,2}', date)) and len(event_name) < 150: | |
| events.append({"Event": event_name, "Date/Time": date}) | |
| except (IndexError, AttributeError): | |
| continue | |
| return events | |
| def deduplicate_events(events, event_type="deadline"): | |
| """Remove duplicates""" | |
| seen = {} | |
| for event in events: | |
| if not isinstance(event.get("Event"), str) or not isinstance(event.get("Date/Time"), str): | |
| continue | |
| event_name = event["Event"].strip() | |
| date_time = event["Date/Time"].strip() | |
| if len(event_name) < 1 or len(date_time) < 2: | |
| continue | |
| # Skip generic entries | |
| if "not specified" in date_time.lower(): | |
| continue | |
| if event_name.lower() in ["quizzes and assignments", "assignments", "quizzes"]: | |
| continue | |
| normalized_name = event_name.lower() | |
| base_date = date_time.split(',')[0].strip().lower() | |
| key = f"{normalized_name}||{base_date}" | |
| if key not in seen or len(event_name) > len(seen[key]["Event"]): | |
| seen[key] = event | |
| return list(seen.values()) | |
| def extract_dates(pdf_file): | |
| if pdf_file is None: | |
| return None, None, "Please upload a PDF file." | |
| logger.info("=" * 70) | |
| logger.info("STARTING PDF EXTRACTION") | |
| logger.info("=" * 70) | |
| apis_available = [] | |
| if GEMINI_API_KEY: | |
| apis_available.append("Gemini") | |
| if GROQ_API_KEY: | |
| apis_available.append("Groq") | |
| if apis_available: | |
| logger.info(f"Available APIs: {', '.join(apis_available)}") | |
| else: | |
| logger.warning("No LLM APIs configured - using regex only") | |
| try: | |
| with pdfplumber.open(pdf_file) as pdf: | |
| text = "\n".join(page.extract_text() or "" for page in pdf.pages) | |
| logger.info(f"Extracted {len(text)} characters from PDF") | |
| except Exception as e: | |
| logger.error(f"PDF extraction error: {e}") | |
| return None, None, f"Error reading PDF: {e}" | |
| if not text.strip(): | |
| return None, None, "No text extracted β PDF may be scanned." | |
| logger.info("\n" + "=" * 50) | |
| logger.info("EXTRACTING SCHEDULE") | |
| logger.info("=" * 50) | |
| schedule_events_llm = extract_schedule_with_llm(text) if apis_available else [] | |
| schedule_events_regex = regex_extract_schedule(text) | |
| schedule_events = schedule_events_llm + schedule_events_regex | |
| schedule_events = deduplicate_events(schedule_events, "schedule") | |
| logger.info("\n" + "=" * 50) | |
| logger.info("EXTRACTING DEADLINES") | |
| logger.info("=" * 50) | |
| deadline_events_llm = extract_deadlines_with_llm(text) if apis_available else [] | |
| deadline_events_regex = regex_extract_deadlines(text) | |
| logger.info(f"LLM extracted: {len(deadline_events_llm)} deadlines") | |
| logger.info(f"Regex extracted: {len(deadline_events_regex)} deadlines") | |
| # Log what was found | |
| for i, event in enumerate(deadline_events_llm[:5]): # Show first 5 | |
| logger.info(f" LLM {i+1}: {event}") | |
| for i, event in enumerate(deadline_events_regex[:5]): # Show first 5 | |
| logger.info(f" Regex {i+1}: {event}") | |
| deadline_events = deadline_events_llm + deadline_events_regex | |
| deadline_events = deduplicate_events(deadline_events, "deadline") | |
| logger.info("\n" + "=" * 70) | |
| logger.info(f"FINAL: {len(schedule_events)} schedule, {len(deadline_events)} deadlines") | |
| logger.info("=" * 70) | |
| schedule_path = None | |
| deadlines_path = None | |
| if schedule_events: | |
| df_schedule = pd.DataFrame(schedule_events) | |
| with tempfile.NamedTemporaryFile(delete=False, suffix="_schedule.csv", mode="w", encoding="utf-8") as f: | |
| df_schedule.to_csv(f, index=False) | |
| schedule_path = f.name | |
| if deadline_events: | |
| df_deadlines = pd.DataFrame(deadline_events) | |
| with tempfile.NamedTemporaryFile(delete=False, suffix="_deadlines.csv", mode="w", encoding="utf-8") as f: | |
| df_deadlines.to_csv(f, index=False) | |
| deadlines_path = f.name | |
| if not schedule_path and not deadlines_path: | |
| return None, None, "β οΈ No events found. Try checking the logs for details." | |
| source = "AI + Regex" if apis_available else "Regex only" | |
| message = f"β Extracted {len(schedule_events)} schedule items and {len(deadline_events)} deadlines! ({source})" | |
| return schedule_path, deadlines_path, message | |
| print("Building Gradio interface...", flush=True) | |
| # Gradio UI | |
| with gr.Blocks(theme=gr.themes.Soft(), title="π ProPlanner") as demo: | |
| gr.Markdown(""" | |
| # π ProPlanner β Hybrid AI Syllabus Extractor | |
| Uses **Google Gemini + Groq APIs (free)** + comprehensive regex patterns! | |
| **π Schedule CSV:** Class times, office hours | |
| **π Deadlines CSV:** Assignments, exams, projects | |
| """) | |
| with gr.Row(): | |
| with gr.Column(): | |
| pdf_input = gr.File(label="π Upload Syllabus PDF", file_types=[".pdf"]) | |
| submit_btn = gr.Button("π Extract Dates", variant="primary", size="lg") | |
| with gr.Column(): | |
| status_output = gr.Textbox(label="Status", value="Ready", interactive=False) | |
| with gr.Row(): | |
| schedule_output = gr.File(label="π Download Schedule") | |
| deadlines_output = gr.File(label="π Download Deadlines") | |
| gr.Markdown(""" | |
| ### Setup (Optional but Recommended): | |
| Add these free API keys to Repository Secrets for better results: | |
| 1. **GEMINI_API_KEY**: Get free at [Google AI Studio](https://aistudio.google.com/app/apikey) (15 req/min free) | |
| 2. **GROQ_API_KEY**: Get free at [Groq Console](https://console.groq.com/keys) (fast & free) | |
| **Without API keys:** Uses comprehensive regex patterns only (still works pretty well!) | |
| **With API keys:** Hybrid approach = best accuracy for any syllabus format | |
| """) | |
| submit_btn.click( | |
| fn=extract_dates, | |
| inputs=[pdf_input], | |
| outputs=[schedule_output, deadlines_output, status_output] | |
| ) | |
| print("β Gradio interface built successfully", flush=True) | |
| print("Launching app...", flush=True) | |
| if __name__ == "__main__": | |
| demo.launch() | |
| print("β App launched successfully", flush=True) | |
| except Exception as e: | |
| print(f"\nβ FATAL ERROR: {e}", file=sys.stderr, flush=True) | |
| traceback.print_exc() | |
| sys.exit(1) | |