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

Clarifai Bundle Laravel Package

daviddlv/clarifai-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation:

    composer require daviddlv/clarifai-bundle
    

    Ensure your composer.json has "minimum-stability": "dev" if using unreleased versions.

  2. Enable the Bundle: Add new ClarifaiBundle\ClarifaiBundle() to AppKernel.php (Symfony 2.x) or config/bundles.php (Symfony 3/4/5).

  3. Configure Credentials: Add your Clarifai API credentials to config/packages/clarifai.yaml (or config.yml in Symfony 2.x):

    clarifai:
        auth:
            client_id: "%env(CLARIFAI_CLIENT_ID)%"
            client_secret: "%env(CLARIFAI_CLIENT_SECRET)%"
    

    Use environment variables (.env) for security.

  4. First Use Case: Inject the Clarifai client into a service/controller and call the API:

    use ClarifaiBundle\Service\ClarifaiClient;
    
    class ImageAnalyzer
    {
        public function __construct(private ClarifaiClient $clarifai)
        {
        }
    
        public function analyzeImage(string $imagePath): array
        {
            $response = $this->clarifai->getClient()->models()
                ->predict(ClarifaiModel::GENERAL_MODEL, $imagePath);
    
            return $response->get('outputs')[0]['data']['concepts'];
        }
    }
    

Implementation Patterns

Common Workflows

  1. Image Tagging/Classification: Use the predict method with the general model or a custom model:

    $concepts = $this->clarifai->predict(
        ClarifaiModel::GENERAL_MODEL,
        'path/to/image.jpg',
        ['concepts' => ['limit' => 5]] // Optional parameters
    );
    
  2. Custom Model Workflows:

    • Train a Model:
      $model = $this->clarifai->models()->create(
          'my-custom-model',
          ClarifaiModelType::CONCEPT,
          ['concept' => ['name' => 'my-concept']]
      );
      
    • Predict with Custom Model:
      $results = $this->clarifai->predict($model->getId(), 'image.jpg');
      
  3. Batch Processing: Process multiple images sequentially or in parallel (using Symfony’s Messenger or Process components):

    foreach ($imagePaths as $path) {
        $this->clarifai->predict(ClarifaiModel::GENERAL_MODEL, $path);
    }
    
  4. Error Handling: Wrap API calls in try-catch blocks to handle Clarifai-specific exceptions:

    try {
        $response = $this->clarifai->predict(...);
    } catch (ClarifaiException $e) {
        // Log or retry (e.g., rate limit exceeded)
        $this->logger->error('Clarifai API error: ' . $e->getMessage());
    }
    
  5. Integration with Forms: Use the bundle in a Symfony form to validate or auto-tag uploaded images:

    $builder->add('image', FileType::class, [
        'mapped' => false,
        'constraints' => [
            new Callback([
                'callback' => [$this, 'validateImageTags'],
            ]),
        ],
    ]);
    
  6. Caching Responses: Cache API responses (e.g., with Symfony’s Cache component) to avoid redundant calls:

    $cacheKey = md5($imagePath);
    $concepts = $this->cache->get($cacheKey, function() use ($imagePath) {
        return $this->clarifai->predict(ClarifaiModel::GENERAL_MODEL, $imagePath);
    });
    

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony Version: The bundle was last updated in 2016 and targets Symfony 2.x. For Symfony 3/4/5:

    • Use a wrapper service to adapt the bundle’s client to Symfony’s DI container.
    • Example:
      // src/Service/ClarifaiAdapter.php
      class ClarifaiAdapter
      {
          public function __construct(private ClarifaiClient $legacyClient)
          {
          }
      
          public function predict(string $modelId, string $imagePath): array
          {
              return $this->legacyClient->getClient()->models()->predict($modelId, $imagePath);
          }
      }
      
    • Register the adapter as a service in config/services.yaml:
      services:
          App\Service\ClarifaiAdapter:
              arguments:
                  $legacyClient: '@clarifai.api.client'
      
  2. Authentication Issues:

    • Ensure client_id and client_secret are correctly set in config.yml.
    • If using Symfony 4/5, prepend with %env(CLARIFAI_ to load from .env:
      clarifai:
          auth:
              client_id: "%env(CLARIFAI_CLIENT_ID)%"
      
  3. Rate Limiting: Clarifai enforces rate limits (e.g., 1000 requests/day for free tier). Implement exponential backoff:

    use Symfony\Component\Process\Exception\ProcessFailedException;
    
    try {
        $response = $this->clarifai->predict(...);
    } catch (ProcessFailedException $e) {
        if (strpos($e->getMessage(), 'rate limit') !== false) {
            sleep(60); // Wait 1 minute and retry
        }
    }
    
  4. Image Format Requirements: Clarifai expects images in JPEG, PNG, or GIF format. Validate uploads:

    $image = $request->file('image');
    $mimeType = $image->getMimeType();
    if (!in_array($mimeType, ['image/jpeg', 'image/png', 'image/gif'])) {
        throw $this->createNotAcceptableException('Unsupported image format');
    }
    
  5. Model Management:

    • The bundle lacks built-in methods for deleting models or managing datasets. Use raw API calls:
      $this->clarifai->getClient()->models()->delete($modelId);
      

Tips

  1. Environment-Specific Config: Override the bundle’s configuration per environment (e.g., config/packages/clarifai/dev.yaml):

    clarifai:
        auth:
            client_id: "%env(CLARIFAI_CLIENT_ID_DEV)%"
        debug: true
    
  2. Logging API Calls: Enable debug mode to log API requests/responses:

    clarifai:
        debug: true
    

    Check logs for raw API output (useful for debugging).

  3. Testing: Mock the ClarifaiClient in tests using PHPUnit’s createMock:

    $mockClient = $this->createMock(ClarifaiClient::class);
    $mockClient->method('getClient')->willReturn($this->createMock(Clarifai\Client::class));
    $this->container->set('clarifai.api.client', $mockClient);
    
  4. Custom Endpoints: Extend the bundle to support Clarifai’s custom endpoints (e.g., moderation, face detection):

    // src/Service/ClarifaiExtendedClient.php
    class ClarifaiExtendedClient extends ClarifaiClient
    {
        public function detectModeration(string $imagePath): array
        {
            return $this->getClient()->models()
                ->predict(ClarifaiModel::MODERATION_MODEL, $imagePath);
        }
    }
    
  5. Performance:

    • Stream large images to avoid memory issues:
      $imageStream = fopen($imagePath, 'r');
      $response = $this->clarifai->predict(..., $imageStream);
      fclose($imageStream);
      
    • Use asynchronous processing (e.g., Symfony Messenger) for long-running tasks.
  6. Fallback Mechanisms: Implement a fallback to a local ML model if Clarifai fails:

    try {
        return $this->clarifai->predict(...);
    } catch (ClarifaiException $e) {
        return $this->localFallbackModel->predict($imagePath);
    }
    
  7. Documentation Gaps: The bundle’s README lacks examples for custom models or dataset management. Refer to:

    • Clarifai API Docs
    • Bundle’s source code (src/Service/ClarifaiClient.php) for undocumented methods.
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui