abdullahmubeen10 commited on
Commit
b6d9308
1 Parent(s): 6bb59f3

Upload 5 files

Browse files
.streamlit/config.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [theme]
2
+ base="light"
3
+ primaryColor="#29B4E8"
Demo.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import sparknlp
3
+ import pandas as pd
4
+
5
+ from sparknlp.base import *
6
+ from sparknlp.annotator import *
7
+ from pyspark.ml import Pipeline
8
+ from annotated_text import annotated_text
9
+ from streamlit_tags import st_tags
10
+
11
+ # Page configuration
12
+ st.set_page_config(layout="wide", initial_sidebar_state="auto")
13
+
14
+ # CSS for styling
15
+ st.markdown("""
16
+ <style>
17
+ .main-title {
18
+ font-size: 36px;
19
+ color: #4A90E2;
20
+ font-weight: bold;
21
+ text-align: center;
22
+ }
23
+ .section {
24
+ background-color: #f9f9f9;
25
+ padding: 10px;
26
+ border-radius: 10px;
27
+ margin-top: 10px;
28
+ }
29
+ .section p, .section ul {
30
+ color: #666666;
31
+ }
32
+ </style>
33
+ """, unsafe_allow_html=True)
34
+
35
+ @st.cache_resource
36
+ def init_spark():
37
+ return sparknlp.start()
38
+
39
+ @st.cache_resource
40
+ def create_pipeline(model_name, task):
41
+ document_assembler = DocumentAssembler().setInputCol('text').setOutputCol('document')
42
+ tokenizer = Tokenizer().setInputCols(['document']).setOutputCol('token')
43
+
44
+ if task == "Token Classification":
45
+ token_classifier = LongformerForTokenClassification \
46
+ .pretrained('longformer_base_token_classifier_conll03', 'en') \
47
+ .setInputCols(['token', 'document']) \
48
+ .setOutputCol('ner') \
49
+ .setCaseSensitive(False) \
50
+ .setMaxSentenceLength(512)
51
+
52
+ ner_converter = NerConverter() \
53
+ .setInputCols(['document', 'token', 'ner']) \
54
+ .setOutputCol('entities')
55
+
56
+ pipeline = Pipeline(stages=[document_assembler, tokenizer, token_classifier, ner_converter])
57
+ return pipeline
58
+
59
+ elif task == "Sequence Classification":
60
+ sequence_classifier = LongformerForSequenceClassification \
61
+ .pretrained(model_name, 'en') \
62
+ .setInputCols(['token', 'document']) \
63
+ .setOutputCol('class') \
64
+ .setCaseSensitive(False) \
65
+ .setMaxSentenceLength(1024)
66
+
67
+ pipeline = Pipeline(stages=[document_assembler, tokenizer, sequence_classifier])
68
+ return pipeline
69
+
70
+ elif task == "Question Answering":
71
+ document_assembler = MultiDocumentAssembler() \
72
+ .setInputCols(["question", "context"]) \
73
+ .setOutputCols(["document_question", "document_context"])
74
+
75
+ span_classifier = LongformerForQuestionAnswering.pretrained("longformer_base_base_qa_squad2", "en") \
76
+ .setInputCols(["document_question", "document_context"]) \
77
+ .setOutputCol("answer")\
78
+ .setCaseSensitive(True)
79
+
80
+ pipeline = Pipeline(stages=[document_assembler, span_classifier])
81
+ return pipeline
82
+
83
+ def fit_data(pipeline, task, data, question=None, context=None):
84
+ if task in ['Token Classification', 'Sequence Classification']:
85
+ empty_df = spark.createDataFrame([['']]).toDF('text')
86
+ pipeline_model = pipeline.fit(empty_df)
87
+ model = LightPipeline(pipeline_model)
88
+ result = model.fullAnnotate(data)
89
+ return result
90
+ elif task == "Question Answering":
91
+ df = spark.createDataFrame([[question, context]]).toDF("question", "context")
92
+ result = pipeline.fit(df).transform(df)
93
+ result = result.select('answer.result').collect()
94
+ return result
95
+
96
+ def annotate(data):
97
+ document, chunks, labels = data["Document"], data["NER Chunk"], data["NER Label"]
98
+ annotated_words = []
99
+ for chunk, label in zip(chunks, labels):
100
+ parts = document.split(chunk, 1)
101
+ if parts[0]:
102
+ annotated_words.append(parts[0])
103
+ annotated_words.append((chunk, label))
104
+ document = parts[1]
105
+ if document:
106
+ annotated_words.append(document)
107
+ annotated_text(*annotated_words)
108
+
109
+ tasks_models_descriptions = {
110
+ "Token Classification": {
111
+ "models": ["longformer_base_token_classifier_conll03"],
112
+ "description": "The 'longformer_base_token_classifier_conll03' model is optimized for token classification tasks, such as Named Entity Recognition (NER). Leveraging Longformer's ability to process long sequences, this model can accurately identify and classify entities like names, organizations, and locations within extended text passages, making it highly effective for information extraction from lengthy documents."
113
+ },
114
+ "Sequence Classification": {
115
+ "models": ["longformer_base_sequence_classifier_imdb", "longformer_base_sequence_classifier_ag_news"],
116
+ "description": "The 'longformer_base_sequence_classifier_imdb' and 'longformer_base_sequence_classifier_ag_news' models are tailored for sequence classification tasks. With the ability to handle long text inputs, these models excel in sentiment analysis and document classification. Whether it's assessing sentiment in lengthy movie reviews or categorizing extensive news articles, Longformer's unique architecture ensures accurate and context-aware classification."
117
+ },
118
+ "Question Answering": {
119
+ "models": ["longformer_base_base_qa_squad2"],
120
+ "description": "The 'longformer_base_base_qa_squad2' model is specifically designed for question answering tasks, excelling in scenarios where the context may be lengthy and complex. Utilizing Longformer's extended attention span, this model can accurately extract answers from long documents or passages, making it ideal for applications like automated customer support, educational tools, and advanced chatbots."
121
+ }
122
+ }
123
+
124
+ # Sidebar content
125
+ task = st.sidebar.selectbox("Choose the task", list(tasks_models_descriptions.keys()))
126
+ model = st.sidebar.selectbox("Choose the pretrained model", tasks_models_descriptions[task]["models"], help="For more info about the models visit: https://sparknlp.org/models")
127
+
128
+ # Reference notebook link in sidebar
129
+ colab_link = """
130
+ <a href="https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/331849cae5215e58757e5f2313ccefc5fd30ac32/Spark_NLP_Udemy_MOOC/Open_Source/17.01.Transformers-based_Embeddings.ipynb#L106">
131
+ <img src="https://colab.research.google.com/assets/colab-badge.svg" style="zoom: 1.3" alt="Open In Colab"/>
132
+ </a>
133
+ """
134
+ st.sidebar.markdown('Reference notebook:')
135
+ st.sidebar.markdown(colab_link, unsafe_allow_html=True)
136
+
137
+ # Page content
138
+ st.markdown(f'<div class="main-title">Albert for {task}</div>', unsafe_allow_html=True)
139
+ st.write(tasks_models_descriptions[task]["description"])
140
+
141
+ if model == 'longformer_base_sequence_classifier_ag_news':
142
+ examples_to_select = [
143
+ "The Prime Minister of the country announced new policies aimed at reducing carbon emissions by 40% over the next decade. These measures are part of a global effort to combat climate change.",
144
+ "A devastating earthquake hit the coastal city, leaving thousands homeless. International aid is pouring in to assist in the relief efforts as rescue teams continue to search for survivors.",
145
+ "The basketball star signed a record-breaking contract, making him the highest-paid player in the league. Fans are excited to see how he will perform in the upcoming season.",
146
+ "The Olympic Games concluded with a spectacular closing ceremony. The host nation topped the medal tally with an impressive number of gold medals across various sports.",
147
+ "The stock market saw significant gains today, with the Dow Jones reaching an all-time high. Investors are optimistic about the economic recovery following positive job growth data.",
148
+ "A major retail chain announced the closure of 150 stores nationwide due to declining sales. The company plans to focus more on its online presence to adapt to changing consumer behavior.",
149
+ "Scientists have discovered a new exoplanet that could potentially support life. The planet, located in a nearby star system, has conditions similar to those on Earth.",
150
+ "A leading technology firm unveiled its latest smartphone model, featuring a revolutionary camera system and a powerful new processor. The device is expected to set new standards in mobile computing.",
151
+ "In a historic move, the two rival nations signed a peace treaty, ending decades of hostility. The agreement is seen as a major step toward lasting stability in the region.",
152
+ "The tennis legend announced her retirement after a career spanning two decades, during which she won numerous Grand Slam titles. Tributes are pouring in from across the sporting world.",
153
+ "The energy company reported a significant increase in profits this quarter, driven by higher oil prices. Analysts are predicting continued growth in the coming months.",
154
+ "A new study has revealed that a diet high in fiber can significantly reduce the risk of heart disease. The findings are based on a large-scale analysis of dietary habits over the past decade."
155
+ ]
156
+ else:
157
+ examples_to_select = [
158
+ "This movie was absolutely fantastic! The storyline was gripping, the characters were well-developed, and the cinematography was stunning. I was on the edge of my seat the entire time.",
159
+ "A heartwarming and beautiful film. The performances were top-notch, and the direction was flawless. This is easily one of the best movies I've seen this year.",
160
+ "What a delightful surprise! The humor was spot on, and the plot was refreshingly original. The cast did an amazing job bringing the characters to life. Highly recommended!",
161
+ "This was one of the worst movies I’ve ever seen. The plot was predictable, the acting was wooden, and the pacing was painfully slow. I couldn’t wait for it to end.",
162
+ "A complete waste of time. The movie lacked any real substance or direction, and the dialogue was cringe-worthy. I wouldn’t recommend this to anyone.",
163
+ "I had high hopes for this film, but it turned out to be a huge disappointment. The story was disjointed, and the special effects were laughably bad. Don’t bother watching this one.",
164
+ "The movie was okay, but nothing special. It had a few good moments, but overall, it felt pretty average. Not something I would watch again, but it wasn’t terrible either.",
165
+ "An average film with a decent plot. The acting was passable, but it didn't leave much of an impression on me. It's a movie you might watch once and forget about.",
166
+ "This movie was neither good nor bad, just kind of there. It had some interesting ideas, but they weren’t executed very well. It’s a film you could take or leave."
167
+ ]
168
+
169
+ # Load examples
170
+ examples_mapping = {
171
+ "Token Classification": [
172
+ "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.",
173
+ "The Mona Lisa is a 16th century oil painting created by Leonardo. It's held at the Louvre in Paris.",
174
+ "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.",
175
+ "Facebook is a social networking service launched as TheFacebook on February 4, 2004. It was founded by Mark Zuckerberg with his college roommates and fellow Harvard University students Eduardo Saverin, Andrew McCollum, Dustin Moskovitz and Chris Hughes. The website's membership was initially limited by the founders to Harvard students, but was expanded to other colleges in the Boston area, the Ivy League, and gradually most universities in the United States and Canada.",
176
+ "The history of natural language processing generally started in the 1950s, although work can be found from earlier periods. In 1950, Alan Turing published an article titled 'Computing Machinery and Intelligence' which proposed what is now called the Turing test as a criterion of intelligence",
177
+ "Geoffrey Everest Hinton is an English Canadian cognitive psychologist and computer scientist, most noted for his work on artificial neural networks. Since 2013 he divides his time working for Google and the University of Toronto. In 2017, he cofounded and became the Chief Scientific Advisor of the Vector Institute in Toronto.",
178
+ "When I told John that I wanted to move to Alaska, he warned me that I'd have trouble finding a Starbucks there.",
179
+ "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.",
180
+ "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.",
181
+ "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."
182
+ ],
183
+ "Sequence Classification": examples_to_select,
184
+ "Question Answering": {
185
+ """What does increased oxygen concentrations in the patient’s lungs displace?""": """Hyperbaric (high-pressure) medicine uses special oxygen chambers to increase the partial pressure of O 2 around the patient and, when needed, the medical staff. Carbon monoxide poisoning, gas gangrene, and decompression sickness (the ’bends’) are sometimes treated using these devices. Increased O 2 concentration in the lungs helps to displace carbon monoxide from the heme group of hemoglobin. Oxygen gas is poisonous to the anaerobic bacteria that cause gas gangrene, so increasing its partial pressure helps kill them. Decompression sickness occurs in divers who decompress too quickly after a dive, resulting in bubbles of inert gas, mostly nitrogen and helium, forming in their blood. Increasing the pressure of O 2 as soon as possible is part of the treatment.""",
186
+ """What category of game is Legend of Zelda: Twilight Princess?""": """The Legend of Zelda: Twilight Princess (Japanese: ゼルダの伝説 トワイライトプリンセス, Hepburn: Zeruda no Densetsu: Towairaito Purinsesu?) is an action-adventure game developed and published by Nintendo for the GameCube and Wii home video game consoles. It is the thirteenth installment in the The Legend of Zelda series. Originally planned for release on the GameCube in November 2005, Twilight Princess was delayed by Nintendo to allow its developers to refine the game, add more content, and port it to the Wii. The Wii version was released alongside the console in North America in November 2006, and in Japan, Europe, and Australia the following month. The GameCube version was released worldwide in December 2006.""",
187
+ """Who is founder of Alibaba Group?""": """Alibaba Group founder Jack Ma has made his first appearance since Chinese regulators cracked down on his business empire. His absence had fuelled speculation over his whereabouts amid increasing official scrutiny of his businesses. The billionaire met 100 rural teachers in China via a video meeting on Wednesday, according to local government media. Alibaba shares surged 5% on Hong Kong's stock exchange on the news.""",
188
+ """For what instrument did Frédéric write primarily for?""": """Frédéric François Chopin (/ˈʃoʊpæn/; French pronunciation: ​[fʁe.de.ʁik fʁɑ̃.swa ʃɔ.pɛ̃]; 22 February or 1 March 1810 – 17 October 1849), born Fryderyk Franciszek Chopin,[n 1] was a Polish and French (by citizenship and birth of father) composer and a virtuoso pianist of the Romantic era, who wrote primarily for the solo piano. He gained and has maintained renown worldwide as one of the leading musicians of his era, whose "poetic genius was based on a professional technique that was without equal in his generation." Chopin was born in what was then the Duchy of Warsaw, and grew up in Warsaw, which after 1815 became part of Congress Poland. A child prodigy, he completed his musical education and composed his earlier works in Warsaw before leaving Poland at the age of 20, less than a month before the outbreak of the November 1830 Uprising.""",
189
+ """The most populated city in the United States is which city?""": """New York—often called New York City or the City of New York to distinguish it from the State of New York, of which it is a part—is the most populous city in the United States and the center of the New York metropolitan area, the premier gateway for legal immigration to the United States and one of the most populous urban agglomerations in the world. A global power city, New York exerts a significant impact upon commerce, finance, media, art, fashion, research, technology, education, and entertainment, its fast pace defining the term New York minute. Home to the headquarters of the United Nations, New York is an important center for international diplomacy and has been described as the cultural and financial capital of the world."""
190
+ }
191
+ }
192
+
193
+ if task == 'Question Answering':
194
+ examples = list(examples_mapping[task].keys())
195
+ selected_text = st.selectbox('Select an Example:', examples)
196
+ st.subheader('Try it yourself!')
197
+ custom_input_question = st.text_input('Create a question')
198
+ custom_input_context = st.text_input("Create it's context")
199
+
200
+ custom_examples = {}
201
+
202
+ st.subheader('Selected Text')
203
+
204
+ if custom_input_question and custom_input_context:
205
+ QUESTION = custom_input_question
206
+ CONTEXT = custom_input_context
207
+ elif selected_text:
208
+ QUESTION = selected_text
209
+ CONTEXT = examples_mapping[task][selected_text]
210
+
211
+ st.markdown(f"**Question:** {QUESTION}")
212
+ st.markdown(f"**Context:** {CONTEXT}")
213
+
214
+ else:
215
+ examples = examples_mapping[task]
216
+ selected_text = st.selectbox("Select an example", examples)
217
+ custom_input = st.text_input("Try it with your own Sentence!")
218
+
219
+ if task == 'Zero-Shot Classification':
220
+ zeroShotLables = ["urgent", "mobile", "travel", "movie", "music", "sport", "weather", "technology"]
221
+ lables = st_tags(
222
+ label='Select labels',
223
+ text='Press enter to add more',
224
+ value=zeroShotLables,
225
+ suggestions=[
226
+ "Positive", "Negative", "Neutral",
227
+ "Urgent", "Mobile", "Travel", "Movie", "Music", "Sport", "Weather", "Technology",
228
+ "Happiness", "Sadness", "Anger", "Fear", "Surprise", "Disgust",
229
+ "Informational", "Navigational", "Transactional", "Commercial Investigation",
230
+ "Politics", "Business", "Sports", "Entertainment", "Health", "Science",
231
+ "Product Quality", "Delivery Experience", "Customer Service", "Pricing", "Return Policy",
232
+ "Education", "Finance", "Lifestyle", "Fashion", "Food", "Art", "History",
233
+ "Culture", "Environment", "Real Estate", "Automotive", "Travel", "Fitness", "Career"],
234
+ maxtags = -1)
235
+
236
+ try:
237
+ text_to_analyze = custom_input if custom_input else selected_text
238
+ st.subheader('Full example text')
239
+ 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>"""
240
+ st.markdown(HTML_WRAPPER.format(text_to_analyze), unsafe_allow_html=True)
241
+ except:
242
+ text_to_analyze = selected_text
243
+
244
+ # Initialize Spark and create pipeline
245
+ spark = init_spark()
246
+ pipeline = create_pipeline(model, task)
247
+ try:
248
+ output = fit_data(pipeline, task, text_to_analyze, QUESTION, CONTEXT)
249
+ except:
250
+ output = fit_data(pipeline, task, text_to_analyze)
251
+
252
+ # Display matched sentence
253
+ st.subheader("Prediction:")
254
+
255
+ if task == 'Token Classification':
256
+ results = {
257
+ 'Document': output[0]['document'][0].result,
258
+ 'NER Chunk': [n.result for n in output[0]['entities']],
259
+ 'NER Label': [n.metadata['entity']for n in output[0]['entities']]
260
+ }
261
+ annotate(results)
262
+ df = pd.DataFrame({'NER Chunk': results['NER Chunk'], 'NER Label': results['NER Label']})
263
+ df.index += 1
264
+ st.dataframe(df)
265
+
266
+ elif task == 'Sequence Classification':
267
+ st.markdown(f"Classified as : **{output[0]['class'][0].result}**")
268
+
269
+ elif task == "Question Answering":
270
+ output_text = "".join(output[0][0])
271
+ st.markdown(f"Answer: **{output_text}**")
Dockerfile ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Download base image ubuntu 18.04
2
+ FROM ubuntu:18.04
3
+
4
+ # Set environment variables
5
+ ENV NB_USER jovyan
6
+ ENV NB_UID 1000
7
+ ENV HOME /home/${NB_USER}
8
+ ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64/
9
+
10
+ # Install required packages
11
+ RUN apt-get update && apt-get install -y \
12
+ tar \
13
+ wget \
14
+ bash \
15
+ rsync \
16
+ gcc \
17
+ libfreetype6-dev \
18
+ libhdf5-serial-dev \
19
+ libpng-dev \
20
+ libzmq3-dev \
21
+ python3 \
22
+ python3-dev \
23
+ python3-pip \
24
+ unzip \
25
+ pkg-config \
26
+ software-properties-common \
27
+ graphviz \
28
+ openjdk-8-jdk \
29
+ ant \
30
+ ca-certificates-java \
31
+ && apt-get clean \
32
+ && update-ca-certificates -f
33
+
34
+ # Install Python 3.8 and pip
35
+ RUN add-apt-repository ppa:deadsnakes/ppa \
36
+ && apt-get update \
37
+ && apt-get install -y python3.8 python3-pip \
38
+ && apt-get clean
39
+
40
+ # Set up JAVA_HOME
41
+ RUN echo "export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/" >> /etc/profile \
42
+ && echo "export PATH=\$JAVA_HOME/bin:\$PATH" >> /etc/profile
43
+ # Create a new user named "jovyan" with user ID 1000
44
+ RUN useradd -m -u ${NB_UID} ${NB_USER}
45
+
46
+ # Switch to the "jovyan" user
47
+ USER ${NB_USER}
48
+
49
+ # Set home and path variables for the user
50
+ ENV HOME=/home/${NB_USER} \
51
+ PATH=/home/${NB_USER}/.local/bin:$PATH
52
+
53
+ # Set up PySpark to use Python 3.8 for both driver and workers
54
+ ENV PYSPARK_PYTHON=/usr/bin/python3.8
55
+ ENV PYSPARK_DRIVER_PYTHON=/usr/bin/python3.8
56
+
57
+ # Set the working directory to the user's home directory
58
+ WORKDIR ${HOME}
59
+
60
+ # Upgrade pip and install Python dependencies
61
+ RUN python3.8 -m pip install --upgrade pip
62
+ COPY requirements.txt /tmp/requirements.txt
63
+ RUN python3.8 -m pip install -r /tmp/requirements.txt
64
+
65
+ # Copy the application code into the container at /home/jovyan
66
+ COPY --chown=${NB_USER}:${NB_USER} . ${HOME}
67
+
68
+ # Expose port for Streamlit
69
+ EXPOSE 7860
70
+
71
+ # Define the entry point for the container
72
+ ENTRYPOINT ["streamlit", "run", "Demo.py", "--server.port=7860", "--server.address=0.0.0.0"]
pages/Workflow & Model Overview.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ # Page configuration
4
+ st.set_page_config(
5
+ layout="wide",
6
+ initial_sidebar_state="auto"
7
+ )
8
+
9
+ # Custom CSS for better styling
10
+ st.markdown("""
11
+ <style>
12
+ .main-title {
13
+ font-size: 36px;
14
+ color: #4A90E2;
15
+ font-weight: bold;
16
+ text-align: center;
17
+ }
18
+ .sub-title {
19
+ font-size: 24px;
20
+ color: #4A90E2;
21
+ margin-top: 20px;
22
+ }
23
+ .section {
24
+ background-color: #f9f9f9;
25
+ padding: 15px;
26
+ border-radius: 10px;
27
+ margin-top: 20px;
28
+ }
29
+ .section h2 {
30
+ font-size: 22px;
31
+ color: #4A90E2;
32
+ }
33
+ .section p, .section ul {
34
+ color: #666666;
35
+ }
36
+ .link {
37
+ color: #4A90E2;
38
+ text-decoration: none;
39
+ }
40
+ .benchmark-table {
41
+ width: 100%;
42
+ border-collapse: collapse;
43
+ margin-top: 20px;
44
+ }
45
+ .benchmark-table th, .benchmark-table td {
46
+ border: 1px solid #ddd;
47
+ padding: 8px;
48
+ text-align: left;
49
+ }
50
+ .benchmark-table th {
51
+ background-color: #4A90E2;
52
+ color: white;
53
+ }
54
+ .benchmark-table td {
55
+ background-color: #f2f2f2;
56
+ }
57
+ </style>
58
+ """, unsafe_allow_html=True)
59
+
60
+ # Title
61
+ st.markdown('<div class="main-title">Introduction to Longformer for Token & Sequence Classification</div>', unsafe_allow_html=True)
62
+
63
+ # Subtitle
64
+ st.markdown("""
65
+ <div class="section">
66
+ <p>Longformer is a transformer-based model designed to handle long documents by leveraging an attention mechanism that scales linearly with the length of the document. This makes it highly effective for tasks such as token classification and sequence classification, especially when dealing with lengthy text inputs.</p>
67
+ </div>
68
+ """, unsafe_allow_html=True)
69
+
70
+ # Tabs for Longformer Annotators
71
+ tab1, tab2, tab3= st.tabs(["Longformer For Token Classification", "Longformer For Sequence Classification", "Longformer For Question Answering"])
72
+
73
+ # Tab 1: LongformerForTokenClassification
74
+ with tab1:
75
+ st.markdown("""
76
+ <div class="section">
77
+ <h2>Longformer for Token Classification</h2>
78
+ <p><strong>Token Classification</strong> involves assigning labels to individual tokens (words or subwords) within a sentence. This is essential for tasks like Named Entity Recognition (NER), where each token is classified as a specific entity such as a person, organization, or location.</p>
79
+ <p>Longformer is particularly effective for token classification tasks due to its ability to handle long contexts and capture dependencies over long spans of text.</p>
80
+ <p>Using Longformer for token classification enables:</p>
81
+ <ul>
82
+ <li><strong>Precise NER:</strong> Extract entities from lengthy documents with high accuracy.</li>
83
+ <li><strong>Efficient Contextual Understanding:</strong> Leverage Longformer's attention mechanism to model long-range dependencies.</li>
84
+ <li><strong>Scalability:</strong> Process large documents efficiently using Spark NLP.</li>
85
+ </ul>
86
+ </div>
87
+ """, unsafe_allow_html=True)
88
+
89
+ # Implementation Section
90
+ st.markdown('<div class="sub-title">How to Use Longformer for Token Classification in Spark NLP</div>', unsafe_allow_html=True)
91
+ st.markdown("""
92
+ <div class="section">
93
+ <p>Below is an example of how to set up a pipeline in Spark NLP using the Longformer model for token classification, specifically for Named Entity Recognition (NER).</p>
94
+ </div>
95
+ """, unsafe_allow_html=True)
96
+
97
+ st.code('''
98
+ from sparknlp.base import *
99
+ from sparknlp.annotator import *
100
+ from pyspark.ml import Pipeline
101
+ from pyspark.sql.functions import col, expr
102
+
103
+ document_assembler = DocumentAssembler() \\
104
+ .setInputCol('text') \\
105
+ .setOutputCol('document')
106
+
107
+ tokenizer = Tokenizer() \\
108
+ .setInputCols(['document']) \\
109
+ .setOutputCol('token')
110
+
111
+ tokenClassifier = LongformerForTokenClassification \\
112
+ .pretrained('longformer_base_token_classifier_conll03', 'en') \\
113
+ .setInputCols(['token', 'document']) \\
114
+ .setOutputCol('ner') \\
115
+ .setCaseSensitive(True) \\
116
+ .setMaxSentenceLength(512)
117
+
118
+ ner_converter = NerConverter() \\
119
+ .setInputCols(['document', 'token', 'ner']) \\
120
+ .setOutputCol('entities')
121
+
122
+ pipeline = Pipeline(stages=[
123
+ document_assembler,
124
+ tokenizer,
125
+ tokenClassifier,
126
+ ner_converter
127
+ ])
128
+
129
+ text = "Facebook is a social networking service launched as TheFacebook on February 4, 2004. It was founded by Mark Zuckerberg with his college roommates and fellow Harvard University students Eduardo Saverin, Andrew McCollum, Dustin Moskovitz and Chris Hughes. The website's membership was initially limited by the founders to Harvard students, but was expanded to other colleges in the Boston area, the Ivy League, and gradually most universities in the United States and Canada."
130
+ example = spark.createDataFrame([[text]]).toDF("text")
131
+ result = pipeline.fit(example).transform(example)
132
+
133
+ result.select(
134
+ expr("explode(entities) as ner_chunk")
135
+ ).select(
136
+ col("ner_chunk.result").alias("chunk"),
137
+ col("ner_chunk.metadata.entity").alias("ner_label")
138
+ ).show(truncate=False)
139
+ ''', language='python')
140
+
141
+ # Example Output
142
+ st.text("""
143
+ +------------------+---------+
144
+ |chunk |ner_label|
145
+ +------------------+---------+
146
+ |Mark Zuckerberg |PER |
147
+ |Harvard University|ORG |
148
+ |Eduardo Saverin |PER |
149
+ |Andrew McCollum |PER |
150
+ |Dustin Moskovitz |PER |
151
+ |Chris Hughes |PER |
152
+ |Harvard |ORG |
153
+ |Boston |LOC |
154
+ |Ivy |ORG |
155
+ |League |ORG |
156
+ |United |LOC |
157
+ |States |LOC |
158
+ |Canada |LOC |
159
+ +------------------+---------+
160
+ """)
161
+
162
+ # Model Info Section
163
+ st.markdown('<div class="sub-title">Choosing the Right Longformer Model</div>', unsafe_allow_html=True)
164
+ st.markdown("""
165
+ <div class="section">
166
+ <p>Spark NLP offers various Longformer models tailored for token classification tasks. Selecting the appropriate model can significantly impact performance.</p>
167
+ <p>Explore the available models on the <a class="link" href="https://sparknlp.org/models?annotator=LongformerForTokenClassification" target="_blank">Spark NLP Models Hub</a> to find the one that fits your needs.</p>
168
+ </div>
169
+ """, unsafe_allow_html=True)
170
+
171
+ # Tab 2: LongformerForSequenceClassification
172
+ with tab2:
173
+ st.markdown("""
174
+ <div class="section">
175
+ <h2>Longformer for Sequence Classification</h2>
176
+ <p><strong>Sequence Classification</strong> involves assigning a label to an entire sequence of text, such as determining the sentiment of a review or categorizing a document into topics. Longformer’s ability to model long-range dependencies is particularly beneficial for sequence classification tasks.</p>
177
+ <p>Using Longformer for sequence classification enables:</p>
178
+ <ul>
179
+ <li><strong>Accurate Sentiment Analysis:</strong> Determine the sentiment of long text sequences.</li>
180
+ <li><strong>Effective Document Classification:</strong> Categorize lengthy documents based on their content.</li>
181
+ <li><strong>Robust Performance:</strong> Benefit from Longformer’s attention mechanism for improved classification accuracy.</li>
182
+ </ul>
183
+ </div>
184
+ """, unsafe_allow_html=True)
185
+
186
+ # Implementation Section
187
+ st.markdown('<div class="sub-title">How to Use Longformer for Sequence Classification in Spark NLP</div>', unsafe_allow_html=True)
188
+ st.markdown("""
189
+ <div class="section">
190
+ <p>The following example demonstrates how to set up a pipeline in Spark NLP using the Longformer model for sequence classification, particularly for sentiment analysis of movie reviews.</p>
191
+ </div>
192
+ """, unsafe_allow_html=True)
193
+
194
+ st.code('''
195
+ from sparknlp.base import *
196
+ from sparknlp.annotator import *
197
+ from pyspark.ml import Pipeline
198
+
199
+ document_assembler = DocumentAssembler() \\
200
+ .setInputCol('text') \\
201
+ .setOutputCol('document')
202
+
203
+ tokenizer = Tokenizer() \\
204
+ .setInputCols(['document']) \\
205
+ .setOutputCol('token')
206
+
207
+ sequenceClassifier = LongformerForSequenceClassification \\
208
+ .pretrained('longformer_base_sequence_classifier_imdb', 'en') \\
209
+ .setInputCols(['token', 'document']) \\
210
+ .setOutputCol('class') \\
211
+ .setCaseSensitive(False) \\
212
+ .setMaxSentenceLength(1024)
213
+
214
+ pipeline = Pipeline(stages=[
215
+ document_assembler,
216
+ tokenizer,
217
+ sequenceClassifier
218
+ ])
219
+
220
+ example = spark.createDataFrame([['I really liked that movie!']]).toDF("text")
221
+ result = pipeline.fit(example).transform(example)
222
+
223
+ result.select('document.result','class.result').show()
224
+ ''', language='python')
225
+
226
+ # Example Output
227
+ st.text("""
228
+ +--------------------+------+
229
+ | result|result|
230
+ +--------------------+------+
231
+ |[I really liked t...| [pos]|
232
+ +--------------------+------+
233
+ """)
234
+
235
+ # Model Info Section
236
+ st.markdown('<div class="sub-title">Choosing the Right Longformer Model</div>', unsafe_allow_html=True)
237
+ st.markdown("""
238
+ <div class="section">
239
+ <p>Various Longformer models are available for sequence classification in Spark NLP. Each model is fine-tuned for specific tasks, so selecting the right one is crucial for achieving optimal performance.</p>
240
+ <p>Explore the available models on the <a class="link" href="https://sparknlp.org/models?annotator=LongformerForSequenceClassification" target="_blank">Spark NLP Models Hub</a> to find the best fit for your use case.</p>
241
+ </div>
242
+ """, unsafe_allow_html=True)
243
+
244
+ # Tab 3: LongformerForQuestionAnswering
245
+ with tab3:
246
+ st.markdown("""
247
+ <div class="section">
248
+ <h2>Longformer for Question Answering</h2>
249
+ <p><strong>Question Answering</strong> is the task of identifying the correct answer to a question from a given context or passage. Longformer's ability to process long documents makes it highly suitable for question answering tasks, especially in cases where the context is lengthy.</p>
250
+ <p>Using Longformer for question answering enables:</p>
251
+ <ul>
252
+ <li><strong>Accurate Answer Extraction:</strong> Identify precise answers within long passages.</li>
253
+ <li><strong>Contextual Understanding:</strong> Benefit from Longformer's global and local attention mechanisms to capture relevant information from context.</li>
254
+ <li><strong>Scalability:</strong> Efficiently process and handle extensive documents using Spark NLP.</li>
255
+ </ul>
256
+ </div>
257
+ """, unsafe_allow_html=True)
258
+
259
+ # Implementation Section
260
+ st.markdown('<div class="sub-title">How to Use Longformer for Question Answering in Spark NLP</div>', unsafe_allow_html=True)
261
+ st.markdown("""
262
+ <div class="section">
263
+ <p>The following example demonstrates how to set up a pipeline in Spark NLP using the Longformer model for question answering, specifically tailored for SQuAD v2 dataset.</p>
264
+ </div>
265
+ """, unsafe_allow_html=True)
266
+
267
+ st.code('''
268
+ from sparknlp.base import *
269
+ from sparknlp.annotator import *
270
+ from pyspark.ml import Pipeline
271
+
272
+ documentAssembler = MultiDocumentAssembler() \\
273
+ .setInputCols(["question", "context"]) \\
274
+ .setOutputCols(["document_question", "document_context"])
275
+
276
+ spanClassifier = LongformerForQuestionAnswering.pretrained("longformer_base_base_qa_squad2", "en") \\
277
+ .setInputCols(["document_question", "document_context"]) \\
278
+ .setOutputCol("answer")\\
279
+ .setCaseSensitive(True)
280
+
281
+ pipeline = Pipeline(stages=[documentAssembler, spanClassifier])
282
+
283
+ data = spark.createDataFrame([["What is my name?", "My name is Clara and I live in Berkeley."]]).toDF("question", "context")
284
+
285
+ result = pipeline.fit(data).transform(data)
286
+ ''', language='python')
287
+
288
+ # Example Output
289
+ st.text("""
290
+ +-------+
291
+ | result|
292
+ +-------+
293
+ |[Clara]|
294
+ +-------+
295
+ """)
296
+
297
+ # Model Info Section
298
+ st.markdown('<div class="sub-title">Choosing the Right Longformer Model</div>', unsafe_allow_html=True)
299
+ st.markdown("""
300
+ <div class="section">
301
+ <p>Various Longformer models are available for question answering in Spark NLP. Each model is fine-tuned for specific tasks, so selecting the right one is crucial for achieving optimal performance.</p>
302
+ <p>Explore the available models on the <a class="link" href="https://sparknlp.org/models?annotator=LongformerForQuestionAnswering" target="_blank">Spark NLP Models Hub</a> to find the best fit for your use case.</p>
303
+ </div>
304
+ """, unsafe_allow_html=True)
305
+
306
+ # Footer
307
+ st.markdown('<div class="sub-title">Community & Support</div>', unsafe_allow_html=True)
308
+
309
+ st.markdown("""
310
+ <div class="section">
311
+ <ul>
312
+ <li><a class="link" href="https://sparknlp.org/" target="_blank">Official Website</a>: Documentation and examples</li>
313
+ <li><a class="link" href="https://join.slack.com/t/spark-nlp/shared_invite/zt-198dipu77-L3UWNe_AJ8xqDk0ivmih5Q" target="_blank">Slack</a>: Live discussion with the community and team</li>
314
+ <li><a class="link" href="https://github.com/JohnSnowLabs/spark-nlp" target="_blank">GitHub</a>: Bug reports, feature requests, and contributions</li>
315
+ <li><a class="link" href="https://medium.com/spark-nlp" target="_blank">Medium</a>: Spark NLP articles</li>
316
+ <li><a class="link" href="https://www.youtube.com/channel/UCmFOjlpYEhxf_wJUDuz6xxQ/videos" target="_blank">YouTube</a>: Video tutorials</li>
317
+ </ul>
318
+ </div>
319
+ """, unsafe_allow_html=True)
320
+
321
+ st.markdown('<div class="sub-title">Quick Links</div>', unsafe_allow_html=True)
322
+
323
+ st.markdown("""
324
+ <div class="section">
325
+ <ul>
326
+ <li><a class="link" href="https://sparknlp.org/docs/en/quickstart" target="_blank">Getting Started</a></li>
327
+ <li><a class="link" href="https://nlp.johnsnowlabs.com/models" target="_blank">Pretrained Models</a></li>
328
+ <li><a class="link" href="https://github.com/JohnSnowLabs/spark-nlp/tree/master/examples/python/annotation/text/english" target="_blank">Example Notebooks</a></li>
329
+ <li><a class="link" href="https://sparknlp.org/docs/en/install" target="_blank">Installation Guide</a></li>
330
+ </ul>
331
+ </div>
332
+ """, unsafe_allow_html=True)
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ st-annotated-text
3
+ streamlit-tags
4
+ pandas
5
+ numpy
6
+ spark-nlp
7
+ pyspark