Loosebag commited on
Commit
2fc96b6
·
1 Parent(s): b605d24

feat(space): add gradio app and configure huggingface space runtime

Browse files
Files changed (3) hide show
  1. README.md +28 -123
  2. app.py +120 -0
  3. requirements.txt +1 -0
README.md CHANGED
@@ -1,135 +1,40 @@
1
  ---
2
- language: en
3
- tags:
4
- - reinforcement-learning
5
- - dqn
6
- - traffic-control
7
- - pytorch
8
- license: mit
9
- library_name: pytorch
10
- pipeline_tag: reinforcement-learning
11
  ---
12
 
13
  # RL-Based Adaptive Traffic Intelligence System
14
 
15
- A modular, production-style Reinforcement Learning project for adaptive traffic signal control.
16
 
17
- ## Problem Statement
18
- Traffic control is treated as a sequential decision-making problem. An agent selects signal actions each step to:
19
- - minimize waiting time
20
- - minimize queue length
21
- - maximize throughput
22
- - prioritize emergency vehicles
23
-
24
- ## Hugging Face Model Artifacts
25
- - `artifacts/dqn_state_dict.pt` (trained DQN weights)
26
- - `artifacts/model_config.json` (environment/training config snapshot)
27
- - `artifacts/model_metrics.json` (evaluation snapshot)
28
-
29
- ## Highlights
30
- - OpenEnv-style deterministic environment (`TrafficEnv`)
31
- - Dense multi-component reward (no sparse-only objective)
32
- - Fixed-time baseline controller for mandatory comparison
33
- - Lightweight PyTorch DQN (replay buffer, epsilon-greedy, target network)
34
- - Realistic traffic dynamics (stochastic arrivals, lane imbalance, peak/off-peak)
35
- - Emergency vehicle priority handling
36
- - Bonus multi-intersection decentralized simulator
37
- - Visualization + end-to-end demo pipeline
38
- - Skill-style modular wrappers for orchestration
39
-
40
- ## Architecture
41
- - `traffic_rl/env`: core environment + multi-intersection extension
42
- - `traffic_rl/reward`: reward engineering logic
43
- - `traffic_rl/baseline`: fixed-time control baseline
44
- - `traffic_rl/agent`: DQN and replay buffer
45
- - `traffic_rl/training`: training loop
46
- - `traffic_rl/evaluation`: metrics + policy comparison
47
- - `traffic_rl/visualization`: dashboard plots
48
- - `traffic_rl/demo`: demo pipeline runner
49
- - `traffic_rl/skills`: modular reusable wrappers
50
-
51
- ## State, Action, Reward
52
- ### State
53
- `[Q1,Q2,Q3,Q4,W1,W2,W3,W4,phase,ambulance_flag]`
54
-
55
- ### Action Space
56
- - `0`: hold current phase
57
- - `1`: switch/set NS green phase
58
- - `2`: switch/set EW green phase
59
-
60
- ### Reward
61
- `R_total = R_base + flow_bonus - congestion_penalty + emergency_bonus - switch_penalty`
62
-
63
- Where:
64
- - `R_base = - (queue_length + waiting_time)`
65
- - `flow_bonus` rewards throughput
66
- - `congestion_penalty` penalizes overloaded states
67
- - `emergency_bonus` rewards ambulance clearance and penalizes ambulance delay
68
- - `switch_penalty` discourages unstable phase flapping
69
-
70
- ## Quick Start
71
- Use the project-local virtual environment.
72
 
 
73
  ```powershell
74
- # run tests
75
  .\.venv\Scripts\python.exe -m pytest
76
-
77
- # run demo pipeline
78
  .\.venv\Scripts\python.exe run_demo.py --episodes 70 --eval-episodes 20 --output-dir outputs
79
  ```
80
 
