Passed
Push — master ( 198526...2cbb41 )
by Chris
13:39
created

Rekognition::detectFaces()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 2
b 0
f 0
nc 3
nop 2
dl 0
loc 19
rs 10
1
<?php
2
3
namespace Meema\MediaRecognition\Recognizers;
4
5
use Aws\Rekognition\RekognitionClient;
6
use Exception;
7
use Illuminate\Support\Facades\Storage;
8
use Illuminate\Support\Str;
9
use Meema\MediaRecognition\Contracts\MediaRecognition as MediaRecognitionInterface;
10
use Meema\MediaRecognition\Events\FacialAnalysisCompleted;
11
use Meema\MediaRecognition\Facades\Recognize;
12
use Meema\MediaRecognition\Models\MediaRecognition;
13
use Meema\MediaRecognition\Traits\CanRecognizeImages;
14
use Meema\MediaRecognition\Traits\CanRecognizeVideos;
15
use Meema\MediaRecognition\Traits\InteractsWithStorage;
16
17
class Rekognition implements MediaRecognitionInterface
18
{
19
    use InteractsWithStorage, CanRecognizeImages, CanRecognizeVideos;
20
21
    /**
22
     * Client instance of MediaRecognition.
23
     *
24
     * @var \Aws\Rekognition\RekognitionClient
25
     */
26
    protected RekognitionClient $client;
27
28
    /**
29
     * The settings provided to the Rekognition job.
30
     *
31
     * @var array
32
     */
33
    protected array $settings;
34
35
    /**
36
     * The relating media model's id.
37
     *
38
     * @var int|null
39
     */
40
    protected ?int $mediaId = null;
41
42
    /**
43
     * Construct converter.
44
     *
45
     * @param \Aws\Rekognition\RekognitionClient $client
46
     * @throws \Exception
47
     */
48
    public function __construct(RekognitionClient $client)
49
    {
50
        $this->client = $client;
51
    }
52
53
    /**
54
     * Get the MediaRecognition Client.
55
     *
56
     * @return \Aws\Rekognition\RekognitionClient
57
     */
58
    public function getClient(): RekognitionClient
59
    {
60
        return $this->client;
61
    }
62
63
    /**
64
     * Detects labels/objects in an image.
65
     *
66
     * @param int|null $mediaId
67
     * @param int|null $minConfidence
68
     * @param int|null $maxLabels
69
     * @return \Aws\Result
70
     * @throws \Exception
71
     */
72
    public function detectLabels($mediaId = null, $minConfidence = null, $maxLabels = null)
73
    {
74
        $this->ensureMimeTypeIsSet();
75
76
        if (Str::contains($this->mimeType, 'image')) {
77
            $result = $this->detectImageLabels($mediaId, $minConfidence, $maxLabels);
0 ignored issues
show
Bug introduced by
It seems like $maxLabels can also be of type integer; however, parameter $maxLabels of Meema\MediaRecognition\R...on::detectImageLabels() does only seem to accept null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

77
            $result = $this->detectImageLabels($mediaId, $minConfidence, /** @scrutinizer ignore-type */ $maxLabels);
Loading history...
Bug introduced by
It seems like $minConfidence can also be of type integer; however, parameter $minConfidence of Meema\MediaRecognition\R...on::detectImageLabels() does only seem to accept null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

77
            $result = $this->detectImageLabels($mediaId, /** @scrutinizer ignore-type */ $minConfidence, $maxLabels);
Loading history...
78
79
            // we need to manually fire the event for image analyses because unlike the video analysis,
80
            // AWS is not sending a webhook upon completion of the image analysis
81
            event(new FacialAnalysisCompleted($result));
82
83
            return $result;
84
        }
85
86
        if (Str::contains($this->mimeType, 'video')) {
87
            return $this->detectVideoLabels($mediaId, $minConfidence, $maxLabels);
88
        }
89
90
        throw new \Exception('$mimeType does neither indicate being a video nor an image');
91
    }
92
93
    /**
94
     * Detects faces in an image & analyzes them.
95
     *
96
     * @param int|null $mediaId
97
     * @param array $attributes
98
     * @return \Aws\Result
99
     * @throws \Exception
100
     */
101
    public function detectFaces($mediaId = null, $attributes = ['DEFAULT'])
102
    {
103
        $this->ensureMimeTypeIsSet();
104
105
        if (Str::contains($this->mimeType, 'image')) {
106
            $result = $this->detectImageFaces($mediaId, $attributes);
107
108
            // we need to manually fire the event for image analyses because unlike the video analysis,
109
            // AWS is not sending a webhook upon completion of the image analysis
110
            event(new FacialAnalysisCompleted($result));
111
112
            return $result;
113
        }
114
115
        if (Str::contains($this->mimeType, 'video')) {
116
            return $this->detectVideoFaces($mediaId, $attributes);
117
        }
118
119
        throw new \Exception('$mimeType does neither indicate being a video nor an image');
120
    }
121
122
    /**
123
     * Detects moderation labels in an image.
124
     * This can be useful for children-friendly images or NSFW images.
125
     *
126
     * @param int|null $mediaId
127
     * @param int|null $minConfidence
128
     * @return \Aws\Result
129
     * @throws \Exception
130
     */
131
    public function detectModeration($mediaId = null, $minConfidence = null)
132
    {
133
        $this->setImageSettings();
134
135
        $this->settings['MinConfidence'] = $minConfidence ?? config('media-recognition.min_confidence');
136
137
        $results = $this->client->detectModerationLabels($this->settings);
138
139
        $this->updateOrCreate('moderation', $mediaId, $results);
140
141
        return $results;
142
    }
143
144
    /**
145
     * Detects text in an image (OCR).
146
     *
147
     * @param int|null $mediaId
148
     * @return \Aws\Result
149
     * @throws \Exception
150
     */
151
    public function detectText($mediaId = null)
152
    {
153
        $this->setImageSettings();
154
155
        $results = $this->client->detectText($this->settings);
156
157
        $this->updateOrCreate('ocr', $mediaId, $results);
158
159
        return $results;
160
    }
161
162
    /**
163
     * @param $type
164
     * @param $mediaId
165
     * @param $results
166
     * @return mixed
167
     * @throws \Exception
168
     */
169
    protected function updateOrCreate($type, $mediaId, $results)
170
    {
171
        if (! config('media-recognition.track_media_recognitions')) {
172
            return $results;
173
        }
174
175
        if (is_null($mediaId)) {
176
            throw new Exception('Please make sure to set a $mediaId.');
177
        }
178
179
        MediaRecognition::updateOrCreate([
180
            'model_id' => $mediaId,
181
            'model_type' => config('media-converter.media_model'),
182
        ], [$type => $results->toArray()]);
183
184
        return $results;
185
    }
186
187
    /**
188
     * @param string $jobId
189
     * @param string $type
190
     * @return void
191
     * @throws \Exception
192
     */
193
    protected function updateJobId(string $jobId, string $type)
194
    {
195
        if (! config('media-recognition.track_media_recognitions')) {
196
            return;
197
        }
198
199
        if (is_null($this->mediaId)) {
200
            throw new Exception('Please make sure to set a $mediaId.');
201
        }
202
203
        MediaRecognition::updateOrCreate([
204
            'model_id' => $this->mediaId,
205
            'model_type' => config('media-converter.media_model'),
206
        ], [$type.'_job_id' => $jobId]);
207
    }
208
209
    /**
210
     * @param array $results
211
     * @param string $type
212
     * @param int $mediaId
213
     * @return void
214
     */
215
    protected function updateVideoResults(array $results, string $type, int $mediaId)
216
    {
217
        if (! config('media-recognition.track_media_recognitions')) {
218
            return;
219
        }
220
221
        $mediaRecognition = MediaRecognition::where('model_id', $mediaId)->firstOrFail();
222
        $mediaRecognition->$type = $results;
223
        $mediaRecognition->save();
224
    }
225
226
    protected function ensureMimeTypeIsSet()
227
    {
228
        if (is_null($this->mimeType)) {
229
            $this->mimeType = Storage::disk(config('media-recognition.disk'))->mimeType($this->path);
0 ignored issues
show
Documentation Bug introduced by
It seems like Illuminate\Support\Facad...->mimeType($this->path) can also be of type false. However, the property $mimeType is declared as type null|string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
Bug Best Practice introduced by
The property path does not exist on Meema\MediaRecognition\Recognizers\Rekognition. Did you maybe forget to declare it?
Loading history...
230
        }
231
    }
232
}
233