Skip to content

Instantly share code, notes, and snippets.

@nexxai
Last active April 29, 2024 19:01
Show Gist options
  • Select an option

  • Save nexxai/a6c98860c943fbbcf3341674e672a68b to your computer and use it in GitHub Desktop.

Select an option

Save nexxai/a6c98860c943fbbcf3341674e672a68b to your computer and use it in GitHub Desktop.
A PHP class that will allow you to determine how many people are in a photo and if the photo contains inappropriate content, using AWS Rekognition
<?php
namespace App\Rekognition;
use Aws\Rekognition\RekognitionClient;
use Aws\Result;
class Client
{
public RekognitionClient $client;
public function __construct(string $region = 'us-east-1')
{
$this->client = new RekognitionClient([
'region' => $region,
'credentials' => [
'key' => config('services.ses.key'),
'secret' => config('services.ses.secret'),
],
]);
}
public function handle(string $bucket, string $photoPath)
{
$image = ['Image' => ['S3Object' => ['Bucket' => $bucket, 'Name' => $photoPath]]];
if ($this->hasInappropriateContent($image)) {
dump('Inappropriate content detected in photo');
}
if (! $this->hasExactlyOnePerson($image)) {
dump('Multiple or no people detected in photo');
}
dump('photo accepted');
}
/**
* $allowedLabels should be an array of Rekognition Moderation Labels
* that are permitted, and should not be flagged.
*
* Full list of labels can be found in the table at
* https://docs.aws.amazon.com/rekognition/latest/dg/moderation.html
*
* Example: ['Drugs & Tobacco', 'Alcohol']
*/
public function hasInappropriateContent(array $image, array $allowedLabels = []): bool
{
$image['MinConfidence'] = 50;
$labels = $this->client->detectModerationLabels($image);
$moderationLabels = $labels['ModerationLabels'];
if (! empty($allowedLabels)) {
foreach ($moderationLabels as $label) {
if (in_array($label['Name'], $allowedLabels)) {
$moderationLabels = $this->unchain($moderationLabels, $label['Name']);
}
}
}
return ! empty($moderationLabels);
}
public function unchain(array $labels, string $parentName): array
{
foreach ($labels as $index => $label) {
if ($label['ParentName'] === $parentName) {
$labels = $this->unchain($labels, $label['Name']);
}
unset($labels[$index]);
}
return $labels;
}
public function hasNoPeople(Result $result): bool
{
foreach ($result['Labels'] as $label) {
if ($label['Name'] === 'Person') {
return count($label['Instances']) === 0;
}
}
return true;
}
public function hasMultiplePeople(Result $result): bool
{
foreach ($result['Labels'] as $label) {
if ($label['Name'] === 'Person') {
return count($label['Instances']) > 1;
}
}
return false;
}
private function hasExactlyOnePerson(array $image): bool
{
$image['MinConfidence'] = 90;
$labels = $this->client->detectLabels($image);
if ($this->hasMultiplePeople($labels) || $this->hasNoPeople($labels)) {
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment