GPT-3 open-source alternatives: GPT-Neo and GPT-J

OpenAI’s GPT-3 model gives great results, but it is not open-source and OpenAI’s API is very expensive. GPT-Neo and GPT-J are 2 great open-source alternatives to GPT-3. How do they compare to GPT-3?

The GPT-3 Breakthrough

GPT-3 was released in May 2020 by the OpenAI research lab, based in San Francisco. As of this writing this is the biggest Natural Language Processing model ever created, trained on 175 billion parameters! See GPT-3’s website here.

It can be used for various Natural Language Processing use cases, but it especially excels at text generation (give a small piece of text to the model with an expected text length, and let the model generate the rest of the text for you). The stunning accuracy of GPT-3 opens tons of new AI possibilities, like automatic marketing content creation, advanced chat bots, medical question answering, and much more. For more examples about what you can do with GPT-3, please see their documentation.

Problem: the model can only be used through an expensive paid API as a black box, and only for selected customers (new customers have to join a waitlist). The source code of GPT-3 belongs to Microsoft.

GPT-3 Pricing

OpenAI’s API offers 4 GPT-3 models trained on different numbers of parameters: Ada, Babbage, Curie, and Davinci. OpenAI doesn’t say how many parameters each model contains, but some estimations have been made (see here) and it seems that Ada contains more or less 350 million parameters, Babbage contains 1.3 billion parameters, Curie contains 6.7 billion parameters, and Davinci contains 175 billion parameters.

The more parameters the better the accuracy, but also the slower the model, and the higher the price. Their price is per token. Basically you can consider that 100 tokens are roughly equivalent to 75 words. They count the tokens you send in the input request plus the tokens generated by the model. On Davinci, for example, the price for 1,000 tokens is $0.06.

Example: sending a piece of text made up of 1000 tokens (roughly 750 words) and asking the model to generate 200 tokens, will cost you $0.072. If you want to send 20 requests per minute to their API, it will then cost you $64,250 per month…

GPT-3 pricing

GPT-Neo and GPT-J

GPT-Neo has been released in March 2021, and GPT-J in June 2021, as open-source models, both created by EleutherAI (a collective of researchers working to open source AI).

GPT-Neo has 3 versions: 125 million parameters, 1.3 billion parameters (equivalent to GPT-3 Babbage), and 2.7 billion parameters. GPT-J has 6 billion parameters, which makes it the most advanced open-source Natural Language Processing model as of this writing. This is a direct equivalent of GPT-3 Curie.

The tests made on these models show great performances. When generating text with GPT-J, this is almost impossible to tell whether it has been written by a human or a machine…

How to use GPT-Neo and GPT-J?

GPT-Neo and GPT-J are open-source Natural Language Processing models, so everybody can download them and use them. Well, in theory…

GPT-J, for example, needs around 25GB of RAM to run + many CPUs. On CPUs, GPT-J is painfully slow though, so it is much better to perform inference with GPT-J on a GPU. As GPT-J needs around 25GB of GPU VRAM, it does not fit in most of the standard NVIDIA GPUs existing on the market today (that either have 8GB or 16GB of VRAM maximum).

These hardware requirements make it very impractical to test GPT-J and GPT-Neo, let alone use them reliably for inference in production with high-availability and scalability in mind.

A text generation request to the GPT-J endpoint looks like this:

GPT-J API example

GPT-3 vs GPT-J on NLP Cloud: pricing comparison

Here is the math.

Imagine that you want to perform text generation with GPT-3 Curie. You want to pass an input of 1000 tokens and generate 200 tokens. You want to perform 1 request per minute.

The price per month would be (1200/1000) x 0.006 x 44,640 = $321/month

Now the same thing with GPT-J on NLP Cloud:

On NLP Cloud, the plan for 1 request per minute on GPT-J costs $29/month on CPU or $99/month on GPU, no matter the number of tokens.

