leavoigt commited on
Commit
d43a0b6
1 Parent(s): 82f5e0e

Upload appStore_target.py

Browse files
Files changed (1) hide show
  1. appStore/appStore_target.py +397 -0
appStore/appStore_target.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # set path
2
+ import glob, os, sys;
3
+ sys.path.append('../utils')
4
+
5
+ #import needed libraries
6
+ import seaborn as sns
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ import pandas as pd
10
+ import streamlit as st
11
+ from st_aggrid import AgGrid
12
+ from utils.target_classifier import load_targetClassifier, target_classification
13
+ import logging
14
+ logger = logging.getLogger(__name__)
15
+ from utils.config import get_classifier_params
16
+ from io import BytesIO
17
+ import xlsxwriter
18
+ import plotly.express as px
19
+ from pandas.api.types import (
20
+ is_categorical_dtype,
21
+ is_datetime64_any_dtype,
22
+ is_numeric_dtype,
23
+ is_object_dtype,
24
+ is_list_like)
25
+
26
+ # Declare all the necessary variables
27
+ classifier_identifier = 'target'
28
+ params = get_classifier_params(classifier_identifier)
29
+
30
+ ## Labels dictionary ###
31
+ _lab_dict = {
32
+ 'NEGATIVE':'NO TARGET INFO',
33
+ 'TARGET':'TARGET',
34
+ }
35
+
36
+ # @st.cache_data
37
+ def to_excel(df):
38
+ # df['Target Validation'] = 'No'
39
+ # df['Netzero Validation'] = 'No'
40
+ # df['GHG Validation'] = 'No'
41
+ # df['Adapt-Mitig Validation'] = 'No'
42
+ # df['Sector'] = 'No'
43
+ len_df = len(df)
44
+ output = BytesIO()
45
+ writer = pd.ExcelWriter(output, engine='xlsxwriter')
46
+ df.to_excel(writer, index=False, sheet_name='rawdata')
47
+ if 'target_hits' in st.session_state:
48
+ target_hits = st.session_state['target_hits']
49
+ if 'keep' in target_hits.columns:
50
+
51
+ target_hits = target_hits[target_hits.keep == True]
52
+ target_hits = target_hits.reset_index(drop=True)
53
+ target_hits.drop(columns = ['keep'], inplace=True)
54
+ target_hits.to_excel(writer,index=False,sheet_name = 'Target')
55
+ else:
56
+
57
+ target_hits = target_hits.sort_values(by=['Target Score'], ascending=False)
58
+ target_hits = target_hits.reset_index(drop=True)
59
+ target_hits.to_excel(writer,index=False,sheet_name = 'Target')
60
+
61
+ else:
62
+ target_hits = df[df['Target Label'] == True]
63
+ target_hits.drop(columns=['Target Label','Netzero Score','GHG Score','Action Label',
64
+ 'Action Score','Policies_Plans Label','Indicator Label',
65
+ 'Policies_Plans Score','Conditional Score'],inplace=True)
66
+ target_hits = target_hits.sort_values(by=['Target Score'], ascending=False)
67
+ target_hits = target_hits.reset_index(drop=True)
68
+ target_hits.to_excel(writer,index=False,sheet_name = 'Target')
69
+
70
+
71
+ if 'action_hits' in st.session_state:
72
+ action_hits = st.session_state['action_hits']
73
+ if 'keep' in action_hits.columns:
74
+ action_hits = action_hits[action_hits.keep == True]
75
+ action_hits = action_hits.reset_index(drop=True)
76
+ action_hits.drop(columns = ['keep'], inplace=True)
77
+ action_hits.to_excel(writer,index=False,sheet_name = 'Action')
78
+ else:
79
+ action_hits = action_hits.sort_values(by=['Action Score'], ascending=False)
80
+ action_hits = action_hits.reset_index(drop=True)
81
+ action_hits.to_excel(writer,index=False,sheet_name = 'Action')
82
+ else:
83
+ action_hits = df[df['Action Label'] == True]
84
+ action_hits.drop(columns=['Target Label','Target Score','Netzero Score',
85
+ 'Netzero Label','GHG Label',
86
+ 'GHG Score','Action Label','Policies_Plans Label',
87
+ 'Policies_Plans Score','Conditional Score'],inplace=True)
88
+ action_hits = action_hits.sort_values(by=['Action Score'], ascending=False)
89
+ action_hits = action_hits.reset_index(drop=True)
90
+ action_hits.to_excel(writer,index=False,sheet_name = 'Action')
91
+
92
+ # hits = hits.drop(columns = ['Target Score','Netzero Score','GHG Score'])
93
+ workbook = writer.book
94
+ # worksheet = writer.sheets['Sheet1']
95
+ # worksheet.data_validation('L2:L{}'.format(len_df),
96
+ # {'validate': 'list',
97
+ # 'source': ['No', 'Yes', 'Discard']})
98
+ # worksheet.data_validation('M2:L{}'.format(len_df),
99
+ # {'validate': 'list',
100
+ # 'source': ['No', 'Yes', 'Discard']})
101
+ # worksheet.data_validation('N2:L{}'.format(len_df),
102
+ # {'validate': 'list',
103
+ # 'source': ['No', 'Yes', 'Discard']})
104
+ # worksheet.data_validation('O2:L{}'.format(len_df),
105
+ # {'validate': 'list',
106
+ # 'source': ['No', 'Yes', 'Discard']})
107
+ # worksheet.data_validation('P2:L{}'.format(len_df),
108
+ # {'validate': 'list',
109
+ # 'source': ['No', 'Yes', 'Discard']})
110
+ writer.save()
111
+ processed_data = output.getvalue()
112
+ return processed_data
113
+
114
+ def app():
115
+ ### Main app code ###
116
+ with st.container():
117
+ if 'key0' in st.session_state:
118
+ df = st.session_state.key0
119
+
120
+ #load Classifier
121
+ classifier = load_targetClassifier(classifier_name=params['model_name'])
122
+ st.session_state['{}_classifier'.format(classifier_identifier)] = classifier
123
+ if len(df) > 100:
124
+ warning_msg = ": This might take sometime, please sit back and relax."
125
+ else:
126
+ warning_msg = ""
127
+
128
+ df = target_classification(haystack_doc=df,
129
+ threshold= params['threshold'])
130
+ st.session_state.key1 = df
131
+
132
+ def filter_for_tracs(df):
133
+ sector_list = ['Transport','Energy','Economy-wide']
134
+ df['check'] = df['Sector Label'].apply(lambda x: any(i in x for i in sector_list))
135
+ df = df[df.check == True].reset_index(drop=True)
136
+ df['Sector Label'] = df['Sector Label'].apply(lambda x: [i for i in x if i in sector_list])
137
+ df.drop(columns = ['check'],inplace=True)
138
+ return df
139
+
140
+ def target_display():
141
+ if 'key1' in st.session_state:
142
+ df = st.session_state.key1
143
+ st.caption(""" **{}** is splitted into **{}** paragraphs/text chunks."""\
144
+ .format(os.path.basename(st.session_state['filename']),
145
+ len(df)))
146
+ hits = df[df['Target Label'] == 'TARGET'].reset_index(drop=True)
147
+ range_val = min(5,len(hits))
148
+ if range_val !=0:
149
+ # collecting some statistics
150
+ count_target = sum(hits['Target Label'] == 'TARGET')
151
+ count_netzero = sum(hits['Netzero Label'] == 'NETZERO TARGET')
152
+ count_ghg = sum(hits['GHG Label'] == 'GHG')
153
+ count_transport = sum([True if 'Transport' in x else False
154
+ for x in hits['Sector Label']])
155
+
156
+ c1, c2 = st.columns([1,1])
157
+ with c1:
158
+ st.write('**Target Paragraphs**: `{}`'.format(count_target))
159
+ st.write('**NetZero Related Paragraphs**: `{}`'.format(count_netzero))
160
+ with c2:
161
+ st.write('**GHG Target Related Paragraphs**: `{}`'.format(count_ghg))
162
+ st.write('**Transport Related Paragraphs**: `{}`'.format(count_transport))
163
+ # st.write('-------------------')
164
+ hits.drop(columns=['Target Label','Netzero Score','GHG Score','Action Label',
165
+ 'Action Score','Policies_Plans Label','Indicator Label',
166
+ 'Policies_Plans Score','Conditional Score'],inplace=True)
167
+ hits = hits.sort_values(by=['Target Score'], ascending=False)
168
+ hits = hits.reset_index(drop=True)
169
+
170
+ # netzerohit = hits[hits['Netzero Label'] == 'NETZERO']
171
+ # if not netzerohit.empty:
172
+ # netzerohit = netzerohit.sort_values(by = ['Netzero Score'], ascending = False)
173
+ # # st.write('-------------------')
174
+ # # st.markdown("###### Netzero paragraph ######")
175
+ # st.write('**Netzero paragraph** `page {}`: {}'.format(netzerohit.iloc[0]['page'],
176
+ # netzerohit.iloc[0]['text'].replace("\n", " ")))
177
+ # st.write("")
178
+ # else:
179
+ # st.info("🤔 No Netzero paragraph found")
180
+
181
+ # # st.write("**Result {}** `page {}` (Relevancy Score: {:.2f})'".format(i+1,hits.iloc[i]['page'],hits.iloc[i]['Relevancy'])")
182
+ # st.write('-------------------')
183
+ # st.markdown("###### Top few Target Classified paragraph/text results ######")
184
+ # range_val = min(5,len(hits))
185
+ # for i in range(range_val):
186
+ # # the page number reflects the page that contains the main paragraph
187
+ # # according to split limit, the overlapping part can be on a separate page
188
+ # st.write('**Result {}** (Relevancy Score: {:.2f}): `page {}`, `Sector: {}`,\
189
+ # `GHG: {}`, `Adapt-Mitig :{}`'\
190
+ # .format(i+1,hits.iloc[i]['Relevancy'],
191
+ # hits.iloc[i]['page'], hits.iloc[i]['Sector Label'],
192
+ # hits.iloc[i]['GHG Label'],hits.iloc[i]['Adapt-Mitig Label']))
193
+ # st.write("\t Text: \t{}".format(hits.iloc[i]['text'].replace("\n", " ")))
194
+ # hits = hits.reset_index(drop =True)
195
+ st.write('----------------')
196
+
197
+
198
+ st.caption("Filter table to select rows to keep for Target category")
199
+ hits = filter_for_tracs(hits)
200
+ convert_type = {'Netzero Label': 'category',
201
+ 'Conditional Label':'category',
202
+ 'GHG Label':'category',
203
+ }
204
+ hits = hits.astype(convert_type)
205
+ filter_dataframe(hits)
206
+
207
+ # filtered_df = filtered_df[filtered_df.keep == True]
208
+ # st.write('Explore the data')
209
+ # AgGrid(hits)
210
+
211
+
212
+ with st.sidebar:
213
+ st.write('-------------')
214
+ df_xlsx = to_excel(df)
215
+ st.download_button(label='📥 Download Result',
216
+ data=df_xlsx ,
217
+ file_name= os.path.splitext(os.path.basename(st.session_state['filename']))[0]+'.xlsx')
218
+
219
+ # st.write(
220
+ # """This app accomodates the blog [here](https://blog.streamlit.io/auto-generate-a-dataframe-filtering-ui-in-streamlit-with-filter_dataframe/)
221
+ # and walks you through one example of how the Streamlit
222
+ # Data Science Team builds add-on functions to Streamlit.
223
+ # """
224
+ # )
225
+
226
+
227
+ def filter_dataframe(df: pd.DataFrame) -> pd.DataFrame:
228
+ """
229
+ Adds a UI on top of a dataframe to let viewers filter columns
230
+
231
+ Args:
232
+ df (pd.DataFrame): Original dataframe
233
+
234
+ Returns:
235
+ pd.DataFrame: Filtered dataframe
236
+ """
237
+ modify = st.checkbox("Add filters")
238
+
239
+ if not modify:
240
+ st.session_state['target_hits'] = df
241
+ return
242
+
243
+
244
+ # df = df.copy()
245
+ # st.write(len(df))
246
+
247
+ # Try to convert datetimes into a standard format (datetime, no timezone)
248
+ # for col in df.columns:
249
+ # if is_object_dtype(df[col]):
250
+ # try:
251
+ # df[col] = pd.to_datetime(df[col])
252
+ # except Exception:
253
+ # pass
254
+
255
+ # if is_datetime64_any_dtype(df[col]):
256
+ # df[col] = df[col].dt.tz_localize(None)
257
+
258
+ modification_container = st.container()
259
+
260
+ with modification_container:
261
+ cols = list(set(df.columns) -{'page','Extracted Text'})
262
+ cols.sort()
263
+ to_filter_columns = st.multiselect("Filter dataframe on", cols
264
+ )
265
+ for column in to_filter_columns:
266
+ left, right = st.columns((1, 20))
267
+ left.write("↳")
268
+ # Treat columns with < 10 unique values as categorical
269
+ if is_categorical_dtype(df[column]):
270
+ # st.write(type(df[column][0]), column)
271
+ user_cat_input = right.multiselect(
272
+ f"Values for {column}",
273
+ df[column].unique(),
274
+ default=list(df[column].unique()),
275
+ )
276
+ df = df[df[column].isin(user_cat_input)]
277
+ elif is_numeric_dtype(df[column]):
278
+ _min = float(df[column].min())
279
+ _max = float(df[column].max())
280
+ step = (_max - _min) / 100
281
+ user_num_input = right.slider(
282
+ f"Values for {column}",
283
+ _min,
284
+ _max,
285
+ (_min, _max),
286
+ step=step,
287
+ )
288
+ df = df[df[column].between(*user_num_input)]
289
+ elif is_list_like(df[column]) & (type(df[column][0]) == list) :
290
+ list_vals = set(x for lst in df[column].tolist() for x in lst)
291
+ user_multi_input = right.multiselect(
292
+ f"Values for {column}",
293
+ list_vals,
294
+ default=list_vals,
295
+ )
296
+ df['check'] = df[column].apply(lambda x: any(i in x for i in user_multi_input))
297
+ df = df[df.check == True]
298
+ df.drop(columns = ['check'],inplace=True)
299
+
300
+ # df[df[column].between(*user_num_input)]
301
+ # elif is_datetime64_any_dtype(df[column]):
302
+ # user_date_input = right.date_input(
303
+ # f"Values for {column}",
304
+ # value=(
305
+ # df[column].min(),
306
+ # df[column].max(),
307
+ # ),
308
+ # )
309
+ # if len(user_date_input) == 2:
310
+ # user_date_input = tuple(map(pd.to_datetime, user_date_input))
311
+ # start_date, end_date = user_date_input
312
+ # df = df.loc[df[column].between(start_date, end_date)]
313
+ else:
314
+ user_text_input = right.text_input(
315
+ f"Substring or regex in {column}",
316
+ )
317
+ if user_text_input:
318
+ df = df[df[column].str.lower().str.contains(user_text_input)]
319
+
320
+ df = df.reset_index(drop=True)
321
+
322
+ st.session_state['target_hits'] = df
323
+ df['IKI_Netzero'] = df.apply(lambda x: 'T_NETZERO' if ((x['Netzero Label'] == 'NETZERO TARGET') &
324
+ (x['Conditional Label'] == 'UNCONDITIONAL'))
325
+ else 'T_NETZERO_C' if ((x['Netzero Label'] == 'NETZERO TARGET') &
326
+ (x['Conditional Label'] == 'CONDITIONAL')
327
+ )
328
+ else None, axis=1
329
+ )
330
+ def check_t(s,c):
331
+ temp = []
332
+ if (('Transport' in s) & (c== 'UNCONDITIONAL')):
333
+ temp.append('T_Transport_Unc')
334
+ if (('Transport' in s) & (c == 'CONDITIONAL')):
335
+ temp.append('T_Transport_C')
336
+ if (('Economy-wide' in s) & (c == 'CONDITIONAL')):
337
+ temp.append('T_Economy_C')
338
+ if (('Economy-wide' in s) & (c == 'UNCONDITIONAL')):
339
+ temp.append('T_Economy_Unc')
340
+ if (('Energy' in s) & (c == 'CONDITIONAL')):
341
+ temp.append('T_Energy_C')
342
+ if (('Energy' in s) & (c == 'UNCONDITIONAL')):
343
+ temp.append('T_Economy_Unc')
344
+ return temp
345
+ df['IKI_Target'] = df.apply(lambda x:check_t(x['Sector Label'], x['Conditional Label']),
346
+ axis=1 )
347
+
348
+ # target_hits = st.session_state['target_hits']
349
+ df['keep'] = True
350
+
351
+
352
+ df = df[['text','IKI_Netzero','IKI_Target','Target Score','Netzero Label','GHG Label',
353
+ 'Conditional Label','Sector Label','Adapt-Mitig Label','page','keep']]
354
+ st.dataframe(df)
355
+ # df = st.data_editor(
356
+ # df,
357
+ # column_config={
358
+ # "keep": st.column_config.CheckboxColumn(
359
+ # help="Select which rows to keep",
360
+ # default=False,
361
+ # )
362
+ # },
363
+ # disabled=list(set(df.columns) - {'keep'}),
364
+ # hide_index=True,
365
+ # )
366
+ # st.write("updating target hits....")
367
+ # st.write(len(df[df.keep == True]))
368
+ st.session_state['target_hits'] = df
369
+
370
+ return
371
+
372
+
373
+ # df = pd.read_csv(
374
+ # "https://raw.githubusercontent.com/mcnakhaee/palmerpenguins/master/palmerpenguins/data/penguins.csv"
375
+ # )
376
+
377
+
378
+ # else:
379
+ # st.info("🤔 No Targets found")
380
+ # count_df = df['Target Label'].value_counts()
381
+ # count_df = count_df.rename('count')
382
+ # count_df = count_df.rename_axis('Target Label').reset_index()
383
+ # count_df['Label_def'] = count_df['Target Label'].apply(lambda x: _lab_dict[x])
384
+ # st.plotly_chart(fig,use_container_width= True)
385
+
386
+ # count_netzero = sum(hits['Netzero Label'] == 'NETZERO')
387
+ # count_ghg = sum(hits['GHG Label'] == 'LABEL_2')
388
+ # count_economy = sum([True if 'Economy-wide' in x else False
389
+ # for x in hits['Sector Label']])
390
+ # # excel part
391
+ # temp = df[df['Relevancy']>threshold]
392
+
393
+ # df['Validation'] = 'No'
394
+ # df_xlsx = to_excel(df)
395
+ # st.download_button(label='📥 Download Current Result',
396
+ # data=df_xlsx ,
397
+ # file_name= 'file_target.xlsx')