Skip to content

Commit

Permalink
Add functionality for specific API responses
Browse files Browse the repository at this point in the history
  • Loading branch information
bgalego authored and Carlos Abad committed Jan 4, 2018
1 parent 210bc0f commit 003e4d2
Show file tree
Hide file tree
Showing 12 changed files with 1,462 additions and 52 deletions.
85 changes: 60 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ You can load meaningcloud-php into your project by using Composer (https://getco
If you already have composer installed, you just need to run the following:

```
composer require meaningcloud/public/meaningcloud-php
composer require meaningcloud/meaningcloud-php
```

### Configuration
Expand All @@ -32,51 +32,86 @@ You can find all the technical documentation about the APIs in the API section o
And we are always available at support@meaningcloud.com


### Functionality

This SDK currently contains the following:

- **MCRequest**: to easily create a request to any of MeaningCloud's APIS.

- **MCResponse**: models a generic response from the MeaningCloud API.

- **MCTopicsResponse**: models a response from the Topic Extraction API, providing auxiliary functions to work with the response, extracting the different types of topics and some of the most used fields in them.

- **MCClassResponse**: models a response from the Text Classification API, providing auxiliary functions to work with the response and extract the different fields in each category.

- **MCSentimentResponse**: models a response from the Sentiment Analysis API, providing auxiliary functions to work with the response and extract the sentiment detected at different levels and for different elements.


### Usage

This is an example on how to use this client (also included in the _bin_ folder):
This is an example on how to use this client (also included in the _bin_ folder). This code makes to requests, once to the Language Identification API and another one to the Topic Extraction API using the language detected in the first request. The results of both requests are printed in the standard output:

```php

require_once(__DIR__.'/../vendor/autoload.php');

use MeaningCloud\MCRequest;
use MeaningCloud\MCResponse;

$server = 'https://api.meaningcloud.com/';
$license_key = '<< your license key >>'; // your license key (https://www.meaningcloud.com/developer/account/subscription)

try {
// We are going to make a request to the Topics Extraction API
$mc = new MCRequest($server.'topics-2.0', $license_key);


// We add the required parameters of the API we are using
$mc->addParam('lang', 'en'); //languages -> English
$mc->addParam('tt', 'e'); //topic type -> entities
$text = 'London is a very nice city but I also love Madrid.';

try {
// We are going to make a request to the Language Identification API
$mc = new MCRequest($server.'lang-2.0', $license_key);

//We set the content we want to analyze
$mc->setContentTxt('London is a very nice city but I also love Madrid.');
//$mc->setContentUrl('https://en.wikipedia.org/wiki/Star_Trek');//if we want to analyze an URL
$response = $mc->sendRequest();

//We set the content we want to analyze
$mc->setContentTxt($text);
//$mc->setContentUrl('https://en.wikipedia.org/wiki/Star_Trek'); //if we want to analyze an URL
$response = new MCResponse($mc->sendRequest());

// if there are no errors in the request, we print the output
// if there are no errors in the request, we will use the language detected to make a request to Sentiment and Topics
if($response->isSuccessful()) {
echo "\nThe request finished successfully!\n";
echo "\nThe request to 'Language Identification' finished successfully!\n";

$results = $response->getResults();
if(isset($results['entity_list'])) {
echo "Entities detected (".sizeof($results['entity_list'])."):\n";
foreach ($results['entity_list'] as $entity) {
echo "\t".$entity['form'].' --> '.(isset($entity['sementity']['type']) ? $entity['sementity']['type'] : 'Unknown')."\n";
if(isset($results['language_list']) && !empty($results['language_list'])) {
$language = $results['language_list'][0]['language'];
echo "\tLanguage detected: ".$results['language_list'][0]['name'].' ('.$language.")\n";

// We are going to make a request to the Topics Extraction API
$mc_topics = new MCRequest($server.'topics-2.0', $license_key);
// We set the content we want to analyze
$mc_topics->setContentTxt($text);

// We add the required parameters of the API we are using
$response = $mc_topics->sendTopicsRequest($language, 'e'); //languages -> English, topic type -> entities

// if there are no errors in the request, we print the output
if($response->isSuccessful()) {
echo "\nThe request to 'Topics Extraction' finished successfully!\n";

$entities = $response->getEntities();
if(!empty($entities)) {
echo "\tEntities detected (".sizeof($entities)."):\n";
foreach ($entities as $entity) {
echo "\t\t".$response->getTopicForm($entity).' --> '.$response->getTypeLastNode($response->getOntoType($entity))."\n";
}
}
} else {
echo "\nOh no! There was the following error: ".$response->getStatusMsg()."\n";
}
}
} else {
echo "\nOh no! There was the following error: ".$response->getStatusMsg()."\n";
if(is_null($response->getResponse()))
echo "\nOh no! The request sent did not return a Json\n";
else
echo "\nOh no! There was the following error: ".$response->getStatusMsg()."\n";
}
}catch (Exception $e) {
} catch (Exception $e) {
echo "\nEXCEPTION: ".$e->getMessage().' ('.$e->getFile().':'.$e->getLine().')'."\n\n";
}
?>

```
```
55 changes: 39 additions & 16 deletions bin/MCClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,38 +7,61 @@
require_once(__DIR__.'/../vendor/autoload.php');

use MeaningCloud\MCRequest;
use MeaningCloud\MCResponse;

$server = 'https://api.meaningcloud.com/';
$license_key = '<< your license key >>'; // your license key (https://www.meaningcloud.com/developer/account/subscription)

try {
// We are going to make a request to the Topics Extraction API
$mc = new MCRequest($server.'topics-2.0', $license_key);
$text = 'London is a very nice city but I also love Madrid.';

// We add the required parameters of the API we are using
$mc->addParam('lang', 'en'); //languages -> English
$mc->addParam('tt', 'e'); //topic type -> entities
try {
// We are going to make a request to the Language Identification API
$mc = new MCRequest($server.'lang-2.0', $license_key);

//We set the content we want to analyze
$mc->setContentTxt('London is a very nice city but I also love Madrid.');
$mc->setContentTxt($text);
//$mc->setContentUrl('https://en.wikipedia.org/wiki/Star_Trek'); //if we want to analyze an URL
$response = $mc->sendRequest();
$response = new MCResponse($mc->sendRequest());

// if there are no errors in the request, we print the output
// if there are no errors in the request, we will use the language detected to make a request to Sentiment and Topics
if($response->isSuccessful()) {
echo "\nThe request finished successfully!\n";
echo "\nThe request to 'Language Identification' finished successfully!\n";

$results = $response->getResults();
if(isset($results['entity_list'])) {
echo "Entities detected (".sizeof($results['entity_list'])."):\n";
foreach ($results['entity_list'] as $entity) {
echo "\t".$entity['form'].' --> '.(isset($entity['sementity']['type']) ? $entity['sementity']['type'] : 'Unknown')."\n";
if(isset($results['language_list']) && !empty($results['language_list'])) {
$language = $results['language_list'][0]['language'];
echo "\tLanguage detected: ".$results['language_list'][0]['name'].' ('.$language.")\n";

// We are going to make a request to the Topics Extraction API
$mc_topics = new MCRequest($server.'topics-2.0', $license_key);
// We set the content we want to analyze
$mc_topics->setContentTxt($text);

// We add the required parameters of the API we are using
$response = $mc_topics->sendTopicsRequest($language, 'e'); //language detected, topic type -> entities

// if there are no errors in the request, we print the output
if($response->isSuccessful()) {
echo "\nThe request to 'Topics Extraction' finished successfully!\n";

$entities = $response->getEntities();
if(!empty($entities)) {
echo "\tEntities detected (".sizeof($entities)."):\n";
foreach ($entities as $entity) {
echo "\t\t".$response->getTopicForm($entity).' --> '.$response->getTypeLastNode($response->getOntoType($entity))."\n";
}
}
} else {
echo "\nOh no! There was the following error: ".$response->getStatusMsg()."\n";
}
}
} else {
echo "\nOh no! There was the following error: ".$response->getStatusMsg()."\n";
if(is_null($response->getResponse()))
echo "\nOh no! The request sent did not return a Json\n";
else
echo "\nOh no! There was the following error: ".$response->getStatusMsg()."\n";
}
} catch (Exception $e) {
echo "\nEXCEPTION: ".$e->getMessage().' ('.$e->getFile().':'.$e->getLine().')'."\n\n";
}
?>
?>
72 changes: 72 additions & 0 deletions src/MCClassResponse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php
/**
* Created by MeaningCloud Support Team.
* Date: 02/01/18
*/

namespace MeaningCloud;


class MCClassResponse extends MCResponse {



/**
* MCClassResponse constructor
* @param string $response string returned by the request
* @throws \Exception if the parameters passed are incorrect
*/
public function __construct($response) {
if(empty($response))
throw new \Exception("The request sent did not return a response");
parent::__construct($response);
}


/**
* @return array with the categories detected
*/
public function getCategories() {
return (isset($this->response['category_list']) ? $this->response['category_list'] : []);
}


/*** Generic auxiliary functions ****/

/**
* @param array $category
* @return string
*/
public function getCategoryCode($category) {
return (isset($category['code']) ? $category['code'] : '');
}


/**
* @param array $category
* @return string
*/
public function getCategoryLabel($category) {
return (isset($category['label']) ? $category['label'] : '');
}


/**
* @param array $category
* @return string
*/
public function getCategoryAbsRelevance($category) {
return (isset($category['abs_relevance']) ? $category['abs_relevance'] : '');
}


/**
* @param array $category
* @return string
*/
public function getCategoryRelevance($category) {
return (isset($category['relevance']) ? $category['relevance'] : '');
}

}

62 changes: 59 additions & 3 deletions src/MCRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function addParam($paramName, $paramValue) {
private function setContent($type, $value) {
if(in_array($type, [self::CONTENT_TYPE_TXT, self::CONTENT_TYPE_URL, self::CONTENT_TYPE_FILE])) {
if($type == self::CONTENT_TYPE_FILE)
$this->addParam('doc', curl_file_create(realpath($value),'txt/plain'));
$this->addParam('doc', curl_file_create(realpath($value)));
else
$this->addParam($type, $value);
}
Expand Down Expand Up @@ -93,13 +93,69 @@ public function setContentFile($file) {
}


/**
* Sends request to the Topic Extraction API
*
* @param string $lang language of the text
* @param string $topicType type of topics to extract
* @param array $otherParams other parameters to send
* @param array $extraHeaders
* @return MCTopicsResponse
*/
public function sendTopicsRequest($lang, $topicType, $otherParams = array(), $extraHeaders = array()) {
$this->addParam('lang', $lang);
$this->addParam('tt', $topicType);
array_walk($otherParams, [$this,'addParam']);

$response = $this->sendRequest($extraHeaders);
return new MCTopicsResponse($response);
}


/**
* Sends request to the Text Classification API
*
* @param string $model classification model to use
* @param array $otherParams
* @param array $extraHeaders
* @return MCClassResponse
*/
public function sendClassRequest($model, $otherParams = array(), $extraHeaders = array()) {
$this->addParam('model', $model);
array_walk($otherParams, [$this, 'addParam']);

$response = $this->sendRequest($extraHeaders);
return new MCClassResponse($response);
}


/**
* Sends request to the Topic Extraction API
*
* @param string $lang language of the text
* @param string $model sentiment model to use
* @param array $otherParams other parameters to send
* @param array $extraHeaders
* @return MCSentimentResponse
*/
public function sendSentimentRequest($lang, $model, $otherParams = array(), $extraHeaders = array()) {
$this->addParam('lang', $lang);
$this->addParam('model', $model);
array_walk($otherParams, [$this, 'addParam']);

$response = $this->sendRequest($extraHeaders);
return new MCSentimentResponse($response);
}



/**
* Sends a request to the URL specified and returns a response only if the HTTP code returned is OK
*
* @param array $extraHeaders allows to configure additional headers in the request
* @return MCResponse object set to NULL if there is an error
*/
public function sendRequest($extraHeaders=array()) {
public function sendRequest($extraHeaders = array()) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->url);
curl_setopt($curl, CURLOPT_HEADER, 1);
Expand All @@ -119,7 +175,7 @@ public function sendRequest($extraHeaders=array()) {
$result = curl_exec($curl);
$info = curl_getinfo($curl);
curl_close($curl);
$response = new MCResponse(substr($result, $info['header_size']));
$response = substr($result, $info['header_size']);
return $response;
} // sendRequest

Expand Down
15 changes: 13 additions & 2 deletions src/MCResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@

class MCResponse {

/** @var string */
private $response; //associative array with the response
/** @var array */
protected $response; //associative array with the response

/** @var string */
protected $strResponse; //string response

/**
* MCResponse constructor
Expand All @@ -20,6 +22,7 @@ class MCResponse {
public function __construct($response) {
if(empty($response))
throw new \Exception("The request sent did not return a response");
$this->strResponse = $response;
$this->response = json_decode($response, true);
}

Expand Down Expand Up @@ -101,5 +104,13 @@ public function getResults() {
public function getResponse() {
return $this->response;
}

/**
* Returns the response from de API as a string
* @return string
*/
public function getStrResponse() {
return $this->strResponse;
}
}
?>
Loading

0 comments on commit 003e4d2

Please sign in to comment.