Spaces:
Sleeping
Sleeping
Update pages/1_Data_Validation.py
Browse files- pages/1_Data_Validation.py +187 -177
pages/1_Data_Validation.py
CHANGED
@@ -4,18 +4,20 @@ import plotly.express as px
|
|
4 |
import plotly.graph_objects as go
|
5 |
from Eda_functions import *
|
6 |
import numpy as np
|
7 |
-
import re
|
8 |
import pickle
|
9 |
-
#from ydata_profiling import ProfileReport
|
10 |
from streamlit_pandas_profiling import st_profile_report
|
11 |
import streamlit as st
|
12 |
import streamlit.components.v1 as components
|
13 |
import sweetviz as sv
|
14 |
-
from utilities import set_header,
|
15 |
from st_aggrid import GridOptionsBuilder,GridUpdateMode
|
16 |
from st_aggrid import GridOptionsBuilder
|
17 |
from st_aggrid import AgGrid
|
18 |
import base64
|
|
|
|
|
|
|
|
|
19 |
|
20 |
st.set_page_config(
|
21 |
page_title="Data Validation",
|
@@ -28,155 +30,187 @@ set_header()
|
|
28 |
|
29 |
|
30 |
|
31 |
-
#preprocessing
|
32 |
-
# with open('Categorised_data.pkl', 'rb') as file:
|
33 |
-
# Categorised_data = pickle.load(file)
|
34 |
-
# with open("edited_dataframe.pkl", 'rb') as file:
|
35 |
-
|
36 |
-
|
37 |
-
# df = pickle.load(file)
|
38 |
-
# date=df.index
|
39 |
-
# df.reset_index(inplace=True)
|
40 |
-
# df['Date'] = pd.to_datetime(date)
|
41 |
-
|
42 |
|
43 |
-
#prospects=pd.read_excel('EDA_Data.xlsx',sheet_name='Prospects')
|
44 |
-
#spends=pd.read_excel('EDA_Data.xlsx',sheet_name='SPEND INPUT')
|
45 |
-
#spends.columns=['Week','Streaming (Spends)','TV (Spends)','Search (Spends)','Digital (Spends)']
|
46 |
-
#df=pd.concat([df,spends],axis=1)
|
47 |
-
|
48 |
-
#df['Date'] =pd.to_datetime(df['Date']).dt.strftime('%m/%d/%Y')
|
49 |
-
#df['Prospects']=prospects['Prospects']
|
50 |
-
#df.drop(['Week'],axis=1,inplace=True)
|
51 |
|
|
|
|
|
|
|
|
|
|
|
52 |
|
53 |
st.title('Data Validation and Insights')
|
54 |
|
55 |
-
with open("Pickle_files/main_df",'rb') as f:
|
56 |
-
st.session_state['cleaned_data']= pickle.load(f)
|
57 |
-
with open("Pickle_files/category_dict",'rb') as c:
|
58 |
-
st.session_state['category_dict']=pickle.load(c)
|
59 |
-
|
60 |
-
# st.write(st.session_state['cleaned_data'])
|
61 |
-
|
62 |
-
target_variables=[st.session_state['category_dict'][key] for key in st.session_state['category_dict'].keys() if key =='Response_Metric']
|
63 |
|
|
|
64 |
|
65 |
target_column = st.selectbox('Select the Target Feature/Dependent Variable (will be used in all charts as reference)',list(*target_variables))
|
66 |
st.session_state['target_column']=target_column
|
|
|
|
|
|
|
67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
-
fig=line_plot_target(st.session_state['cleaned_data'], target=target_column, title=f'{target_column} Over Time')
|
70 |
-
st.plotly_chart(fig, use_container_width=True)
|
71 |
|
|
|
|
|
72 |
|
73 |
-
media_channel=list(*[st.session_state['category_dict'][key] for key in st.session_state['category_dict'].keys() if key =='Media'])
|
74 |
-
# st.write(media_channel)
|
75 |
|
76 |
-
|
|
|
77 |
|
|
|
78 |
|
79 |
-
st.markdown('### Annual Data Summary')
|
80 |
-
st.dataframe(summary(st.session_state['cleaned_data'], media_channel+[target_column], spends=None,Target=True), use_container_width=True)
|
81 |
|
82 |
-
|
83 |
-
st.
|
|
|
|
|
|
|
84 |
col1 = st.columns(1)
|
85 |
|
86 |
if "selected_feature" not in st.session_state:
|
87 |
st.session_state['selected_feature']=None
|
88 |
|
89 |
-
st.header('1. Media Channels')
|
90 |
-
|
91 |
-
if 'Validation' not in st.session_state:
|
92 |
-
st.session_state['Validation']=[]
|
93 |
-
|
94 |
-
eda_columns=st.columns(2)
|
95 |
-
with eda_columns[0]:
|
96 |
-
if st.button('Generate Profile Report'):
|
97 |
-
pr = st.session_state['cleaned_data'].profile_report()
|
98 |
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
|
107 |
with eda_columns[1]:
|
108 |
-
if st.button('Generate Sweetviz Report'):
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
if
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
if
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
st.
|
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 |
st.plotly_chart(fig_row4, use_container_width=True)
|
177 |
selected_non_media=selected_columns_row4
|
178 |
-
sum_df =
|
179 |
-
sum_df['Year']=pd.to_datetime(
|
180 |
#st.dataframe(df)
|
181 |
#st.dataframe(sum_df.head(2))
|
182 |
sum_df=sum_df.groupby('Year').agg('sum')
|
@@ -184,58 +218,34 @@ else:
|
|
184 |
sum_df=sum_df.applymap(format_numbers)
|
185 |
sum_df.fillna('-',inplace=True)
|
186 |
sum_df=sum_df.replace({"0.0":'-','nan':'-'})
|
187 |
-
st.markdown('###
|
188 |
st.dataframe(sum_df,use_container_width=True)
|
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 |
-
options =
|
215 |
-
|
216 |
-
st.
|
217 |
-
st.markdown('# Exploratory Data Analysis')
|
218 |
-
st.markdown(' ')
|
219 |
-
|
220 |
-
selected_options = []
|
221 |
-
num_columns = 4
|
222 |
-
num_rows = -(-len(options) // num_columns) # Ceiling division to calculate rows
|
223 |
-
|
224 |
-
# Create a grid of checkboxes
|
225 |
-
st.header('Select Features for Correlation Plot')
|
226 |
-
tick=False
|
227 |
-
if st.checkbox('Select all'):
|
228 |
-
tick=True
|
229 |
-
selected_options = []
|
230 |
-
for row in range(num_rows):
|
231 |
-
cols = st.columns(num_columns)
|
232 |
-
for col in cols:
|
233 |
-
if options:
|
234 |
-
option = options.pop(0)
|
235 |
-
selected = col.checkbox(option,value=tick)
|
236 |
-
if selected:
|
237 |
-
selected_options.append(option)
|
238 |
-
# Display selected options
|
239 |
-
#st.write('You selected:', selected_options)
|
240 |
-
st.pyplot(correlation_plot(df,selected_options,target_column))
|
241 |
|
|
|
4 |
import plotly.graph_objects as go
|
5 |
from Eda_functions import *
|
6 |
import numpy as np
|
|
|
7 |
import pickle
|
|
|
8 |
from streamlit_pandas_profiling import st_profile_report
|
9 |
import streamlit as st
|
10 |
import streamlit.components.v1 as components
|
11 |
import sweetviz as sv
|
12 |
+
from utilities import set_header,load_local_css
|
13 |
from st_aggrid import GridOptionsBuilder,GridUpdateMode
|
14 |
from st_aggrid import GridOptionsBuilder
|
15 |
from st_aggrid import AgGrid
|
16 |
import base64
|
17 |
+
import os
|
18 |
+
import tempfile
|
19 |
+
from ydata_profiling import ProfileReport
|
20 |
+
import re
|
21 |
|
22 |
st.set_page_config(
|
23 |
page_title="Data Validation",
|
|
|
30 |
|
31 |
|
32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
+
with open('data_import.pkl', 'rb') as f:
|
36 |
+
data = pickle.load(f)
|
37 |
+
|
38 |
+
st.session_state['cleaned_data']= data['final_df']
|
39 |
+
st.session_state['category_dict'] = data['bin_dict']
|
40 |
|
41 |
st.title('Data Validation and Insights')
|
42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
+
target_variables=[st.session_state['category_dict'][key] for key in st.session_state['category_dict'].keys() if key =='Response Metrics']
|
45 |
|
46 |
target_column = st.selectbox('Select the Target Feature/Dependent Variable (will be used in all charts as reference)',list(*target_variables))
|
47 |
st.session_state['target_column']=target_column
|
48 |
+
panels=st.session_state['category_dict']['Panel Level 1'][0]
|
49 |
+
selected_panels=st.multiselect('Please choose the panels you wish to analyze.If no panels are selected, insights will be derived from the overall data.',st.session_state['cleaned_data'][panels].unique())
|
50 |
+
aggregation_dict = {item: 'sum' if key == 'Media' else 'mean' for key, value in st.session_state['category_dict'].items() for item in value if item not in ['date','Panel_1']}
|
51 |
|
52 |
+
with st.expander('**Reponse Metric Analysis**'):
|
53 |
+
|
54 |
+
if len(selected_panels)>0:
|
55 |
+
st.session_state['Cleaned_data_panel']=st.session_state['cleaned_data'][st.session_state['cleaned_data']['Panel_1'].isin(selected_panels)]
|
56 |
+
|
57 |
+
st.session_state['Cleaned_data_panel']=st.session_state['Cleaned_data_panel'].groupby(by='date').agg(aggregation_dict)
|
58 |
+
st.session_state['Cleaned_data_panel']=st.session_state['Cleaned_data_panel'].reset_index()
|
59 |
+
else:
|
60 |
+
st.session_state['Cleaned_data_panel']=st.session_state['cleaned_data'].groupby(by='date').agg(aggregation_dict)
|
61 |
+
st.session_state['Cleaned_data_panel']=st.session_state['Cleaned_data_panel'].reset_index()
|
62 |
|
|
|
|
|
63 |
|
64 |
+
fig=line_plot_target(st.session_state['Cleaned_data_panel'], target=target_column, title=f'{target_column} Over Time')
|
65 |
+
st.plotly_chart(fig, use_container_width=True)
|
66 |
|
|
|
|
|
67 |
|
68 |
+
media_channel=list(*[st.session_state['category_dict'][key] for key in st.session_state['category_dict'].keys() if key =='Media'])
|
69 |
+
# st.write(media_channel)
|
70 |
|
71 |
+
Non_media_variables=list(*[st.session_state['category_dict'][key] for key in st.session_state['category_dict'].keys() if key =='Exogenous' or key=='Internal'])
|
72 |
|
|
|
|
|
73 |
|
74 |
+
st.markdown('### Annual Data Summary')
|
75 |
+
st.dataframe(summary(st.session_state['Cleaned_data_panel'], media_channel+[target_column], spends=None,Target=True), use_container_width=True)
|
76 |
+
|
77 |
+
if st.checkbox('Show raw data'):
|
78 |
+
st.write(pd.concat([pd.to_datetime(st.session_state['Cleaned_data_panel']['date']).dt.strftime('%m/%d/%Y'),st.session_state['Cleaned_data_panel'].select_dtypes(np.number).applymap(format_numbers)],axis=1))
|
79 |
col1 = st.columns(1)
|
80 |
|
81 |
if "selected_feature" not in st.session_state:
|
82 |
st.session_state['selected_feature']=None
|
83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
|
85 |
+
def generate_report_with_target(channel_data, target_feature):
|
86 |
+
report = sv.analyze([channel_data, "Dataset"], target_feat=target_feature)
|
87 |
+
temp_dir = tempfile.mkdtemp()
|
88 |
+
report_path = os.path.join(temp_dir, "report.html")
|
89 |
+
report.show_html(filepath=report_path, open_browser=False) # Generate the report as an HTML file
|
90 |
+
return report_path
|
91 |
+
|
92 |
+
def generate_profile_report(df):
|
93 |
+
pr = df.profile_report()
|
94 |
+
temp_dir = tempfile.mkdtemp()
|
95 |
+
report_path = os.path.join(temp_dir, "report.html")
|
96 |
+
pr.to_file(report_path)
|
97 |
+
return report_path
|
98 |
+
|
99 |
+
|
100 |
+
#st.header()
|
101 |
+
with st.expander('Univariate and Bivariate Report'):
|
102 |
+
eda_columns=st.columns(2)
|
103 |
+
with eda_columns[0]:
|
104 |
+
if st.button('Generate Profile Report',help='Univariate report which inlcudes all statistical analysis'):
|
105 |
+
with st.spinner('Generating Report'):
|
106 |
+
report_file = generate_profile_report(st.session_state['Cleaned_data_panel'])
|
107 |
+
|
108 |
+
if os.path.exists(report_file):
|
109 |
+
with open(report_file, 'rb') as f:
|
110 |
+
st.success('Report Generated')
|
111 |
+
st.download_button(
|
112 |
+
label="Download EDA Report",
|
113 |
+
data=f.read(),
|
114 |
+
file_name="pandas_profiling_report.html",
|
115 |
+
mime="text/html"
|
116 |
+
)
|
117 |
+
else:
|
118 |
+
st.warning("Report generation failed. Unable to find the report file.")
|
119 |
|
120 |
with eda_columns[1]:
|
121 |
+
if st.button('Generate Sweetviz Report',help='Bivariate report for selected response metric'):
|
122 |
+
with st.spinner('Generating Report'):
|
123 |
+
report_file = generate_report_with_target(st.session_state['Cleaned_data_panel'], target_column)
|
124 |
+
|
125 |
+
if os.path.exists(report_file):
|
126 |
+
with open(report_file, 'rb') as f:
|
127 |
+
st.success('Report Generated')
|
128 |
+
st.download_button(
|
129 |
+
label="Download EDA Report",
|
130 |
+
data=f.read(),
|
131 |
+
file_name="report.html",
|
132 |
+
mime="text/html"
|
133 |
+
)
|
134 |
+
else:
|
135 |
+
st.warning("Report generation failed. Unable to find the report file.")
|
136 |
+
|
137 |
+
|
138 |
+
|
139 |
+
#st.warning('Work in Progress')
|
140 |
+
with st.expander('Media Variables Analysis'):
|
141 |
+
# Get the selected feature
|
142 |
+
st.session_state["selected_feature"]= st.selectbox('Select media', [col for col in media_channel if 'cost' not in col.lower() and 'spend' not in col.lower()])
|
143 |
+
|
144 |
+
# Filter spends features based on the selected feature
|
145 |
+
spends_features = [col for col in st.session_state['Cleaned_data_panel'].columns if any(keyword in col.lower() for keyword in ['cost', 'spend'])]
|
146 |
+
spends_feature = [col for col in spends_features if re.split(r'_cost|_spend', col.lower())[0] in st.session_state["selected_feature"]]
|
147 |
+
|
148 |
+
if 'validation' not in st.session_state:
|
149 |
+
st.session_state['validation']=[]
|
150 |
+
|
151 |
+
|
152 |
+
val_variables=[col for col in media_channel if col!='date']
|
153 |
+
if len(spends_feature)==0:
|
154 |
+
st.warning('No spends varaible available for the selected metric in data')
|
155 |
+
|
156 |
+
else:
|
157 |
+
fig_row1 = line_plot(st.session_state['Cleaned_data_panel'], x_col='date', y1_cols=[st.session_state["selected_feature"]], y2_cols=[target_column], title=f'Analysis of {st.session_state["selected_feature"]} and {[target_column][0]} Over Time')
|
158 |
+
st.plotly_chart(fig_row1, use_container_width=True)
|
159 |
+
st.markdown('### Summary')
|
160 |
+
st.dataframe(summary(st.session_state['cleaned_data'],[st.session_state["selected_feature"]],spends=spends_feature[0]),use_container_width=True)
|
161 |
+
|
162 |
+
cols2=st.columns(2)
|
163 |
+
with cols2[0]:
|
164 |
+
if st.button('Validate'):
|
165 |
+
st.session_state['validation'].append(st.session_state["selected_feature"])
|
166 |
+
with cols2[1]:
|
167 |
+
if st.checkbox('Validate all'):
|
168 |
+
st.session_state['validation'].extend(val_variables)
|
169 |
+
st.success('All media variables are validated ✅')
|
170 |
+
|
171 |
+
if len(set(st.session_state['validation']).intersection(val_variables))!=len(val_variables):
|
172 |
+
validation_data=pd.DataFrame({'Validate':[True if col in st.session_state['validation'] else False for col in val_variables],
|
173 |
+
'Variables':val_variables
|
174 |
+
})
|
175 |
+
cols3=st.columns([1,30])
|
176 |
+
with cols3[1]:
|
177 |
+
validation_df=st.data_editor(validation_data,
|
178 |
+
# column_config={
|
179 |
+
# 'Validate':st.column_config.CheckboxColumn(wi)
|
180 |
+
|
181 |
+
# },
|
182 |
+
column_config={
|
183 |
+
"Validate": st.column_config.CheckboxColumn(
|
184 |
+
default=False,
|
185 |
+
width=100,
|
186 |
+
),
|
187 |
+
'Variables':st.column_config.TextColumn(
|
188 |
+
width=1000
|
189 |
+
|
190 |
+
)
|
191 |
+
},hide_index=True)
|
192 |
+
|
193 |
+
selected_rows = validation_df[validation_df['Validate']==True]['Variables']
|
194 |
+
|
195 |
+
#st.write(selected_rows)
|
196 |
+
|
197 |
+
st.session_state['validation'].extend(selected_rows)
|
198 |
+
|
199 |
+
not_validated_variables = [col for col in val_variables if col not in st.session_state["validation"]]
|
200 |
+
if not_validated_variables:
|
201 |
+
not_validated_message = f'The following variables are not validated:\n{" , ".join(not_validated_variables)}'
|
202 |
+
st.warning(not_validated_message)
|
203 |
+
|
204 |
+
|
205 |
+
|
206 |
+
with st.expander('Non Media Variables Analysis'):
|
207 |
+
selected_columns_row4 = st.selectbox('Select Channel',Non_media_variables,index=1)
|
208 |
+
# # Create the dual-axis line plot
|
209 |
+
fig_row4 = line_plot(st.session_state['Cleaned_data_panel'], x_col='date', y1_cols=[selected_columns_row4], y2_cols=[target_column], title=f'Analysis of {selected_columns_row4} and {target_column} Over Time')
|
210 |
st.plotly_chart(fig_row4, use_container_width=True)
|
211 |
selected_non_media=selected_columns_row4
|
212 |
+
sum_df = st.session_state['Cleaned_data_panel'][['date', selected_non_media,target_column]]
|
213 |
+
sum_df['Year']=pd.to_datetime(st.session_state['Cleaned_data_panel']['date']).dt.year
|
214 |
#st.dataframe(df)
|
215 |
#st.dataframe(sum_df.head(2))
|
216 |
sum_df=sum_df.groupby('Year').agg('sum')
|
|
|
218 |
sum_df=sum_df.applymap(format_numbers)
|
219 |
sum_df.fillna('-',inplace=True)
|
220 |
sum_df=sum_df.replace({"0.0":'-','nan':'-'})
|
221 |
+
st.markdown('### Summary')
|
222 |
st.dataframe(sum_df,use_container_width=True)
|
223 |
|
224 |
+
|
225 |
+
with st.expander('Correlation Analysis'):
|
226 |
+
options = list(st.session_state['Cleaned_data_panel'].select_dtypes(np.number).columns)
|
227 |
+
|
228 |
+
# selected_options = []
|
229 |
+
# num_columns = 4
|
230 |
+
# num_rows = -(-len(options) // num_columns) # Ceiling division to calculate rows
|
231 |
+
|
232 |
+
# # Create a grid of checkboxes
|
233 |
+
# st.header('Select Features for Correlation Plot')
|
234 |
+
# tick=False
|
235 |
+
# if st.checkbox('Select all'):
|
236 |
+
# tick=True
|
237 |
+
# selected_options = []
|
238 |
+
# for row in range(num_rows):
|
239 |
+
# cols = st.columns(num_columns)
|
240 |
+
# for col in cols:
|
241 |
+
# if options:
|
242 |
+
# option = options.pop(0)
|
243 |
+
# selected = col.checkbox(option,value=tick)
|
244 |
+
# if selected:
|
245 |
+
# selected_options.append(option)
|
246 |
+
# # Display selected options
|
247 |
+
|
248 |
+
selected_options=st.multiselect('Select Variables For correlation plot',[var for var in options if var!= target_column],default=options[3])
|
249 |
+
|
250 |
+
st.pyplot(correlation_plot(st.session_state['Cleaned_data_panel'],selected_options,target_column))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
251 |
|