As you can see the price difference is quite significant.

Conclusion

GPT-3 is an amazing model that really changed the Natural Language Processing game. For the first time in Natural Language Processing history, it’s almost impossible to say whether the generated content is coming from a human or a machine, which leads many companies to integrate GPT-3 into their product or their internal workflows.

However, sadly, GPT-3 is far from easily accessible… EleutherAI made a great job at designing open-source alternatives to GPT-3. GPT-J is the largest of these alternatives as of this writing.

Google Cloud Natural Language API: pricing and features comparison with the NLP Cloud API

Google Cloud Natural Language is a cloud-based Natural Language Processing API that proposes several advanced Natural Language Processing models. Despite being an important actor on the Natural Language Processing market, it is important to carefully review Google Natural Language’s offer in order to understand if it is the best solution for you. How does the Google Natural Language Processing API compare to the NLP Cloud API in terms of pricing and features?

Pricing: Google Natural Language VS NLP Cloud

Google Natural Language considers that a request should contain less than 1,000 characters. If your request contains more than 1,000 characters, it is considered as several requests. For example, if you are trying to classify a piece of text made up of 3,500 characters, this is considered as 4 requests.

The price goes from $0,0005 to $0,002 per request depending on the feature you are using.

The first 5,000 requests are free every month, and if you use their text classification model, you get more free requests (30,000 per month).

The more requests you send, the more you’re charged.

Google Natural Language API Pricing

NLP Cloud adopts a totally different pricing strategy.

NLP Cloud’s pricing is flat, which means that you have a number of requests included in your plan. If you want to change the number of requests, you can upgrade or downgrade your plan anytime. The interesting thing with such a pricing is that it is predictable: you always know in advance how much you will be charged at the end of the month.

NLP Cloud proposes several plans, depending on the number of requests you need, no matter the Natural Language Processing model you are going to use, and no matter the number of characters contained in your request. For example, 15 requests per minute cost $29 per month on CPU servers, and $99 per month on GPU servers.

Concrete price example: text classification

Imagine that you want to classify pieces of text made up of 10,000 characters, at a rate of 15 requests per minute.

Google would consider that each request is actually equivalent to 10 requests (because each request can only be virtually made up of 1,000 characters). So at the end of the month you would perform 10 x 15 x 44,640 = 6,696,000 requests.

Taking into account their first 30k free requests, and their proportional pricing, you would eventually pay $3,140 per month.

For the same service you would pay $29 per month on NLP Cloud. The difference is quite impressive!

Google Natural Language is expensive and it is quite hard to predict how much you are going to be charged at the end of the month. Take time to do the math in advance in order to avoid surprises…

Features: Google Natural Language VS NLP Cloud

Google Natural Language develops their own in-house models, while NLP Cloud integrates the best open-source models available on the market. They are 2 different strategies, and both have pros and cons. Google has a perfect control on their models, but in return their models are black boxes: it is not clear what is inside exactly.

Interesting feature: customers can fine-tune their own models on the Google Natural Language platform, and it is also the case on NLP Cloud. It is an interesting option if you think that the base models are not accurate enough and then should be tailored to your needs.

Also, Google has specific models dedicated to medical data analysis, that NLP Cloud doesn’t have, so you might find it interesting if you’re in the healthcare industry.

Now let’s list all the proposed Natural Language Processing features.

Here are the Natural Language Processing features supported by Google Natural Language:

  • Sentiment analysis
  • NER (entity extraction)
  • Entity sentiment analysis
  • Text classification
  • Part-of-Speech (POS) tagging

And here are the Natural Language Processing features supported by NLP Cloud as of this writing:

  • Sentiment analysis
  • NER (entity extraction)
  • Text classification
  • Part-of-Speech (POS) tagging and dependency parsing
  • Question answering
  • Text summarization
  • Text generation (with GPT-J and GPT-Neo, the open-source equivalents of GPT-3)
  • Translation (English, French, Spanish, German, Dutch, Chinese, Russian, and Arabic)
  • Language detection
  • Tokenization
  • Lemmatization

