Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +147 -38
src/streamlit_app.py
CHANGED
@@ -1,40 +1,149 @@
|
|
1 |
-
import altair as alt
|
2 |
-
import numpy as np
|
3 |
-
import pandas as pd
|
4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
st.
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
+
from code_editor import code_editor
|
3 |
+
import json
|
4 |
+
import requests
|
5 |
+
import contextlib
|
6 |
+
import io
|
7 |
+
import streamlit.components.v1 as st1
|
8 |
|
9 |
+
# --- Sidebar info ---
|
10 |
+
st.sidebar.title("💡 About")
|
11 |
+
st.sidebar.info(
|
12 |
+
"This app generates Python code from your prompt using an AI model API.\n\n"
|
13 |
+
"Enter your prompt and click 'Generate Code' to see the result."
|
14 |
+
)
|
15 |
+
st.sidebar.markdown("---")
|
16 |
+
st.sidebar.write("Created with ❤️ using Streamlit and code_editor.")
|
17 |
+
st.sidebar.write("You can also edit your pyhton code in the code editor and lively run it.")
|
18 |
+
st.sidebar.subheader("📦 Install Python Library")
|
19 |
+
with st.sidebar.form("install_lib_form"):
|
20 |
+
lib_name = st.text_input("Library name (e.g., numpy, pandas)")
|
21 |
+
install_btn = st.form_submit_button("Install with pip")
|
22 |
+
if install_btn and lib_name.strip():
|
23 |
+
with st.spinner(f"Installing {lib_name}..."):
|
24 |
+
import subprocess
|
25 |
+
import sys
|
26 |
+
try:
|
27 |
+
result = subprocess.run(
|
28 |
+
[sys.executable, "-m", "pip", "install", lib_name],
|
29 |
+
capture_output=True, text=True
|
30 |
+
)
|
31 |
+
if result.returncode == 0:
|
32 |
+
st.success(f"Successfully installed `{lib_name}`.")
|
33 |
+
else:
|
34 |
+
st.error(f"Error installing `{lib_name}`:\n{result.stderr}")
|
35 |
+
except Exception as e:
|
36 |
+
st.error(f"Exception: {e}")
|
37 |
+
st.title("🧠 Python Code Generator & Runner")
|
38 |
+
concepts=st.selectbox("Here are several examples that you can be familiar with the concept of our WebApp.",
|
39 |
+
("Write a Python program to plot the Gaussian distribution. Use Streamlit and Plotly Express for plotting.",
|
40 |
+
"Create a Python program to make the K-means algorithm with sklearn and plot the clusters. Use Streamlit and matplotlib for plotting the object.",
|
41 |
+
"Write a Python program to read my CSV file and describe it for me. The name of the CSV file is 'test.csv'"))
|
42 |
+
st.markdown("Here is the selected example prompt")
|
43 |
+
st.write(concepts)
|
44 |
+
# --- Initialize session state ---
|
45 |
+
if "code" not in st.session_state:
|
46 |
+
st.session_state.code = "print('Hello, world!')"
|
47 |
+
if "edited_code" not in st.session_state:
|
48 |
+
st.session_state.edited_code = st.session_state.code
|
49 |
+
|
50 |
+
# --- Prompt input ---
|
51 |
+
st.write("### Enter your prompt to generate Python code:")
|
52 |
+
user_prompt = st.text_area("Prompt", "Write a function to add two numbers")
|
53 |
+
|
54 |
+
# --- Buttons ---
|
55 |
+
col1, col2 = st.columns(2)
|
56 |
+
with col1:
|
57 |
+
generate_button = st.button("🚀 Generate Code")
|
58 |
+
with col2:
|
59 |
+
run_button = st.button("▶️ Run Code")
|
60 |
+
|
61 |
+
# --- Code generation logic ---
|
62 |
+
if generate_button:
|
63 |
+
if user_prompt.strip():
|
64 |
+
with st.spinner("Generating code..."):
|
65 |
+
try:
|
66 |
+
api_url = "https://11434-dep-01jxanw2ryrzcfn2bv59eg2r87-d.cloudspaces.litng.ai/api/chat"
|
67 |
+
s = requests.Session()
|
68 |
+
s.headers.update({"Authorization": "Bearer bf54d08f-e88a-4a4a-bd14-444c984eaa6e"})
|
69 |
+
response = s.post(api_url, json={
|
70 |
+
"model": "hf.co/alibidaran/LLAMA3-inatructive_Python-GGUF:Q8_0",
|
71 |
+
"messages": [
|
72 |
+
{"role": "system", "content": """
|
73 |
+
You are an expert Python programmer. You task contians following instructions:
|
74 |
+
- You should answer the user questions about python.
|
75 |
+
- The output format must contain only python codes with ```python syntax format.
|
76 |
+
- You must use the user input variables in your code as code place holder.
|
77 |
+
"""},
|
78 |
+
{"role": "user", "content": user_prompt},
|
79 |
+
],
|
80 |
+
"options": {
|
81 |
+
'temperature': 0.5,
|
82 |
+
'top_p': 0.95
|
83 |
+
},
|
84 |
+
})
|
85 |
+
full_response = ""
|
86 |
+
for line in response.iter_lines():
|
87 |
+
if line:
|
88 |
+
data = json.loads(line.decode("utf-8"))
|
89 |
+
content = data.get("message", {}).get("content", "")
|
90 |
+
full_response += content
|
91 |
+
if data.get("done", False):
|
92 |
+
break
|
93 |
+
except Exception as e:
|
94 |
+
full_response = f"# Error: {str(e)}"
|
95 |
+
# Clean markdown formatting
|
96 |
+
if full_response.startswith("```python"):
|
97 |
+
full_response = full_response[9:]
|
98 |
+
if full_response.endswith("```"):
|
99 |
+
full_response = full_response[:-3]
|
100 |
+
# Update session state
|
101 |
+
st.session_state.code = full_response
|
102 |
+
st.session_state.edited_code = full_response
|
103 |
+
else:
|
104 |
+
st.warning("Please enter a prompt before generating.")
|
105 |
+
|
106 |
+
# --- Code Editor ---
|
107 |
+
editor_result = code_editor(
|
108 |
+
st.session_state.edited_code,
|
109 |
+
lang="python",
|
110 |
+
height=300
|
111 |
+
)
|
112 |
+
|
113 |
+
# Update edited_code only if not empty
|
114 |
+
if editor_result and "text" in editor_result and editor_result["text"].strip() != "":
|
115 |
+
st.session_state.edited_code = editor_result["text"]
|
116 |
+
|
117 |
+
if run_button:
|
118 |
+
st.write("### 🧪 Output:")
|
119 |
+
print(st.session_state.edited_code)
|
120 |
+
# if 'edited_code' in st.session_state.edited_code:
|
121 |
+
# if 'matplotlib.pyplot' in st.session_state.edited_code:
|
122 |
+
|
123 |
+
|
124 |
+
|
125 |
+
try:
|
126 |
+
# Prepare an output buffer to capture printed text
|
127 |
+
output_buffer = io.StringIO()
|
128 |
+
exec_globals = {}
|
129 |
+
|
130 |
+
# Capture stdout during execution
|
131 |
+
with contextlib.redirect_stdout(output_buffer):
|
132 |
+
exec(st.session_state.edited_code, exec_globals)
|
133 |
+
|
134 |
+
# Show stdout (printed output)
|
135 |
+
output_text = output_buffer.getvalue()
|
136 |
+
if output_text.strip():
|
137 |
+
st.code(output_text, language="text")
|
138 |
+
else:
|
139 |
+
st.info("Code ran, but produced no printed output.")
|
140 |
+
|
141 |
+
# Optional: Display returned variables or functions
|
142 |
+
user_vars = {k: v for k, v in exec_globals.items() if not k.startswith("__")}
|
143 |
+
if user_vars:
|
144 |
+
st.write("**Variables in scope:**")
|
145 |
+
st.json(user_vars)
|
146 |
+
|
147 |
+
except Exception as e:
|
148 |
+
st.error(f"Execution error: {e}")
|
149 |
+
st1.iframe("https://cloudhand-sdk-xlsh.vercel.app/",width=400)
|