for file in os.listdir(agent_dir):
if file.startswith("agent_"):
os.remove(os.path.join(agent_dir, file))
for file in os.listdir(config_dir):
if file.startswith("config_"):
os.remove(os.path.join(config_dir, file))
return "Reset complete. All temporary files removed."
The rest of the file remains the same
def create_dynamic_agent_customization_ui():
with gr.Blocks() as dynamic_agent_customization:
gr.Markdown("## Dynamic Agent Customization")
with gr.Row():
agent_file = gr.File(label="Upload Agent File (.py)")
config_file = gr.File(label="Upload Config File (.yml)")
with gr.Accordion("Advanced Settings"):
with gr.Row():
learning_rate = gr.Slider(minimum=0.0001, maximum=0.1, value=0.001, label="Learning Rate")
batch_size = gr.Slider(minimum=8, maximum=256, step=8, value=32, label="Batch Size")
epochs = gr.Slider(minimum=1, maximum=100, step=1, value=10, label="Epochs")
with gr.Row():
gamma = gr.Slider(minimum=0.1, maximum=1.0, value=0.99, label="Gamma")
epsilon = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, label="Epsilon")
epsilon_min = gr.Slider(minimum=0.0, maximum=1.0, value=0.01, label="Epsilon Min")
epsilon_decay = gr.Slider(minimum=0.9, maximum=1.0, value=0.995, label="Epsilon Decay")
with gr.Row():
ngpu = gr.Textbox(value="-1", label="GPU to be used")
thread_num = gr.Slider(minimum=1, maximum=16, step=1, value=4, label="Number of threads")
with gr.Row():
prefix = gr.Textbox(value="test", label="Prefix for this running process")
seed = gr.Number(value=None, label="Seed for pytorch backend")
with gr.Row():
debug = gr.Checkbox(value=True, label="Debug mode")
interface = gr.Dropdown(choices=["libsumo", "traci"], value="libsumo", label="Interface type")
with gr.Row():
delay_type = gr.Dropdown(choices=["apx", "real"], value="apx", label="Method of calculating delay")
task = gr.Textbox(value="tsc", label="Task type to run")
with gr.Row():
agent = gr.Textbox(value="frap", label="Agent type")
world = gr.Dropdown(choices=["cityflow", "sumo"], value="sumo", label="Simulator type")
with gr.Row():
network = gr.Textbox(value="sumo1x1", label="Network name")
dataset = gr.Textbox(value="onfly", label="Type of dataset in training process")
upload_button = gr.Button("Upload and Deploy Agent")
reset_button = gr.Button("Reset")
output = gr.Textbox(label="Output")
upload_button.click(fn=upload_agent, inputs=[agent_file, config_file, learning_rate, batch_size, epochs, gamma, epsilon, epsilon_min, epsilon_decay, ngpu, thread_num, prefix, seed, debug, interface, delay_type, task, agent, world, network, dataset], outputs=output)
reset_button.click(fn=reset, outputs=output)
return dynamic_agent_customization"
It seems you're experiencing an issue where your new Streamlit code isn't logging outputs in the same way as your old Gradio code. Specifically, the logging outputs from your drl_deployment.py script aren't being displayed in your Streamlit app. This is a common issue when transitioning between frameworks or when handling subprocesses and their outputs.
Let's delve into why this is happening and how you can fix it.
Understanding the Issue
In your Gradio code, you used subprocess.Popen along with communicate() to capture stdout and stderr from your drl_deployment.py script:
This approach waits for the subprocess to finish execution and then captures all the output at once.
In your Streamlit code, you're using subprocess.Popen and attempting to read the output line by line:
for line in drl_process.stdout:
output_queue.put(line.strip())
However, you're likely encountering buffering issues which prevent the immediate capture and display of logging outputs. Additionally, if drl_deployment.py is configured to log outputs to a file or if the logging outputs are not being flushed properly, they may not appear in stdout or stderr as expected.
Steps to Resolve the Issue
1. Ensure Logging Outputs to stdout or stderr in drl_deployment.py
First, check how logging is configured in drl_deployment.py. The logging outputs need to be directed to stdout or stderr so that they can be captured by the parent process (your Streamlit app).
By setting stream=sys.stdout, you direct all logging outputs to stdout.
2. Use Unbuffered Output in the Subprocess
When running the subprocess, you can use the -u flag with the Python interpreter to force unbuffered binary stdout and stderr. This ensures that outputs are flushed immediately and can be read line by line.
3. Read stdout and stderr Simultaneously Using Threads
Reading stdout and stderr sequentially can cause deadlocks if one buffer fills up. To avoid this, you can read both streams simultaneously using separate threads.
In your main thread, you should continuously read from the output_queue and update the Streamlit text area. This allows the user to see outputs in real-time.
Update the Output Loop in Your upload_agent Function:
output_text = ""
while subprocess_thread.is_alive() or not output_queue.empty():
try:
line = output_queue.get_nowait()
outputs.append(line)
# Update the output text area
output_text += line + '\n'
output_placeholder.text_area("Output", value=output_text, height=300)
except queue.Empty:
time.sleep(0.1)
5. Increase the Timeout or Remove It
Your current code has a 5-minute timeout which could cut off outputs if the process takes longer.
Adjust or Remove the Timeout:
# Remove or adjust the timeout condition
# if time.time() - start_time > 300: # 5 minutes timeout
# outputs.append("Deployment timed out after 5 minutes.")
# break
6. Ensure Proper Exception Handling
Make sure that any exceptions in your run_subprocess function are being properly handled and that they log meaningful messages to the output_queue.
7. Verify That drl_deployment.py Is Not Logging to a File
If drl_deployment.py is configured to log outputs to a file rather than stdout or stderr, you need to adjust it to log to the console or read the log file after execution.
Option A: Log to Console
As shown earlier, configure logging to output to stdout or stderr.
Option B: Read Log File After Execution
If logging to a file is necessary, read the log file contents after the subprocess completes and display them in Streamlit.
# After drl_process.wait()
log_file_path = os.path.join(workspace_dir, 'path_to_log_file.log')
if os.path.exists(log_file_path):
with open(log_file_path, 'r') as file:
log_contents = file.read()
output_queue.put(log_contents)
8. Compare with Your Gradio Code
In your Gradio code, you directly captured stdout and stderr after process completion. You can replicate this behavior in your Streamlit code if immediate real-time output isn't necessary.
After making the above changes, test your Streamlit app to see if the logging outputs from drl_deployment.py are now displayed as expected.
Summary of Changes
Configure drl_deployment.py to log to stdout or stderr.
Use the -u flag in your subprocess command for unbuffered output.
Read both stdout and stderr simultaneously using separate threads.
Continuously update the output in Streamlit to display logs in real-time.
Adjust or remove any timeouts that might interrupt long-running processes.
Ensure exceptions are properly handled and logged.
By implementing these changes, your Streamlit app should now capture and display logging outputs similarly to how your Gradio app did.
Additional Considerations
Buffering Issues: Python's output is often buffered, which can cause delays in outputting logs. Using the -u flag forces unbuffered output.
Thread Safety: Ensure that shared resources (like your outputs list) are thread-safe or appropriately synchronized.
Performance: Continuously updating the Streamlit text area can be resource-intensive for large outputs. Consider batching updates or limiting the displayed logs.
Error Handling: Extend your exception handling to catch and log any specific errors that may arise during the subprocess execution.
If you continue to experience issues, please provide more details about any errors or unexpected behaviors, and I'll be happy to help further.