As you can see, more Natural Language Processing features are supported on NLP Cloud, and more should come soon.

Conclusion

Google Natural Language is a major actor in the Natural Language Processing market. They propose interesting features like the ability to train your own models, or address medical vocabulary.

However their API is very expensive. For the same price, you can get at least 100 times as many requests on the NLP Cloud API.

In terms of features, NLP Cloud proposes many interesting Natural Language Processing models that Google doesn’t propose, like text summarization, question answering, text generation, translation, language detection, tokenization, lemmatization…

Last of all, Google’s pricing makes it extremely hard to predict in advance how much you are going to be charged at the end of the month, which is not the case with NLP Cloud’s flat pricing.

Natural Language Processing Introduction: what is Natural Language Processing (NLP)?

You have heard of Natural Language Processing (NLP) but you don’t know what it is precisely, and what it is used for? In this post, I will try to help you understand Natural Language Processing with some examples.

What is Natural Language Processing (NLP)?

Natural Language Processing is a subfield of linguistics, computer science, and artificial intelligence. This is the processing of language, words and speech, by a computer.

It is about developing interactions between computers and human language, and especially about how to program computers to process and analyze large amounts of natural language data.

Don’t make the mistake: Natural Language Processing is not only linguistics! Linguistics aims at understanding foreign languages through software.

Natural Language Processing is based on rules. But rules are not enough: context is also very important. When a friend tells you: « What a wonderful spring! », is it the season or the water? Here is another example: « I go to the bank. ». Is it about walking along the bank of the river or about taking money to the bank?

So Natural Language Processing needs lots of rules and dictionaries.

Context is key in Natural Language Processing

What is Natural Language Processing for?

Thanks to Natural Language Processing, a machine can “understand” the contents of documents, including the contextual nuances of the language within them. A machine can also extract information and insights contained in the documents as well as categorize and organize the documents themselves.

Challenges in natural language processing frequently involve speech recognition, natural language understanding (NLU), and natural-language generation (NLG).

Why is Natural Language Processing interesting?

The world is full of unstructured data (i.e. data that is not formatted for machines): it amounts to 70-90% of digital data. Natural Language Processing is a great way to process these huge volumes of data.

« AI will power 95% of customer interactions by 2025. »

Gartner

For companies, Natural Language Processing is a way to know their customers in an automated way and to create new opportunities (better knowledge, better targeting,…).

Natural Language Processing Use Cases

Here are some typical Natural Language Processing use cases:

  • Sentiment analysis: as a CEO you want to automatically measure the happiness of your customers by analyzing their messages
  • Text classification: automatically knowing what a piece of text is talking about
  • Speech recognition: converting audio into text for further processing
  • Chatbots: providing 24/7/365 customer support
  • Machine translation: reaching new markets in other languages with minimal investment
  • Autocompleting text: similar to what Gmail does to help you increase your employee’s efficiency through a centralized knowledge base, or to improve how your customers interact with your product or website
  • Spell checking: making sure that documents don’t contain errors. Especially relevant in industries with high compliance requirements such as banking, insurance and finance.
  • Keyword search: locating relevant information faster across all data facilities, leading to increased efficiency
  • Advertisement matching
  • Entity extraction: extracting information from large volumes of unstructured data
  • Spam detection
  • Text generation: automatically creating new text, e.g. client contracts, research documents, training materials, and so on
  • Automatic summarization: adding summaries to existing documents
  • Questions answering: answering specific questions based on disparate information sources
  • Image captioning: annotating images
  • Video captioning: videos can take a long time to watch. Sometimes it’s faster to extract information from them in the form of text and then process it further using other Natural Language Processing techniques like summarization

Natural Language Processing is not new!

