Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +243 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,245 @@
|
|
| 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 |
-
|
| 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 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import os
|
| 11 |
+
from database_center import db_transaction
|
| 12 |
+
import uuid
|
| 13 |
+
import dotenv
|
| 14 |
+
import os
|
| 15 |
+
from cloudhands import CloudHandsPayment
|
| 16 |
+
from streamlit_lottie import st_lottie, st_lottie_spinner
|
| 17 |
+
import json
|
| 18 |
+
import time
|
| 19 |
+
import openai
|
| 20 |
+
import dotenv
|
| 21 |
+
import os
|
| 22 |
+
dotenv.load_dotenv()
|
| 23 |
+
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
|
| 24 |
|
| 25 |
+
payment_key=os.environ['Payment_Key']
|
| 26 |
+
def load_local_lottie(path):
|
| 27 |
+
with open(path, 'r') as file:
|
| 28 |
+
return json.load(file)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def complete_payment(db_transaction):
|
| 34 |
+
if st.session_state.token :
|
| 35 |
+
chPay=st.session_state.chPay
|
| 36 |
+
try:
|
| 37 |
+
result = chPay.charge(
|
| 38 |
+
charge=0.5,
|
| 39 |
+
event_name="Sample cloudhands charge",
|
| 40 |
+
)
|
| 41 |
+
st.success(f"You payment is succeeded")
|
| 42 |
+
st.session_state.transaction_id=result.transaction_id
|
| 43 |
+
db_transaction.add({
|
| 44 |
+
'id':str(uuid.uuid4()),
|
| 45 |
+
'app':'app_title',
|
| 46 |
+
'transaction-id':result.transaction_id,
|
| 47 |
+
'price':0.5
|
| 48 |
+
|
| 49 |
+
})
|
| 50 |
+
except Exception as e:
|
| 51 |
+
st.error(f"Charge failed: {e}")
|
| 52 |
+
else:
|
| 53 |
+
st.error('Please generate your Tokens.')
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# Init payment handler once
|
| 57 |
+
if "chPay" not in st.session_state:
|
| 58 |
+
st.session_state.chPay = CloudHandsPayment(
|
| 59 |
+
author_key=payment_key
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
if "token" not in st.session_state:
|
| 63 |
+
st.session_state.token = None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@st.dialog("Payment link")
|
| 67 |
+
def pay():
|
| 68 |
+
chPay = st.session_state.chPay
|
| 69 |
+
|
| 70 |
+
# Step 1: Show auth link only once
|
| 71 |
+
auth_url = chPay.get_authorization_url()
|
| 72 |
+
st.link_button("Authenticate", url=auth_url)
|
| 73 |
+
|
| 74 |
+
# Step 2: User pastes the code
|
| 75 |
+
code = st.text_input("Place your code")
|
| 76 |
+
|
| 77 |
+
if st.button("Exchange Code"):
|
| 78 |
+
try:
|
| 79 |
+
token = chPay.exchange_code_for_token(code)
|
| 80 |
+
st.session_state.token = token
|
| 81 |
+
st.success("Code exchanged successfully! Token stored.")
|
| 82 |
+
except Exception as e:
|
| 83 |
+
st.error(f"Failed: {e}")
|
| 84 |
+
|
| 85 |
+
def respond_default_model(user_prompt):
|
| 86 |
+
url = "https://8000-01k36m8w3tq0w1hk9xwscmxs1c.cloudspaces.litng.ai/predict"
|
| 87 |
+
message = {"user_prompt": user_prompt}
|
| 88 |
+
response = requests.post(url, data=message)
|
| 89 |
+
#print(response.json())
|
| 90 |
+
full_response = response.json()['output'][0]
|
| 91 |
+
|
| 92 |
+
def respond_gpt5(user_prompt):
|
| 93 |
+
chat_engine=openai.OpenAI()
|
| 94 |
+
response = chat_engine.chat.completions.create(
|
| 95 |
+
model='gpt-5-mini',
|
| 96 |
+
messages=[{'role':'user','content':user_prompt}]
|
| 97 |
+
)
|
| 98 |
+
return response.choices[0].message.content.strip()
|
| 99 |
+
|
| 100 |
+
# --- Initialize session state ---
|
| 101 |
+
if "code" not in st.session_state:
|
| 102 |
+
st.session_state.code = "print('Hello, world!')"
|
| 103 |
+
if "edited_code" not in st.session_state:
|
| 104 |
+
st.session_state.edited_code = st.session_state.code
|
| 105 |
+
if 'db_transaction' not in st.session_state:
|
| 106 |
+
st.session_state.db_transaction = db_transaction
|
| 107 |
+
if 'loading_state' not in st.session_state:
|
| 108 |
+
st.session_state.loading_state = True
|
| 109 |
+
# --- Sidebar info ---
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
if st.session_state.loading_state:
|
| 113 |
+
with st_lottie_spinner(load_local_lottie('Hello World!.json'), key='hello'):
|
| 114 |
+
time.sleep(5)
|
| 115 |
+
st.session_state.loading_state = False
|
| 116 |
+
|
| 117 |
+
st.sidebar.title("💡 About")
|
| 118 |
+
st.sidebar.info(
|
| 119 |
+
"This app generates Python code from your prompt using an AI model API.\n\n"
|
| 120 |
+
"Enter your prompt and click 'Generate Code' to see the result."
|
| 121 |
+
)
|
| 122 |
+
st.sidebar.markdown("---")
|
| 123 |
+
st.sidebar.write("Created with ❤️ using Streamlit and code_editor.")
|
| 124 |
+
st.sidebar.write("You can also edit your pyhton code in the code editor and lively run it.")
|
| 125 |
+
st.sidebar.subheader("📦 Install Python Library")
|
| 126 |
+
with st.sidebar.form("install_lib_form"):
|
| 127 |
+
lib_name = st.text_input("Library name (e.g., numpy, pandas)")
|
| 128 |
+
install_btn = st.form_submit_button("Install with pip")
|
| 129 |
+
if install_btn and lib_name.strip():
|
| 130 |
+
with st.spinner(f"Installing {lib_name}..."):
|
| 131 |
+
try:
|
| 132 |
+
# Define target directory for installation
|
| 133 |
+
target_dir = "/.local/lib/python3.9/site-packages"
|
| 134 |
+
os.makedirs(target_dir, exist_ok=True)
|
| 135 |
+
|
| 136 |
+
# Add to sys.path so imports work immediately
|
| 137 |
+
if target_dir not in sys.path:
|
| 138 |
+
sys.path.insert(0, target_dir)
|
| 139 |
+
|
| 140 |
+
# Run pip install into target dir
|
| 141 |
+
result = subprocess.run(
|
| 142 |
+
[
|
| 143 |
+
sys.executable, "-m", "pip", "install",
|
| 144 |
+
lib_name,
|
| 145 |
+
"--no-cache-dir",
|
| 146 |
+
"--target", target_dir
|
| 147 |
+
],
|
| 148 |
+
capture_output=True, text=True
|
| 149 |
+
)
|
| 150 |
+
if result.returncode == 0:
|
| 151 |
+
st.success(f"Successfully installed `{lib_name}`.")
|
| 152 |
+
else:
|
| 153 |
+
st.error(f"Error installing `{lib_name}`:\n{result.stderr}")
|
| 154 |
+
except Exception as e:
|
| 155 |
+
st.error(f"Exception: {e}")
|
| 156 |
+
st.title("🧠 Python Code Generator & Runner")
|
| 157 |
+
Authenication=st.button('Authenicate')
|
| 158 |
+
if Authenication:
|
| 159 |
+
pay()
|
| 160 |
+
concepts=st.selectbox("Here are several examples that you can be familiar with the concept of our WebApp.",
|
| 161 |
+
("Write a Python program to plot the Gaussian distribution. Use Streamlit and Plotly Express for plotting.",
|
| 162 |
+
"Create a Python program to make the K-means algorithm with sklearn and plot the clusters. Use Streamlit and matplotlib for plotting the object.",
|
| 163 |
+
"Write a Python program to read my CSV file and describe it for me. The name of the CSV file is 'test.csv'"))
|
| 164 |
+
st.markdown("Here is the selected example prompt")
|
| 165 |
+
st.write(concepts)
|
| 166 |
+
|
| 167 |
+
# --- Prompt input ---
|
| 168 |
+
st.write("### Enter your prompt to generate Python code:")
|
| 169 |
+
model=st.pills('Select AI Model',["Default","gpt-5-mini"],selection_mode='single')
|
| 170 |
+
user_prompt = st.text_area("Prompt", "Write a function to add two numbers")
|
| 171 |
+
|
| 172 |
+
# --- Buttons ---
|
| 173 |
+
col1, col2 = st.columns(2)
|
| 174 |
+
with col1:
|
| 175 |
+
generate_button = st.button("🚀 Generate Code")
|
| 176 |
+
with col2:
|
| 177 |
+
run_button = st.button("▶️ Run Code")
|
| 178 |
+
|
| 179 |
+
# --- Code generation logic ---
|
| 180 |
+
if generate_button:
|
| 181 |
+
complete_payment(st.session_state.db_transaction)
|
| 182 |
+
if st.session_state.transaction_id:
|
| 183 |
+
if user_prompt.strip():
|
| 184 |
+
with st.spinner("Generating code..."):
|
| 185 |
+
try:
|
| 186 |
+
if model == "Default":
|
| 187 |
+
full_response = respond_default_model(user_prompt)
|
| 188 |
+
elif model == "gpt-5-mini":
|
| 189 |
+
full_response = respond_gpt5(user_prompt)
|
| 190 |
+
|
| 191 |
+
except Exception as e:
|
| 192 |
+
st.error(f"Error during code generation: {e}")
|
| 193 |
+
if full_response.startswith("```python"):
|
| 194 |
+
full_response = full_response[9:]
|
| 195 |
+
if full_response.endswith("```"):
|
| 196 |
+
full_response = full_response[:-3]
|
| 197 |
+
# Update session state
|
| 198 |
+
st.session_state.code = full_response
|
| 199 |
+
st.session_state.edited_code = full_response
|
| 200 |
+
else:
|
| 201 |
+
st.warning("Please enter a prompt before generating.")
|
| 202 |
+
|
| 203 |
+
# --- Code Editor ---
|
| 204 |
+
editor_result = code_editor(
|
| 205 |
+
st.session_state.edited_code,
|
| 206 |
+
lang="python",
|
| 207 |
+
height=300
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# Update edited_code only if not empty
|
| 211 |
+
if editor_result and "text" in editor_result and editor_result["text"].strip() != "":
|
| 212 |
+
st.session_state.edited_code = editor_result["text"]
|
| 213 |
+
|
| 214 |
+
if run_button:
|
| 215 |
+
st.write("### 🧪 Output:")
|
| 216 |
+
print(st.session_state.edited_code)
|
| 217 |
+
# if 'edited_code' in st.session_state.edited_code:
|
| 218 |
+
# if 'matplotlib.pyplot' in st.session_state.edited_code:
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
try:
|
| 223 |
+
# Prepare an output buffer to capture printed text
|
| 224 |
+
output_buffer = io.StringIO()
|
| 225 |
+
exec_globals = {}
|
| 226 |
+
|
| 227 |
+
# Capture stdout during execution
|
| 228 |
+
with contextlib.redirect_stdout(output_buffer):
|
| 229 |
+
exec(st.session_state.edited_code, exec_globals)
|
| 230 |
+
|
| 231 |
+
# Show stdout (printed output)
|
| 232 |
+
output_text = output_buffer.getvalue()
|
| 233 |
+
if output_text.strip():
|
| 234 |
+
st.code(output_text, language="text")
|
| 235 |
+
else:
|
| 236 |
+
st.info("Code ran, but produced no printed output.")
|
| 237 |
+
|
| 238 |
+
# # Optional: Display returned variables or functions
|
| 239 |
+
# user_vars = {k: v for k, v in exec_globals.items() if not k.startswith("__")}
|
| 240 |
+
# if user_vars:
|
| 241 |
+
# st.write("**Variables in scope:**")
|
| 242 |
+
# st.json(user_vars)
|
| 243 |
+
|
| 244 |
+
except Exception as e:
|
| 245 |
+
st.error(f"Execution error: {e}")
|