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:
question, context) the model should find the span of text in content answering the question.context.input article to a shorter article.Pipelines encapsulate the overall process of every NLP process:
The overall API is exposed to the end-user through the pipeline() method with the following
structure:
from transformers import pipeline
# Using default model and tokenizer for the task
pipeline("<task-name>")
# Using a user-specified model
pipeline("<task-name>", model="<model_name>")
# Using custom model/tokenizer as str
pipeline('<task-name>', model='<model name>', tokenizer='<tokenizer_name>')
In [2]:
!pip install -q transformers
In [0]:
from __future__ import print_function
import ipywidgets as widgets
from transformers import pipeline
In [0]:
nlp_sentence_classif = pipeline('sentiment-analysis')
nlp_sentence_classif('Such a nice weather outside !')
Out[0]:
In [0]:
nlp_token_class = pipeline('ner')
nlp_token_class('Hugging Face is a French company based in New-York.')
Out[0]:
In [0]:
nlp_qa = pipeline('question-answering')
nlp_qa(context='Hugging Face is a French company based in New-York.', question='Where is based Hugging Face ?')
Out[0]:
In [0]:
nlp_fill = pipeline('fill-mask')
nlp_fill('Hugging Face is a French company based in ' + nlp_fill.tokenizer.mask_token)
Out[0]:
In [0]:
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)
Out[0]:
In [0]:
# 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")
Out[0]:
In [0]:
# 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.")
Out[0]:
In [5]:
text_generator = pipeline("text-generation")
text_generator("Today is a beautiful day and I will")
Out[5]:
In [0]:
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)
Out[0]:
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 [0]:
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('<mask>') == -1:
output = nlp_fill(input.value + ' <mask>')
else:
output = nlp_fill(input.value)
print(output)
input.on_submit(forward)
display(task, input)
In [0]:
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)