Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Rekognition Php Laravel Package

clickandmortar/rekognition-php

Simple PHP library for AWS Rekognition. Detect labels (objects, scenes, concepts) and text in JPEG/PNG images. Works with image URLs, raw file bytes, or base64, returning easy-to-filter results by confidence.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require clickandmortar/rekognition-php
    

    Ensure your AWS credentials are configured via:

    • Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION)
    • Or via ~/.aws/credentials file.
  2. First Use Case: Detect Labels in an Image

    use ClickAndMortar\Rekognition\Rekognition;
    
    $rekognition = new Rekognition();
    $result = $rekognition->detectLabels('path/to/image.jpg');
    print_r($result);
    
    • Key Output: Returns an array of detected labels with confidence scores.
  3. Where to Look First

    • AWS Rekognition Documentation (for feature reference).
    • src/ClickAndMortar/Rekognition/Rekognition.php (core class methods).
    • tests/ directory (for usage examples and edge cases).

Implementation Patterns

Common Workflows

  1. Image Analysis Pipeline

    $rekognition = new Rekognition();
    $labels = $rekognition->detectLabels($imagePath);
    $faces = $rekognition->detectFaces($imagePath);
    $text = $rekognition->detectText($imagePath);
    
    // Filter labels by confidence threshold
    $filteredLabels = array_filter($labels, fn($label) => $label['Confidence'] > 80);
    
  2. Batch Processing

    $rekognition = new Rekognition();
    $images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
    $results = [];
    
    foreach ($images as $image) {
        $results[$image] = $rekognition->detectLabels($image);
    }
    
  3. Integration with Laravel

    • Store AWS responses in a database:
      $rekognition = new Rekognition();
      $labels = $rekognition->detectLabels($request->file('image')->path());
      
      Analysis::create([
          'user_id' => auth()->id(),
          'labels' => json_encode($labels),
      ]);
      
    • Use middleware to validate AWS responses:
      public function handle($request, Closure $next) {
          $response = $rekognition->detectLabels($request->image);
          if (empty($response)) {
              abort(400, 'No labels detected.');
          }
          return $next($request);
      }
      
  4. Async Processing with Queues

    // Dispatch a job
    DetectLabelsJob::dispatch($imagePath, $userId);
    
    // Job class
    public function handle() {
        $rekognition = new Rekognition();
        $labels = $rekognition->detectLabels(storage_path($this->imagePath));
        Analysis::create([...]);
    }
    

Gotchas and Tips

Pitfalls

  1. AWS Credentials

    • If using IAM roles (e.g., in EC2), ensure the role has rekognition:Detect* permissions.
    • Error: AccessDeniedException → Verify IAM policies and credentials.
  2. Image Format/Size

    • Rekognition supports JPEG/PNG (max 10MB for DetectLabels, 5MB for DetectText).
    • Error: InvalidS3ObjectException → Check file size/type before upload.
  3. Rate Limits

    • AWS Rekognition has service quotas.
    • Tip: Implement exponential backoff for throttling (ThrottlingException).
  4. Deprecated Methods

    • The package is unmaintained (last release: 2019). Some AWS API changes may break compatibility.
    • Workaround: Extend the class or use the official AWS SDK as a fallback.

Debugging Tips

  1. Enable AWS SDK Debugging

    use Aws\Common\Aws;
    Aws::setDebug(true); // Logs requests/responses to `storage/logs/aws.log`
    
  2. Validate Responses

    $result = $rekognition->detectLabels($imagePath);
    if (!isset($result['Labels'])) {
        throw new \RuntimeException('Invalid Rekognition response');
    }
    
  3. Handle Exceptions

    try {
        $result = $rekognition->detectLabels($imagePath);
    } catch (\Aws\Rekognition\Exception\RekognitionException $e) {
        Log::error('Rekognition Error: ' . $e->getMessage());
        abort(500, 'Image analysis failed.');
    }
    

Extension Points

  1. Custom Response Mapping

    $rekognition = new Rekognition();
    $rawResult = $rekognition->detectLabels($imagePath);
    
    // Transform raw AWS response
    $formatted = array_map(function($label) {
        return [
            'name' => $label['Name'],
            'confidence' => $label['Confidence'] / 100, // Convert to decimal
            'parents' => $label['Parents'] ?? [],
        ];
    }, $rawResult['Labels']);
    
  2. Add New Features

    • Extend the Rekognition class to support unsupported APIs (e.g., CompareFaces):
      class ExtendedRekognition extends Rekognition {
          public function compareFaces($sourceImage, $targetImage) {
              return $this->client->compareFaces([
                  'SourceImage' => ['Bytes' => file_get_contents($sourceImage)],
                  'TargetImage' => ['Bytes' => file_get_contents($targetImage)],
              ]);
          }
      }
      
  3. Mocking for Tests

    $rekognition = Mockery::mock(ClickAndMortar\Rekognition\Rekognition::class);
    $rekognition->shouldReceive('detectLabels')
                ->once()
                ->andReturn(['Labels' => [['Name' => 'Car', 'Confidence' => 99]]]);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor