Watson Work Services Development

We’ve just concluded our Introduction to IBM Watson Work Services Development webinar.  Attendance was great, but if you missed it, here’s everything you need to get started developing.

Getting Started Webinar

Presentation on SlideShare

The replay is available here on Box.  There is an additional Developer Roundtable also on Box.

Samples, Samples, Samples!

Learn about APIs

Start Using IBM Watson Workspace

Questions?

Cognitive Listening

For a decade now, we’ve lived in a “social” era – through networks such as LinkedIn, Facebook, and IBM Connections.  Social networks have given us the tools by which we can engage in dialogue, share ideas, and find new information.  A simple example is the now-ubiquitous comments section seen on most websites.  Someone posts content, and someone writes back in the form of a comment.  Collectively, those comments reflect public perception, understanding, and support.  But to get a sense of the public’s reaction, you have to read through all of the comments.

This is where the emerging cognitive era can help.  Rather than manually read the comments, one could simply use a cognitive service to classify the emotions of commenters.  One such service is IBM’s AlchemyAPI.  Below I’ve combined Alchemy’s emotion analysis with IBM Connections’ comments to generate a “social reaction” to my post.

Connections Sentiment

Admittedly, people aren’t really angry with my post – maybe it’s the exclamation marks being used by commenters … but you get the point.  In isolation, this is a neat trick.  But when you apply this on a larger scale, it gives you the ability to listen cognitively to the social network.  For example, an active forum of actual angry customers could trigger intervention by a customer support representative.  Or combined with other services – like concept extraction – would tell us which areas of the company, initiative, or project that employees are struggling with.  The possibilities and outcomes are substantial, which is why cognitive is more than just technology. It’s a new era of business and computing.

Getting Started

  1. Lots of information exists on using AlchemyAPI.  Start out by creating an account on Bluemix and adding the service.
  2. I used a tool called Greasemonkey to add the “Reaction widget” to IBM Connections Blog pages.  Think of Greasemonkey as a way of creating small, personal applications that run only in your browser.
  3. Adapt my widget below to experiment with content an APIs.
// ==UserScript==
// @name        Blog Entry Emotion Analyzer
// @namespace   http://demos.ibm.com
// @include     https://apps.*.collabserv.com/blogs/*/entry/*
// @include     https://w3-connections.ibm.com/blogs/*/entry/*
// @version     1
// @require     https://code.jquery.com/jquery-3.1.0.min.js
// @require     https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js
// @grant       GM_xmlhttpRequest
// ==/UserScript==


console.log("Starting up Blog Entry Emotion Analyzer Widget");

// setup the widget in right side column
var sidebar = $( ".lotusColRight" )

if(sidebar.length){
  // any html added to DOM MUST USE SINGLE QUOTES
  sidebar.append("<div aria-expanded='true' name='reaction_section_mainpart' class='lotusSection' role='complementary' aria-label='Tone' aria-labelledby='section_reaction_label'><label class='lotusOffScreen' aria-live='polite' id='reaction_section_hint_label'>Expanded section</label><h2 style='cursor:default'><span id='section_authors_label' class='lotusLeft'>Reaction</div></span></h2><div id='section_reaction' class='lotusSectionBody'><span class='lotusBtn lotusLeft'><a id='analyzeButton' role='button' href='javascript:;'>Analyze Comments</a></span><canvas id='watsonChart' width='300' height='300'></canvas></div></div>");
  
  // attach an event handler to do the analysis when button is clicked
  $("#analyzeButton").click(function() {
    
    // inform the user something is happening
    $("#analyzeButton").text("Analyzing ...")
    
    // get the html of the blog entry
    var entryHtml = $("div.entryContentContainer");

    // get the html of the blog comments
    // var commentsHtml = $("#blogCommentPanel"); // Connections Cloud
    var commentsHtml = $( "div[dojoattachpoint='commentsAP']" ); // Connections on-prem

    // decide whether you want to use AlchemyAPI against comments or the entry
    if(commentsHtml.length) {
      post(commentsHtml.html());

    } else {
      console.error("Could not find text entry; can't add widget");
    }
  });
} else {
  console.error("No sidebar found in HTML; can't add widget");
}

function post(html) {
  // any HTML text sent to AlchemyAPI needs encoded
  html = encodeURIComponent(html);
  
   console.log("Sending text to AlchemyAPI: " + html);
  
  // send the html to watson APIs
  GM_xmlhttpRequest({
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    url: "https://watson-api-explorer.mybluemix.net/alchemy-api/calls/html/HTMLGetEmotion",
    data: "apikey=<use your own API key>&outputMode=json&html=" + html,
    onload: function(response) {
      console.log(response.responseText);

      // received response; construct the widget
      createChart(response);
    },
    onerror: function(response) {
      console.error(response.responseText);
    }
  });
}
 
function createChart(response) {
  console.log("Creating chart");
  
  // remove the analyze button from the view
  $("#analyzeButton").hide();
  
  // convert the API response to JSON
  var json = JSON.parse(response.responseText);
  
  // set up the chart
  var ctx = $("#watsonChart");
  
  if(ctx == undefined) {
    console.error("Context for chart not found");
  }
  
  var data = {
    labels: ["Anger", "Disgust", "Fear", "Joy", "Sadness"],
    datasets: [
      {
        label: "Sentiment",
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(54, 162, 235, 0.2)'

        ],
        borderColor: [
          'rgba(255,99,132,1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(54, 162, 235, 1)'

        ],
        borderWidth: 1,
        data: [
          json.docEmotions.anger,
          json.docEmotions.disgust,
          json.docEmotions.fear,
          json.docEmotions.joy,
          json.docEmotions.sadness,
        ],
      }
    ]
  };
  
  // add the chart to the view
  var myBarChart = new Chart(ctx, {
      type: 'horizontalBar',
      data: data,
      options: {
        title: {
          display: false
        },
        legend: {
          display: false
        }
      }
  });
}

Installing Greasemonkey Reaction Widget

  1. Launch your Firefox browser.
  2. Head over to the Greasemonkey addon page.
  3. Click the “Add to Firefox” button.
  4. You’ll then see a little monkey on the toolbar.
  5. Copy the script above to the clipboard.
  6. Click “Add New User Script”.
  7. Click “Use Script From Clipboard”.
  8. Change the script as needed.

New User Script

Greasemonkey Script

Greasemonkey Editor

How It Works

A few things to point out:

  • The top of the script defines where the “application” can run.  I’ve made it so that the widget will be added to IBM Connections Cloud and IBM’s Connections deployment.  You should update the @include line to reflect your server installation.  The @include directive also says to run the application only on Blog entry pages.  It does not currently run on a wiki or forum page for example.
  • The script will add a button to the right sidebar.  Pressing the button invokes the AlchemyAPI.
  • The text sent to AlchemyAPI is obtained from the Comments section of the post.  All we’re doing here is grabbing the HTML from inside your browser and making an API call.  AlchemyAPI does the rest.
  • I’m using Chart.js to create the chart.  I’ve used it before on other blog posts.
  • The color of the emotions in the chart is similar to the “Inside Out” characters. 😉

Inside OutHappy coding!