import streamlit as st
# Custom CSS for better styling
st.markdown("""
""", unsafe_allow_html=True)
# Introduction
st.markdown('
Text Preprocessing with Spark NLP
', unsafe_allow_html=True)
st.markdown("""
Welcome to the Spark NLP Text Preprocessing Demo App! In the field of Natural Language Processing (NLP), preprocessing is a crucial step that ensures the text data is clean and suitable for modeling. Effective preprocessing can significantly enhance the performance of NLP models.
Spark NLP stands out as a leading library for text preprocessing, offering a range of tools and models within an easy-to-use pipeline design compatible with Apache Spark. This demo showcases how you can leverage Spark NLP to preprocess your text data efficiently.
""", unsafe_allow_html=True)
# About Text Preprocessing
st.markdown('About Text Preprocessing
', unsafe_allow_html=True)
st.markdown("""
Text preprocessing involves a series of steps to clean and normalize text data. Common tasks include tokenization, stopword removal, stemming, lemmatization, and more. These steps are essential for preparing raw text for downstream NLP tasks.
In Spark NLP, text preprocessing is facilitated through various annotators that can be combined into a preprocessing pipeline. We'll demonstrate how to use these annotators in Python to preprocess text data effectively.
""", unsafe_allow_html=True)
st.image('https://www.johnsnowlabs.com/wp-content/uploads/2023/05/img_blog_2-4.jpg', caption='Text preprocessing pipeline visual', use_column_width='auto')
# How to Use the Preprocessing Tools
st.markdown('How to Use Spark NLP for Text Preprocessing
', unsafe_allow_html=True)
st.markdown("""
To preprocess text using Spark NLP, we need to create a pipeline that includes various preprocessing annotators. These annotators transform the input text through steps like tokenization, normalization, and stopword removal.
""", unsafe_allow_html=True)
st.markdown('Installation
', unsafe_allow_html=True)
st.code('!pip install spark-nlp', language='python')
# Import Libraries and Read Data
st.markdown('Importing Libraries and Reading Data
', unsafe_allow_html=True)
st.markdown("""
First, we'll import Spark NLP and necessary libraries, read the data from a local file, and convert it into a Spark DataFrame.
""", unsafe_allow_html=True)
st.code("""
import sparknlp
from sparknlp.base import *
from sparknlp.annotator import *
spark= sparknlp.start()
df= spark.read\\
.option("header", True)\\
.csv("spam_text_messages.csv")\\
.toDF("category", "text")
df.show(5, truncate=30)
>>>
+--------+------------------------------+
|category| text|
+--------+------------------------------+
| ham|Go until jurong point, craz...|
| ham| Ok lar... Joking wif u oni...|
| spam|Free entry in 2 a wkly comp...|
| ham|U dun say so early hor... U...|
| ham|Nah I don't think he goes t...|
+--------+------------------------------+
only showing top 5 rows
""", language='python')
st.markdown("""
The dataset contains two columns: category and text. The text column contains messages, and the category column indicates whether the message is spam or not (ham).
""", unsafe_allow_html=True)
# Document Assembler
st.markdown('Document Assembler
', unsafe_allow_html=True)
st.markdown("""
The DocumentAssembler is the beginning part of any Spark NLP project. It creates the first annotation of type Document, which may be used by annotators down the road. We use it as follows:
""", unsafe_allow_html=True)
st.code("""
documentAssembler = DocumentAssembler() \\
.setInputCol("text") \\
.setOutputCol("document") \\
.setCleanupMode("shrink")
df_doc = documentAssembler.transform(df)
df_doc.printSchema()
""", language='python')
st.markdown("""
The shrink
cleanup mode removes new lines and tabs, merging multiple spaces and blank lines into a single space. The schema after transformation includes the new document column.
""", unsafe_allow_html=True)
# Tokenizer
st.markdown('Tokenizer
', unsafe_allow_html=True)
st.markdown("""
The Tokenizer identifies the tokens in Spark NLP:
""", unsafe_allow_html=True)
st.code("""
tokenizer = Tokenizer() \\
.setInputCols(["document"]) \\
.setOutputCol("token")
""", language='python')
# Sentence Detector
st.markdown('Sentence Detector
', unsafe_allow_html=True)
st.markdown("""
The SentenceDetector finds sentence boundaries in raw text:
""", unsafe_allow_html=True)
st.code("""
sentenceDetector = SentenceDetector() \\
.setInputCols(["document"]) \\
.setOutputCol("sentence")
""", language='python')
# Normalizer
st.markdown('Normalizer
', unsafe_allow_html=True)
st.markdown("""
The Normalizer cleans dirty characters after regex pattern and removes words based on a given dictionary:
""", unsafe_allow_html=True)
st.code("""
normalizer = Normalizer() \\
.setInputCols(["token"]) \\
.setOutputCol("normalized") \\
.setLowercase(True) \\
.setCleanupPatterns(["[^\w\d\s]"])
""", language='python')
# Stopwords Cleaner
st.markdown('Stopwords Cleaner
', unsafe_allow_html=True)
st.markdown("""
The StopWordsCleaner removes stopwords from the text:
""", unsafe_allow_html=True)
st.code("""
stopwordsCleaner = StopWordsCleaner() \\
.setInputCols(["token"]) \\
.setOutputCol("cleaned_tokens") \\
.setCaseSensitive(True)
""", language='python')
# Token Assembler
st.markdown('Token Assembler
', unsafe_allow_html=True)
st.markdown("""
The TokenAssembler assembles cleaned tokens back together:
""", unsafe_allow_html=True)
st.code("""
tokenAssembler = TokenAssembler() \\
.setInputCols(["sentence", "cleaned_tokens"]) \\
.setOutputCol("assembled")
""", language='python')
# Stemmer
st.markdown('Stemmer
', unsafe_allow_html=True)
st.markdown("""
The Stemmer reduces inflectional forms and sometimes derivationally related forms of a word to a common base form:
""", unsafe_allow_html=True)
st.code("""
stemmer = Stemmer() \\
.setInputCols(["token"]) \\
.setOutputCol("stem")
""", language='python')
# Lemmatizer
st.markdown('Lemmatizer
', unsafe_allow_html=True)
st.markdown("""
The Lemmatizer reduces words to their base or root form, referring to a dictionary to understand the word's meaning:
""", unsafe_allow_html=True)
st.code("""
lemmatizer = Lemmatizer() \\
.setInputCols(["token"]) \\
.setOutputCol("lemma") \\
.setDictionary("AntBNC_lemmas_ver_001.txt", value_delimiter="\\t", key_delimiter="->")
""", language='python')
# Pipeline
st.markdown('Putting All Processes into a Spark ML Pipeline
', unsafe_allow_html=True)
st.markdown("""
Now, we will put all the preprocessing stages into a Spark ML Pipeline and apply it to our dataset.
""", unsafe_allow_html=True)
st.code("""
from pyspark.ml import Pipeline
nlpPipeline = Pipeline(stages=[
documentAssembler,
tokenizer,
sentenceDetector,
normalizer,
stopwordsCleaner,
tokenAssembler,
stemmer,
lemmatizer
])
empty_df = spark.createDataFrame([[""]]).toDF("text")
model = nlpPipeline.fit(empty_df)
result = model.transform(df)
""", language='python')
# Showcase/Example
st.markdown('Showcase/Example
', unsafe_allow_html=True)
st.markdown("""
Let's examine the results of our preprocessing pipeline, starting with tokens and normalized tokens:
""", unsafe_allow_html=True)
st.code("""
from pyspark.sql import functions as F
result.select("token.result", "normalized.result").show(5, truncate=30)
>>>
+------------------------------+------------------------------+
| result| result|
+------------------------------+------------------------------+
|[Go, until, jurong, point, ...|[go, until, jurong, point, ...|
|[Ok, lar, ..., Joking, wif,...|[ok, lar, joking, wif, u, oni]|
|[Free, entry, in, 2, a, wkl...|[free, entry, in, 2, a, wkl...|
|[U, dun, say, so, early, ho...|[u, dun, say, so, early, ho...|
|[Nah, I, don't, think, he, ...|[nah, ı, dont, think, he, g...|
+------------------------------+------------------------------+
only showing top 5 rows
""", language='python')
st.markdown("""
Next, we check the cleaned data from stopwords:
""", unsafe_allow_html=True)
st.code("""
result.select(F.explode(F.arrays_zip("token.result", "cleaned_tokens.result")).alias("col")) \\
.select(F.expr("col['0']").alias("token"), F.expr("col['1']").alias("cleaned_sw")).show(10)
>>>
+------------------------------+------------------------------+
| result| result|
+------------------------------+------------------------------+
|[Go, until, jurong, point, ...|[go, until, jurong, point, ...|
|[Ok, lar, ..., Joking, wif,...|[ok, lar, joking, wif, u, oni]|
|[Free, entry, in, 2, a, wkl...|[free, entry, in, 2, a, wkl...|
|[U, dun, say, so, early, ho...|[u, dun, say, so, early, ho...|
|[Nah, I, don't, think, he, ...|[nah, ı, dont, think, he, g...|
+------------------------------+------------------------------+
only showing top 5 rows
""", language='python')
st.markdown("""
Finally, we compare the sentence detector result and token assembler result:
""", unsafe_allow_html=True)
st.code("""
result.select(F.explode(F.arrays_zip("sentence.result", "assembled.result")).alias("col")) \\
.select(F.expr("col['0']").alias("sentence"), F.expr("col['1']").alias("assembled")).show(5, truncate=30)
>>>
+------------------------------+------------------------------+
| sentence| assembled|
+------------------------------+------------------------------+
| Go until jurong point, crazy.| Go jurong point, crazy|
| .| |
|Available only in bugis n g...|Available bugis n great wor...|
| Cine there got amore wat.| Cine got amore wat|
| .| |
+------------------------------+------------------------------+
only showing top 5 rows
result.withColumn("tmp", F.explode("assembled")) \\
.select("tmp.*").select("begin", "end", "result", "metadata.sentence").show(5, truncate=30)
>>>
+-----+---+------------------------------+--------+
|begin|end| result|sentence|
+-----+---+------------------------------+--------+
| 0| 21| Go jurong point, crazy| 0|
| 29| 28| | 1|
| 31| 74|Available bugis n great wor...| 2|
| 84|101| Cine got amore wat| 3|
| 109|108| | 4|
+-----+---+------------------------------+--------+
only showing top 5 rows
""", language='python')
st.markdown("""
In this example, we have successfully cleaned and preprocessed text data using various annotators and transformers in Spark NLP. This preprocessing pipeline is essential for preparing the data for further NLP tasks, ensuring that the text is clean and normalized.
""", unsafe_allow_html=True)
st.markdown('Additional Resources and References
', unsafe_allow_html=True)
st.markdown("""
""", unsafe_allow_html=True)
st.markdown('Community & Support
', unsafe_allow_html=True)
st.markdown("""
- Official Website: Documentation and examples
- Slack: Live discussion with the community and team
- GitHub: Bug reports, feature requests, and contributions
- Medium: Spark NLP articles
- YouTube: Video tutorials
""", unsafe_allow_html=True)