|
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
|
|
|
$apiKey, |
|
|
|
|
|
|
21
|
|
|
$projectId, |
|
22
|
|
|
$serviceAccountFile, |
|
23
|
|
|
EntityManagerInterface $entityManager |
|
24
|
|
|
) |
|
25
|
|
|
{ |
|
26
|
|
|
//dd(file_get_contents($serviceAccountFile)); |
|
27
|
|
|
$this->client = new ImageAnnotatorClient([ |
|
28
|
|
|
'projectId' => $projectId, |
|
29
|
|
|
'credentials' => $serviceAccountFile |
|
30
|
|
|
]); |
|
31
|
|
|
$this->entityManager = $entityManager; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function tagImage(Image $image, bool $overwriteExisting = false): bool |
|
35
|
|
|
{ |
|
36
|
|
|
if ($overwriteExisting === false && $image->getAutoTagsCount() > 0) { |
|
37
|
|
|
return false; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
$feature = new Feature(); |
|
41
|
|
|
$feature->setType(Type::LABEL_DETECTION); |
|
42
|
|
|
$feature->setMaxResults(15); |
|
43
|
|
|
$result = $this->client->annotateImage( |
|
44
|
|
|
$image->getMediumImageUri(), |
|
45
|
|
|
[$feature] |
|
46
|
|
|
); |
|
47
|
|
|
|
|
48
|
|
|
$tags = []; |
|
49
|
|
|
foreach ($result->getLabelAnnotations() as $annotation) { |
|
50
|
|
|
$tags[] = $annotation->getDescription(); |
|
51
|
|
|
} |
|
52
|
|
|
$image->setAutoTags($tags); |
|
53
|
|
|
$this->entityManager->persist($image); |
|
54
|
|
|
$this->entityManager->flush(); // Calling the API's a lot more overhead; we might as well flush on every image. |
|
55
|
|
|
return true; |
|
56
|
|
|
} |
|
57
|
|
|
} |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.