Integration

Sentiments Analysis using Salesforce Einstein API

Sentiments Analysis using Salesforce Einstein API



In continuation of the series of Salesforce Einstein posts, this post will explain the basic steps and prerequisites required to leverage salesforce Language API to describe the Sentiments of the text.

The Einstein Sentiments API helps the user to decide if the summary of the body of the text is positive or negative without going through the text.

Pre Requisite :

1) Sign Up for Einstein Platform Services Account:
 Copy and paste this link to create an Einstein Platform services account https://api.einstein.ai/signup

Click on Sign Up using Salesforce.

log in using your Salesforce credentials



Click on allow and then click download to save the einstein_platform.pem file.

2) Upload the key to Salesforce Files.



Navigate to files tab in sales application and then click upload. select the file downloaded in step 1 and click on done.


3) Create a remote site setting:


Log in to Salesforce.
From Setup, enter Remote Site in the Quick Find box, then select Remote Site Settings.
Click New Remote Site.
Enter a name for the remote site.
In the Remote Site URL field, enter https://api.einstein.ai.
Click Save.

similarly, create one more remote site setting with https://api.metamind.io as the site url

4) Create Apex Classes:

Clone two apex classes (JWT.apex and JWTBearer.apex) from the repository  https://github.com/salesforceidentity/jwt.

In Salesforce, from Setup, enter Apex Classes in the Quick Find box, then select Apex Classes.
Click New.
To create the JWT Apex class, copy all the code from JWT.apex into the Apex Class tab and click Save.
To create the JWTBearerFlow Apex class, go back to to the Apex Classes page, and click New.
Copy all the code from JWTBearer.apex to the Apex Class tab and click Save.


This completes the prerequisites for sentiment analysis.
Now let us begin and create a Visualforce page and controller which could be used to predict the sentiments.

copy and paste the code to create two classes as mentioned below:

global class SentimentAnalysisResponse {
    webservice List<Probabilities> probabilities    { get; set; } 
    
    global class Probabilities {
        webservice String label                     { get; set; } 
        webservice Double probability               { get; set; }
    }
}

Controller :
public class EinsteinAPI {
public string TextToPredict {get;set;}
public SentimentAnalysisResponse resp{get;set;}    
    //constructor
    public EinsteinAPI (){
    
    } 
    
    public void checkSentiments() {
        resp = findSentiment(TextToPredict );
    }
    
    
    public String getAccessToken() {
        ContentVersion base64Content = [
            SELECT  Title
                    ,VersionData
            FROM    ContentVersion
            WHERE   Title = 'einstein_platform'
            OR      Title = 'predictive_services'
            ORDER BY Title
            LIMIT 1
        ];
        
        String keyContents  = base64Content.VersionData.tostring();
        keyContents         = keyContents.replace( '-----BEGIN RSA PRIVATE KEY-----', '' );
        keyContents         = keyContents.replace( '-----END RSA PRIVATE KEY-----', '' );
        keyContents         = keyContents.replace( '\n', '' );

        JWT jwt             = new JWT( 'RS256' );
        
        jwt.pkcs8           = keyContents; 
        jwt.iss             = 'developer.force.com';
        jwt.sub             = 'Saurabh.dua@XXX.XXX'; // Update with your own email ID
        jwt.aud             = 'https://api.metamind.io/v1/oauth2/token';
        jwt.exp             = String.valueOf(3600);
        String access_token = JWTBearerFlow.getAccessToken( 'https://api.metamind.io/v1/oauth2/token', jwt );
        return access_token;
    }
    
    /**
     * This method is created to make call
     * to the Sentiment Endpoint and get 
     * the Sentiment of the block of text.
     * 
     * @param       text                        Block of text whose Sentiment has to be analysed
     * 
     * @return      SentimentAnalysisResponse   Returns an instance of SentimentAnalysisResponse class
     */
    public SentimentAnalysisResponse findSentiment( String text ) {
        String key = getAccessToken();
        
        Http http = new Http();
        
        HttpRequest req = new HttpRequest();
        req.setMethod( 'POST' );
        req.setEndpoint( 'https://api.einstein.ai/v2/language/sentiment');
        req.setHeader( 'Authorization', 'Bearer ' + key );
        req.setHeader( 'Content-type', 'application/json' );
        
        String body = '{\"modelId\":\"CommunitySentiment\",\"document\":\"' + text + '\"}';
        req.setBody( body );
        
        HTTPResponse res = http.send( req );
        
        SentimentAnalysisResponse resp = ( SentimentAnalysisResponse ) JSON.deserialize( res.getBody(), SentimentAnalysisResponse.class );
        
        return resp;
    }

}


Visualforce page code :

<apex:page controller="EinsteinAPI">
<apex:form >
    <b>Enter the Text for analysis</b><br/>
    <apex:inputTextarea value="{!TextToPredict}"/><br/>
    <apex:commandButton value="Check Sentiments" action="{!checkSentiments}" reRender="ResponsePanel"/>
    <hr/>
    <apex:outputPanel id="ResponsePanel">
        <table width="100%">
            <tr>
                <th>Label</th>
                <th>Probability</th>
            </tr>    
        <apex:repeat value="{!resp.probabilities}" var="r">
            <tr>
                <td>{!r.label}</td>
                <td>{!r.probability}</td>
            </tr>    
        </apex:repeat>
        </table>
    </apex:outputPanel>
</apex:form>
</apex:page>

Preview the Visualforce page and check the sentiments of the text.


Live demo Below , Start by entering text and click on check sentiments to see the results

 




https://einsteinlanguage-developer-edition.ap5.force.com/Einstein/

About Saurabh Dua

1 comments:

  1. Hi Saurabh everything got saved without any error but is not giving any results.



    ReplyDelete

Powered by Blogger.