Spaces:
Sleeping
Sleeping
Upload 5 files
Browse files- .streamlit/config.toml +3 -0
- Demo.py +161 -0
- Dockerfile +70 -0
- pages/Workflow & Model Overview.py +264 -0
- requirements.txt +6 -0
.streamlit/config.toml
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
[theme]
|
2 |
+
base="light"
|
3 |
+
primaryColor="#29B4E8"
|
Demo.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
12 |
+
# Page configuration
|
13 |
+
st.set_page_config(
|
14 |
+
layout="wide",
|
15 |
+
initial_sidebar_state="auto"
|
16 |
+
)
|
17 |
+
|
18 |
+
# CSS for styling
|
19 |
+
st.markdown("""
|
20 |
+
<style>
|
21 |
+
.main-title {
|
22 |
+
font-size: 36px;
|
23 |
+
color: #4A90E2;
|
24 |
+
font-weight: bold;
|
25 |
+
text-align: center;
|
26 |
+
}
|
27 |
+
.section p, .section ul {
|
28 |
+
color: #666666;
|
29 |
+
}
|
30 |
+
</style>
|
31 |
+
""", unsafe_allow_html=True)
|
32 |
+
|
33 |
+
@st.cache_resource
|
34 |
+
def init_spark():
|
35 |
+
return sparknlp.start()
|
36 |
+
|
37 |
+
@st.cache_resource
|
38 |
+
def create_pipeline(model):
|
39 |
+
document_assembler = DocumentAssembler() \
|
40 |
+
.setInputCol("text") \
|
41 |
+
.setOutputCol("document")
|
42 |
+
|
43 |
+
tokenizer = Tokenizer() \
|
44 |
+
.setInputCols(["document"]) \
|
45 |
+
.setOutputCol("token")
|
46 |
+
|
47 |
+
if model == "ner_wikiner_glove_840B_300":
|
48 |
+
embeddings = WordEmbeddingsModel.pretrained('glove_840B_300', lang='xx') \
|
49 |
+
.setInputCols(['document', 'token']) \
|
50 |
+
.setOutputCol('embeddings')
|
51 |
+
elif model == "wikiner_6B_300":
|
52 |
+
embeddings = WordEmbeddingsModel.pretrained('glove_6B_300', lang='xx') \
|
53 |
+
.setInputCols(['document', 'token']) \
|
54 |
+
.setOutputCol('embeddings')
|
55 |
+
elif model == "wikiner_6B_100":
|
56 |
+
embeddings = WordEmbeddingsModel.pretrained('glove_100d') \
|
57 |
+
.setInputCols(['document', 'token']) \
|
58 |
+
.setOutputCol('embeddings')
|
59 |
+
|
60 |
+
lang = 'xx' if model == "ner_wikiner_glove_840B_300" else 'pt'
|
61 |
+
ner_model = NerDLModel.pretrained(model, lang) \
|
62 |
+
.setInputCols(["document", "token", "embeddings"]) \
|
63 |
+
.setOutputCol("ner")
|
64 |
+
|
65 |
+
ner_converter = NerConverter() \
|
66 |
+
.setInputCols(["document", "token", "ner"]) \
|
67 |
+
.setOutputCol("ner_chunk")
|
68 |
+
|
69 |
+
pipeline = Pipeline(stages=[
|
70 |
+
document_assembler,
|
71 |
+
tokenizer,
|
72 |
+
embeddings,
|
73 |
+
ner_model,
|
74 |
+
ner_converter
|
75 |
+
])
|
76 |
+
|
77 |
+
return pipeline
|
78 |
+
|
79 |
+
def fit_data(pipeline, data):
|
80 |
+
empty_df = spark.createDataFrame([['']]).toDF('text')
|
81 |
+
pipeline_model = pipeline.fit(empty_df)
|
82 |
+
model = LightPipeline(pipeline_model)
|
83 |
+
result = model.fullAnnotate(data)
|
84 |
+
return result
|
85 |
+
|
86 |
+
def annotate(data):
|
87 |
+
document, chunks, labels = data["Document"], data["NER Chunk"], data["NER Label"]
|
88 |
+
annotated_words = []
|
89 |
+
for chunk, label in zip(chunks, labels):
|
90 |
+
parts = document.split(chunk, 1)
|
91 |
+
if parts[0]:
|
92 |
+
annotated_words.append(parts[0])
|
93 |
+
annotated_words.append((chunk, label))
|
94 |
+
document = parts[1]
|
95 |
+
if document:
|
96 |
+
annotated_words.append(document)
|
97 |
+
annotated_text(*annotated_words)
|
98 |
+
|
99 |
+
# Set up the page layout
|
100 |
+
st.markdown('<div class="main-title">Reconhecer pessoas, lugares, organizações e outras entidades</div>', unsafe_allow_html=True)
|
101 |
+
|
102 |
+
# Sidebar content
|
103 |
+
model = st.sidebar.selectbox(
|
104 |
+
"Choose the pretrained model",
|
105 |
+
["ner_wikiner_glove_840B_300", "wikiner_6B_100", "wikiner_6B_300"],
|
106 |
+
help="For more info about the models visit: https://sparknlp.org/models"
|
107 |
+
)
|
108 |
+
|
109 |
+
# Reference notebook link in sidebar
|
110 |
+
link = """
|
111 |
+
<a href="https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/NER_PT.ipynb">
|
112 |
+
<img src="https://colab.research.google.com/assets/colab-badge.svg" style="zoom: 1.3" alt="Open In Colab"/>
|
113 |
+
</a>
|
114 |
+
"""
|
115 |
+
st.sidebar.markdown('Reference notebook:')
|
116 |
+
st.sidebar.markdown(link, unsafe_allow_html=True)
|
117 |
+
|
118 |
+
# Load examples
|
119 |
+
examples = [
|
120 |
+
"William Henry Gates III (nascido em 28 de outubro de 1955) é um magnata dos negócios americano, desenvolvedor de software, investidor e filantropo. Ele é mais conhecido como co-fundador da Microsoft Corporation. Durante sua carreira na Microsoft, Gates ocupou os cargos de presidente, diretor executivo (CEO), presidente e arquiteto-chefe de software, sendo também o maior acionista individual até maio de 2014. Ele é um dos empreendedores mais conhecidos e pioneiros da revolução dos microcomputadores das décadas de 1970 e 1980. Nascido e criado em Seattle, Washington, Gates co-fundou a Microsoft com seu amigo de infância Paul Allen em 1975, em Albuquerque, Novo México; tornou-se a maior empresa de software para computadores pessoais do mundo. Gates liderou a empresa como presidente e CEO até renunciar como CEO em janeiro de 2000, mas permaneceu como presidente e tornou-se arquiteto-chefe de software. No final dos anos 1990, Gates foi criticado por suas táticas comerciais, consideradas anticompetitivas. Esta opinião foi confirmada por várias decisões judiciais. Em junho de 2006, Gates anunciou que passaria para um papel de meio período na Microsoft e trabalho em tempo integral na Fundação Bill & Melinda Gates, a fundação de caridade privada que ele e sua esposa Melinda Gates estabeleceram em 2000. Ele transferiu gradualmente suas responsabilidades para Ray Ozzie e Craig Mundie. Ele renunciou como presidente da Microsoft em fevereiro de 2014 e assumiu um novo cargo como conselheiro de tecnologia para apoiar o recém-nomeado CEO Satya Nadella.",
|
121 |
+
"A Mona Lisa é uma pintura a óleo do século XVI criada por Leonardo. Está exposta no Louvre, em Paris.",
|
122 |
+
"Quando Sebastian Thrun começou a trabalhar em carros autônomos na Google em 2007, poucas pessoas fora da empresa o levaram a sério. 'Posso dizer que CEOs muito importantes de grandes empresas automobilísticas americanas apertavam minha mão e se afastavam porque não valia a pena conversar comigo', disse Thrun, agora co-fundador e CEO da startup de educação superior online Udacity, em uma entrevista com o Recode no início desta semana.",
|
123 |
+
"O Facebook é um serviço de rede social lançado como TheFacebook em 4 de fevereiro de 2004. Foi fundado por Mark Zuckerberg com seus colegas de quarto e colegas de Harvard Eduardo Saverin, Andrew McCollum, Dustin Moskovitz e Chris Hughes. A adesão ao site inicialmente era limitada aos estudantes de Harvard, mas foi expandida para outras faculdades na área de Boston, a Ivy League e gradualmente para a maioria das universidades nos Estados Unidos e Canadá.",
|
124 |
+
"A história do processamento de linguagem natural geralmente começou na década de 1950, embora o trabalho possa ser encontrado em períodos anteriores. Em 1950, Alan Turing publicou um artigo intitulado 'Computing Machinery and Intelligence', que propunha o que agora é chamado de teste de Turing como critério de inteligência.",
|
125 |
+
"Geoffrey Everest Hinton é um psicólogo cognitivo e cientista da computação inglês-canadense, mais conhecido por seu trabalho em redes neurais artificiais. Desde 2013, ele divide seu tempo trabalhando para o Google e a Universidade de Toronto. Em 2017, ele co-fundou e tornou-se o Conselheiro Científico Chefe do Instituto Vector em Toronto.",
|
126 |
+
"Quando eu disse a John que queria me mudar para o Alasca, ele me avisou que eu teria dificuldade em encontrar um Starbucks lá.",
|
127 |
+
"Steven Paul Jobs foi um magnata dos negócios americano, designer industrial, investidor e proprietário de mídia. Ele foi presidente, diretor executivo (CEO) e co-fundador da Apple Inc., presidente e acionista majoritário da Pixar, membro do conselho administrativo da The Walt Disney Company após sua aquisição da Pixar, e fundador, presidente e CEO da NeXT. Jobs é amplamente reconhecido como um pioneiro da revolução do computador pessoal das décadas de 1970 e 1980, junto com o co-fundador da Apple, Steve Wozniak. Jobs nasceu em São Francisco, Califórnia, e foi colocado para adoção. Ele cresceu na área da Baía de São Francisco. Ele frequentou a Reed College em 1972 antes de abandonar o mesmo ano e viajar pela Índia em 1974 em busca de iluminação e estudar o budismo zen.",
|
128 |
+
"Titanic é um filme épico americano de romance e desastre de 1997 dirigido, escrito, co-produzido e co-editado por James Cameron. Incorporando aspectos tanto históricos quanto ficcionais, é baseado em relatos do naufrágio do RMS Titanic, e estrelado por Leonardo DiCaprio e Kate Winslet como membros de diferentes classes sociais que se apaixonam a bordo do navio durante sua malfadada viagem inaugural.",
|
129 |
+
"Além de ser o rei do norte, John Snow é um médico inglês e um líder no desenvolvimento da anestesia e higiene médica. Ele é considerado o primeiro a usar dados para curar o surto de cólera em 1834."
|
130 |
+
]
|
131 |
+
|
132 |
+
selected_text = st.selectbox("Select an example", examples)
|
133 |
+
custom_input = st.text_input("Try it with your own Sentence!")
|
134 |
+
|
135 |
+
text_to_analyze = custom_input if custom_input else selected_text
|
136 |
+
|
137 |
+
st.subheader('Full example text')
|
138 |
+
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>"""
|
139 |
+
st.markdown(HTML_WRAPPER.format(text_to_analyze), unsafe_allow_html=True)
|
140 |
+
|
141 |
+
# Initialize Spark and create pipeline
|
142 |
+
spark = init_spark()
|
143 |
+
pipeline = create_pipeline(model)
|
144 |
+
output = fit_data(pipeline, text_to_analyze)
|
145 |
+
|
146 |
+
# Display matched sentence
|
147 |
+
st.subheader("Processed output:")
|
148 |
+
|
149 |
+
results = {
|
150 |
+
'Document': output[0]['document'][0].result,
|
151 |
+
'NER Chunk': [n.result for n in output[0]['ner_chunk']],
|
152 |
+
"NER Label": [n.metadata['entity'] for n in output[0]['ner_chunk']]
|
153 |
+
}
|
154 |
+
|
155 |
+
annotate(results)
|
156 |
+
|
157 |
+
with st.expander("View DataFrame"):
|
158 |
+
df = pd.DataFrame({'NER Chunk': results['NER Chunk'], 'NER Label': results['NER Label']})
|
159 |
+
df.index += 1
|
160 |
+
st.dataframe(df)
|
161 |
+
|
Dockerfile
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
9 |
+
# Install required packages
|
10 |
+
RUN apt-get update && apt-get install -y \
|
11 |
+
tar \
|
12 |
+
wget \
|
13 |
+
bash \
|
14 |
+
rsync \
|
15 |
+
gcc \
|
16 |
+
libfreetype6-dev \
|
17 |
+
libhdf5-serial-dev \
|
18 |
+
libpng-dev \
|
19 |
+
libzmq3-dev \
|
20 |
+
python3 \
|
21 |
+
python3-dev \
|
22 |
+
python3-pip \
|
23 |
+
unzip \
|
24 |
+
pkg-config \
|
25 |
+
software-properties-common \
|
26 |
+
graphviz \
|
27 |
+
openjdk-8-jdk \
|
28 |
+
ant \
|
29 |
+
ca-certificates-java \
|
30 |
+
&& apt-get clean \
|
31 |
+
&& update-ca-certificates -f;
|
32 |
+
|
33 |
+
# Install Python 3.8 and pip
|
34 |
+
RUN add-apt-repository ppa:deadsnakes/ppa \
|
35 |
+
&& apt-get update \
|
36 |
+
&& apt-get install -y python3.8 python3-pip \
|
37 |
+
&& apt-get clean;
|
38 |
+
|
39 |
+
# Set up JAVA_HOME
|
40 |
+
ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64/
|
41 |
+
RUN mkdir -p ${HOME} \
|
42 |
+
&& echo "export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/" >> ${HOME}/.bashrc \
|
43 |
+
&& chown -R ${NB_UID}:${NB_UID} ${HOME}
|
44 |
+
|
45 |
+
# Create a new user named "jovyan" with user ID 1000
|
46 |
+
RUN useradd -m -u ${NB_UID} ${NB_USER}
|
47 |
+
|
48 |
+
# Switch to the "jovyan" user
|
49 |
+
USER ${NB_USER}
|
50 |
+
|
51 |
+
# Set home and path variables for the user
|
52 |
+
ENV HOME=/home/${NB_USER} \
|
53 |
+
PATH=/home/${NB_USER}/.local/bin:$PATH
|
54 |
+
|
55 |
+
# Set the working directory to the user's home directory
|
56 |
+
WORKDIR ${HOME}
|
57 |
+
|
58 |
+
# Upgrade pip and install Python dependencies
|
59 |
+
RUN python3.8 -m pip install --upgrade pip
|
60 |
+
COPY requirements.txt /tmp/requirements.txt
|
61 |
+
RUN python3.8 -m pip install -r /tmp/requirements.txt
|
62 |
+
|
63 |
+
# Copy the application code into the container at /home/jovyan
|
64 |
+
COPY --chown=${NB_USER}:${NB_USER} . ${HOME}
|
65 |
+
|
66 |
+
# Expose port for Streamlit
|
67 |
+
EXPOSE 7860
|
68 |
+
|
69 |
+
# Define the entry point for the container
|
70 |
+
ENTRYPOINT ["streamlit", "run", "Demo.py", "--server.port=7860", "--server.address=0.0.0.0"]
|
pages/Workflow & Model Overview.py
ADDED
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
|
3 |
+
# Custom CSS for better styling
|
4 |
+
st.markdown("""
|
5 |
+
<style>
|
6 |
+
.main-title {
|
7 |
+
font-size: 36px;
|
8 |
+
color: #4A90E2;
|
9 |
+
font-weight: bold;
|
10 |
+
text-align: center;
|
11 |
+
}
|
12 |
+
.sub-title {
|
13 |
+
font-size: 24px;
|
14 |
+
color: #4A90E2;
|
15 |
+
margin-top: 20px;
|
16 |
+
}
|
17 |
+
.section {
|
18 |
+
background-color: #f9f9f9;
|
19 |
+
padding: 15px;
|
20 |
+
border-radius: 10px;
|
21 |
+
margin-top: 20px;
|
22 |
+
}
|
23 |
+
.section h2 {
|
24 |
+
font-size: 22px;
|
25 |
+
color: #4A90E2;
|
26 |
+
}
|
27 |
+
.section p, .section ul {
|
28 |
+
color: #666666;
|
29 |
+
}
|
30 |
+
.link {
|
31 |
+
color: #4A90E2;
|
32 |
+
text-decoration: none;
|
33 |
+
}
|
34 |
+
</style>
|
35 |
+
""", unsafe_allow_html=True)
|
36 |
+
|
37 |
+
# Main Title
|
38 |
+
st.markdown('<div class="main-title">State-of-the-Art Named Entity Recognition with Spark NLP (Spanish)</div>', unsafe_allow_html=True)
|
39 |
+
|
40 |
+
# Introduction
|
41 |
+
st.markdown("""
|
42 |
+
<div class="section">
|
43 |
+
<p>Named Entity Recognition (NER) is the task of identifying important words in a text and associating them with a category. For example, we may be interested in finding all the personal names in documents, or company names in news articles. Other examples include domain-specific uses such as identifying all disease names in a clinical text, or company trading codes in financial ones.</p>
|
44 |
+
<p>NER can be implemented with many approaches. In this post, we introduce a deep learning-based method using the NerDL model. This approach leverages the scalability of Spark NLP with Python.</p>
|
45 |
+
</div>
|
46 |
+
""", unsafe_allow_html=True)
|
47 |
+
|
48 |
+
# Introduction to Spark NLP
|
49 |
+
st.markdown('<div class="sub-title">Introduction to Spark NLP</div>', unsafe_allow_html=True)
|
50 |
+
st.markdown("""
|
51 |
+
<div class="section">
|
52 |
+
<p>Spark NLP is an open-source library maintained by John Snow Labs. It is built on top of Apache Spark and Spark ML and provides simple, performant & accurate NLP annotations for machine learning pipelines that can scale easily in a distributed environment.</p>
|
53 |
+
<p>To install Spark NLP, you can simply use any package manager like conda or pip. For example, using pip you can simply run <code>pip install spark-nlp</code>. For different installation options, check the official <a href="https://nlp.johnsnowlabs.com/docs/en/install" target="_blank" class="link">documentation</a>.</p>
|
54 |
+
</div>
|
55 |
+
""", unsafe_allow_html=True)
|
56 |
+
|
57 |
+
# Using NerDL Model
|
58 |
+
st.markdown('<div class="sub-title">Using NerDL Model</div>', unsafe_allow_html=True)
|
59 |
+
st.markdown("""
|
60 |
+
<div class="section">
|
61 |
+
<p>The NerDL model in Spark NLP is a deep learning-based approach for NER tasks. It uses a Char CNNs - BiLSTM - CRF architecture that achieves state-of-the-art results in most datasets. The training data should be a labeled Spark DataFrame in the format of CoNLL 2003 IOB with annotation type columns.</p>
|
62 |
+
</div>
|
63 |
+
""", unsafe_allow_html=True)
|
64 |
+
|
65 |
+
# Setup Instructions
|
66 |
+
st.markdown('<div class="sub-title">Setup</div>', unsafe_allow_html=True)
|
67 |
+
st.markdown('<p>To install Spark NLP in Python, use your favorite package manager (conda, pip, etc.). For example:</p>', unsafe_allow_html=True)
|
68 |
+
st.code("""
|
69 |
+
pip install spark-nlp
|
70 |
+
pip install pyspark
|
71 |
+
""", language="bash")
|
72 |
+
|
73 |
+
st.markdown("<p>Then, import Spark NLP and start a Spark session:</p>", unsafe_allow_html=True)
|
74 |
+
st.code("""
|
75 |
+
import sparknlp
|
76 |
+
|
77 |
+
# Start Spark Session
|
78 |
+
spark = sparknlp.start()
|
79 |
+
""", language='python')
|
80 |
+
|
81 |
+
# Example Usage with NerDL Model in Italian
|
82 |
+
st.markdown('<div class="sub-title">Example Usage with NerDL Model in portuguese</div>', unsafe_allow_html=True)
|
83 |
+
st.markdown("""
|
84 |
+
<div class="section">
|
85 |
+
<p>Below is an example of how to set up and use the NerDL model for named entity recognition in portuguese:</p>
|
86 |
+
</div>
|
87 |
+
""", unsafe_allow_html=True)
|
88 |
+
st.code('''
|
89 |
+
from sparknlp.base import *
|
90 |
+
from sparknlp.annotator import *
|
91 |
+
from pyspark.ml import Pipeline
|
92 |
+
from pyspark.sql.functions import col, expr, round, concat, lit
|
93 |
+
|
94 |
+
# Document Assembler
|
95 |
+
document_assembler = DocumentAssembler() \\
|
96 |
+
.setInputCol("text") \\
|
97 |
+
.setOutputCol("document")
|
98 |
+
|
99 |
+
# Tokenizer
|
100 |
+
tokenizer = Tokenizer() \\
|
101 |
+
.setInputCols(["document"]) \\
|
102 |
+
.setOutputCol("token")
|
103 |
+
|
104 |
+
# Word Embeddings
|
105 |
+
embeddings = WordEmbeddingsModel.pretrained('glove_840B_300', lang='xx') \\
|
106 |
+
.setInputCols(["document", "token"]) \\
|
107 |
+
.setOutputCol("embeddings")
|
108 |
+
|
109 |
+
# NerDL Model
|
110 |
+
ner_model = NerDLModel.pretrained('ner_wikiner_glove_840B_300', 'xx') \\
|
111 |
+
.setInputCols(["document", "token", "embeddings"]) \\
|
112 |
+
.setOutputCol("ner")
|
113 |
+
|
114 |
+
# NER Converter
|
115 |
+
ner_converter = NerConverter() \\
|
116 |
+
.setInputCols(["document", "token", "ner"]) \\
|
117 |
+
.setOutputCol("ner_chunk")
|
118 |
+
|
119 |
+
# Pipeline
|
120 |
+
pipeline = Pipeline(stages=[
|
121 |
+
document_assembler,
|
122 |
+
tokenizer,
|
123 |
+
embeddings,
|
124 |
+
ner_model,
|
125 |
+
ner_converter
|
126 |
+
])
|
127 |
+
|
128 |
+
# Example sentence
|
129 |
+
example = """
|
130 |
+
A cidade de Lisboa, capital de Portugal, é uma das mais antigas do mundo. Com uma história rica que remonta a mais de três mil anos, Lisboa tem sido um importante centro cultural, econômico e político na Europa. A cidade é famosa por seus bairros históricos, como Alfama, Bairro Alto e Belém.
|
131 |
+
Fernando Pessoa, um dos maiores poetas da língua portuguesa, nasceu em Lisboa em 1888. Sua obra é amplamente estudada e apreciada tanto em Portugal quanto internacionalmente. Outro escritor famoso, José Saramago, vencedor do Prêmio Nobel de Literatura, também tem fortes ligações com a cidade.
|
132 |
+
O Rio Tejo atravessa Lisboa, criando uma bela paisagem que atrai turistas de todo o mundo. Perto do rio, encontra-se a Torre de Belém, uma das atrações turísticas mais visitadas da cidade. Este monumento é um símbolo da Era dos Descobrimentos de Portugal.
|
133 |
+
Em termos econômicos, Lisboa é o maior centro financeiro de Portugal. Muitas empresas multinacionais têm escritórios na cidade, como a Microsoft, a Google e a Nestlé. Além disso, Lisboa é sede de várias startups de tecnologia, beneficiando-se de um ambiente empreendedor vibrante.
|
134 |
+
A educação também é uma área importante em Lisboa. A cidade abriga algumas das melhores universidades do país, incluindo a Universidade de Lisboa e a Universidade Nova de Lisboa. Estas instituições são conhecidas por sua pesquisa de ponta e por formar alguns dos profissionais mais qualificados de Portugal.
|
135 |
+
No mundo do esporte, o Sport Lisboa e Benfica e o Sporting Clube de Portugal são os dois principais clubes de futebol da cidade. Ambos têm uma longa história de sucesso em competições nacionais e internacionais. O estádio do Benfica, o Estádio da Luz, é um dos maiores e mais modernos de Portugal.
|
136 |
+
Lisboa também é conhecida por sua gastronomia. Pratos tradicionais como o bacalhau à brás e os pastéis de nata são famosos em todo o país e no mundo. Os mercados de alimentos, como o Mercado da Ribeira, oferecem uma variedade de produtos frescos e pratos típicos que refletem a rica cultura culinária da cidade.
|
137 |
+
Além disso, eventos culturais, como o Festival de Fado e a Festa de Santo António, atraem milhares de visitantes todos os anos. Estes eventos celebram a música, a dança e as tradições populares de Lisboa, reforçando o papel da cidade como um importante centro cultural.
|
138 |
+
Recentemente, Lisboa tem se destacado como um destino turístico de primeira linha. A cidade foi eleita várias vezes como o "Melhor Destino Europeu" pelos World Travel Awards. Suas belas paisagens, clima agradável e rica herança cultural fazem de Lisboa um destino imperdível para viajantes de todo o mundo.
|
139 |
+
"""
|
140 |
+
data = spark.createDataFrame([[example]]).toDF("text")
|
141 |
+
|
142 |
+
# Transforming data
|
143 |
+
result = pipeline.fit(data).transform(data)
|
144 |
+
|
145 |
+
# Select the result, entity, and confidence columns
|
146 |
+
result.select(
|
147 |
+
expr("explode(ner_chunk) as ner_chunk")
|
148 |
+
).select(
|
149 |
+
col("ner_chunk.result").alias("result"),
|
150 |
+
col("ner_chunk.metadata").getItem("entity").alias("entity"),
|
151 |
+
concat(
|
152 |
+
round((col("ner_chunk.metadata").getItem("confidence").cast("float") * 100), 2),
|
153 |
+
lit("%")
|
154 |
+
).alias("confidence")
|
155 |
+
).show(truncate=False)
|
156 |
+
''', language="python")
|
157 |
+
|
158 |
+
st.text("""
|
159 |
+
+--------------------------+------+----------+
|
160 |
+
|result |entity|confidence|
|
161 |
+
+--------------------------+------+----------+
|
162 |
+
|Lisboa |LOC |88.48% |
|
163 |
+
|Portugal |LOC |90.64% |
|
164 |
+
|Lisboa |LOC |99.55% |
|
165 |
+
|Europa |LOC |97.55% |
|
166 |
+
|Alfama |LOC |96.97% |
|
167 |
+
|Bairro Alto |LOC |76.44% |
|
168 |
+
|Belém |LOC |95.85% |
|
169 |
+
|Fernando Pessoa |LOC |77.32% |
|
170 |
+
|Lisboa |LOC |94.97% |
|
171 |
+
|Portugal |LOC |90.94% |
|
172 |
+
|José Saramago |PER |73.39% |
|
173 |
+
|Prêmio Nobel de Literatura|MISC |47.64% |
|
174 |
+
|Rio Tejo |LOC |73.64% |
|
175 |
+
|Lisboa |LOC |96.04% |
|
176 |
+
|Perto |LOC |88.33% |
|
177 |
+
|Torre de Belém |LOC |80.21% |
|
178 |
+
|Era dos Descobrimentos |LOC |63.05% |
|
179 |
+
|Portugal |LOC |72.65% |
|
180 |
+
|Lisboa |LOC |99.28% |
|
181 |
+
|Portugal |LOC |88.78% |
|
182 |
+
+--------------------------+------+----------+
|
183 |
+
""")
|
184 |
+
|
185 |
+
# Benchmark Section
|
186 |
+
st.markdown('<div class="sub-title">Benchmark</div>', unsafe_allow_html=True)
|
187 |
+
st.markdown("""
|
188 |
+
<div class="section">
|
189 |
+
<p>Evaluating the performance of NER models is crucial to understanding their effectiveness in real-world applications. Below are the benchmark results for the "ner_wikiner_glove_840B_300" model on <strong>portuguese</strong> text, focusing on various named entity categories. The metrics used include precision, recall, and F1-score, which are standard for evaluating classification models.</p>
|
190 |
+
</div>
|
191 |
+
""", unsafe_allow_html=True)
|
192 |
+
st.markdown("""
|
193 |
+
---
|
194 |
+
#### Classification Report
|
195 |
+
|
196 |
+
| Label | Precision | Recall | F1-Score | Support |
|
197 |
+
|-------|-----------|--------|----------|---------|
|
198 |
+
| B-LOC | 0.91 | 0.94 | 0.92 | 14818 |
|
199 |
+
| I-ORG | 0.84 | 0.74 | 0.79 | 1705 |
|
200 |
+
| I-LOC | 0.89 | 0.88 | 0.89 | 8354 |
|
201 |
+
| I-PER | 0.94 | 0.93 | 0.93 | 4338 |
|
202 |
+
| B-ORG | 0.90 | 0.77 | 0.83 | 2351 |
|
203 |
+
| B-PER | 0.92 | 0.93 | 0.93 | 6398 |
|
204 |
+
|
205 |
+
#### Averages
|
206 |
+
|
207 |
+
| Metric | Precision | Recall | F1-Score | Support |
|
208 |
+
|----------------|-----------|--------|----------|---------|
|
209 |
+
| Micro Average | 0.90 | 0.90 | 0.90 | 37964 |
|
210 |
+
| Macro Average | 0.90 | 0.87 | 0.88 | 37964 |
|
211 |
+
| Weighted Avg | 0.90 | 0.90 | 0.90 | 37964 |
|
212 |
+
|
213 |
+
#### Overall Metrics
|
214 |
+
|
215 |
+
- Processed 348,966 tokens with 26,513 phrases; found: 26,359 phrases; correct: 23,574.
|
216 |
+
- Accuracy (non-O): **88.48%**
|
217 |
+
- Overall Accuracy: **98.39%**
|
218 |
+
- Precision: **89.43%**
|
219 |
+
- Recall: **88.91%**
|
220 |
+
- F1 Score: **89.17**
|
221 |
+
|
222 |
+
#### Entity-Specific Metrics
|
223 |
+
|
224 |
+
| Entity | Precision | Recall | F1-Score | Instances |
|
225 |
+
|--------|-----------|--------|----------|-----------|
|
226 |
+
| LOC | 89.52% | 92.60% | 91.04 | 15328 |
|
227 |
+
| MISC | 84.55% | 72.47% | 78.05 | 2525 |
|
228 |
+
| ORG | 88.53% | 75.84% | 81.70 | 2014 |
|
229 |
+
| PER | 91.40% | 92.75% | 92.07 | 6492 |
|
230 |
+
---
|
231 |
+
""", unsafe_allow_html=True)
|
232 |
+
|
233 |
+
# Summary
|
234 |
+
st.markdown('<div class="sub-title">Summary</div>', unsafe_allow_html=True)
|
235 |
+
st.markdown("""
|
236 |
+
<div class="section">
|
237 |
+
<p>In this article, we discussed named entity recognition using a deep learning-based method with the "wikiner_840B_300" model for Italian. We introduced how to perform the task using the open-source Spark NLP library with Python, which can be used at scale in the Spark ecosystem. These methods can be used for natural language processing applications in various fields, including finance and healthcare.</p>
|
238 |
+
</div>
|
239 |
+
""", unsafe_allow_html=True)
|
240 |
+
|
241 |
+
# References
|
242 |
+
st.markdown('<div class="sub-title">References</div>', unsafe_allow_html=True)
|
243 |
+
st.markdown("""
|
244 |
+
<div class="section">
|
245 |
+
<ul>
|
246 |
+
<li><a class="link" href="https://sparknlp.org/api/python/reference/autosummary/sparknlp/annotator/ner/ner_dl/index.html" target="_blank" rel="noopener">NerDLModel</a> annotator documentation</li>
|
247 |
+
<li>Model Used: <a class="link" href="https://sparknlp.org/2021/07/19/ner_wikiner_glove_840B_300_xx.html" target="_blank" rel="noopener">ner_wikiner_glove_840B_300</a></li>
|
248 |
+
<li><a class="link" href="https://nlp.johnsnowlabs.com/recognize_entitie" target="_blank" rel="noopener">Visualization demos for NER in Spark NLP</a></li>
|
249 |
+
<li><a class="link" href="https://www.johnsnowlabs.com/named-entity-recognition-ner-with-bert-in-spark-nlp/">Named Entity Recognition (NER) with BERT in Spark NLP</a></li>
|
250 |
+
</ul>
|
251 |
+
</div>
|
252 |
+
""", unsafe_allow_html=True)
|
253 |
+
|
254 |
+
# Community & Support
|
255 |
+
st.markdown('<div class="sub-title">Community & Support</div>', unsafe_allow_html=True)
|
256 |
+
st.markdown("""
|
257 |
+
<div class="section">
|
258 |
+
<ul>
|
259 |
+
<li><a class="link" href="https://sparknlp.org/" target="_blank">Official Website</a>: Documentation and examples</li>
|
260 |
+
<li><a class="link" href="https://join.slack.com/t/spark-nlp/shared_invite/zt-198dipu77-L3UWNe_AJf4Rqb3DaMb-7A" target="_blank">Slack Community</a>: Connect with other Spark NLP users</li>
|
261 |
+
<li><a class="link" href="https://github.com/JohnSnowLabs/spark-nlp" target="_blank">GitHub Repository</a>: Source code and issue tracker</li>
|
262 |
+
</ul>
|
263 |
+
</div>
|
264 |
+
""", unsafe_allow_html=True)
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit
|
2 |
+
st-annotated-text
|
3 |
+
pandas
|
4 |
+
numpy
|
5 |
+
spark-nlp
|
6 |
+
pyspark
|