aemin commited on
Commit
a13d49c
·
1 Parent(s): d0e8147

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -302
app.py DELETED
@@ -1,302 +0,0 @@
1
- import streamlit as st
2
- st.set_page_config(
3
- layout="centered", # Can be "centered" or "wide". In the future also "dashboard", etc.
4
- initial_sidebar_state="auto", # Can be "auto", "expanded", "collapsed"
5
- page_title='Extractive Summarization', # String or None. Strings get appended with "• Streamlit".
6
- page_icon='./favicon.png', # String, anything supported by st.image, or None.
7
- )
8
- import pandas as pd
9
- import numpy as np
10
- import os
11
- import sys
12
- sys.path.append(os.path.abspath('./'))
13
- import streamlit_apps_config as config
14
- from streamlit_ner_output import show_html2, jsl_display_annotations, get_color
15
-
16
- import sparknlp
17
- from sparknlp.base import *
18
- from sparknlp.annotator import *
19
- from pyspark.sql import functions as F
20
- from sparknlp_display import NerVisualizer
21
- from pyspark.ml import Pipeline
22
- from pyspark.sql.types import StringType
23
- spark= sparknlp.start()
24
-
25
- ## Marking down NER Style
26
- st.markdown(config.STYLE_CONFIG, unsafe_allow_html=True)
27
-
28
- root_path = config.project_path
29
-
30
- ########## To Remove the Main Menu Hamburger ########
31
-
32
- hide_menu_style = """
33
- <style>
34
- #MainMenu {visibility: hidden;}
35
- </style>
36
- """
37
- st.markdown(hide_menu_style, unsafe_allow_html=True)
38
-
39
- ########## Side Bar ########
40
-
41
- ## loading logo(newer version with href)
42
- import base64
43
- @st.cache(allow_output_mutation=True)
44
- def get_base64_of_bin_file(bin_file):
45
- with open(bin_file, 'rb') as f:
46
- data = f.read()
47
- return base64.b64encode(data).decode()
48
-
49
- @st.cache(allow_output_mutation=True)
50
- def get_img_with_href(local_img_path, target_url):
51
- img_format = os.path.splitext(local_img_path)[-1].replace('.', '')
52
- bin_str = get_base64_of_bin_file(local_img_path)
53
- html_code = f'''
54
- <a href="{target_url}">
55
- <img height="90%" width="90%" src="data:image/{img_format};base64,{bin_str}" />
56
- </a>'''
57
- return html_code
58
-
59
- logo_html = get_img_with_href('./jsl-logo.png', 'https://www.johnsnowlabs.com/')
60
- st.sidebar.markdown(logo_html, unsafe_allow_html=True)
61
-
62
-
63
- #sidebar info
64
- model_name= ["nerdl_fewnerd_100d", "ner_conll_elmo", "ner_mit_movie_complex_distilbert_base_cased", "ner_conll_albert_large_uncased", "onto_100"]
65
- st.sidebar.title("Pretrained model to test")
66
- selected_model = st.sidebar.selectbox("", model_name)
67
-
68
- ######## Main Page #########
69
- if selected_model == "nerdl_fewnerd_100d":
70
- app_title= "Detect up to 8 entity types in general domain texts"
71
- app_description= "Named Entity Recognition model aimed to detect up to 8 entity types from general domain texts. This model was trained on the Few-NERD/inter public dataset using Spark NLP, and it is available in Spark NLP Models hub (https://nlp.johnsnowlabs.com/models)"
72
- st.title(app_title)
73
- st.markdown("<h2>"+app_description+"</h2>" , unsafe_allow_html=True)
74
- st.markdown("**`PERSON`** **,** **`ORGANIZATION`** **,** **`LOCATION`** **,** **`ART`** **,** **`BUILDING`** **,** **`PRODUCT`** **,** **`EVENT`** **,** **`OTHER`**", unsafe_allow_html=True)
75
-
76
- elif selected_model== "ner_conll_elmo":
77
- app_title= "Detect up to 4 entity types in general domain texts"
78
- app_description= "Named Entity Recognition model aimed to detect up to 4 entity types from general domain texts. This model was trained on the CoNLL 2003 text corpus using Spark NLP, and it is available in Spark NLP Models hub (https://nlp.johnsnowlabs.com/models)"
79
- st.title(app_title)
80
- st.markdown("<h2>"+app_description+"</h2>" , unsafe_allow_html=True)
81
- st.markdown("**`PER`** **,** **`LOC`** **,** **`ORG`** **,** **`MISC` **", unsafe_allow_html=True)
82
-
83
-
84
- elif selected_model== "ner_mit_movie_complex_distilbert_base_cased":
85
- app_title= "Detect up to 12 entity types in movie domain texts"
86
- app_description= "Named Entity Recognition model aimed to detect up to 12 entity types from movie domain texts. This model was trained on the MIT Movie Corpus complex queries dataset to detect movie trivia using Spark NLP, and it is available in Spark NLP Models hub (https://nlp.johnsnowlabs.com/models)"
87
- st.title(app_title)
88
- st.markdown("<h2>"+app_description+"</h2>" , unsafe_allow_html=True)
89
- st.markdown("""**`ACTOR`** **,** **`AWARD`** **,** **`CHARACTER_NAME`** **,** **`DIRECTOR`** **,** **`GENRE`** **,** **`OPINION`** **,** **`ORIGIN`** **,** **`PLOT`**,
90
- **`QUOTE`** **,** **`RELATIONSHIP`** **,** **`SOUNDTRACK`** **,** **`YEAR` **""", unsafe_allow_html=True)
91
-
92
- elif selected_model=="ner_conll_albert_large_uncased":
93
- app_title= "Detect up to 4 entity types in general domain texts"
94
- app_description= "Named Entity Recognition model aimed to detect up to 4 entity types from general domain texts. This model was trained on the CoNLL 2003 text corpus using Spark NLP, and it is available in Spark NLP Models hub (https://nlp.johnsnowlabs.com/models)"
95
- st.title(app_title)
96
- st.markdown("<h2>"+app_description+"</h2>" , unsafe_allow_html=True)
97
- st.markdown("**`PER`** **,** **`LOC`** **,** **`ORG`** **,** **`MISC` **", unsafe_allow_html=True)
98
-
99
- elif selected_model=="onto_100":
100
- app_title= "Detect up to 18 entity types in general domain texts"
101
- app_description= "Named Entity Recognition model aimed to detect up to 18 entity types from general domain texts. This model was trained with GloVe 100d word embeddings using Spark NLP, so be sure to use same embeddings in the pipeline. It is available in Spark NLP Models hub (https://nlp.johnsnowlabs.com/models)"
102
- st.title(app_title)
103
- st.markdown("<h2>"+app_description+"</h2>" , unsafe_allow_html=True)
104
- st.markdown("""**`CARDINAL`** **,** **`EVENT`** **,** **`WORK_OF_ART`** **,** **`ORG`** **,** **`DATE`** **,** **`GPE`** **,** **`PERSON`** **,** **`PRODUCT`**,
105
- **`NORP`** **,** **`ORDINAL`** **,** **`MONEY`** **,** **`LOC` **, **`FAC`** **,** **`LAW`** **,** **`TIME`** **,** **`PERCENT`** **,** **`QUANTITY`** **,** **`LANGUAGE` **""", unsafe_allow_html=True)
106
-
107
- st.subheader("")
108
-
109
-
110
- #### Running model and creating pipeline
111
- st.cache(allow_output_mutation=True)
112
- def get_pipeline(text):
113
- documentAssembler = DocumentAssembler()\
114
- .setInputCol("text")\
115
- .setOutputCol("document")
116
-
117
- sentenceDetector= SentenceDetector()\
118
- .setInputCols(["document"])\
119
- .setOutputCol("sentence")
120
-
121
- tokenizer = Tokenizer()\
122
- .setInputCols(["sentence"])\
123
- .setOutputCol("token")
124
-
125
-
126
- if selected_model=="nerdl_fewnerd_100d":
127
- embeddings= WordEmbeddingsModel.pretrained("glove_100d")\
128
- .setInputCols(["sentence", "token"])\
129
- .setOutputCol("embeddings")
130
-
131
- ner= NerDLModel.pretrained(selected_model)\
132
- .setInputCols(["document", "token", "embeddings"])\
133
- .setOutputCol("ner")
134
-
135
-
136
- ner_converter= NerConverter()\
137
- .setInputCols(["sentence", "token", "ner"])\
138
- .setOutputCol("ner_chunk")
139
-
140
-
141
- pipeline = Pipeline(
142
- stages = [
143
- documentAssembler,
144
- sentenceDetector,
145
- tokenizer,
146
- embeddings,
147
- ner,
148
- ner_converter
149
- ])
150
-
151
- elif selected_model=="ner_conll_elmo":
152
- embeddings = ElmoEmbeddings\
153
- .pretrained('elmo', 'en')\
154
- .setInputCols(["token", "document"])\
155
- .setOutputCol("embeddings")\
156
- .setPoolingLayer("elmo")
157
-
158
- ner = NerDLModel.pretrained('ner_conll_elmo', 'en') \
159
- .setInputCols(['document', 'token', 'embeddings']) \
160
- .setOutputCol('ner')
161
-
162
- ner_converter= NerConverter()\
163
- .setInputCols(["document", "token", "ner"])\
164
- .setOutputCol("ner_chunk")
165
-
166
- pipeline = Pipeline(
167
- stages = [
168
- documentAssembler,
169
- sentenceDetector,
170
- tokenizer,
171
- embeddings,
172
- ner,
173
- ner_converter
174
- ])
175
-
176
- elif selected_model=="ner_mit_movie_complex_distilbert_base_cased":
177
- embeddings = DistilBertEmbeddings\
178
- .pretrained('distilbert_base_cased', 'en')\
179
- .setInputCols(["token", "document"])\
180
- .setOutputCol("embeddings")
181
-
182
- ner = NerDLModel.pretrained('ner_mit_movie_complex_distilbert_base_cased', 'en') \
183
- .setInputCols(['document', 'token', 'embeddings']) \
184
- .setOutputCol('ner')
185
-
186
- ner_converter= NerConverter()\
187
- .setInputCols(["document", "token", "ner"])\
188
- .setOutputCol("ner_chunk")
189
-
190
- pipeline = Pipeline(
191
- stages = [
192
- documentAssembler,
193
- sentenceDetector,
194
- tokenizer,
195
- embeddings,
196
- ner,
197
- ner_converter
198
- ])
199
-
200
- elif selected_model=="ner_conll_albert_large_uncased":
201
- embeddings = AlbertEmbeddings\
202
- .pretrained('albert_large_uncased', 'en')\
203
- .setInputCols(["document", "token"])\
204
- .setOutputCol("embeddings")
205
-
206
- ner = NerDLModel.pretrained('ner_conll_albert_large_uncased', 'en') \
207
- .setInputCols(['document', 'token', 'embeddings']) \
208
- .setOutputCol('ner')
209
-
210
- ner_converter = NerConverter()\
211
- .setInputCols(["document","token","ner"])\
212
- .setOutputCol("ner_chunk")
213
-
214
- pipeline = Pipeline(
215
- stages = [
216
- documentAssembler,
217
- sentenceDetector,
218
- tokenizer,
219
- embeddings,
220
- ner,
221
- ner_converter
222
- ])
223
-
224
- elif selected_model=="onto_100":
225
- embeddings = WordEmbeddingsModel.pretrained('glove_100d') \
226
- .setInputCols(['document', 'token']) \
227
- .setOutputCol('embeddings')
228
-
229
- ner = NerDLModel.pretrained("onto_100", "en") \
230
- .setInputCols(["document", "token", "embeddings"]) \
231
- .setOutputCol("ner")
232
-
233
- ner_converter = NerConverter()\
234
- .setInputCols(["document","token","ner"])\
235
- .setOutputCol("ner_chunk")
236
-
237
- pipeline = Pipeline(
238
- stages = [
239
- documentAssembler,
240
- sentenceDetector,
241
- tokenizer,
242
- embeddings,
243
- ner,
244
- ner_converter
245
- ])
246
-
247
-
248
- empty_df = spark.createDataFrame([[""]]).toDF("text")
249
- pipeline_model = pipeline.fit(empty_df)
250
-
251
- text_df= spark.createDataFrame(pd.DataFrame({"text": [text]}))
252
- result= pipeline_model.transform(text_df).toPandas()
253
-
254
- return result
255
-
256
- if selected_model=="ner_conll_albert_large_uncased":
257
- 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.")
258
-
259
-
260
-
261
- elif selected_model=="ner_mit_movie_complex_distilbert_base_cased":
262
- 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")
263
-
264
- elif selected_model=="ner_conll_elmo":
265
- 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.")
266
-
267
- elif selected_model=="onto_100":
268
- 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. He was 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. He led the company as chairman and CEO until stepping down as CEO in January 2000, but he remained chairman and became chief software architect.")
269
-
270
- else:
271
- 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.")
272
-
273
-
274
- #placeholder for warning
275
- placeholder= st.empty()
276
- placeholder.info("Processing...")
277
-
278
- result= get_pipeline(text)
279
-
280
- placeholder.empty()
281
-
282
-
283
- #Displaying Ner Visualization
284
- df= pd.DataFrame({"ner_chunk": result["ner_chunk"].iloc[0]})
285
-
286
- labels_set = set()
287
- for i in df['ner_chunk'].values:
288
- labels_set.add(i[4]['entity'])
289
- labels_set = list(labels_set)
290
-
291
- labels = st.sidebar.multiselect(
292
- "NER Labels", options=labels_set, default=list(labels_set)
293
- )
294
-
295
- show_html2(text, df, labels, "Text annotated with identified Named Entities")
296
-
297
-
298
- 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>"""
299
- st.sidebar.title('')
300
- st.sidebar.markdown('Try it yourself:')
301
- st.sidebar.markdown(try_link, unsafe_allow_html=True)
302
-