File size: 29,555 Bytes
1e0e995 b5fab4b 1e0e995 95fc4d2 1e0e995 a340427 338b9ad 1e0e995 c05ff3f 338b9ad b5fab4b 338b9ad c05ff3f 1e0e995 c05ff3f 1e0e995 338b9ad 1e0e995 a340427 1e0e995 95fc4d2 1e0e995 95fc4d2 c05ff3f 95fc4d2 c05ff3f a340427 b5fab4b 95fc4d2 338b9ad 95fc4d2 338b9ad 95fc4d2 b5fab4b 95fc4d2 a340427 95fc4d2 38c2e3c 95fc4d2 338b9ad 95fc4d2 b5fab4b af4403f a340427 b5fab4b 38c2e3c b5fab4b 4ffbfe7 b5fab4b a7d1ac5 f435b72 a7d1ac5 a340427 b5fab4b a7d1ac5 1e0e995 95fc4d2 1e0e995 95fc4d2 1e0e995 95fc4d2 1e0e995 a7d1ac5 1e0e995 a7d1ac5 1e0e995 a7d1ac5 1e0e995 a7d1ac5 |
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 |
# set path
import glob, os, sys
sys.path.append('../utils')
#import needed libraries
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import streamlit as st
from utils.policyaction_classifier import load_policyactionClassifier, policyaction_classification
import logging
logger = logging.getLogger(__name__)
from utils.config import get_classifier_params
from utils.preprocessing import paraLengthCheck
from io import BytesIO
import xlsxwriter
import plotly.express as px
from pandas.api.types import (
is_categorical_dtype,
is_datetime64_any_dtype,
is_numeric_dtype,
is_object_dtype,
is_list_like)
# Declare all the necessary variables
classifier_identifier = 'policyaction'
params = get_classifier_params(classifier_identifier)
# @st.cache_data
def to_excel(df):
# df['Target Validation'] = 'No'
# df['Netzero Validation'] = 'No'
# df['GHG Validation'] = 'No'
# df['Adapt-Mitig Validation'] = 'No'
# df['Sector'] = 'No'
len_df = len(df)
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, index=False, sheet_name='rawdata')
if 'target_hits' in st.session_state:
target_hits = st.session_state['target_hits']
if 'keep' in target_hits.columns:
target_hits = target_hits[target_hits.keep == True]
target_hits = target_hits.reset_index(drop=True)
target_hits.drop(columns = ['keep'], inplace=True)
target_hits.to_excel(writer,index=False,sheet_name = 'Target')
else:
target_hits = target_hits.sort_values(by=['Target Score'], ascending=False)
target_hits = target_hits.reset_index(drop=True)
target_hits.to_excel(writer,index=False,sheet_name = 'Target')
else:
target_hits = df[df['Target Label'] == True]
target_hits.drop(columns=['Target Label','Netzero Score','GHG Score','Action Label',
'Action Score','Policies_Plans Label','Indicator Label',
'Policies_Plans Score','Conditional Score'],inplace=True)
target_hits = target_hits.sort_values(by=['Target Score'], ascending=False)
target_hits = target_hits.reset_index(drop=True)
target_hits.to_excel(writer,index=False,sheet_name = 'Target')
if 'action_hits' in st.session_state:
action_hits = st.session_state['action_hits']
if 'keep' in action_hits.columns:
action_hits = action_hits[action_hits.keep == True]
action_hits = action_hits.reset_index(drop=True)
action_hits.drop(columns = ['keep'], inplace=True)
action_hits.to_excel(writer,index=False,sheet_name = 'Action')
else:
action_hits = action_hits.sort_values(by=['Action Score'], ascending=False)
action_hits = action_hits.reset_index(drop=True)
action_hits.to_excel(writer,index=False,sheet_name = 'Action')
else:
action_hits = df[df['Action Label'] == True]
action_hits.drop(columns=['Target Label','Target Score','Netzero Score',
'Netzero Label','GHG Label',
'GHG Score','Action Label','Policies_Plans Label',
'Policies_Plans Score','Conditional Score'],inplace=True)
action_hits = action_hits.sort_values(by=['Action Score'], ascending=False)
action_hits = action_hits.reset_index(drop=True)
action_hits.to_excel(writer,index=False,sheet_name = 'Action')
if 'policy_hits' in st.session_state:
policy_hits = st.session_state['policy_hits']
if 'keep' in policy_hits.columns:
policy_hits = policy_hits[policy_hits.keep == True]
policy_hits = policy_hits.reset_index(drop=True)
policy_hits.drop(columns = ['keep'], inplace=True)
policy_hits.to_excel(writer,index=False,sheet_name = 'Policy')
else:
policy_hits = policy_hits.sort_values(by=['Policies_Plans Score'], ascending=False)
policy_hits = policy_hits.reset_index(drop=True)
policy_hits.to_excel(writer,index=False,sheet_name = 'Policy')
else:
policy_hits = df[df['Action Label'] == True]
policy_hits.drop(columns=['Target Label','Target Score','Netzero Score',
'Netzero Label','GHG Label',
'GHG Score','Action Label','Policies_Plans Label',
'Action Score','Conditional Score'],inplace=True)
policy_hits = policy_hits.sort_values(by=['Policies_Plans Score'], ascending=False)
policy_hits = policy_hits.reset_index(drop=True)
policy_hits.to_excel(writer,index=False,sheet_name = 'Policy')
# hits = hits.drop(columns = ['Target Score','Netzero Score','GHG Score'])
workbook = writer.book
# worksheet = writer.sheets['Sheet1']
# worksheet.data_validation('L2:L{}'.format(len_df),
# {'validate': 'list',
# 'source': ['No', 'Yes', 'Discard']})
# worksheet.data_validation('M2:L{}'.format(len_df),
# {'validate': 'list',
# 'source': ['No', 'Yes', 'Discard']})
# worksheet.data_validation('N2:L{}'.format(len_df),
# {'validate': 'list',
# 'source': ['No', 'Yes', 'Discard']})
# worksheet.data_validation('O2:L{}'.format(len_df),
# {'validate': 'list',
# 'source': ['No', 'Yes', 'Discard']})
# worksheet.data_validation('P2:L{}'.format(len_df),
# {'validate': 'list',
# 'source': ['No', 'Yes', 'Discard']})
writer.save()
processed_data = output.getvalue()
return processed_data
# def to_excel(df, hits):
# len_df = len(df)
# output = BytesIO()
# writer = pd.ExcelWriter(output, engine='xlsxwriter')
# df.to_excel(writer, index=False, sheet_name='rawdata')
# if 'keep' in hits.columns:
# hits = hits[hits.keep == True]
# hits = hits.reset_index(drop=True)
# hits.drop(columns = ['keep'], inplace=True)
# # hits = hits.drop(columns = ['Target Score','Netzero Score','GHG Score'])
# hits.to_excel(writer,index=False,sheet_name = 'Action')
# workbook = writer.book
# # worksheet = writer.sheets['Sheet1']
# # worksheet.data_validation('L2:L{}'.format(len_df),
# # {'validate': 'list',
# # 'source': ['No', 'Yes', 'Discard']})
# # worksheet.data_validation('M2:L{}'.format(len_df),
# # {'validate': 'list',
# # 'source': ['No', 'Yes', 'Discard']})
# # worksheet.data_validation('N2:L{}'.format(len_df),
# # {'validate': 'list',
# # 'source': ['No', 'Yes', 'Discard']})
# # worksheet.data_validation('O2:L{}'.format(len_df),
# # {'validate': 'list',
# # 'source': ['No', 'Yes', 'Discard']})
# # worksheet.data_validation('P2:L{}'.format(len_df),
# # {'validate': 'list',
# # 'source': ['No', 'Yes', 'Discard']})
# writer.save()
# processed_data = output.getvalue()
# return processed_data
def app():
### Main app code ###
with st.container():
if 'key1' in st.session_state:
df = st.session_state.key1
classifier = load_policyactionClassifier(classifier_name=params['model_name'])
st.session_state['{}_classifier'.format(classifier_identifier)] = classifier
if sum(df['Target Label'] == 'TARGET') > 100:
warning_msg = ": This might take sometime, please sit back and relax."
else:
warning_msg = ""
df = policyaction_classification(haystack_doc=df,
threshold= params['threshold'])
st.session_state.key1 = df
def filter_for_tracs(df):
sector_list = ['Transport','Energy','Economy-wide']
df['check'] = df['Sector Label'].apply(lambda x: any(i in x for i in sector_list))
df = df[df.check == True].reset_index(drop=True)
df['Sector Label'] = df['Sector Label'].apply(lambda x: [i for i in x if i in sector_list])
df.drop(columns = ['check'],inplace=True)
return df
def action_display():
if 'key1' in st.session_state:
df = st.session_state.key1
st.caption(""" **{}** is splitted into **{}** paragraphs/text chunks."""\
.format(os.path.basename(st.session_state['filename']),
len(df)))
hits = df[df['Action Label'] == 'Action']
range_val = min(5,len(hits))
if range_val !=0:
count_action = len(hits)
hits.drop(columns=['Target Label','Target Score','Netzero Score',
'Netzero Label','GHG Label',
'GHG Score','Action Label','Policies_Plans Label',
'Policies_Plans Score','Conditional Score'],inplace=True)
hits = hits.sort_values(by=['Action Score'], ascending=False)
hits = hits.reset_index(drop=True)
st.write('----------------')
st.caption("Filter table to select rows to keep for Action category")
hits = filter_for_tracs(hits)
convert_type = {'Conditional Label':'category',
}
hits = hits.astype(convert_type)
filter_dataframe_action(hits)
# filtered_df = filtered_df[filtered_df.keep == True]
# st.write('Explore the data')
# AgGrid(hits)
with st.sidebar:
st.write('-------------')
df_xlsx = to_excel(df)
st.download_button(label='π₯ Download Result',
data=df_xlsx ,
file_name= os.path.splitext(os.path.basename(st.session_state['filename']))[0]+'.xlsx')
def filter_dataframe_action(df: pd.DataFrame) -> pd.DataFrame:
"""
Adds a UI on top of a dataframe to let viewers filter columns
Args:
df (pd.DataFrame): Original dataframe
Returns:
pd.DataFrame: Filtered dataframe
"""
modify = st.checkbox("Add filters")
if not modify:
st.session_state['action_hits'] = df
return
df = df.copy()
# Try to convert datetimes into a standard format (datetime, no timezone)
# for col in df.columns:
# if is_object_dtype(df[col]):
# try:
# df[col] = pd.to_datetime(df[col])
# except Exception:
# pass
# if is_datetime64_any_dtype(df[col]):
# df[col] = df[col].dt.tz_localize(None)
modification_container = st.container()
with modification_container:
cols = list(set(df.columns) -{'page','Extracted Text'})
cols.sort()
to_filter_columns = st.multiselect("Filter dataframe on", cols
)
# to_filter_columns = st.multiselect("Filter dataframe on", df.columns)
for column in to_filter_columns:
left, right = st.columns((1, 20))
left.write("β³")
# Treat columns with < 10 unique values as categorical
if is_categorical_dtype(df[column]):
user_cat_input = right.multiselect(
f"Values for {column}",
df[column].unique(),
default=list(df[column].unique()),
)
df = df[df[column].isin(user_cat_input)]
elif is_numeric_dtype(df[column]):
_min = float(df[column].min())
_max = float(df[column].max())
step = (_max - _min) / 100
user_num_input = right.slider(
f"Values for {column}",
_min,
_max,
(_min, _max),
step=step,
)
df = df[df[column].between(*user_num_input)]
elif is_list_like(df[column]) & (type(df[column][0]) == list):
list_vals = set(x for lst in df[column].tolist() for x in lst)
user_multi_input = right.multiselect(
f"Values for {column}",
list_vals,
default=list_vals,
)
df['check'] = df[column].apply(lambda x: any(i in x for i in user_multi_input))
df = df[df.check == True]
df.drop(columns = ['check'],inplace=True)
# df[df[column].between(*user_num_input)]
# elif is_datetime64_any_dtype(df[column]):
# user_date_input = right.date_input(
# f"Values for {column}",
# value=(
# df[column].min(),
# df[column].max(),
# ),
# )
# if len(user_date_input) == 2:
# user_date_input = tuple(map(pd.to_datetime, user_date_input))
# start_date, end_date = user_date_input
# df = df.loc[df[column].between(start_date, end_date)]
else:
user_text_input = right.text_input(
f"Substring or regex in {column}",
)
if user_text_input:
df = df[df[column].str.contains(user_text_input)]
df['keep'] = True
df = df[['keep','text','Action Score','Conditional Label',
'Sector Label','Adapt-Mitig Label','Indicator Label','page']]
df = st.data_editor(
df,
column_config={
"keep": st.column_config.CheckboxColumn(
help="Select which rows to keep",
default=False,
)
},
disabled=list(set(df.columns) - {'keep'}),
hide_index=True,
)
st.session_state['action_hits'] = df
return
def filter_dataframe_policy(df: pd.DataFrame) -> pd.DataFrame:
"""
Adds a UI on top of a dataframe to let viewers filter columns
Args:
df (pd.DataFrame): Original dataframe
Returns:
pd.DataFrame: Filtered dataframe
"""
modify = st.checkbox("Add filters")
if not modify:
st.session_state['policy_hits'] = df
return
df = df.copy()
# Try to convert datetimes into a standard format (datetime, no timezone)
# for col in df.columns:
# if is_object_dtype(df[col]):
# try:
# df[col] = pd.to_datetime(df[col])
# except Exception:
# pass
# if is_datetime64_any_dtype(df[col]):
# df[col] = df[col].dt.tz_localize(None)
modification_container = st.container()
with modification_container:
cols = list(set(df.columns) -{'page','Extracted Text','Adapt-Mitig Label',
'Conditional Label', 'Indicator Label'})
cols.sort()
to_filter_columns = st.multiselect("Filter dataframe on", cols
)
# to_filter_columns = st.multiselect("Filter dataframe on", df.columns)
for column in to_filter_columns:
left, right = st.columns((1, 20))
left.write("β³")
# Treat columns with < 10 unique values as categorical
if is_categorical_dtype(df[column]):
user_cat_input = right.multiselect(
f"Values for {column}",
df[column].unique(),
default=list(df[column].unique()),
)
df = df[df[column].isin(user_cat_input)]
elif is_numeric_dtype(df[column]):
_min = float(df[column].min())
_max = float(df[column].max())
step = (_max - _min) / 100
user_num_input = right.slider(
f"Values for {column}",
_min,
_max,
(_min, _max),
step=step,
)
df = df[df[column].between(*user_num_input)]
elif is_list_like(df[column]) & (type(df[column][0]) == list):
list_vals = set(x for lst in df[column].tolist() for x in lst)
user_multi_input = right.multiselect(
f"Values for {column}",
list_vals,
default=list_vals,
)
df['check'] = df[column].apply(lambda x: any(i in x for i in user_multi_input))
df = df[df.check == True]
df.drop(columns = ['check'],inplace=True)
# df[df[column].between(*user_num_input)]
# elif is_datetime64_any_dtype(df[column]):
# user_date_input = right.date_input(
# f"Values for {column}",
# value=(
# df[column].min(),
# df[column].max(),
# ),
# )
# if len(user_date_input) == 2:
# user_date_input = tuple(map(pd.to_datetime, user_date_input))
# start_date, end_date = user_date_input
# df = df.loc[df[column].between(start_date, end_date)]
else:
user_text_input = right.text_input(
f"Substring or regex in {column}",
)
if user_text_input:
df = df[df[column].str.contains(user_text_input)]
df['keep'] = True
df = df[['keep','text','Policies_Plans Score',
'Sector Label','page']]
df = st.data_editor(
df,
column_config={
"keep": st.column_config.CheckboxColumn(
help="Select which rows to keep",
default=False,
)
},
disabled=list(set(df.columns) - {'keep'}),
hide_index=True,
)
st.session_state['policy_hits'] = df
return
def policy_display():
if 'key1' in st.session_state:
df = st.session_state.key1
st.caption(""" **{}** is splitted into **{}** paragraphs/text chunks."""\
.format(os.path.basename(st.session_state['filename']),
len(df)))
hits = df[df['Policies_Plans Label'] == 'Policy and Plans']
range_val = min(5,len(hits))
if range_val !=0:
count_action = len(hits)
hits.drop(columns=['Target Label','Target Score','Netzero Score',
'Netzero Label','GHG Label',
'GHG Score','Action Label','Policies_Plans Label',
'Action Score','Conditional Score'],inplace=True)
hits = hits.sort_values(by=['Policies_Plans Score'], ascending=False)
hits = hits.reset_index(drop=True)
st.write('----------------')
st.caption("Filter table to select rows to keep for Policies and Plans category")
hits = filter_for_tracs(hits)
convert_type = {'Conditional Label':'category',
}
hits = hits.astype(convert_type)
filter_dataframe_policy(hits)
# filtered_df = filtered_df[filtered_df.keep == True]
# st.write('Explore the data')
# AgGrid(hits)
with st.sidebar:
st.write('-------------')
df_xlsx = to_excel(df)
st.download_button(label='π₯ Download Result',
data=df_xlsx ,
file_name= os.path.splitext(os.path.basename(st.session_state['filename']))[0]+'.xlsx')
#count_netzero = sum(hits['Netzero Label'] == 'NETZERO')
#count_ghg = sum(hits['GHG Label'] == 'GHG')
#count_economy = sum([True if 'Economy-wide' in x else False
# for x in hits['Sector Label']])
# count_df = df['Target Label'].value_counts()
# count_df = count_df.rename('count')
# count_df = count_df.rename_axis('Target Label').reset_index()
# count_df['Label_def'] = count_df['Target Label'].apply(lambda x: _lab_dict[x])
# fig = px.bar(count_df, y="Label_def", x="count", orientation='h', height=200)
# c1, c2 = st.columns([1,1])
# with c1:
# st.write('**Target Paragraphs**: `{}`'.format(count_target))
# st.write('**NetZero Related Paragraphs**: `{}`'.format(count_netzero))
#
# # st.plotly_chart(fig,use_container_width= True)
#
# count_netzero = sum(hits['Netzero Label'] == 'NETZERO')
# count_ghg = sum(hits['GHG Label'] == 'LABEL_2')
# count_economy = sum([True if 'Economy-wide' in x else False
# for x in hits['Sector Label']])
# with c2:
# st.write('**GHG Related Paragraphs**: `{}`'.format(count_ghg))
# st.write('**Economy-wide Related Paragraphs**: `{}`'.format(count_economy))
# st.write('-------------------')
# hits = hits.sort_values(by=['Relevancy'], ascending=False)
# netzerohit = hits[hits['Netzero Label'] == 'NETZERO']
# if not netzerohit.empty:
# netzerohit = netzerohit.sort_values(by = ['Netzero Score'], ascending = False)
# # st.write('-------------------')
# st.markdown("###### Netzero paragraph ######")
# st.write('**Netzero paragraph** `page {}`: {}'.format(netzerohit.iloc[0]['page'],
# netzerohit.iloc[0]['text'].replace("\n", " ")))
# st.write("")
# else:
# st.info("π€ No Netzero paragraph found")
# st.write("**Result {}** `page {}` (Relevancy Score: {:.2f})'".format(i+1,hits.iloc[i]['page'],hits.iloc[i]['Relevancy'])")
# st.write('-------------------')
# st.write("")
# st.markdown("###### Top few Action Classified paragraph/text results from list of {} classified paragraphs ######".format(count_action))
# st.markdown("""<hr style="height:10px;border:none;color:#097969;background-color:#097969;" /> """, unsafe_allow_html=True)
# range_val = min(5,len(hits))
# for i in range(range_val):
# # the page number reflects the page that contains the main paragraph
# # according to split limit, the overlapping part can be on a separate page
# st.write('**Result {}** : `page {}`, `Sector: {}`,\
# `Indicators: {}`, `Adapt-Mitig :{}`'\
# .format(i+1,
# hits.iloc[i]['page'], hits.iloc[i]['Sector Label'],
# hits.iloc[i]['Indicator Label'],hits.iloc[i]['Adapt-Mitig Label']))
# st.write("\t Text: \t{}".format(hits.iloc[i]['text'].replace("\n", " ")))
# hits = hits.reset_index(drop =True)
# st.write('----------------')
# st.write('Explore the data')
# st.write(hits)
# df.drop(columns = ['Action_check'],inplace=True)
# df_xlsx = to_excel(df)
# with st.sidebar:
# st.write('-------------')
# st.download_button(label='π₯ Download Result',
# data=df_xlsx ,
# file_name= os.path.splitext(st.session_state['filename'])[0]+'.xlsx')
# else:
# st.info("π€ No Actions found")
# def policy_display():
# if 'key1' in st.session_state:
# df = st.session_state.key1
# df['Policy_check'] = df['Policy-Action Label'].apply(lambda x: True if 'Policies & Plans' in x else False)
# hits = df[df['Policy_check'] == True]
# # hits['GHG Label'] = hits['GHG Label'].apply(lambda i: _lab_dict[i])
# range_val = min(5,len(hits))
# if range_val !=0:
# count_policy = len(hits)
# #count_netzero = sum(hits['Netzero Label'] == 'NETZERO')
# #count_ghg = sum(hits['GHG Label'] == 'GHG')
# #count_economy = sum([True if 'Economy-wide' in x else False
# # for x in hits['Sector Label']])
# # count_df = df['Target Label'].value_counts()
# # count_df = count_df.rename('count')
# # count_df = count_df.rename_axis('Target Label').reset_index()
# # count_df['Label_def'] = count_df['Target Label'].apply(lambda x: _lab_dict[x])
# # fig = px.bar(count_df, y="Label_def", x="count", orientation='h', height=200)
# # c1, c2 = st.columns([1,1])
# # with c1:
# # st.write('**Target Paragraphs**: `{}`'.format(count_target))
# # st.write('**NetZero Related Paragraphs**: `{}`'.format(count_netzero))
# #
# # # st.plotly_chart(fig,use_container_width= True)
# #
# # count_netzero = sum(hits['Netzero Label'] == 'NETZERO')
# # count_ghg = sum(hits['GHG Label'] == 'LABEL_2')
# # count_economy = sum([True if 'Economy-wide' in x else False
# # for x in hits['Sector Label']])
# # with c2:
# # st.write('**GHG Related Paragraphs**: `{}`'.format(count_ghg))
# # st.write('**Economy-wide Related Paragraphs**: `{}`'.format(count_economy))
# # st.write('-------------------')
# # hits = hits.sort_values(by=['Relevancy'], ascending=False)
# # netzerohit = hits[hits['Netzero Label'] == 'NETZERO']
# # if not netzerohit.empty:
# # netzerohit = netzerohit.sort_values(by = ['Netzero Score'], ascending = False)
# # # st.write('-------------------')
# # st.markdown("###### Netzero paragraph ######")
# # st.write('**Netzero paragraph** `page {}`: {}'.format(netzerohit.iloc[0]['page'],
# # netzerohit.iloc[0]['text'].replace("\n", " ")))
# # st.write("")
# # else:
# # st.info("π€ No Netzero paragraph found")
# # st.write("**Result {}** `page {}` (Relevancy Score: {:.2f})'".format(i+1,hits.iloc[i]['page'],hits.iloc[i]['Relevancy'])")
# # st.write('-------------------')
# st.write("")
# st.markdown("###### Top few Policy/Plans Classified paragraph/text results from list of {} classified paragraphs ######".format(count_policy))
# st.markdown("""<hr style="height:10px;border:none;color:#097969;background-color:#097969;" /> """, unsafe_allow_html=True)
# range_val = min(5,len(hits))
# for i in range(range_val):
# # the page number reflects the page that contains the main paragraph
# # according to split limit, the overlapping part can be on a separate page
# st.write('**Result {}** : `page {}`, `Sector: {}`,\
# `Indicators: {}`, `Adapt-Mitig :{}`'\
# .format(i+1,
# hits.iloc[i]['page'], hits.iloc[i]['Sector Label'],
# hits.iloc[i]['Indicator Label'],hits.iloc[i]['Adapt-Mitig Label']))
# st.write("\t Text: \t{}".format(hits.iloc[i]['text'].replace("\n", " ")))
# hits = hits.reset_index(drop =True)
# st.write('----------------')
# st.write('Explore the data')
# st.write(hits)
# df.drop(columns = ['Policy_check'],inplace=True)
# df_xlsx = to_excel(df)
# with st.sidebar:
# st.write('-------------')
# st.download_button(label='π₯ Download Result',
# data=df_xlsx ,
# file_name= os.path.splitext(st.session_state['filename'])[0]+'.xlsx')
# else:
# st.info("π€ No Policy/Plans found") |