abdullahmubeen10 commited on
Commit
2aa8b07
·
verified ·
1 Parent(s): 8fd5e0a

Update pages/Named Entity Recognition.py

Browse files
Files changed (1) hide show
  1. pages/Named Entity Recognition.py +88 -208
pages/Named Entity Recognition.py CHANGED
@@ -1,27 +1,43 @@
1
  import streamlit as st
 
2
  import os
3
- import json
4
  import pandas as pd
5
- import numpy as np
6
- import random
7
- import base64
8
- import ast
9
- import sparknlp
10
- import pyspark.sql.functions as F
11
- from pyspark.ml import Pipeline
12
- from pyspark.sql import SparkSession
13
- from sparknlp.annotator import *
14
  from sparknlp.base import *
 
 
15
  from sparknlp.pretrained import PretrainedPipeline
16
- from pyspark.sql.types import StringType, IntegerType
17
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  @st.cache_resource
19
  def init_spark():
20
- spark = sparknlp.start()
21
- return spark
22
 
23
  @st.cache_resource
24
  def create_pipeline(model):
 
25
  documentAssembler = DocumentAssembler() \
26
  .setInputCol('text') \
27
  .setOutputCol('document')
@@ -34,13 +50,12 @@ def create_pipeline(model):
34
  embeddings = WordEmbeddingsModel.pretrained('glove_100d') \
35
  .setInputCols(["document", 'token']) \
36
  .setOutputCol("embeddings")
37
-
38
  elif model == "ner_dl_bert":
39
- embeddings = BertEmbeddings.pretrained(name='bert_base_cased', lang='en') \
40
  .setInputCols(['document', 'token']) \
41
  .setOutputCol('embeddings')
42
 
43
- ner_model = NerDLModel.pretrained(model, abbreviation_map[langauge].lower()) \
44
  .setInputCols(['document', 'token', 'embeddings']) \
45
  .setOutputCol('ner')
46
 
@@ -63,100 +78,42 @@ def fit_data(pipeline, data):
63
  pipeline_model = pipeline.fit(empty_df)
64
  model = LightPipeline(pipeline_model)
65
  result = model.fullAnnotate(data)
66
-
67
  return result
68
 
69
- def get_color(l):
70
- if str(l).lower() in LABEL_COLORS.keys():
71
- return LABEL_COLORS[l.lower()]
72
- else:
73
- r = lambda: random.randint(0,200)
74
- return '#%02X%02X%02X' % (r(), r(), r())
75
-
76
- def simplified_display_annotations(text, annotations, labels):
77
- def get_html_for_span(span_text, background_color=None, entity_name=None):
78
- if background_color:
79
- style = f'style="background-color: {background_color};"'
80
- else:
81
- style = ""
82
- if entity_name:
83
- return f'<span {style}>{span_text} <span>({entity_name})</span></span>'
84
- return f'<span {style}>{span_text}</span>'
85
-
86
- label_color = {label: get_color(label) for label in labels}
87
- html_output, pos = "", 0
88
-
89
- for chunk in annotations:
90
- begin, end = chunk[1], chunk[2]
91
- entity_type = chunk[4]['entity']
92
-
93
- if pos < begin:
94
- html_output += get_html_for_span(text[pos:begin])
95
- html_output += get_html_for_span(chunk[3], label_color.get(entity_type), entity_type if entity_type in label_color else None)
96
- pos = end + 1
97
-
98
- if pos < len(text):
99
- html_output += get_html_for_span(text[pos:])
100
-
101
- return html_output
102
-
103
- def parse_text_to_complex_list(text):
104
- text = text.strip()[11:-1]
105
- def parse_inner_structure(s):
106
- stack = []
107
- result = ''
108
- for char in s:
109
- if char in ['{', '[']:
110
- stack.append(char)
111
- elif char in ['}', ']']:
112
- stack.pop()
113
- if not stack:
114
- return result + char
115
- result += char
116
- return result
117
-
118
- elements = []
119
- temp = ''
120
- stack = []
121
- for char in text:
122
- if char in ['{', '[']:
123
- stack.append(char)
124
- elif char in [']', '}']:
125
- stack.pop()
126
- elif char == ',' and not stack:
127
- elements.append(temp.strip())
128
- temp = ''
129
- continue
130
- temp += char
131
- elements.append(temp.strip())
132
-
133
- # Convert elements to the appropriate type
134
- parsed_elements = []
135
- for element in elements:
136
- element = element.strip()
137
- if element.isdigit():
138
- parsed_elements.append(int(element))
139
- elif element.startswith(('\'', '"')):
140
- parsed_elements.append(element.strip('\'"'))
141
- elif element.startswith(('{', '[')):
142
- parsed_elements.append(ast.literal_eval(element))
143
- else:
144
- parsed_elements.append(element)
145
-
146
- return parsed_elements
147
-
148
- language_info = {
149
- "EN": {
150
- "title": "Recognize entities in text",
151
- "description": "Recognize Persons, Locations, Organizations and Misc entities using out of the box pretrained Deep Learning models based on BERT (ner_dl_bert) word embeddings.",
152
- "model_name": ["ner_dl_bert", "ner_dl"]
153
- }
154
- }
155
-
156
- abbreviation_map = {"English": "EN"}
157
 
