codewithkyrian/transformers
A Laravel-friendly transformers package for turning models, arrays, and API responses into consistent, reusable output. Define transformer classes, map fields, nest relations, and format data cleanly for JSON APIs, with minimal boilerplate and flexible customization.
Installation
composer require codewithkyrian/transformers
Ensure PHP ≥ 8.4 (due to nullable deprecations in this release) and php-ml extension is installed (required for core ML operations).
First Use Case: Text Classification
use CodeWithKyrian\Transformers\Pipeline;
use CodeWithKyrian\Transformers\Tasks\ClassificationTask;
$pipeline = Pipeline::create('distilbert-base-uncased-finetuned-sst-2-english');
$result = $pipeline->forward(['text' => 'This product is amazing!']);
// Output: ['label' => 'POSITIVE', 'scores' => ['NEGATIVE' => 0.05, 'POSITIVE' => 0.95]]
Key Files to Explore
config/transformers.php: Updated model configurations, API endpoints, and Symfony 8 compatibility settings.src/Tasks/: Predefined tasks (e.g., TextGenerationTask, TranslationTask).src/Pipeline.php: Core pipeline logic with PHP 8.4 nullable type fixes.src/Console/: New CLI command registration fixes (if using artisan commands).$task = new ClassificationTask('bert-base-uncased');
$task->setText('The service was terrible.');
$predictions = $task->predict(); // Returns labeled probabilities
$generator = new TextGenerationTask('gpt2');
$generator->setPrompt('Once upon a time');
$output = $generator->generate(); // Returns generated text
$translator = new TranslationTask('Helsinki-NLP/opus-mt-en-fr');
$translation = $translator->translate('Hello', 'fr'); // 'Bonjour'
Chaining Tasks:
$pipeline = Pipeline::create('text2text-generation')
->setTask(new TextGenerationTask('t5-small'))
->setTask(new PostProcessTask()); // Custom post-processing
Dynamic Model Loading:
$pipeline = Pipeline::create('custom-model')
->setModelPath(storage_path('models/custom.pt'))
->setTask(new CustomTask());
// app/Providers/AppServiceProvider.php
public function register()
{
$this->app->singleton(Pipeline::class, function ($app) {
return Pipeline::create('distilbert-base-uncased');
});
}
Route::post('/analyze-sentiment', function (Request $request) {
$pipeline = app(Pipeline::class);
$result = $pipeline->forward(['text' => $request->text]);
return response()->json($result);
});
// app/Jobs/ProcessTextJob.php
public function handle()
{
$pipeline = Pipeline::create('text-generation');
$this->text->content = $pipeline->forward(['text' => $this->text->prompt]);
$this->text->save();
}
$pipeline = Pipeline::create('bert-base-uncased')
->setCacheTTL(3600); // Cache for 1 hour
$result = $pipeline->forward(['text' => 'Cached example']);
If using artisan commands, ensure proper CLI registration:
php artisan transformers:task --help # Example command (if applicable)
PHP 8.4 Nullable Deprecations
Symfony 8 Compatibility
composer.json to align with Symfony 8 requirements if needed.Namespace Conflicts
Transformers to prevent conflicts.App\Tasks\CustomTask).Model Size Limits
gpt-3.5-turbo) require significant RAM. Use smaller variants (e.g., distilbert) for production.memory_get_usage() and offload to a microservice if needed.API Rate Limits
Cache::remember wrapper around Pipeline::forward().Tokenization Errors
bigscience/bloom).GPU Acceleration
config/transformers.php:
'device' => 'cuda',
$pipeline->setLogger(function ($log) {
\Log::debug('Transformer Log:', ['event' => $log]);
});
if (!$pipeline->isValid()) {
\Log::error('Invalid model output:', $pipeline->getErrors());
}
Custom Tasks
// app/Tasks/CustomTask.php
class CustomTask extends Task
{
public function predict(array $inputs): array
{
// Implement custom logic (e.g., ensemble models)
return ['custom_result' => true];
}
}
Pre/Post-Processing
$pipeline->setPreProcess(function ($inputs) {
return ['cleaned_text' => strtolower($inputs['text'])];
});
$pipeline->setPostProcess(function ($output) {
return ['formatted' => ucfirst($output['label'])];
});
Model Fine-Tuning
HuggingFace\Transformers PHP bindings to fine-tune models locally, then load them via:
$pipeline->setModelPath('/path/to/fine-tuned-model');
// config/transformers.php
'api_endpoint' => env('TRANSFORMERS_API_URL', 'https://api-inference.huggingface.co'),
$model = config('transformers.models.'.env('APP_ENV'));
$pipeline = Pipeline::create($model);
$results = $pipeline->batchForward([
['text' => 'Sample 1'],
['text' => 'Sample 2'],
]);
$pipeline = Pipeline::lazy('text-generation'); // Loads model on first use
composer.json includes compatible dependencies:
"require": {
"symfony/*": "^6.4 || ^8.0"
}
Transformers to prevent conflicts.How can I help you explore Laravel packages today?