leavoigt commited on
Commit
eb83e3d
1 Parent(s): 1968c31

Update appStore/target.py

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