Maria Tsilimos commited on
Commit
8939561
·
unverified ·
1 Parent(s): 56a55c8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +250 -0
app.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import streamlit as st
3
+ from bs4 import BeautifulSoup
4
+ import pandas as pd
5
+ from transformers import pipeline
6
+ import plotly.express as px
7
+ import time
8
+ import io
9
+ import os
10
+ from comet_ml import Experiment
11
+ import zipfile
12
+ import re
13
+ from streamlit_extras.stylable_container import stylable_container
14
+
15
+
16
+ st.set_page_config(layout="wide", page_title="Named Entity Recognition App")
17
+
18
+
19
+
20
+
21
+ COMET_API_KEY = os.environ.get("COMET_API_KEY")
22
+ COMET_WORKSPACE = os.environ.get("COMET_WORKSPACE")
23
+ COMET_PROJECT_NAME = os.environ.get("COMET_PROJECT_NAME")
24
+
25
+ comet_initialized = False
26
+ if COMET_API_KEY and COMET_WORKSPACE and COMET_PROJECT_NAME:
27
+ comet_initialized = True
28
+
29
+
30
+
31
+ st.subheader("4-Scandinavian Named Entity Recognition Web App", divider="rainbow")
32
+ st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
33
+
34
+ expander = st.expander("**Important notes on the 4-Scandinavian Named Entity Recognition Web App**")
35
+ expander.write('''
36
+ **Named Entities:** This 4-Scandinavian Named Entity Recognition Web App predicts four (4) labels (“PER: person”, “LOC: location”, “ORG: organization”, “MISC: miscellaneous”). Results are presented in an easy-to-read table, visualized in an interactive tree map, pie chart, and bar chart, and are available for download along with a Glossary of tags.
37
+
38
+ **How to Use:** Paste a URL, and then press Enter. If you type or paste text, just press Ctrl + Enter.
39
+
40
+ **Usage Limits:** You can request results up to 10 times.
41
+
42
+ **Customization:** 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.
43
+
44
+ **Technical issues:** If your connection times out, please refresh the page or reopen the app's URL.
45
+
46
+ For any errors or inquiries, please contact us at info@nlpblogs.com
47
+ ''')
48
+
49
+
50
+ with st.sidebar:
51
+ container = st.container(border=True)
52
+ container.write("**Named Entity Recognition (NER)** is the task of extracting and tagging entities in text data. Entities can be persons, organizations, locations, countries, products, events etc.")
53
+ st.subheader("Related NLP Web Apps", divider="rainbow")
54
+ st.link_button("8-Named Entity Recognition Web App", "https://nlpblogs.com/shop/named-entity-recognition-ner/8-named-entity-recognition-web-app/", type="primary")
55
+
56
+
57
+ if 'source_type_attempts' not in st.session_state:
58
+ st.session_state['source_type_attempts'] = 0
59
+ max_attempts = 10
60
+
61
+ def clear_url_input():
62
+
63
+ st.session_state.url = ""
64
+
65
+ def clear_text_input():
66
+
67
+ st.session_state.my_text_area = ""
68
+
69
+ url = st.text_input("Enter URL from the internet, and then press Enter:", key="url")
70
+ st.button("Clear URL", on_click=clear_url_input)
71
+
72
+ text = st.text_area("Type or paste your text below, and then press Ctrl + Enter", key='my_text_area')
73
+ st.button("Clear Text", on_click=clear_text_input)
74
+
75
+
76
+ source_type = None
77
+ input_content = None
78
+ text_to_process = None
79
+
80
+ if url:
81
+ source_type = 'url'
82
+ input_content = url
83
+ elif text:
84
+ source_type = 'text'
85
+ input_content = text
86
+
87
+ if source_type:
88
+
89
+ st.subheader("Results", divider = "rainbow")
90
+
91
+
92
+ if st.session_state['source_type_attempts'] >= max_attempts:
93
+ st.error(f"You have requested results {max_attempts} times. You have reached your daily request limit.")
94
+ st.stop()
95
+
96
+ st.session_state['source_type_attempts'] += 1
97
+
98
+
99
+ @st.cache_resource
100
+ def load_ner_model():
101
+
102
+ return pipeline("token-classification", model="saattrupdan/nbailab-base-ner-scandi", aggregation_strategy="max")
103
+
104
+ model = load_ner_model()
105
+ experiment = None
106
+
107
+ try:
108
+ if source_type == 'url':
109
+ if not url.startswith(("http://", "https://")):
110
+ st.error("Please enter a valid URL starting with 'http://' or 'https://'.")
111
+ else:
112
+ with st.spinner(f"Fetching and parsing content from **{url}**...", show_time=True):
113
+ f = requests.get(url, timeout=10)
114
+ f.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
115
+ soup = BeautifulSoup(f.text, 'html.parser')
116
+ text_to_process = soup.get_text(separator=' ', strip=True)
117
+ st.divider()
118
+ st.write("**Input text content**")
119
+ st.write(text_to_process[:500] + "..." if len(text_to_process) > 500 else text_to_process)
120
+
121
+
122
+
123
+ elif source_type == 'text':
124
+ text_to_process = text
125
+ st.divider()
126
+ st.write("**Input text content**")
127
+
128
+ st.write(text_to_process[:500] + "..." if len(text_to_process) > 500 else text_to_process)
129
+
130
+ if text_to_process and len(text_to_process.strip()) > 0:
131
+ with st.spinner("Analyzing text...", show_time=True):
132
+ entities = model(text_to_process)
133
+ data = []
134
+ for entity in entities:
135
+ data.append({
136
+ 'word': entity['word'],
137
+ 'entity_group': entity['entity_group'],
138
+ 'score': entity['score'],
139
+ 'start': entity['start'], # Include start and end for download
140
+ 'end': entity['end']
141
+ })
142
+ df = pd.DataFrame(data)
143
+
144
+
145
+ pattern = r'[^\w\s]'
146
+ df['word'] = df['word'].replace(pattern, '', regex=True)
147
+
148
+ df = df.replace('', 'Unknown')
149
+ st.dataframe(df)
150
+
151
+
152
+ if comet_initialized:
153
+ experiment = Experiment(
154
+ api_key=COMET_API_KEY,
155
+ workspace=COMET_WORKSPACE,
156
+ project_name=COMET_PROJECT_NAME,
157
+ )
158
+ experiment.log_parameter("input_source_type", source_type)
159
+ experiment.log_parameter("input_content_length", len(input_content))
160
+ experiment.log_table("predicted_entities", df)
161
+
162
+ with st.expander("See Glossary of tags"):
163
+ st.write('''
164
+ '**word**': ['entity extracted from your text data']
165
+
166
+ '**score**': ['accuracy score; how accurately a tag has been assigned to a given entity']
167
+
168
+ '**entity_group**': ['label (tag) assigned to a given extracted entity']
169
+
170
+ '**start**': ['index of the start of the corresponding entity']
171
+
172
+ '**end**': ['index of the end of the corresponding entity']
173
+ ''')
174
+
175
+
176
+ if not df.empty:
177
+
178
+ st.markdown("---")
179
+ st.subheader("Treemap", divider="rainbow")
180
+ fig = px.treemap(df, path=[px.Constant("all"), 'entity_group', 'word'],
181
+ values='score', color='entity_group',
182
+ )
183
+ fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
184
+ st.plotly_chart(fig, use_container_width=True)
185
+ if comet_initialized and experiment:
186
+ experiment.log_figure(figure=fig, figure_name="entity_treemap")
187
+
188
+
189
+
190
+ value_counts = df['entity_group'].value_counts().reset_index()
191
+ value_counts.columns = ['entity_group', 'count']
192
+
193
+ col1, col2 = st.columns(2)
194
+ with col1:
195
+ st.subheader("Pie Chart", divider="rainbow")
196
+ fig1 = px.pie(value_counts, values='count', names='entity_group',
197
+ hover_data=['count'], labels={'count': 'count'},
198
+ title='Percentage of Predicted Labels')
199
+ fig1.update_traces(textposition='inside', textinfo='percent+label')
200
+ st.plotly_chart(fig1, use_container_width=True)
201
+ if comet_initialized and experiment: # Check if experiment is initialized
202
+ experiment.log_figure(figure=fig1, figure_name="label_pie_chart")
203
+
204
+ with col2:
205
+ st.subheader("Bar Chart", divider="rainbow")
206
+ fig2 = px.bar(value_counts, x="count", y="entity_group", color="entity_group",
207
+ text_auto=True, title='Occurrences of Predicted Labels')
208
+ st.plotly_chart(fig2, use_container_width=True)
209
+ if comet_initialized and experiment: # Check if experiment is initialized
210
+ experiment.log_figure(figure=fig2, figure_name="label_bar_chart")
211
+ else:
212
+ st.warning("No entities were extracted from the provided text.")
213
+
214
+
215
+
216
+ dfa = pd.DataFrame(
217
+ data={
218
+ 'word': ['entity extracted from your text data'],
219
+ 'score': ['accuracy score; how accurately a tag has been assigned to a given entity'],
220
+ 'entity_group': ['label (tag) assigned to a given extracted entity'],
221
+ 'start': ['index of the start of the corresponding entity'],
222
+ 'end': ['index of the end of the corresponding entity'],
223
+ }
224
+ )
225
+ buf = io.BytesIO()
226
+ with zipfile.ZipFile(buf, "w") as myzip:
227
+ if not df.empty:
228
+ myzip.writestr("Summary_of_results.csv", df.to_csv(index=False))
229
+ myzip.writestr("Glossary_of_tags.csv", dfa.to_csv(index=False))
230
+
231
+ with stylable_container(
232
+ key="download_button",
233
+ css_styles="""button { background-color: yellow; border: 1px solid black; padding: 5px; color: black; }""",
234
+ ):
235
+ st.download_button(
236
+ label="Download zip file",
237
+ data=buf.getvalue(),
238
+ file_name="nlpblogs_ner_results.zip",
239
+ mime="application/zip",)
240
+
241
+
242
+ if comet_initialized and experiment: # Ensure experiment exists before ending
243
+ experiment.end()
244
+ else:
245
+ st.warning("No meaningful text found to process. Please enter a URL or text.")
246
+
247
+ except requests.exceptions.RequestException as e:
248
+ st.error(f"Error fetching the URL: {e}. Please check the URL and your internet connection.")
249
+
250
+ st.write(f"Number of times you requested results: **{st.session_state['source_type_attempts']}/{max_attempts}**")