aemin commited on
Commit
c2bf0b7
·
1 Parent(s): e487a25

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -8
app.py CHANGED
@@ -1,21 +1,19 @@
 
 
 
 
 
1
  import streamlit as st
2
 
3
 
 
4
  st.set_page_config(
5
  layout="centered", # Can be "centered" or "wide". In the future also "dashboard", etc.
6
  initial_sidebar_state="auto", # Can be "auto", "expanded", "collapsed"
7
  page_title='Extractive Summarization', # String or None. Strings get appended with "• Streamlit".
8
  page_icon='./favicon.png', # String, anything supported by st.image, or None.
9
  )
10
-
11
-
12
- import pandas as pd
13
- import numpy as np
14
- import json
15
- import os
16
- import sys
17
  sys.path.append(os.path.abspath('./'))
18
- import streamlit_apps_config as config
19
  from streamlit_ner_output import show_html2, jsl_display_annotations, get_color
20
 
21
  import sparknlp
@@ -117,7 +115,195 @@ st.subheader("")
117
 
118
 
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
 
 
 
 
121
 
122
 
123
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import json
4
+ import os
5
+ import sys
6
  import streamlit as st
7
 
8
 
9
+ import streamlit_apps_config as config
10
  st.set_page_config(
11
  layout="centered", # Can be "centered" or "wide". In the future also "dashboard", etc.
12
  initial_sidebar_state="auto", # Can be "auto", "expanded", "collapsed"
13
  page_title='Extractive Summarization', # String or None. Strings get appended with "• Streamlit".
14
  page_icon='./favicon.png', # String, anything supported by st.image, or None.
15
  )
 
 
 
 
 
 
 
16
  sys.path.append(os.path.abspath('./'))
 
17
  from streamlit_ner_output import show_html2, jsl_display_annotations, get_color
18
 
19
  import sparknlp
 
115
 
116
 
117
 
