CosmickVisions commited on
Commit
b4e9662
·
verified ·
1 Parent(s): cb10183

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -251
app.py CHANGED
@@ -5,7 +5,7 @@ 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
@@ -14,11 +14,8 @@ from langchain_community.vectorstores import FAISS
14
  from langchain.text_splitter import RecursiveCharacterTextSplitter
15
  from langchain_huggingface import HuggingFaceEmbeddings
16
  from langchain_community.document_loaders import TextLoader
17
- from langchain_community.tools.tavily_search import TavilySearchResults
18
- import torch
19
  import os
20
  import tempfile
21
- import json
22
 
23
  # Initialize clients
24
  client = Groq(api_key=os.getenv("GROQ_API_KEY"))
@@ -27,141 +24,106 @@ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-
27
  # Set page config
28
  st.set_page_config(page_title="Neural-Vision Enhanced", layout="wide")
29
 
30
- # Custom CSS
31
  st.markdown("""
32
  <style>
33
  :root {
34
- --primary-blue: #3B82F6;
35
- --dark-blue: #1E40AF;
36
- --light-blue: #DBEAFE;
37
- --medium-grey: #6B7280;
38
- --light-grey: #F3F4F6;
39
- --white: #FFFFFF;
40
- --border-grey: #E5E7EB;
41
- --success-green: #10B981;
42
- --warning-yellow: #F59E0B;
43
  }
44
  .stApp {
45
- background-color: var(--light-grey);
46
  font-family: 'Inter', sans-serif;
47
  max-width: 1200px;
48
  margin: 0 auto;
 
49
  }
50
  .header {
51
- background-color: var(--white);
52
- border-bottom: 2px solid var(--border-grey);
53
  padding: 15px;
54
- border-radius: 12px 12px 0 0;
55
- box-shadow: 0 2px 4px rgba(0,0,0,0.05);
56
  text-align: center;
 
57
  }
58
  .header-title {
59
- color: var(--dark-blue);
60
  font-size: 1.8rem;
61
  font-weight: 700;
62
  margin: 0;
63
  }
64
  .header-subtitle {
65
- color: var(--medium-grey);
66
  font-size: 1rem;
67
  margin-top: 5px;
68
  }
69
  .card {
70
- background-color: var(--white);
71
- border-radius: 12px;
72
- box-shadow: 0 4px 6px rgba(0,0,0,0.1);
73
  padding: 20px;
74
  margin-bottom: 20px;
75
  }
76
- .layer-card {
77
- background-color: var(--light-blue);
78
- border-radius: 8px;
79
- padding: 15px;
80
- margin-bottom: 10px;
81
- border-left: 4px solid var(--primary-blue);
82
- }
83
- .sidebar .sidebar-content {
84
- background-color: var(--white);
85
- border-radius: 12px;
86
- box-shadow: 0 4px 6px rgba(0,0,0,0.1);
87
- padding: 15px;
88
- }
89
  .chat-container {
90
- background-color: var(--white);
91
- border-radius: 12px;
92
- box-shadow: 0 4px 6px rgba(0,0,0,0.1);
93
  padding: 15px;
94
  margin-top: 20px;
 
95
  }
96
  .user-message {
97
- background-color: var(--primary-blue);
98
- color: var(--white);
99
- border-radius: 18px 18px 4px 18px;
100
- padding: 12px 16px;
101
- margin-left: auto;
102
  max-width: 80%;
 
103
  margin-bottom: 10px;
104
  }
105
  .bot-message {
106
- background-color: var(--light-grey);
107
- color: var(--medium-grey);
108
- border-radius: 18px 18px 18px 4px;
109
- padding: 12px 16px;
110
- margin-right: auto;
111
  max-width: 80%;
 
112
  margin-bottom: 10px;
113
  }
114
- .model-card {
115
- border: 1px solid var(--border-grey);
116
- border-radius: 8px;
117
- padding: 15px;
118
- margin-bottom: 15px;
119
- transition: all 0.3s ease;
120
- cursor: pointer;
121
- }
122
- .model-card:hover {
123
- box-shadow: 0 4px 12px rgba(0,0,0,0.1);
124
- border-color: var(--primary-blue);
125
- }
126
- .selected-model {
127
- border-color: var(--primary-blue);
128
- background-color: var(--light-blue);
129
- }
130
- .stButton>button {
131
- background-color: var(--primary-blue);
132
  color: white;
133
- border-radius: 6px;
134
  padding: 8px 16px;
135
  border: none;
136
- font-weight: 500;
137
- transition: all 0.3s ease;
138
  }
139
- .stButton>button:hover {
140
- background-color: var(--dark-blue);
141
- box-shadow: 0 4px 6px rgba(0,0,0,0.1);
142
  }
143
- .status-bar {
144
- height: 10px;
145
- width: 100%;
146
- background-color: var(--light-grey);
147
  border-radius: 5px;
148
- margin-top: 10px;
149
- overflow: hidden;
150
- }
151
- .status-progress {
152
- height: 100%;
153
- background-color: var(--primary-blue);
154
- transition: width 0.5s ease;
155
  }
156
- .feature-desc {
157
- font-size: 0.9rem;
158
- color: var(--medium-grey);
159
- margin-top: 5px;
 
 
 
 
 
 
 
 
 
160
  }
161
  </style>
162
  """, unsafe_allow_html=True)
