Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!-- Copyright 2023 The MediaPipe Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. -->

<link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
<script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>

<h1>Classifying text with the MediaPipe Text Classifier Task</h1>
<p>This demo runs sentiment analysis on the input text. The result shows how likely the input text is to have a positive or negative sentiment.

<section id="demos" class="invisible">
  <h2>How to use</h2>
  <p>Add text to the input field, and then press <b>Classify</b> to view sentiment classification.</p>
  <p>You can <button class="mdc-button" id="populate-text">
      <span class="mdc-button__ripple"></span>
      <span class="mdc-button__label">POPULATE TEXT</span>
    </button> with a default input, or add your own text.</p>
  <p><b>Input:
    </b>
  </p>
  <label class="mdc-text-field mdc-text-field--filled mdc-text-field--textarea mdc-text-field--no-label">
    <span class="mdc-text-field__ripple"></span>
    <span class="mdc-text-field__resizer">

      <textarea id="input" class="mdc-text-field__input" rows="8" cols="40" aria-label="Text Input"></textarea>
    </span>
    <span class="mdc-line-ripple"></span>
  </label></br>
  <button id="submit" class="mdc-button mdc-button--raised">
    <span class="mdc-button__label">CLASSIFY</span>
  </button></br>

  <p><b>Sentiment:</b></p>
  <p id="output"></p>
</section>
              
            
!

CSS

              
                /* Copyright 2023 The MediaPipe Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

@use "@material";
body {
  font-family: roboto;
  margin: 2em;
  color: #3d3d3d;
  --mdc-theme-primary: #007f8b;
  --mdc-theme-on-primary: #f1f3f4;
}

h1 {
  color: #007f8b;
}

h2 {
  clear: both;
}

button {
  min-width: 200px;
  height: 50px;
}

section {
  opacity: 1;
  transition: opacity 500ms ease-in-out;
}

#input {
  height: 100px;
  --mdc-theme-primary: #12b5cb;
  --mdc-theme-on-primary: #f1f3f4;
}

#output {
  min-height: 100px;
  min-width: 500px;
  font-weight: bold;
}

.invisible {
  opacity: 0.2;
}

#submit {
  margin-top: 20px;
}

              
            
!

JS

              
                /* Copyright 2023 The MediaPipe Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

import { MDCTextField } from "https://cdn.skypack.dev/@material/textfield";
import {
  TextClassifier,
  FilesetResolver
} from "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-text@0.10.0";

const textField = new MDCTextField(document.querySelector(".mdc-text-field"));
const defaultText =
  "But soft, what light through yonder window breaks? \n \
It is the East, and Juliet is the sun.\n \
Arise, fair sun, and kill the envious moon,\n \
Who is already sick and pale with grief\n \
That thou, her maid, art far more fair than she.\n \
Be not her maid since she is envious.\n \
Her vestal livery is but sick and green,\n \
And none but fools do wear it. Cast it off.\n \
It is my lady. O, it is my love!\n \
O, that she knew she were!\n othing. What of that?\n \
Her eye discourses; I will answer it.";

// Get the required elements
const input = document.getElementById("input") as HTMLInputElement;
const output = document.getElementById("output") as HTMLElement;
const submit = document.getElementById("submit") as HTMLButtonElement;
const defaultTextButton = document.getElementById(
  "populate-text"
) as HTMLButtonElement;
const demosSection: HTMLElement = document.getElementById("demos");

let textClassifier: TextClassifier;
// Create the TextClassifier object upon page load
const createTextClassifier = async () => {
  const text = await FilesetResolver.forTextTasks(
    "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-text@0.10.0/wasm"
  );
  textClassifier = await TextClassifier.createFromOptions(text, {
    baseOptions: {
      modelAssetPath: `https://storage.googleapis.com/mediapipe-models/text_classifier/bert_classifier/float32/1/bert_classifier.tflite`
    },
    maxResults: 5
  });

  // Show demo section now model is ready to use.
  demosSection.classList.remove("invisible");
};
createTextClassifier();

// Add a button click listener to add the default text
defaultTextButton.addEventListener("click", () => {
  input.value = defaultText;
});

// Add a button click listener that classifies text on click
submit.addEventListener("click", async () => {
  if (input.value === "") {
    alert("Please write some text, or click 'Populate text' to add text");
    return;
  }

  output.innerText = "Classifying...";

  await sleep(5);
  const result = textClassifier.classify(
    input.value
  );
  displayClassificationResult(result);
});

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

// Iterate through the sentiment categories in the TextClassifierResult object, then display them in #output
function displayClassificationResult(result: TextClassifierResult) {
  if (result.classifications[0].categories.length > 0) {
    output.innerText = "";
  } else {
    output.innerText = "Result is empty";
  }
  const categories: string[] = [];
  // Single-head model.
  for (const category of result.classifications[0].categories) {
    const categoryDiv = document.createElement("div");
    categoryDiv.innerText = `${category.categoryName}: ${category.score.toFixed(
      2
    )}`;
    // highlight the likely category
    if (category.score.toFixed(2) > 0.5) {
      categoryDiv.style.color = "#12b5cb";
    }
    output.appendChild(categoryDiv);
  }
}

              
            
!
999px

Console