During World War 2, Alan Turing created a machine to understand the coded messages sent by the Nazis, called Turing’s machine.

Turing Machine

Later, the Georgetown–IBM experiment was an influential demonstration of machine translation, which was performed during January 7, 1954. Developed jointly by the Georgetown University and IBM, the experiment involved completely automatic translation of more than sixty Russian sentences into English. It had only six grammar rules and 250 lexical items in its vocabulary.

Another interesting milestone was the ELIZA software, developed in 1966 at the MIT Artificial Intelligence Laboratory by Joseph Weizenbaum. The most famous script, DOCTOR, simulated a psychotherapist and used rules, dictated in the script, to respond with non-directional questions to user inputs. As such, ELIZA was one of the first chatbots and one of the first programs capable of attempting the Turing test.

Conclusion

In this post, you discovered what natural language processing is and how it can be used in real life. Lots of challenges still exist but great progress has been made these last years in the Natural Language Processing field. Today, the maturity of Natural Language Processing encourages more and more companies to leverage Natural Language Processing in their product or in their internal organization.

Contextual targeting for privacy-friendly advertizing thanks to text classification Natural Language Processing API

Unless stated otherwise, all pictures in the article are by the author.

Don’t track the user, track interests

In today’s online advertising reality, effective marketing tactics rely on a variety of user tracking techniques, such as third-party cookies (and alternative storages) and device fingerprinting. But in a world of data leaks, GDPR, CCPA and increased data protection legislation inspired by those, this approach becomes obsolete. Safari and Firefox already have built-in solutions to reduce cross-site tracking. Chrome also works on alternatives. So, the end of third-party cookies is soon. Apple’s Identifier for Advertisers (IDFA) will soon be accessible only for apps with explicit consent from the user. The disappearance of the possibility of cross-domain tracking makes advertisers return to contextual advertising.

In this article, I show you how to implement context targeting based on the Text Classification API provided by NLP Cloud. The approach described here can be easily adapted to any advertising technologies (such as ad servers, OpenRTB etc.).

Context targeting

Because advertisers won’t be able to target individual users by using third-party cookies, an easy prediction is contextual advertising campaigns rising again. This could be the only way to target user interests on a large enough scale. Contextual ads are based on content which the user is looking at right now, instead of their browser history or behavioral profile.

Contextual advertizing

(picture from What Is Contextual Advertising?)

It is supposed to be more interesting for users, as they’ll see ads that match the topic of the website pages that they are visiting.

Give me a tag

Most ad serving technologies and ad networks support the passing of keywords or tags during the ad serving codes. Text is the core of the web and can be an extremely rich source of information. However, extracting context, tags and keywords from it, e.g. for advertisement or recommendation purposes, can be hard and time-consuming. But if you are the owner of even a medium-sized news site, beyond a few tags allocated by the editorial team, it will be difficult to extract all the relevant topics.

First attempts to automate this process have resulted in more or less hilarious screw-ups in the past:

Incorrect contextual advertizing

(picture from Bad Ad Placements Funny, If Not Yours)

Text classification of articles

Fortunately, advances in Natural Language Processing allow for much more accurate matches, in less time. Text classification is the assignment of categories or labels consistent with text content.

Let’s consider an example page with articles on a variety of topics:

Article page with an empty ad slot

My goal is to have ad placements display banners thematically related to the article content.

Conditions that my solution must meet:

  1. I choose keywords and topics that are relevant to the ad campaign.
  2. The system analyzes the content of the displayed article and categorizes it.
  3. Relevant ads are chosen and placed.

Note that advertising systems and web development are outside the scope of this article, but the general concepts remain the same regardless of the tools and technologies used.

Text Classification API

My preferred solution in such cases is to separate the logic that handles text classification into a separate API. I have two options: create it myself or use a ready-made solution.

Preparing a simple text classification engine using Python and Natural Language Processing libraries is a task for one afternoon. But the problem arises in terms of accuracy and serving increased traffic. I need to somehow handle the growing user base and their clickstream.

If you are a website owner, you are unlikely to want to play with the machine learning models tuning and evaluation. So I will delegate as much as I can to an external solution. Note that I do not plan to send any user data here, only data belonging to the website. This makes the use of external contextual targeting tools much simpler from a user privacy perspective.

NLP Cloud is a provider of multiple APIs for text processing using machine learning models. One of these is the text classifier, which looks promising in terms of simple implementation.

With the NLP Cloud API, you can try out which algorithm might be useful for a particular business case.

Integrate text classification with the content of the website

As the backend of the website is Python-based (Flask), I start by writing a simple client to the Natural Language Processing API:

import pandas as pd
import requests
import json


class TextClassification:
    def __init__(self, key, base='https://api.nlpcloud.io/v1/bart-large-mnli',):
        self.base = base
        self.headers = {
            "accept": "application/json",
            "content-type": "application/json",
            "Authorization": f"Token {key}"
        }

    def get_keywords(self, text, labels):
        url = f"{self.base}/classification"
        payload = {
            "text":text,
            "labels":labels,
            "multi_class": True
        }

        response = requests.request("POST", url, json=payload, headers=self.headers)
        result = []
        try:
            result = dict(zip(response.json()['labels'], response.json()['scores']))
        except:
            pass
        return result
        
tc = TextClassification(key='<your API token>')

print(
    tc.get_keywords(
        "Football is a family of team sports that involve, to varying degrees, kicking a ball to score a goal. Unqualified, the word football normally means the form of football that is the most popular where the word is used. Sports commonly called football include association football (known as soccer in some countries); gridiron football (specifically American football or Canadian football); Australian rules football; rugby football (either rugby union or rugby league); and Gaelic football.[1][2] These various forms of football share to varying extent common origins and are known as football codes.",
        ["football", "sport", "cooking", "machine learning"]
    )
)

Results:

{
    'labels': [
        'sport', 
        'football', 
        'machine learning', 
        'cooking'
    ], 

    'scores': [
        0.9651273488998413, 
        0.938549280166626, 
        0.013061746023595333, 
        0.0016104158712550998
    ]
}

Pretty good. Each label is assigned its relevance to the topic with no effort.

The plan is that the selection of banners to be displayed will be done by an ad serving system (decision will be based on the scores of the individually assigned labels). Therefore, in order not to expose the API keys and to have more control over the data, I will write a simple proxy:

@app.route('/get-labels',methods = ['POST'])
def get_labels():
    if request.method == 'POST':
        try:
            return tc.get_keywords(request.json['text'], request.json['labels'])
        except:
            return []

Campaigns

Let’s assume there are 3 ad campaigns to run:

Insurance campaign banner

Insurance company (keyword: insurance)

Renewable energy campaign banner

Renewable energy company (keyword: renewables)

Hairdresser campaign banner

Hairdresser (keyword: good look)

Let’s sketch a mechanism on the front-end, which will manage the display of an appropriate creative.

function displayAd(keyword, placement_id) {

    var conditions = {
        false: '<a href="#"><img src="https://via.placeholder.com/728x90.png?text=Place+for+your+advertisement" /></a> ',
        "insurance": '<a href="#"><img src="https://via.placeholder.com/728x90.png?text=BEST+Insurance+Company+Ever" /></a> ',
        "renewables": '<a href="#"><img src="https://via.placeholder.com/728x90.png?text=Cheap+PV+cells" /></a> ',
        "good look": '<a href="#"><img src="https://via.placeholder.com/728x90.png?text=Hairdresser+for+bald+people" /></a> '
    }

    var banner = document.querySelector(placement_id);
    banner.innerHTML = conditions[keyword];

}

This is my adserver 🤪

Now using fetch, I will retrieve labels for the text of an article, that I get using its selector:

