File size: 9,681 Bytes
814316f
 
ca8b7a3
9f22029
814316f
 
 
 
 
 
 
 
 
 
e3d2b77
814316f
ca37c17
e3d2b77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
814316f
 
 
 
 
 
 
 
 
 
ca8b7a3
9f22029
814316f
 
 
ca8b7a3
814316f
 
 
 
ca8b7a3
9f22029
ca8b7a3
 
 
 
9f22029
ca8b7a3
9f22029
ca8b7a3
 
9f22029
ca8b7a3
 
 
 
 
 
 
 
9f22029
ca8b7a3
 
9f22029
ca8b7a3
 
 
 
 
 
9f22029
 
 
ca8b7a3
9f22029
814316f
 
 
 
 
 
 
 
 
 
ca8b7a3
814316f
ca8b7a3
814316f
ca8b7a3
814316f
 
9f22029
ca8b7a3
 
 
 
 
 
9f22029
 
814316f
 
 
 
 
ca8b7a3
0d96540
814316f
 
 
ca37c17
 
 
814316f
 
ca8b7a3
 
814316f
 
 
 
 
 
e3d2b77
814316f
 
 
 
 
 
 
 
 
 
24b4795
0d96540
 
 
 
 
814316f
 
ca37c17
814316f
 
ca37c17
 
 
 
 
 
 
 
 
 
 
 
 
814316f
 
 
 
 
 
 
 
 
 
e3d2b77
814316f
 
 
9581ef6
814316f
9581ef6
814316f
9581ef6
814316f
9581ef6
e3d2b77
 
814316f
9581ef6
814316f
9581ef6
 
e3d2b77
 
814316f
9581ef6
814316f
e3d2b77
9581ef6
e3d2b77
814316f
9f22029
 
ca8b7a3
 
 
 
814316f
ca8b7a3
 
 
 
814316f
 
 
9581ef6
 
814316f
 
 
ca8b7a3
e3d2b77
ca8b7a3
814316f
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import streamlit as st
import pandas as pd
import tempfile
import os

# Page configuration
st.set_page_config(
    page_title="πŸ“Š LLM Data Analyzer",
    page_icon="πŸ“Š",
    layout="wide",
    initial_sidebar_state="expanded"
)

st.title("πŸ“Š LLM Data Analyzer")
st.write("*Analyze data and chat with AI - Powered by Hugging Face Spaces*")

# Simple AI responses without API calls
def get_ai_response(prompt):
    """Generate simple AI-like responses without external API"""
    prompt_lower = prompt.lower()
    
    # Data analysis responses
    if "average" in prompt_lower or "mean" in prompt_lower:
        return "Based on the data summary, the average values can be calculated from the statistical measures shown. For more detailed analysis, look at the mean values in the data description."
    elif "trend" in prompt_lower or "pattern" in prompt_lower:
        return "The data shows various patterns. Examine the min, max, and std deviation values to understand the distribution and trends in your dataset."
    elif "correlation" in prompt_lower or "relationship" in prompt_lower:
        return "To understand relationships between columns, look at how values change together. The standard deviation and percentiles in the summary can give insights."
    elif "outlier" in prompt_lower or "unusual" in prompt_lower:
        return "Check the min/max values and compare them to the mean and median. Large differences suggest outliers in your data."
    elif "summary" in prompt_lower or "overview" in prompt_lower:
        return "The data summary shows key statistics including count, mean, standard deviation, min, 25%, 50%, 75%, and max values for each column."
    
    # General chat responses
    elif "hello" in prompt_lower or "hi" in prompt_lower:
        return "Hello! I'm the LLM Data Analyzer. I can help you understand your data better. Upload a CSV or Excel file and ask me questions about it!"
    elif "what can you do" in prompt_lower or "help" in prompt_lower:
        return "I can help you: 1) Upload and preview data 2) View statistics 3) Answer questions about your data 4) Have conversations. Try uploading a CSV or Excel file!"
    elif "thank" in prompt_lower:
        return "You're welcome! Feel free to ask more questions about your data anytime."
    else:
        return "That's an interesting question! To get the most accurate analysis, please upload your data and ask specific questions about the columns and values. I can then provide detailed insights based on your actual dataset."

# Create tabs
tab1, tab2, tab3 = st.tabs(["πŸ“€ Upload & Analyze", "πŸ’¬ Chat", "πŸ“Š About"])

