1. 程式人生 > >How to create a browser extension that leverages IBM Watson cognitive API

How to create a browser extension that leverages IBM Watson cognitive API

You want to use IBM Watson API cognitive solutions, but theyb re too often integrated with products that you donb t need. Browser extensions extend your browsersb capabilities and provide better online experiences for users. In this tutorial, we show you how to create a browser extension that uses Watson APIs via a browser extension, so that you can use the popular API.

Learning objectives

In this tutorial, developers will create a browser extension that uses IBM Watson cognitive API. This browser allows users to consume Language Translation & Tone Analyzer services on their e-mail, calendar, and any other web portals.

Prerequisites

Before beginning this tutorial, you’ll need:

Estimated time

Completing this tutorial should take approximately 15 minutes.

Steps

Step 1: Create Watson services on IBM Cloud

  1. Click Catalog and search for Language Translator.

  2. Create a Language Translator service. Once the service is created, you are directed to the service page where you can see the service credentials. Click on Show Credentials, and you see a username and password for the newly created service.

    Take note of the credentials appearing here, we’ll need them in the next step.

  3. Repeat steps 1 – 3 for the Tone Analyzer service.

Step 2: Create a Chrome browser extension

  1. In a new directory create two files and name them, manifest.json and contentscript.js.

  2. Open the working directory with your favorite IDE. Open the manifest.json file and update it with the content below.

    {
        "name": "IBM Watson Extension V1",
        "version": "1.0",
        "manifest_version": 2,
        "description": "Chrome Extension to access IBM Watson API",
        "icons": {
            "128": "ibmwatson.png"
        },
        "author": "Shankar Venkatachalam1/India/IBM",
        "background": {
            "scripts": ["contentscript.js"]
        },
        "content_scripts": [{
            "matches": [
                "https://*/",
                "http://*/*"
    
            ],
            "all_frames": true,
            "js": ["contentscript.js"]
        }],
        "web_accessible_resources": [
            "contentscript.js"
        ],
        "permissions": [
            "contextMenus",
            "storage",
            "activeTab",
            "tabs",
            "http://*/*",
            "https://*/*"
        ]
    }
    
  3. You need a logo for your extension. You can use your own or download this one. The image name needs to match the value of the icons key in the file above. In this case, it is ibmwatson.png. Save this in the root directory of the workspace.

  4. Now open your file, contentscript.js, and copy the lines below.

    const languageTranslatorUsername = "32e86ec8-723c-4008-9794-403db5819c00";
    const languageTranslatorPassword = "4oKBNnbomj8P";
    const toneAnalyzerUsername = "36d3f118-bcdb-436d-91f9-c87a686dba02";
    const toneAnalyzerPassword = "PSURBoojx7P2";
    
    var callToneAnalyzer = function (word) {
        //Authorization needs to be in base64
        var encodedData = window.btoa(toneAnalyzerUsername + ":" + toneAnalyzerPassword);
        var toneAuth = "Basic " + encodedData;
        var textContent = String(word.selectionText);
        var inputContent = textContent.replace(/%20/g, "");
        var xhr = new XMLHttpRequest();
        var toneURL = "https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?sentences=true&version=2016-05-19&text=\'";
        xhr.open("GET", toneURL + inputContent + "\'", false);
        xhr.setRequestHeader("Authorization", toneAuth);
        xhr.send();
    
        var result = xhr.responseText;
        var obj = JSON.parse(result);
        var angerTone = obj.document_tone.tone_categories[0].tones[0].tone_name;
        var angerScore = obj.document_tone.tone_categories[0].tones[0].score;
    
        var disgustTone = obj.document_tone.tone_categories[0].tones[1].tone_name;
        var disgustScore = obj.document_tone.tone_categories[0].tones[1].score;
    
        var fearTone = obj.document_tone.tone_categories[0].tones[2].tone_name;
        var fearScore = obj.document_tone.tone_categories[0].tones[2].score;
    
        var joyTone = obj.document_tone.tone_categories[0].tones[3].tone_name;
        var joyScore = obj.document_tone.tone_categories[0].tones[3].score;
    
        var sadnessTone = obj.document_tone.tone_categories[0].tones[4].tone_name;
        var sadnessScore = obj.document_tone.tone_categories[0].tones[4].score;
    
        alert(angerTone + "=  " + angerScore * 100 + " %" + ";" + "\n" + disgustTone + "= " + disgustScore * 100 + " %" + "\n" + fearTone + "= " + fearScore * 100 + " %" + "\n" + joyTone + "= " + joyScore * 100 + " %" + "\n" + sadnessTone + "= " + sadnessScore * 100 + " %");
    };
    
    function Translator(word, lang, langname) {
        //Authorization needs to be in base64
        var encodedData = window.btoa(languageTranslatorUsername + ":" + languageTranslatorPassword);
        var languageAuth = "Basic " + encodedData
        var textContent = String(word.selectionText);
        var inputContent = textContent.replace(/%20/g, " ");
        var xmlRequest = new XMLHttpRequest();
    
        if (window.XMLHttpRequest) {
            var translateURL = "https://gateway.watsonplatform.net/language-translator/api/v2/translate?source=en⌖=";
            xmlRequest.open("GET", translateURL + String(lang) + "&text=" + inputContent + "\'", true);
            xmlRequest.setRequestHeader("Authorization", languageAuth);
            xmlRequest.setRequestHeader("Content-type", "text/plain");
            xmlRequest.send();
    
            xmlRequest.onreadystatechange = function () {
                if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
                    alert("Translated to  " + langname + "\n" + xmlRequest.responseText);
                }
            };
        }
    
        return;
    }
    
    function generalTranslator(word) {
    
        var childname = word.menuItemId;
    
        if (childname == 'child1') {
            Translator(word, 'es', 'Spanish');
            return;
        }
        if (childname == 'child2') {
            Translator(word, 'ar', 'Arabic');
            return;
        }
        if (childname == 'child3') {
            Translator(word, 'fr', 'French');
            return;
        }
        if (childname == 'child4') {
            Translator(word, 'pt', 'Portuguese');
            return;
        }
        if (childname == 'child5') {
            Translator(word, 'de', 'German');
            return;
        }
    }
    
    chrome.contextMenus.create({
        title: "IBM Watson API V1",
        id: 'parent',
        contexts: ["selection"]
    });
    
    chrome.contextMenus.create({
        title: "Translate to Spanish",
        parentId: "parent",
        id: "child1",
        contexts: ["selection"],
        onclick: generalTranslator
    });
    
    chrome.contextMenus.create({
        title: "Translate to Arabic",
        parentId: "parent",
        id: "child2",
        contexts: ["selection"],
        onclick: generalTranslator
    });
    
    chrome.contextMenus.create({
        title: "Translate to French",
        parentId: "parent",
        id: 'child3',
        contexts: ["selection"],
        onclick: generalTranslator
    });
    
    chrome.contextMenus.create({
        title: "Translate to Portuguese",
        parentId: "parent",
        id: 'child4',
        contexts: ["selection"],
        onclick: generalTranslator
    });
    
    chrome.contextMenus.create({
        title: "Translate to German",
        parentId: "parent",
        id: 'child5',
        contexts: ["selection"],
        onclick: generalTranslator
    });
    
    chrome.contextMenus.create({
        title: "Tone Analyzer",
        parentId: "parent",
        id: 'child6',
        contexts: ["selection"],
        onclick: callToneAnalyzer
    });
    
  5. You need to update the lines below with the Watson service credentials from the previous step.

    const languageTranslatorUsername = "32e86ec8-723c-4008-9794-403db5819c00";
    const languageTranslatorPassword = "4oKBNnbomj8P";
    const toneAnalyzerUsername = "36d3f118-bcdb-436d-91f9-c87a686dba02";
    const toneAnalyzerPassword = "PSURBoojx7P2";
    

