CosmickVisions commited on
Commit
792d1fc
·
verified ·
1 Parent(s): fa565b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +261 -142
app.py CHANGED
@@ -2,99 +2,202 @@ import streamlit as st
2
  import pandas as pd
3
  import plotly.express as px
4
  import numpy as np
5
- from pycaret.classification import *
6
- from pycaret.regression import *
7
- from pycaret.clustering import *
 
 
8
  from ydata_profiling import ProfileReport
9
  from streamlit_pandas_profiling import st_profile_report
10
- import mlflow
11
- import requests
12
- import json
 
 
 
13
  import os
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  # Set page config
16
  st.set_page_config(page_title="Neural-Vision Enhanced", layout="wide")
17
 
18
- # MLflow Tracking
19
- mlflow.set_tracking_uri("http://127.0.0.1:5000")
20
- mlflow.set_experiment("Neural-Vision Enhanced")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  # Initialize session state
23
- st.session_state.setdefault('metrics', {})
24
- st.session_state.setdefault('chat_history', [])
25
-
26
- # Enhanced Visualization Functions
27
- def visualize_model(model, plots):
28
- cols = st.columns(len(plots))
29
- for col, plot in zip(cols, plots):
30
- with col:
31
- plot_model(model, plot=plot, display_format='streamlit')
32
-
33
- def visualize_classification():
34
- visualize_model(st.session_state.best_model, ['confusion_matrix', 'auc', 'feature', 'pr'])
35
-
36
- def visualize_regression():
37
- visualize_model(st.session_state.best_model, ['residuals', 'error', 'cooks', 'learning'])
38
-
39
- def visualize_clustering():
40
- visualize_model(st.session_state.best_model, ['cluster', 'distribution', 'elbow', 'silhouette'])
41
-
42
- # Enhanced Context Generator
43
- def get_app_context():
44
- df_stats = {}
45
- if 'df' in st.session_state:
46
- df = st.session_state.df
47
- df_stats = {
48
- "rows": df.shape[0],
49
- "columns": df.shape[1],
50
- "missing_values": df.isna().sum().sum(),
51
- "columns": {col: str(df[col].dtype) for col in df.columns}
52
- }
 
 
 
 
 
 
 
 
53
 
54
- context = {
55
- "current_state": {
56
- "active_page": st.session_state.get('active_page', 'Data Upload'),
57
- "dataset_stats": df_stats,
58
- "model_metrics": st.session_state.metrics,
59
- "problem_type": st.session_state.get('problem_type'),
60
- "target": st.session_state.get('target'),
61
- "best_model": str(st.session_state.get('best_model', None))
62
- },
63
- "app_capabilities": [
64
- "CSV data upload and statistical analysis",
65
- "Automated EDA report generation",
66
- "PyCaret-powered model training for classification, regression, and clustering",
67
- "Advanced model evaluation visualizations",
68
- "ML experiment tracking with MLflow",
69
- "AI-powered analysis through DeepSeek integration"
70
- ]
71
  }
 
72
 
73
- return json.dumps(context)
74
-
75
- # Chatbot Handler
76
- def handle_ai_query(prompt):
77
- try:
78
- response = requests.post(
79
- "http://127.0.0.1:5001/analyze",
80
- json={
81
- "prompt": prompt,
82
- "context": get_app_context(),
83
- "metrics": st.session_state.metrics
84
- }
85
- )
86
- return response.json().get("analysis", "Error in analysis")
87
- except Exception as e:
88
- return f"Analysis error: {str(e)}"
89
-
90
- # Main App Components
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  def data_upload_page():
92
- st.title("📤 Data Upload & Analysis")
93
  uploaded_file = st.file_uploader("Upload Dataset", type=["csv"])
94
 
95
  if uploaded_file:
96
  df = pd.read_csv(uploaded_file)
97
  st.session_state.df = df
 
98
  st.session_state.metrics = {}
99
 
100
  st.subheader("Dataset Health Check")
