Delete appStore/vulnerability_analysis.py
Browse files
appStore/vulnerability_analysis.py
DELETED
@@ -1,168 +0,0 @@
|
|
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 st_aggrid.shared import ColumnsAutoSizeMode
|
13 |
-
from utils.vulnerability_classifier import vulnerability_classification
|
14 |
-
from utils.vulnerability_classifier import runPreprocessingPipeline, load_Classifier
|
15 |
-
import logging
|
16 |
-
logger = logging.getLogger(__name__)
|
17 |
-
from utils.checkconfig import getconfig
|
18 |
-
|
19 |
-
|
20 |
-
# Declare all the necessary variables
|
21 |
-
config = getconfig('paramconfig.cfg')
|
22 |
-
model_name = config.get('vulnerability','MODEL')
|
23 |
-
split_by = config.get('vulnerability','SPLIT_BY')
|
24 |
-
split_length = int(config.get('vulnerability','SPLIT_LENGTH'))
|
25 |
-
split_overlap = int(config.get('vulnerability','SPLIT_OVERLAP'))
|
26 |
-
remove_punc = bool(int(config.get('vulnerability','REMOVE_PUNC')))
|
27 |
-
split_respect_sentence_boundary = bool(int(config.get('vulnerability','RESPECT_SENTENCE_BOUNDARY')))
|
28 |
-
threshold = float(config.get('vulnerability','THRESHOLD'))
|
29 |
-
top_n = int(config.get('vulnerability','TOP_KEY'))
|
30 |
-
|
31 |
-
|
32 |
-
def app():
|
33 |
-
|
34 |
-
#### APP INFO #####
|
35 |
-
with st.container():
|
36 |
-
st.markdown("<h1 style='text-align: center; color: black;'> Vulnerability Classification </h1>", unsafe_allow_html=True)
|
37 |
-
st.write(' ')
|
38 |
-
st.write(' ')
|
39 |
-
|
40 |
-
with st.expander("ℹ️ - About this app", expanded=False):
|
41 |
-
|
42 |
-
st.write(
|
43 |
-
"""
|
44 |
-
The *Vulnerability Indicator* app is an easy-to-use interface built \
|
45 |
-
in Streamlit for analyzing policy documents with respect to SDG \
|
46 |
-
Classification for the paragraphs/texts in the document and \
|
47 |
-
extracting the keyphrase per SDG label - developed by GIZ Data \
|
48 |
-
and the Sustainable Development Solution Network. \n
|
49 |
-
""")
|
50 |
-
st.write("""**Document Processing:** The Uploaded/Selected document is \
|
51 |
-
automatically cleaned and split into paragraphs with a maximum \
|
52 |
-
length of 120 words using a Haystack preprocessing pipeline. The \
|
53 |
-
length of 120 is an empirical value which should reflect the length \
|
54 |
-
of a “context” and should limit the paragraph length deviation. \
|
55 |
-
However, since we want to respect the sentence boundary the limit \
|
56 |
-
can breach and hence this limit of 120 is tentative. \n
|
57 |
-
""")
|
58 |
-
st.write("""**Vulnerability cLassification:** The application assigns paragraphs \
|
59 |
-
to 18 different vulnerable groups in the climate context.\
|
60 |
-
Each paragraph is assigned to one vulnerable group only. Again, the results are \
|
61 |
-
displayed in a summary table including the vulnerability label, a \
|
62 |
-
relevancy score highlighted through a green color shading, and the \
|
63 |
-
respective text of the analyzed paragraph. Additionally, a pie \
|
64 |
-
chart with a blue color shading is displayed which illustrates the \
|
65 |
-
three most prominent groups mentioned in the document. Training data has been \
|
66 |
-
collected manually from different policy documents and been assigned to the groups. \
|
67 |
-
The summary table only displays \
|
68 |
-
paragraphs with a calculated relevancy score above 85%. \n""")
|
69 |
-
|
70 |
-
st.write("")
|
71 |
-
st.write("")
|
72 |
-
st.markdown("Some runtime metrics tested with cpu: Intel(R) Xeon(R) CPU @ 2.20GHz, memory: 13GB")
|
73 |
-
col1,col2,col3,col4 = st.columns([2,2,4,4])
|
74 |
-
with col1:
|
75 |
-
st.caption("Loading Time Classifier")
|
76 |
-
# st.markdown('<div style="text-align: center;">12 sec</div>', unsafe_allow_html=True)
|
77 |
-
st.write("12 sec")
|
78 |
-
with col2:
|
79 |
-
st.caption("OCR File processing")
|
80 |
-
# st.markdown('<div style="text-align: center;">50 sec</div>', unsafe_allow_html=True)
|
81 |
-
st.write("50 sec")
|
82 |
-
with col3:
|
83 |
-
st.caption("SDG Classification of 200 paragraphs(~ 35 pages)")
|
84 |
-
# st.markdown('<div style="text-align: center;">120 sec</div>', unsafe_allow_html=True)
|
85 |
-
st.write("120 sec")
|
86 |
-
with col4:
|
87 |
-
st.caption("Keyword extraction for 200 paragraphs(~ 35 pages)")
|
88 |
-
# st.markdown('<div style="text-align: center;">3 sec</div>', unsafe_allow_html=True)
|
89 |
-
st.write("3 sec")
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
### Main app code ###
|
95 |
-
with st.container():
|
96 |
-
if st.button("RUN Vulnerability Analysis"):
|
97 |
-
|
98 |
-
if 'filepath' in st.session_state:
|
99 |
-
file_name = st.session_state['filename']
|
100 |
-
file_path = st.session_state['filepath']
|
101 |
-
st.write(file_name)
|
102 |
-
st.write(file_path)
|
103 |
-
classifier = load_Classifier(classifier_name=model_name)
|
104 |
-
st.session_state['vulnerability_classifier'] = classifier
|
105 |
-
all_documents = runPreprocessingPipeline(file_name= file_name,
|
106 |
-
file_path= file_path, split_by= split_by,
|
107 |
-
split_length= split_length,
|
108 |
-
split_respect_sentence_boundary= split_respect_sentence_boundary,
|
109 |
-
split_overlap= split_overlap, remove_punc= remove_punc)
|
110 |
-
|
111 |
-
if len(all_documents['documents']) > 100:
|
112 |
-
warning_msg = ": This might take sometime, please sit back and relax."
|
113 |
-
else:
|
114 |
-
warning_msg = ""
|
115 |
-
|
116 |
-
with st.spinner("Running Classification{}".format(warning_msg)):
|
117 |
-
|
118 |
-
df, x = vulnerability_classification(haystack_doc=all_documents['documents'],
|
119 |
-
threshold= threshold)
|
120 |
-
df = df.drop(['Relevancy'], axis = 1)
|
121 |
-
vulnerability_labels = x.vulnerability.unique()
|
122 |
-
textrank_keyword_list = []
|
123 |
-
for label in sdg_labels:
|
124 |
-
vulnerability_data = " ".join(df[df.vulnerability == label].text.to_list())
|
125 |
-
textranklist_ = textrank(textdata=sdgdata, words= top_n)
|
126 |
-
if len(textranklist_) > 0:
|
127 |
-
textrank_keyword_list.append({'Vulnerability':label, 'TextRank Keywords':",".join(textranklist_)})
|
128 |
-
textrank_keywords_df = pd.DataFrame(textrank_keyword_list)
|
129 |
-
|
130 |
-
|
131 |
-
plt.rcParams['font.size'] = 25
|
132 |
-
colors = plt.get_cmap('Blues')(np.linspace(0.2, 0.7, len(x)))
|
133 |
-
# plot
|
134 |
-
fig, ax = plt.subplots()
|
135 |
-
ax.pie(x['count'], colors=colors, radius=2, center=(4, 4),
|
136 |
-
wedgeprops={"linewidth": 1, "edgecolor": "white"},
|
137 |
-
textprops={'fontsize': 14},
|
138 |
-
frame=False,labels =list(x.SDG_Num),
|
139 |
-
labeldistance=1.2)
|
140 |
-
# fig.savefig('temp.png', bbox_inches='tight',dpi= 100)
|
141 |
-
|
142 |
-
|
143 |
-
st.markdown("#### Anything related to Vulnerabilities? ####")
|
144 |
-
|
145 |
-
c4, c5, c6 = st.columns([1,2,2])
|
146 |
-
|
147 |
-
with c5:
|
148 |
-
st.pyplot(fig)
|
149 |
-
with c6:
|
150 |
-
labeldf = x['SDG_name'].values.tolist()
|
151 |
-
labeldf = "<br>".join(labeldf)
|
152 |
-
st.markdown(labeldf, unsafe_allow_html=True)
|
153 |
-
st.write("")
|
154 |
-
st.markdown("###### What keywords are present under vulnerability classified text? ######")
|
155 |
-
|
156 |
-
AgGrid(textrank_keywords_df, reload_data = False,
|
157 |
-
update_mode="value_changed",
|
158 |
-
columns_auto_size_mode = ColumnsAutoSizeMode.FIT_CONTENTS)
|
159 |
-
st.write("")
|
160 |
-
st.markdown("###### Top few vulnerability Classified paragraph/text results ######")
|
161 |
-
|
162 |
-
AgGrid(df, reload_data = False, update_mode="value_changed",
|
163 |
-
columns_auto_size_mode = ColumnsAutoSizeMode.FIT_CONTENTS)
|
164 |
-
else:
|
165 |
-
st.info("🤔 No document found, please try to upload it at the sidebar!")
|
166 |
-
logging.warning("Terminated as no document provided")
|
167 |
-
|
168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|