Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,74 +1,58 @@
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
st.
|
| 10 |
-
st.
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
try:
|
| 33 |
-
|
| 34 |
-
st.
|
| 35 |
-
|
| 36 |
-
# Initialize the Gemini LLM
|
| 37 |
-
llm = ChatGoogleGenerativeAI(
|
| 38 |
-
model="gemini-1.5-pro-latest", # Using the latest, most capable model
|
| 39 |
-
google_api_key=api_key,
|
| 40 |
-
temperature=0
|
| 41 |
-
)
|
| 42 |
-
|
| 43 |
-
# Create the Pandas DataFrame Agent
|
| 44 |
-
agent = create_pandas_dataframe_agent(
|
| 45 |
-
llm,
|
| 46 |
-
df,
|
| 47 |
-
verbose=True, # This will print the agent's thoughts in the log
|
| 48 |
-
allow_dangerous_code=True,
|
| 49 |
-
handle_parsing_errors=True # Helps with bad LLM outputs
|
| 50 |
-
)
|
| 51 |
-
|
| 52 |
-
# --- User Interaction ---
|
| 53 |
-
user_question = st.text_input("Ask a question about your data:")
|
| 54 |
-
|
| 55 |
-
if user_question:
|
| 56 |
-
with st.spinner("Analyzing..."):
|
| 57 |
-
try:
|
| 58 |
-
# Invoke the agent
|
| 59 |
-
response = agent.invoke(user_question)
|
| 60 |
-
st.write("### Answer")
|
| 61 |
-
st.success(response["output"])
|
| 62 |
-
|
| 63 |
-
except Exception as e:
|
| 64 |
-
# This is the most important error block
|
| 65 |
-
st.error(f"π΄ An error occurred while analyzing the data.")
|
| 66 |
-
st.write("Here is the full error message:")
|
| 67 |
-
# Print the full error stack trace to the app
|
| 68 |
-
st.exception(e)
|
| 69 |
-
|
| 70 |
except Exception as e:
|
| 71 |
-
st.error(f"
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
main()
|
|
|
|
| 1 |
+
import os
|
| 2 |
import streamlit as st
|
| 3 |
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
# --- CONFIG ---
|
| 8 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 9 |
+
if not GEMINI_API_KEY:
|
| 10 |
+
st.error("β Missing Gemini API key. Add it as a secret: GEMINI_API_KEY")
|
| 11 |
+
st.stop()
|
| 12 |
+
|
| 13 |
+
GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta"
|
| 14 |
+
CHAT_MODEL = "models/gemini-1.5-flash"
|
| 15 |
+
EMBED_MODEL = "models/embedding-001"
|
| 16 |
+
|
| 17 |
+
# --- Helper Functions ---
|
| 18 |
+
def get_embedding(text):
|
| 19 |
+
url = f"{GEMINI_BASE}/{EMBED_MODEL}:embedText?key={GEMINI_API_KEY}"
|
| 20 |
+
data = {"text": text}
|
| 21 |
+
r = requests.post(url, json=data)
|
| 22 |
+
r.raise_for_status()
|
| 23 |
+
return r.json()["embedding"]["value"]
|
| 24 |
+
|
| 25 |
+
def chat_with_gemini(prompt, context=""):
|
| 26 |
+
url = f"{GEMINI_BASE}/{CHAT_MODEL}:generateContent?key={GEMINI_API_KEY}"
|
| 27 |
+
payload = {
|
| 28 |
+
"contents": [
|
| 29 |
+
{"parts": [{"text": f"{context}\n\nUser question: {prompt}"}]}
|
| 30 |
+
]
|
| 31 |
+
}
|
| 32 |
+
r = requests.post(url, json=payload)
|
| 33 |
+
r.raise_for_status()
|
| 34 |
+
data = r.json()
|
| 35 |
+
return data["candidates"][0]["content"]["parts"][0]["text"]
|
| 36 |
+
|
| 37 |
+
# --- UI ---
|
| 38 |
+
st.title("π Data Analyst Agent (Gemini + Streamlit)")
|
| 39 |
+
st.write("Upload a CSV file and ask natural language questions about your data.")
|
| 40 |
+
|
| 41 |
+
uploaded = st.file_uploader("Upload CSV", type=["csv"])
|
| 42 |
+
|
| 43 |
+
if uploaded:
|
| 44 |
+
df = pd.read_csv(uploaded)
|
| 45 |
+
st.dataframe(df.head())
|
| 46 |
+
|
| 47 |
+
question = st.text_input("Ask a question about your data:")
|
| 48 |
+
if st.button("Analyze") and question:
|
| 49 |
+
# Summarize dataset for context
|
| 50 |
+
summary = f"Columns: {', '.join(df.columns)}. Example rows:\n{df.head(3).to_string(index=False)}"
|
| 51 |
try:
|
| 52 |
+
response = chat_with_gemini(question, summary)
|
| 53 |
+
st.markdown("### π¬ Gemini Answer:")
|
| 54 |
+
st.write(response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
except Exception as e:
|
| 56 |
+
st.error(f"Error: {e}")
|
| 57 |
+
else:
|
| 58 |
+
st.info("π Upload a CSV file to begin.")
|
|
|