@@ -109,7 +212,7 @@ def data_upload_page():
109
  st_profile_report(profile)
110
 
111
  def model_training_page():
112
- st.title("🧠 Model Training Studio")
113
 
114
  if 'df' not in st.session_state:
115
  st.warning("Upload data first!")
@@ -117,107 +220,123 @@ def model_training_page():
117
 
118
  df = st.session_state.df
119
  problem_type = st.selectbox("Select Problem Type", ["Classification", "Regression", "Clustering"])
 
120
 
121
  if problem_type != "Clustering":
122
- st.session_state.target = st.selectbox("Select Target Variable", df.columns)
 
 
 
 
 
123
 
124
- if st.button("Initialize Training Environment"):
125
- with st.spinner("Configuring PyCaret..."):
126
- setup_func = {
127
- "Classification": classification_setup,
128
- "Regression": regression_setup,
129
- "Clustering": clustering_setup
130
- }[problem_type]
131
- setup_func(df, target=st.session_state.get('target'), session_id=42)
132
- st.session_state.problem_type = problem_type
133
- st.success("Environment ready for modeling!")
134
-
135
- if 'problem_type' in st.session_state:
136
- st.subheader("Model Training Dashboard")
137
- if st.session_state.problem_type in ["Classification", "Regression"]:
138
- compare_models = st.checkbox("Compare Multiple Models", True)
139
- n_models = st.slider("Number of Models", 1, 15, 5) if compare_models else 1
140
 
141
- if st.button("Start Training"):
142
- with st.spinner("Training in progress..."):
143
- if compare_models:
144
- models = compare_models(n_select=n_models)
145
- st.session_state.best_model = models[0]
146
- else:
147
- st.session_state.best_model = create_model()
148
-
149
- # Capture metrics
150
- results = pull()
151
- st.session_state.metrics = results.to_dict()
152
- st.success(f"Best Model: {st.session_state.best_model}")
153
-
154
- # Log to MLflow
155
- with mlflow.start_run():
156
- mlflow.log_metrics(results.iloc[0].to_dict())
157
- mlflow.sklearn.log_model(st.session_state.best_model, "model")
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
  def visualization_page():
160
- st.title("🔍 Model Evaluation Center")
161
 
162
  if 'best_model' not in st.session_state:
163
  st.warning("Train a model first!")
164
  return
165
 
166
  st.subheader("Performance Analysis")
 
 
 
 
 
 
 
 
167
 
168
- visualizers = {
169
- "Classification": visualize_classification,
170
- "Regression": visualize_regression,
171
- "Clustering": visualize_clustering
172
- }
173
- visualizers[st.session_state.problem_type]()
174
-
175
- st.subheader("Metric Analysis")
176
- st.dataframe(pd.DataFrame.from_dict(st.session_state.metrics))
177
-
178
- if st.button("Request AI Analysis"):
179
- analysis = handle_ai_query("Analyze these model metrics")
180
- st.markdown(f"**AI Analysis:**\n\n{analysis}")
181
 
182
  # Chatbot Interface
183
  def ai_assistant():
184
- st.markdown("---")
185
- st.subheader("🧠 Neural Insight Assistant")
 
 
 
186
 
187
  for msg in st.session_state.chat_history:
188
- st.chat_message(msg["role"]).write(msg["content"])
 
189
 
190
- if prompt := st.chat_input("Ask about models, data, or app usage"):
191
  st.session_state.chat_history.append({"role": "user", "content": prompt})
192
- st.chat_message("user").write(prompt)
 
193
 
194
- response = handle_ai_query(prompt)
 
 
195
 
196
- st.session_state.chat_history.append({"role": "assistant", "content": response})
197
- st.chat_message("assistant").write(response)
 
 
 
 
 
 
 
 
 
 
198
 
199
- # App Layout
200
  with st.sidebar:
201
  st.title("🔮 Neural-Vision Enhanced")
