Powered by
/src$ make
  • Home
  • About
  • Directory
  • Contact
  • Home
  • About
  • Directory
  • Contact

IBM Watson: Personality Insights - Code Example

2/26/2018

 

Introduction - IBM Watson/Bluemix Services

We've already had two blog posts on IBM Watson so far. One blog post for Watson's Tone Analyzer service, and another blog post for Watson's Visual Recognition service. We're going to go through this article quickly since we already have a lot of experience using Watson. If this is your first time, see the Tone Analyzer service since it's meant for people getting started. 

​IBM's Personality Insight service "predicts personality characteristics, needs, and values through written text." We're going to go through setting the service up, and creating a node project to use that service. 

Create The Service On IBM's Website

First, we need to set the Personality Insight service up on IBM's website. If you don't have a Bluemix account, register for one. (Free, very easy, no credit card.)

Next, go to the Personality Insights page and click the "Get started free" button. (Log in if you need too.)

You'll be prompted to create a new project. For the project name, enter "srcmakePersonality" and click the "Create Project" button on the bottom right of the screen. 

You'll be taken to your project page. Click the "Show" button and make note of the username and password under the Credentials section. We'll need to use them soon to authenticate our API calls to the Personality Insights API.

(Did this section seem fast? Remember to watch the youtube video for this topic or go back and read the Tone Analyzer article, since we went through these steps in detail.)

So we have our API credentials, now we need to actually write some code to use the service. 

Setting Up Our Node Project

We're going to make a project using Node to test using the Personality Insights service. Since this is just going to be a basic project (that we've already went over in detail in the Tone Analyzer article), just copy the code from GitHub. In your terminal in the folder you want the project to be stored in: 
git clone https://github.com/srcmake/watson-node-starter
cd watson-node-starter
It's a basic node project with the Watson library installed, and a config.js file to store our credentials.

Open "config.js" and for the username and password, enter the usename and password that we got in the previous section after creating the srcmakePersonality project on the Bluemix website. 

Adding The Personality Insight Code

Our project is set up, but doesn't actually do anything useful yet. We want to test the Personality Insight service. Specifically, we want to make an API call to it and pass it some text to be analyzed. We're going to write code that does that, with the help of the API reference documentation. 

Add the following code to "index.js".
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Copyright www.srcmake.com 2018.
// Require our libraries and our config file.
var PersonalityInsightsV3 = require('watson-developer-cloud/personality-insights/v3');
var config = require('./config');

// Start the visualizer service by authenticating with our API key.
var personality_insights = new PersonalityInsightsV3(
        {
        username: config.username,
        password: config.password,
        version_date: '2017-10-13'
        });
        
