in functions/imagemagick/index.php [28:71]
function blurOffensiveImages(CloudEvent $cloudevent): void
{
$log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
$storage = new StorageClient();
$data = $cloudevent->getData();
$file = $storage->bucket($data['bucket'])->object($data['name']);
$filePath = 'gs://' . $data['bucket'] . '/' . $data['name'];
fwrite($log, 'Analyzing ' . $filePath . PHP_EOL);
$annotator = new ImageAnnotatorClient();
$storage = new StorageClient();
try {
$response = $annotator->safeSearchDetection($filePath);
// Handle error
if ($response->hasError()) {
$code = Code::name($response->getError()->getCode());
$message = $response->getError()->getMessage();
fwrite($log, sprintf('%s: %s' . PHP_EOL, $code, $message));
return;
}
$annotation = $response->getSafeSearchAnnotation();
$isInappropriate =
$annotation->getAdult() === Likelihood::VERY_LIKELY ||
$annotation->getViolence() === Likelihood::VERY_LIKELY;
if ($isInappropriate) {
fwrite($log, 'Detected ' . $data['name'] . ' as inappropriate.' . PHP_EOL);
$blurredBucketName = getenv('BLURRED_BUCKET_NAME');
blurImage($log, $file, $blurredBucketName);
} else {
fwrite($log, 'Detected ' . $data['name'] . ' as OK.' . PHP_EOL);
}
} catch (Exception $e) {
fwrite($log, 'Failed to analyze ' . $data['name'] . PHP_EOL);
fwrite($log, $e->getMessage() . PHP_EOL);
}
}