nlpblogs commited on
Commit
e1e9610
·
verified ·
1 Parent(s): b34ede8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +223 -0
app.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from cryptography.fernet import Fernet
3
+ import time
4
+ import pandas as pd
5
+ import io
6
+ from transformers import pipeline
7
+ from streamlit_extras.stylable_container import stylable_container
8
+ import json
9
+
10
+ import nltk
11
+
12
+ import plotly.express as px
13
+ from PyPDF2 import PdfReader
14
+ import docx
15
+ import zipfile
16
+
17
+ from gliner import GLiNER
18
+
19
+
20
+
21
+ st.subheader("Named Entity Recognition (NER)", divider="red")
22
+
23
+ # generate Fernet key
24
+ if 'fernet_key' not in st.session_state:
25
+ st.session_state.fernet_key = Fernet.generate_key()
26
+
27
+ key = st.session_state.fernet_key
28
+
29
+
30
+ # function for generating and validating fernet key
31
+ def generate_fernet_token(key, data):
32
+ fernet = Fernet(key)
33
+ token = fernet.encrypt(data.encode())
34
+ return token
35
+
36
+ def validate_fernet_token(key, token, ttl_seconds):
37
+
38
+ fernet = Fernet(key)
39
+ try:
40
+ decrypted_data = fernet.decrypt(token, ttl=ttl_seconds).decode()
41
+ return decrypted_data, None
42
+ except Exception as e:
43
+ return None, f"Expired token: {e}"
44
+
45
+
46
+ # sidebar
47
+ with st.sidebar:
48
+ with stylable_container(
49
+ key="test_button",
50
+ css_styles="""
51
+ button {
52
+ background-color: yellow;
53
+ border: 1px solid black;
54
+ padding: 5px;
55
+ color: black;
56
+ }
57
+ """,
58
+ ):
59
+ st.button("DEMO APP")
60
+
61
+
62
+ expander = st.expander("**Important notes on the Demo Named Entity Recognition (NER) App**")
63
+ expander.write('''
64
+
65
+ **Supported File Formats**
66
+ This app accepts files in .pdf and .docx formats.
67
+
68
+ **How to Use**
69
+ Upload your file first. Then, click the 'Results' button.
70
+
71
+ **Usage Limits**
72
+ You can request results up to 5 times.
73
+
74
+ **Subscription Management**
75
+ This demo app offers a one-day subscription, expiring after 24 hours. If you are interested in building your own Named Entity Recognition (NER) Web App, we invite you to explore our NLP Web App Store on our website. You can select your desired features, place your order, and we will deliver your custom app within five business days. If you wish to delete your Account with us, please contact us at [email protected]
76
+
77
+ **Authorization**
78
+ For security purposes, your authorization access expires hourly. To restore access, click the "Request Authorization" button.
79
+
80
+ **Customization**
81
+ To change the app's background color to white or black, click the three-dot menu on the right-hand side of your app, go to Settings and then Choose app theme, colors and fonts.
82
+
83
+ **File Handling and Errors**
84
+ The app may display an error message if your file is corrupt, or has other errors.
85
+
86
+
87
+ For any errors or inquiries, please contact us at [email protected]
88
+
89
+ ''')
90
+
91
+
92
+
93
+ # count attempts based on file upload
94
+ if 'file_upload_attempts' not in st.session_state:
95
+ st.session_state['file_upload_attempts'] = 0
96
+
97
+ max_attempts = 5
98
+
99
+ # upload file
100
+ upload_file = st.file_uploader("Upload your file. Accepted file formats include: .pdf, .docx", type=['pdf', 'docx'])
101
+ text = None
102
+ df = None
103
+
104
+ if upload_file is not None:
105
+
106
+ file_extension = upload_file.name.split('.')[-1].lower()
107
+ if file_extension == 'pdf':
108
+ try:
109
+ pdf_reader = PdfReader(upload_file)
110
+ text = ""
111
+ for page in pdf_reader.pages:
112
+ text += page.extract_text()
113
+ st.write(text)
114
+ except Exception as e:
115
+ st.error(f"An error occurred while reading PDF: {e}")
116
+ elif file_extension == 'docx':
117
+ try:
118
+ doc = docx.Document(upload_file)
119
+ text = "\n".join([para.text for para in doc.paragraphs])
120
+ st.write(text)
121
+ except Exception as e:
122
+ st.error(f"An error occurred while reading docx: {e}")
123
+ else:
124
+ st.warning("Unsupported file type.")
125
+
126
+ st.stop()
127
+
128
+
129
+
130
+
131
+ # generate and validate Fernet token for the current file
132
+ if 'fernet_token' not in st.session_state:
133
+ if text is not None:
134
+ st.session_state.fernet_token = generate_fernet_token(key, text)
135
+ else:
136
+ st.stop()
137
+
138
+ decrypted_data_streamlit, error_streamlit = validate_fernet_token(key, st.session_state.fernet_token, ttl_seconds=3600)
139
+
140
+ if error_streamlit:
141
+ if text is not None:
142
+ st.warning("Please press Request Authorization.")
143
+ if st.button("Request Authorization"):
144
+ st.session_state.fernet_token = generate_fernet_token(key, text)
145
+ st.success("Authorization granted")
146
+ decrypted_data_streamlit, error_streamlit = validate_fernet_token(key, st.session_state.fernet_token, ttl_seconds=3600)
147
+ if error_streamlit:
148
+ st.error(f"Your authorization has expired: {error_streamlit}")
149
+ st.stop()
150
+
151
+
152
+ st.divider()
153
+
154
+
155
+
156
+ #retrieve answer
157
+ if st.button("Results"):
158
+ if st.session_state['file_upload_attempts'] >= max_attempts:
159
+ st.error(f"You have requested results {max_attempts} times. You have reached your daily request limit.")
160
+ st.stop()
161
+ st.session_state['file_upload_attempts'] += 1
162
+ if error_streamlit:
163
+ st.warning("Please upload a file before retrieving the results.")
164
+ else:
165
+ with st.spinner('Wait for it...'):
166
+ time.sleep(2)
167
+ model = GLiNER.from_pretrained("xomad/gliner-model-merge-large-v1.0")
168
+ labels = ["person", "location", "country", "city", "organization", "time", "date", "product", "event name", "money", "affiliation", "ordinal value", "percent value", "position"]
169
+ entities = model.predict_entities(text, labels)
170
+ df = pd.DataFrame(entities)
171
+
172
+ properties = {"border": "2px solid gray", "color": "blue", "font-size": "16px"}
173
+ df_styled = df.style.set_properties(**properties)
174
+ st.dataframe(df_styled)
175
+ if df is not None:
176
+ value_counts1 = df['label'].value_counts()
177
+
178
+ df1 = pd.DataFrame(value_counts1)
179
+
180
+ final_df = df1.reset_index().rename(columns={"index": "label"})
181
+
182
+ col1, col2 = st.columns(2)
183
+ with col1:
184
+ fig1 = px.pie(final_df, values='count', names='label', hover_data=['count'], labels={'count': 'count'}, title='Percentage of predicted labels')
185
+ fig1.update_traces(textposition='inside', textinfo='percent+label')
186
+ st.plotly_chart(fig1)
187
+ with col2:
188
+ fig2 = px.bar(final_df, x="count", y="label", color="label", text_auto=True, title='Occurrences of predicted labels')
189
+ st.plotly_chart(fig2)
190
+
191
+ dfa = pd.DataFrame(
192
+ data={
193
+
194
+ 'text': ['entity extracted from file'], 'score': ['accuracy score'], 'label': ['label assigned to the extracted entity'],
195
+ 'start': ['index of the start of the corresponding entity'],
196
+ 'end': ['index of the end of the corresponding entity'],
197
+ })
198
+ buf = io.BytesIO()
199
+ with zipfile.ZipFile(buf, "w") as myzip:
200
+ myzip.writestr("Summary of the results.csv", df.to_csv(index=False))
201
+ myzip.writestr("Glossary of labels.csv", dfa.to_csv(index=False))
202
+
203
+ with stylable_container(
204
+ key="download_button",
205
+ css_styles="""button { background-color: yellow; border: 1px solid black; padding: 5px; color: black; }""",
206
+ ):
207
+ st.download_button(
208
+ label="Download zip file",
209
+ data=buf.getvalue(),
210
+ file_name="zip file.zip",
211
+ mime="application/zip",
212
+ )
213
+
214
+
215
+
216
+
217
+
218
+
219
+
220
+
221
+
222
+ st.divider()
223
+ st.write(f"Number of times you requested results: {st.session_state['file_upload_attempts']}/{max_attempts}")