Update app.py
Browse files
app.py
CHANGED
|
@@ -1,193 +1,65 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 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 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
messages=messages,
|
| 67 |
-
)
|
| 68 |
-
|
| 69 |
-
response_message = response.choices[0].message
|
| 70 |
-
python_code = match_code_blocks(response_message.content)
|
| 71 |
-
|
| 72 |
-
if python_code:
|
| 73 |
-
code_interpreter_results = code_interpret(e2b_code_interpreter, python_code)
|
| 74 |
-
return code_interpreter_results, response_message.content
|
| 75 |
-
else:
|
| 76 |
-
st.warning(f"Failed to match any Python code in model's response")
|
| 77 |
-
return None, response_message.content
|
| 78 |
-
|
| 79 |
-
def upload_dataset(code_interpreter: Sandbox, uploaded_file) -> str:
|
| 80 |
-
dataset_path = f"./{uploaded_file.name}"
|
| 81 |
-
|
| 82 |
-
try:
|
| 83 |
-
code_interpreter.files.write(dataset_path, uploaded_file)
|
| 84 |
-
return dataset_path
|
| 85 |
-
except Exception as error:
|
| 86 |
-
st.error(f"Error during file upload: {error}")
|
| 87 |
-
raise error
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def main():
|
| 91 |
-
"""Main Streamlit application."""
|
| 92 |
-
st.set_page_config(page_title="📊 AI Data Visualization Agent", page_icon="📊", layout="wide")
|
| 93 |
-
|
| 94 |
-
st.title("📊 AI Data Visualization Agent")
|
| 95 |
-
st.write("Upload your dataset and ask questions about it!")
|
| 96 |
-
|
| 97 |
-
# Initialize session state variables
|
| 98 |
-
if 'together_api_key' not in st.session_state:
|
| 99 |
-
st.session_state.together_api_key = ''
|
| 100 |
-
if 'e2b_api_key' not in st.session_state:
|
| 101 |
-
st.session_state.e2b_api_key = ''
|
| 102 |
-
if 'model_name' not in st.session_state:
|
| 103 |
-
st.session_state.model_name = ''
|
| 104 |
-
|
| 105 |
-
# Sidebar for API keys and model configuration
|
| 106 |
-
with st.sidebar:
|
| 107 |
-
st.header("🔑 API Keys and Model Configuration")
|
| 108 |
-
st.session_state.together_api_key = st.text_input("Together AI API Key", type="password")
|
| 109 |
-
st.info("💡 Everyone gets a free $1 credit by Together AI - AI Acceleration Cloud platform")
|
| 110 |
-
st.markdown("[Get Together AI API Key](https://api.together.ai/signin)")
|
| 111 |
-
|
| 112 |
-
st.session_state.e2b_api_key = st.text_input("Enter E2B API Key", type="password")
|
| 113 |
-
st.markdown("[Get E2B API Key](https://e2b.dev/docs/legacy/getting-started/api-key)")
|
| 114 |
-
|
| 115 |
-
# Add model selection dropdown
|
| 116 |
-
model_options = {
|
| 117 |
-
"Meta-Llama 3.1 405B": "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo",
|
| 118 |
-
"DeepSeek V3": "deepseek-ai/DeepSeek-V3",
|
| 119 |
-
"Qwen 2.5 7B": "Qwen/Qwen2.5-7B-Instruct-Turbo",
|
| 120 |
-
"Meta-Llama 3.3 70B": "meta-llama/Llama-3.3-70B-Instruct-Turbo"
|
| 121 |
-
}
|
| 122 |
-
st.session_state.model_name = st.selectbox(
|
| 123 |
-
"Select Model",
|
| 124 |
-
options=list(model_options.keys()),
|
| 125 |
-
index=0 # Default to first option
|
| 126 |
-
)
|
| 127 |
-
st.session_state.model_name = model_options[st.session_state.model_name]
|
| 128 |
-
|
| 129 |
-
# Main content layout
|
| 130 |
-
col1, col2 = st.columns([1, 2]) # Split the main content into two columns
|
| 131 |
-
|
| 132 |
-
with col1:
|
| 133 |
-
st.header("📂 Upload Dataset")
|
| 134 |
-
uploaded_file = st.file_uploader("Choose a CSV file", type="csv", key="file_uploader")
|
| 135 |
-
|
| 136 |
-
if uploaded_file is not None:
|
| 137 |
-
# Display dataset with toggle
|
| 138 |
-
df = pd.read_csv(uploaded_file)
|
| 139 |
-
st.write("### Dataset Preview")
|
| 140 |
-
show_full = st.checkbox("Show full dataset")
|
| 141 |
-
if show_full:
|
| 142 |
-
st.dataframe(df)
|
| 143 |
-
else:
|
| 144 |
-
st.write("Preview (first 5 rows):")
|
| 145 |
-
st.dataframe(df.head())
|
| 146 |
-
|
| 147 |
-
with col2:
|
| 148 |
-
if uploaded_file is not None:
|
| 149 |
-
st.header("❓ Ask a Question")
|
| 150 |
-
query = st.text_area(
|
| 151 |
-
"What would you like to know about your data?",
|
| 152 |
-
"Can you compare the average cost for two people between different categories?",
|
| 153 |
-
height=100
|
| 154 |
-
)
|
| 155 |
-
|
| 156 |
-
if st.button("Analyze", type="primary", key="analyze_button"):
|
| 157 |
-
if not st.session_state.together_api_key or not st.session_state.e2b_api_key:
|
| 158 |
-
st.error("Please enter both API keys in the sidebar.")
|
| 159 |
-
else:
|
| 160 |
-
with Sandbox(api_key=st.session_state.e2b_api_key) as code_interpreter:
|
| 161 |
-
# Upload the dataset
|
| 162 |
-
dataset_path = upload_dataset(code_interpreter, uploaded_file)
|
| 163 |
-
|
| 164 |
-
# Pass dataset_path to chat_with_llm
|
| 165 |
-
code_results, llm_response = chat_with_llm(code_interpreter, query, dataset_path)
|
| 166 |
-
|
| 167 |
-
# Display LLM's text response
|
| 168 |
-
st.header("🤖 AI Response")
|
| 169 |
-
st.write(llm_response)
|
| 170 |
-
|
| 171 |
-
# Display results/visualizations
|
| 172 |
-
if code_results:
|
| 173 |
-
st.header("📊 Analysis Results")
|
| 174 |
-
for result in code_results:
|
| 175 |
-
if hasattr(result, 'png') and result.png: # Check if PNG data is available
|
| 176 |
-
# Decode the base64-encoded PNG data
|
| 177 |
-
png_data = base64.b64decode(result.png)
|
| 178 |
-
|
| 179 |
-
# Convert PNG data to an image and display it
|
| 180 |
-
image = Image.open(BytesIO(png_data))
|
| 181 |
-
st.image(image, caption="Generated Visualization", use_container_width=True)
|
| 182 |
-
elif hasattr(result, 'figure'): # For matplotlib figures
|
| 183 |
-
fig = result.figure # Extract the matplotlib figure
|
| 184 |
-
st.pyplot(fig) # Display using st.pyplot
|
| 185 |
-
elif hasattr(result, 'show'): # For plotly figures
|
| 186 |
-
st.plotly_chart(result)
|
| 187 |
-
elif isinstance(result, (pd.DataFrame, pd.Series)):
|
| 188 |
-
st.dataframe(result)
|
| 189 |
-
else:
|
| 190 |
-
st.write(result)
|
| 191 |
-
|
| 192 |
-
if __name__ == "__main__":
|
| 193 |
-
main()
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import openai
|
| 3 |
+
import streamlit as st
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
|
| 6 |
+
# Analyze using OpenAI
|
| 7 |
+
def get_openai_insights(api_key, prompt):
|
| 8 |
+
openai.api_key = api_key
|
| 9 |
+
response = openai.Completion.create(
|
| 10 |
+
engine="text-davinci-003",
|
| 11 |
+
prompt=prompt,
|
| 12 |
+
max_tokens=500,
|
| 13 |
+
temperature=0.5
|
| 14 |
+
)
|
| 15 |
+
return response["choices"][0]["text"].strip()
|
| 16 |
+
|
| 17 |
+
# Streamlit app
|
| 18 |
+
def main():
|
| 19 |
+
st.title("Excel Data Visualization with OpenAI Insights")
|
| 20 |
+
|
| 21 |
+
# Input OpenAI API Key
|
| 22 |
+
api_key = st.text_input("Enter your OpenAI API Key", type="password")
|
| 23 |
+
if not api_key:
|
| 24 |
+
st.warning("Please enter your OpenAI API key to proceed.")
|
| 25 |
+
return
|
| 26 |
+
|
| 27 |
+
# File upload
|
| 28 |
+
excel_file = st.file_uploader("Upload the Excel File", type=["xls", "xlsx"])
|
| 29 |
+
|
| 30 |
+
if excel_file:
|
| 31 |
+
# Load Excel data
|
| 32 |
+
excel_data = pd.ExcelFile(excel_file)
|
| 33 |
+
st.sidebar.header("Select a Sheet to Visualize")
|
| 34 |
+
sheet_name = st.sidebar.selectbox("Sheet Name", excel_data.sheet_names)
|
| 35 |
+
|
| 36 |
+
if sheet_name:
|
| 37 |
+
data = pd.read_excel(excel_data, sheet_name=sheet_name)
|
| 38 |
+
st.subheader(f"Data from Sheet: {sheet_name}")
|
| 39 |
+
st.dataframe(data)
|
| 40 |
+
|
| 41 |
+
# Option to generate insights using OpenAI
|
| 42 |
+
st.header("Generate AI Insights")
|
| 43 |
+
if st.button("Get Insights from OpenAI"):
|
| 44 |
+
with st.spinner("Generating insights..."):
|
| 45 |
+
try:
|
| 46 |
+
data_sample = data.head(5).to_csv(index=False)
|
| 47 |
+
prompt = f"Analyze the following data and provide key insights:\n\n{data_sample}"
|
| 48 |
+
insights = get_openai_insights(api_key, prompt)
|
| 49 |
+
st.success("AI Insights Generated!")
|
| 50 |
+
st.text_area("AI Insights:", insights, height=200)
|
| 51 |
+
except openai.error.OpenAIError as e:
|
| 52 |
+
st.error(f"Error with OpenAI API: {e}")
|
| 53 |
+
|
| 54 |
+
# Visualize numeric data
|
| 55 |
+
st.header("Visualize Data")
|
| 56 |
+
numeric_cols = data.select_dtypes(include="number").columns
|
| 57 |
+
if numeric_cols.any():
|
| 58 |
+
col_to_plot = st.selectbox("Select a Column to Plot", numeric_cols)
|
| 59 |
+
if col_to_plot:
|
| 60 |
+
fig, ax = plt.subplots()
|
| 61 |
+
data[col_to_plot].plot(kind="bar", ax=ax, title=f"{col_to_plot} Analysis")
|
| 62 |
+
st.pyplot(fig)
|
| 63 |
+
|
| 64 |
+
if __name__ == "__main__":
|
| 65 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|