163
 
164
- # Initialize session state
165
  if 'metrics' not in st.session_state:
166
  st.session_state.metrics = {}
167
  if 'chat_history' not in st.session_state:
@@ -175,205 +137,145 @@ if 'prebuilt_selection' not in st.session_state:
175
  if 'model_config' not in st.session_state:
176
  st.session_state.model_config = {}
177
  if 'model_builder_mode' not in st.session_state:
178
- st.session_state.model_builder_mode = "prebuilt" # Options: "prebuilt" or "custom"
179
  if 'custom_model_type' not in st.session_state:
180
- st.session_state.custom_model_type = "classification" # Options: "classification", "regression", "clustering"
181
 
182
- # Prebuilt model templates
183
  PREBUILT_MODELS = {
184
  "Legal Document Classifier": {
185
- "description": "Neural network optimized for legal document classification with special features for contract analysis.",
186
- "architecture": {
187
- "type": "classification",
188
- "hidden_layers": [(128, "relu"), (64, "relu")],
189
- "dropout": 0.3,
190
- "optimizer": "adam",
191
- "learning_rate": 0.001
192
- },
193
- "domain": "Legal",
194
- "use_case": "Document classification"
195
  },
196
  "Financial Fraud Detector": {
197
- "description": "Deep learning model designed to detect anomalies in financial transactions with high accuracy.",
198
- "architecture": {
199
- "type": "classification",
200
- "hidden_layers": [(256, "relu"), (128, "relu"), (64, "relu")],
201
- "dropout": 0.4,
202
- "optimizer": "adam",
203
- "learning_rate": 0.0005
204
- },
205
- "domain": "Financial",
206
- "use_case": "Fraud detection"
207
- },
208
- "Academic Paper Topic Classifier": {
209
- "description": "Neural model for categorizing academic papers by subject area.",
210
- "architecture": {
211
- "type": "classification",
212
- "hidden_layers": [(100, "relu"), (50, "tanh")],
213
- "dropout": 0.2,
214
- "optimizer": "adam",
215
- "learning_rate": 0.001
216
- },
217
- "domain": "Academic",
218
- "use_case": "Topic classification"
219
- },
220
- "Customer Churn Predictor": {
221
- "description": "Regression model that predicts likelihood of customer churn based on engagement metrics.",
222
- "architecture": {
223
- "type": "regression",
224
- "hidden_layers": [(64, "relu"), (32, "relu")],
225
- "dropout": 0.2,
226
- "optimizer": "adam",
227
- "learning_rate": 0.001
228
- },
229
- "domain": "Business",
230
- "use_case": "Churn prediction"
231
- },
232
- "Medical Diagnosis Assistant": {
233
- "description": "Classification model for preliminary medical diagnosis based on patient symptoms and metrics.",
234
- "architecture": {
235
- "type": "classification",
236
- "hidden_layers": [(128, "relu"), (64, "relu"), (32, "relu")],
237
- "dropout": 0.3,
238
- "optimizer": "adam",
239
- "learning_rate": 0.0005
240
- },
241
- "domain": "Healthcare",
242
- "use_case": "Diagnosis assistance"
243
  },
244
  "Customer Segmentation Engine": {
245
- "description": "Clustering model for advanced customer segmentation based on behavioral patterns.",
246
- "architecture": {
247
- "type": "clustering",
248
- "n_clusters": 5,
249
- "algorithm": "kmeans",
250
- "init": "k-means++",
251
- "n_init": 10
252
- },
253
- "domain": "Marketing",
254
- "use_case": "Customer segmentation"
255
  }
256
  }
