import pandas as pd import openai import streamlit as st import matplotlib.pyplot as plt # Analyze using OpenAI def get_openai_insights(api_key, prompt): openai.api_key = api_key response = openai.Completion.create( engine="text-davinci-003", prompt=prompt, max_tokens=500, temperature=0.5 ) return response["choices"][0]["text"].strip() # Streamlit app def main(): st.title("Excel Data Visualization with OpenAI Insights") # Input OpenAI API Key api_key = st.text_input("Enter your OpenAI API Key", type="password") if not api_key: st.warning("Please enter your OpenAI API key to proceed.") return # File upload excel_file = st.file_uploader("Upload the Excel File", type=["xls", "xlsx"]) if excel_file: # Load Excel data excel_data = pd.ExcelFile(excel_file) st.sidebar.header("Select a Sheet to Visualize") sheet_name = st.sidebar.selectbox("Sheet Name", excel_data.sheet_names) if sheet_name: data = pd.read_excel(excel_data, sheet_name=sheet_name) st.subheader(f"Data from Sheet: {sheet_name}") st.dataframe(data) # Option to generate insights using OpenAI st.header("Generate AI Insights") if st.button("Get Insights from OpenAI"): with st.spinner("Generating insights..."): try: data_sample = data.head(5).to_csv(index=False) prompt = f"Analyze the following data and provide key insights:\n\n{data_sample}" insights = get_openai_insights(api_key, prompt) st.success("AI Insights Generated!") st.text_area("AI Insights:", insights, height=200) except openai.error.OpenAIError as e: st.error(f"Error with OpenAI API: {e}") # Visualize numeric data st.header("Visualize Data") numeric_cols = data.select_dtypes(include="number").columns if numeric_cols.any(): col_to_plot = st.selectbox("Select a Column to Plot", numeric_cols) if col_to_plot: fig, ax = plt.subplots() data[col_to_plot].plot(kind="bar", ax=ax, title=f"{col_to_plot} Analysis") st.pyplot(fig) if __name__ == "__main__": main()