Step 3: Test your Chrome extension

  1. Launch Chrome and go to the extension overview page: chrome://extensions.

  2. Enable Developer mode by clicking the checkbox in the upper-right corner.

  3. Click on the Load unpacked extension button.

  4. Select the directory containing your unpacked extension, either contentscript.js or manifest.json.

  5. After loading the directory, you should see that the extension is set to enabled. In the figure below, the name of the extension is IBM Watson Chrome Extension.

  6. After following the steps above, right click on your Chrome browser, you should then see a menu to interact with IBM Watson API services. Letb s try it out.

    • Highlight a portion of text and right click to see IBM Watson in the context menu.

    • Select a language to see the translated output.

    • Check the tone of the words using the same steps.

Summary

In this tutorial, you’ve successfully created a Chrome browser extension that used Watson API to anaylze tone and translate language.

FAQ

  1. How does this browser extension help on a globally dispersed team with members who speak different languages?

    Well, we canb t expect everyone to speak or understand every language. Certain forms of jargon, slang, or colloquialisms are hard to translate and can lead to misunderstandings. Browser extensions are easy to use, and anyone can use them in their work on any platform.

  2. What are the benefits of checking the tone of an email?

    When writing text, we sometimes ask ourselves how the recipient will interpret the message web re trying to convey. By using the browser extension you just successfully created, you now have access to a tone analyzer service that can help with analyzing your messages and can also provide suggestions to re-write messages to align to the sentiment of your choice.

A special thank you to the following people for their contributions and mentoring on this project: