The author selected Code 2040 to receive a donation as part of the Write for DOnations program.
As the field of machine learning (ML) grows, so does the list of environments for using this technology. One of these environments is the web browser, and in recent years, there has been a surge in data-related frameworks targeting web-based machine learning models. An example of these frameworks is TensorFlow.js, TensorFlow’s JavaScript counterpart library for training, executing, and deploying machine learning models in the browser. In an attempt to make TensorFlow.js accessible to developers with limited or no ML experience, the library comes with several pre-trained models that work out of the box.
A pre-trained machine learning model is ready-to-use machine learning you don’t have to train. TensorFlow.js includes 14 that suit a variety of use cases. For example, there is an image classifying model for identifying common objects and a body segmentation model for identifying body parts. The principal convenience of these models is that, as the name states, you don’t have to train them. Instead, you load them in your application. Besides their ease of use and pre-trained nature, these are curated models—they are accurate and fast, sometimes trained by the algorithms’ authors and optimized for the web browser.
In this tutorial, you will create a web application that serves a Question and Answer (QnA) pre-trained model using TensorFlow.js. The model you will deploy is a Bidirectional Encoder Representations from Transformers (BERT) model that uses a passage and a question as the input, and tries to answer the question from the passage.
You will deploy the app in DigitalOcean’s App Platform, a managed solution for building, deploying, and scaling applications within a few clicks from sources such as GitHub. The app you will create consists of a static page with two input fields, one for the passage and one for the question. In the end, you will have a written and deployed—from GitHub—a Question and Answer application using one of TensorFlow.js’ pre-trained models and DigitalOcean’s App Platform.
To complete this tutorial, you will need:
In this step, you will write the app’s HTML code, which will define its interface and import the libraries for the app. The first of these libraries is TensorFlow.js, and instead of installing the package locally, you will load it from a content delivery network or CDN. A CDN is a network of servers spanning multiple locations that store content they provide to the internet. This content includes JavaScript files, such as the TensorFlow.js library, and loading it from a CDN saves you from packing them in your application. Similarly, you will import the library containing the Question and Answer model. In the next step, you will write the app’s JavaScript, which uses the model to answer a given question.
In this tutorial, you will structure an app that will look like this:
The app has five major elements:
Start by creating a new directory named tfjs-qna-do
at your preferred location. In this directory, using a text editor of your choice, create a new HTML file named index.html
and paste in the following code:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<!-- Load TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<!-- Load the QnA model -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/qna"></script>
<link href="./style.css" rel="stylesheet">
</head>
<body>
<div class="main-centered-container">
<h1>TensorFlow.js Pre-trained "QnA" BERT model</h1>
<h3 class="header-border">Introduction</h3>
<p>This application hosts TensorFlow.js' pre-trained Question and Answer model, and it attempts to answer the question
using a given passage. To use it, write a passage (any!) in the input area below and a question. Then, click the
"answer!" button to answer the question using the given passage as a reference. You could also click the test
button to load a pre-defined input text.</p>
<h4>Try the test passage!</h4>
<div id='test-buttons'></div>
<div>
<h4>Enter the model's input passage here</h4>
<textarea id='input-text' rows="20" cols="100" placeholder="Write the input text..."></textarea>
</div>
<div>
<h4>Enter the question to ask</h4>
<textarea id='question' rows="5" cols="100" placeholder="Write the input text..."></textarea>
</div>
<h4>Click to answer the question</h4>
<div id="answer-button"></div>
<h4>The model's answers</h4>
<div id='answer'></div>
<script src="./index.js"></script>
</div>
</body>
</html>
Here’s how that HTML breaks down:
<html>
tag has the <head>
tag that’s used for defining metadata, styles, and loading scripts. Its first element is <meta>
, and here you will set the page’s charset
encoding to utf-8
. After it, there are two <script>
tags for loading both TensorFlow.js and the Question and Answer model from a CDN.<script>
tags, there’s a <link>
tag that loads a CSS file (which you will create next).<body>
—the document’s content. Inside of it, there’s a <div>
tag of class main-centered-container
containing the page’s elements. The first is a <h1>
header with the application title and a smaller <h3>
header, followed by a brief introduction explaining how it works.<h4>
header and a <div>
where you will append buttons that populate the passage input text field with sample text.rows
and cols
attributes.<div>
with id button
where you will later append a button that, upon clicking, reads the text fields’ text and uses them as an input to the model.<div>
with id answer
that’s used to display the model’s output and a <script>
tag to include the JavaScript code you will write in the following section.Next, you’ll add CSS to the project. In the same directory where you added the index.html
file, create a new file named style.css
and add the following code:
body {
margin: 50px 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial;
}
button {
margin: 10px 10px;
font-size: 100%;
}
p {
line-height: 1.8;
}
.main-centered-container {
padding: 60px;
display: flex;
flex-direction: column;
margin: 0 auto;
max-width: 960px;
}
.header-border {
border: solid #d0d0d0;
border-width: 0 0 1px;
padding: 0 0 5px;
}
This CSS adds style to three HTML elements: body, buttons, and paragraphs (<p>
). To body
, it adds a margin, padding, and changes the default font. To button
, it adds margin and increases the font size. To paragraph p
, it modifies the line-height
attribute. The CSS has a class main-centered-container
that centers the content and another one, header-border
, that adds a solid line to an element.
In this step, you wrote the app’s HTML file. You imported the TensorFlow.js library and QnA model, and defined the elements you will use later to add the passage and the question you want to answer. In the following step, you will write the JavaScript code that reads the elements and triggers the predictions.
In this section, you will implement the web app’s JavaScript code that reads the app’s input fields, makes a prediction, and writes the predicted answers in HTML. You will do it in one function that’s triggered when you click the “answer” button. Once clicked, it will reference both input fields to get their values, use them as inputs to the model, and write its output in the <div>
with id output
you defined in Step 1. Then, you will run the app locally to test it before adding it to GitHub.
In the project’s directory tfjs-qna-do/
, create a new file named index.js
, and declare the following variables:
let model;
// The text field containing the input text
let inputText;
// The text field containing the question
let questionText;
// The div where we will write the model's answer
let answersOutput;
The first of the variables, model
, is where you will store the QnA model; inputText
and questionText
are references to the input and question text fields; answersOutput
is a reference to the output <div>
.
In addition to these variables, you will need a constant for storing the sample text you will use to test the app. We will use the Wikipedia article on DigitalOcean as a sample passage. Based on this passage, you could ask the model questions like “Where is DigitalOcean headquartered?” and hopefully, it will output “New York”.
Copy this block into your index.js
file:
// Sample passage from Wikipedia.
const doText = `DigitalOcean, Inc. is an American cloud infrastructure provider[2] headquartered in New York City with data centers worldwide.[3]
DigitalOcean provides developers cloud services that help to deploy and scale applications that run simultaneously on multiple computers.
DigitalOcean also runs Hacktoberfest which is a month-long celebration (October 1-31) of open source software run in partnership with GitHub and Twilio.
`;
Now, you will define the app’s functions, starting with createButton()
. This function creates a button and appends it to an HTML element:
function createButton(innerText, id, listener, selector, disabled = false) {
const btn = document.createElement('BUTTON');
btn.innerText = innerText;
btn.id = id;
btn.disabled = disabled;
btn.addEventListener('click', listener);
document.querySelector(selector).appendChild(btn);
}
createButton()
is a function that creates the app’s two buttons; since all the buttons work similarly, this function avoids repeating code. The function has five parameters:
innerText
: the button’s text.id
: the button’s id.listener
: a callback function that’s executed when the user clicks the button.selector
: the <div>
element where you will append the button.disabled
: a boolean value to disable or enable the button. This parameter’s default value is false
.createButton()
starts by creating an instance of a button and assigns it to the variable btn
. Then, it sets the button’s innerText
, id
, and disabled
attributes. The button uses a click event listener that executes a callback function whenever you click it. The function’s last line appends the button to the <div>
element specified in the selector
parameter.
Next, you will create a new function named setupButtons()
that calls createButton()
two times to create the app’s buttons. Begin by creating the app’s Answer! button:
function setupButtons() {
// Button to predict
createButton('Answer!', 'answer-btn',
() => {
model.findAnswers(questionText.value, inputText.value).then((answers) => {
// Write the answers to the output div as an unordered list.
// It uses map create a new list of the answers while adding the list tags.
// Then, we use join to concatenate the answers as an array with a line break
// between answers.
const answersList = answers.map((answer) => `<li>${answer.text} (confidence: ${answer.score})</li>`)
.join('<br>');
answersOutput.innerHTML = `<ul>${answersList}</ul>`;
}).catch((e) => console.log(e));
}, '#answer-button', true);
}
The first button the function creates is the one that triggers the predictions. Its first two arguments, innerText
and id
, are the button’s text and the identifier you want to assign to the button. The third argument is the listener’s callback (explained below). The fourth argument, selector
, is the id of the <div> where you want to add the button (#answer-button
), and the fifth argument, disabled
, is set to true
, which disables the button (to avoid predicting before the app loads the model).
The listener’s callback is a function that’s executed once you click the Answer! button. Once clicked, the callback function first calls the pre-trained model’s function findAnswers()
. (For more about the findAnswers()
function, see the product documentation). findAnswers()
uses as arguments the input passage (read from questionText
) and the question (read from inputText
). It returns the model’s output in an array that looks as follows:
Model's output[
{
"text": "New York City",
"score": 19.08431625366211,
"startIndex": 84,
"endIndex": 97
},
{
"text": "in New York City",
"score": 8.737937569618225,
"startIndex": 81,
"endIndex": 97
},
{
"text": "New York",
"score": 7.998648166656494,
"startIndex": 84,
"endIndex": 92
},
{
"text": "York City",
"score": 7.5290607213974,
"startIndex": 88,
"endIndex": 97
},
{
"text": "headquartered in New York City",
"score": 6.888534069061279,
"startIndex": 67,
"endIndex": 97
}
]
Each of the array’s elements is an object of four attributes:
text
: the answer.score
: the model confidence level.startIndex
: the index of the passage’s first character that answers the question.endIndex
: the index of the answer’s last characters.Instead of displaying the output as the model returns it, the callback uses a map()
function that creates a new array containing the model’s answers and scores while adding the list <li>
HTML tags. Then, it joins the array’s elements with a <br>
(line break) between answers and assigns the result to the answer
<div>
to display them as a list.
Next, add a second call to createButton()
. Add the highlighted portion to the setupButtons
function beneath the first createButton
:
function setupButtons() {
// Button to predict
createButton('Answer!', 'answer-btn',
() => {
model.findAnswers(questionText.value, inputText.value).then((answers) => {
// Write the answers to the output div as an unordered list.
// It uses map create a new list of the answers while adding the list tags.
// Then, we use join to concatenate the answers as an array with a line break
// between answers.
const answersList = answers.map((answer) => `<li>${answer.text} (confidence: ${answer.score})</li>`)
.join('<br>');
answersOutput.innerHTML = `<ul>${answersList}</ul>`;
}).catch((e) => console.log(e));
}, '#answer-button', true);
createButton('DigitalOcean', 'test-case-do-btn',
() => {
document.getElementById('input-text').value = doText;
}, '#test-buttons', false);
}
This new call appends to the test-buttons
<div>
the button that loads the DigitalOcean sample text you defined earlier in the variable doText
. The function’s first argument is the label for the button (DigitalOcean), the second argument is the id
, the third is the listener’s callback that writes in the passage input text area the value of the doText
variable, the fourth is the selector
, and the last is a false
value (to avoid disabling the button).
Next, you will create a function, named init()
, that calls the other functions:
async function init() {
setupButtons();
answersOutput = document.getElementById('answer');
inputText = document.getElementById('input-text');
questionText = document.getElementById('question');
model = await qna.load();
document.getElementById('answer-btn').disabled = false;
}
init()
starts by calling setupButtons()
. Then, it assigns some of the app’s HTML elements to the variables you defined at the top of the script. Next, it loads the QnA model and changes to false
the disabled attribute of the answer (answer-btn
) button.
Last, call init()
:
init();
You have finished the app. To test it, open your web browser and write the project’s directory absolute path with /index.html
appended to it in the address bar. You could also open your file manager application (such as Finder on Mac) and click on “index.html” to open the web application. In this case, the address would look like your_filepath/tfjs-qna-do/index.html
.
To find the absolute path, go to the terminal and execute the following command from the project’s directory:
- pwd
Its output will look like this:
Output/Users/your_filepath/tfjs-qna-do
After launching the app, you will need to wait a few seconds while it downloads and loads the model. You will know it’s ready when the app enables the Answer! button. Then, you could either use the test passage button (DigitalOcean
) or write your own passage, and then input a question.
To test the app, click the “DigitalOcean” button. In the passage input area, you will see the sample text about DigitalOcean. In the question input area, write “Where is DigitalOcean headquartered?” From the passage, we can see the answer is “New York”. But will the model say the same? Click Answer! to find out.
The output should look similar to this:
Correct! Although there are slight differences, four of the five answers say that DigitalOcean’s headquarters are in New York City.
In this step, you completed and tested the web application. The JavaScript code you wrote reads the input passage and question and uses it as an input to the QnA model to answer the question. Next, you will add the code to GitHub.
In this section, you will add the web application to a GitHub repository. Later, you will connect the repository to DigitalOcean’s App Platform and deploy the app.
Start by logging in to GitHub. From its main page, click the green button under your name or the plus sign on the screen’s upper right corner to create a new repository.
Either choice takes you to the Create a new repository screen. In the Repository name field (after your username), name the repository tfjs-qna-do. Select its privacy setting, and click Create repository to create it.
Open a terminal and go to the project’s directory tfjs-qna-do/
. There, execute the following command to create a new local Git repository:
- git init
Next, stage the files you want to track with Git, which in this case, is everything in the directory:
- git add .
And commit them:
- git commit -m "initial version of the app"
Rename the repository’s principal branch to main
:
- git branch -M main
Then link your local repository with the remote one on GitHub:
- git remote add origin git@github.com:your-github-username/tfjs-qna-do.git
Last, push the local codebase to the remote repository:
- git push -u origin main
It will ask you to enter your GitHub credentials if this is the first time you are pushing code to it.
Once you have pushed the code, return to the GitHub repository and refresh the page. You should see your code.
In this step, you have pushed your web app’s code to a remote GitHub repository. Next, you will link this repository to your DigitalOcean account and deploy the app.
In this last section, you will deploy the Question and Answer app to DigitalOcean’s App Platform) from the GitHub repository created in Step 3.
Start by logging into your DigitalOcean account. Once logged in, click the Create green button in the upper right corner and then on Apps; this takes you to the Create new app screen:
Here, choose GitHub as the source where the project resides.
If you haven’t linked your DigitalOcean account with GitHub, it will ask you to authorize DigitalOcean to access your GitHub. After doing so, select the repository you want to link: tfjs-qna-do.
Back on the App Platform window, select the app’s repository (tfjs-qna-do), the branch from where it will deploy the app (main), and check the Autodeploy code changes box; this option ensures that the application gets re-deployed every time you push code to the main branch.
In the next screen, Configure your app, use the default configuration values. As an additional step, if you wish to change the web app’s HTTP requests route, from, for example, the default https://example.ondigitalocean.app/tfjs-qna-do, to https://example.ondigitalocean.app/my-custom-route, click on Edit under HTTP Routes and write my-custom-route in the ROUTES input.
Next, you will name the site. Again, you could leave the default tfjs-qna-do name or replace it with another one.
Clicking Next will take you to the last screen, Finalize and launch, where you will select the app’s pricing tier. Since the app is a static webpage, App Platform will automatically select the free Starter plan. Last, click the Launch Starter App button to build and deploy the application.
While the app is deployed, you will see a screen similar to this:
And once deployed, you will see:
To access the app, click on the app’s URL to access your app, which is now deployed in the cloud.
As the field of machine learning expands, so do its use cases alongside the environments and platforms it reaches – including the web browser.
In this tutorial, you have built and deployed a web application that uses a TensorFlow.js pre-trained model. Your Question and Answer web app takes as input a passage along with a question and uses a pre-trained BERT model to answer the question according to the passage. After developing the app, you linked your GitHub account with DigitalOcean and deployed the application in App Platform without needing additional code.
As future work, you could trigger the app’s automatic deployment by adding a change to it and pushing it to GitHub. You could also add a new test passage and format the answer’s output as a table to improve its readability.
For more information about TensorFlow.js, refer to its official documentation.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Hello! Thank you very much for creating this tutorial. Your clear explanations made learning about this topic straightforward and enjoyable. I was wondering if it is possible to use this model with languages other than English, or if it is possible to train it to do so?. Thank you.