81
- ## Load Saved Weights
82
- ```python
83
- import torch
84
- from traffic_rl.agent.dqn_agent import DQNAgent
85
-
86
- agent = DQNAgent(state_dim=10, action_dim=3)
87
- state_dict = torch.load("artifacts/dqn_state_dict.pt", map_location="cpu")
88
- agent.q_network.load_state_dict(state_dict)
89
- agent.sync_target()
90
- ```
91
-
92
- ## Demo Pipeline
93
- The demo performs:
94
- 1. fixed baseline simulation
95
- 2. RL training
96
- 3. RL evaluation
97
- 4. emergency-priority scenario
98
- 5. metrics + plots export
99
-
100
- Artifacts are saved to `outputs/`:
101
- - `metrics_summary.json`
102
- - `training_history.png`
103
- - `policy_comparison.png`
104
- - `fixed_trajectory.png`
105
- - `rl_trajectory.png`
106
-
107
- ## Measured Results (Demo Run)
108
- From `outputs/metrics_summary.json`:
109
-
110
- ### Baseline vs RL
111
- - Waiting time improvement: **9.82%**
112
- - Queue length improvement: **1.64%**
113
- - Throughput gain: **7.62%**
114
-
115
- ### Emergency Scenario
116
- - Baseline ambulance clearances: **1.0**
117
- - RL ambulance clearances: **2.0**
118
-
119
- ## Skill-Modular Components
120
- Reusable orchestration wrappers:
121
- - `env_builder_skill.py`
122
- - `reward_engineering_skill.py`
123
- - `baseline_skill.py`
124
- - `dqn_training_skill.py`
125
- - `evaluation_skill.py`
126
- - `visualization_skill.py`
127
-
128
- ## Test Coverage
129
- TDD tests include:
130
- - Environment reset/step contracts, deterministic behavior, non-negative state
131
- - Reward monotonicity and penalty/bonus triggers
132
- - Baseline phase alternation logic
133
- - DQN action validity and Q-value output shape
134
- - Training/evaluation smoke tests
135
- - Multi-intersection step contract
 
1
  ---
2
+ title: RL Traffic Intelligence
3
+ emoji: ??
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: gradio
7
+ sdk_version: 5.29.0
8
+ app_file: app.py
9
+ pinned: false
 
10
  ---
11
 
12
  # RL-Based Adaptive Traffic Intelligence System
13
 
14
+ A modular reinforcement learning project for adaptive traffic signal control.
15
 
16
+ ## What this Space does
17
+ - Runs a fixed-time baseline traffic controller
18
+ - Trains a lightweight DQN agent
19
+ - Compares baseline vs RL on:
20
+ - waiting time
21
+ - queue length
22
+ - throughput
23
+ - emergency handling
24
+ - Produces visual plots for training trends and policy comparison
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ ## Local run
27
  ```powershell
 
28
  .\.venv\Scripts\python.exe -m pytest
 
 
29
  .\.venv\Scripts\python.exe run_demo.py --episodes 70 --eval-episodes 20 --output-dir outputs
30
  ```
31
 