202
  page = st.selectbox("Navigation", [
203
  "Data Upload & Analysis",
204
- "Model Training Studio",
205
- "Model Evaluation Center"
206
  ])
207
  st.session_state.active_page = page
208
  st.markdown("---")
209
- st.markdown("**DeepSeek API Key**")
210
- os.environ["DEEPSEEK_API_KEY"] = st.text_input(
211
- "Enter API Key:", type="password",
212
- help="Required for AI analysis features"
213
- )
214
  st.markdown("---")
215
- st.markdown("v4.0 | © 2025 Neural-Vision")
216
 
217
  # Page Routing
218
  if "Data Upload & Analysis" in page:
219
  data_upload_page()
220
- elif "Model Training Studio" in page:
221
  model_training_page()
222
  else:
223
  visualization_page()
 
2
  import pandas as pd
3
  import plotly.express as px
4
  import numpy as np
5
+ from sklearn.model_selection import train_test_split
6
+ from sklearn.neural_network import MLPClassifier, MLPRegressor
7
+ from sklearn.cluster import KMeans
8
+ from sklearn.metrics import accuracy_score, r2_score, silhouette_score, confusion_matrix, classification_report, mean_squared_error
9
+ from sklearn.preprocessing import StandardScaler
10
  from ydata_profiling import ProfileReport
11
  from streamlit_pandas_profiling import st_profile_report
12
+ from groq import Groq
13
+ from langchain_community.vectorstores import FAISS
14
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
15
+ from langchain.embeddings import HuggingFaceEmbeddings
16
+ from langchain_community.document_loaders import TextLoader
17
+ from langchain_community.tools.tavily_search import TavilySearchResults
18
  import os
19
+ from dotenv import load_dotenv
20
+ import tempfile
21
+
22
+ # Load environment variables
23
+ load_dotenv()
24
+
25
+ # Initialize Groq client
26
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
27
+
28
+ # Initialize embeddings for FAISS
29
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
30
 
31
  # Set page config
32
  st.set_page_config(page_title="Neural-Vision Enhanced", layout="wide")
33
 
34
+ # Custom CSS matching previous theme
35
+ st.markdown("""
36
+ <style>
37
+ :root {
38
+ --primary-blue: #3B82F6;
39
+ --dark-blue: #1E40AF;
40
+ --light-blue: #DBEAFE;
41
+ --medium-grey: #6B7280;
42
+ --light-grey: #F3F4F6;
43
+ --white: #FFFFFF;
44
+ --border-grey: #E5E7EB;
45
+ }
46
+ .stApp {
47
+ background-color: var(--light-grey);
48
+ font-family: 'Inter', sans-serif;
49
+ max-width: 1200px;
50
+ margin: 0 auto;
51
+ }
52
+ .header {
53
+ background-color: var(--white);
54
+ border-bottom: 2px solid var(--border-grey);
55
+ padding: 15px;
56
+ border-radius: 12px 12px 0 0;
57
+ box-shadow: 0 2px 4px rgba(0,0,0,0.05);
58
+ text-align: center;
59
+ }
60
+ .header-title {
61
+ color: var(--dark-blue);
62
+ font-size: 1.8rem;
63
+ font-weight: 700;
64
+ margin: 0;
65
+ }
66
+ .header-subtitle {
67
+ color: var(--medium-grey);
68
+ font-size: 1rem;
69
+ margin-top: 5px;
70
+ }
71
+ .sidebar .sidebar-content {
72
+ background-color: var(--white);
73
+ border-radius: 12px;
74
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
75
+ padding: 15px;
76
+ }
77
+ .chat-container {
78
+ background-color: var(--white);
79
+ border-radius: 12px;
80
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
81
+ padding: 15px;
82
+ margin-top: 20px;
83
+ }
84
+ .user-message {
85
+ background-color: var(--primary-blue);
86
+ color: var(--white);
87
+ border-radius: 18px 18px 4px 18px;
88
+ padding: 12px 16px;
89
+ margin-left: auto;
90
+ max-width: 80%;
91
+ margin-bottom: 10px;
92
+ }
93
+ .bot-message {
94
+ background-color: var(--light-grey);
95
+ color: var(--medium-grey);
96
+ border-radius: 18px 18px 18px 4px;
97
+ padding: 12px 16px;
98
+ margin-right: auto;
99
+ max-width: 80%;
100
+ margin-bottom: 10px;
101
+ }
102
+ </style>
103
+ """, unsafe_allow_html=True)
104
 