257
 
258
- # Helper Functions
259
  def convert_df_to_text(df):
260
- """Convert dataframe to text format for RAG system"""
261
  text = f"Dataset Summary: {df.shape[0]} rows, {df.shape[1]} columns\n"
262
  text += f"Missing Values: {df.isna().sum().sum()}\n"
263
- text += "Columns:\n"
264
  for col in df.columns:
265
- text += f"- {col} ({df[col].dtype}): "
266
- if pd.api.types.is_numeric_dtype(df[col]):
267
- text += f"Mean={df[col].mean():.2f}, Min={df[col].min()}, Max={df[col].max()}"
268
- else:
269
- text += f"Unique={df[col].nunique()}, Top={df[col].mode()[0] if not df[col].mode().empty else 'N/A'}"
270
- text += f", Missing={df[col].isna().sum()}\n"
271
  return text
272
 
273
  def create_vector_store(df_text):
274
- """Create FAISS vector store from dataframe text"""
275
  with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as temp_file:
276
  temp_file.write(df_text)
277
  temp_path = temp_file.name
278
  loader = TextLoader(temp_path)
279
  documents = loader.load()
280
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
281
- texts = text_splitter.split_documents(documents)
282
  vector_store = FAISS.from_documents(texts, embeddings)
283
  os.unlink(temp_path)
284
  return vector_store
285
 
286
- def get_groq_response(prompt, mode, context_type="model_building", use_web_search=False):
287
- """Get response from Groq LLM with different context types"""
288
  context = ""
289
- sources = []
290
-
291
- # RAG context from uploaded data
292
  if st.session_state.vector_store:
293
  docs = st.session_state.vector_store.similarity_search(prompt, k=3)
294
- context += "\n\nUploaded Dataset Context:\n" + "\n".join([f"- {doc.page_content}" for doc in docs])
295
- sources.append("Uploaded Data")
296
-
297
- # Tavily web search if toggled
298
- if use_web_search:
299
- tavily_api_key = os.environ.get("TAVILY_API_KEY")
300
- if tavily_api_key:
301
- try:
302
- tavily = TavilySearchResults(max_results=3, api_key=tavily_api_key)
303
- web_results = tavily.invoke(prompt)
304
- context += "\n\nWeb Search Results (Tavily):\n" + "\n".join([f"- {res['content'][:200]}..." for res in web_results])
305
- sources.append("Tavily Web Search")
306
- except Exception as e:
307
- return f"Error with Tavily web search: {str(e)}. Ensure your API key is valid."
308
- else:
309
- context += "\n\nWeb search requested but no Tavily API key provided."
310
-
311
- # Model building context
312
- if context_type == "model_building":
313
- context += "\n\nYou are advising on neural network architecture and implementation. Provide specific layer recommendations, parameters, and explain your reasoning. Be specific with activation functions, layer sizes, and learning approaches."
314
-
315
- # Domain-specific prompt
316
- prompts = {
317
- "Legal": "You are an expert in legal data analysis, providing insights and predictions based on available data and web information if enabled.",
318
- "Financial": "You are an expert in financial data analysis, providing insights and predictions based on available data and web information if enabled.",
319
- "Academic": "You are an expert in academic data analysis, providing insights and predictions based on available data and web information if enabled.",
320
- "Technical": "You are an expert in technical data analysis, providing insights and predictions based on available data and web information if enabled.",
321
- "Healthcare": "You are an expert in healthcare data analysis, providing medical insights based on available data and web information if enabled.",
322
- "Marketing": "You are an expert in marketing data analysis, providing customer insights based on available data and web information if enabled."
323
- }
324
- system_prompt = prompts.get(mode, prompts["Technical"]) + "\n" + context
325
-
326
  try:
