Spaces:
Sleeping
Sleeping
File size: 7,684 Bytes
1a48c91 |
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 |
import matplotlib
matplotlib.use('Agg')
import gradio as gr
import gymnasium as gym
from stable_baselines3 import SAC
from stable_baselines3.common.vec_env import VecFrameStack, DummyVecEnv
import os
from huggingface_hub import hf_hub_download
import gym_laser # Registers env name for gym.make()
# Pre-trained model configurations (TODO: add models by hosting them on huggingface)
PRETRAINED_MODELS = {
"Random Policy": None,
"Upload Custom Model": "upload",
"SAC-UDR(1.5,2.5)": "sac-udr-narrow",
"SAC-UDR(1.0,9.0)": "sac-udr-wide-extra",
}
MAX_STEPS = 100_000 # large number for continuous simulation
def get_model_path(model_id):
"""Get the path to a pre-trained model."""
return f"pretrained-policies/{model_id}.zip"
def load_pretrained_model(model_id):
"""Load a pre-trained model."""
model = hf_hub_download(
repo_id=f"fracapuano/{model_id}", filename=f"{model_id}.zip"
)
return SAC.load(model)
def make_env_fn():
"""Helper function to create a single environment instance."""
return gym.make("LaserEnv", render_mode="rgb_array")
def initialize_environment():
"""Initializes the environment on app load."""
try:
env = DummyVecEnv([make_env_fn])
env = VecFrameStack(env, n_stack=5)
obs = env.reset()
state = {
"env": env,
"obs": obs,
"model": None,
"step_num": 0,
"current_b_integral": 2.0, # Store current B-integral in state
"model_filename": "Random Policy" # Default model name
}
return state
except Exception as e:
return None, f"Error: {e}"
def load_selected_model(state, model_selection, uploaded_file):
"""Loads a model based on selection (pre-trained or uploaded)."""
if state is None:
return state, gr.update()
try:
if model_selection == "Random Policy":
state["model"] = None
state["model_filename"] = "Random Policy"
state["obs"] = state["env"].reset()
state["step_num"] = 0
return state, gr.update()
elif model_selection == "Upload Custom Model":
if uploaded_file is None:
return state, "Please upload a model file.", gr.update()
model_filename = uploaded_file.name.split('/')[-1]
state["model"] = SAC.load(uploaded_file.name)
state["model_filename"] = model_filename
state["obs"] = state["env"].reset()
state["step_num"] = 0
return state, gr.update()
else:
model_id = PRETRAINED_MODELS[model_selection]
model = load_pretrained_model(model_id)
state["model"] = model
state["model_filename"] = model_selection
state["obs"] = state["env"].reset()
state["step_num"] = 0
return state, gr.update()
except Exception as e:
return state, f"Error loading model: {e}", gr.update()
def update_b_integral(state, b_integral):
"""Updates the B-integral value in the state without restarting simulation."""
if state is not None:
state["current_b_integral"] = b_integral
return state
def run_continuous_simulation(state):
"""Runs the simulation continuously, using the current B-integral from state."""
if not state or "env" not in state:
yield state, None, "Environment not ready."
return
env = state["env"]
obs = state["obs"]
step_num = state.get("step_num", 0)
# Run for a large number of steps to simulate "always-on"
for i in range(MAX_STEPS):
model = state.get("model")
model_filename = state.get("model_filename", "Random Policy")
current_b = state.get("current_b_integral", 2.0)
# Apply the current B-integral value from state
env.envs[0].unwrapped.laser.B = float(current_b)
if model:
action, _ = model.predict(obs, deterministic=True)
else:
action = env.action_space.sample().reshape(1, -1)
obs, _, done, _ = env.step(action)
frame = env.render()
if done[0]:
obs = env.reset()
step_num = 0
else:
step_num += 1
state["obs"] = obs
state["step_num"] = step_num
yield state, frame
with gr.Blocks(css="body {zoom: 90%}") as demo:
gr.Markdown("# Shaping Laser Pulses with Reinforcement Learning")
with gr.Tab("Demo"):
sim_state = gr.State()
with gr.Row():
b_slider = gr.Slider(
minimum=0,
maximum=10,
step=0.5,
value=2.0,
label="B-integral",
info="Adjust nonlinearity live during simulation.",
)
with gr.Row():
image_display = gr.Image(label="Environment Render", interactive=False, height=360)
with gr.Row():
with gr.Column():
model_selector = gr.Dropdown(
choices=list(PRETRAINED_MODELS.keys()),
value="Random Policy",
label="Model Selection",
info="Choose a pre-trained model or upload your own"
)
with gr.Row():
with gr.Column(scale=1):
model_uploader = gr.UploadButton(
"Upload Model (.zip)",
file_types=['.zip'],
elem_id="model-upload",
visible=False # Initially hidden
)
# Show/hide upload button based on selection
def update_upload_visibility(selection):
return gr.update(visible=(selection == "Upload Custom Model"))
model_selector.change(
fn=update_upload_visibility,
inputs=[model_selector],
outputs=[model_uploader]
)
# On page load, initialize and start the continuous simulation
init_event = demo.load(
fn=initialize_environment,
inputs=None,
outputs=[sim_state]
)
continuous_event = init_event.then(
fn=run_continuous_simulation,
inputs=[sim_state],
outputs=[sim_state, image_display]
)
# When model selection changes, load the selected model
model_change_event = model_selector.change(
fn=load_selected_model,
inputs=[sim_state, model_selector, model_uploader],
outputs=[sim_state, model_uploader],
cancels=[continuous_event]
).then(
fn=run_continuous_simulation,
inputs=[sim_state],
outputs=[sim_state, image_display]
)
# When a custom model is uploaded, load it
model_upload_event = model_uploader.upload(
fn=load_selected_model,
inputs=[sim_state, model_selector, model_uploader],
outputs=[sim_state, model_uploader],
cancels=[continuous_event]
).then(
fn=run_continuous_simulation,
inputs=[sim_state],
outputs=[sim_state, image_display]
)
# When B-integral slider changes, just update the value in state (no restart needed)
b_slider.change(
fn=update_b_integral,
inputs=[sim_state, b_slider],
outputs=[sim_state]
)
with gr.Tab("About"):
with open("copy.md", "r") as f:
gr.Markdown(f.read())
demo.launch() |