var text = document.querySelector("#article").textContent;
var labels = ["insurance", "renewables", "good look"];

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({"text":text,"labels":labels});

var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: raw,
};

fetch("http://127.0.0.1:5000/get-labels", requestOptions)
    .then(response => 
    response.json()
    )
    .then(result => {
    if (result == []){
        console.log("self-promote");
        displayAd(false, "#banner");
    } else {
        var scores = result['scores'];
        var labels = result['labels'];

    if (Math.max(...scores) >= 0.8) {
        console.log("Ad success");
        var indexOfMaxScore = scores.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0);
        displayAd(labels[indexOfMaxScore], "#banner");

    } else {
        displayAd(false, "#banner");
    }
    }
    })
    .catch(error => console.log('error', error));

Note that I only display the client ad if the score is above 0.8:

Math.max(…scores) >= 0.8

Otherwise, I display self-promotion.

This is of course an arbitrary value, which can be tightened and loosened as needed.

Renewable energy article with a matching ad

News about renewable energy source fits PV cell ads.

Home safety article with an insurance ad

News about the dangers in the house can increase the intention to buy insurance.

Article whose classification score stays below the threshold

Although an ad about insurance would have been suitable for the article, it was not displayed because the right level of relevancy was not achieved.

The careful reader will notice that the example of the hairdresser’s banner did not appear. This is because the subject matter of the articles is focused on serious world news, where fashion issues are not addressed. To be able to implement the campaign, you need to choose a different site or rethink your keyword strategy.

Performance

I can achieve fast page load thanks to this asynchronous function: fetch. However, at the same time, the ad will only show after the labels have been downloaded. For this reason and to reduce costs, it is best to implement some form of cache in a production environment.

An additional modification could be simply storing labels directly in the database. For infrequently updated articles, this certainly makes sense.

However, a solution based on a separate API, which I can feed with any text and get its labels, gives me the possibility to use JS code virtually on any page in near real-time, even without access to the backend!

Takeaways

The biggest challenge in using contextual targeting is using it on news websites. Many topics appear in the articles posted there, including those which are in line with the advertiser’s industry. But at the same time, the sensational, often sad overtones of the stories they contain are not a good place to advertise.

The text classification API by NLP Cloud, on the other hand, does a pretty good job of tagging texts, so I might as well repeat the whole process, this time keeping in mind to exclude texts with a given topic from having banners emitted on them.

Introduction to the NLP Cloud API using the Python client

NLP Cloud is an API that makes it easy to use Natural Language Processing in production. The API is based on the best open-source pre-trained models. You can also use your own models or train models on the platform. NLP Cloud most of the text understanding and text generation features: entities extraction (NER), sentiment analysis, text classification, text summarization, question answering, text generation, and Part-of-speech (POS) tagging… and more!

Let’s see how to use the API in this tutorial.

Why NLP Cloud?

Deploying AI models to production is a frequent source of project failure. Natural Language Processing models are very resource intensive, and ensuring high availability of these models in production, while having good response times, is a challenge. It takes and expensive infrastructure and advanced DevOps, programming, and AI skills.

Create an Account

After you create an account you land in the dashboard, where you can see your API token. Keep this token safely, you will need it for all the API calls you will make.

NLP Cloud API Client Libs

NLP Cloud provides you, out-of-the-box, with most of the typical Natural Language Processing features, either thanks to pre-trained spaCy or Hugging Face models, or by uploading your own spaCy models.

In order to make the API easy to use, NLP Cloud provides you with client libraries in several languages (Python, Ruby, PHP, Go, Node.js). In the rest of this tutorial, I am going to use the Python lib.

Use PIP in order to install the Python lib:

pip install nlpcloud

Entity Extraction (NER)

Entities extraction is done via spaCy. All the spaCy “large” pre-trained models are available, which means that 15 languages are available (more details on all these models on the spaCy website). You can also upload custom in-house spaCy models that you developed by yourself in order to use them in production. If that’s what you want, just go to the “Custom Models” section in your dashboard:

