leavoigt commited on
Commit
8f420e0
1 Parent(s): 3efd370

Update appStore/target.py

Browse files
Files changed (1) hide show
  1. appStore/target.py +352 -352
appStore/target.py CHANGED
@@ -1,368 +1,368 @@
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
- '0':'NO',
33
- '1':'YES',
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
 
116
- ### Main app code ###
117
- with st.container():
118
- if 'key0' in st.session_state:
119
- df = st.session_state.key0
120
-
121
- #load Classifier
122
- classifier = load_targetClassifier(classifier_name=params['model_name'])
123
- st.session_state['{}_classifier'.format(classifier_identifier)] = classifier
124
- if len(df) > 100:
125
- warning_msg = ": This might take sometime, please sit back and relax."
126
- else:
127
- warning_msg = ""
128
 
129
- df = target_classification(haystack_doc=df,
130
- threshold= params['threshold'])
131
- st.session_state.key1 = df
132
 
133
 
134
- # def target_display():
135
 
136
- # if 'key1' in st.session_state:
137
- # df = st.session_state.key1
138
- # st.caption(""" **{}** is splitted into **{}** paragraphs/text chunks."""\
139
- # .format(os.path.basename(st.session_state['filename']),
140
- # len(df)))
141
- # hits = df[df['Target Label'] == 'TARGET'].reset_index(drop=True)
142
- # range_val = min(5,len(hits))
143
- # if range_val !=0:
144
 
145
- # # collecting some statistics
146
- # count_target = sum(hits['Target Label'] == 'TARGET')
147
- # count_netzero = sum(hits['Netzero Label'] == 'NETZERO TARGET')
148
- # count_ghg = sum(hits['GHG Label'] == 'GHG')
149
- # count_transport = sum([True if 'Transport' in x else False
150
- # for x in hits['Sector Label']])
151
-
152
- # c1, c2 = st.columns([1,1])
153
- # with c1:
154
- # st.write('**Target Paragraphs**: `{}`'.format(count_target))
155
- # st.write('**NetZero Related Paragraphs**: `{}`'.format(count_netzero))
156
- # with c2:
157
- # st.write('**GHG Target Related Paragraphs**: `{}`'.format(count_ghg))
158
- # st.write('**Transport Related Paragraphs**: `{}`'.format(count_transport))
159
- # # st.write('-------------------')
160
- # hits.drop(columns=['Target Label','Netzero Score','GHG Score','Action Label',
161
- # 'Action Score','Policies_Plans Label','Indicator Label',
162
- # 'Policies_Plans Score','Conditional Score'],inplace=True)
163
- # hits = hits.sort_values(by=['Target Score'], ascending=False)
164
- # hits = hits.reset_index(drop=True)
165
-
166
- # # netzerohit = hits[hits['Netzero Label'] == 'NETZERO']
167
- # # if not netzerohit.empty:
168
- # # netzerohit = netzerohit.sort_values(by = ['Netzero Score'], ascending = False)
169
- # # # st.write('-------------------')
170
- # # # st.markdown("###### Netzero paragraph ######")
171
- # # st.write('**Netzero paragraph** `page {}`: {}'.format(netzerohit.iloc[0]['page'],
172
- # # netzerohit.iloc[0]['text'].replace("\n", " ")))
173
- # # st.write("")
174
- # # else:
175
- # # st.info("🤔 No Netzero paragraph found")
176
-
177
- # # st.write("**Result {}** `page {}` (Relevancy Score: {:.2f})'".format(i+1,hits.iloc[i]['page'],hits.iloc[i]['Relevancy'])")
178
- # st.write('-------------------')
179
- # st.markdown("###### Top few Target Classified paragraph/text results ######")
180
- # range_val = min(5,len(hits))
181
- # for i in range(range_val):
182
- # # the page number reflects the page that contains the main paragraph
183
- # # according to split limit, the overlapping part can be on a separate page
184
- # st.write('**Result {}** (Relevancy Score: {:.2f}): `page {}`, `Sector: {}`,\
185
- # `GHG: {}`, `Adapt-Mitig :{}`'\
186
- # .format(i+1,hits.iloc[i]['Relevancy'],
187
- # hits.iloc[i]['page'], hits.iloc[i]['Sector Label'],
188
- # hits.iloc[i]['GHG Label'],hits.iloc[i]['Adapt-Mitig Label']))
189
- # st.write("\t Text: \t{}".format(hits.iloc[i]['text'].replace("\n", " ")))
190
- # hits = hits.reset_index(drop =True)
191
- st.write('----------------')
192
-
193
-
194
- st.caption("Filter table to select rows to keep for Target category")
195
- hits = filter_for_tracs(hits)
196
- convert_type = {'Netzero Label': 'category',
197
- 'Conditional Label':'category',
198
- 'GHG Label':'category',
199
- }
200
- hits = hits.astype(convert_type)
201
- filter_dataframe(hits)
202
 
