Installation:
composer require bubnov/tenserflow-bundle:~3.0
Add the bundle to AppKernel.php:
new Bubnov\TensorFlowBundle\BubnovTensorFlowBundle(),
Configure TensorFlow Binary:
The bundle auto-installs TensorFlow binaries via Composer scripts (post-install-cmd/post-update-cmd). Ensure your system meets TensorFlow’s native dependencies (e.g., CUDA for GPU acceleration if needed).
First Use Case: Inject the recognizer service in a controller and recognize an image:
use Bubnov\TensorFlowBundle\Util\RecognizerResult;
class ImageController extends Controller
{
public function recognizeAction(string $imagePath)
{
/** @var RecognizerResult $result */
$result = $this->get('tenserflow.recognizer')->recognize($imagePath);
$topLabel = $result->getTopLabel();
return $this->render('image/result.html.twig', [
'label' => $topLabel->getName(),
'score' => $topLabel->getScore(),
]);
}
}
Resources/config/services.yml (if provided) for customization options.Util\RecognizerResult class to understand available methods (e.g., getLabels(), getTopLabel()).php bin/console to see available TensorFlow-related commands (e.g., model training or binary updates).Image Recognition Pipeline:
/uploads/cats/1.jpg).tenserflow.recognizer service to process the image.RecognizerResult object to extract labels/scores.
$labels = $result->getLabels(); // Array of Label objects
$topLabel = $result->getTopLabel();
Batch Processing: Loop through images and cache results to avoid redundant TensorFlow calls:
$imagePaths = ['path1.jpg', 'path2.jpg'];
$results = [];
foreach ($imagePaths as $path) {
$results[$path] = $this->get('tenserflow.recognizer')->recognize($path);
}
Integration with Forms: Use Symfony’s form components to upload images and trigger recognition:
// In a form type
$builder->add('image', FileType::class, [
'mapped' => false,
'constraints' => [new Image(['maxSize' => '1024k'])]
]);
// In controller
$file = $request->files->get('image');
$tempPath = $file->getRealPath();
$result = $this->get('tenserflow.recognizer')->recognize($tempPath);
Custom Model Support: If the bundle supports loading custom TensorFlow models, configure it via YAML:
# config.yml
bubnov_tensorflow:
model_path: "%kernel.project_dir%/models/custom_model.pb"
Asynchronous Processing: Use Symfony’s Messenger component to offload recognition to a background worker (e.g., Symfony Messenger + Doctrine Messenger):
$message = new RecognizeImageMessage($imagePath);
$this->get('messenger.default_bus')->dispatch($message);
API Endpoint: Expose recognition as a REST API:
// src/Controller/ImageApiController.php
#[Route('/api/recognize', methods: ['POST'])]
public function recognizeApi(Request $request): JsonResponse
{
$image = $request->files->get('image');
$result = $this->get('tenserflow.recognizer')->recognize($image->getRealPath());
return $this->json([
'label' => $result->getTopLabel()->getName(),
'score' => $result->getTopLabel()->getScore(),
]);
}
Filesystem or VichUploaderBundle to manage image uploads before recognition.RecognizerResult objects if the same image is processed repeatedly (e.g., with Symfony Cache component).try {
$result = $this->get('tenserflow.recognizer')->recognize($path);
} catch (\RuntimeException $e) {
// Log error or return user-friendly message
}
TensorFlow Binary Dependencies:
libstdc++).composer.json scripts for errors during post-install-cmd. Run composer install --verbose to diagnose issues.Image Format Limitations:
.tiff). Convert images to .jpg/.png before processing.Imagick or Gd extensions to pre-process images.Performance Bottlenecks:
Outdated Bundle:
Service Naming:
tenserflow.recognizer (note the typo in "tenserflow"). Double-check the service ID when autowiring or injecting.Binary Installation Failures:
post-install-cmd fails, manually install TensorFlow binaries:
# Example for Linux (adjust for your OS)
wget https://github.com/tensorflow/tensorflow/releases/download/v1.15.0/tensorflow-1.15.0-cp37-cp37m-linux_x86_64.whl
pip install tensorflow-1.15.0-cp37-cp37m-linux_x86_64.whl
composer install -v) to see detailed script output.Image Recognition Errors:
if (!file_exists($imagePath) || !is_readable($imagePath)) {
throw new \InvalidArgumentException("Image not found or unreadable.");
}
Service Unavailable:
AppKernel.php.vendor/bubnov/tenserflow-bundle/bin/.chmod +x vendor/bubnov/tenserflow-bundle/bin/*).Custom Recognizer Logic:
Extend the RecognizerResult class to add domain-specific methods:
class CustomRecognizerResult extends \Bubnov\TensorFlowBundle\Util\RecognizerResult
{
public function isCat(): bool
{
return $this->getTopLabel()->getName() === 'cat';
}
}
Override Service Configuration:
Replace the default recognizer service in services.yaml:
services:
tenserflow.recognizer:
class: App\Service\CustomRecognizer
arguments:
- '@tenserflow.recognizer' # Inject the original service
Add New Commands: Create a custom command to interact with TensorFlow (e.g., model training):
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class TrainModelCommand extends Command
{
protected function configure()
{
$this->setName('tensorflow:train');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// Use TensorFlow PHP bindings or shell out to TensorFlow CLI
$output->
How can I help you explore Laravel packages today?