# ============================================================================
# TAB 1: Upload & Analyze
# ============================================================================
with tab1:
    st.header("πŸ“€ Upload and Analyze Data")
    
    st.info("πŸ’‘ Tip: CSV files work best. If upload fails, try saving your Excel file as CSV first.")
    
    uploaded_file = st.file_uploader(
        "Upload a CSV or Excel file",
        type=["csv", "xlsx", "xls"],
        help="Supported formats: CSV, Excel"
    )
    
    if uploaded_file is not None:
        try:
            st.success(f"βœ… File received: {uploaded_file.name}")
            
            # Save to temp file to avoid streaming issues
            with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]) as tmp_file:
                tmp_file.write(uploaded_file.getbuffer())
                tmp_path = tmp_file.name
            
            # Read file
            try:
                if uploaded_file.name.lower().endswith('.csv'):
                    df = pd.read_csv(tmp_path, on_bad_lines='skip')
                else:
                    # Try multiple engines for Excel
                    try:
                        df = pd.read_excel(tmp_path, engine='openpyxl')
                    except:
                        try:
                            df = pd.read_excel(tmp_path, engine='xlrd')
                        except:
                            df = pd.read_excel(tmp_path)
            except Exception as read_error:
                st.error("❌ Could not read file. Try converting to CSV format.")
                st.info("**Solution:** Open in Excel β†’ File β†’ Save As β†’ CSV β†’ Upload again")
                st.stop()
            finally:
                # Clean up temp file
                try:
                    os.unlink(tmp_path)
                except:
                    pass
            
            # Validate dataframe
            if df.empty:
                st.error("❌ File is empty. Make sure it contains data rows.")
                st.stop()
            
            # Display data preview
            st.subheader("πŸ“‹ Data Preview")
            st.dataframe(df.head(10), use_container_width=True)
            
            # Display statistics
            st.subheader("πŸ“Š Data Statistics")
            col1, col2, col3 = st.columns(3)
            
            with col1:
                st.metric("Rows", len(df))
            with col2:
                st.metric("Columns", len(df.columns))
            with col3:
                st.metric("Columns", ", ".join(df.columns[:3].tolist()) + "...")
            
            # Detailed statistics
            try:
                numeric_df = df.select_dtypes(include=['number'])
                if not numeric_df.empty:
                    st.write("### Numeric Columns Summary")
                    st.write(numeric_df.describe().T)
                else:
                    st.info("No numeric columns found in dataset.")
            except:
                st.info("Could not generate statistics for this data.")
            
            # Ask AI about the data
            st.subheader("❓ Ask AI About Your Data")
            question = st.text_input(
                "What would you like to know about this data?",
                placeholder="e.g., What is the average? What patterns do you see?",
                key="data_question"
            )
            
            if question:
                response = get_ai_response(question)
                st.success("βœ… Analysis Complete")
                st.write(response)
        
        except Exception as e:
            st.error(f"❌ Unexpected error: {str(e)[:50]}")
            st.info("**Try this:** Save your Excel file as CSV, then upload again.")

# ============================================================================
# TAB 2: Chat
# ============================================================================
with tab2:
    st.header("πŸ’¬ Chat with AI Assistant")
    st.write("Have a conversation about data analysis and AI.")
    
    # Initialize session state for chat history
    if "messages" not in st.session_state:
        st.session_state.messages = []
    
    # Display chat history
    for message in st.session_state.messages:
        with st.chat_message(message["role"]):
            st.markdown(message["content"])
    
    # Chat input
    user_input = st.text_input(
        "Type your message:",
        placeholder="Ask me anything...",
        key="chat_input"
    )
    
    if user_input:
        # Add user message immediately
        st.session_state.messages.append({"role": "user", "content": user_input})
        
        # Get response
        response = get_ai_response(user_input)
        
        # Add assistant message
        st.session_state.messages.append({
            "role": "assistant",
            "content": response
        })
        
        # Display latest messages
        st.divider()
        with st.chat_message("assistant"):
            st.markdown(response)

# ============================================================================
# TAB 3: About
# ============================================================================
with tab3:
    st.header("ℹ️ About This App")
    
    st.markdown("""
    ### 🎯 What is this?
    
    **LLM Data Analyzer** is a tool for analyzing data and having conversations about your datasets.
    
    ### πŸ”§ Technology Stack
    
    - **Framework:** Streamlit
    - **Hosting:** Hugging Face Spaces (Free Tier)
    - **Language:** Python
    
    ### ⚑ Features
    
    1. **Data Analysis**: Upload CSV/Excel and ask questions about your data
    2. **Chat**: Have conversations about data insights
    3. **Statistics**: View comprehensive data summaries
    
    ### πŸ“ How to Use
    
    1. **Upload Data** - Start by uploading a CSV or Excel file
    2. **Preview** - Review your data and statistics
    3. **Ask Questions** - Ask about patterns, averages, outliers, etc.
    4. **Chat** - Have conversations about your analysis
    
    ### 🌐 Powered By
    
    - [Hugging Face](https://huggingface.co/) - AI platform and hosting
    - [Streamlit](https://streamlit.io/) - Web framework
    - [Pandas](https://pandas.pydata.org/) - Data analysis
    
    ### πŸ“– Troubleshooting
    
    **File upload fails with 403 error?**
    - Convert Excel to CSV first (File β†’ Save As β†’ CSV format)
    - Upload the CSV file instead
    - This solves 99% of upload issues
    
    **Still having issues?**
    - Make sure file has valid data
    - File size should be under 50MB
    - Try a simpler file first to test
    
    ### πŸ”— Links
    
    - [GitHub Repository](https://github.com/Arif-Badhon/LLM-Data-Analyzer)
    - [Hugging Face Hub](https://huggingface.co/)
    
    ---
    
    **Version:** 1.1 | **Last Updated:** Dec 2025
    
    πŸ’‘ **Note:** This version uses intelligent pattern matching for responses.
    """)