Korean-NER / Demo.py
abdullahmubeen10's picture
Upload 5 files
4c983c8 verified
raw
history blame
6.39 kB
import streamlit as st
import sparknlp
import os
import pandas as pd
from sparknlp.base import *
from sparknlp.annotator import *
from pyspark.ml import Pipeline
from sparknlp.pretrained import PretrainedPipeline
from annotated_text import annotated_text
# Page configuration
st.set_page_config(
layout="wide",
initial_sidebar_state="auto"
)
# CSS for styling
st.markdown("""
<style>
.main-title {
font-size: 36px;
color: #4A90E2;
font-weight: bold;
text-align: center;
}
.section {
background-color: #f9f9f9;
padding: 10px;
border-radius: 10px;
margin-top: 10px;
}
.section p, .section ul {
color: #666666;
}
</style>
""", unsafe_allow_html=True)
@st.cache_resource
def init_spark():
return sparknlp.start()
@st.cache_resource
def create_pipeline(model):
document_assembler = DocumentAssembler() \
.setInputCol("text") \
.setOutputCol("document")
sentence_detector = SentenceDetector() \
.setInputCols(["document"]) \
.setOutputCol("sentence")
word_segmenter = WordSegmenterModel.pretrained("wordseg_kaist_ud", "ko") \
.setInputCols(["sentence"]) \
.setOutputCol("token")
embeddings = WordEmbeddingsModel.pretrained("glove_840B_300", "xx") \
.setInputCols(["document", "token"]) \
.setOutputCol("embeddings")
ner = NerDLModel.pretrained("ner_kmou_glove_840B_300d", "ko") \
.setInputCols(["document", "token", "embeddings"]) \
.setOutputCol("ner")
ner_converter = NerConverter().setInputCols(["document", "token", "ner"]).setOutputCol("ner_chunk")
pipeline = Pipeline(stages=[document_assembler, sentence_detector, word_segmenter, embeddings, ner, ner_converter])
return nlpPipeline
def fit_data(pipeline, data):
empty_df = spark.createDataFrame([['']]).toDF('text')
pipeline_model = pipeline.fit(empty_df)
model = LightPipeline(pipeline_model)
result = model.fullAnnotate(data)
return result
def annotate(data):
document, chunks, labels = data["Document"], data["NER Chunk"], data["NER Label"]
annotated_words = []
for chunk, label in zip(chunks, labels):
parts = document.split(chunk, 1)
if parts[0]:
annotated_words.append(parts[0])
annotated_words.append((chunk, label))
document = parts[1]
if document:
annotated_words.append(document)
annotated_text(*annotated_words)
# Set up the page layout
st.markdown('<div class="main-title">Recognize entities in Urdu text</div>', unsafe_allow_html=True)
st.markdown("""
<div class="section">
<p>This model uses the pre-trained <code>glove_840B_300</code> embeddings model from WordEmbeddings annotator as an input</p>
</div>
""", unsafe_allow_html=True)
# Sidebar content
model = st.sidebar.selectbox(
"Choose the pretrained model",
["ner_kmou_glove_840B_300d"],
help="For more info about the models visit: https://sparknlp.org/models"
)
# Reference notebook link in sidebar
link = """
<a href="https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/public/NER_KO.ipynb">
<img src="https://colab.research.google.com/assets/colab-badge.svg" style="zoom: 1.3" alt="Open In Colab"/>
</a>
"""
st.sidebar.markdown('Reference notebook:')
st.sidebar.markdown(link, unsafe_allow_html=True)
# Load examples
examples = [
"""ARD , ZDF λ“± 곡영 TV 와 바이에λ₯Έμ£Ό 방솑 , 뢁뢀 독일 방솑 λ“± 은 이 λ‚  ν•œκ΅­ 의 총선 μ†Œμ‹ κ³Ό κ΄€λ ¨ , μ—¬λ‹Ή 의 과반수 μ˜μ„ 확보 와 μ‹ λ‹Ή 의 λ“ν‘œ 율 이 이번 μ„ κ±° 의 μ΅œλŒ€ 관심사 이 라고 보도 ν•˜ γ„΄ 데 μž‡ μ–΄ 저녁 μ‹œκ°„ λΆ€ν„° λŠ” 수 μ°¨λ‘€ 에 걸치 μ–΄ κ°œν‘œ 상황 κ³Ό μ •λ‹Ή 별 μ˜μ„ 전망 을 속보 둜 μ „ν•˜ μ•˜ λ‹€ .""",
"""두 λ‚˜λΌ 관계 λŠ” 쀑ꡭ 의 인ꢌ 문제 와 ν•΅ν™•μ‚° λ°©μ§€ 문제 , 톡상 문제 및 졜근 의 F 16 μ „νˆ¬κΈ° λŒ€ λŒ€λ§Œ 판맀 λ“± 을 놓 κ³  이미 μœ„ν—˜μ„  상 에 였 μ•„ 있 λŠ”λ° 클린턴 ν–‰μ •λΆ€ 의 λ“±μž₯ 으둜 μ–‘κ΅­ 관계 κ°€ λ”μš± 경색 되 γ„Ή 것 을 κ±±μ • ν•˜ λŠ” λΆ„μœ„κΈ° .""",
"""μ„œμšΈλŒ€ 건좕곡학 κ³Ό λ₯Ό μ‘Έμ—… ν•˜ γ„΄ 이 씨 λŠ” ν•œκ΅­κ±΄μΆ•κ°€ν˜‘νšŒ""",
"""λ‚˜ λŠ” λ‹€μ‹œ 순자 λ₯Ό 양동 μ—μ„œ λΉΌλ‚΄ κΈ° μœ„ν•˜ μ•„μ„œ μ°½μ‹  νŒ”λ™""",
"""헀라신전 μ„œ 채화 되 γ„΄ μ§€ 보름 , 지ꡬ 의 λ°˜λ°”ν€΄ λ₯Ό 돌 μ•„ μ œμ£Όκ³΅ν•­ 에 첫발 을 λ‚΄λ””λ”” γ„΄ 이래 둜 열이틀""",
"""λ‹€μŒ 은 홍콩 의 κΆŒμœ„μ§€ λͺ…보 와 일본 도쿄 ( 동경 ) μ‹ λ¬Έ 이 24일""",
"""졜 μ˜μ‚¬ κ°€ 우리 외ꡐ관 이 λ©° κ·Έ μ‹ λ³€λ³΄ν˜Έ μ±…μž„ 이 주재ꡭ 이 γ„΄ λŸ¬μ‹œμ•„ 에 있 λ‹€λŠ” 점 μ—μ„œ λŸ¬μ‹œμ•„ λŠ” 이 κ°™ 은 우리 μ •λΆ€ μš”κ΅¬ 에 μ‘ν•˜ μ•„μ•Ό ν•˜ γ„Ή 의무 κ°€ 있 λ‹€ .""",
"""판 에 λ°• 은 λ“― ν•˜ γ„΄ 깨끗 ν•˜ γ„΄ 글씨 둜 , 처음 단ꡰ λ‹˜ 이 λ‹ˆ 신라 , 백제 , 고ꡬ렀 이 λ‹ˆ 띄엄띄엄 μ–΄λ₯Έ λ“€ ν•œν…Œ μ„œ κ·€κ²° 둜 λ“€μ–΄μ˜€ 던 μ–˜κΈ° λ“€ 이 참말 둜 μ”Œ μ–΄ 있 μ—ˆ λ‹€ ."""
]
selected_text = st.selectbox("Select an example", examples)
custom_input = st.text_input("Try it with your own Sentence!")
text_to_analyze = custom_input if custom_input else selected_text
st.subheader('Full example text')
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>"""
st.markdown(HTML_WRAPPER.format(text_to_analyze), unsafe_allow_html=True)
# Initialize Spark and create pipeline
spark = init_spark()
pipeline = create_pipeline(model)
output = fit_data(pipeline, text_to_analyze)
# Display matched sentence
st.subheader("Processed output:")
results = {
'Document': output[0]['document'][0].result,
'NER Chunk': [n.result for n in output[0]['ner_chunk']],
"NER Label": [n.metadata['entity'] for n in output[0]['ner_chunk']]
}
annotate(results)
with st.expander("View DataFrame"):
df = pd.DataFrame({'NER Chunk': results['NER Chunk'], 'NER Label': results['NER Label']})
df.index += 1
st.dataframe(df)