158
- examples = {
159
- "English" : [
160
  "William Henry Gates III (born October 28, 1955) is an American business magnate, software developer, investor, and philanthropist. He is best known as the co-founder of Microsoft Corporation. During his career at Microsoft, Gates held the positions of chairman, chief executive officer (CEO), president and chief software architect, while also being the largest individual shareholder until May 2014. He is one of the best-known entrepreneurs and pioneers of the microcomputer revolution of the 1970s and 1980s. Born and raised in Seattle, Washington, Gates co-founded Microsoft with childhood friend Paul Allen in 1975, in Albuquerque, New Mexico; it went on to become the world's largest personal computer software company. Gates led the company as chairman and CEO until stepping down as CEO in January 2000, but he remained chairman and became chief software architect. During the late 1990s, Gates had been criticized for his business tactics, which have been considered anti-competitive. This opinion has been upheld by numerous court rulings. In June 2006, Gates announced that he would be transitioning to a part-time role at Microsoft and full-time work at the Bill & Melinda Gates Foundation, the private charitable foundation that he and his wife, Melinda Gates, established in 2000.[9] He gradually transferred his duties to Ray Ozzie and Craig Mundie. He stepped down as chairman of Microsoft in February 2014 and assumed a new post as technology adviser to support the newly appointed CEO Satya Nadella.",
161
  "The Mona Lisa is a 16th century oil painting created by Leonardo. It's held at the Louvre in Paris.",
162
  "When Sebastian Thrun started working on self-driving cars at Google in 2007, few people outside of the company took him seriously. “I can tell you very senior CEOs of major American car companies would shake my hand and turn away because I wasn’t worth talking to,” said Thrun, now the co-founder and CEO of online higher education startup Udacity, in an interview with Recode earlier this week.",
@@ -167,112 +124,35 @@ examples = {
167
  "Steven Paul Jobs was an American business magnate, industrial designer, investor, and media proprietor. He was the chairman, chief executive officer (CEO), and co-founder of Apple Inc., the chairman and majority shareholder of Pixar, a member of The Walt Disney Company's board of directors following its acquisition of Pixar, and the founder, chairman, and CEO of NeXT. Jobs is widely recognized as a pioneer of the personal computer revolution of the 1970s and 1980s, along with Apple co-founder Steve Wozniak. Jobs was born in San Francisco, California, and put up for adoption. He was raised in the San Francisco Bay Area. He attended Reed College in 1972 before dropping out that same year, and traveled through India in 1974 seeking enlightenment and studying Zen Buddhism.",
168
  "Titanic is a 1997 American epic romance and disaster film directed, written, co-produced, and co-edited by James Cameron. Incorporating both historical and fictionalized aspects, it is based on accounts of the sinking of the RMS Titanic, and stars Leonardo DiCaprio and Kate Winslet as members of different social classes who fall in love aboard the ship during its ill-fated maiden voyage.",
169
  "Other than being the king of the north, John Snow is a an english physician and a leader in the development of anaesthesia and medical hygiene. He is considered for being the first one using data to cure cholera outbreak in 1834."
170
- ]
171
- }
172
 
173
- ner_mapping = {
174
- 'PERSON': 'People, including fictional.',
175
- 'PER': 'People, including fictional.',
176
- 'HUM': 'Humans',
177
- 'IND': 'Individuals',
178
- 'NORP': 'Nationalities or religious or political groups.',
179
- 'FAC': 'Buildings, airports, highways, bridges, etc.',
180
- 'FACILITY': 'Buildings, airports, highways, bridges, etc.',
181
- 'STRUCTURE': 'Structures like buildings, bridges, etc.',
182
- 'ORG': 'Companies, agencies, institutions, etc.',
183
- 'ORGANIZATION': 'Companies, agencies, institutions, etc.',
184
- 'INSTITUTION': 'Educational, governmental, and other organizations.',
185
- 'LOC': 'Countries, cities, states, mountain ranges, bodies of water.',
186
- 'LOCATION': 'Countries, cities, states, mountain ranges, bodies of water.',
187
- 'PLACE': 'Specific locations.',
188
- 'GPE': 'Geopolitical entities, such as countries, cities, states.',
189
- 'PRODUCT': 'Objects, vehicles, foods, etc. (Not services.)',
190
- 'PROD': 'Product',
191
- 'GOOD': 'Goods and products.',
192
- 'EVENT': 'Named hurricanes, battles, wars, sports events, etc.',
193
- 'OCCURRENCE': 'Occurrences and events.',
194
- 'WORK_OF_ART': 'Titles of books, songs, etc.',
195
- 'ART': 'Works of art, including books, paintings, songs, etc.',
196
- 'LAW': 'Named documents made into laws.',
197
- 'LEGISLATION': 'Laws and legal documents.',
198
- 'LANGUAGE': 'Any named language.',
199
- 'DATE': 'Absolute or relative dates or periods.',
200
- 'TIME': 'Times smaller than a day.',
201
- 'PERCENT': 'Percentage, including ”%“.',
202
- 'MONEY': 'Monetary values, including unit.',
203
- 'CURRENCY': 'Monetary values, including unit.',
204
- 'QUANTITY': 'Measurements, as of weight or distance.',
205
- 'MEASURE': 'Measurements and quantities.',
206
- 'ORDINAL': '“first”, “second”, etc.',
207
- 'CARDINAL': 'Numerals that do not fall under another type.',
208
- 'NUMBER': 'Numbers and numerals.',
209
- 'MISC': 'Miscellaneous entities, e.g. events, nationalities, products or works of art.',
210
- 'MISCELLANEOUS': 'Miscellaneous entities.',
211
- 'ENT': 'Entity (generic label).',
212
- 'GPE_LOC': 'Geopolitical Entity',
213
- 'ANIMAL': 'Animals, including fictional.',
214
- 'PLANT': 'Plants, including fictional.',
215
- 'SUBSTANCE': 'Substances and materials.',
216
- 'DISEASE': 'Diseases and medical conditions.',
217
- 'SYMPTOM': 'Symptoms and medical signs.',
218
- 'MEDICAL': 'Medical terms and conditions.',
219
- 'FOOD': 'Food items.',
220
- 'DRINK': 'Drinks and beverages.',
221
- 'VEHICLE': 'Types of vehicles.',
222
- 'WEAPON': 'Weapons and armaments.',
223
- 'TECHNOLOGY': 'Technological terms and devices.',
224
- 'GAME': 'Games and sports.',
225
- 'HOBBY': 'Hobbies and recreational activities.',
226
- 'RELIGION': 'Religious terms and entities.',
227
- 'MYTH': 'Mythological entities.',
228
- 'ASTRONOMICAL': 'Astronomical entities (e.g., planets, stars).',
229
- 'NATURAL_PHENOMENON': 'Natural phenomena (e.g., earthquakes, storms).',
230
- 'CELESTIAL_BODY': 'Celestial bodies (e.g., stars, planets).',
231
- 'DRV': 'Driver'
232
- }
233
 
234
- langauge = 'English'
235
- model_list = language_info[abbreviation_map[langauge]]["model_name"]
236
- model = st.sidebar.selectbox("Choose the pretrained model", model_list, help="For more info about the models visit: https://sparknlp.org/models")
237
- st.title(language_info[abbreviation_map[langauge]]["title"])
238
 
239
- link= """<a href="https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/NER_EN.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" style="zoom: 1.3" alt="Open In Colab"/></a>"""
240
- st.sidebar.markdown('Reference notebook:')
241
- st.sidebar.markdown(link, unsafe_allow_html=True)
242
-
243
- st.subheader(language_info[abbreviation_map[langauge]]["description"])
244
- selected_text = st.selectbox("Select an example", examples[langauge])
245
- custom_input = st.text_input("Try it for yourself!")
246
-
247
- if custom_input:
248
- selected_text = custom_input
249
- elif selected_text:
250
- selected_text = selected_text
251
-
252
- st.subheader('Selected Text')
253
- st.write(selected_text)
254
 
 
255
  spark = init_spark()
256
- Pipeline = create_pipeline(model)
257
- output = fit_data(Pipeline, selected_text)
258
 
259
- entities = [{'text': ent.result, 'start': ent.begin, 'end': ent.end, 'label': ent.metadata['entity'], 'Explain NER Labels' : ner_mapping[ent.metadata['entity']]} for ent in output[0]['ner_chunk']]
 
260
 
261
- LABEL_COLORS = {'per':'#0C8888', 'pers':'#0C8888','person':'#0C8888',
262
- 'org':'#FF33C1',
263
- 'misc': '#3196D4', 'mis': '#3196D4',
264
- 'loc':'#5B00A3', 'location':'#5B00A3'}
265
-
266
- HTML_WRAPPER = """<div class="scroll entities" style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem; white-space:pre-wrap">{}</div>"""
267
-
268
- chunk_list = []
269
- for n in output[0]['ner_chunk']:
270
- parsed_list = parse_text_to_complex_list(str(n))
271
- chunk_list.append(parsed_list)
272
 
273
- st.subheader("Text annotated with identified Named Entities")
274
 
275
- labels = [n.metadata['entity'] for n in output[0]['ner_chunk']]
276
- ner = simplified_display_annotations(selected_text, chunk_list, labels)
277
- st.markdown(HTML_WRAPPER.format(ner), unsafe_allow_html=True)
278
- st.write(pd.DataFrame(entities))
 
1
  import streamlit as st
2
+ import sparknlp
3
  import os
 
4
  import pandas as pd
5
+
 
 
 
 
 
 
 
 
6
  from sparknlp.base import *
7
+ from sparknlp.annotator import *
8
+ from pyspark.ml import Pipeline
9
  from sparknlp.pretrained import PretrainedPipeline
10
+ from annotated_text import annotated_text
11
+
12
+ # Page configuration
13
+ st.set_page_config(
14
+ layout="wide",
15
+ page_title="Spark NLP Demos App",
16
+ initial_sidebar_state="auto"
17
+ )
18
+
19
+ # CSS for styling
20
+ st.markdown("""
21
+ <style>
22
+ .main-title {
23
+ font-size: 36px;
24
+ color: #4A90E2;
25
+ font-weight: bold;
26
+ text-align: center;
27
+ }
28
+ .section p, .section ul {
29
+ color: #666666;
30
+ }
31
+ </style>
32
+ """, unsafe_allow_html=True)
33
+
34
  @st.cache_resource
35
  def init_spark():
36
+ return sparknlp.start()
 
37
 
38
  @st.cache_resource
39
  def create_pipeline(model):
40
+
41
  documentAssembler = DocumentAssembler() \
42
  .setInputCol('text') \
43
  .setOutputCol('document')
 
50
  embeddings = WordEmbeddingsModel.pretrained('glove_100d') \
51
  .setInputCols(["document", 'token']) \
52
  .setOutputCol("embeddings")
 
53
  elif model == "ner_dl_bert":
54
+ embeddings = BertEmbeddings.pretrained('bert_base_cased','en') \
55
  .setInputCols(['document', 'token']) \
56
  .setOutputCol('embeddings')
57
 
58
+ ner_model = NerDLModel.pretrained(model, 'en') \
59
  .setInputCols(['document', 'token', 'embeddings']) \
60
  .setOutputCol('ner')
61
 
 
78
  pipeline_model = pipeline.fit(empty_df)
79
  model = LightPipeline(pipeline_model)
80
  result = model.fullAnnotate(data)
 
81
  return result
82
 
83
+ def annotate(data):
84
+ document, chunks, labels = data["Document"], data["NER Chunk"], data["NER Label"]
85
+ annotated_words = []
86
+ for chunk, label in zip(chunks, labels):
87
+ parts = document.split(chunk, 1)
88
+ if parts[0]:
89
+ annotated_words.append(parts[0])
90
+ annotated_words.append((chunk, label))
91
+ document = parts[1]
92
+ if document:
93
+ annotated_words.append(document)
94
+ annotated_text(*annotated_words)
95
+
96
+ # Set up the page layout
97
+ st.markdown('<div class="main-title">State-of-the-Art Named Entity Recognition with Spark NLP</div>', unsafe_allow_html=True)
98
+
99
+ # Sidebar content
100
+ model = st.sidebar.selectbox(
101
+ "Choose the pretrained model",
102
+ ["ner_dl", "ner_dl_bert"],
103
+ help="For more info about the models visit: https://sparknlp.org/models"
104
+ )
105
+
106
+ # Reference notebook link in sidebar
107
+ link = """
108
+ <a href="https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/NER_EN.ipynb">
109
+ <img src="https://colab.research.google.com/assets/colab-badge.svg" style="zoom: 1.3" alt="Open In Colab"/>
110
+ </a>
111
+ """
112
+ st.sidebar.markdown('Reference notebook:')
113
+ st.sidebar.markdown(link, unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
+ # Load examples
116
+ examples = [
117
  "William Henry Gates III (born October 28, 1955) is an American business magnate, software developer, investor, and philanthropist. He is best known as the co-founder of Microsoft Corporation. During his career at Microsoft, Gates held the positions of chairman, chief executive officer (CEO), president and chief software architect, while also being the largest individual shareholder until May 2014. He is one of the best-known entrepreneurs and pioneers of the microcomputer revolution of the 1970s and 1980s. Born and raised in Seattle, Washington, Gates co-founded Microsoft with childhood friend Paul Allen in 1975, in Albuquerque, New Mexico; it went on to become the world's largest personal computer software company. Gates led the company as chairman and CEO until stepping down as CEO in January 2000, but he remained chairman and became chief software architect. During the late 1990s, Gates had been criticized for his business tactics, which have been considered anti-competitive. This opinion has been upheld by numerous court rulings. In June 2006, Gates announced that he would be transitioning to a part-time role at Microsoft and full-time work at the Bill & Melinda Gates Foundation, the private charitable foundation that he and his wife, Melinda Gates, established in 2000.[9] He gradually transferred his duties to Ray Ozzie and Craig Mundie. He stepped down as chairman of Microsoft in February 2014 and assumed a new post as technology adviser to support the newly appointed CEO Satya Nadella.",
118
  "The Mona Lisa is a 16th century oil painting created by Leonardo. It's held at the Louvre in Paris.",
119
  "When Sebastian Thrun started working on self-driving cars at Google in 2007, few people outside of the company took him seriously. “I can tell you very senior CEOs of major American car companies would shake my hand and turn away because I wasn’t worth talking to,” said Thrun, now the co-founder and CEO of online higher education startup Udacity, in an interview with Recode earlier this week.",
 
124
  "Steven Paul Jobs was an American business magnate, industrial designer, investor, and media proprietor. He was the chairman, chief executive officer (CEO), and co-founder of Apple Inc., the chairman and majority shareholder of Pixar, a member of The Walt Disney Company's board of directors following its acquisition of Pixar, and the founder, chairman, and CEO of NeXT. Jobs is widely recognized as a pioneer of the personal computer revolution of the 1970s and 1980s, along with Apple co-founder Steve Wozniak. Jobs was born in San Francisco, California, and put up for adoption. He was raised in the San Francisco Bay Area. He attended Reed College in 1972 before dropping out that same year, and traveled through India in 1974 seeking enlightenment and studying Zen Buddhism.",
125
  "Titanic is a 1997 American epic romance and disaster film directed, written, co-produced, and co-edited by James Cameron. Incorporating both historical and fictionalized aspects, it is based on accounts of the sinking of the RMS Titanic, and stars Leonardo DiCaprio and Kate Winslet as members of different social classes who fall in love aboard the ship during its ill-fated maiden voyage.",
126
  "Other than being the king of the north, John Snow is a an english physician and a leader in the development of anaesthesia and medical hygiene. He is considered for being the first one using data to cure cholera outbreak in 1834."
127
+ ]
 
128
 
129
+ # st.subheader("Automatically detect phrases expressing dates and normalize them with respect to a reference date.")
130
+ selected_text = st.selectbox("Select an example", examples)
131
+ custom_input = st.text_input("Try it with your own Sentence!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
+ text_to_analyze = custom_input if custom_input else selected_text
 
 
 
134
 
135
+ st.subheader('Full example text')
136
+ HTML_WRAPPER = """<div class="scroll entities" style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem; white-space:pre-wrap">{}</div>"""
137
+ st.markdown(HTML_WRAPPER.format(text_to_analyze), unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
+ # Initialize Spark and create pipeline
140
  spark = init_spark()
141
+ pipeline = create_pipeline(model)
142
+ output = fit_data(pipeline, text_to_analyze)
143
 
144
+ # Display matched sentence
145
+ st.subheader("Processed output:")
146
 
147
+ results = {
148
+ 'Document': output[0]['document'][0].result,
149
+ 'NER Chunk': [n.result for n in output[0]['ner_chunk']],
150
+ "NER Label": [n.metadata['entity'] for n in output[0]['ner_chunk']]
151
+ }
 
 
 
 
 
 
152
 
153
+ annotate(results)
154
 
155
+ with st.expander("View DataFrame"):
156
+ df = pd.DataFrame({'NER Chunk': results['NER Chunk'], 'NER Label': results['NER Label']})
157
+ df.index += 1
158
+ st.dataframe(df)