203
- # filtered_df = filtered_df[filtered_df.keep == True]
204
- # st.write('Explore the data')
205
- # AgGrid(hits)
206
 
207
 
208
- with st.sidebar:
209
- st.write('-------------')
210
- df_xlsx = to_excel(df)
211
- st.download_button(label='📥 Download Result',
212
- data=df_xlsx ,
213
- file_name= os.path.splitext(os.path.basename(st.session_state['filename']))[0]+'.xlsx')
214
-
215
- # st.write(
216
- # """This app accomodates the blog [here](https://blog.streamlit.io/auto-generate-a-dataframe-filtering-ui-in-streamlit-with-filter_dataframe/)
217
- # and walks you through one example of how the Streamlit
218
- # Data Science Team builds add-on functions to Streamlit.
219
- # """
220
- # )
221
-
222
-
223
- # def filter_dataframe(df: pd.DataFrame) -> pd.DataFrame:
224
- # """
225
- # Adds a UI on top of a dataframe to let viewers filter columns
226
-
227
- # Args:
228
- # df (pd.DataFrame): Original dataframe
229
-
230
- # Returns:
231
- # pd.DataFrame: Filtered dataframe
232
- # """
233
- # modify = st.checkbox("Add filters")
234
-
235
- # if not modify:
236
- # st.session_state['target_hits'] = df
237
- # return
238
-
239
-
240
- # # df = df.copy()
241
- # # st.write(len(df))
242
-
243
- # # Try to convert datetimes into a standard format (datetime, no timezone)
244
- # # for col in df.columns:
245
- # # if is_object_dtype(df[col]):
246
- # # try:
247
- # # df[col] = pd.to_datetime(df[col])
248
- # # except Exception:
249
- # # pass
250
-
251
- # # if is_datetime64_any_dtype(df[col]):
252
- # # df[col] = df[col].dt.tz_localize(None)
253
-
254
- # modification_container = st.container()
255
-
256
- # with modification_container:
257
- # cols = list(set(df.columns) -{'page','Extracted Text'})
258
- # cols.sort()
259
- # to_filter_columns = st.multiselect("Filter dataframe on", cols
260
- # )
261
- # for column in to_filter_columns:
262
- # left, right = st.columns((1, 20))
263
- # left.write("↳")
264
- # # Treat columns with < 10 unique values as categorical
265
- # if is_categorical_dtype(df[column]):
266
- # # st.write(type(df[column][0]), column)
267
- # user_cat_input = right.multiselect(
268
- # f"Values for {column}",
269
- # df[column].unique(),
270
- # default=list(df[column].unique()),
271
- # )
272
- # df = df[df[column].isin(user_cat_input)]
273
- # elif is_numeric_dtype(df[column]):
274
- # _min = float(df[column].min())
275
- # _max = float(df[column].max())
276
- # step = (_max - _min) / 100
277
- # user_num_input = right.slider(
278
- # f"Values for {column}",
279
- # _min,
280
- # _max,
281
- # (_min, _max),
282
- # step=step,
283
- # )
284
- # df = df[df[column].between(*user_num_input)]
285
- # elif is_list_like(df[column]) & (type(df[column][0]) == list) :
286
- # list_vals = set(x for lst in df[column].tolist() for x in lst)
287
- # user_multi_input = right.multiselect(
288
- # f"Values for {column}",
289
- # list_vals,
290
- # default=list_vals,
291
- # )
292
- # df['check'] = df[column].apply(lambda x: any(i in x for i in user_multi_input))
293
- # df = df[df.check == True]
294
- # df.drop(columns = ['check'],inplace=True)
295
 
