-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
5085 lines (4359 loc) · 340 KB
/
app.py
File metadata and controls
5085 lines (4359 loc) · 340 KB
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import pandas as pd
import numpy as np
import altair as alt
import matplotlib.pyplot as plt
import seaborn as sns
import json
import plotly.express as px
import plotly.graph_objects as go
from sklearn.cluster import KMeans
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import OneHotEncoder, StandardScaler, MinMaxScaler, PolynomialFeatures
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score, accuracy_score, classification_report
import folium
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, export_text, plot_tree
from sklearn.ensemble import RandomForestClassifier # Added import
from streamlit_folium import folium_static
from sklearn.cluster import DBSCAN # For Geospatial Clustering # For ROC AUC
import google.generativeai as genai
import io
import base64
import os
import re
from datetime import datetime, timedelta
import time # Import the time module
import warnings # Import locally to keep dependencies clear
from scipy import stats
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from statsmodels.tsa.seasonal import STL # For Time Series Anomaly Detection
from mlxtend.frequent_patterns import apriori, association_rules # For Market Basket
from mlxtend.preprocessing import TransactionEncoder # For Market Basket
import nltk # For Sentiment Analysis
import networkx as nx # For Network Analysis
from wordcloud import WordCloud # For Text Profiler
from scipy.stats import norm, lognorm, expon, weibull_min # For Distribution Fitting
import matplotlib.cm as cm # For Distribution Fitting plot colors
from statsmodels.tsa.stattools import ccf # For Time-Lagged Cross-Correlation
from sklearn.linear_model import LogisticRegression # For Propensity Scoring & Treatment Effect
from lifelines import KaplanMeierFitter # For Survival Analysis
from sklearn.preprocessing import LabelEncoder # For Decision Tree target encoding # For ROC curve
from nltk.sentiment.vader import SentimentIntensityAnalyzer # For Sentiment Analysis
from lifelines import CoxPHFitter # For Survival Regression
# New imports for added tools
import duckdb # For SQL Query Workbench
from scipy.cluster.hierarchy import dendrogram, linkage # For Hierarchical Clustering
from sklearn.feature_extraction.text import CountVectorizer # For LDA
from sklearn.decomposition import LatentDirichletAllocation # For LDA
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.inspection import PartialDependenceDisplay # For PDP/ICE plots
warnings.filterwarnings('ignore')
# New imports for SHAP and Prophet
import shap # For SHAP
from prophet import Prophet # For Prophet forecasting
from prophet.plot import plot_plotly as prophet_plot_plotly, plot_components_plotly as prophet_plot_components_plotly # For Prophet plots
# Page configuration
from sklearn.ensemble import GradientBoostingClassifier
st.set_page_config(layout="wide", page_title="Advanced Dashboard Creator", page_icon="📊")
# --- FUNCTIONS ---
def get_base64_of_bin_file(bin_file):
"""Encodes a binary file to a base64 string."""
with open(bin_file, 'rb') as f:
data = f.read()
return base64.b64encode(data).decode()
def set_page_background_and_style(file_path):
"""Sets the background image and applies custom CSS styles."""
if not os.path.exists(file_path):
st.error(f"Error: Background image not found at '{file_path}'.")
return
base64_img = get_base64_of_bin_file(file_path)
css_text = f'''
<style>
.stApp {{
background-image: url("data:image/png;base64,{base64_img}");
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
}}
/* 100% Pure Transparency - No boxes, no borders */
[data-testid="stHeader"],
[data-testid="stSidebar"],
[data-testid="stSidebar"] > div,
[data-testid="stSidebarContent"],
[data-testid="stBottomBlockContainer"],
[data-testid="stChatInputContainer"],
[data-testid="stFileUploader"],
[data-testid="stFileUploaderDropzone"],
[data-testid="stFileUploaderDropzoneInstructions"],
.stTextArea,
.stTextInput,
.stChatMessage,
[data-testid="stChatMessageContent"],
.element-container,
.stMarkdown,
section[data-testid="stSidebar"],
.stSelectbox,
div[data-baseweb="select"],
.stExpander,
[data-testid="stSidebar"]::before {{
background: transparent !important;
backdrop-filter: none !important;
border: none !important;
box-shadow: none !important;
}}
/* Remove all borders from sidebar */
[data-testid="stSidebar"] {{
border-right: none !important;
}}
/* Pure transparent inputs - no borders */
textarea, input {{
background: transparent !important;
border: none !important;
color: #F0F2F5 !important; /* Brighter text for inputs */
transition: all 0.3s ease !important;
text-shadow: 0 1px 2px rgba(0,0,0,0.5); /* Readability on image */
box-shadow: none !important;
}}
textarea:hover, input:hover,
textarea:focus, input:focus {{
background: transparent !important;
border: none !important;
box-shadow: none !important;
color: #FFFFFF !important; /* Brighter on focus/hover */
}}
/* Pure transparent buttons - no borders */
button {{
background: transparent !important;
border: none !important;
color: #F0F2F5 !important; /* Brighter text for buttons */
transition: all 0.3s ease !important;
text-shadow: 0 1px 2px rgba(0,0,0,0.5); /* Readability on image */
box-shadow: none !important;
}}
button:hover {{
background: transparent !important;
border: none !important;
box-shadow: none !important;
color: #FFFFFF !important; /* Brighter on hover */
transform: none !important;
}}
/* App-wide text styling */
/* The div selector is modified with :not() to exclude icon containers, fixing a bug where icons were replaced by text. */
body, h1, h2, h3, h4, h5, h6, p, label, .stMarkdown {{
color: #F0F2F5 !important; /* Brighter off-white for better contrast */
font-family: 'Inter', -apple-system, system-ui, sans-serif !important;
font-size: 1rem; /* Standard base font size for readability */
line-height: 1.6;
text-shadow: 0 1px 3px rgba(0,0,0,0.6); /* Universal text shadow for readability */
}}
h1, h2, h3 {{
font-weight: 500 !important; /* Bolder weight for headings */
text-align: center;
letter-spacing: 1px; /* Tighter letter spacing for readability */
}}
h1 {{
font-size: 3rem !important;
color: #FFFFFF !important; /* Make main title stand out */
font-weight: 600 !important; /* Semibold for main title */
letter-spacing: 1.5px;
}}
.subtitle {{
color: rgba(240, 242, 245, 0.85); /* Brighter subtitle color */
font-size: 1.1rem; /* Keep subtitle size */
margin-top: -10px;
letter-spacing: 1.5px; /* Tighter letter spacing */
font-weight: 400; /* Bolder subtitle */
}}
/* Transparent chat messages - no borders */
.stChatMessage {{
background: transparent !important;
border: none !important;
padding-left: 0px !important;
margin: 8px 0 !important;
}}
.stChatMessage:hover {{
background: transparent !important;
border: none !important;
box-shadow: none !important;
}}
/* File badges - pure transparent */
.file-badge {{
display: inline-block;
background: transparent;
border: none;
padding: 4px 10px;
margin: 3px;
font-size: 0.9rem; /* Slightly larger badge text */
color: rgba(226, 232, 240, 0.8);
transition: all 0.3s ease;
}}
.file-badge:hover {{
background: transparent;
border: none;
color: #FFFFFF;
}}
/* Data tool buttons - no special styling */
.data-tool-button button {{
background: transparent !important;
border: none !important;
box-shadow: none !important;
}}
.data-tool-button button:hover {{
background: transparent !important;
border: none !important;
box-shadow: none !important;
}}
/* Minimal scrollbar */
::-webkit-scrollbar {{
width: 6px;
background: transparent;
}}
::-webkit-scrollbar-thumb {{
background: rgba(150, 150, 150, 0.3);
border-radius: 3px;
}}
::-webkit-scrollbar-thumb:hover {{
background: rgba(180, 180, 180, 0.5);
}}
/* Placeholder text */
::placeholder {{
color: rgba(240, 242, 245, 0.5) !important; /* Adjusted for new base color */
}}
/* Selectbox - transparent */
div[data-baseweb="select"] > div {{
background: transparent !important;
border: none !important;
color: #F0F2F5 !important; /* Ensure selectbox text is correct color */
}}
div[data-baseweb="select"]:hover > div {{
background: transparent !important;
border: none !important;
box-shadow: none !important;
}}
/* Footer */
.footer {{
font-size: 0.9rem;
color: rgba(226, 232, 240, 0.7);
text-align: center;
font-weight: 300;
letter-spacing: 1px;
}}
hr {{
opacity: 0.1;
border-color: rgba(200, 200, 200, 0.15);
box-shadow: none;
}}
/* Expander - transparent */
.stExpander {{
background: transparent !important;
border: none !important;
}}
.stExpander:hover {{
background: transparent !important;
border: none !important;
box-shadow: none !important;
}}
/* Caption text */
.stCaptionContainer, small {{
color: rgba(240, 242, 245, 0.8) !important; /* Slightly brighter caption */
font-weight: 300;
}}
/* File uploader */
.stFileUploader label {{
color: #E2E8F0 !important;
}}
.stFileUploader section {{
background: transparent !important;
border: none !important;
}}
.stFileUploader section:hover {{
background: transparent !important;
border: none !important;
}}
</style>
'''
st.markdown(css_text, unsafe_allow_html=True)
# --- APP LAYOUT ---
set_page_background_and_style('Gemini_Generated_Image_phsbymphsbymphsb (1).png')
# --- PASSWORD PROTECTION ---
def check_password():
"""Returns `True` if the user has entered the correct password."""
# Initialize session state if it doesn't exist
if "password_correct" not in st.session_state:
st.session_state.password_correct = False
st.session_state.password_attempts = 0
# If password is correct, we're done.
if st.session_state.password_correct:
return True
# If max attempts reached, lock the app
if st.session_state.password_attempts >= 3:
st.warning("🚨 Too many incorrect attempts. Access denied. Please refresh the page to try again.")
st.stop()
# Show password input form
st.title("🔐 Secure Access")
st.info("Please enter the password to access the Advanced Data Explorer.")
with st.form("password_form"):
password = st.text_input("Password", type="password")
submitted = st.form_submit_button("Enter")
if submitted:
if password == st.secrets["app_password"]:
st.session_state.password_correct = True
st.rerun()
else:
st.session_state.password_attempts += 1
st.error(f"Incorrect password. You have {3 - st.session_state.password_attempts} attempts left.")
st.rerun()
st.stop()
check_password()
#with st.sidebar:
# st.image("d2.jpg", caption="From rows to revelations.", use_container_width=True)
# Sidebar configuration
st.sidebar.header("🛠️ Dashboard Controls & Options")
selected_theme = st.sidebar.selectbox("🎨 Theme Selection", options=['light', 'dark', 'cyberpunk'], index=1) # Default to dark
color_scheme = st.sidebar.selectbox("🌈 Chart Color Palette", options=['viridis', 'plasma', 'inferno', 'magma', 'cividis'], index=1) # Plasma default
custom_color = st.sidebar.color_picker("🎨 Custom Accent Color", "#38B2AC") # Teal default
# NEW FEATURE 1: Real-time data refresh
refresh_interval = st.sidebar.slider("⏱️ Auto-Refresh Interval (s)", 0, 60, 0)
if refresh_interval > 0:
st.sidebar.info(f"Dashboard will refresh every {refresh_interval} seconds")
# Gemini API Integration
# Helper function to get common columns
def get_common_columns(datasets_dict, col_type='all'):
if not datasets_dict or len(datasets_dict) < 2: # Needs at least two datasets to find common columns
return []
dfs_to_compare = list(datasets_dict.values())
if not dfs_to_compare:
return []
common_cols_set = set(dfs_to_compare[0].columns)
for i in range(1, len(dfs_to_compare)):
common_cols_set.intersection_update(dfs_to_compare[i].columns)
common_cols_list = sorted(list(common_cols_set))
if col_type == 'all':
return common_cols_list
first_df = dfs_to_compare[0]
if col_type == 'numeric':
return [col for col in common_cols_list if pd.api.types.is_numeric_dtype(first_df[col])]
elif col_type == 'categorical':
return [col for col in common_cols_list if pd.api.types.is_object_dtype(first_df[col]) or pd.api.types.is_categorical_dtype(first_df[col])]
elif col_type == 'datetime':
return [col for col in common_cols_list if pd.api.types.is_datetime64_any_dtype(first_df[col])]
return []
st.sidebar.header("🪄 AI-Powered Assistance")
gemini_api_key = None # Initialize to handle cases where it's not found
try:
# Load Gemini API key from Streamlit secrets
gemini_api_key = st.secrets["gemini_api_key"]
genai.configure(api_key=gemini_api_key)
st.sidebar.success("Gemini API key loaded from secrets.")
except KeyError:
st.sidebar.warning("Gemini API key not found in secrets. AI features will be disabled.")
except Exception as e:
st.sidebar.error(f"API Error: {str(e)}")
# Main title with metrics
st.title("Advanced Data Explorer & Visualizer")
#st.image("d3.jpg", caption="Made for Analysts. Loved by Scientists.", use_container_width=True)
st.markdown("### 🔮 Upload your data to unlock insights and visualizations!")
# NEW FEATURE 2: Multiple file upload support
uploaded_files = st.file_uploader("Choose files", type=["csv", "xlsx", "json"], accept_multiple_files=True)
# NEW FEATURE 3: Data comparison mode
comparison_mode = st.checkbox("📊 Enable Data Comparison Mode")
if uploaded_files:
# Process multiple files
datasets = {}
for i, file in enumerate(uploaded_files):
try:
if file.name.endswith('.csv'):
datasets[f"Dataset_{i+1}"] = pd.read_csv(file)
elif file.name.endswith('.xlsx'):
datasets[f"Dataset_{i+1}"] = pd.read_excel(file)
elif file.name.endswith('.json'):
datasets[f"Dataset_{i+1}"] = pd.read_json(file)
except Exception as e:
st.error(f"Error reading {file.name}: {str(e)}")
if datasets:
# Dataset selector
selected_dataset = st.selectbox("Select Primary Dataset", options=list(datasets.keys()))
# Define the callback function for resetting model parameters
# This function will be called when the reset button is clicked.
def reset_all_model_parameters_callback():
# Reset DT parameters to their initial defaults
# Fallback values in .get() are for extreme safety,
# assuming INIT_DEFAULT keys are always set before button click.
st.session_state.dt_max_depth = st.session_state.get("INIT_DEFAULT_dt_max_depth", 5)
st.session_state.dt_min_samples_split = st.session_state.get("INIT_DEFAULT_dt_min_samples_split", 2)
st.session_state.dt_min_samples_leaf = st.session_state.get("INIT_DEFAULT_dt_min_samples_leaf", 1)
st.session_state.dt_criterion = st.session_state.get("INIT_DEFAULT_dt_criterion", "gini")
# Reset RF parameters to their initial defaults
st.session_state.rf_n_estimators = st.session_state.get("INIT_DEFAULT_rf_n_estimators", 100)
st.session_state.rf_max_depth = st.session_state.get("INIT_DEFAULT_rf_max_depth", 10)
st.session_state.rf_min_samples_split = st.session_state.get("INIT_DEFAULT_rf_min_samples_split", 2)
st.session_state.rf_min_samples_leaf = st.session_state.get("INIT_DEFAULT_rf_min_samples_leaf", 1)
st.session_state.rf_criterion = st.session_state.get("INIT_DEFAULT_rf_criterion", "gini")
df = datasets[selected_dataset]
# NEW FEATURE: Automatic Data Overview Table (before Advanced Profiling)
with st.expander("📄 Quick Data Overview", expanded=True):
st.subheader(f"Overview of: {selected_dataset}")
st.markdown("#### First 5 Rows:")
st.dataframe(df.head())
col_info1, col_info2 = st.columns(2)
with col_info1:
st.markdown("#### Data Dimensions:")
st.write(f"Rows: {df.shape[0]:,}")
st.write(f"Columns: {df.shape[1]}")
with col_info2:
st.markdown("#### Missing Values (per column):")
st.dataframe(df.isnull().sum().rename("Missing Count").to_frame().T)
st.markdown("#### Column Data Types:")
st.dataframe(df.dtypes.rename("Data Type").to_frame().T)
# NEW FEATURE 4: Advanced data profiling
with st.expander("📊 Advanced Data Profiling", expanded=True):
col1, col2, col3, col4 = st.columns(4)
with col1:
st.markdown(f'<div class="metric-card"><h3>{df.shape[0]:,}</h3><p>Total Rows</p></div>', unsafe_allow_html=True)
with col2:
st.markdown(f'<div class="metric-card"><h3>{df.shape[1]}</h3><p>Columns</p></div>', unsafe_allow_html=True)
with col3:
st.markdown(f'<div class="metric-card"><h3>{df.memory_usage(deep=True).sum() / 1024**2:.1f} MB</h3><p>Memory Usage</p></div>', unsafe_allow_html=True)
with col4:
duplicates = df.duplicated().sum()
st.markdown(f'<div class="metric-card"><h3>{duplicates}</h3><p>Duplicates</p></div>', unsafe_allow_html=True)
missing_pct = (df.isnull().sum().sum() / (df.shape[0] * df.shape[1])) * 100
quality_score = max(0, 100 - missing_pct - (duplicates/df.shape[0]*10))
st.markdown(f'<div class="insight-box"><strong>Data Quality Score: {quality_score:.1f}/100</strong><br>Based on missing values and duplicate records</div>', unsafe_allow_html=True)
# NEW FEATURE 5: Smart data type detection and conversion
with st.expander("💡 Smart Data Type Detection & Conversion"):
st.subheader("Suggested Data Type Conversions")
suggestions = []
for col in df.columns:
if df[col].dtype == 'object': # Check object columns for potential conversion
# Check if it's actually numeric
try:
pd.to_numeric(df[col].dropna())
suggestions.append((col, "numeric", "Contains numeric values"))
except:
# Check if it's a date
try:
pd.to_datetime(df[col].dropna().head(100))
suggestions.append((col, "datetime", "Contains date patterns"))
except:
pass
if suggestions:
for col, suggested_type, reason in suggestions:
if st.checkbox(f"Convert '{col}' to {suggested_type} ({reason})", key=f"convert_{col}_{suggested_type}"):
try:
if suggested_type == "numeric":
df[col] = pd.to_numeric(df[col], errors='coerce')
elif suggested_type == "datetime":
df[col] = pd.to_datetime(df[col], errors='coerce')
st.success(f"Converted {col} to {suggested_type}")
except Exception as e:
st.error(f"Conversion failed: {str(e)}")
else:
st.info("No conversion suggestions found")
# Globally define/update column type lists after potential conversions in Feature 5
numeric_cols = df.select_dtypes(include=np.number).columns.tolist()
categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()
date_cols = df.select_dtypes(include='datetime').columns.tolist()
# NEW FEATURE 6: Advanced filtering system
with st.expander("⚙️ Advanced Data Filtering System"):
st.subheader("Multi-Column Filters")
# Numeric filters
if numeric_cols:
st.write("**Numeric Filters:**")
for col in numeric_cols[:3]: # Limit to 3 for space
if not df[col].isna().all():
min_val, max_val = float(df[col].min()), float(df[col].max())
filter_range = st.slider(f"{col} Range", min_val, max_val, (min_val, max_val), key=f"filter_{col}")
df = df[(df[col] >= filter_range[0]) & (df[col] <= filter_range[1])]
# Categorical filters
if categorical_cols:
st.write("**Categorical Filters:**")
for col in categorical_cols[:2]: # Limit to 2 for space
unique_values = df[col].dropna().unique()
if len(unique_values) <= 20: # Only show if manageable number of categories
selected_values = st.multiselect(f"Filter {col}", unique_values, default=unique_values, key=f"cat_filter_{col}")
if selected_values:
df = df[df[col].isin(selected_values)]
st.success(f"Filtered dataset: {df.shape[0]} rows × {df.shape[1]} columns")
if not df.empty:
st.markdown("#### Filtered Data Preview (First 100 rows):")
st.dataframe(df.head(100)) # Show a preview
# Download button for the filtered data
@st.cache_data # Cache the conversion to prevent re-computation on every rerun
def convert_df_to_csv(df_to_convert):
return df_to_convert.to_csv(index=False).encode('utf-8')
csv_filtered = convert_df_to_csv(df)
st.download_button(
label="📥 Download Filtered Data as CSV",
data=csv_filtered,
file_name=f"filtered_{selected_dataset.lower().replace('dataset_','')}.csv",
mime="text/csv",
)
else:
st.warning("The current filter selection results in an empty dataset.")
# NEW FEATURE 7: Automated statistical testing
with st.expander("📈 Statistical Analysis Suite"):
if len(numeric_cols) >= 2:
st.subheader("Correlation Analysis")
corr_method = st.selectbox("Correlation Method", ["pearson", "spearman", "kendall"])
corr_matrix = df[numeric_cols].corr(method=corr_method)
# Heatmap
fig = px.imshow(corr_matrix, text_auto=True, aspect="auto",
title=f"Correlation Matrix ({corr_method})")
st.plotly_chart(fig, use_container_width=True)
# Strongest correlations
corr_pairs = []
for i in range(len(numeric_cols)):
for j in range(i+1, len(numeric_cols)):
corr_val = corr_matrix.iloc[i, j]
if not np.isnan(corr_val):
corr_pairs.append((numeric_cols[i], numeric_cols[j], corr_val))
corr_pairs.sort(key=lambda x: abs(x[2]), reverse=True)
if corr_pairs:
st.write("**Top Correlations:**")
for col1, col2, corr_val in corr_pairs[:3]:
strength = "Strong" if abs(corr_val) > 0.7 else "Moderate" if abs(corr_val) > 0.3 else "Weak"
direction = "positive" if corr_val > 0 else "negative"
st.write(f"• {strength} {direction} correlation: **{col1}** ↔ **{col2}** ({corr_val:.3f})")
# NEW FEATURE 8: Machine Learning Pipeline
with st.expander("🧠 AutoML Predictive Pipeline"):
if len(numeric_cols) >= 2:
st.subheader("Automated Model Building")
# Target selection
target_col = st.selectbox("Select Target Variable", numeric_cols)
feature_cols = [col for col in numeric_cols if col != target_col]
if feature_cols:
# Prepare data
X = df[feature_cols].dropna()
y = df.loc[X.index, target_col]
if len(X) > 10: # Minimum data requirement
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Polynomial degree selection for Polynomial Regression
poly_degree = st.number_input("Polynomial Degree (for Polynomial Regression)", min_value=2, max_value=5, value=2, step=1, key="automl_poly_degree")
# Model selection
models = {
"Linear Regression": LinearRegression(),
"Polynomial Regression": Pipeline([
("poly_features", PolynomialFeatures(degree=poly_degree, include_bias=False)),
("lin_reg", LinearRegression())
]),
"Random Forest": RandomForestRegressor(n_estimators=50, random_state=42)
}
results = {}
for name, model in models.items():
try:
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
r2 = r2_score(y_test, y_pred)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
results[name] = {"R²": r2, "RMSE": rmse, "Model": model}
except Exception as e:
st.error(f"Error training {name}: {str(e)}")
if results:
# Display results
col1, col2 = st.columns(2)
for i, (name, metrics) in enumerate(results.items()):
with col1 if i % 2 == 0 else col2:
st.metric(f"{name} R²", f"{metrics['R²']:.3f}")
st.metric(f"{name} RMSE", f"{metrics['RMSE']:.3f}")
# Feature importance (for Random Forest)
if "Random Forest" in results:
rf_model = results["Random Forest"]["Model"]
importance_df = pd.DataFrame({
'Feature': feature_cols,
'Importance': rf_model.feature_importances_
}).sort_values('Importance', ascending=False)
fig = px.bar(importance_df, x='Importance', y='Feature',
orientation='h', title="Feature Importance")
st.plotly_chart(fig, use_container_width=True)
else:
st.warning("Need more data points for modeling")
else:
st.warning("Need multiple numeric columns for modeling")
# NEW FEATURE 9: Data comparison dashboard
if comparison_mode and len(datasets) > 1:
with st.expander("🆚 Dataset Comparison Dashboard", expanded=True): # Keep expanded if conditions met
# Ensure default selection is valid and doesn't exceed available datasets
num_available_datasets = len(datasets.keys())
default_selection_count = min(2, num_available_datasets)
compare_datasets_selected = st.multiselect(
"Select datasets to compare",
list(datasets.keys()),
default=list(datasets.keys())[:default_selection_count] if num_available_datasets > 0 else [],
key="compare_multiselect"
)
if len(compare_datasets_selected) >= 2:
selected_dfs_dict = {name: datasets[name] for name in compare_datasets_selected}
tab_overview, tab_schema, tab_numeric, tab_categorical, tab_quality = st.tabs([
"📊 Overview", "🧬 Schema Comparison", "🔢 Numeric Deep Dive",
"🔠 Categorical Deep Dive", "📉 Data Quality"
])
with tab_overview:
st.subheader("Basic Statistics Overview")
overview_data = []
for name, ds in selected_dfs_dict.items():
missing_pct_val = (ds.isnull().sum().sum() / (ds.shape[0] * ds.shape[1]) * 100) if ds.shape[0] > 0 and ds.shape[1] > 0 else 0
overview_data.append({
'Dataset': name,
'Rows': ds.shape[0],
'Columns': ds.shape[1],
'Numeric Cols': len(ds.select_dtypes(include=['number']).columns),
'Categorical Cols': len(ds.select_dtypes(include=['object', 'category']).columns),
'Datetime Cols': len(ds.select_dtypes(include=['datetime']).columns),
'Total Missing %': f"{missing_pct_val:.2f}%",
'Memory Usage (MB)': f"{ds.memory_usage(deep=True).sum() / (1024*1024):.2f}", # Feature 1
'Duplicate Rows': ds.duplicated().sum() # Feature 2
})
overview_df = pd.DataFrame(overview_data)
st.dataframe(overview_df)
if not overview_df.empty:
fig_rows_comp = px.bar(overview_df, x='Dataset', y='Rows', title="Dataset Size Comparison (Rows)", color_discrete_sequence=[custom_color])
st.plotly_chart(fig_rows_comp, use_container_width=True)
fig_cols_comp = px.bar(overview_df, x='Dataset', y='Columns', title="Dataset Size Comparison (Columns)", color_discrete_sequence=[px.colors.qualitative.Plotly[1]])
st.plotly_chart(fig_cols_comp, use_container_width=True)
with tab_schema:
st.subheader("Schema & Structure Comparison")
# Feature 3: Common Columns
common_cols_schema = get_common_columns(selected_dfs_dict, 'all')
st.markdown("#### Common Columns Across All Selected Datasets")
if common_cols_schema:
st.write(", ".join(common_cols_schema) if common_cols_schema else "None")
else:
st.info("No columns are common across all selected datasets.")
# Feature 4: Unique Columns
st.markdown("#### Unique Columns per Dataset")
all_cols_in_selection = set()
for ds_name, ds_df in selected_dfs_dict.items():
all_cols_in_selection.update(ds_df.columns)
for ds_name, ds_df in selected_dfs_dict.items():
other_cols = set()
for other_name, other_df in selected_dfs_dict.items():
if ds_name != other_name:
other_cols.update(other_df.columns)
unique_to_ds = set(ds_df.columns) - other_cols
if unique_to_ds:
st.write(f"**{ds_name}:** {', '.join(sorted(list(unique_to_ds)))}")
else:
st.write(f"**{ds_name}:** No columns unique to this dataset compared to others in selection.")
# Feature 5: Data Type Mismatches for Common Columns
if common_cols_schema:
st.markdown("#### Data Type Mismatches for Common Columns")
mismatch_info = []
first_ds_name = list(selected_dfs_dict.keys())[0]
first_ds_df = selected_dfs_dict[first_ds_name]
for col_name in common_cols_schema:
base_dtype = str(first_ds_df[col_name].dtype)
for ds_name_comp, ds_df_comp in selected_dfs_dict.items():
if ds_name_comp == first_ds_name:
continue
current_dtype = str(ds_df_comp[col_name].dtype)
if base_dtype != current_dtype:
mismatch_info.append({
'Column': col_name,
first_ds_name: base_dtype,
ds_name_comp: current_dtype,
'Status': 'Mismatch'
})
if mismatch_info:
st.dataframe(pd.DataFrame(mismatch_info))
else:
st.info("No data type mismatches found for common columns across the selected datasets.")
with tab_numeric:
st.subheader("Numeric Column Deep Dive")
common_numeric_cols = get_common_columns(selected_dfs_dict, 'numeric')
if not common_numeric_cols:
st.info("No common numeric columns found across selected datasets.")
else:
selected_num_col_compare = st.selectbox("Select a common numeric column to analyze:", common_numeric_cols, key="num_col_compare_select")
if selected_num_col_compare:
# Feature 6: Side-by-side descriptive statistics
st.markdown(f"#### Descriptive Statistics for '{selected_num_col_compare}'")
desc_stats_list = []
for ds_name, ds_df in selected_dfs_dict.items():
if selected_num_col_compare in ds_df.columns:
desc_stats_list.append(ds_df[selected_num_col_compare].describe().rename(ds_name))
if desc_stats_list:
st.dataframe(pd.concat(desc_stats_list, axis=1))
# Feature 7: Visual comparison (overlaid histograms or box plots)
st.markdown(f"#### Visual Comparison for '{selected_num_col_compare}'")
plot_type_num = st.radio("Plot Type:", ["Overlaid Histograms", "Box Plots"], key="num_plot_type_radio")
combined_num_data = pd.DataFrame()
for ds_name, ds_df in selected_dfs_dict.items():
if selected_num_col_compare in ds_df.columns:
temp_df = pd.DataFrame({selected_num_col_compare: ds_df[selected_num_col_compare], 'Dataset': ds_name})
combined_num_data = pd.concat([combined_num_data, temp_df], ignore_index=True)
if not combined_num_data.empty:
if plot_type_num == "Overlaid Histograms":
fig_num_hist = px.histogram(combined_num_data, x=selected_num_col_compare, color='Dataset',
barmode='overlay', marginal='rug', opacity=0.7,
title=f"Distribution of '{selected_num_col_compare}' by Dataset")
st.plotly_chart(fig_num_hist, use_container_width=True)
else: # Box Plots
fig_num_box = px.box(combined_num_data, y=selected_num_col_compare, color='Dataset',
title=f"Box Plot of '{selected_num_col_compare}' by Dataset")
st.plotly_chart(fig_num_box, use_container_width=True)
# Feature 8: Statistical test (T-test/Mann-Whitney U) - for first two selected datasets
if len(selected_dfs_dict) >= 2:
st.markdown(f"#### Statistical Test for Difference in '{selected_num_col_compare}'")
ds_names_for_test = list(selected_dfs_dict.keys())[:2]
data1_test = selected_dfs_dict[ds_names_for_test[0]][selected_num_col_compare].dropna()
data2_test = selected_dfs_dict[ds_names_for_test[1]][selected_num_col_compare].dropna()
if len(data1_test) > 1 and len(data2_test) > 1: # Need at least 2 samples for these tests
test_choice = st.radio("Choose Test:", ["T-test (parametric)", "Mann-Whitney U (non-parametric)"], key="num_stat_test_choice")
st.caption(f"Comparing '{ds_names_for_test[0]}' and '{ds_names_for_test[1]}'. For more than 2 datasets, only the first two are compared here.")
alpha_stat_test = 0.05 # Significance level
if test_choice == "T-test (parametric)":
stat, p_value = stats.ttest_ind(data1_test, data2_test, equal_var=False) # Welch's t-test
st.write(f"**T-test results:** Statistic = {stat:.3f}, P-value = {p_value:.4f}")
else: # Mann-Whitney U
stat, p_value = stats.mannwhitneyu(data1_test, data2_test, alternative='two-sided')
st.write(f"**Mann-Whitney U test results:** Statistic = {stat:.3f}, P-value = {p_value:.4f}")
if p_value < alpha_stat_test:
st.success(f"Significant difference found (p < {alpha_stat_test}).")
else:
st.info(f"No significant difference found (p >= {alpha_stat_test}).")
else:
st.warning("Not enough data in one or both datasets for statistical testing on this column.")
with tab_categorical:
st.subheader("Categorical Column Deep Dive")
common_categorical_cols = get_common_columns(selected_dfs_dict, 'categorical')
if not common_categorical_cols:
st.info("No common categorical columns found across selected datasets.")
else:
selected_cat_col_compare = st.selectbox("Select a common categorical column to analyze:", common_categorical_cols, key="cat_col_compare_select")
if selected_cat_col_compare:
# Feature 9: Side-by-side value counts & visual
st.markdown(f"#### Value Distribution for '{selected_cat_col_compare}'")
all_cat_data_for_plot = pd.DataFrame()
for ds_name, ds_df in selected_dfs_dict.items():
if selected_cat_col_compare in ds_df.columns:
counts = ds_df[selected_cat_col_compare].value_counts(normalize=True).mul(100).rename('Percentage').reset_index()
counts.columns = [selected_cat_col_compare, 'Percentage']
counts['Dataset'] = ds_name
all_cat_data_for_plot = pd.concat([all_cat_data_for_plot, counts])
if not all_cat_data_for_plot.empty:
fig_cat_dist = px.bar(all_cat_data_for_plot, x=selected_cat_col_compare, y='Percentage', color='Dataset',
barmode='group', title=f"Distribution of '{selected_cat_col_compare}' by Dataset")
st.plotly_chart(fig_cat_dist, use_container_width=True)
st.markdown("##### Value Counts (Top 10 per Dataset)")
for ds_name, ds_df in selected_dfs_dict.items():
if selected_cat_col_compare in ds_df.columns:
st.write(f"**{ds_name}:**")
st.dataframe(ds_df[selected_cat_col_compare].value_counts().head(10).rename("Count"))
with tab_quality:
st.subheader("Data Quality Comparison")
# Feature 10: Detailed Missing Values per common column
st.markdown("#### Missing Values per Common Column")
common_cols_quality = get_common_columns(selected_dfs_dict, 'all')
if not common_cols_quality:
st.info("No common columns to compare missing values.")
else:
missing_data_list = []
for ds_name, ds_df in selected_dfs_dict.items():
for col_name in common_cols_quality:
if col_name in ds_df.columns:
missing_count = ds_df[col_name].isnull().sum()
missing_pct = (missing_count / len(ds_df)) * 100 if len(ds_df) > 0 else 0
missing_data_list.append({'Dataset': ds_name, 'Column': col_name, 'MissingPercentage': missing_pct})
if missing_data_list:
missing_df_plot = pd.DataFrame(missing_data_list)
fig_missing_comp = px.bar(missing_df_plot, x='Column', y='MissingPercentage', color='Dataset',
barmode='group', title="Missing Value Percentage per Common Column by Dataset")
st.plotly_chart(fig_missing_comp, use_container_width=True)
else:
st.info("No data to plot for missing values comparison.")
elif len(compare_datasets_selected) < 2: # If mode is on, datasets > 1, but not enough selected in multiselect
st.info("Please select at least two datasets from the dropdown above to compare.")
elif comparison_mode and len(datasets) <= 1: # If mode is on, but not enough datasets uploaded
st.info("📊 Data Comparison Mode is enabled. Please upload at least two datasets to use this feature.")
# NEW FEATURE 10: Export and reporting system
with st.expander("📄 Advanced Export & Reporting System"):
st.subheader("Generate Analysis Report")
report_sections = st.multiselect("Include in Report",
["Data Summary", "Correlation Analysis", "Missing Data Report",
"Statistical Summary", "Data Quality Assessment"],
default=["Data Summary", "Data Quality Assessment"])
if st.button("Generate Report"):
report = f"""
# Data Analysis Report
Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
## Dataset Overview
- **Rows**: {df.shape[0]:,}
- **Columns**: {df.shape[1]}
- **Memory Usage**: {df.memory_usage(deep=True).sum() / 1024**2:.1f} MB
"""
if "Data Quality Assessment" in report_sections:
missing_pct = (df.isnull().sum().sum() / (df.shape[0] * df.shape[1])) * 100
duplicates = df.duplicated().sum()
quality_score = max(0, 100 - missing_pct - (duplicates/df.shape[0]*10))
report += f"""
## Data Quality Assessment
- **Quality Score**: {quality_score:.1f}/100
- **Missing Data**: {missing_pct:.1f}%
- **Duplicate Rows**: {duplicates}
"""
if "Statistical Summary" in report_sections and numeric_cols:
report += f"""
## Statistical Summary
{df[numeric_cols].describe().to_string()}
"""
st.text_area("Generated Report", report, height=300)
st.download_button("Download Report", report, file_name="analysis_report.txt")
# AI-Powered Insights with Gemini API
with st.expander("💬 AI-Powered Insights (Gemini)", expanded=True):
st.subheader("Ask Questions About Your Data")
if gemini_api_key:
user_question = st.text_input("Ask a question about your data:",
placeholder="E.g., What are the key trends in this dataset?")
if user_question:
# Prepare data summary
buffer = io.StringIO()
df.describe().to_csv(buffer)
data_summary = buffer.getvalue()
# Prepare data sample
buffer = io.StringIO()
df.head(5).to_csv(buffer)
data_sample = buffer.getvalue()
# Prepare column info
column_info = "\n".join([
f"- {col} ({df[col].dtype}): {df[col].nunique()} unique values"
for col in df.columns
])
# Create prompt
prompt = f"""
I have a dataset with {df.shape[0]} rows and {df.shape[1]} columns.
Column information:
{column_info}
Data sample:
{data_sample}
Summary statistics:
{data_summary}
Question: {user_question}
Please provide a helpful, concise, and accurate answer based on this data.
"""
try:
model = genai.GenerativeModel("gemini-flash-lite-latest")
response = model.generate_content(prompt)
st.write("AI Response:")
st.write(response.text)
except Exception as e:
st.error(f"Gemini API Error: {str(e)}")
else:
st.info("Enter your Gemini API key in the sidebar to enable AI insights.")
# Interactive visualization builder
with st.expander("🎨 Quick Visualization Builder"):
if numeric_cols or categorical_cols:
viz_type = st.selectbox("Chart Type", ["Scatter", "Line", "Bar", "Histogram", "Box"])
if viz_type in ["Scatter", "Line"] and len(numeric_cols) >= 2:
x_col = st.selectbox("X-axis", numeric_cols)