Spaceai / app.py
Artificial-superintelligence's picture
Update app.py
0f94234 verified
raw
history blame
3.11 kB
import streamlit as st
import subprocess
import os
import shutil
import uuid
from pathlib import Path
import atexit
# Generate a unique workspace for the user
session_id = str(uuid.uuid4())
workspace_dir = f"temp_workspace_{session_id}"
Path(workspace_dir).mkdir(parents=True, exist_ok=True)
# Helper function to execute shell commands
def run_shell_command(command):
try:
result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT, text=True)
return result
except subprocess.CalledProcessError as e:
return f"Error: {e.output}"
# Cleanup workspace when the script exits
def cleanup_workspace():
if os.path.exists(workspace_dir):
shutil.rmtree(workspace_dir)
atexit.register(cleanup_workspace)
# Custom CSS for styling
st.markdown(
"""
<style>
.stButton>button {
background-color: #4CAF50;
color: white;
border: none;
padding: 10px 20px;
text-align: center;
text-decoration: none;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border-radius: 5px;
}
.stButton>button:hover {
background-color: #45a049;
}
textarea {
font-family: "Courier New", monospace;
font-size: 14px;
}
</style>
""",
unsafe_allow_html=True,
)
st.title("Advanced Streamlit IDE")
# Editor for writing Python code
st.subheader("Code Editor")
default_code = """import streamlit as st
st.title("Welcome to the Advanced Streamlit IDE!")
st.write("Start coding your Python project here.")"""
code = st.text_area("Write your Python code below:", value=default_code, height=300)
# Option to install packages
st.subheader("Install Python Packages")
packages = st.text_input("Enter package names separated by space (e.g., numpy pandas):")
if st.button("Install Packages"):
with st.spinner("Installing packages..."):
install_command = f"pip install --target={workspace_dir} {packages}"
install_output = run_shell_command(install_command)
st.text(install_output)
# Run the code in a temporary workspace
if st.button("Run Code"):
temp_file_path = os.path.join(workspace_dir, "temp_app.py")
with open(temp_file_path, "w") as temp_file:
temp_file.write(code)
with st.spinner("Running your code..."):
run_command = f"PYTHONPATH={workspace_dir} python {temp_file_path}"
run_output = run_shell_command(run_command)
st.text(run_output)
# Export code
if st.button("Export Code"):
temp_file_path = os.path.join(workspace_dir, "temp_app.py")
if os.path.exists(temp_file_path):
with open(temp_file_path, "r") as temp_file:
exported_code = temp_file.read()
st.download_button("Download Code", data=exported_code, file_name="exported_code.py", mime="text/plain")
else:
st.error("No code to export!")
st.markdown("---")
st.info(
"""
- Write and execute Python code in a temporary workspace.
- Install and use packages dynamically within your session.
- All data is deleted once you leave the site.
"""
)