File size: 22,396 Bytes
50f4414 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
import streamlit as st
import sparknlp
import pandas as pd
from sparknlp.base import *
from sparknlp.annotator import *
from pyspark.ml import Pipeline
from annotated_text import annotated_text
from streamlit_tags import st_tags
# 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_name, task):
document_assembler = DocumentAssembler().setInputCol('text').setOutputCol('document')
tokenizer = Tokenizer().setInputCols(['document']).setOutputCol('token')
if task == "Token Classification":
token_classifier = LongformerForTokenClassification \
.pretrained('longformer_base_token_classifier_conll03', 'en') \
.setInputCols(['token', 'document']) \
.setOutputCol('ner') \
.setCaseSensitive(False) \
.setMaxSentenceLength(512)
ner_converter = NerConverter() \
.setInputCols(['document', 'token', 'ner']) \
.setOutputCol('entities')
pipeline = Pipeline(stages=[document_assembler, tokenizer, token_classifier, ner_converter])
return pipeline
elif task == "Sequence Classification":
sequence_classifier = LongformerForSequenceClassification \
.pretrained(model_name, 'en') \
.setInputCols(['token', 'document']) \
.setOutputCol('class') \
.setCaseSensitive(False) \
.setMaxSentenceLength(1024)
pipeline = Pipeline(stages=[document_assembler, tokenizer, sequence_classifier])
return pipeline
elif task == "Question Answering":
document_assembler = MultiDocumentAssembler() \
.setInputCols(["question", "context"]) \
.setOutputCols(["document_question", "document_context"])
span_classifier = LongformerForQuestionAnswering.pretrained("longformer_base_base_qa_squad2", "en") \
.setInputCols(["document_question", "document_context"]) \
.setOutputCol("answer")\
.setCaseSensitive(True)
pipeline = Pipeline(stages=[document_assembler, span_classifier])
return pipeline
def fit_data(pipeline, task, data, question=None, context=None):
if task in ['Token Classification', 'Sequence Classification']:
empty_df = spark.createDataFrame([['']]).toDF('text')
pipeline_model = pipeline.fit(empty_df)
model = LightPipeline(pipeline_model)
result = model.fullAnnotate(data)
return result
elif task == "Question Answering":
df = spark.createDataFrame([[question, context]]).toDF("question", "context")
result = pipeline.fit(df).transform(df)
result = result.select('answer.result').collect()
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)
tasks_models_descriptions = {
"Token Classification": {
"models": ["longformer_base_token_classifier_conll03"],
"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."
},
"Sequence Classification": {
"models": ["longformer_base_sequence_classifier_imdb", "longformer_base_sequence_classifier_ag_news"],
"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."
},
"Question Answering": {
"models": ["longformer_base_base_qa_squad2"],
"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."
}
}
# Sidebar content
task = st.sidebar.selectbox("Choose the task", list(tasks_models_descriptions.keys()))
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")
# Reference notebook link in sidebar
colab_link = """
<a href="https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/331849cae5215e58757e5f2313ccefc5fd30ac32/Spark_NLP_Udemy_MOOC/Open_Source/17.01.Transformers-based_Embeddings.ipynb#L106">
<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(colab_link, unsafe_allow_html=True)
# Page content
st.markdown(f'<div class="main-title">Longformer for {task}</div>', unsafe_allow_html=True)
st.write(tasks_models_descriptions[task]["description"])
if model == 'longformer_base_sequence_classifier_ag_news':
examples_to_select = [
"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.",
"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.",
"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.",
"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.",
"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.",
"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.",
"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.",
"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.",
"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.",
"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.",
"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.",
"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."
]
else:
examples_to_select = [
"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.",
"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.",
"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!",
"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.",
"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.",
"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.",
"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.",
"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.",
"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."
]
# Load examples
examples_mapping = {
"Token Classification": [
"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.",
"The Mona Lisa is a 16th century oil painting created by Leonardo. It's held at the Louvre in Paris.",
"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.",
"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.",
"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",
"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.",
"When I told John that I wanted to move to Alaska, he warned me that I'd have trouble finding a Starbucks there.",
"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.",
"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.",
"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."
],
"Sequence Classification": examples_to_select,
"Question Answering": {
"""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.""",
"""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.""",
"""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.""",
"""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.""",
"""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."""
}
}
if task == 'Question Answering':
examples = list(examples_mapping[task].keys())
selected_text = st.selectbox('Select an Example:', examples)
st.subheader('Try it yourself!')
custom_input_question = st.text_input('Create a question')
custom_input_context = st.text_input("Create it's context")
custom_examples = {}
st.subheader('Selected Text')
if custom_input_question and custom_input_context:
QUESTION = custom_input_question
CONTEXT = custom_input_context
elif selected_text:
QUESTION = selected_text
CONTEXT = examples_mapping[task][selected_text]
st.markdown(f"**Question:** {QUESTION}")
st.markdown(f"**Context:** {CONTEXT}")
else:
examples = examples_mapping[task]
selected_text = st.selectbox("Select an example", examples)
custom_input = st.text_input("Try it with your own Sentence!")
if task == 'Zero-Shot Classification':
zeroShotLables = ["urgent", "mobile", "travel", "movie", "music", "sport", "weather", "technology"]
lables = st_tags(
label='Select labels',
text='Press enter to add more',
value=zeroShotLables,
suggestions=[
"Positive", "Negative", "Neutral",
"Urgent", "Mobile", "Travel", "Movie", "Music", "Sport", "Weather", "Technology",
"Happiness", "Sadness", "Anger", "Fear", "Surprise", "Disgust",
"Informational", "Navigational", "Transactional", "Commercial Investigation",
"Politics", "Business", "Sports", "Entertainment", "Health", "Science",
"Product Quality", "Delivery Experience", "Customer Service", "Pricing", "Return Policy",
"Education", "Finance", "Lifestyle", "Fashion", "Food", "Art", "History",
"Culture", "Environment", "Real Estate", "Automotive", "Travel", "Fitness", "Career"],
maxtags = -1)
try:
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)
except:
text_to_analyze = selected_text
# Initialize Spark and create pipeline
spark = init_spark()
pipeline = create_pipeline(model, task)
try:
output = fit_data(pipeline, task, text_to_analyze, QUESTION, CONTEXT)
except:
output = fit_data(pipeline, task, text_to_analyze)
# Display matched sentence
st.subheader("Prediction:")
if task == 'Token Classification':
results = {
'Document': output[0]['document'][0].result,
'NER Chunk': [n.result for n in output[0]['entities']],
'NER Label': [n.metadata['entity']for n in output[0]['entities']]
}
annotate(results)
df = pd.DataFrame({'NER Chunk': results['NER Chunk'], 'NER Label': results['NER Label']})
df.index += 1
st.dataframe(df)
elif task == 'Sequence Classification':
st.markdown(f"Classified as : **{output[0]['class'][0].result}**")
elif task == "Question Answering":
output_text = "".join(output[0][0])
st.markdown(f"Answer: **{output_text}**")
|