Update app.py
Browse files
app.py
CHANGED
|
@@ -1,45 +1,128 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
#
|
| 5 |
-
st.
|
| 6 |
|
| 7 |
-
#
|
|
|
|
| 8 |
st.image("./nadi-lok-image.png")
|
| 9 |
|
| 10 |
-
# Sidebar
|
| 11 |
st.sidebar.header("Upload CSV File")
|
| 12 |
uploaded_file = st.sidebar.file_uploader("Choose a CSV file", type="csv")
|
| 13 |
|
| 14 |
-
# Display the uploaded file's content if a file is uploaded
|
| 15 |
if uploaded_file:
|
| 16 |
-
# Read the CSV file
|
| 17 |
try:
|
| 18 |
-
|
| 19 |
st.sidebar.success("File uploaded successfully!")
|
| 20 |
st.sidebar.write("Preview of the uploaded file:")
|
| 21 |
-
st.sidebar.dataframe(
|
|
|
|
| 22 |
except Exception as e:
|
| 23 |
st.sidebar.error(f"Error reading file: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
# Main app
|
| 26 |
with st.form("user_form"):
|
| 27 |
-
# Display a header
|
| 28 |
st.header("Welcome to Streamlit Form!")
|
| 29 |
-
|
| 30 |
-
# Add a text input widget
|
| 31 |
user_input = st.text_input("Enter your name:")
|
| 32 |
-
|
| 33 |
-
# Add a slider widget
|
| 34 |
age = st.slider("Select your age:", 0, 100, 25)
|
| 35 |
-
|
| 36 |
-
# Add form buttons
|
| 37 |
submit_button = st.form_submit_button("Submit")
|
| 38 |
|
| 39 |
-
# Handle form submission
|
| 40 |
if submit_button:
|
| 41 |
if user_input:
|
| 42 |
st.success(f"Hello, {user_input}!")
|
| 43 |
st.info(f"You are {age} years old.")
|
| 44 |
else:
|
| 45 |
-
st.error("Please enter your name.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
+
import os
|
| 4 |
+
import requests
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
|
| 8 |
+
# — Page config
|
| 9 |
+
st.set_page_config(page_title="App with CSV Upload & AI Agent", layout="wide")
|
| 10 |
|
| 11 |
+
# — Title & image
|
| 12 |
+
st.title("App with Form and CSV-Backed AI Agent")
|
| 13 |
st.image("./nadi-lok-image.png")
|
| 14 |
|
| 15 |
+
# — Sidebar: CSV upload (from Code 1)
|
| 16 |
st.sidebar.header("Upload CSV File")
|
| 17 |
uploaded_file = st.sidebar.file_uploader("Choose a CSV file", type="csv")
|
| 18 |
|
|
|
|
| 19 |
if uploaded_file:
|
|
|
|
| 20 |
try:
|
| 21 |
+
df = pd.read_csv(uploaded_file)
|
| 22 |
st.sidebar.success("File uploaded successfully!")
|
| 23 |
st.sidebar.write("Preview of the uploaded file:")
|
| 24 |
+
st.sidebar.dataframe(df.head())
|
| 25 |
+
csv_text = df.to_csv(index=False)
|
| 26 |
except Exception as e:
|
| 27 |
st.sidebar.error(f"Error reading file: {e}")
|
| 28 |
+
df = None
|
| 29 |
+
csv_text = None
|
| 30 |
+
else:
|
| 31 |
+
df = None
|
| 32 |
+
csv_text = None
|
| 33 |
|
| 34 |
+
# — Main app: user form (from Code 1)
|
| 35 |
with st.form("user_form"):
|
|
|
|
| 36 |
st.header("Welcome to Streamlit Form!")
|
|
|
|
|
|
|
| 37 |
user_input = st.text_input("Enter your name:")
|
|
|
|
|
|
|
| 38 |
age = st.slider("Select your age:", 0, 100, 25)
|
|
|
|
|
|
|
| 39 |
submit_button = st.form_submit_button("Submit")
|
| 40 |
|
|
|
|
| 41 |
if submit_button:
|
| 42 |
if user_input:
|
| 43 |
st.success(f"Hello, {user_input}!")
|
| 44 |
st.info(f"You are {age} years old.")
|
| 45 |
else:
|
| 46 |
+
st.error("Please enter your name.")
|
| 47 |
+
|
| 48 |
+
# — AI Agent section (from Code 2)
|
| 49 |
+
st.subheader("🔎 CSV-Backed AI Agent")
|
| 50 |
+
|
| 51 |
+
# Load OpenAI key
|
| 52 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 53 |
+
if not api_key:
|
| 54 |
+
st.error("❌ Secret OPENAI_API_KEY not set! Add it under Settings → Secrets.")
|
| 55 |
+
st.stop()
|
| 56 |
+
|
| 57 |
+
# Show loaded CSV info
|
| 58 |
+
if df is not None:
|
| 59 |
+
st.markdown(f"**Loaded CSV:** {df.shape[0]} rows × {df.shape[1]} columns")
|
| 60 |
+
|
| 61 |
+
# Prompt input
|
| 62 |
+
prompt = st.text_area(
|
| 63 |
+
"Enter your prompt for the agent",
|
| 64 |
+
placeholder="e.g. Which products have price > 100?",
|
| 65 |
+
height=150
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
# Run the agent
|
| 69 |
+
if st.button("Run Agent"):
|
| 70 |
+
if df is None:
|
| 71 |
+
st.error("Please upload a CSV file first.")
|
| 72 |
+
elif not prompt.strip():
|
| 73 |
+
st.error("Please enter a prompt.")
|
| 74 |
+
else:
|
| 75 |
+
# Build chat messages
|
| 76 |
+
system_msg = {
|
| 77 |
+
"role": "system",
|
| 78 |
+
"content": (
|
| 79 |
+
"You are an AI agent that reads the provided CSV data and answers the user's query. "
|
| 80 |
+
"Return your answer as JSON only (no extra text)."
|
| 81 |
+
)
|
| 82 |
+
}
|
| 83 |
+
csv_msg = {
|
| 84 |
+
"role": "system",
|
| 85 |
+
"content": f"CSV Data:\n{csv_text}\n<End of CSV>"
|
| 86 |
+
}
|
| 87 |
+
user_msg = {"role": "user", "content": prompt}
|
| 88 |
+
|
| 89 |
+
# Call OpenAI API
|
| 90 |
+
response = requests.post(
|
| 91 |
+
"https://api.openai.com/v1/chat/completions",
|
| 92 |
+
headers={
|
| 93 |
+
"Authorization": f"Bearer {api_key}",
|
| 94 |
+
"Content-Type": "application/json",
|
| 95 |
+
},
|
| 96 |
+
json={
|
| 97 |
+
"model": "gpt-3.5-turbo",
|
| 98 |
+
"messages": [system_msg, csv_msg, user_msg],
|
| 99 |
+
"temperature": 0,
|
| 100 |
+
"max_tokens": 1500,
|
| 101 |
+
},
|
| 102 |
+
timeout=60,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
if response.status_code != 200:
|
| 106 |
+
st.error(f"API Error {response.status_code}: {response.text}")
|
| 107 |
+
else:
|
| 108 |
+
answer = response.json()["choices"][0]["message"]["content"]
|
| 109 |
+
# Strip code fences & extract JSON
|
| 110 |
+
txt = re.sub(r'```(?:json)?', '', answer).strip()
|
| 111 |
+
start = txt.find("{")
|
| 112 |
+
end = txt.rfind("}") + 1
|
| 113 |
+
parsed = None
|
| 114 |
+
if start >= 0 and end > 0:
|
| 115 |
+
frag = txt[start:end]
|
| 116 |
+
frag = re.sub(r',\s*([}\]])', r'\1', frag)
|
| 117 |
+
try:
|
| 118 |
+
parsed = json.loads(frag)
|
| 119 |
+
except json.JSONDecodeError:
|
| 120 |
+
parsed = None
|
| 121 |
+
|
| 122 |
+
# Display result
|
| 123 |
+
if parsed is not None:
|
| 124 |
+
st.subheader("✅ JSON Output")
|
| 125 |
+
st.json(parsed)
|
| 126 |
+
else:
|
| 127 |
+
st.subheader("🔍 Raw Output")
|
| 128 |
+
st.text(answer)
|