// Our example text needs to be at least 100 words.
// The following is MLKJ's "I Have A Dream" speech.
var text = "I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.\n\nFive score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of their captivity.\n\nBut one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself an exile in his own land. And so we've come here today to dramatize a shameful condition.\n\nIn a sense we've come to our nation's capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to fall heir. This note was a promise that all men, yes, black men as well as white men, would be guaranteed the \"unalienable Rights\" of \"Life, Liberty and the pursuit of Happiness.\" It is obvious today that America has defaulted on this promissory note, insofar as her citizens of color are concerned. Instead of honoring this sacred obligation, America has given the Negro people a bad check, a check which has come back marked \"insufficient funds.\"\n\nBut we refuse to believe that the bank of justice is bankrupt. We refuse to believe that there are insufficient funds in the great vaults of opportunity of this nation. And so, we've come to cash this check, a check that will give us upon demand the riches of freedom and the security of justice.\n\nWe have also come to this hallowed spot to remind America of the fierce urgency of Now. This is no time to engage in the luxury of cooling off or to take the tranquilizing drug of gradualism. Now is the time to make real the promises of democracy. Now is the time to rise from the dark and desolate valley of segregation to the sunlit path of racial justice. Now is the time to lift our nation from the quicksands of racial injustice to the solid rock of brotherhood. Now is the time to make justice a reality for all of God's children.\n\nIt would be fatal for the nation to overlook the urgency of the moment. This sweltering summer of the Negro's legitimate discontent will not pass until there is an invigorating autumn of freedom and equality. Nineteen sixty-three is not an end, but a beginning. And those who hope that the Negro needed to blow off steam and will now be content will have a rude awakening if the nation returns to business as usual. And there will be neither rest nor tranquility in America until the Negro is granted his citizenship rights. The whirlwinds of revolt will continue to shake the foundations of our nation until the bright day of justice emerges.\n\nBut there is something that I must say to my people, who stand on the warm threshold which leads into the palace of justice: In the process of gaining our rightful place, we must not be guilty of wrongful deeds. Let us not seek to satisfy our thirst for freedom by drinking from the cup of bitterness and hatred. We must forever conduct our struggle on the high plane of dignity and discipline. We must not allow our creative protest to degenerate into physical violence. Again and again, we must rise to the majestic heights of meeting physical force with soul force.\n\nThe marvelous new militancy which has engulfed the Negro community must not lead us to a distrust of all white people, for many of our white brothers, as evidenced by their presence here today, have come to realize that their destiny is tied up with our destiny. And they have come to realize that their freedom is inextricably bound to our freedom.\n\nWe cannot walk alone.\n\nAnd as we walk, we must make the pledge that we shall always march ahead.\n\nWe cannot turn back.\n\nThere are those who are asking the devotees of civil rights, \"When will you be satisfied?\" We can never be satisfied as long as the Negro is the victim of the unspeakable horrors of police brutality. We can never be satisfied as long as our bodies, heavy with the fatigue of travel, cannot gain lodging in the motels of the highways and the hotels of the cities. **We cannot be satisfied as long as the negro's basic mobility is from a smaller ghetto to a larger one. We can never be satisfied as long as our children are stripped of their self-hood and robbed of their dignity by signs stating: \"For Whites Only.\"** We cannot be satisfied as long as a Negro in Mississippi cannot vote and a Negro in New York believes he has nothing for which to vote. No, no, we are not satisfied, and we will not be satisfied until \"justice rolls down like waters, and righteousness like a mighty stream.\"\n\n \n\nI am not unmindful that some of you have come here out of great trials and tribulations. Some of you have come fresh from narrow jail cells. And some of you have come from areas where your quest -- quest for freedom left you battered by the storms of persecution and staggered by the winds of police brutality. You have been the veterans of creative suffering. Continue to work with the faith that unearned suffering is redemptive. Go back to Mississippi, go back to Alabama, go back to South Carolina, go back to Georgia, go back to Louisiana, go back to the slums and ghettos of our northern cities, knowing that somehow this situation can and will be changed.\n\nLet us not wallow in the valley of despair, I say to you today, my friends.\n\nAnd so even though we face the difficulties of today and tomorrow, I still have a dream. It is a dream deeply rooted in the American dream.\n\nI have a dream that one day this nation will rise up and live out the true meaning of its creed: \"We hold these truths to be self-evident, that all men are created equal.\"\n\nI have a dream that one day on the red hills of Georgia, the sons of former slaves and the sons of former slave owners will be able to sit down together at the table of brotherhood.\n\nI have a dream that one day even the state of Mississippi, a state sweltering with the heat of injustice, sweltering with the heat of oppression, will be transformed into an oasis of freedom and justice.\n\nI have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character.\n\nI have a dream today!\n\nI have a dream that one day, down in Alabama, with its vicious racists, with its governor having his lips dripping with the words of \"interposition\" and \"nullification\" -- one day right there in Alabama little black boys and black girls will be able to join hands with little white boys and white girls as sisters and brothers.\n\nI have a dream today!\n\nI have a dream that one day every valley shall be exalted, and every hill and mountain shall be made low, the rough places will be made plain, and the crooked places will be made straight; \"and the glory of the Lord shall be revealed and all flesh shall see it together.\"\n\nThis is our hope, and this is the faith that I go back to the South with.\n\nWith this faith, we will be able to hew out of the mountain of despair a stone of hope. With this faith, we will be able to transform the jangling discords of our nation into a beautiful symphony of brotherhood. With this faith, we will be able to work together, to pray together, to struggle together, to go to jail together, to stand up for freedom together, knowing that we will be free one day.\n\nAnd this will be the day -- this will be the day when all of God's children will be able to sing with new meaning:\n\nMy country 'tis of thee, sweet land of liberty, of thee I sing. Land where my fathers died, land of the Pilgrim's pride,    From every mountainside, let freedom ring!\n\nAnd if America is to be a great nation, this must become true.\n\nAnd so let freedom ring from the prodigious hilltops of New Hampshire.\n\nLet freedom ring from the mighty mountains of New York.\n\nLet freedom ring from the heightening Alleghenies of Pennsylvania.\n\nLet freedom ring from the snow-capped Rockies of Colorado.\n\nLet freedom ring from the curvaceous slopes of California.\n\nBut not only that:\n\nLet freedom ring from Stone Mountain of Georgia.\n\nLet freedom ring from Lookout Mountain of Tennessee.\n\nLet freedom ring from every hill and molehill of Mississippi.\n\nFrom every mountainside, let freedom ring.\n\nAnd when this happens, and when we allow freedom ring, when we let it ring from every village and every hamlet, from every state and every city, we will be able to speed up that day when all of God's children, black men and white men, Jews and Gentiles, Protestants and Catholics, will be able to join hands and sing in the words of the old Negro spiritual:\n\nFree at last! Free at last!\n\nThank God Almighty, we are free at last!";