118
+ #caching the models in the dictionary
119
+ @st.cache(allow_output_mutation=True, show_spinner=False)
120
+ def load_sparknlp_models():
121
+ ner_models_list= ["nerdl_fewnerd_100d", "ner_conll_elmo", "ner_mit_movie_complex_distilbert_base_cased", "ner_conll_albert_large_uncased", "onto_100"]
122
+ embeddings_list= ["glove_100d", "elmo", "distilbert_base_cased", "albert_large_uncased", "glove_100d_for_onto"]
123
+
124
+
125
+ documentAssembler = DocumentAssembler()\
126
+ .setInputCol("text")\
127
+ .setOutputCol("document")
128
+
129
+ sentenceDetector= SentenceDetector()\
130
+ .setInputCols(["document"])\
131
+ .setOutputCol("sentence")
132
+
133
+ tokenizer = Tokenizer()\
134
+ .setInputCols(["sentence"])\
135
+ .setOutputCol("token")
136
+
137
+ ner_converter= NerConverter()\
138
+ .setInputCols(["document", "token", "ner"])\
139
+ .setOutputCol("ner_chunk")
140
+
141
+ model_dict= {
142
+ 'documentAssembler': documentAssembler,
143
+ 'sentenceDetector': sentenceDetector,
144
+ 'tokenizer': tokenizer,
145
+ 'ner_converter': ner_converter
146
+ }
147
+
148
+ for embeddings_name, ner_model_name in zip(embeddings_list, ner_models_list):
149
+
150
+ try:
151
+ if embeddings_name=="glove_100d":
152
+ model_dict[embeddings_name]= WordEmbeddingsModel.pretrained(embeddings_name, "en")\
153
+ .setInputCols(["sentence", "token"])\
154
+ .setOutputCol("embeddings")
155
+
156
+ elif embeddings_name=="elmo":
157
+ model_dict[embeddings_name]= ElmoEmbeddings.pretrained(embeddings_name, "en")\
158
+ .setInputCols(["token", "document"])\
159
+ .setOutputCol("embeddings")\
160
+ .setPoolingLayer("elmo")
161
+
162
+ elif embeddings_name=="distilbert_base_cased":
163
+ model_dict[embeddings_name]= DistilBertEmbeddings\
164
+ .pretrained(embeddings_name, 'en')\
165
+ .setInputCols(["token", "document"])\
166
+ .setOutputCol("embeddings")
167
+
168
+ elif embeddings_name=="albert_large_uncased":
169
+ model_dict[embeddings_name]= AlbertEmbeddings\
170
+ .pretrained(embeddings_name, 'en')\
171
+ .setInputCols(["document", "token"])\
172
+ .setOutputCol("embeddings")
173
+
174
+ elif embeddings_name=="glove_100d_for_onto":
175
+ model_dict[embeddings_name]= WordEmbeddingsModel.pretrained("glove_100d", "en")\
176
+ .setInputCols(["sentence", "token"])\
177
+ .setOutputCol("embeddings")
178
+
179
+
180
+ model_dict[ner_model_name]= NerDLModel.pretrained(ner_model_name, "en")\
181
+ .setInputCols(["document", "token", "embeddings"])\
182
+ .setOutputCol("ner")
183
+
184
+
185
+ except:
186
+ pass
187
+ return model_dict
188
+
189
+
190
+
191
+ placeholder_= st.empty()
192
+ placeholder_.info("If you are launching the app for the first time, it may take some time (approximately 1 minute) for SparkNLP models to load...")
193
+ nlp_dict= load_sparknlp_models()
194
+ placeholder_.empty()
195
+
196
+
197
+
198
+
199
+ if selected_model=="ner_conll_albert_large_uncased":
200
+ text= st.text_input("Type here your text and press enter to run:", value="Mark Knopfler was born in Glasgow, Scotland. He is a British singer-songwriter, guitarist, and record producer. He became known as the lead guitarist, singer and songwriter of the rock band Dire Straits.")
201
+
202
+ elif selected_model=="ner_mit_movie_complex_distilbert_base_cased":
203
+ text= st.text_input("Type here your text and press enter to run:", value="It's only appropriate that Solaris, Russian filmmaker Andrei Tarkovsky's psychological sci-fi classic from 1972, contains an equally original and mind-bending score. Solaris explores the inadequacies of time and memory on an enigmatic planet below a derelict space station. To reinforce the film's chilling setting, Tarkovsky commissioned composer Eduard Artemiev to construct an electronic soundscape reflecting planet Solaris' amorphous and mysterious surface")
204
+
205
+ elif selected_model=="ner_conll_elmo":
206
+ text= st.text_input("Type here your text and press enter to run: ", value="Tottenham Hotspur Football Club, commonly referred to as Tottenham or Spurs, is an English professional football club based in Tottenham, London, that competes in the Premier League, the top flight of English football.")
207
+
208
+ elif selected_model=="onto_100":
209
+ text= st.text_input("Type here your text and press enter to run: ", value="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.")
210
+
211
+ else:
212
+ text= st.text_input("Type here your text and press enter to run:", value="12 Corazones ('12 Hearts') is Spanish-language dating game show produced in the United States for the television network Telemundo since January 2005, based on its namesake Argentine TV show format. The show is filmed in Los Angeles and revolves around the twelve Zodiac signs that identify each contestant. In 2008, Ho filmed a cameo in the Steven Spielberg feature film The Cloverfield Paradox, as a news pundit.")
213
+
214
+
215
+
216
+ def build_pipeline(text, model_name=selected_model):
217
+
218
+ base_pipeline= Pipeline(stages=[
219
+ nlp_dict["documentAssembler"],
220
+ nlp_dict["sentenceDetector"],
221
+ nlp_dict["tokenizer"]
222
+ ])
223
+
224
+ fewnerd_pipeline= Pipeline(stages=[
225
+ base_pipeline,
226
+ nlp_dict["glove_100d"],
227
+ nlp_dict[model_name],
228
+ nlp_dict["ner_converter"]
229
+ ])
230
+
231
+ elmo_pipeline= Pipeline(stages=[
232
+ base_pipeline,
233
+ nlp_dict["elmo"],
234
+ nlp_dict[model_name],
235
+ nlp_dict["ner_converter"]
236
+ ])
237
+
238
+ movie_pipeline= Pipeline(stages=[
239
+ base_pipeline,
240
+ nlp_dict["distilbert_base_cased"],
241
+ nlp_dict[model_name],
242
+ nlp_dict["ner_converter"]
243
+ ])
244
+
245
+ albert_pipeline= Pipeline(stages=[
246
+ base_pipeline,
247
+ nlp_dict["albert_large_uncased"],
248
+ nlp_dict[model_name],
249
+ nlp_dict["ner_converter"]
250
+ ])
251
+
252
+ onto_pipeline= Pipeline(stages=[
253
+ base_pipeline,
254
+ nlp_dict["glove_100d_for_onto"],
255
+ nlp_dict[model_name],
256
+ nlp_dict["ner_converter"]
257
+ ])
258
+
259
+
260
+ empty_df = spark.createDataFrame([[""]]).toDF("text")
261
+
262
+ if model_name=="nerdl_fewnerd_100d":
263
+ pipeline_model= fewnerd_pipeline.fit(empty_df)
264
+
265
+ elif model_name=="ner_conll_elmo":
266
+ pipeline_model= elmo_pipeline.fit(empty_df)
267
+
268
+ elif model_name=="ner_mit_movie_complex_distilbert_base_cased":
269
+ pipeline_model= movie_pipeline.fit(empty_df)
270
+
271
+ elif model_name=="ner_conll_albert_large_uncased":
272
+ pipeline_model= albert_pipeline.fit(empty_df)
273
+
274
+ elif model_name=="onto_100":
275
+ pipeline_model= onto_pipeline.fit(empty_df)
276
+
277
+
278
+ text_df= spark.createDataFrame(pd.DataFrame({"text": [text]}))
279
+ result= pipeline_model.transform(text_df).toPandas()
280
+
281
+ return result
282
+
283
+ #placeholder for warning
284
+ placeholder= st.empty()
285
+ placeholder.info("Processing...")
286
+
287
+ result= build_pipeline(text)
288
+ placeholder.empty()
289
+
290
+ df= pd.DataFrame({"ner_chunk": result["ner_chunk"].iloc[0]})
291
+
292
+ labels_set = set()
293
+ for i in df['ner_chunk'].values:
294
+ labels_set.add(i[4]['entity'])
295
+ labels_set = list(labels_set)
296
+
297
+ labels = st.sidebar.multiselect(
298
+ "NER Labels", options=labels_set, default=list(labels_set)
299
+ )
300
+
301
+ show_html2(text, df, labels, "Text annotated with identified Named Entities")
302
 
303
+ try_link="""<a href="https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Public/3.SparkNLP_Pretrained_Models.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" style="zoom: 1.3" alt="Open In Colab"/></a>"""
304
+ st.sidebar.title('')
305
+ st.sidebar.markdown('Try it yourself:')
306
+ st.sidebar.markdown(try_link, unsafe_allow_html=True)
307
 
308
 
309