|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace AhmadMayahi\Vision\Detectors; |
|
6
|
|
|
|
|
7
|
|
|
use AhmadMayahi\Vision\Data\ImageText as ImageTextData; |
|
8
|
|
|
use AhmadMayahi\Vision\Support\AbstractDetector; |
|
9
|
|
|
use Google\Cloud\Vision\V1\EntityAnnotation; |
|
10
|
|
|
use Google\Protobuf\Internal\RepeatedField; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Detect text in images |
|
14
|
|
|
* |
|
15
|
|
|
* @see https://cloud.google.com/vision/docs/ocr |
|
16
|
|
|
*/ |
|
17
|
|
|
class ImageText extends AbstractDetector |
|
18
|
|
|
{ |
|
19
|
|
|
public function getOriginalResponse(): ?RepeatedField |
|
20
|
|
|
{ |
|
21
|
|
|
return $this->getDocumentTextAnnotations(); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
public function plain(): ?ImageTextData |
|
25
|
|
|
{ |
|
26
|
|
|
$detection = $this |
|
27
|
|
|
->imageAnnotatorClient |
|
28
|
|
|
->textDetection($this->file->toVisionFile()); |
|
29
|
|
|
|
|
30
|
|
|
$annotations = $detection->getTextAnnotations(); |
|
31
|
|
|
|
|
32
|
|
|
if (! $annotations->count()) { |
|
33
|
|
|
return null; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** @var EntityAnnotation $text */ |
|
37
|
|
|
$text = $annotations->offsetGet(0); |
|
38
|
|
|
|
|
39
|
|
|
return new ImageTextData( |
|
40
|
|
|
locale: $text->getLocale(), |
|
41
|
|
|
text: $text->getDescription(), |
|
42
|
|
|
); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function document(): ImageTextData |
|
46
|
|
|
{ |
|
47
|
|
|
$text = $this->getDocumentTextAnnotations()->offsetGet(0); |
|
48
|
|
|
|
|
49
|
|
|
return new ImageTextData( |
|
50
|
|
|
locale: $text->getLocale(), |
|
51
|
|
|
text: $text->getDescription(), |
|
52
|
|
|
); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
private function getDocumentTextAnnotations(): RepeatedField |
|
56
|
|
|
{ |
|
57
|
|
|
return $this |
|
58
|
|
|
->imageAnnotatorClient |
|
59
|
|
|
->documentTextDetection($this->file->toVisionFile()) |
|
60
|
|
|
->getTextAnnotations(); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
public function __toString(): string |
|
64
|
|
|
{ |
|
65
|
|
|
return $this->plain()?->text ?? ''; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|