Spaces:
No application file
No application file
Download app.py from dee2004/rl-study-scheduler: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/spaces/dee2004/rl-study-scheduler/resolve/main/app.py
- Command line
-
hf download hf://spaces/dee2004/rl-study-scheduler/app.py
-
curl -L -o app.py https://huggingface.co/spaces/dee2004/rl-study-scheduler/resolve/main/app.py
11.4 kB
| """ | |
| 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() | |