Spaces:
Build error
Build error
Update app.py
Browse files
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
|
| 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 |
-
--
|
| 35 |
-
--
|
| 36 |
-
--
|
| 37 |
-
--
|
| 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(--
|
| 46 |
font-family: 'Inter', sans-serif;
|
| 47 |
max-width: 1200px;
|
| 48 |
margin: 0 auto;
|
|
|
|
| 49 |
}
|
| 50 |
.header {
|
| 51 |
-
background-color: var(--
|
| 52 |
-
|
| 53 |
padding: 15px;
|
| 54 |
-
border-radius:
|
| 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:
|
| 71 |
-
border-radius:
|
| 72 |
-
box-shadow: 0 4px
|
| 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:
|
| 91 |
-
border-radius:
|
| 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(--
|
| 98 |
-
color:
|
| 99 |
-
border-radius:
|
| 100 |
-
padding:
|
| 101 |
-
margin-left: auto;
|
| 102 |
max-width: 80%;
|
|
|
|
| 103 |
margin-bottom: 10px;
|
| 104 |
}
|
| 105 |
.bot-message {
|
| 106 |
-
background-color:
|
| 107 |
-
color: var(--
|
| 108 |
-
border-radius:
|
| 109 |
-
padding:
|
| 110 |
-
margin-right: auto;
|
| 111 |
max-width: 80%;
|
|
|
|
| 112 |
margin-bottom: 10px;
|
| 113 |
}
|
| 114 |
-
.
|
| 115 |
-
|
| 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:
|
| 134 |
padding: 8px 16px;
|
| 135 |
border: none;
|
| 136 |
-
|
| 137 |
-
transition: all 0.3s ease;
|
| 138 |
}
|
| 139 |
-
.stButton>button:hover {
|
| 140 |
-
background-color:
|
| 141 |
-
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
| 142 |
}
|
| 143 |
-
.
|
| 144 |
-
|
| 145 |
-
width: 100%;
|
| 146 |
-
background-color: var(--light-grey);
|
| 147 |
border-radius: 5px;
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
}
|
| 151 |
-
.status-progress {
|
| 152 |
-
height: 100%;
|
| 153 |
-
background-color: var(--primary-blue);
|
| 154 |
-
transition: width 0.5s ease;
|
| 155 |
}
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
}
|
| 161 |
</style>
|
| 162 |
""", unsafe_allow_html=True)
|
| 163 |
|
| 164 |
-
#
|
| 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"
|
| 179 |
if 'custom_model_type' not in st.session_state:
|
| 180 |
-
st.session_state.custom_model_type = "classification"
|
| 181 |
|
| 182 |
-
# Prebuilt
|
| 183 |
PREBUILT_MODELS = {
|
| 184 |
"Legal Document Classifier": {
|
| 185 |
-
"description": "
|
| 186 |
-
"architecture": {
|
| 187 |
-
|
| 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": "
|
| 198 |
-
"architecture": {
|
| 199 |
-
|
| 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": "
|
| 246 |
-
"architecture": {
|
| 247 |
-
|
| 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 |
-
|
| 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
|
| 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 += "\
|
| 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":
|
| 331 |
{"role": "user", "content": prompt}
|
| 332 |
-
]
|
| 333 |
-
temperature=0.7,
|
| 334 |
-
max_tokens=1024
|
| 335 |
).choices[0].message.content
|
| 336 |
-
return response
|
| 337 |
except Exception as e:
|
| 338 |
-
return f"Error
|
| 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 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
)
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|