296
- # # df[df[column].between(*user_num_input)]
297
- # # elif is_datetime64_any_dtype(df[column]):
298
- # # user_date_input = right.date_input(
299
- # # f"Values for {column}",
300
- # # value=(
301
- # # df[column].min(),
302
- # # df[column].max(),
303
- # # ),
304
- # # )
305
- # # if len(user_date_input) == 2:
306
- # # user_date_input = tuple(map(pd.to_datetime, user_date_input))
307
- # # start_date, end_date = user_date_input
308
- # # df = df.loc[df[column].between(start_date, end_date)]
309
- # else:
310
- # user_text_input = right.text_input(
311
- # f"Substring or regex in {column}",
312
- # )
313
- # if user_text_input:
314
- # df = df[df[column].str.lower().str.contains(user_text_input)]
315
 
316
- # df = df.reset_index(drop=True)
317
 
318
- # st.session_state['target_hits'] = df
319
- # df['IKI_Netzero'] = df.apply(lambda x: 'T_NETZERO' if ((x['Netzero Label'] == 'NETZERO TARGET') &
320
- # (x['Conditional Label'] == 'UNCONDITIONAL'))
321
- # else 'T_NETZERO_C' if ((x['Netzero Label'] == 'NETZERO TARGET') &
322
- # (x['Conditional Label'] == 'CONDITIONAL')
323
- # )
324
- # else None, axis=1
325
- # )
326
- # def check_t(s,c):
327
- # temp = []
328
- # if (('Transport' in s) & (c== 'UNCONDITIONAL')):
329
- # temp.append('T_Transport_Unc')
330
- # if (('Transport' in s) & (c == 'CONDITIONAL')):
331
- # temp.append('T_Transport_C')
332
- # if (('Economy-wide' in s) & (c == 'CONDITIONAL')):
333
- # temp.append('T_Economy_C')
334
- # if (('Economy-wide' in s) & (c == 'UNCONDITIONAL')):
335
- # temp.append('T_Economy_Unc')
336
- # if (('Energy' in s) & (c == 'CONDITIONAL')):
337
- # temp.append('T_Energy_C')
338
- # if (('Energy' in s) & (c == 'UNCONDITIONAL')):
339
- # temp.append('T_Economy_Unc')
340
- # return temp
341
- # df['IKI_Target'] = df.apply(lambda x:check_t(x['Sector Label'], x['Conditional Label']),
342
- # axis=1 )
343
-
344
- # # target_hits = st.session_state['target_hits']
345
- # df['keep'] = True
346
-
347
-
348
- # df = df[['text','IKI_Netzero','IKI_Target','Target Score','Netzero Label','GHG Label',
349
- # 'Conditional Label','Sector Label','Adapt-Mitig Label','page','keep']]
350
- # st.dataframe(df)
351
- # # df = st.data_editor(
352
- # # df,
353
- # # column_config={
354
- # # "keep": st.column_config.CheckboxColumn(
355
- # # help="Select which rows to keep",
356
- # # default=False,
357
- # # )
358
- # # },
359
- # # disabled=list(set(df.columns) - {'keep'}),
360
- # # hide_index=True,
361
- # # )
362
- # # st.write("updating target hits....")
363
- # # st.write(len(df[df.keep == True]))
364
- # st.session_state['target_hits'] = df
365
 
366
- # return
367
 
368
 
 
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
+ # '0':'NO',
33
+ # '1':'YES',
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
 
116
+ # ### Main app code ###
117
+ # with st.container():
118
+ # if 'key0' in st.session_state:
119
+ # df = st.session_state.key0
120
+
121
+ # #load Classifier
122
+ # classifier = load_targetClassifier(classifier_name=params['model_name'])
123
+ # st.session_state['{}_classifier'.format(classifier_identifier)] = classifier
124
+ # if len(df) > 100:
125
+ # warning_msg = ": This might take sometime, please sit back and relax."
126
+ # else:
127
+ # warning_msg = ""
128
 