327
  response = client.chat.completions.create(
328
  model="llama3-70b-8192",
329
  messages=[
330
- {"role": "system", "content": system_prompt},
331
  {"role": "user", "content": prompt}
332
- ],
333
- temperature=0.7,
334
- max_tokens=1024
335
  ).choices[0].message.content
336
- return response + f"\n\n**Sources:** {', '.join(sources) if sources else 'General Knowledge'}"
337
  except Exception as e:
338
- return f"Error generating response: {str(e)}"
339
 
340
  def build_model_from_config(config, X, y=None):
341
- """Build a model from configuration dictionary"""
342
  problem_type = config.get("type", "classification")
343
-
344
  if problem_type == "clustering":
345
- model = KMeans(
346
- n_clusters=config.get("n_clusters", 3),
347
- init=config.get("init", "k-means++"),
348
- n_init=config.get("n_init", 10),
349
- random_state=42
350
- )
351
- else:
352
- # Extract hidden layer sizes and activations
353
- hidden_layers = config.get("hidden_layers", [(100, "relu")])
354
- layer_sizes = [size for size, _ in hidden_layers]
355
- activation = hidden_layers[0][1] if hidden_layers else "relu"
356
-
357
- # Create appropriate model based on problem type
358
- if problem_type == "classification":
359
- model = MLPClassifier(
360
- hidden_layer_sizes=layer_sizes,
361
- activation=activation,
362
- solver=config.get("optimizer", "adam"),
363
- alpha=config.get("regularization", 0.0001),
364
- learning_rate_init=config.get("learning_rate", 0.001),
365
- max_iter=config.get("max_iter", 500),
366
- random_state=42
367
- )
368
- else: # regression
369
- model = MLPRegressor(
370
- hidden_layer_sizes=layer_sizes,
371
- activation=activation,
372
- solver=config.get("optimizer", "adam"),
373
- alpha=config.get("regularization", 0.0001),
374
- learning_rate_init=config.get("learning_rate", 0.001),
375
- max_iter=config.get("max_iter", 500),
376
- random_state=42
377
- )
378
-
379
- return model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
9
  from sklearn.preprocessing import StandardScaler
10
  from ydata_profiling import ProfileReport
11
  from streamlit_pandas_profiling import st_profile_report
 
14
  from langchain.text_splitter import RecursiveCharacterTextSplitter
15
  from langchain_huggingface import HuggingFaceEmbeddings
16
  from langchain_community.document_loaders import TextLoader
 
 
17
  import os
18
  import tempfile
 
19
 
20
  # Initialize clients
21
  client = Groq(api_key=os.getenv("GROQ_API_KEY"))
 
24
  # Set page config
25
  st.set_page_config(page_title="Neural-Vision Enhanced", layout="wide")
26
 
