An elegant wrapper around Google Vision API

Overview

PHP Google Vision

STILL UNDER DEVELOPMENT - DO NOT USE IN PRODUCTION

Requires PHP 8.0+

For feedback, please contact me.

Latest Version on Packagist Tests GitHub Code Style Action Status Total Downloads

This package provides an elegant wrapper around Google Vision API and more.

It's an effort to make Google Vision API easy and fun to work with.

Contents

Installation

You may install the package via composer:

composer require ahmadmayahi/php-google-vision

Creating Google Service Account

First, you must create a Google service account and setup the configuration object.

Configuration

use AhmadMayahi\Vision\Config;

$config = (new Config())
    // optional
    ->setRequestTimeout(50)

    // optional: by default it uses the sys_get_temp_dir() function
    ->setTempDirPath('/path/to/temp')
    
    // Required: path to your google service account;
    ->setCredentialsPathname('path/to/google-service-account.json');

Original Responses

All the features come with getOriginalResponse() method which returns the original response that's generated by PHP Google Vision package.

You may get the original response for any feature as follows:

use AhmadMayahi\Vision\Vision;

$response = (new Vision($config))
    ->file('/path/to/input/file')
    ->faceDetection()
    ->getOriginalResponse();

Depending on the feature, the response type might vary, here is a list of all the response types:

Feature Response Type
faceDetection Google\Protobuf\Internal\RepeatedField contains Google\Cloud\Vision\V1\FaceAnnotation
imageTextDetection Google\Protobuf\Internal\RepeatedField
imagePropertiesDetection Google\Cloud\Vision\V1\ImageProperties
labelDetection Google\Protobuf\Internal\RepeatedField
landmarkDetection Google\Protobuf\Internal\RepeatedField
logoDetection Google\Protobuf\Internal\RepeatedField
objectLocalizer Google\Protobuf\Internal\RepeatedField
safeSearchDetection Google\Cloud\Vision\V1\SafeSearchAnnotation

The file() method accepts the following types:

  • Local file path: path/to/your/file.
  • Google Storage path: gs://path/to/file.
  • File resource, such as fopen().
  • SplFileInfo.
  • SplFileObject.

You may also use the static new method to instanciate the Vision object:

use AhmadMayahi\Vision\Vision;

$vision = Vision::new($config)
    ->file('/path/to/image.jpg')
    ->faceDetection()
    ->getOriginalResponse();

Integration with Laravel

Open up the AppServiceProvider and add the following lines:

use AhmadMayahi\Vision\Vision;
use AhmadMayahi\Vision\Config;

public function register()
{
    $this->app->singleton(Vision::class, function ($app) {
        $config = (new Config())
            ->setCredentialsPathname(config('vision.service_account_path'));
    
        return new Vision($config);
    });
}

Using Dependency Injection:

use AhmadMayahi\Vision\Vision;
use Illuminate\Http\Request;

class FaceDetectionController
{
    public function detect(Request $request, Vision $vision)
    {
        $vision = $vision
            ->file($request->face_file->path())
            ->faceDetection()
            ->detect();
            
        // ...
    }
}

You may also resolve the object using the app helper as follows:

use AhmadMayahi\Vision\Vision;

/** @var Vision $vision */
$vision = app(Vision::class);

$result = $vision
    ->file('path/to/file')
    ->faceDetection()
    ->detect();

// ...

Face Detection

Face Detection detects multiple faces within an image along with the associated key facial attributes such as emotional state or wearing headwear.

The detect method returns a Generator of AhmadMayahi\Vision\Data\FaceData:

use AhmadMayahi\Vision\Vision;

$faces = (new Vision($config))
    ->file('/path/to/image.jpg')
    ->faceDetection()
    ->detect();

echo count($faces). ' faces found';

foreach ($faces as $faceData) {
    // How angry the face is? 
    $faceData->getAnger();
    
    // Surprise reaction? 
    $faceData->getSurprise();
    
    // Is he/she happy?
    $faceData->getJoy();
    
    // Bounds
    $faceData->getBounds();
}

