Using Google Visio API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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