PyAct / src /streamlit_app.py
alibidaran's picture
Update src/streamlit_app.py
962841a verified
import streamlit as st
from code_editor import code_editor
import json
import requests
import contextlib
import io
import streamlit.components.v1 as st1
import subprocess
import sys
import os
# --- Sidebar info ---
st.sidebar.title("💡 About")
st.sidebar.info(
"This app generates Python code from your prompt using an AI model API.\n\n"
"Enter your prompt and click 'Generate Code' to see the result."
)
st.sidebar.markdown("---")
st.sidebar.write("Created with ❤️ using Streamlit and code_editor.")
st.sidebar.write("You can also edit your pyhton code in the code editor and lively run it.")
st.sidebar.subheader("📦 Install Python Library")
with st.sidebar.form("install_lib_form"):
lib_name = st.text_input("Library name (e.g., numpy, pandas)")
install_btn = st.form_submit_button("Install with pip")
if install_btn and lib_name.strip():
with st.spinner(f"Installing {lib_name}..."):
try:
# Define target directory for installation
target_dir = "/.local/lib/python3.9/site-packages"
os.makedirs(target_dir, exist_ok=True)
# Add to sys.path so imports work immediately
if target_dir not in sys.path:
sys.path.insert(0, target_dir)
# Run pip install into target dir
result = subprocess.run(
[
sys.executable, "-m", "pip", "install",
lib_name,
"--no-cache-dir",
"--target", target_dir
],
capture_output=True, text=True
)
if result.returncode == 0:
st.success(f"Successfully installed `{lib_name}`.")
else:
st.error(f"Error installing `{lib_name}`:\n{result.stderr}")
except Exception as e:
st.error(f"Exception: {e}")
st.title("🧠 Python Code Generator & Runner")
concepts=st.selectbox("Here are several examples that you can be familiar with the concept of our WebApp.",
("Write a Python program to plot the Gaussian distribution. Use Streamlit and Plotly Express for plotting.",
"Create a Python program to make the K-means algorithm with sklearn and plot the clusters. Use Streamlit and matplotlib for plotting the object.",
"Write a Python program to read my CSV file and describe it for me. The name of the CSV file is 'test.csv'"))
st.markdown("Here is the selected example prompt")
st.write(concepts)
# --- Initialize session state ---
if "code" not in st.session_state:
st.session_state.code = "print('Hello, world!')"
if "edited_code" not in st.session_state:
st.session_state.edited_code = st.session_state.code
# --- Prompt input ---
st.write("### Enter your prompt to generate Python code:")
user_prompt = st.text_area("Prompt", "Write a function to add two numbers")
# --- Buttons ---
col1, col2 = st.columns(2)
with col1:
generate_button = st.button("🚀 Generate Code")
with col2:
run_button = st.button("▶️ Run Code")
# --- Code generation logic ---
if generate_button:
if user_prompt.strip():
with st.spinner("Generating code..."):
try:
api_url = "https://11434-dep-01jxanw2ryrzcfn2bv59eg2r87-d.cloudspaces.litng.ai/api/chat"
s = requests.Session()
s.headers.update({"Authorization": "Bearer bf54d08f-e88a-4a4a-bd14-444c984eaa6e"})
response = s.post(api_url, json={
"model": "hf.co/alibidaran/LLAMA3-inatructive_Python-GGUF:Q8_0",
"messages": [
{"role": "system", "content": """
You are an expert Python programmer. You task contians following instructions:
- You should answer the user questions about python.
- The output format must contain only python codes with ```python syntax format.
- You must use the user input variables in your code as code place holder.
"""},
{"role": "user", "content": user_prompt},
],
"options": {
'temperature': 0.5,
'top_p': 0.95
},
})
full_response = ""
for line in response.iter_lines():
if line:
data = json.loads(line.decode("utf-8"))
content = data.get("message", {}).get("content", "")
full_response += content
if data.get("done", False):
break
except Exception as e:
full_response = f"# Error: {str(e)}"
# Clean markdown formatting
if full_response.startswith("```python"):
full_response = full_response[9:]
if full_response.endswith("```"):
full_response = full_response[:-3]
# Update session state
st.session_state.code = full_response
st.session_state.edited_code = full_response
else:
st.warning("Please enter a prompt before generating.")
# --- Code Editor ---
editor_result = code_editor(
st.session_state.edited_code,
lang="python",
height=300
)
# Update edited_code only if not empty
if editor_result and "text" in editor_result and editor_result["text"].strip() != "":
st.session_state.edited_code = editor_result["text"]
if run_button:
st.write("### 🧪 Output:")
print(st.session_state.edited_code)
# if 'edited_code' in st.session_state.edited_code:
# if 'matplotlib.pyplot' in st.session_state.edited_code:
try:
# Prepare an output buffer to capture printed text
output_buffer = io.StringIO()
exec_globals = {}
# Capture stdout during execution
with contextlib.redirect_stdout(output_buffer):
exec(st.session_state.edited_code, exec_globals)
# Show stdout (printed output)
output_text = output_buffer.getvalue()
if output_text.strip():
st.code(output_text, language="text")
else:
st.info("Code ran, but produced no printed output.")
# # Optional: Display returned variables or functions
# user_vars = {k: v for k, v in exec_globals.items() if not k.startswith("__")}
# if user_vars:
# st.write("**Variables in scope:**")
# st.json(user_vars)
except Exception as e:
st.error(f"Execution error: {e}")
components.iframe(
src="https://cloudhand-sdk-lmpc.vercel.app/",
height=600)