getAnger, getSurprise and getJoy return Likelihoods ratings which are expressed as 6 different values: UNKNOWN, VERY_UNLIKELY, UNLIKELY, POSSIBLE, LIKELY, or VERY_LIKELY. See Likelihood.

Draw box around faces

use AhmadMayahi\Vision\Vision;
use AhmadMayahi\Vision\Enums\ColorEnum;

$analyzer = (new Vision($config))
    ->file('/path/to/input/image.jpg')
    ->faceDetection()
    ->drawBoxAroundFaces(ColorEnum::MAGENTA)
    ->toJpeg('faces.jpg'); // Alternatively, you may use "toPng", "toGif", "toBmp".

All the drawing methods return an object of type AhmadMayahi\Vision\Utils\Image.

Larry Page and Sergey Brin Faces

This feature doesn't support Google Storage yet.

Image Text Detection

Get plain text

The getPlainText returns an object of type AhmadMayahi\Vision\Data\ImageTextData.

getText(); // Image text ">
use AhmadMayahi\Vision\Vision;

$response = (new Vision($config))
    ->file('/path/to/input/image.jpg')
    ->imageTextDetection()
    ->getPlainText();

$response->getLocale(); // locale, for example "en" for English
$response->getText();   // Image text

You may also get the plain text using __toString():

echo $response;

Get Document

The getDocument returns an object of type AhmadMayahi\Vision\Data\ImageTextData.

getText(); // Image text ">
use AhmadMayahi\Vision\Vision;

$response = (new Vision($config))
    ->file('/path/to/input/image.jpg')
    ->imageTextDetection()
    ->getDocument();
 
$response->getLocale(); // locale, for example "en" for English
$response->getText();   // Image text

The difference between getPlainText() and getDocuemnt() is that the first one only retrieves the plain text (no bullets, signs, etc...), whereas the latter one tries to retrieve the entire document (including bullets, symbols, etc...).

Image Properties Detection

The Image Properties feature detects general attributes of the image, such as dominant color.

The detect method returns a Generator of AhmadMayahi\Vision\Data\ImagePropertiesData:

use AhmadMayahi\Vision\Vision;

$properties = (new Vision($config))
    ->file('/path/to/input/image.jpg')
    ->imagePropertiesDetection()
    ->detect();

foreach ($properties as $item) {
    $item->getRed();

    $item->getBlue();

    $item->getGreen();

    $item->getPixelFraction();    
}

Landmark Detection

Landmark Detection detects popular natural and human-made structures within an image.

use AhmadMayahi\Vision\Vision;

$landmarks = (new Vision($config))
    ->file('/path/to/baghdad.jpg')
    ->landmarkDetection()
    ->detect();

foreach ($landmarks as $landmark) {
    $landmark->getName();
    
    // An array containing the detected locations in latitude/longitude format.
    $landmark->getLocations();
}

Safe Search Detection

SafeSearch Detection detects explicit content such as adult content or violent content within an image.

The detect method returns an object of type AhmadMayahi\Vision\Data\SafeSearchData:

use AhmadMayahi\Vision\Vision;

$result = (new Vision($config))
    ->file('/path/to/input/image.jpg')
    ->safeSearchDetection()
    ->detect();

$result->getAdult();

$result->getMedical();

$result->getViolence();

$result->getRacy();

$result->getSpoof();

Label Detection

Detect and extract information about entities in an image, across a broad group of categories.

The detect method returns an a Generator of labels:

use AhmadMayahi\Vision\Vision;

$labels = (new Vision($config))
    ->file('/path/to/input/image.jpg')
    ->labelDetection()
    ->detect();

Logo Detection

Detect and extract information about entities in an image, across a broad group of categories.

The detect method returns an Generator of logos:

use AhmadMayahi\Vision\Vision;

