Spaces:
No application file
No application file
Upload inference.py.py
Browse files- inference.py.py +114 -0
inference.py.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import json
|
| 3 |
+
import matplotlib
|
| 4 |
+
matplotlib.use("Agg")
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
import tempfile
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
from compare import compare_agents, aggregate_results
|
| 10 |
+
from llm_grader import evaluate_plan_with_llm
|
| 11 |
+
from eval import evaluate
|
| 12 |
+
|
| 13 |
+
def run_scheduler(episodes, num_tasks_override=None):
|
| 14 |
+
"""Run RL vs baseline comparison and return results + chart."""
|
| 15 |
+
from config import generate_tasks
|
| 16 |
+
import config
|
| 17 |
+
|
| 18 |
+
rl, base = compare_agents(int(episodes))
|
| 19 |
+
|
| 20 |
+
rl_stats = aggregate_results(rl)
|
| 21 |
+
base_stats = aggregate_results(base)
|
| 22 |
+
|
| 23 |
+
rl_rewards = [r[0] for r in rl]
|
| 24 |
+
base_rewards = [r[0] for r in base]
|
| 25 |
+
|
| 26 |
+
# Build comparison text
|
| 27 |
+
winner_reward = "RL β
" if rl_stats["avg_reward"] > base_stats["avg_reward"] else "Baseline"
|
| 28 |
+
winner_tasks = "RL β
" if rl_stats["avg_tasks_completed"] > base_stats["avg_tasks_completed"] else "Baseline"
|
| 29 |
+
winner_miss = "RL β
" if rl_stats["avg_missed_deadlines"] < base_stats["avg_missed_deadlines"] else "Baseline"
|
| 30 |
+
winner_stress = "RL β
" if rl_stats["avg_stress"] < base_stats["avg_stress"] else "Baseline"
|
| 31 |
+
|
| 32 |
+
text = f"""
|
| 33 |
+
=== RESULTS ({episodes} episodes) ===
|
| 34 |
+
|
| 35 |
+
Metric | RL Agent | Baseline | Winner
|
| 36 |
+
------------------------|-----------|-----------|--------
|
| 37 |
+
Avg Reward | {rl_stats['avg_reward']:<9} | {base_stats['avg_reward']:<9} | {winner_reward}
|
| 38 |
+
Avg Tasks Completed | {rl_stats['avg_tasks_completed']:<9} | {base_stats['avg_tasks_completed']:<9} | {winner_tasks}
|
| 39 |
+
Avg Missed Deadlines | {rl_stats['avg_missed_deadlines']:<9} | {base_stats['avg_missed_deadlines']:<9} | {winner_miss}
|
| 40 |
+
Avg Final Stress | {rl_stats['avg_stress']:<9} | {base_stats['avg_stress']:<9} | {winner_stress}
|
| 41 |
+
Avg Efficiency Score | {rl_stats['avg_efficiency_score']:<9} | {base_stats['avg_efficiency_score']:<9} |
|
| 42 |
+
|
| 43 |
+
Key Finding: RL agent learns to balance productivity and well-being dynamically.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
# LLM grade on last RL episode metrics
|
| 47 |
+
last_rl_metrics = rl[-1][1]
|
| 48 |
+
grade = evaluate_plan_with_llm(last_rl_metrics)
|
| 49 |
+
text += f"\n=== LLM EVALUATION (last episode) ===\nScore: {grade['score']}/10\n{grade['comment']}\n"
|
| 50 |
+
|
| 51 |
+
# Plot
|
| 52 |
+
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
|
| 53 |
+
fig.suptitle(f"RL Study Scheduler vs Baseline ({episodes} episodes)", fontsize=13, fontweight="bold")
|
| 54 |
+
|
| 55 |
+
ax = axes[0][0]
|
| 56 |
+
ax.plot(rl_rewards, color="#1D9E75", label="RL Agent", linewidth=1.5)
|
| 57 |
+
ax.plot(base_rewards, color="#D85A30", label="Baseline", linewidth=1.5, linestyle="--")
|
| 58 |
+
ax.set_title("Reward per Episode"); ax.set_xlabel("Episode"); ax.set_ylabel("Reward")
|
| 59 |
+
ax.legend(); ax.grid(True, alpha=0.3)
|
| 60 |
+
|
| 61 |
+
metrics_keys = ["avg_tasks_completed", "avg_missed_deadlines", "avg_efficiency_score", "avg_stress"]
|
| 62 |
+
labels = ["Tasks Completed", "Missed Deadlines", "Efficiency", "Avg Stress"]
|
| 63 |
+
colors = [["#1D9E75","#D85A30"]] * 4
|
| 64 |
+
|
| 65 |
+
for i, (key, label) in enumerate(zip(metrics_keys[1:], labels[1:])):
|
| 66 |
+
r, c = divmod(i+1, 2)
|
| 67 |
+
ax = axes[r][c]
|
| 68 |
+
vals = [rl_stats[key], base_stats[key]]
|
| 69 |
+
bars = ax.bar(["RL", "Baseline"], vals, color=["#1D9E75","#D85A30"])
|
| 70 |
+
ax.set_title(label); ax.grid(True, alpha=0.3, axis='y')
|
| 71 |
+
for bar in bars:
|
| 72 |
+
ax.text(bar.get_x()+bar.get_width()/2, bar.get_height()+0.01,
|
| 73 |
+
f'{bar.get_height():.2f}', ha='center', fontsize=10)
|
| 74 |
+
|
| 75 |
+
plt.tight_layout()
|
| 76 |
+
img_path = tempfile.mktemp(suffix=".png")
|
| 77 |
+
plt.savefig(img_path, dpi=130, bbox_inches="tight")
|
| 78 |
+
plt.close()
|
| 79 |
+
|
| 80 |
+
return text, img_path
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
with gr.Blocks(title="RL Study Scheduler") as iface:
|
| 84 |
+
gr.Markdown("""
|
| 85 |
+
# RL-Based Adaptive Study Scheduler
|
| 86 |
+
**Q-learning agent vs heuristic baseline** under cognitive constraints (energy, stress, focus).
|
| 87 |
+
|
| 88 |
+
The RL agent learns *when* to work, *when* to rest, and *which task* to prioritize β dynamically.
|
| 89 |
+
""")
|
| 90 |
+
|
| 91 |
+
with gr.Row():
|
| 92 |
+
ep_slider = gr.Slider(minimum=10, maximum=100, value=50, step=5, label="Number of Episodes")
|
| 93 |
+
run_btn = gr.Button("Run Simulation", variant="primary")
|
| 94 |
+
|
| 95 |
+
with gr.Row():
|
| 96 |
+
output_text = gr.Textbox(label="Results", lines=20)
|
| 97 |
+
output_img = gr.Image(label="Comparison Chart")
|
| 98 |
+
|
| 99 |
+
run_btn.click(fn=run_scheduler, inputs=[ep_slider], outputs=[output_text, output_img])
|
| 100 |
+
|
| 101 |
+
gr.Markdown("""
|
| 102 |
+
---
|
| 103 |
+
**How it works:**
|
| 104 |
+
- **State**: energy (0-100), stress (0-100), pending tasks, deadline urgency, difficulty
|
| 105 |
+
- **Actions**: DO_TASK | BREAK | SKIP | SWITCH
|
| 106 |
+
- **Reward**: +10 task done, -8 missed deadline, -10 burnout, +2 self-care break
|
| 107 |
+
- **RL**: Q-learning with deadline-aware state representation
|
| 108 |
+
""")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
iface.launch()
|
| 113 |
+
|
| 114 |
+
iface.launch()
|