105
  # Initialize session state
106
+ if 'metrics' not in st.session_state:
107
+ st.session_state.metrics = {}
108
+ if 'chat_history' not in st.session_state:
109
+ st.session_state.chat_history = []
110
+ if 'vector_store' not in st.session_state:
111
+ st.session_state.vector_store = None
112
+
113
+ # Helper Functions
114
+ def convert_df_to_text(df):
115
+ text = f"Dataset Summary: {df.shape[0]} rows, {df.shape[1]} columns\n"
116
+ text += f"Missing Values: {df.isna().sum().sum()}\n"
117
+ text += "Columns:\n"
118
+ for col in df.columns:
119
+ text += f"- {col} ({df[col].dtype}): "
120
+ if pd.api.types.is_numeric_dtype(df[col]):
121
+ text += f"Mean={df[col].mean():.2f}, Min={df[col].min()}, Max={df[col].max()}"
122
+ else:
123
+ text += f"Unique={df[col].nunique()}, Top={df[col].mode()[0] if not df[col].mode().empty else 'N/A'}"
124
+ text += f", Missing={df[col].isna().sum()}\n"
125
+ return text
126
+
127
+ def create_vector_store(df_text):
128
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as temp_file:
129
+ temp_file.write(df_text)
130
+ temp_path = temp_file.name
131
+ loader = TextLoader(temp_path)
132
+ documents = loader.load()
133
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
134
+ texts = text_splitter.split_documents(documents)
135
+ vector_store = FAISS.from_documents(texts, embeddings)
136
+ os.unlink(temp_path)
137
+ return vector_store
138
+
139
+ def get_groq_response(prompt, mode, use_web_search=False):
140
+ context = ""
141
+ if st.session_state.vector_store:
142
+ docs = st.session_state.vector_store.similarity_search(prompt, k=3)
143
+ context = "\n\nDataset Context:\n" + "\n".join([f"- {doc.page_content}" for doc in docs])
144
 
145
+ if use_web_search:
146
+ tavily = TavilySearchResults(max_results=3)
147
+ web_results = tavily.invoke(prompt)
148
+ context += "\n\nWeb Search Results:\n" + "\n".join([f"- {res['content'][:200]}..." for res in web_results])
149
+
150
+ prompts = {
151
+ "Legal": "You are a neural network expert specializing in legal data analysis.",
152
+ "Financial": "You are a neural network expert specializing in financial data analysis.",
153
+ "Academic": "You are a neural network expert specializing in academic data analysis.",
154
+ "Technical": "You are a neural network expert specializing in technical data analysis."
 
 
 
 
 
 
 
155
  }
156
+ system_prompt = prompts.get(mode, "You are a neural network development assistant.") + "\n" + context
157
 