$labels = (new Vision($config))
    ->file('/path/to/input/image.jpg')
    ->logoDetection()
    ->detect();

Object Localizer

Object Localizer detects and extract multiple objects in an image with Object Localization.

Detect Objects

The detect method returns a Generator of AhmadMayahi\Vision\Data\LocalizedObjectData:

use AhmadMayahi\Vision\Vision;

$objects = (new Vision($config))
    ->file('/path/to/image.jpg')
    ->objectLocalizer()
    ->detect();

/** @var AhmadMayahi\Vision\Data\LocalizedObjectData $obj */
foreach ($objects as $obj) {
    $obj->getName();
    
    $obj->getLanguageCode();
    
    $obj->getMid();
    
    $obj->getNormalizedVertices();
    
    $obj->getScore();
}

Draw Box Around Objects

You may draw box around objects using the drawBoxAroundObjects method:

use AhmadMayahi\Vision\Vision;
use AhmadMayahi\Vision\Enums\ColorEnum;

$objects = (new Vision($config))
    ->file('/path/to/input/image.jpg')
    ->objectLocalizer()
    ->drawBoxAroundObjects(ColorEnum::GREEN)
    ->toJpeg('out.jpg');

Larry Page and Sergey Brin faces

The drawBoxAroundObjects() takes an optionalcallback as a second parameter:

use AhmadMayahi\Vision\Vision;
use AhmadMayahi\Vision\Enums\ColorEnum;
use AhmadMayahi\Vision\Support\Image;
use AhmadMayahi\Vision\Data\LocalizedObjectData;

$objects = (new Vision($config))
    ->file('/path/to/input/image.jpg')
    ->objectLocalizer()
    ->drawBoxAroundObjects(ColorEnum::GREEN, function(Image $outputImage, LocalizedObjectData $object) {
        // Get GD Image
        $outputImage->getImage();
        
        // Get object info
        $object->getName();
    });

This feature doesn't support Google Storage yet.

Draw Box Around Objects With Text

You may want to draw box around objects and include the object's text as well:

use AhmadMayahi\Vision\Vision;
use AhmadMayahi\Vision\Enums\ColorEnum;
use AhmadMayahi\Vision\Enums\FontEnum;
use AhmadMayahi\Vision\Support\Image;
use AhmadMayahi\Vision\Data\LocalizedObjectData;

$objects = (new Vision($config))
    ->file('/path/to/input/image.jpg')
    ->objectLocalizer()
    ->drawBoxAroundObjectsWithText(
        boxColor: ColorEnum::GREEN,
        textColor: ColorEnum::RED,
        fontSize: 15,
        font: FontEnum::OPEN_SANS_BOLD_ITALIC,
    )
    ->toJpeg('output.jpg');

Larry Page and Sergey Brin Objects

This feature doesn't support Google Storage yet.

Web Detection

Web Detection detects Web references to an image.

use AhmadMayahi\Vision\Vision;
use AhmadMayahi\Vision\Enums\ColorEnum;
use AhmadMayahi\Vision\Enums\FontEnum;
use AhmadMayahi\Vision\Support\Image;
use AhmadMayahi\Vision\Data\LocalizedObjectData;

$response = (new Vision($config))
    ->file('/path/to/input/image.jpg')
    ->webDetection()
    ->detect(); 

$response->getFullMatchingImages();

$response->getBestGuessLabels();

$response->getPagesWithMatchingImages();

$response->getPartialMatchingImages();

$response->getVisuallySimilarImages();

$response->getWebEntities();

The detect method returns either an object of tupe AhmadMayahi\Vision\Data\WebData or null value.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

You might also like...
Simple Curl based wrapper for Binance API for PHP scripts

Simple Curl based wrapper for Binance API for PHP scripts Feaures API support for SPOT data/trading FAPI/DAPI support for futures data/trading Curl-on

