Completed
Pull Request — master (#51)
by Matt
05:11
created

GoogleImageTaggingService::getImageToSend()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
namespace App\Service;
4
5
use App\Entity\Image;
6
use Doctrine\ORM\EntityManagerInterface;
7
use Google\Cloud\Vision\V1\Feature;
8
use Google\Cloud\Vision\V1\Feature\Type;
9
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
10
11
class GoogleImageTaggingService implements ImageTaggingServiceInterface
12
{
13
    /** @var EntityManagerInterface */
14
    private $entityManager;
15
16
    /** @var ImageAnnotatorClient */
17
    private $client;
18
19
    public function __construct(
20
        string $projectId,
21
        string $serviceAccountFile,
22
        EntityManagerInterface $entityManager
23
    )
24
    {
25
        //dd(file_get_contents($serviceAccountFile));
26
        $this->client = new ImageAnnotatorClient([
27
            'projectId' => $projectId,
28
            'credentials' => $serviceAccountFile
29
        ]);
30
        $this->entityManager = $entityManager;
31
    }
32
33
    public function tagImage(Image $image, bool $overwriteExisting = false): bool
34
    {
35
        if ($overwriteExisting === false && $image->getAutoTagsCount() > 0) {
36
            return false;
37
        }
38
39
        $feature = new Feature();
40
        $feature->setType(Type::LABEL_DETECTION);
41
        $feature->setMaxResults(15);
42
        $result = $this->client->annotateImage(
43
            $this->getImageToSend($image),
44
            [$feature]
45
        );
46
47
        $tags = [];
48
        foreach ($result->getLabelAnnotations() as $annotation) {
49
            $tags[] = $annotation->getDescription();
50
        }
51
        $image->setAutoTags($tags);
52
        $this->entityManager->persist($image);
53
        $this->entityManager->flush(); // Calling the API's a lot more overhead; we might as well flush on every image.
54
        return true;
55
    }
56
57
    /**
58
     *
59
     * Can be overridden, e.g. our dev service overrides this to provide
60
     * the actual image data through readfile as the dev service's URLs
61
     * aren't public.
62
     *
63
     * @return mixed|string
64
     */
65
    protected function getImageToSend(Image $image)
66
    {
67
        // We just send back a reasonable-resolution public URL
68
        return $image->getMediumImageUri();
69
    }
70
}