""" RL-Based Adaptive Study Scheduler — Gradio App Hugging Face Space: dee2004/rl-study-scheduler """ import gradio as gr import numpy as np import json import threading from env import StudyEnv, Task from agent_q import QLearningAgent from baseline import HeuristicBaseline from compare import train_agent, evaluate_agent, evaluate_baseline, make_tasks # ── Global trained agent (lazy-loaded once) ───────────────────────────────── _agent = None _agent_lock = threading.Lock() def get_agent(): global _agent if _agent is None: with _agent_lock: if _agent is None: agent, _ = train_agent(n_episodes=300) _agent = agent return _agent # ── Helpers ────────────────────────────────────────────────────────────────── def parse_tasks(task_text: str): """Parse user-entered tasks from the text area.""" tasks = [] for line in task_text.strip().splitlines(): line = line.strip() if not line or line.startswith("#"): continue parts = [p.strip() for p in line.split(",")] if len(parts) < 4: continue try: name = parts[0] difficulty = int(parts[1]) deadline = int(parts[2]) subject = parts[3] tasks.append(Task(name, difficulty, deadline, subject)) except ValueError: pass return tasks if tasks else make_tasks() def run_simulation(task_text, n_episodes, agent_type): """Run a full simulation and return schedule + metrics.""" tasks = parse_tasks(task_text) if agent_type == "RL Agent (Q-Learning)": agent, _ = train_agent(n_episodes=int(n_episodes), tasks_fn=lambda: [ Task(t.name, t.difficulty, t.deadline, t.subject) for t in tasks ]) env = StudyEnv(tasks=tasks) env.initial_tasks = tasks state = env.reset() done = False while not done: action = agent.choose_action(state, greedy=True) state, _, done, _ = env.step(action) else: baseline = HeuristicBaseline() env = StudyEnv(tasks=tasks) env.initial_tasks = tasks state = env.reset() done = False while not done: action = baseline.choose_action(state, env) state, _, done, _ = env.step(action) stats = env.get_stats() history = env.history # Format schedule table schedule_rows = [] for h in history: schedule_rows.append([ h["step"], h["action"], h["detail"], f"{h['reward']:+.1f}", f"{h['energy']:.0f}", f"{h['stress']:.0f}", f"{h['focus']:.0f}", ]) # Format metrics metrics_md = f""" ### 📊 Session Results | Metric | Value | |--------|-------| | ✅ Tasks Completed | **{stats['tasks_completed']} / {stats['tasks_total']}** | | ❌ Missed Deadlines | **{stats['missed_deadlines']}** | | 😰 Avg Stress | **{stats['avg_stress']:.1f}** | | 💰 Total Reward | **{stats['total_reward']:.1f}** | | ⚡ Efficiency | **{stats['efficiency']:.1f}%** | """ return schedule_rows, metrics_md def run_comparison_ui(task_text, n_episodes): """Run RL vs Baseline comparison and return results.""" tasks = parse_tasks(task_text) tasks_fn = lambda: [Task(t.name, t.difficulty, t.deadline, t.subject) for t in tasks] agent, reward_history = train_agent(n_episodes=int(n_episodes), tasks_fn=tasks_fn) rl_stats = evaluate_agent(agent, tasks_fn=tasks_fn) bl_stats = evaluate_baseline(tasks_fn=tasks_fn) rows = [] icons = { "tasks_completed": "✅", "missed_deadlines": "❌", "avg_stress": "😰", "total_reward": "💰", "efficiency": "⚡", } labels = { "tasks_completed": "Tasks Completed", "missed_deadlines": "Missed Deadlines", "avg_stress": "Avg Stress", "total_reward": "Total Reward", "efficiency": "Efficiency %", } # Determine winner (higher is better, except missed_deadlines and avg_stress) lower_is_better = {"missed_deadlines", "avg_stress"} for key in ["tasks_completed", "missed_deadlines", "avg_stress", "total_reward", "efficiency"]: rl_val = rl_stats[key] bl_val = bl_stats[key] if key in lower_is_better: winner = "🤖 RL" if rl_val < bl_val else ("📏 Baseline" if bl_val < rl_val else "🤝 Tie") else: winner = "🤖 RL" if rl_val > bl_val else ("📏 Baseline" if bl_val > rl_val else "🤝 Tie") rows.append([ f"{icons.get(key,'')} {labels[key]}", f"{rl_val:.2f}", f"{bl_val:.2f}", winner, ]) # Training curve summary window = 50 recent_avg = np.mean(reward_history[-window:]) if len(reward_history) >= window else np.mean(reward_history) summary_md = f""" ### 🏆 Comparison Complete Training episodes: **{n_episodes}** | Recent avg reward (last {window} eps): **{recent_avg:.1f}** > The RL agent learns to balance energy, stress, and deadlines through experience. > The heuristic baseline uses fixed rules and cannot adapt. """ return rows, summary_md # ── Default task text ──────────────────────────────────────────────────────── DEFAULT_TASKS = """\ # Format: Name, Difficulty(1-10), Deadline(days), Subject Math Exam Prep, 8, 1, Math Physics Assignment, 7, 2, Physics Essay Writing, 5, 3, English Chemistry Lab, 9, 1, Chemistry History Reading, 4, 4, History CS Project, 8, 2, CS Biology Notes, 5, 5, Biology Math Practice, 6, 3, Math """ # ── Gradio UI ──────────────────────────────────────────────────────────────── CSS = """ body { font-family: 'Segoe UI', sans-serif; } .gr-button-primary { background: #4f46e5 !important; } .metric-box { background: #f8fafc; border-radius: 8px; padding: 12px; } h1 { color: #1e1b4b; } """ with gr.Blocks( title="RL Study Scheduler", theme=gr.themes.Soft(primary_hue="indigo"), css=CSS, ) as demo: gr.Markdown(""" # 🧠 RL-Based Adaptive Study Scheduler **Q-Learning agent vs Heuristic baseline** for cognitive-aware study planning. > *Adaptive scheduling under stress is not a sorting problem — it's a **learning** problem.* """) with gr.Tabs(): # ── Tab 1: Simulate ────────────────────────────────────────────────── with gr.Tab("📅 Run Schedule"): gr.Markdown("Enter your tasks and run the scheduler to get an adaptive study plan.") with gr.Row(): with gr.Column(scale=1): task_input = gr.Textbox( label="📚 Your Tasks", value=DEFAULT_TASKS, lines=12, placeholder="Name, Difficulty, Deadline(days), Subject", ) with gr.Row(): episodes_slider = gr.Slider( minimum=50, maximum=500, value=200, step=50, label="Training Episodes (RL only)", ) agent_choice = gr.Radio( choices=["RL Agent (Q-Learning)", "Heuristic Baseline"], value="RL Agent (Q-Learning)", label="Scheduler Type", ) run_btn = gr.Button("▶ Run Scheduler", variant="primary") with gr.Column(scale=2): metrics_out = gr.Markdown("*Click 'Run Scheduler' to see results.*") schedule_table = gr.Dataframe( headers=["Step", "Action", "Detail", "Reward", "Energy", "Stress", "Focus"], label="📋 Step-by-Step Schedule", interactive=False, wrap=True, ) run_btn.click( fn=run_simulation, inputs=[task_input, episodes_slider, agent_choice], outputs=[schedule_table, metrics_out], ) # ── Tab 2: Compare ─────────────────────────────────────────────────── with gr.Tab("⚔️ RL vs Baseline"): gr.Markdown("Compare the RL agent head-to-head against the heuristic baseline over multiple evaluation runs.") with gr.Row(): with gr.Column(scale=1): task_input2 = gr.Textbox( label="📚 Your Tasks", value=DEFAULT_TASKS, lines=12, ) episodes_slider2 = gr.Slider( minimum=50, maximum=500, value=200, step=50, label="Training Episodes", ) compare_btn = gr.Button("⚔️ Compare", variant="primary") with gr.Column(scale=2): compare_summary = gr.Markdown("*Click 'Compare' to start.*") compare_table = gr.Dataframe( headers=["Metric", "🤖 RL Agent", "📏 Baseline", "🏆 Winner"], label="Comparison Results", interactive=False, ) compare_btn.click( fn=run_comparison_ui, inputs=[task_input2, episodes_slider2], outputs=[compare_table, compare_summary], ) # ── Tab 3: About ───────────────────────────────────────────────────── with gr.Tab("ℹ️ About"): gr.Markdown(""" ## How It Works ### MDP Formulation | Component | Details | |-----------|---------| | **State** | energy, stress, focus, pending tasks, min deadline, max difficulty | | **Actions** | DO_TASK · BREAK · SKIP · SWITCH | | **Agent** | Tabular Q-Learning with ε-greedy exploration | ### Reward Function | Event | Reward | |-------|--------| | Task completion | +10 | | Difficult task (difficulty > 7) | +5 | | Urgent task (deadline < 2) | +4 | | Missed deadline | −8 | | Burnout (energy < 20) | −10 | | High stress (> 80) | −5 | | Context switching | −2 | | Self-care break | +2 | ### Why RL? | Requirement | Rule-based | RL | |---|---|---| | Sequential decisions | ❌ | ✅ | | Delayed rewards (rest now → no burnout later) | ❌ | ✅ | | Adapts to energy/stress state | ❌ | ✅ | | Learns from experience | ❌ | ✅ | **Tech Stack**: Python · NumPy · Gradio """) if __name__ == "__main__": demo.launch()