Twitch Helix API PHP Wrapper for Laravel
Twitch Helix API PHP Wrapper for Laravel

Laravel Twitch PHP Twitch Helix API Wrapper for Laravel 5+ ⚠️ Changes on May 01, 2020 Since May 01, 2020, Twitch requires all requests to contain a va

Super-simple, minimum abstraction MailChimp API v3 wrapper, in PHP

MailChimp API Super-simple, minimum abstraction MailChimp API v3 wrapper, in PHP. I hate complex wrappers. This lets you get from the MailChimp API do

Laravel 8.x package wrapper library for Metatrader 5 Web API

Laravel 8.x package wrapper library for Metatrader 5 Web API

An unofficial wrapper client for lknpd.nalog.ru API

Unofficial MoyNalog API client An unofficial wrapper client for lknpd.nalog.ru API Install Via Composer $ composer require shoman4eg/moy-nalog Usage S

A Gitlab API wrapper that helps to automate common actions on CI jobs

Gitlab CI client This is a Gitlab API wrapper that helps to automate common actions on CI jobs (eg: Open a merge request, Open or close an issue etc)

The Official Vultr API PHP Wrapper

WIP - This is not the final API Client. Unstable release use with caution. Vultr API PHP Client. Getting Started Must have a PSR7, PSR17, and PSR18 Co

A versatile PHP Library for Google PageSpeed Insights

PhpInsights An easy-to-use API Wrapper for Googles PageSpeed Insights. The JSON response is mapped to objects for an headache-free usage. Installation

A Laravel package to retrieve pageviews and other data from Google Analytics
A Laravel package to retrieve pageviews and other data from Google Analytics

Retrieve data from Google Analytics Using this package you can easily retrieve data from Google Analytics. Here are a few examples of the provided met

Releases(v1.0.0)
Owner
Ahmad Mayahi
Ahmad Mayahi
Google Drive Api Wrapper by PHP

GoogleDrive Api Wrapper usage at first you need to create oauth client on google cloud platform. so go to the your google console dashboard and create

Arash Abedi 2 Mar 24, 2022
Google Translator Api Wrapper For Php Developers.

Google Translator Api Wrapper For Php Developers.

Roldex Stark 2 Oct 12, 2022
NovaGram - An elegant, Object-Oriented, reliable PHP Telegram Bot Library

An elegant, Object-Oriented, reliable PHP Telegram Bot Library Full Documentation • Public support group Examples • Features • Installation ?

Gaetano 165 Jan 6, 2023
This package is a simple API laravel wrapper for Pokemontcg with a sleek Model design for API routes and authentication.

This package is a simple API laravel wrapper for Pokemontcg with a sleek Model design for API routes and authentication.

Daniel Henze 3 Aug 29, 2022
PHP package to manage google-api interactions

Google-api-client PHP package to manage google-api interactions Supports: Google Drive API Google Spreadsheet API Installation composer require obrio-

OBRIO 3 Apr 28, 2022
🌐 Free Google Translate API PHP Package. Translates totally free of charge.

Google Translate PHP Free Google Translate API PHP Package. Translates totally free of charge. Installation Basic Usage Advanced Usage Language Detect

Levan Velijanashvili 1.5k Dec 31, 2022
Google PHP API Client Services

Google PHP API Client Services

Google APIs 1.1k Dec 22, 2022
Simple Google Tts Api Class

Simple Google Tts Api Class

Ömer Faruk Demirel 2 Dec 2, 2022
Attempting to create an intelligent mock of the Google API PHP Client for unit and functional testing

google-api-php-client-mock A small scale intelligent mock of the Google API PHP Client for unit and functional testing. Overview This is intended to m

SIL International 0 Jan 4, 2022
A PHP wrapper for Spotify's Web API.

Spotify Web API PHP This is a PHP wrapper for Spotify's Web API. It includes the following: Helper methods for all API endpoints: Information about ar

Jonathan Wilsson 796 Jan 8, 2023