Spaces:
Configuration error
Configuration error
File size: 6,206 Bytes
1e3b91d | 1 2 3 4 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | import streamlit as st
import pandas as pd
import re
from data_utils import load_and_clean_excel
from llm_utils import generate_response
from viz_utils import generate_chart
st.set_page_config(page_title="Excel Assistant", layout="wide")
# Initialize session state for chat history
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "df" not in st.session_state:
st.session_state.df = None
if "cleaned_columns" not in st.session_state:
st.session_state.cleaned_columns = None
if "awaiting_followup" not in st.session_state:
st.session_state.awaiting_followup = False
def clean_response(response):
"""Clean up the LLM response by removing code blocks and unnecessary explanations"""
# Remove any code blocks
response = re.sub(r'```[\s\S]*?```', '', response)
# Remove any inline code
response = re.sub(r'`.*?`', '', response)
# Remove lines that look like code (heuristic)
lines = response.split('\n')
cleaned_lines = [line for line in lines if not line.strip().startswith(('import ', 'from ', 'def ', 'class ', '#', '//', 'plt.', 'fig,', 'ax.'))]
# Join the remaining lines
cleaned_response = '\n'.join(cleaned_lines)
# Remove multiple newlines
cleaned_response = re.sub(r'\n\s*\n', '\n\n', cleaned_response)
return cleaned_response.strip()
# Function to handle question submission
def handle_question(question):
if question:
with st.spinner("Generating response..."):
# Check if this is a chart request
is_chart_request = any(chart_type in question.lower() for chart_type in [
"chart", "plot", "graph", "visualize", "visualization", "histogram", "bar", "pie", "scatter", "line"
])
# Get response from LLM
response = generate_response(
question,
st.session_state.df,
st.session_state.cleaned_columns
)
# Clean up the response
cleaned_response = clean_response(response)
# Generate chart if needed
chart_fig = generate_chart(response, st.session_state.df)
# For chart requests, keep the response extra minimal if a chart was generated
if is_chart_request and chart_fig:
# Extract only the essential information about the chart
chart_info = re.search(r'(bar chart|histogram|line chart|scatter plot|pie chart|box plot).*?(of|between|showing|with).*?[.!]', cleaned_response, re.IGNORECASE)
if chart_info:
cleaned_response = chart_info.group(0)
# Save chart to session state if it exists
if chart_fig:
setattr(st.session_state, f"chart_for_{len(st.session_state.chat_history)}", chart_fig)
# Add to history
st.session_state.chat_history.append((question, cleaned_response))
# Set awaiting followup flag
st.session_state.awaiting_followup = True
def main():
st.title("Excel Assistant")
st.write("Upload your Excel file and ask questions about your data.")
# Sidebar for file upload and options
with st.sidebar:
st.header("Upload Data")
uploaded_file = st.file_uploader("Choose an Excel file", type=["xlsx"])
if uploaded_file is not None:
try:
# Process the uploaded file
df, cleaned_columns = load_and_clean_excel(uploaded_file)
st.session_state.df = df
st.session_state.cleaned_columns = cleaned_columns
st.success("File loaded successfully!")
# Display column mappings
st.subheader("Column Cleanup")
mapping_df = pd.DataFrame({
"Original": list(cleaned_columns.keys()),
"Cleaned": list(cleaned_columns.values())
})
st.dataframe(mapping_df)
# History section in sidebar
st.subheader("Question History")
if st.session_state.chat_history:
for i, (q, _) in enumerate(st.session_state.chat_history):
st.text(f"{i+1}. {q}")
except Exception as e:
st.error(f"Error loading file: {str(e)}")
# Main content area
if st.session_state.df is not None:
# Display dataframe preview
st.subheader("Data Preview")
st.dataframe(st.session_state.df.head(10))
# Create a chat container
chat_container = st.container()
# Display chat history in main area
with chat_container:
for idx, (question, answer) in enumerate(st.session_state.chat_history):
st.markdown(f"**You:** {question}")
st.markdown(f"**Assistant:** {answer}")
# If a chart was generated for this response, display it
if hasattr(st.session_state, f"chart_for_{idx}"):
chart_fig = getattr(st.session_state, f"chart_for_{idx}")
if chart_fig:
st.pyplot(chart_fig)
st.markdown("---")
# Show follow-up prompt if awaiting follow-up
if st.session_state.awaiting_followup and st.session_state.chat_history:
st.markdown("**Assistant:** Would you like to know anything else about your data?")
# Question input using a form to handle submission properly
with st.form(key="question_form", clear_on_submit=True):
user_question = st.text_input("Ask a question about your data:")
submit_button = st.form_submit_button("Ask")
if submit_button and user_question:
handle_question(user_question)
st.experimental_rerun()
else:
st.info("Please upload an Excel file to get started.")
if __name__ == "__main__":
main() |