# CSV Data Analyzer with OpenAI A Python application that analyzes CSV files using OpenAI's GPT model to answer questions about your data. ## Setup Instructions 1. Create a new directory for your project: ```bash mkdir csv-analyzer cd csv-analyzer ``` 2. Create the following directory structure: ``` csv-analyzer/ ├── data/ # Place your CSV files here ├── .streamlit/ # Streamlit configuration ├── main.py # Main application file └── utils.py # Utility functions ``` 3. Install the required packages: ```bash pip install streamlit openai pandas ``` 4. Set up your OpenAI API key as an environment variable: - On Windows (Command Prompt): ```bash set OPENAI_API_KEY=your-api-key-here ``` - On macOS/Linux: ```bash export OPENAI_API_KEY=your-api-key-here ``` 5. Place your CSV files in the `data` directory. 6. Run the application: ```bash streamlit run main.py ``` The application will be available at http://localhost:8501 ## Files Overview Here are the contents of each file you need to create: ### 1. .streamlit/config.toml ```toml [server] headless = true address = "0.0.0.0" port = 8501 [theme] primaryColor = "#0066cc" backgroundColor = "#ffffff" secondaryBackgroundColor = "#f0f2f6" textColor = "#262730" ``` ### 2. utils.py ```python import pandas as pd import os from openai import OpenAI import json # the newest OpenAI model is "gpt-4o" which was released May 13, 2024. # do not change this unless explicitly requested by the user OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") client = OpenAI(api_key=OPENAI_API_KEY) def validate_csv(file): try: df = pd.read_csv(file, low_memory=False) return True, df except Exception as e: return False, str(e) def get_data_description(dfs): """Generate a concise description of the available data""" description = [] for name, df in dfs.items(): cols = df.columns.tolist() rows = len(df) description.append(f"File '{name}': {rows} rows, columns: {', '.join(cols)}") return "\n".join(description) def prepare_data_sample(df): """Prepare first row sample of the dataframe""" sample = df.head(1) # Convert to string and limit column width for readability return sample.to_string(max_cols=None, max_colwidth=20) def analyze_data(question, dfs): """Analyze data using OpenAI API with optimized prompt and data handling""" try: # Prepare context about the data context = get_data_description(dfs) # Prepare first row samples from all files data_samples = [] total_files = len(dfs) for name, df in dfs.items(): sample = prepare_data_sample(df) data_samples.append(f"First row from {name}:\n{sample}") prompt = f"""Question: {question} Available data ({total_files} files total): {context} Data preview (first row from each file): {chr(10).join(data_samples)} Note: Showing first row from each file to provide context about data structure. Please provide a clear, data-driven answer using all available data.""" response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "You are a data analysis expert. Provide clear, accurate answers based on the CSV data provided."}, {"role": "user", "content": prompt} ], max_tokens=1000 ) return True, response.choices[0].message.content except Exception as e: if "string too long" in str(e): return False, "Error: The dataset is too large. Please try asking about specific columns or use a smaller dataset." return False, f"Error analyzing data: {str(e)}" ``` ### 3. main.py ```python import streamlit as st import pandas as pd from utils import validate_csv, analyze_data import os from pathlib import Path st.set_page_config( page_title="CSV Data Analyzer", page_icon="📊", layout="wide" ) # Create data directory if it doesn't exist data_dir = Path("data") data_dir.mkdir(exist_ok=True) # Initialize session state if 'selected_files' not in st.session_state: st.session_state.selected_files = {} def main(): st.title("📊 CSV Data Analyzer") # Check for API key api_key = os.environ.get("OPENAI_API_KEY") if not api_key: st.error("⚠️ OpenAI API key not found. Please set the OPENAI_API_KEY environment variable.") return # File selection section st.header("1. Available CSV Files") # Get list of CSV files in data directory csv_files = list(data_dir.glob("*.csv")) if not csv_files: st.warning("No CSV files found in the 'data' directory. Please add CSV files to the 'data' folder.") st.markdown(""" ### How to add files: 1. Create a folder named 'data' in the project root (if not exists) 2. Place your CSV files in the 'data' folder 3. The files will appear here automatically """) return # File selection selected_file_paths = st.multiselect( "Select CSV files to analyze", options=csv_files, format_func=lambda x: x.name, help="Choose one or more CSV files from the data directory" ) # Process selected files for file_path in selected_file_paths: if file_path.name not in st.session_state.selected_files: with file_path.open('rb') as f: is_valid, result = validate_csv(f) if is_valid: st.session_state.selected_files[file_path.name] = result else: st.error(f"Error in {file_path.name}: {result}") # Display data preview if st.session_state.selected_files: st.header("2. Data Preview") # Show analysis information total_files = len(st.session_state.selected_files) st.info(f""" 🔍 Analysis Details: - Total files selected: {total_files} - Using first row from each file for analysis - All files will be included in the analysis """) for filename, df in st.session_state.selected_files.items(): with st.expander(f"Preview: {filename}"): st.dataframe( df.head(5), use_container_width=True ) st.text(f"Shape: {df.shape[0]} rows × {df.shape[1]} columns") # Question input st.header("3. Ask Questions About Your Data") question = st.text_area( "Enter your question", placeholder="Example: What is the average value in column X? Compare data across all files.", help="Ask any question about your data - the AI will analyze all selected files" ) if st.button("Analyze", type="primary"): if question: with st.spinner("Analyzing your data..."): success, response = analyze_data(question, st.session_state.selected_files) if success: st.header("4. Analysis Results") st.write(response) else: st.error(response) else: st.warning("Please enter a question to analyze.") # Clear data button if st.button("Clear Selected Files"): st.session_state.selected_files = {} st.rerun() else: st.info("👆 Start by selecting CSV files from the data directory") # Footer st.markdown("---") st.markdown("""
Built with Streamlit and OpenAI