abdullahmubeen10 commited on
Commit
876127f
Β·
verified Β·
1 Parent(s): 497996d

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,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from streamlit_tags import st_tags
12
+
13
+ # Page configuration
14
+ st.set_page_config(
15
+ layout="wide",
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 {
29
+ background-color: #f9f9f9;
30
+ padding: 10px;
31
+ border-radius: 10px;
32
+ margin-top: 10px;
33
+ }
34
+ .section p, .section ul {
35
+ color: #666666;
36
+ }
37
+ </style>
38
+ """, unsafe_allow_html=True)
39
+
40
+ @st.cache_resource
41
+ def init_spark():
42
+ return sparknlp.start()
43
+
44
+ @st.cache_resource
45
+ def create_pipeline(model, task):
46
+ document_assembler = DocumentAssembler() \
47
+ .setInputCol('text') \
48
+ .setOutputCol('document')
49
+
50
+ sentence_detector = SentenceDetectorDLModel.pretrained("sentence_detector_dl", "xx") \
51
+ .setInputCols(["document"]) \
52
+ .setOutputCol("sentence")
53
+
54
+ tokenizer = Tokenizer() \
55
+ .setInputCols(['sentence']) \
56
+ .setOutputCol('token')
57
+
58
+ if task == "Token Classification":
59
+ classifier = XlnetForTokenClassification.pretrained('xlnet_base_token_classifier_conll03', 'en') \
60
+ .setInputCols(["sentence", "token"]) \
61
+ .setOutputCol("ner") \
62
+ .setCaseSensitive(False) \
63
+ .setMaxSentenceLength(512)
64
+
65
+ ner_converter = NerConverter() \
66
+ .setInputCols(['sentence', 'token', 'ner']) \
67
+ .setOutputCol('ner_chunk')
68
+
69
+ pipeline = Pipeline(stages=[document_assembler, sentence_detector, tokenizer, classifier, ner_converter])
70
+
71
+ elif task == "Sequence Classification":
72
+ tokenizer.setInputCols(['document'])
73
+
74
+ classifier = XlnetForSequenceClassification.pretrained(model, 'en') \
75
+ .setInputCols(["document", "token"]) \
76
+ .setOutputCol("class")
77
+
78
+ pipeline = Pipeline(stages=[document_assembler, tokenizer, classifier])
79
+
80
+ return pipeline
81
+
82
+ def fit_data(pipeline, data):
83
+ empty_df = spark.createDataFrame([['']]).toDF('text')
84
+ pipeline_model = pipeline.fit(empty_df)
85
+ model = LightPipeline(pipeline_model)
86
+ result = model.fullAnnotate(data)
87
+ return result
88
+
89
+ def annotate(data):
90
+ document, chunks, labels = data["Document"], data["NER Chunk"], data["NER Label"]
91
+ annotated_words = []
92
+ for chunk, label in zip(chunks, labels):
93
+ parts = document.split(chunk, 1)
94
+ if parts[0]:
95
+ annotated_words.append(parts[0])
96
+ annotated_words.append((chunk, label))
97
+ document = parts[1]
98
+ if document:
99
+ annotated_words.append(document)
100
+ annotated_text(*annotated_words)
101
+
102
+ tasks_models_descriptions = {
103
+ "Token Classification": {
104
+ "models": ["xlnet_base_token_classifier_conll03"],
105
+ "description": "The 'xlnet_base_token_classifier_conll03' model is adept at token classification tasks, including named entity recognition (NER). It identifies and categorizes tokens in text, such as names, dates, and locations, enhancing the extraction of meaningful information from unstructured data."
106
+ },
107
+ "Sequence Classification": {
108
+ "models": ["xlnet_base_sequence_classifier_imdb", "xlnet_base_sequence_classifier_ag_news"],
109
+ "description": "Both the xlnet_base_sequence_classifier model is proficient in sequence classification tasks, such as sentiment analysis and document categorization. It effectively determines the sentiment of reviews, classifies text, and sorts documents based on their content and context."
110
+ }
111
+ }
112
+
113
+ # Sidebar content
114
+ task = st.sidebar.selectbox("Choose the task", list(tasks_models_descriptions.keys()))
115
+ 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")
116
+
117
+ # Reference notebook link in sidebar
118
+ link = """
119
+ <a href="https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/357691d18373d6e8f13b5b1015137a398fd0a45f/Spark_NLP_Udemy_MOOC/Open_Source/17.01.Transformers-based_Embeddings.ipynb#L103">
120
+ <img src="https://colab.research.google.com/assets/colab-badge.svg" style="zoom: 1.3" alt="Open In Colab"/>
121
+ </a>
122
+ """
123
+ st.sidebar.markdown('Reference notebook:')
124
+ st.sidebar.markdown(link, unsafe_allow_html=True)
125
+
126
+ # Page content
127
+ title, sub_title = (f'DeBERTa for {task}', tasks_models_descriptions[task]["description"])
128
+ st.markdown(f'<div class="main-title">{title}</div>', unsafe_allow_html=True)
129
+ container = st.container(border=True)
130
+ container.write(sub_title)
131
+
132
+ # Load examples
133
+ examples_mapping = {
134
+ "Token Classification": [
135
+ "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.",
136
+ "The Mona Lisa is a 16th century oil painting created by Leonardo. It's held at the Louvre in Paris.",
137
+ "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.",
138
+ "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.",
139
+ "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",
140
+ "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.",
141
+ "When I told John that I wanted to move to Alaska, he warned me that I'd have trouble finding a Starbucks there.",
142
+ "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.",
143
+ "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.",
144
+ "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."
145
+ ],
146
+ "Sequence Classification": [
147
+ "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.",
148
+ "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.",
149
+ "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!",
150
+ "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.",
151
+ "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.",
152
+ "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.",
153
+ "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.",
154
+ "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.",
155
+ "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."
156
+ ]
157
+ }
158
+
159
+ examples = examples_mapping[task]
160
+ selected_text = st.selectbox("Select an example", examples)
161
+ custom_input = st.text_input("Try it with your own Sentence!")
162
+
163
+ try:
164
+ text_to_analyze = custom_input if custom_input else selected_text
165
+ st.subheader('Full example text')
166
+ 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>"""
167
+ st.markdown(HTML_WRAPPER.format(text_to_analyze), unsafe_allow_html=True)
168
+ except:
169
+ text_to_analyze = selected_text
170
+
171
+ # Initialize Spark and create pipeline
172
+ spark = init_spark()
173
+ pipeline = create_pipeline(model, task)
174
+ output = fit_data(pipeline, text_to_analyze)
175
+
176
+ # Display matched sentence
177
+ st.subheader("Prediction:")
178
+
179
+ if task == 'Token Classification':
180
+ results = {
181
+ 'Document': output[0]['document'][0].result,
182
+ 'NER Chunk': [n.result for n in output[0]['ner_chunk']],
183
+ 'NER Label': [n.metadata['entity'] for n in output[0]['ner_chunk']]
184
+ }
185
+ annotate(results)
186
+ df = pd.DataFrame({'NER Chunk': results['NER Chunk'], 'NER Label': results['NER Label']})
187
+ df.index += 1
188
+ st.dataframe(df)
189
+
190
+ else:
191
+ st.markdown(f"Classified as : **{output[0]['class'][0].result}**")
192
+
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,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 XLNet for Token & Sequence Classification in Spark NLP</div>', unsafe_allow_html=True)
62
+
63
+ # Subtitle
64
+ st.markdown("""
65
+ <div class="section">
66
+ <p>XLNet is a powerful transformer-based language model that excels in handling various Natural Language Processing (NLP) tasks. It uses a permutation-based training approach, which allows it to capture bidirectional context, making it highly effective for tasks like token classification and sequence classification.</p>
67
+ </div>
68
+ """, unsafe_allow_html=True)
69
+
70
+ # Tabs for XLNet Annotators
71
+ tab1, tab2 = st.tabs(["XlnetForTokenClassification", "XlnetForSequenceClassification"])
72
+
73
+ # Tab 1: XlnetForTokenClassification
74
+ with tab1:
75
+ st.markdown("""
76
+ <div class="section">
77
+ <h2>XLNet for Token Classification</h2>
78
+ <p><strong>Token Classification</strong> involves assigning labels to individual tokens (words or subwords) within a sentence. This is crucial for tasks such as Named Entity Recognition (NER), where each token is classified as a specific entity like a person, organization, or location.</p>
79
+ <p>XLNet, with its robust contextual understanding, is particularly suited for token classification tasks. Its permutation-based training enables the model to capture dependencies across different parts of a sentence, improving accuracy in token-level predictions.</p>
80
+ <p>Using XLNet for token classification enables:</p>
81
+ <ul>
82
+ <li><strong>Accurate NER:</strong> Extract entities from text with high precision.</li>
83
+ <li><strong>Contextual Understanding:</strong> Benefit from XLNet's ability to model bidirectional context for each token.</li>
84
+ <li><strong>Scalability:</strong> Efficiently process large-scale datasets 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 XLNet 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 XLNet 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
+
102
+ document_assembler = DocumentAssembler() \\
103
+ .setInputCol('text') \\
104
+ .setOutputCol('document')
105
+
106
+ tokenizer = Tokenizer() \\
107
+ .setInputCols(['document']) \\
108
+ .setOutputCol('token')
109
+
110
+ tokenClassifier = XlnetForTokenClassification \\
111
+ .pretrained('xlnet_base_token_classifier_conll03', 'en') \\
112
+ .setInputCols(['token', 'document']) \\
113
+ .setOutputCol('ner') \\
114
+ .setCaseSensitive(True) \\
115
+ .setMaxSentenceLength(512)
116
+
117
+ ner_converter = NerConverter() \\
118
+ .setInputCols(['document', 'token', 'ner']) \\
119
+ .setOutputCol('entities')
120
+
121
+ pipeline = Pipeline(stages=[
122
+ document_assembler,
123
+ tokenizer,
124
+ tokenClassifier,
125
+ ner_converter
126
+ ])
127
+
128
+ example = spark.createDataFrame([['My name is John!']]).toDF("text")
129
+ result = pipeline.fit(example).transform(example)
130
+ ''', language='python')
131
+
132
+ # Example Output
133
+ st.text("""
134
+ +---------+---------+
135
+ |entities |label |
136
+ +---------+---------+
137
+ |John |PER |
138
+ +---------+---------+
139
+ """)
140
+
141
+ # Model Info Section
142
+ st.markdown('<div class="sub-title">Choosing the Right XLNet Model</div>', unsafe_allow_html=True)
143
+ st.markdown("""
144
+ <div class="section">
145
+ <p>Spark NLP offers various XLNet models tailored for token classification tasks. Selecting the appropriate model can significantly impact performance.</p>
146
+ <p>Explore the available models on the <a class="link" href="https://sparknlp.org/models?annotator=XlnetForTokenClassification" target="_blank">Spark NLP Models Hub</a> to find the one that fits your needs.</p>
147
+ </div>
148
+ """, unsafe_allow_html=True)
149
+
150
+ # Tab 2: XlnetForSequenceClassification
151
+ with tab2:
152
+ st.markdown("""
153
+ <div class="section">
154
+ <h2>XLNet for Sequence Classification</h2>
155
+ <p><strong>Sequence Classification</strong> is the task of assigning a label to an entire sequence of text, such as determining the sentiment of a review or categorizing a document into topics. XLNet's ability to model long-range dependencies makes it particularly effective for sequence classification.</p>
156
+ <p>Using XLNet for sequence classification enables:</p>
157
+ <ul>
158
+ <li><strong>Sentiment Analysis:</strong> Accurately determine the sentiment of text.</li>
159
+ <li><strong>Document Classification:</strong> Categorize documents based on their content.</li>
160
+ <li><strong>Robust Performance:</strong> Benefit from XLNet's permutation-based training for improved classification accuracy.</li>
161
+ </ul>
162
+ </div>
163
+ """, unsafe_allow_html=True)
164
+
165
+ # Implementation Section
166
+ st.markdown('<div class="sub-title">How to Use XLNet for Sequence Classification in Spark NLP</div>', unsafe_allow_html=True)
167
+ st.markdown("""
168
+ <div class="section">
169
+ <p>The following example demonstrates how to set up a pipeline in Spark NLP using the XLNet model for sequence classification, particularly for sentiment analysis of movie reviews.</p>
170
+ </div>
171
+ """, unsafe_allow_html=True)
172
+
173
+ st.code('''
174
+ from sparknlp.base import *
175
+ from sparknlp.annotator import *
176
+ from pyspark.ml import Pipeline
177
+
178
+ document_assembler = DocumentAssembler() \\
179
+ .setInputCol('text') \\
180
+ .setOutputCol('document')
181
+
182
+ tokenizer = Tokenizer() \\
183
+ .setInputCols(['document']) \\
184
+ .setOutputCol('token')
185
+
186
+ sequenceClassifier = XlnetForSequenceClassification \\
187
+ .pretrained('xlnet_base_sequence_classifier_imdb', 'en') \\
188
+ .setInputCols(['token', 'document']) \\
189
+ .setOutputCol('class') \\
190
+ .setCaseSensitive(False) \\
191
+ .setMaxSentenceLength(512)
192
+
193
+ pipeline = Pipeline(stages=[
194
+ document_assembler,
195
+ tokenizer,
196
+ sequenceClassifier
197
+ ])
198
+
199
+ example = spark.createDataFrame([['I really liked that movie!']]).toDF("text")
200
+ result = pipeline.fit(example).transform(example)
201
+ ''', language='python')
202
+
203
+ # Example Output
204
+ st.text("""
205
+ +------------------------+
206
+ |class |
207
+ +------------------------+
208
+ |[positive] |
209
+ +------------------------+
210
+ """)
211
+
212
+ # Model Info Section
213
+ st.markdown('<div class="sub-title">Choosing the Right XLNet Model</div>', unsafe_allow_html=True)
214
+ st.markdown("""
215
+ <div class="section">
216
+ <p>Various XLNet 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>
217
+ <p>Explore the available models on the <a class="link" href="https://sparknlp.org/models?annotator=XlnetForSequenceClassification" target="_blank">Spark NLP Models Hub</a> to find the best fit for your use case.</p>
218
+ </div>
219
+ """, unsafe_allow_html=True)
220
+
221
+
222
+ # Footer
223
+ st.markdown('<div class="sub-title">Community & Support</div>', unsafe_allow_html=True)
224
+
225
+ st.markdown("""
226
+ <div class="section">
227
+ <ul>
228
+ <li><a class="link" href="https://sparknlp.org/" target="_blank">Official Website</a>: Documentation and examples</li>
229
+ <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>
230
+ <li><a class="link" href="https://github.com/JohnSnowLabs/spark-nlp" target="_blank">GitHub</a>: Bug reports, feature requests, and contributions</li>
231
+ <li><a class="link" href="https://medium.com/spark-nlp" target="_blank">Medium</a>: Spark NLP articles</li>
232
+ <li><a class="link" href="https://www.youtube.com/channel/UCmFOjlpYEhxf_wJUDuz6xxQ/videos" target="_blank">YouTube</a>: Video tutorials</li>
233
+ </ul>
234
+ </div>
235
+ """, unsafe_allow_html=True)
236
+
237
+ st.markdown('<div class="sub-title">Quick Links</div>', unsafe_allow_html=True)
238
+
239
+ st.markdown("""
240
+ <div class="section">
241
+ <ul>
242
+ <li><a class="link" href="https://sparknlp.org/docs/en/quickstart" target="_blank">Getting Started</a></li>
243
+ <li><a class="link" href="https://nlp.johnsnowlabs.com/models" target="_blank">Pretrained Models</a></li>
244
+ <li><a class="link" href="https://github.com/JohnSnowLabs/spark-nlp/tree/master/examples/python/annotation/text/english" target="_blank">Example Notebooks</a></li>
245
+ <li><a class="link" href="https://sparknlp.org/docs/en/install" target="_blank">Installation Guide</a></li>
246
+ </ul>
247
+ </div>
248
+ """, 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