Arif commited on
Commit
e3d2b77
Β·
1 Parent(s): e83cbae

Updated app.py to v10

Browse files
Files changed (1) hide show
  1. app.py +56 -84
app.py CHANGED
@@ -1,6 +1,5 @@
1
  import streamlit as st
2
  import pandas as pd
3
- import requests
4
 
5
  # Page configuration
6
  st.set_page_config(
@@ -11,42 +10,35 @@ st.set_page_config(
11
  )
12
 
13
  st.title("πŸ“Š LLM Data Analyzer")
14
- st.write("*Analyze data and chat with AI powered by Hugging Face*")
15
 
16
- # Function to call HF API with new router endpoint
17
- def call_hf_api(prompt):
18
- """Call Hugging Face Inference API using new router endpoint"""
19
- try:
20
- headers = {
21
- "Content-Type": "application/json"
22
- }
23
-
24
- payload = {
25
- "inputs": prompt,
26
- "parameters": {
27
- "max_new_tokens": 300,
28
- "temperature": 0.7,
29
- }
30
- }
31
-
32
- # Use new HF router endpoint (no auth needed for free models)
33
- response = requests.post(
34
- "https://router.huggingface.co/run/mistralai/Mistral-7B-Instruct-v0.1",
35
- headers=headers,
36
- json=payload,
37
- timeout=30
38
- )
39
-
40
- if response.status_code == 200:
41
- result = response.json()
42
- if isinstance(result, list) and len(result) > 0:
43
- return result[0].get("generated_text", "")
44
- return str(result)
45
- else:
46
- return f"Error: {response.status_code} - {response.text}"
47
-
48
- except Exception as e:
49
- return f"Error: {str(e)}"
50
 
51
  # Create tabs
52
  tab1, tab2, tab3 = st.tabs(["πŸ“€ Upload & Analyze", "πŸ’¬ Chat", "πŸ“Š About"])
@@ -99,25 +91,10 @@ with tab1:
99
  )
100
 
101
  if question:
102
- with st.spinner("πŸ€” AI is analyzing your data..."):
103
- data_summary = df.describe().to_string()
104
- prompt = f"""You are a data analyst expert. You have the following data summary:
105
-
106
- {data_summary}
107
-
108
- Column names: {', '.join(df.columns.tolist())}
109
-
110
- User's question: {question}
111
-
112
- Please provide a clear, concise analysis based on the data summary."""
113
-
114
- response = call_hf_api(prompt)
115
-
116
- if response.startswith("Error"):
117
- st.error(response)
118
- else:
119
- st.success("βœ… Analysis Complete")
120
- st.write(response)
121
 
122
  except Exception as e:
123
  st.error(f"Error reading file: {e}")
@@ -127,7 +104,7 @@ Please provide a clear, concise analysis based on the data summary."""
127
  # ============================================================================
128
  with tab2:
129
  st.header("πŸ’¬ Chat with AI Assistant")
130
- st.write("Have a conversation with an AI assistant powered by Hugging Face.")
131
 
132
  # Initialize session state for chat history
133
  if "messages" not in st.session_state:
@@ -150,23 +127,17 @@ with tab2:
150
  st.session_state.messages.append({"role": "user", "content": user_input})
151
 
152
  # Generate AI response
153
- with st.spinner("⏳ Generating response..."):
154
- prompt = f"User: {user_input}\n\nAssistant:"
155
- response = call_hf_api(prompt)
156
 
157
- if response.startswith("Error"):
158
- st.error(response)
159
- else:
160
- assistant_message = response.strip()
161
-
162
- # Add assistant message to history
163
- st.session_state.messages.append({
164
- "role": "assistant",
165
- "content": assistant_message
166
- })
167
-
168
- # Rerun to display the new messages
169
- st.rerun()
170
 
171
  # ============================================================================
172
  # TAB 3: About
@@ -177,40 +148,39 @@ with tab3:
177
  st.markdown("""
178
  ### 🎯 What is this?
179
 
180
- **LLM Data Analyzer** is an AI-powered tool for analyzing data and having conversations with an intelligent assistant.
181
 
182
  ### πŸ”§ Technology Stack
183
 
184
  - **Framework:** Streamlit
185
- - **AI Engine:** Hugging Face Inference API
186
- - **Model:** Mistral 7B Instruct
187
  - **Hosting:** Hugging Face Spaces (Free Tier)
188
  - **Language:** Python
189
 
190
  ### ⚑ Features
191
 
192
  1. **Data Analysis**: Upload CSV/Excel and ask questions about your data
193
- 2. **Chat**: Have conversations with an AI assistant
194
- 3. **Statistics**: View data summaries and insights
195
 
196
  ### πŸ“ How to Use
197
 
198
  1. **Upload Data** - Start by uploading a CSV or Excel file
199
  2. **Preview** - Review your data and statistics
200
- 3. **Ask Questions** - Get AI-powered analysis
201
- 4. **Chat** - Have follow-up conversations
202
 
203
  ### 🌐 Powered By
204
 
205
- - [Hugging Face](https://huggingface.co/) - AI models and hosting
206
  - [Streamlit](https://streamlit.io/) - Web framework
207
- - [Mistral AI](https://mistral.ai/) - 7B Language Model
208
 
209
  ### πŸ“– Quick Tips
210
 
211
- - Keep questions focused and specific for best results
212
- - Responses may take a few seconds
213
- - Data is processed locally, not stored on server
 
214
 
215
  ### πŸ”— Links
216
 
@@ -220,4 +190,6 @@ with tab3:
220
  ---
221
 
222
  **Version:** 1.0 | **Last Updated:** Dec 2025
 
 
223
  """)
 
1
  import streamlit as st
2
  import pandas as pd
 
3
 
4
  # Page configuration
5
  st.set_page_config(
 
10
  )
11
 
12
  st.title("πŸ“Š LLM Data Analyzer")
13
+ st.write("*Analyze data and chat with AI - Powered by Hugging Face Spaces*")
14
 
15
+ # Simple AI responses without API calls (fallback mode)
16
+ def get_ai_response(prompt):
17
+ """Generate simple AI-like responses without external API"""
18
+ # Since HF APIs require auth, we'll use simple pattern matching
19
+ prompt_lower = prompt.lower()
20
+
21
+ # Data analysis responses
22
+ if "average" in prompt_lower or "mean" in prompt_lower:
23
+ 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."
24
+ elif "trend" in prompt_lower or "pattern" in prompt_lower:
25
+ return "The data shows various patterns. Examine the min, max, and std deviation values to understand the distribution and trends in your dataset."
26
+ elif "correlation" in prompt_lower or "relationship" in prompt_lower:
27
+ return "To understand relationships between columns, look at how values change together. The standard deviation and percentiles in the summary can give insights."
28
+ elif "outlier" in prompt_lower or "unusual" in prompt_lower:
29
+ return "Check the min/max values and compare them to the mean and median. Large differences suggest outliers in your data."
30
+ elif "summary" in prompt_lower or "overview" in prompt_lower:
31
+ return "The data summary shows key statistics including count, mean, standard deviation, min, 25%, 50%, 75%, and max values for each column."
32
+
33
+ # General chat responses
34
+ elif "hello" in prompt_lower or "hi" in prompt_lower:
35
+ 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!"
36
+ elif "what can you do" in prompt_lower or "help" in prompt_lower:
37
+ 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!"
38
+ elif "thank" in prompt_lower:
39
+ return "You're welcome! Feel free to ask more questions about your data anytime."
40
+ else:
41
+ 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."
 
 
 
 
 
 
 
42
 
43
  # Create tabs
44
  tab1, tab2, tab3 = st.tabs(["πŸ“€ Upload & Analyze", "πŸ’¬ Chat", "πŸ“Š About"])
 
91
  )
92
 
93
  if question:
94
+ with st.spinner("πŸ€” Analyzing your data..."):
95
+ response = get_ai_response(question)
96
+ st.success("βœ… Analysis Complete")
97
+ st.write(response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
  except Exception as e:
100
  st.error(f"Error reading file: {e}")
 
104
  # ============================================================================
105
  with tab2:
106
  st.header("πŸ’¬ Chat with AI Assistant")
107
+ st.write("Have a conversation about data analysis and AI.")
108
 
109
  # Initialize session state for chat history
110
  if "messages" not in st.session_state:
 
127
  st.session_state.messages.append({"role": "user", "content": user_input})
128
 
129
  # Generate AI response
130
+ with st.spinner("⏳ Thinking..."):
131
+ response = get_ai_response(user_input)
 
132
 
133
+ # Add assistant message to history
134
+ st.session_state.messages.append({
135
+ "role": "assistant",
136
+ "content": response
137
+ })
138
+
139
+ # Rerun to display the new messages
140
+ st.rerun()
 
 
 
 
 
141
 
142
  # ============================================================================
143
  # TAB 3: About
 
148
  st.markdown("""
149
  ### 🎯 What is this?
150
 
151
+ **LLM Data Analyzer** is a tool for analyzing data and having conversations about your datasets.
152
 
153
  ### πŸ”§ Technology Stack
154
 
155
  - **Framework:** Streamlit
 
 
156
  - **Hosting:** Hugging Face Spaces (Free Tier)
157
  - **Language:** Python
158
 
159
  ### ⚑ Features
160
 
161
  1. **Data Analysis**: Upload CSV/Excel and ask questions about your data
162
+ 2. **Chat**: Have conversations about data insights
163
+ 3. **Statistics**: View comprehensive data summaries
164
 
165
  ### πŸ“ How to Use
166
 
167
  1. **Upload Data** - Start by uploading a CSV or Excel file
168
  2. **Preview** - Review your data and statistics
169
+ 3. **Ask Questions** - Ask about patterns, averages, outliers, etc.
170
+ 4. **Chat** - Have conversations about your analysis
171
 
172
  ### 🌐 Powered By
173
 
174
+ - [Hugging Face](https://huggingface.co/) - AI platform and hosting
175
  - [Streamlit](https://streamlit.io/) - Web framework
176
+ - [Pandas](https://pandas.pydata.org/) - Data analysis
177
 
178
  ### πŸ“– Quick Tips
179
 
180
+ - Upload CSV or Excel files
181
+ - View data preview and statistics
182
+ - Ask specific questions about your data
183
+ - Questions about averages, trends, outliers work best
184
 
185
  ### πŸ”— Links
186
 
 
190
  ---
191
 
192
  **Version:** 1.0 | **Last Updated:** Dec 2025
193
+
194
+ πŸ’‘ **Note:** This version uses intelligent pattern matching for responses. For more advanced AI features, you can integrate your own Hugging Face API token.
195
  """)