27
+ # Custom CSS for Responsive Silver-Blue-Gold Theme
28
  st.markdown("""
29
  <style>
30
  :root {
31
+ --silver: #D8D8D8;
32
+ --blue: #5C89BC;
33
+ --gold: #A87E01;
34
+ --text-color: #333333;
 
 
 
 
 
35
  }
36
  .stApp {
37
+ background-color: var(--silver);
38
  font-family: 'Inter', sans-serif;
39
  max-width: 1200px;
40
  margin: 0 auto;
41
+ padding: 10px;
42
  }
43
  .header {
44
+ background-color: var(--blue);
45
+ color: white;
46
  padding: 15px;
47
+ border-radius: 5px;
 
48
  text-align: center;
49
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
50
  }
51
  .header-title {
 
52
  font-size: 1.8rem;
53
  font-weight: 700;
54
  margin: 0;
55
  }
56
  .header-subtitle {
 
57
  font-size: 1rem;
58
  margin-top: 5px;
59
  }
60
  .card {
61
+ background-color: white;
62
+ border-radius: 5px;
63
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
64
  padding: 20px;
65
  margin-bottom: 20px;
66
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  .chat-container {
68
+ background-color: white;
69
+ border-radius: 5px;
 
70
  padding: 15px;
71
  margin-top: 20px;
72
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
73
  }
74
  .user-message {
75
+ background-color: var(--blue);
76
+ color: white;
77
+ border-radius: 15px 15px 5px 15px;
78
+ padding: 10px;
 
79
  max-width: 80%;
80
+ margin-left: auto;
81
  margin-bottom: 10px;
82
  }
83
  .bot-message {
84
+ background-color: #F0F0F0;
85
+ color: var(--text-color);
86
+ border-radius: 15px 15px 15px 5px;
87
+ padding: 10px;
 
88
  max-width: 80%;
89
+ margin-right: auto;
90
  margin-bottom: 10px;
91
  }
92
+ .stButton > button {
93
+ background-color: var(--gold);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  color: white;
95
+ border-radius: 5px;
96
  padding: 8px 16px;
97
  border: none;
98
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
 
99
  }
100
+ .stButton > button:hover {
101
+ background-color: #8C6B01;
 
102
  }
103
+ .sidebar .sidebar-content {
104
+ background-color: white;
 
 
105
  border-radius: 5px;
106
+ padding: 15px;
107
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
 
 
 
 
 
108
  }
109
+ @media (max-width: 768px) {
110
+ .header-title {
111
+ font-size: 1.4rem;
112
+ }
113
+ .header-subtitle {
114
+ font-size: 0.9rem;
115
+ }
116
+ .card, .chat-container {
117
+ padding: 10px;
118
+ }
119
+ .stApp {
120
+ padding: 5px;
121
+ }
122
  }
123
  </style>
124
  """, unsafe_allow_html=True)
125
 
126
+ # Session State Initialization
127
  if 'metrics' not in st.session_state:
128
  st.session_state.metrics = {}
129
  if 'chat_history' not in st.session_state:
 
137
  if 'model_config' not in st.session_state:
138
  st.session_state.model_config = {}
139
  if 'model_builder_mode' not in st.session_state:
140
+ st.session_state.model_builder_mode = "prebuilt"
141
  if 'custom_model_type' not in st.session_state:
142
+ st.session_state.custom_model_type = "classification"
143
 
144
+ # Prebuilt Models
145
  PREBUILT_MODELS = {
146
  "Legal Document Classifier": {
147
+ "description": "Optimized for legal document classification.",
148
+ "architecture": {"type": "classification", "hidden_layers": [(128, "relu"), (64, "relu")], "dropout": 0.3, "optimizer": "adam", "learning_rate": 0.001},
149
+ "domain": "Legal"
 
 
 
 
 
 
 
150
  },
151
  "Financial Fraud Detector": {
152
+ "description": "Detects anomalies in financial transactions.",
153
+ "architecture": {"type": "classification", "hidden_layers": [(256, "relu"), (128, "relu"), (64, "relu")], "dropout": 0.4, "optimizer": "adam", "learning_rate": 0.0005},
154
+ "domain": "Financial"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  },
156
  "Customer Segmentation Engine": {
157
+ "description": "Advanced customer segmentation.",
158
+ "architecture": {"type": "clustering", "n_clusters": 5, "algorithm": "kmeans", "init": "k-means++", "n_init": 10},
159
+ "domain": "Marketing"
 
 
 
 
 
 
 
160
  }
161
  }
