naveenadama commited on
Commit
6e9d128
·
verified ·
1 Parent(s): dd86f23

Upload 6 files

Browse files
Files changed (6) hide show
  1. README.md +107 -12
  2. app.py +144 -54
  3. data_utils.py +76 -0
  4. llm_utils.py +178 -0
  5. requirements.txt +10 -1
  6. viz_utils.py +109 -0
README.md CHANGED
@@ -1,12 +1,107 @@
1
- ---
2
- title: Natural Language Chabot
3
- emoji: 💬
4
- colorFrom: yellow
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 5.0.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Excel Assistant
2
+
3
+ A Streamlit application that allows users to ask natural language questions about their Excel data and get answers using a Hugging Face LLM (TinyLlama-1.1B-Chat).
4
+
5
+ ## Features
6
+
7
+ - Upload Excel files (.xlsx) with up to 500 rows and 10-20 columns
8
+ - Automatic column name cleaning and normalization
9
+ - Natural language question answering about your data
10
+ - Automatic chart generation based on question context
11
+ - Question history tracking
12
+ - Support for complex data queries
13
+
14
+ ## Architecture
15
+
16
+ This project follows a modular structure:
17
+
18
+ - `app.py`: Main Streamlit application and UI
19
+ - `data_utils.py`: Excel file loading and data cleaning utilities
20
+ - `llm_utils.py`: LLM interaction and prompt handling
21
+ - `viz_utils.py`: Visualization generation based on LLM responses
22
+
23
+ ## Requirements
24
+
25
+ - Python 3.8+
26
+ - CUDA-compatible GPU recommended (but not required)
27
+ - Dependencies listed in `requirements.txt`
28
+
29
+ ## Installation
30
+
31
+ 1. Clone this repository:
32
+ ```
33
+ git clone https://github.com/yourusername/excel-assistant.git
34
+ cd excel-assistant
35
+ ```
36
+
37
+ 2. Create a virtual environment (recommended):
38
+ ```
39
+ python -m venv venv
40
+ source venv/bin/activate # On Windows: venv\Scripts\activate
41
+ ```
42
+
43
+ 3. Install the required packages:
44
+ ```
45
+ pip install -r requirements.txt
46
+ ```
47
+
48
+ ## Usage
49
+
50
+ 1. Start the Streamlit app:
51
+ ```
52
+ streamlit run app.py
53
+ ```
54
+
55
+ 2. Open your web browser and navigate to the URL displayed in your terminal (typically http://localhost:8501)
56
+
57
+ 3. Upload an Excel file using the sidebar upload button
58
+
59
+ 4. View the data preview and ask questions about your data
60
+
61
+ 5. Explore the generated charts and answers
62
+
63
+ ## Example Questions
64
+
65
+ - "What is the average age in the dataset?"
66
+ - "Show me a bar chart of sales by region"
67
+ - "What's the distribution of customer types?"
68
+ - "Show me customers under 30 years old"
69
+ - "Is there a correlation between age and income?"
70
+
71
+ ## Deployment Options
72
+
73
+ ### Streamlit Cloud
74
+
75
+ 1. Push your code to a GitHub repository
76
+ 2. Create an account on [Streamlit Cloud](https://streamlit.io/cloud)
77
+ 3. Create a new app and connect it to your GitHub repository
78
+ 4. Deploy the app
79
+
80
+ ### Hugging Face Spaces
81
+
82
+ 1. Create an account on [Hugging Face](https://huggingface.co/)
83
+ 2. Create a new Space with Streamlit as the SDK
84
+ 3. Upload your code to the Space
85
+ 4. Configure the requirements
86
+
87
+ ## Performance Considerations
88
+
89
+ - The first query might take longer as the model is loaded into memory
90
+ - Quantization is used to reduce memory usage (4-bit)
91
+ - For large Excel files, consider pre-processing to reduce size
92
+ - Chart generation might take a few seconds depending on the complexity
93
+
94
+ ## Limitations
95
+
96
+ - Handles only the first sheet of an Excel file
97
+ - Works best with clean, structured data
98
+ - Chart extraction is based on pattern matching and might not always be perfect
99
+ - Advanced statistical operations might require additional implementation
100
+
101
+ ## Contributing
102
+
103
+ Contributions are welcome! Please feel free to submit a Pull Request.
104
+
105
+ ## License
106
+
107
+ This project is licensed under the MIT License - see the LICENSE file for details.
app.py CHANGED
@@ -1,64 +1,154 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
27
 
28
- response = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
 
 
 
 
 
 
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import re
4
+ from data_utils import load_and_clean_excel
5
+ from llm_utils import generate_response
6
+ from viz_utils import generate_chart
7
 
8
+ st.set_page_config(page_title="Excel Assistant", layout="wide")
 
 
 
9
 
10
+ # Initialize session state for chat history
11
+ if "chat_history" not in st.session_state:
12
+ st.session_state.chat_history = []
13
 
14
+ if "df" not in st.session_state:
15
+ st.session_state.df = None
 
 
 
 
 
 
 
16
 
17
+ if "cleaned_columns" not in st.session_state:
18
+ st.session_state.cleaned_columns = None
 
 
 
19
 
20
+ if "awaiting_followup" not in st.session_state:
21
+ st.session_state.awaiting_followup = False
22
 
23
+ def clean_response(response):
24
+ """Clean up the LLM response by removing code blocks and unnecessary explanations"""
25
+ # Remove any code blocks
26
+ response = re.sub(r'```[\s\S]*?```', '', response)
27
+
28
+ # Remove any inline code
29
+ response = re.sub(r'`.*?`', '', response)
30
+
31
+ # Remove lines that look like code (heuristic)
32
+ lines = response.split('\n')
33
+ cleaned_lines = [line for line in lines if not line.strip().startswith(('import ', 'from ', 'def ', 'class ', '#', '//', 'plt.', 'fig,', 'ax.'))]
34
+
35
+ # Join the remaining lines
36
+ cleaned_response = '\n'.join(cleaned_lines)
37
+
38
+ # Remove multiple newlines
39
+ cleaned_response = re.sub(r'\n\s*\n', '\n\n', cleaned_response)
40
+
41
+ return cleaned_response.strip()
42
 
43
+ # Function to handle question submission
44
+ def handle_question(question):
45
+ if question:
46
+ with st.spinner("Generating response..."):
47
+ # Check if this is a chart request
48
+ is_chart_request = any(chart_type in question.lower() for chart_type in [
49
+ "chart", "plot", "graph", "visualize", "visualization", "histogram", "bar", "pie", "scatter", "line"
50
+ ])
51
+
52
+ # Get response from LLM
53
+ response = generate_response(
54
+ question,
55
+ st.session_state.df,
56
+ st.session_state.cleaned_columns
57
+ )
58
+
59
+ # Clean up the response
60
+ cleaned_response = clean_response(response)
61
+
62
+ # Generate chart if needed
63
+ chart_fig = generate_chart(response, st.session_state.df)
64
+
65
+ # For chart requests, keep the response extra minimal if a chart was generated
66
+ if is_chart_request and chart_fig:
67
+ # Extract only the essential information about the chart
68
+ chart_info = re.search(r'(bar chart|histogram|line chart|scatter plot|pie chart|box plot).*?(of|between|showing|with).*?[.!]', cleaned_response, re.IGNORECASE)
69
+ if chart_info:
70
+ cleaned_response = chart_info.group(0)
71
+
72
+ # Save chart to session state if it exists
73
+ if chart_fig:
74
+ setattr(st.session_state, f"chart_for_{len(st.session_state.chat_history)}", chart_fig)
75
+
76
+ # Add to history
77
+ st.session_state.chat_history.append((question, cleaned_response))
78
+
79
+ # Set awaiting followup flag
80
+ st.session_state.awaiting_followup = True
81
 
82
+ def main():
83
+ st.title("Excel Assistant")
84
+ st.write("Upload your Excel file and ask questions about your data.")
85
+
86
+ # Sidebar for file upload and options
87
+ with st.sidebar:
88
+ st.header("Upload Data")
89
+ uploaded_file = st.file_uploader("Choose an Excel file", type=["xlsx"])
90
+
91
+ if uploaded_file is not None:
92
+ try:
93
+ # Process the uploaded file
94
+ df, cleaned_columns = load_and_clean_excel(uploaded_file)
95
+ st.session_state.df = df
96
+ st.session_state.cleaned_columns = cleaned_columns
97
+ st.success("File loaded successfully!")
98
+
99
+ # Display column mappings
100
+ st.subheader("Column Cleanup")
101
+ mapping_df = pd.DataFrame({
102
+ "Original": list(cleaned_columns.keys()),
103
+ "Cleaned": list(cleaned_columns.values())
104
+ })
105
+ st.dataframe(mapping_df)
106
+
107
+ # History section in sidebar
108
+ st.subheader("Question History")
109
+ if st.session_state.chat_history:
110
+ for i, (q, _) in enumerate(st.session_state.chat_history):
111
+ st.text(f"{i+1}. {q}")
112
+ except Exception as e:
113
+ st.error(f"Error loading file: {str(e)}")
114
+
115
+ # Main content area
116
+ if st.session_state.df is not None:
117
+ # Display dataframe preview
118
+ st.subheader("Data Preview")
119
+ st.dataframe(st.session_state.df.head(10))
120
+
121
+ # Create a chat container
122
+ chat_container = st.container()
123
+
124
+ # Display chat history in main area
125
+ with chat_container:
126
+ for idx, (question, answer) in enumerate(st.session_state.chat_history):
127
+ st.markdown(f"**You:** {question}")
128
+ st.markdown(f"**Assistant:** {answer}")
129
+
130
+ # If a chart was generated for this response, display it
131
+ if hasattr(st.session_state, f"chart_for_{idx}"):
132
+ chart_fig = getattr(st.session_state, f"chart_for_{idx}")
133
+ if chart_fig:
134
+ st.pyplot(chart_fig)
135
+
136
+ st.markdown("---")
137
+
138
+ # Show follow-up prompt if awaiting follow-up
139
+ if st.session_state.awaiting_followup and st.session_state.chat_history:
140
+ st.markdown("**Assistant:** Would you like to know anything else about your data?")
141
+
142
+ # Question input using a form to handle submission properly
143
+ with st.form(key="question_form", clear_on_submit=True):
144
+ user_question = st.text_input("Ask a question about your data:")
145
+ submit_button = st.form_submit_button("Ask")
146
+
147
+ if submit_button and user_question:
148
+ handle_question(user_question)
149
+ st.experimental_rerun()
150
+ else:
151
+ st.info("Please upload an Excel file to get started.")
152
 
153
  if __name__ == "__main__":
154
+ main()
data_utils.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import re
3
+ import numpy as np
4
+
5
+ def clean_column_name(col_name):
6
+ """
7
+ Clean and normalize column names:
8
+ - Convert to lowercase
9
+ - Replace spaces and special chars with underscores
10
+ - Remove duplicate underscores
11
+ - Remove leading/trailing underscores
12
+ """
13
+ if not isinstance(col_name, str):
14
+ col_name = str(col_name)
15
+
16
+ # Convert to lowercase
17
+ col_name = col_name.lower()
18
+
19
+ # Replace spaces and special chars with underscores
20
+ col_name = re.sub(r'[^\w\s]', '_', col_name)
21
+ col_name = re.sub(r'\s+', '_', col_name)
22
+
23
+ # Remove duplicate underscores
24
+ col_name = re.sub(r'_+', '_', col_name)
25
+
26
+ # Remove leading/trailing underscores
27
+ col_name = col_name.strip('_')
28
+
29
+ return col_name
30
+
31
+ def load_and_clean_excel(file_obj):
32
+ """
33
+ Load Excel file and clean column names
34
+ Returns:
35
+ - DataFrame with cleaned column names
36
+ - Dictionary mapping original to cleaned column names
37
+ """
38
+ # Read the first sheet
39
+ df = pd.read_excel(file_obj, sheet_name=0)
40
+
41
+ # Create mapping of original to cleaned column names
42
+ column_mapping = {}
43
+ cleaned_columns = []
44
+
45
+ for col in df.columns:
46
+ cleaned_col = clean_column_name(col)
47
+ column_mapping[col] = cleaned_col
48
+ cleaned_columns.append(cleaned_col)
49
+
50
+ # Rename columns
51
+ df.columns = cleaned_columns
52
+
53
+ # Basic data cleaning
54
+ # Replace empty strings with NaN
55
+ df = df.replace('', np.nan)
56
+
57
+ # Drop rows that are all NaN
58
+ df = df.dropna(how='all')
59
+
60
+ # Remove duplicate rows
61
+ df = df.drop_duplicates()
62
+
63
+ return df, column_mapping
64
+
65
+ def extract_rows_based_on_condition(df, condition_str):
66
+ """
67
+ Attempt to extract rows based on a condition string
68
+ (Simplified implementation - would need more complex parsing for real use)
69
+ """
70
+ try:
71
+ # This is a very simplified implementation
72
+ # In a real application, you'd need more robust parsing
73
+ result = df.query(condition_str)
74
+ return result
75
+ except:
76
+ return None
llm_utils.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import re
3
+ import torch
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+
6
+ # Constants
7
+ MODEL_ID = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" # Open-access model
8
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
9
+ MAX_LENGTH = 2048
10
+ MAX_NEW_TOKENS = 512
11
+
12
+ # Global variables to store model and tokenizer
13
+ model = None
14
+ tokenizer = None
15
+
16
+ def initialize_model():
17
+ """Initialize the model and tokenizer"""
18
+ global model, tokenizer
19
+
20
+ if model is None or tokenizer is None:
21
+ try:
22
+ # Load tokenizer
23
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
24
+
25
+ # Load model without quantization to avoid compatibility issues
26
+ model = AutoModelForCausalLM.from_pretrained(
27
+ MODEL_ID,
28
+ torch_dtype=torch.float32, # Use regular float instead of bfloat16
29
+ device_map=DEVICE
30
+ # Removed quantization parameters
31
+ )
32
+
33
+ return True
34
+ except Exception as e:
35
+ print(f"Error initializing model: {str(e)}")
36
+ return False
37
+
38
+ return True
39
+
40
+ def get_dataframe_info(df):
41
+ """Get information about the dataframe to include in the prompt"""
42
+ # Basic dataframe info
43
+ num_rows, num_cols = df.shape
44
+
45
+ # Column names and sample values
46
+ columns_info = []
47
+ for col in df.columns:
48
+ # Get column type
49
+ col_type = df[col].dtype
50
+
51
+ # Get sample values (non-null)
52
+ non_null_values = df[col].dropna()
53
+ if len(non_null_values) > 0:
54
+ sample_values = non_null_values.iloc[:3].tolist()
55
+ sample_str = ", ".join([str(val) for val in sample_values])
56
+ else:
57
+ sample_str = "No non-null values"
58
+
59
+ columns_info.append(f"- {col} ({col_type}): Example values: {sample_str}")
60
+
61
+ # Combine all info
62
+ info_text = f"Dataset has {num_rows} rows and {num_cols} columns.\n\n"
63
+ info_text += "Column information:\n" + "\n".join(columns_info)
64
+
65
+ return info_text
66
+
67
+ def create_prompt(question, df, column_mapping):
68
+ """Create a formatted prompt for the LLM"""
69
+ # Get dataframe info
70
+ df_info = get_dataframe_info(df)
71
+
72
+ # Determine if this is a chart request
73
+ is_chart_request = any(chart_type in question.lower() for chart_type in [
74
+ "chart", "plot", "graph", "visualize", "visualization", "histogram", "bar", "pie", "scatter", "line"
75
+ ])
76
+
77
+ # Create the complete prompt - adjusted for TinyLlama's format
78
+ prompt = f"""<human>
79
+ You are a helpful data analysis assistant. Your task is to answer questions about a dataset.
80
+
81
+ Dataset Information:
82
+ {df_info}
83
+
84
+ The original column names have been cleaned to remove spaces and special characters.
85
+ Here's the mapping from original to cleaned names:
86
+ {', '.join([f"'{k}' -> '{v}'" for k, v in column_mapping.items()])}
87
+
88
+ User Question: {question}
89
+
90
+ Instructions:
91
+ 1. Provide a clear, direct answer to the question based on the dataset information.
92
+ 2. If the question asks for a chart or visualization:
93
+ - ONLY specify which chart type would be best (bar chart, histogram, etc.)
94
+ - ONLY mention which columns should be used for the visualization
95
+ - DO NOT provide any code snippets
96
+ - DO NOT explain how to create the chart
97
+ - Be very brief and direct
98
+ 3. If asked for data that requires filtering or specific conditions, specify the condition clearly.
99
+ 4. If the question cannot be answered from the given dataset, explain why.
100
+ 5. Keep your response concise and focused.
101
+ </human>
102
+
103
+ <assistant>
104
+ """
105
+
106
+ return prompt
107
+
108
+ def extract_chart_suggestion(response):
109
+ """
110
+ Extract chart suggestion from LLM response
111
+ Returns a dict with chart type and relevant columns if found
112
+ """
113
+ # Look for common chart type mentions
114
+ chart_patterns = {
115
+ "bar chart": r"bar\s*chart",
116
+ "histogram": r"histogram",
117
+ "line chart": r"line\s*chart",
118
+ "scatter plot": r"scatter\s*plot",
119
+ "pie chart": r"pie\s*chart",
120
+ "box plot": r"box\s*plot"
121
+ }
122
+
123
+ chart_info = {"type": None, "columns": []}
124
+
125
+ # Check for chart type mentions
126
+ for chart_type, pattern in chart_patterns.items():
127
+ if re.search(pattern, response, re.IGNORECASE):
128
+ chart_info["type"] = chart_type
129
+ break
130
+
131
+ # If chart type found, try to extract columns
132
+ if chart_info["type"]:
133
+ # This is a simplified column extraction and would need to be more robust in production
134
+ # Look for column names mentioned after the chart type
135
+ full_text_after_chart = response[response.lower().find(chart_info["type"]):]
136
+
137
+ # Simple heuristic: look for words that might be column names
138
+ words = re.findall(r'\b[a-z][a-z0-9_]*\b', full_text_after_chart.lower())
139
+ chart_info["columns"] = words[:3] # Take up to 3 potential column names
140
+
141
+ return chart_info
142
+
143
+ def generate_response(question, df, column_mapping):
144
+ """Generate a response from the LLM for the given question"""
145
+ # Initialize model if needed
146
+ if not initialize_model():
147
+ return "Failed to initialize the language model. Please try again later."
148
+
149
+ # Create the prompt
150
+ prompt = create_prompt(question, df, column_mapping)
151
+
152
+ try:
153
+ # Encode the prompt
154
+ inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
155
+
156
+ # Generate response
157
+ with torch.no_grad():
158
+ output = model.generate(
159
+ **inputs,
160
+ max_length=MAX_LENGTH,
161
+ max_new_tokens=MAX_NEW_TOKENS,
162
+ temperature=0.7,
163
+ top_p=0.9,
164
+ do_sample=True
165
+ )
166
+
167
+ # Decode the response
168
+ response = tokenizer.decode(output[0], skip_special_tokens=True)
169
+
170
+ # Extract just the assistant's reply (after the prompt)
171
+ # Adjusted for TinyLlama format
172
+ if "<assistant>" in response:
173
+ response = response.split("<assistant>")[-1].strip()
174
+
175
+ return response
176
+
177
+ except Exception as e:
178
+ return f"Error generating response: {str(e)}"
requirements.txt CHANGED
@@ -1 +1,10 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
 
 
 
 
 
1
+ streamlit==1.30.0
2
+ pandas==2.1.3
3
+ numpy==1.26.2
4
+ matplotlib==3.8.2
5
+ seaborn==0.13.0
6
+ openpyxl==3.1.2
7
+ torch==2.7.1
8
+ transformers==4.35.2
9
+ accelerate==0.25.0
10
+ scikit-learn==1.3.2
viz_utils.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.pyplot as plt
2
+ import seaborn as sns
3
+ import pandas as pd
4
+ import re
5
+ from llm_utils import extract_chart_suggestion
6
+
7
+ # Set the style for the visualizations
8
+ sns.set_style("whitegrid")
9
+ plt.rcParams.update({'font.size': 12})
10
+
11
+ def generate_chart(response, df):
12
+ """
13
+ Generate a chart based on the LLM response
14
+ Returns a matplotlib figure or None if no chart is needed
15
+ """
16
+ # Extract chart suggestion from response
17
+ chart_info = extract_chart_suggestion(response)
18
+
19
+ # If no chart type detected, return None
20
+ if not chart_info["type"]:
21
+ return None
22
+
23
+ # Create figure
24
+ fig, ax = plt.subplots(figsize=(10, 6))
25
+
26
+ # Check if suggested columns exist in the dataframe
27
+ valid_columns = [col for col in chart_info["columns"] if col in df.columns]
28
+
29
+ # If no valid columns found, try to infer from dataframe
30
+ if not valid_columns:
31
+ # For numerical charts, select numeric columns
32
+ if chart_info["type"] in ["histogram", "line chart", "scatter plot", "box plot"]:
33
+ valid_columns = df.select_dtypes(include=['number']).columns.tolist()[:2]
34
+ else: # For categorical charts, include at least one categorical
35
+ num_cols = df.select_dtypes(include=['number']).columns.tolist()[:1]
36
+ cat_cols = df.select_dtypes(include=['object']).columns.tolist()[:1]
37
+ valid_columns = cat_cols + num_cols
38
+
39
+ # If still no valid columns, return None
40
+ if not valid_columns:
41
+ return None
42
+
43
+ # Generate the appropriate chart based on chart_info["type"]
44
+ try:
45
+ if chart_info["type"] == "bar chart":
46
+ if len(valid_columns) >= 2:
47
+ # If we have at least 2 columns, assume first is category and second is value
48
+ sns.barplot(x=valid_columns[0], y=valid_columns[1], data=df, ax=ax)
49
+ else:
50
+ # Single column - show value counts
51
+ df[valid_columns[0]].value_counts().plot(kind='bar', ax=ax)
52
+
53
+ ax.set_title(f"Bar Chart of {valid_columns[0]}")
54
+ ax.set_xlabel(valid_columns[0])
55
+ ax.tick_params(axis='x', rotation=45)
56
+
57
+ elif chart_info["type"] == "histogram":
58
+ sns.histplot(data=df, x=valid_columns[0], kde=True, ax=ax)
59
+ ax.set_title(f"Histogram of {valid_columns[0]}")
60
+ ax.set_xlabel(valid_columns[0])
61
+
62
+ elif chart_info["type"] == "line chart":
63
+ if len(valid_columns) >= 2:
64
+ # Sort by the x column for better line charts
65
+ sorted_df = df.sort_values(by=valid_columns[0])
66
+ ax.plot(sorted_df[valid_columns[0]], sorted_df[valid_columns[1]])
67
+ ax.set_title(f"Line Chart of {valid_columns[1]} by {valid_columns[0]}")
68
+ ax.set_xlabel(valid_columns[0])
69
+ ax.set_ylabel(valid_columns[1])
70
+ else:
71
+ # Single column - show values over index
72
+ df[valid_columns[0]].plot(ax=ax)
73
+ ax.set_title(f"Line Chart of {valid_columns[0]}")
74
+
75
+ elif chart_info["type"] == "scatter plot":
76
+ if len(valid_columns) >= 2:
77
+ sns.scatterplot(x=valid_columns[0], y=valid_columns[1], data=df, ax=ax)
78
+ ax.set_title(f"Scatter Plot of {valid_columns[1]} vs {valid_columns[0]}")
79
+ ax.set_xlabel(valid_columns[0])
80
+ ax.set_ylabel(valid_columns[1])
81
+
82
+ elif chart_info["type"] == "pie chart":
83
+ # Get value counts for the first column
84
+ counts = df[valid_columns[0]].value_counts()
85
+ # Limit to top 10 categories for readability
86
+ if len(counts) > 10:
87
+ counts = counts.head(10)
88
+ counts.plot(kind='pie', ax=ax, autopct='%1.1f%%')
89
+ ax.set_title(f"Pie Chart of {valid_columns[0]} Distribution")
90
+ ax.set_ylabel('')
91
+
92
+ elif chart_info["type"] == "box plot":
93
+ if len(valid_columns) >= 2:
94
+ # If we have 2 columns, use the first as category and second as value
95
+ sns.boxplot(x=valid_columns[0], y=valid_columns[1], data=df, ax=ax)
96
+ ax.set_title(f"Box Plot of {valid_columns[1]} by {valid_columns[0]}")
97
+ ax.tick_params(axis='x', rotation=45)
98
+ else:
99
+ # Single column - simple box plot
100
+ sns.boxplot(y=valid_columns[0], data=df, ax=ax)
101
+ ax.set_title(f"Box Plot of {valid_columns[0]}")
102
+
103
+ # Adjust layout and return the figure
104
+ plt.tight_layout()
105
+ return fig
106
+
107
+ except Exception as e:
108
+ print(f"Error generating chart: {str(e)}")
109
+ return None