import streamlit as st import subprocess import threading import os import pymongo # Track process and logs process = None log_lines = [] # Function to handle real-time log output def read_logs(process): global log_lines for line in iter(process.stdout.readline, ""): log_lines.append(line.strip()) # Append the string directly if len(log_lines) > 100: # Keep only the last 100 lines log_lines.pop(0) st.experimental_rerun() # Rerun the Streamlit app to refresh logs # Title st.title("Powers Control Panel ⚡") st.write("Use the buttons below to **start** or **stop** the `powers` Python process.") # MongoDB Connection Test mongo_uri = os.getenv("MONGO_URI") st.write(f"Connecting to MongoDB with URI: {mongo_uri}") try: client = pymongo.MongoClient(mongo_uri) client.admin.command('ping') # Test the connection st.success("Connected to MongoDB successfully!") except Exception as e: st.error(f"Failed to connect to MongoDB: {e}") # Start button: Installs dependencies and runs `powers` if st.button("Start Powers"): if process is None or process.poll() is not None: with st.spinner("Installing dependencies..."): subprocess.run(["pip3", "install", "-U", "-r", "requirements.txt"]) # Start the `powers` process and read logs in a separate thread process = subprocess.Popen(["python3", "-m", "powers"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) threading.Thread(target=read_logs, args=(process,), daemon=True).start() st.success("`powers` process started!") else: st.warning("`powers` is already running!") # Stop button: Terminates the `powers` process if st.button("Stop Powers"): if process is not None: process.terminate() # Stop the process process = None st.success("`powers` process stopped!") else: st.warning("No running process to stop.") # Display the status of the `powers` process if process and process.poll() is None: st.write("`powers` is **running**! 🚀") else: st.write("`powers` is **not running**.") # Display real-time logs st.subheader("Real-Time Logs 📜") if log_lines: st.text_area("Logs", "\n".join(log_lines), height=300) else: st.write("No logs yet. Logs will appear here when `powers` is running.")