129
+ # df = target_classification(haystack_doc=df,
130
+ # threshold= params['threshold'])
131
+ # st.session_state.key1 = df
132
 
133
 
134
+ # # def target_display():
135
 
136
+ # # if 'key1' in st.session_state:
137
+ # # df = st.session_state.key1
138
+ # # st.caption(""" **{}** is splitted into **{}** paragraphs/text chunks."""\
139
+ # # .format(os.path.basename(st.session_state['filename']),
140
+ # # len(df)))
141
+ # # hits = df[df['Target Label'] == 'TARGET'].reset_index(drop=True)
142
+ # # range_val = min(5,len(hits))
143
+ # # if range_val !=0:
144
 
145
+ # # # collecting some statistics
146
+ # # count_target = sum(hits['Target Label'] == 'TARGET')
147
+ # # count_netzero = sum(hits['Netzero Label'] == 'NETZERO TARGET')
148
+ # # count_ghg = sum(hits['GHG Label'] == 'GHG')
149
+ # # count_transport = sum([True if 'Transport' in x else False
150
+ # # for x in hits['Sector Label']])
151
+
152
+ # # c1, c2 = st.columns([1,1])
153
+ # # with c1:
154
+ # # st.write('**Target Paragraphs**: `{}`'.format(count_target))
155
+ # # st.write('**NetZero Related Paragraphs**: `{}`'.format(count_netzero))
156
+ # # with c2:
157
+ # # st.write('**GHG Target Related Paragraphs**: `{}`'.format(count_ghg))
158
+ # # st.write('**Transport Related Paragraphs**: `{}`'.format(count_transport))
159
+ # # # st.write('-------------------')
160
+ # # hits.drop(columns=['Target Label','Netzero Score','GHG Score','Action Label',
161
+ # # 'Action Score','Policies_Plans Label','Indicator Label',
162
+ # # 'Policies_Plans Score','Conditional Score'],inplace=True)
163
+ # # hits = hits.sort_values(by=['Target Score'], ascending=False)
164
+ # # hits = hits.reset_index(drop=True)
165
+
166
+ # # # netzerohit = hits[hits['Netzero Label'] == 'NETZERO']
167
+ # # # if not netzerohit.empty:
168
+ # # # netzerohit = netzerohit.sort_values(by = ['Netzero Score'], ascending = False)
169
+ # # # # st.write('-------------------')
170
+ # # # # st.markdown("###### Netzero paragraph ######")
171
+ # # # st.write('**Netzero paragraph** `page {}`: {}'.format(netzerohit.iloc[0]['page'],
172
+ # # # netzerohit.iloc[0]['text'].replace("\n", " ")))
173
+ # # # st.write("")
174
+ # # # else:
175
+ # # # st.info("🤔 No Netzero paragraph found")
176
+
177
+ # # # st.write("**Result {}** `page {}` (Relevancy Score: {:.2f})'".format(i+1,hits.iloc[i]['page'],hits.iloc[i]['Relevancy'])")
178
+ # # st.write('-------------------')
179
+ # # st.markdown("###### Top few Target Classified paragraph/text results ######")
180
+ # # range_val = min(5,len(hits))
181
+ # # for i in range(range_val):
182
+ # # # the page number reflects the page that contains the main paragraph
183
+ # # # according to split limit, the overlapping part can be on a separate page
184
+ # # st.write('**Result {}** (Relevancy Score: {:.2f}): `page {}`, `Sector: {}`,\
185
+ # # `GHG: {}`, `Adapt-Mitig :{}`'\
186
+ # # .format(i+1,hits.iloc[i]['Relevancy'],
187
+ # # hits.iloc[i]['page'], hits.iloc[i]['Sector Label'],
188
+ # # hits.iloc[i]['GHG Label'],hits.iloc[i]['Adapt-Mitig Label']))
189
+ # # st.write("\t Text: \t{}".format(hits.iloc[i]['text'].replace("\n", " ")))
190
+ # # hits = hits.reset_index(drop =True)
191
+ # st.write('----------------')
192
+
193
+
194
+ # st.caption("Filter table to select rows to keep for Target category")
195
+ # hits = filter_for_tracs(hits)
196
+ # convert_type = {'Netzero Label': 'category',
197
+ # 'Conditional Label':'category',
198
+ # 'GHG Label':'category',
199
+ # }
200
+ # hits = hits.astype(convert_type)
201
+ # filter_dataframe(hits)
202
 
