#!/usr/bin/env python
# coding: utf-8
#
# ## How can I leverage State-of-the-Art Natural Language Models with only one line of code ?
# Newly introduced in transformers v2.3.0, **pipelines** provides a high-level, easy to use,
# API for doing inference over a variety of downstream-tasks, including:
#
# - ***Sentence Classification _(Sentiment Analysis)_***: Indicate if the overall sentence is either positive or negative, i.e. *binary classification task* or *logitic regression task*.
# - ***Token Classification (Named Entity Recognition, Part-of-Speech tagging)***: For each sub-entities _(*tokens*)_ in the input, assign them a label, i.e. classification task.
# - ***Question-Answering***: Provided a tuple (`question`, `context`) the model should find the span of text in `content` answering the `question`.
# - ***Mask-Filling***: Suggests possible word(s) to fill the masked input with respect to the provided `context`.
# - ***Summarization***: Summarizes the ``input`` article to a shorter article.
# - ***Translation***: Translates the input from a language to another language.
# - ***Feature Extraction***: Maps the input to a higher, multi-dimensional space learned from the data.
#
# Pipelines encapsulate the overall process of every NLP process:
#
# 1. *Tokenization*: Split the initial input into multiple sub-entities with ... properties (i.e. tokens).
# 2. *Inference*: Maps every tokens into a more meaningful representation.
# 3. *Decoding*: Use the above representation to generate and/or extract the final output for the underlying task.
#
# The overall API is exposed to the end-user through the `pipeline()` method with the following
# structure:
#
# ```python
# from transformers import pipeline
#
# # Using default model and tokenizer for the task
# pipeline("")
#
# # Using a user-specified model
# pipeline("", model="")
#
# # Using custom model/tokenizer as str
# pipeline('', model='', tokenizer='')
# ```
# In[2]:
get_ipython().system('pip install -q transformers')
# In[ ]:
from __future__ import print_function
import ipywidgets as widgets
from transformers import pipeline
# ## 1. Sentence Classification - Sentiment Analysis
# In[ ]:
nlp_sentence_classif = pipeline('sentiment-analysis')
nlp_sentence_classif('Such a nice weather outside !')
# ## 2. Token Classification - Named Entity Recognition
# In[ ]:
nlp_token_class = pipeline('ner')
nlp_token_class('Hugging Face is a French company based in New-York.')
# ## 3. Question Answering
# In[ ]:
nlp_qa = pipeline('question-answering')
nlp_qa(context='Hugging Face is a French company based in New-York.', question='Where is based Hugging Face ?')
# ## 4. Text Generation - Mask Filling
# In[ ]:
nlp_fill = pipeline('fill-mask')
nlp_fill('Hugging Face is a French company based in ' + nlp_fill.tokenizer.mask_token)
# ## 5. Summarization
#
# Summarization is currently supported by `Bart` and `T5`.
# In[ ]:
TEXT_TO_SUMMARIZE = """
New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York.
A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.
Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared "I do" five more times, sometimes only within two weeks of each other.
In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her "first and only" marriage.
Barrientos, now 39, is facing two criminal counts of "offering a false instrument for filing in the first degree," referring to her false statements on the
2010 marriage license application, according to court documents.
Prosecutors said the marriages were part of an immigration scam.
On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further.
After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective
Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.
All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say.
Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.
Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted.
The case was referred to the Bronx District Attorney\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\'s
Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt, Turkey, Georgia, Pakistan and Mali.
Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force.
If convicted, Barrientos faces up to four years in prison. Her next court appearance is scheduled for May 18.
"""
summarizer = pipeline('summarization')
summarizer(TEXT_TO_SUMMARIZE)
# ## 6. Translation
#
# Translation is currently supported by `T5` for the language mappings English-to-French (`translation_en_to_fr`), English-to-German (`translation_en_to_de`) and English-to-Romanian (`translation_en_to_ro`).
# In[ ]:
# English to French
translator = pipeline('translation_en_to_fr')
translator("HuggingFace is a French company that is based in New York City. HuggingFace's mission is to solve NLP one commit at a time")
# In[ ]:
# English to German
translator = pipeline('translation_en_to_de')
translator("The history of natural language processing (NLP) generally started in the 1950s, although work can be found from earlier periods.")
# ## 7. Text Generation
#
# Text generation is currently supported by GPT-2, OpenAi-GPT, TransfoXL, XLNet, CTRL and Reformer.
# In[5]:
text_generator = pipeline("text-generation")
text_generator("Today is a beautiful day and I will")
# ## 8. Projection - Features Extraction
# In[ ]:
import numpy as np
nlp_features = pipeline('feature-extraction')
output = nlp_features('Hugging Face is a French company based in Paris')
np.array(output).shape # (Samples, Tokens, Vector Size)
# Alright ! Now you have a nice picture of what is possible through transformers' pipelines, and there is more
# to come in future releases.
#
# In the meantime, you can try the different pipelines with your own inputs
# In[ ]:
task = widgets.Dropdown(
options=['sentiment-analysis', 'ner', 'fill_mask'],
value='ner',
description='Task:',
disabled=False
)
input = widgets.Text(
value='',
placeholder='Enter something',
description='Your input:',
disabled=False
)
def forward(_):
if len(input.value) > 0:
if task.value == 'ner':
output = nlp_token_class(input.value)
elif task.value == 'sentiment-analysis':
output = nlp_sentence_classif(input.value)
else:
if input.value.find('') == -1:
output = nlp_fill(input.value + ' ')
else:
output = nlp_fill(input.value)
print(output)
input.on_submit(forward)
display(task, input)
# In[ ]:
context = widgets.Textarea(
value='Einstein is famous for the general theory of relativity',
placeholder='Enter something',
description='Context:',
disabled=False
)
query = widgets.Text(
value='Why is Einstein famous for ?',
placeholder='Enter something',
description='Question:',
disabled=False
)
def forward(_):
if len(context.value) > 0 and len(query.value) > 0:
output = nlp_qa(question=query.value, context=context.value)
print(output)
query.on_submit(forward)
display(context, query)