158
+ response = client.chat.completions.create(
159
+ model="llama3-70b-8192",
160
+ messages=[
161
+ {"role": "system", "content": system_prompt},
162
+ {"role": "user", "content": prompt}
163
+ ],
164
+ temperature=0.7,
165
+ max_tokens=1024
166
+ )
167
+ return response.choices[0].message.content
168
+
169
+ # Visualization Functions
170
+ def plot_confusion_matrix(y_true, y_pred):
171
+ cm = confusion_matrix(y_true, y_pred)
172
+ fig = px.imshow(cm, text_auto=True, color_continuous_scale='Blues', title="Confusion Matrix")
173
+ return fig
174
+
175
+ def plot_feature_importance(model, X):
176
+ if hasattr(model, 'feature_importances_'):
177
+ importance = model.feature_importances_
178
+ else:
179
+ importance = np.abs(model.coef_) if hasattr(model, 'coef_') else np.ones(X.shape[1])
180
+ fig = px.bar(x=X.columns, y=importance, title="Feature Importance")
181
+ return fig
182
+
183
+ def plot_residuals(y_true, y_pred):
184
+ residuals = y_true - y_pred
185
+ fig = px.scatter(x=y_pred, y=residuals, title="Residual Plot", labels={"x": "Predicted", "y": "Residuals"})
186
+ return fig
187
+
188
+ def plot_clusters(X, labels):
189
+ fig = px.scatter(X, x=X.columns[0], y=X.columns[1], color=labels, title="Cluster Visualization")
190
+ return fig
191
+
192
+ # Pages
193
  def data_upload_page():
194
+ st.header("📤 Data Upload & Analysis")
195
  uploaded_file = st.file_uploader("Upload Dataset", type=["csv"])
196
 
197
  if uploaded_file:
198
  df = pd.read_csv(uploaded_file)
199
  st.session_state.df = df
200
+ st.session_state.vector_store = create_vector_store(convert_df_to_text(df))
201
  st.session_state.metrics = {}
202
 
203
  st.subheader("Dataset Health Check")
 
212
  st_profile_report(profile)
213
 
214
  def model_training_page():
215
+ st.header("🧠 Neural Network Training Studio")
216
 
217
  if 'df' not in st.session_state:
218
  st.warning("Upload data first!")
 
220
 
221
  df = st.session_state.df
222
  problem_type = st.selectbox("Select Problem Type", ["Classification", "Regression", "Clustering"])
223
+ mode = st.selectbox("Domain Specialization", ["Legal", "Financial", "Academic", "Technical"])
224
 
225
  if problem_type != "Clustering":
226
+ target = st.selectbox("Select Target Variable", df.columns)
227
+ X = df.drop(columns=[target])
228
+ y = df[target]
229
+ else:
230
+ X = df
231
+ y = None
232
 
233
+ if st.button("Train Neural Network"):
234
+ with st.spinner("Training in progress..."):
235
+ X_scaled = StandardScaler().fit_transform(X)
236
+ X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42) if y is not None else (X_scaled, None, None, None)
 
 
 
 
 
 
 
 
 
 
 
 
237
 
238
+ if problem_type == "Classification":
239
+ model = MLPClassifier(hidden_layer_sizes=(100, 50), max_iter=500, random_state=42)
240
+ model.fit(X_train, y_train)
241
+ y_pred = model.predict(X_test)
242
+ st.session_state.metrics = {
243
+ "Accuracy": accuracy_score(y_test, y_pred),
244
+ "Classification Report": classification_report(y_test, y_pred, output_dict=True)
245
+ }
246
+ elif problem_type == "Regression":
247
+ model = MLPRegressor(hidden_layer_sizes=(100, 50), max_iter=500, random_state=42)
248
+ model.fit(X_train, y_train)
249
+ y_pred = model.predict(X_test)
250
+ st.session_state.metrics = {
251
+ "R2 Score": r2_score(y_test, y_pred),
252
+ "Mean Squared Error": mean_squared_error(y_test, y_pred)
253
+ }
254
+ else: # Clustering
255
+ model = KMeans(n_clusters=3, random_state=42)
256
+ labels = model.fit_predict(X_scaled)
257
+ st.session_state.metrics = {
258
+ "Silhouette Score": silhouette_score(X_scaled, labels)
259
+ }
260
+
261
+ st.session_state.best_model = model
262
+ st.session_state.X_test = X_test
263
+ st.session_state.y_test = y_test
264
+ st.session_state.y_pred = y_pred if y is not None else labels
265
+ st.session_state.problem_type = problem_type
266
+ st.success(f"Model trained successfully in {mode} mode!")
267
 
268
  def visualization_page():