203
+ # # filtered_df = filtered_df[filtered_df.keep == True]
204
+ # # st.write('Explore the data')
205
+ # # AgGrid(hits)
206
 
207
 
208
+ # with st.sidebar:
209
+ # st.write('-------------')
210
+ # df_xlsx = to_excel(df)
211
+ # st.download_button(label='📥 Download Result',
212
+ # data=df_xlsx ,
213
+ # file_name= os.path.splitext(os.path.basename(st.session_state['filename']))[0]+'.xlsx')
214
+
215
+ # # st.write(
216
+ # # """This app accomodates the blog [here](https://blog.streamlit.io/auto-generate-a-dataframe-filtering-ui-in-streamlit-with-filter_dataframe/)
217
+ # # and walks you through one example of how the Streamlit
218
+ # # Data Science Team builds add-on functions to Streamlit.
219
+ # # """
220
+ # # )
221
+
222
+
223
+ # # def filter_dataframe(df: pd.DataFrame) -> pd.DataFrame:
224
+ # # """
225
+ # # Adds a UI on top of a dataframe to let viewers filter columns
226
+
227
+ # # Args:
228
+ # # df (pd.DataFrame): Original dataframe
229
+
230
+ # # Returns:
231
+ # # pd.DataFrame: Filtered dataframe
232
+ # # """
233
+ # # modify = st.checkbox("Add filters")
234
+
235
+ # # if not modify:
236
+ # # st.session_state['target_hits'] = df
237
+ # # return
238
+
239
+
240
+ # # # df = df.copy()
241
+ # # # st.write(len(df))
242
+
243
+ # # # Try to convert datetimes into a standard format (datetime, no timezone)
244
+ # # # for col in df.columns:
245
+ # # # if is_object_dtype(df[col]):
246
+ # # # try:
247
+ # # # df[col] = pd.to_datetime(df[col])
248
+ # # # except Exception:
249
+ # # # pass
250
+
251
+ # # # if is_datetime64_any_dtype(df[col]):
252
+ # # # df[col] = df[col].dt.tz_localize(None)
253
+
254
+ # # modification_container = st.container()
255
+
256
+ # # with modification_container:
257
+ # # cols = list(set(df.columns) -{'page','Extracted Text'})
258
+ # # cols.sort()
259
+ # # to_filter_columns = st.multiselect("Filter dataframe on", cols
260
+ # # )
261
+ # # for column in to_filter_columns:
262
+ # # left, right = st.columns((1, 20))
263
+ # # left.write("↳")
264
+ # # # Treat columns with < 10 unique values as categorical
265
+ # # if is_categorical_dtype(df[column]):
266
+ # # # st.write(type(df[column][0]), column)
267
+ # # user_cat_input = right.multiselect(
268
+ # # f"Values for {column}",
269
+ # # df[column].unique(),
270
+ # # default=list(df[column].unique()),
271
+ # # )
272
+ # # df = df[df[column].isin(user_cat_input)]
273
+ # # elif is_numeric_dtype(df[column]):
274
+ # # _min = float(df[column].min())
275
+ # # _max = float(df[column].max())
276
+ # # step = (_max - _min) / 100
277
+ # # user_num_input = right.slider(
278
+ # # f"Values for {column}",
279
+ # # _min,
280
+ # # _max,
281
+ # # (_min, _max),
282
+ # # step=step,
283
+ # # )
284
+ # # df = df[df[column].between(*user_num_input)]
285
+ # # elif is_list_like(df[column]) & (type(df[column][0]) == list) :
286
+ # # list_vals = set(x for lst in df[column].tolist() for x in lst)
287
+ # # user_multi_input = right.multiselect(
288
+ # # f"Values for {column}",
289
+ # # list_vals,
290
+ # # default=list_vals,
291
+ # # )
292
+ # # df['check'] = df[column].apply(lambda x: any(i in x for i in user_multi_input))
293
+ # # df = df[df.check == True]
294
+ # # df.drop(columns = ['check'],inplace=True)
295
 