// Our data.
var params = 
        {
        content: text,
        content_type: 'text/plain',
        raw_scores: true
        };


// Call the Personality Insights API.
personality_insights.profile(params, function(error, response) 
        {
        // No error, so output the response.
        if (!error)
            {
            var res = JSON.stringify(response, null, 2);
            console.log(res);   
            }
        else
            {
            console.log('Error:', error);
            }
        });
We simply include the watson library and our config library. The text we want to analyze is Martin Luther King Jr's "I Have a Dream" speech. We call the Personality Insights API on this text, and output the result. 

Testing Our Code

Testing our code is simple. In the command line, run index.js.
node index.js
You'll see the following output:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
{
  "word_count": 1668,
  "processed_language": "en",
  "personality": [
    {
      "trait_id": "big5_openness",
      "name": "Openness",
      "category": "personality",
      "percentile": 0.9971829354818533,
      "raw_score": 0.8370362576019849,
      "significant": true,
      "children": [
        {
          "trait_id": "facet_adventurousness",
          "name": "Adventurousness",
          "category": "personality",
          "percentile": 0.7576479501350015,
          "raw_score": 0.52966968918565,
          "significant": true
        },
        {
          "trait_id": "facet_artistic_interests",
          "name": "Artistic interests",
          "category": "personality",
          "percentile": 0.9991162996420972,
          "raw_score": 0.8236122278631651,
          "significant": true
        },
        {
          "trait_id": "facet_emotionality",
          "name": "Emotionality",
          "category": "personality",
          "percentile": 0.8334349508251087,
          "raw_score": 0.6876522602064208,
          "significant": true
        }
  ],
  "warnings": []
}

Actually, the output was 440 lines long! But I cut it down to only the first three traits. You can see that Watson returns some personality names, and some numbers that correspond to what the speaker/writer of the text is of that personality.

Conclusion

In this article, we looked at and coded for the Watson Personality Insight service. It was pretty simple, all we did was create a project on the Bluemix website to get a username and password, then we wrote some Node code to call the API that controls the Personality Insight service. 

Obviously, you can spin the project off and customize it for whatever your need is, but we at least know how to use the service. 
Like this content and want more? Feel free to look around and find another blog post that interests you. You can also contact me through one of the various social media channels. 

Twitter: @srcmake
Discord: srcmake#3644
Youtube: srcmake
Twitch: www.twitch.tv/srcmake
​Github: srcmake
References:
1. www.ibm.com/watson/services/personality-insights/
2. console.bluemix.net/docs/services/personality-insights/getting-started.html#getting-started-tutorial
3. https://www.ibm.com/watson/developercloud/personality-insights/api/v3/?node#authentication

Comments are closed.

    Author

    Hi, I'm srcmake. I play video games and develop software. 

    Pro-tip: Click the "DIRECTORY" button in the menu to find a list of blog posts.
    Metamask tip button
    License: All code and instructions are provided under the MIT License.

    Discord

    Chat with me.


    Youtube

    Watch my videos.


    Twitter

    Get the latest news.


    Twitch

    See the me code live.


    Github

    My latest projects.

Powered by Create your own unique website with customizable templates.