Skip to content

Instantly share code, notes, and snippets.

@sohelrana820
Created December 27, 2020 21:01
Show Gist options
  • Save sohelrana820/c4374b612985c6cf0054a164f8265935 to your computer and use it in GitHub Desktop.
Save sohelrana820/c4374b612985c6cf0054a164f8265935 to your computer and use it in GitHub Desktop.
Using Google Visio API
<?php
namespace app\Components;
use Vision\Annotation\SafeSearchAnnotation;
use Vision\Request\Image\Base64Image;
use Vision\Vision;
/**
* This is a wrapper class for image processing through google vision api.
*
* Class GoogleVisionApi
* @package app\Components
*/
class GoogleVisionApi
{
/**
* @var \Vision\Vision|null
*/
private $visionApiClient = null;
/**
* @var null | SafeSearchAnnotation;
*/
private $analysisReport = null;
/**
* GoogleVisionApi constructor.
*/
public function __construct()
{
;
try {
$this->visionApiClient = new Vision(
getenv('GOOGLE_API_KEY'),
[
new \Vision\Feature(\Vision\Feature::SAFE_SEARCH_DETECTION, 100),
]
);
} catch (\Exception $exception) {
\Yii::$app->logger->log->error('Failed to analysis image form google vision api', ['message' => $exception->getMessage()]);
};
}
/**
* Analysis image form google vision API.
*
* @param $imagePath
* @return $this
*/
public function analysisImage($imagePath)
{
$imagePath = base64_encode(file_get_contents($imagePath));
$response = $this->visionApiClient->request(new Base64Image($imagePath));
$this->analysisReport = $response->getSafeSearchAnnotation();
return $this;
}
/**
* Analysis google vision api response and checking given image is safe to use or not.
*
* @return bool
*/
public function isSafe()
{
if ($this->analysisReport->getAdult() == 'POSSIBLE' ||
$this->analysisReport->getMedical() == 'POSSIBLE' ||
$this->analysisReport->getAdult() == 'POSSIBLE' ||
$this->analysisReport->getRacy() == 'POSSIBLE' ||
$this->analysisReport->getSpoof() == 'POSSIBLE') {
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment