File size: 11,359 Bytes
454eb1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
"""
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()