32
+ ## Project modules
33
+ - `traffic_rl/env` � environment and traffic dynamics
34
+ - `traffic_rl/reward` � reward engineering
35
+ - `traffic_rl/baseline` fixed-time baseline
36
+ - `traffic_rl/agent` � DQN + replay buffer
37
+ - `traffic_rl/training` training loop
38
+ - `traffic_rl/evaluation` � metric comparison
39
+ - `traffic_rl/visualization` � plotting dashboard
40
+ - `traffic_rl/skills` � modular wrappers
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+
6
+ import gradio as gr
7
+
8
+ from traffic_rl.env.traffic_env import TrafficEnv
9
+ from traffic_rl.evaluation.evaluator import (
10
+ compare_policies,
11
+ evaluate_agent,
12
+ evaluate_fixed_controller,
13
+ )
14
+ from traffic_rl.training.trainer import TrainingConfig, train_dqn
15
+ from traffic_rl.visualization.dashboard import plot_comparison, plot_training_history
16
+
17
+
18
+ def _default_env_config(ambulance_prob: float, seed: int) -> dict:
19
+ return {
20
+ "max_steps": 120,
21
+ "arrival_mode": "stochastic",
22
+ "lane_bias": (1.6, 0.8, 1.4, 0.6),
23
+ "peak_rates": (3.8, 2.2, 3.4, 1.5),
24
+ "offpeak_rates": (1.4, 0.9, 1.2, 0.7),
25
+ "peak_duration": 35,
26
+ "cycle_duration": 60,
27
+ "service_rate": 2,
28
+ "ambulance_spawn_prob": ambulance_prob,
29
+ "seed": seed,
30
+ }
31
+
32
+
33
+ def run_experiment(train_episodes: int, eval_episodes: int, ambulance_prob: float, seed: int):
34
+ env_config = _default_env_config(ambulance_prob=ambulance_prob, seed=seed)
35
+
36
+ baseline_metrics = evaluate_fixed_controller(
37
+ env_config=env_config,
38
+ episodes=eval_episodes,
39
+ switch_interval=5,
40
+ )
41
+
42
+ train_env = TrafficEnv(config=env_config)
43
+ cfg = TrainingConfig(
44
+ episodes=train_episodes,
45
+ max_steps=env_config["max_steps"],
46
+ batch_size=64,
47
+ target_sync_interval=10,
48
+ epsilon_decay=0.97,
49
+ seed=seed,
50
+ )
51
+
52
+ agent, history = train_dqn(env=train_env, config=cfg)
53
+ rl_metrics = evaluate_agent(agent=agent, env_config=env_config, episodes=eval_episodes)
54
+ improvement = compare_policies(baseline_metrics, rl_metrics)
55
+
56
+ run_dir = Path("outputs") / "space_runs" / datetime.now().strftime("%Y%m%d_%H%M%S")
57
+ run_dir.mkdir(parents=True, exist_ok=True)
58
+
59
+ train_plot = plot_training_history(history, output_dir=run_dir)["training_history"]
60
+ compare_plot = plot_comparison(baseline_metrics, rl_metrics, output_dir=run_dir)["policy_comparison"]
61
+
62
+ result = {
63
+ "baseline": baseline_metrics,
64
+ "rl": rl_metrics,
65
+ "improvement": improvement,
66
+ "config": {
67
+ "train_episodes": train_episodes,
68
+ "eval_episodes": eval_episodes,
69
+ "ambulance_prob": ambulance_prob,
70
+ "seed": seed,
71
+ },
72
+ }
73
+
74
+ summary_md = (
75
+ "## Run Summary\n"
76
+ f"- Waiting time improvement: **{improvement['waiting_time_improvement_pct']:.2f}%**\n"
77
+ f"- Queue length improvement: **{improvement['queue_length_improvement_pct']:.2f}%**\n"
78
+ f"- Throughput gain: **{improvement['throughput_gain_pct']:.2f}%**\n"
79
+ f"- Ambulance clearance gain: **{improvement['ambulance_clearance_gain_pct']:.2f}%**"
80
+ )
81
+
82
+ return result, summary_md, train_plot, compare_plot
83
+
84
+
85
+ def build_app() -> gr.Blocks:
86
+ with gr.Blocks(title="RL-Based Adaptive Traffic Intelligence") as demo:
87
+ gr.Markdown(
88
+ """
89
+ # ?? RL-Based Adaptive Traffic Intelligence System
90
+ Train and compare a DQN traffic controller against a fixed-time baseline.
91
+ This demo optimizes waiting time, queue length, throughput, and emergency handling.
92
+ """
93
+ )
94
+
95
+ with gr.Row():
96
+ train_episodes = gr.Slider(20, 200, value=70, step=10, label="Training Episodes")
97
+ eval_episodes = gr.Slider(5, 50, value=20, step=5, label="Evaluation Episodes")
98
+ with gr.Row():
99
+ ambulance_prob = gr.Slider(0.0, 0.4, value=0.08, step=0.01, label="Ambulance Spawn Probability")
100
+ seed = gr.Number(value=42, precision=0, label="Random Seed")
101
+
102
+ run_btn = gr.Button("Run RL vs Baseline", variant="primary")
103
+
104
+ metrics_json = gr.JSON(label="Metrics")
105
+ summary = gr.Markdown()
106
+ train_img = gr.Image(label="Training Trends")
107
+ compare_img = gr.Image(label="Policy Comparison")
108
+
109
+ run_btn.click(
110
+ fn=run_experiment,
111
+ inputs=[train_episodes, eval_episodes, ambulance_prob, seed],
112
+ outputs=[metrics_json, summary, train_img, compare_img],
113
+ )
114
+
115
+ return demo
116
+
117
+
118
+ if __name__ == "__main__":
119
+ app = build_app()
120
+ app.launch()
requirements.txt CHANGED
@@ -2,3 +2,4 @@ pytest
2
  numpy
3
  matplotlib
4
  torch
 
 
2
  numpy
3
  matplotlib
4
  torch
5
+ gradio