Upload custom Natural Language Processing models

Now let’s imagine that you want to extract entities from the sentence “John Doe has been working for Microsoft in Seattle since 1999.” thanks to the pre-trained spaCy model for English (“en_core_web_lg”). Here’s how you should proceed:

import nlpcloud

client = nlpcloud.Client("en_core_web_lg", "<your API token>")
client.entities("John Doe has been working for Microsoft in Seattle since 1999.")

It will return the content of each extracted entity and its position in the sentence.

Sentiment Analysis

Sentiment analysis is achieved thanks to Hugging Face transformers and Distilbert Base Uncased Finetuned SST 2 English. Here’s an example:

import nlpcloud

client = nlpcloud.Client("distilbert-base-uncased-finetuned-sst-2-english", "<your API token>")
client.sentiment("NLP Cloud proposes an amazing service!")

It will tell you whether the general sentiment in this text is rather positive or negative, and its likelihood.

Text Classification

Text classification is achieved thanks to Hugging Face transformers and Facebook’s Bart Large MNLI. Here is an example:

import nlpcloud

client = nlpcloud.Client("bart-large-mnli", "<your API token>")
client.classification("""John Doe is a Go Developer at Google. 
    He has been working there for 10 years and has been 
    awarded employee of the year.""",
    ["job", "nature", "space"],
    True)

As you can see, I am passing a block of text I am trying to classify, along with possible categories. The last argument is a boolean that defines whether one single category or several ones can apply.

It will return the likelihood for each category.

Text Summarization

Text summarization is achieved thanks to Hugging Face transformers and Facebook’s Bart Large CNN. Here’s an example:

import nlpcloud

client = nlpcloud.Client("bart-large-cnn", "<your API token>")
client.summarization("""The tower is 324 metres (1,063 ft) tall, 
about the same height as an 81-storey building, and the tallest structure in Paris. 
Its base is square, measuring 125 metres (410 ft) on each side. During its construction, 
the Eiffel Tower surpassed the Washington Monument to become the tallest man-made 
structure in the world, a title it held for 41 years until the Chrysler Building 
in New York City was finished in 1930. It was the first structure to reach a 
height of 300 metres. Due to the addition of a broadcasting aerial at the top of 
the tower in 1957, it is now taller than the Chrysler Building by 5.2 metres (17 ft). 
Excluding transmitters, the Eiffel Tower is the second tallest free-standing structure 
in France after the Millau Viaduct.""")

It will return a summarization of the above. This is an “abstractive” summary, and not an “extractive” one, which means new sentences might be generated, and non-important ones are removed. However non-essential sentences are removed of course.

Question Answering

Question answering is achieved thanks to Hugging Face transformers and Deepset’s Roberta Base Squad 2. Here’s an example:

import nlpcloud

client = nlpcloud.Client("roberta-base-squad2", "<your API token>")
client.question("""French president Emmanuel Macron said the country was at war
    with an invisible, elusive enemy, and the measures were unprecedented,
    but circumstances demanded them.""",
    "Who is the French president?")

Here it’s about answering a question thanks to a context.

For example the above example will return “Emmanuel Macron”.

Part-of-Speech (POS) Tagging

Part-Of-Speech tagging is achieved thanks to the same spaCy models as the one used for entities extraction. So for example if you want to use the English pre-trained model, here’s how you should do:

import nlpcloud

client = nlpcloud.Client("en_core_web_lg", "<your API token>")
client.dependencies("John Doe is a Go Developer at Google")

It will return the part-of-speech of each token in the sentence, and its dependency on other tokens.

Conclusion

NLP Cloud is an API for Natural Language Processing that is easy to use and that helps you save a lot of time in production.

I hope this article was useful to some of you! If you have any question, please don’t hesitate to let me know.