PHP Classes

File: google_natural_language_sentiment_analysis.php

Recommend this page to a friend!
  Classes of Manuel Lemos   PHP OAuth Library   google_natural_language_sentiment_analysis.php   Download  
File: google_natural_language_sentiment_analysis.php
Role: Example script
Content type: text/plain
Description: Google natural language artificial intelligence API call example script
Class: PHP OAuth Library
Authorize and access APIs using OAuth
Author: By
Last change: Made the user profile always be retrieved.
Added mode explanatory comments.
Removed needless code.
Date: 10 days ago
Size: 6,096 bytes
 

Contents

Class file image Download
<?php
/*
 * google_natural_language_sentiment_analysis.php
 *
 * @(#) $Id: google_natural_language_sentiment_analysis.php,v 1.7 2024/01/10 11:21:43 mlemos Exp $
 *
 */

    /*
     * Get the http.php file from http://www.phpclasses.org/httpclient
     */
   
require('http.php');
    require(
'oauth_client.php');

   
/*
     * Initialize the OAuth client class.
     *
     */
   
$client = new oauth_client_class;
   
$client->server = 'Google';

   
/*
     * Set the debug variable to true only if there is something wrong you
     * need to understand and fix.
     *
     */
   
$client->debug = false;
   
$client->debug_http = true;
   
$client->redirect_uri = 'https://'.$_SERVER['HTTP_HOST'].
       
dirname(strtok($_SERVER['REQUEST_URI'],'?')).'/google_natural_language_sentiment_analysis.php';

   
/*
     * Set the client_id and client_secret with credentials obtained from the Google Cloud Console
     *
     */
   
$client->client_id = ''; $application_line = __LINE__;
   
$client->client_secret = '';

    if(
strlen($client->client_id) == 0
   
|| strlen($client->client_secret) == 0)
        die(
'Please go to Google APIs console page '.
           
'https://console.cloud.google.com/apis/library/language.googleapis.com in the API access tab, '.
           
'create a new client ID, and in the line '.$application_line.
           
' set the client_id to Client ID and client_secret with Client Secret. '.
           
'The callback URL must be '.$client->redirect_uri.' but make sure '.
           
'the domain is valid and can be resolved by a public DNS.');

   
/* API permissions
     */
   
$client->scope = 'https://www.googleapis.com/auth/cloud-language'.' '.
       
'https://www.googleapis.com/auth/userinfo.profile';
   
   
/*
     * Initialize and call the PHP OAuth client class to call the Google
     * Natural Language API.
     *
     */
   
if(($success = $client->Initialize()))
    {
        if((
$success = $client->Process()))
        {
            if(
strlen($client->authorization_error))
            {
               
$client->error = $client->authorization_error;
               
$success = false;
            }
            elseif(
strlen($client->access_token))
            {
               
/*
                 * Call the Google account user profile API to get the user name
                 *
                 */
               
$success = $client->CallAPI(
                   
'https://www.googleapis.com/oauth2/v1/userinfo',
                   
'GET', array(), array('FailOnAccessError'=>true), $user);
                if(
$success)
                {
                   
/*
                     * Check if the form to enter the text to analyzed
                     * was submitted.
                     *
                     */
                   
if(IsSet($_POST['text']))
                    {
                       
/*
                         * Compose the object with the details for the
                         * sentiment analysis API call.
                         *
                         */
                       
$document = new stdClass;
                       
$document->content = $_POST['text'];
                       
$document->language = 'en';
                       
$document->type = 'PLAIN_TEXT';
                       
$sentiment_analysis_request = new stdClass;
                       
$sentiment_analysis_request->document = $document;
                       
$sentiment_analysis_request->encodingType = 'UTF8';
   
                       
/*
                         * Send the sentiment analysis API call.
                         *
                         */
                       
$success = $client->CallAPI(
                           
'https://language.googleapis.com/v1/documents:analyzeSentiment',
                           
'POST', array(), array(
                               
'FailOnAccessError'=>true,
                               
'RequestContentType'=>'application/json',
                               
'RequestBody'=>json_encode($sentiment_analysis_request),
                            ),
$sentiment_analysis);
                    }
                }
            }
        }
       
$success = $client->Finalize($success);
    }
    if(
$client->exit)
        exit;
    if(
$success)
    {
       
/*
         * If all went well, display the page with the sentiment analysis
         * results and a form to let the user enter a new text message to
         * analyze.
         *
         */
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Google Natural Language Sentiment Analysis</title>
</head>
<body>
<h1>Google Natural Language Sentiment Analysis</h1>
<?php
       
if($client->debug)
        {
           
/*
             * Show the Google user account API call results in debug
             * mode.
             *
             */
           
echo '<h1>', HtmlSpecialChars($user->name),
               
', you have logged in successfully with Google!</h1>';
            echo
'<pre>', HtmlSpecialChars(print_r($user, 1)), '</pre>';
            echo
'<pre>Access token: ', HtmlSpecialChars($client->access_token), '</pre>';
        }

       
/*
         * If the user submitted the form to analyse the sentiments of a
         * text message, display the results.
         *
         */
       
if(IsSet($_POST['text']))
        {
               
$analyze_sentiment_score = function($score)
                {
                    if(
$score >= 0.8)
                        return
'Clearly Positive';
                    if(
$score > 0.1)
                        return
'Positive';
                    if(
$score <= -0.8)
                        return
'Clearly Negative';
                    if(
$score < -0.1)
                        return
'Negative';
                    if(
$score != 0)
                        return
'Neutral';
                    return
'Mixed';
                };
                if(
$client->debug)
                    echo
'<pre>', HtmlSpecialChars(print_r($sentiment_analysis, 1)), '</pre>';
                echo
'<h2>Results:</h2>',"\n";
               
$sentences = count($sentiment_analysis->sentences);
                echo
'<h3>Sentences: ', $sentences, '</h3>',"\n";
               
$score = $sentiment_analysis->documentSentiment->score;
                echo
'<p>Sentiment score: ', $score, ' ', $analyze_sentiment_score($score), '</p>',"\n";
                for(
$sentence = 0; $sentence < $sentences; ++$sentence)
                {
                    echo
'<h3>Sentence ', ($sentence + 1), ': ', HtmlSpecialChars($sentiment_analysis->sentences[$sentence]->text->content), '</h3>';
                   
$score = $sentiment_analysis->sentences[$sentence]->sentiment->score;
                    echo
'<p>Sentiment score: ', $score, ' ', $analyze_sentiment_score($score), '</p>',"\n";
                }
        }

       
/*
         * Show a form to let the user enter a text message to analyse the
         * user sentiments.
         *
         */
?>
<form method="POST">
<h2><?php echo HtmlSpecialChars($user->name); ?>, please enter a text to analyze:</h2>
<div>
    <textarea name="text" rows="6" cols="60"><?php
       
if(IsSet($_POST['text']))
        {
            echo
HtmlSpecialChars($_POST['text']);
        }
?>
</textarea>
</div>
<div>
    <input type="submit" value="Analyze">
</div>
</form>
</body>
</html>
<?php
   
}
    else
    {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>OAuth client error</title>
</head>
<body>
<h1>OAuth client error</h1>
<pre>Error: <?php echo HtmlSpecialChars($client->error); ?></pre>
</body>
</html>
<?php
   
}

?>