269
+ st.header("🔍 Neural Network Evaluation Center")
270
 
271
  if 'best_model' not in st.session_state:
272
  st.warning("Train a model first!")
273
  return
274
 
275
  st.subheader("Performance Analysis")
276
+ if st.session_state.problem_type == "Classification":
277
+ st.plotly_chart(plot_confusion_matrix(st.session_state.y_test, st.session_state.y_pred))
278
+ st.plotly_chart(plot_feature_importance(st.session_state.best_model, pd.DataFrame(st.session_state.X_test, columns=st.session_state.df.columns[:-1])))
279
+ elif st.session_state.problem_type == "Regression":
280
+ st.plotly_chart(plot_residuals(st.session_state.y_test, st.session_state.y_pred))
281
+ st.plotly_chart(plot_feature_importance(st.session_state.best_model, pd.DataFrame(st.session_state.X_test, columns=st.session_state.df.columns[:-1])))
282
+ else: # Clustering
283
+ st.plotly_chart(plot_clusters(pd.DataFrame(st.session_state.X_test, columns=st.session_state.df.columns), st.session_state.y_pred))
284
 
285
+ st.subheader("Metrics")
286
+ st.write(st.session_state.metrics)
 
 
 
 
 
 
 
 
 
 
 
287
 
288
  # Chatbot Interface
289
  def ai_assistant():
290
+ st.markdown('<div class="chat-container">', unsafe_allow_html=True)
291
+ st.subheader("🧠 Neural Insight Assistant (RAG + Web Search)")
292
+
293
+ use_web_search = st.checkbox("Enable Tavily Web Search", value=False)
294
+ mode = st.selectbox("Domain Mode", ["Legal", "Financial", "Academic", "Technical"], key="chat_mode")
295
 
296
  for msg in st.session_state.chat_history:
297
+ with st.chat_message(msg["role"]):
298
+ st.markdown(f'<div class="{msg["role"]}-message">{msg["content"]}</div>', unsafe_allow_html=True)
299
 
300
+ if prompt := st.chat_input("Ask about data, models, or web insights..."):
301
  st.session_state.chat_history.append({"role": "user", "content": prompt})
302
+ with st.chat_message("user"):
303
+ st.markdown(f'<div class="user-message">{prompt}</div>', unsafe_allow_html=True)
304
 
305
+ with st.spinner("Processing..."):
306
+ response = get_groq_response(prompt, mode, use_web_search)
307
+ st.session_state.chat_history.append({"role": "assistant", "content": response})
308
 
309
+ with st.chat_message("assistant"):
310
+ st.markdown(f'<div class="bot-message">{response}</div>', unsafe_allow_html=True)
311
+
312
+ st.markdown('</div>', unsafe_allow_html=True)
313
+
314
+ # Main App Layout
315
+ st.markdown("""
316
+ <div class="header">
317
+ <h1 class="header-title">Neural-Vision Enhanced</h1>
318
+ <div class="header-subtitle">Neural Network Development for Domain-Specialized Analysis</div>
319
+ </div>
320
+ """, unsafe_allow_html=True)
321
 
 
322
  with st.sidebar:
323
  st.title("🔮 Neural-Vision Enhanced")
324
  page = st.selectbox("Navigation", [
325
  "Data Upload & Analysis",
326
+ "Neural Network Training Studio",
327
+ "Neural Network Evaluation Center"
328
  ])
329
  st.session_state.active_page = page
330
  st.markdown("---")
331
+ st.markdown("**Environment Setup**")
332
+ os.environ["TAVILY_API_KEY"] = st.text_input("Tavily API Key", type="password", help="For web search functionality")
 
 
 
333
  st.markdown("---")
334
+ st.markdown("v5.0 | © 2025 Neural-Vision")
335
 
336
  # Page Routing
337
  if "Data Upload & Analysis" in page:
338
  data_upload_page()
339
+ elif "Neural Network Training Studio" in page:
340
  model_training_page()
341
  else:
342
  visualization_page()