162
 
163
+ # Helper Functions (unchanged from previous)
164
  def convert_df_to_text(df):
 
165
  text = f"Dataset Summary: {df.shape[0]} rows, {df.shape[1]} columns\n"
166
  text += f"Missing Values: {df.isna().sum().sum()}\n"
 
167
  for col in df.columns:
168
+ text += f"- {col} ({df[col].dtype}): Mean={df[col].mean():.2f if pd.api.types.is_numeric_dtype(df[col]) else 'N/A'}\n"
 
 
 
 
 
169
  return text
170
 
171
  def create_vector_store(df_text):
 
172
  with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as temp_file:
173
  temp_file.write(df_text)
174
  temp_path = temp_file.name
175
  loader = TextLoader(temp_path)
176
  documents = loader.load()
177
+ texts = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100).split_documents(documents)
 
178
  vector_store = FAISS.from_documents(texts, embeddings)
179
  os.unlink(temp_path)
180
  return vector_store
181
 
182
+ def get_groq_response(prompt, mode):
 
183
  context = ""
 
 
 
184
  if st.session_state.vector_store:
185
  docs = st.session_state.vector_store.similarity_search(prompt, k=3)
186
+ context += "\nDataset Context:\n" + "\n".join([f"- {doc.page_content}" for doc in docs])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  try:
188
  response = client.chat.completions.create(
189
  model="llama3-70b-8192",
190
  messages=[
191
+ {"role": "system", "content": f"You are an expert in {mode} data analysis.\n{context}"},
192
  {"role": "user", "content": prompt}
193
+ ]
 
 
194
  ).choices[0].message.content
195
+ return response
196
  except Exception as e:
197
+ return f"Error: {str(e)}"
198
 
199
  def build_model_from_config(config, X, y=None):
 
200
  problem_type = config.get("type", "classification")
 
201
  if problem_type == "clustering":
