CropHints::getOriginalResponse()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AhmadMayahi\Vision\Detectors;
6
7
use AhmadMayahi\Vision\Contracts\Detectable;
8
use AhmadMayahi\Vision\Contracts\File;
9
use AhmadMayahi\Vision\Data\CropHints as CropHintsData;
10
use AhmadMayahi\Vision\Data\Vertex as VertexData;
11
use AhmadMayahi\Vision\Detectors\CropHints\Crop;
12
use AhmadMayahi\Vision\Detectors\CropHints\DrawBoxAroundHints;
13
use AhmadMayahi\Vision\Enums\Color;
14
use AhmadMayahi\Vision\Support\AbstractDetector;
15
use AhmadMayahi\Vision\Support\Image;
16
use AhmadMayahi\Vision\Traits\Arrayable;
17
use AhmadMayahi\Vision\Traits\Jsonable;
18
use Generator;
19
use Google\Cloud\Vision\V1\CropHintsAnnotation;
20
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
21
use Google\Cloud\Vision\V1\Vertex;
22
23
class CropHints extends AbstractDetector implements Detectable
24
{
25
    use Arrayable;
26
    use Jsonable;
27
28
    public function __construct(protected ImageAnnotatorClient $imageAnnotatorClient, protected File $file, protected Image $image)
29
    {
30
    }
31
32
    public function getOriginalResponse(): ?CropHintsAnnotation
33
    {
34
        return $this
35
            ->imageAnnotatorClient
36
            ->cropHintsDetection($this->file->toVisionFile())
37
            ->getCropHintsAnnotation();
38
    }
39
40
    public function detect(): ?Generator
41
    {
42
        $cropHints = $this->getOriginalResponse()->getCropHints();
43
44
        if (0 === $cropHints->count()) {
45
            return null;
46
        }
47
48
        /** @var \Google\Cloud\Vision\V1\CropHint $item */
49
        foreach ($cropHints as $item) {
50
            $bounds = array_map(function (Vertex $vertex) {
51
                return new VertexData($vertex->getX(), $vertex->getY());
52
            }, iterator_to_array($item->getBoundingPoly()->getVertices()));
53
54
            yield new CropHintsData(
55
                bounds: $bounds,
56
                confidence: $item->getConfidence(),
57
                importanceFraction: $item->getImportanceFraction(),
58
            );
59
        }
60
    }
61
62
    public function drawBoxAroundHints(int $borderColor = Color::GREEN): Image
63
    {
64
        return (new DrawBoxAroundHints(
65
            cropHints:  $this,
66
            image: $this->image,
67
            borderColor: $borderColor
68
        ))->draw();
69
    }
70
71
    public function crop(): Image
72
    {
73
        return (new Crop($this, $this->image))->crop();
74
    }
75
}
76