296
+ # # # df[df[column].between(*user_num_input)]
297
+ # # # elif is_datetime64_any_dtype(df[column]):
298
+ # # # user_date_input = right.date_input(
299
+ # # # f"Values for {column}",
300
+ # # # value=(
301
+ # # # df[column].min(),
302
+ # # # df[column].max(),
303
+ # # # ),
304
+ # # # )
305
+ # # # if len(user_date_input) == 2:
306
+ # # # user_date_input = tuple(map(pd.to_datetime, user_date_input))
307
+ # # # start_date, end_date = user_date_input
308
+ # # # df = df.loc[df[column].between(start_date, end_date)]
309
+ # # else:
310
+ # # user_text_input = right.text_input(
311
+ # # f"Substring or regex in {column}",
312
+ # # )
313
+ # # if user_text_input:
314
+ # # df = df[df[column].str.lower().str.contains(user_text_input)]
315
 
316
+ # # df = df.reset_index(drop=True)
317
 
318
+ # # st.session_state['target_hits'] = df
319
+ # # df['IKI_Netzero'] = df.apply(lambda x: 'T_NETZERO' if ((x['Netzero Label'] == 'NETZERO TARGET') &
320
+ # # (x['Conditional Label'] == 'UNCONDITIONAL'))
321
+ # # else 'T_NETZERO_C' if ((x['Netzero Label'] == 'NETZERO TARGET') &
322
+ # # (x['Conditional Label'] == 'CONDITIONAL')
323
+ # # )
324
+ # # else None, axis=1
325
+ # # )
326
+ # # def check_t(s,c):
327
+ # # temp = []
328
+ # # if (('Transport' in s) & (c== 'UNCONDITIONAL')):
329
+ # # temp.append('T_Transport_Unc')
330
+ # # if (('Transport' in s) & (c == 'CONDITIONAL')):
331
+ # # temp.append('T_Transport_C')
332
+ # # if (('Economy-wide' in s) & (c == 'CONDITIONAL')):
333
+ # # temp.append('T_Economy_C')
334
+ # # if (('Economy-wide' in s) & (c == 'UNCONDITIONAL')):
335
+ # # temp.append('T_Economy_Unc')
336
+ # # if (('Energy' in s) & (c == 'CONDITIONAL')):
337
+ # # temp.append('T_Energy_C')
338
+ # # if (('Energy' in s) & (c == 'UNCONDITIONAL')):
339
+ # # temp.append('T_Economy_Unc')
340
+ # # return temp
341
+ # # df['IKI_Target'] = df.apply(lambda x:check_t(x['Sector Label'], x['Conditional Label']),
342
+ # # axis=1 )
343
+
344
+ # # # target_hits = st.session_state['target_hits']
345
+ # # df['keep'] = True
346
+
347
+
348
+ # # df = df[['text','IKI_Netzero','IKI_Target','Target Score','Netzero Label','GHG Label',
349
+ # # 'Conditional Label','Sector Label','Adapt-Mitig Label','page','keep']]
350
+ # # st.dataframe(df)
351
+ # # # df = st.data_editor(
352
+ # # # df,
353
+ # # # column_config={
354
+ # # # "keep": st.column_config.CheckboxColumn(
355
+ # # # help="Select which rows to keep",
356
+ # # # default=False,
357
+ # # # )
358
+ # # # },
359
+ # # # disabled=list(set(df.columns) - {'keep'}),
360
+ # # # hide_index=True,
361
+ # # # )
362
+ # # # st.write("updating target hits....")
363
+ # # # st.write(len(df[df.keep == True]))
364
+ # # st.session_state['target_hits'] = df
365
 
366
+ # # return
367
 
368