202
+ return KMeans(n_clusters=config.get("n_clusters", 3), init=config.get("init", "k-means++"), n_init=config.get("n_init", 10), random_state=42)
203
+ hidden_layers = config.get("hidden_layers", [(100, "relu")])
204
+ layer_sizes = [size for size, _ in hidden_layers]
205
+ activation = hidden_layers[0][1] if hidden_layers else "relu"
206
+ if problem_type == "classification":
207
+ return MLPClassifier(hidden_layer_sizes=layer_sizes, activation=activation, solver=config.get("optimizer", "adam"), learning_rate_init=config.get("learning_rate", 0.001), random_state=42)
208
+ return MLPRegressor(hidden_layer_sizes=layer_sizes, activation=activation, solver=config.get("optimizer", "adam"), learning_rate_init=config.get("learning_rate", 0.001), random_state=42)
209
+
210
+ # Main Application
211
+ def main():
212
+ st.markdown('<div class="header"><h1 class="header-title">Neural-Vision Enhanced</h1><p class="header-subtitle">Build & Train Neural Networks</p></div>', unsafe_allow_html=True)
213
+
214
+ with st.sidebar:
215
+ st.markdown('<div class="card"><h3>Data Input</h3></div>', unsafe_allow_html=True)
216
+ uploaded_file = st.file_uploader("Upload CSV Dataset", type=["csv"])
217
+ if uploaded_file:
218
+ df = pd.read_csv(uploaded_file)
219
+ st.session_state.vector_store = create_vector_store(convert_df_to_text(df))
220
+ st.success("Dataset uploaded!")
221
+
222
+ col1, col2 = st.columns([2, 1])
223
+ with col1:
224
+ st.markdown('<div class="card"><h2>Model Builder</h2></div>', unsafe_allow_html=True)
225
+ mode = st.selectbox("Domain", ["Legal", "Financial", "Marketing"])
226
+ model_builder_mode = st.radio("Mode", ["Prebuilt", "Custom"])
227
+ st.session_state.model_builder_mode = "prebuilt" if model_builder_mode == "Prebuilt" else "custom"
228
+
229
+ if st.session_state.model_builder_mode == "prebuilt":
230
+ for name, details in PREBUILT_MODELS.items():
231
+ if st.button(f"{name}: {details['description']}", key=name):
232
+ st.session_state.prebuilt_selection = name
233
+ st.session_state.model_config = details["architecture"]
234
+ if st.session_state.prebuilt_selection:
235
+ st.json(st.session_state.model_config)
236
+ else:
237
+ st.session_state.custom_model_type = st.selectbox("Type", ["classification", "regression", "clustering"])
238
+ if st.session_state.custom_model_type != "clustering":
239
+ layer_count = st.number_input("Layers", min_value=1, value=1)
240
+ st.session_state.custom_layers = []
241
+ for i in range(int(layer_count)):
242
+ size = st.number_input(f"Layer {i+1} Size", min_value=1, value=100, key=f"size_{i}")
243
+ activation = st.selectbox(f"Layer {i+1} Activation", ["relu", "tanh"], key=f"act_{i}")
244
+ st.session_state.custom_layers.append((size, activation))
245
+ optimizer = st.selectbox("Optimizer", ["adam", "sgd"])
246
+ st.session_state.model_config = {"type": st.session_state.custom_model_type, "hidden_layers": st.session_state.custom_layers, "optimizer": optimizer, "learning_rate": 0.001}
247
+ else:
248
+ st.session_state.model_config = {"type": "clustering", "n_clusters": st.number_input("Clusters", min_value=2, value=3)}
249
+ if st.button("Finalize"): st.json(st.session_state.model_config)
250
+
251
+ with col2:
252
+ st.markdown('<div class="chat-container"><h3>Chat with Grok</h3></div>', unsafe_allow_html=True)
253
+ prompt = st.text_input("Ask a question:")
254
+ if prompt:
255
+ response = get_groq_response(prompt, mode)
256
+ st.session_state.chat_history.append({"role": "user", "content": prompt})
257
+ st.session_state.chat_history.append({"role": "bot", "content": response})
258
+ for msg in st.session_state.chat_history:
259
+ st.markdown(f'<div class={"user-message" if msg["role"] == "user" else "bot-message"}>{msg["content"]}</div>', unsafe_allow_html=True)
260
+
261
+ if uploaded_file and st.session_state.model_config:
262
+ st.markdown('<div class="card"><h2>Train Model</h2></div>', unsafe_allow_html=True)
263
+ df = pd.read_csv(uploaded_file)
264
+ X = df.drop(columns=[df.columns[-1]]) if st.session_state.model_config["type"] != "clustering" else df
265
+ y = df[df.columns[-1]] if st.session_state.model_config["type"] != "clustering" else None
266
+ if st.button("Train"):
267
+ scaler = StandardScaler()
268
+ X_scaled = scaler.fit_transform(X)
269
+ model = build_model_from_config(st.session_state.model_config, X_scaled, y)
270
+ if st.session_state.model_config["type"] != "clustering":
271
+ X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
272
+ model.fit(X_train, y_train)
273
+ y_pred = model.predict(X_test)
274
+ st.session_state.metrics = {"accuracy" if st.session_state.model_config["type"] == "classification" else "r2_score": accuracy_score(y_test, y_pred) if st.session_state.model_config["type"] == "classification" else r2_score(y_test, y_pred)}
275
+ else:
276
+ model.fit(X_scaled)
277
+ st.session_state.metrics = {"silhouette_score": silhouette_score(X_scaled, model.labels_)}
278
+ st.json(st.session_state.metrics)
279
+
280
+ if __name__ == "__main__":
281
+ main()