### Download and Install Dependencies Source: https://github.com/codewithkyrian/transformers-php/blob/main/scripts/convert_upload_hf.ipynb Downloads the requirements file and conversion script, then installs the necessary Python packages. Ensure you have `wget` and `pip` available. ```python !wget https://raw.githubusercontent.com/xenova/transformers.js/main/scripts/requirements.txt !wget https://raw.githubusercontent.com/xenova/transformers.js/main/scripts/convert.py !pip install -r requirements.txt -q !pip install huggingface_hub -q ``` -------------------------------- ### Running an Inference Session Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/image-to-image.md Example of how to initialize the image-to-image pipeline and perform translation. ```APIDOC ## Running an Inference Session Here's how to perform image-to-image translation using the pipeline: ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $upscaler = pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64'); $result = $upscaler('path/to/image.jpg', saveTo: 'path/to/super-resolved-image.jpg'); ``` ::: details Click to view output ```php [ 'path' => 'path/to/super-resolved-image.jpg', 'width' => 512, 'height' => 512, 'channels' => 3 ] ``` ::: ## Pipeline Input Options When running the `image-to-image` pipeline, you can use the following options: - ### `texts` *(string)* The image(s) to translate. It can be a local file path, a file resource, a URL to an image (local or remote), or an array of these inputs. It's the first argument so there's no need to pass it as a named argument. ```php $result = $upscaler('https://example.com/image.jpg'); ``` - ### `saveTo` *(string)* The path to save the translated image. It is compulsory and an exception will be thrown if it is not provided. If the input texts are an array of images, the `saveTo` should also be an array of the same length. The `saveTo` path(s) should include the file extension (e.g., `.jpg`, `.png`, `.bmp`, etc.). ```php $result = $upscaler('https://example.com/image.jpg', saveTo: 'path/to/super-resolved-image.jpg'); ``` ## Pipeline Output The pipeline returns an array containing the following keys: - `path` *(string)*: The path to the translated image. - `width` *(int)*: The width of the translated image. - `height` *(int)*: The height of the translated image. - `channels` *(int)*: The number of channels in the translated image (e.g., 1 for grayscale, 3 for RGB). If the input is one image(non batched), the output will directly contain the keys `path`, `width`, `height`, and `channels`. If the input is an array of images, the output will be an array of the above keys for each image. E.g., for a single image: ```php [ 'path' => 'path/to/super-resolved-image.jpg', 'width' => 512, 'height' => 512, 'channels' => 3 ] ``` For multiple images: ```php [ [ 'path' => 'path/to/super-resolved-image1.jpg', 'width' => 512, 'height' => 512, 'channels' => 3 ], [ 'path' => 'path/to/super-resolved-image2.jpg', 'width' => 512, 'height' => 512, 'channels' => 3 ], // Additional translated images ] ``` ``` -------------------------------- ### Example Tokenization Output Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/tokenizers.md Illustrates a basic word-based tokenization of a sentence. ```php [ 'His', 'transformation', 'into', 'a', 'smart', 'young', 'man', 'was', 'remarkable' ] ``` -------------------------------- ### Initialize and Run Question Answering Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/question-answering.md Instantiate the question-answering pipeline with a model and provide a question and context to get the answer. ```php $question = "Who is known as the father of computers?"; $context = "The history of computing is longer than the history of computing hardware and modern computing technology and includes the history of methods intended for pen and paper or for chalk and slate, with or without the aid of tables. Charles Babbage is often regarded as one of the fathers of computing because of his contributions to the basic design of the computer through his analytical engine."; $pipeline = pipeline('question-answering', 'Xenova/distilbert-base-cased-distilled-squad'); $result = $pipeline($question, $context); ``` -------------------------------- ### Manually Install TransformersPHP Shared Libraries Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/getting-started.md If the automatic installation of shared libraries fails, use this command to install them manually. Ensure this is run on the target platform. ```bash ./vendor/bin/transformers install ``` -------------------------------- ### Object Detection Output Example Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/object-detection.md Example of the output format for object detection, showing detected objects with their confidence scores, labels, and bounding box coordinates. ```php [ [ "score" => 0.99796805983403, "label" => "remote", "box" => [ "xmin" => 29, "ymin" => 65, "xmax" => 188, "ymax" => 122 ] ], // Additional detected objects with their scores, labels, and bounding boxes ] ``` -------------------------------- ### Install TransformersPHP via Composer Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/getting-started.md Use Composer to install the TransformersPHP library and its dependencies. This is the recommended installation method. ```bash composer require codewithkyrian/transformers ``` -------------------------------- ### Download a Specific Model Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/getting-started.md Example of downloading the 'Xenova/bert-base-uncased' model using the command-line tool. This ensures the model is available locally. ```bash ./vendor/bin/transformers download Xenova/bert-base-uncased ``` -------------------------------- ### Setup Model Credentials and Parameters Source: https://github.com/codewithkyrian/transformers-php/blob/main/scripts/convert_upload_hf.ipynb Defines the model ID, task type, and Hugging Face username for the conversion and upload process. These are configurable parameters. ```python model = "textattack/bert-base-uncased-rotten-tomatoes" # @param {type:"string"} task = "text-classification" # @param {type:"string"} user = "codewithkyrian" # @param {type:"string"} ``` -------------------------------- ### Image Captioning Output Example Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/image-to-text.md Example of the expected output format for image captioning, which is an array containing a 'text' key with the generated caption. ```php [ "text" => "A close up of a cat sitting on a bed" ] ``` -------------------------------- ### Example Classification Output Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/models.md This is an example of the post-processed output for a classification task, showing the probability of different toxicity labels. ```bash toxic: 0.98505208976127 severe_toxic: 0.00054822923280057 obscene: 0.0014310951235518 threat: 0.0036767840868768 insult: 0.0082214922365694 identity_hate: 0.0010703095589325 ``` -------------------------------- ### Token Classification: AggregationStrategy::NONE Example Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/token-classification.md Demonstrates the output structure when no aggregation is performed, showing individual tokens and their labels. ```php [ // ... ['entity' => 'B-LOC', 'word' => 'On', 'score' => 0.9980088367015,], ['entity' => 'I-LOC', 'word' => '##its', 'score' => 0.57264213459144,], ['entity' => 'I-LOC', 'word' => '##ha', 'score' => 0.99585163659008,] ] // For "United States of America" [ // ... ['entity' => 'B-LOC', 'word' => 'United', 'score' => 0.99959621338567,], ['entity' => 'I-LOC', 'word' => 'States', 'score' => 0.99930135657091,], ['entity' => 'I-LOC', 'word' => 'of', 'score' => 0.99910850633584,], ['entity' => 'I-LOC', 'word' => 'America', 'score' => 0.99851260224595,] ] ``` -------------------------------- ### Run Question Natural Language Inference (QNLI) Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/text-classification.md Execute Question Natural Language Inference with a dedicated model. This QNLI example uses Xenova/qnli-electra-base to assess the relationship between a question and a potential answer. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $qnli = pipeline('text-classification', 'Xenova/qnli-electra-base'); $result = $qnli('Where is the capital of Nigeria?', 'The capital of Nigeria is Abuja.'); ``` -------------------------------- ### Setup TransformersPHP with Custom Configuration Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/configuration.md Configure cache directory, remote host, path template, authentication token, user agent, image driver, and logger. Leave out methods to use default settings. ```php use Codewithkyrian\Transformers\Transformers; use Codewithkyrian\Transformers\Utils\ImageDriver; use Psr\Log\LoggerInterface; Transformers::setup() ->setCacheDir('/path/to/models') ->setRemoteHost('https://yourmodelshost.com') ->setRemotePathTemplate('custom/path/{model}/{file}') ->setAuthToken('your-token') ->setUserAgent('your-user-agent') ->setImageDriver(ImageDriver::IMAGICK) ->setLogger($logger); ``` -------------------------------- ### Object Detection Output (Percentage Coordinates) Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/object-detection.md Example of object detection results when the 'percentage' option is set to true, showing bounding box coordinates as percentages of image dimensions. ```php [ [ "score" => 0.99796805983403, "label" => "remote", "box" => [ "xmin" => 0.046750202775002, "ymin" => 0.1370929479599, "xmax" => 0.29410694539547, "ymax" => 0.25422710180283 ] ], [ "score" => 0.99609794521754 "label" => "couch" "box" => array:4 [ "xmin" => -0.0045824944972992, "ymin" => 0.00046494603157043, "xmax" => 0.99463525414467, "ymax" => 0.98414328694344] ], [ "score" => 0.99781166261151 "label" => "cat" "box" => array:4 [ "xmin" => 0.0078403949737549, "ymin" => 0.11353152990341, "xmax" => 0.50537252426147, "ymax" => 0.9735626578331 ] ], // Additional detected objects with their scores, labels, and bounding boxes ] ``` -------------------------------- ### Example Subword Tokenization Output Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/tokenizers.md Demonstrates subword tokenization, reducing vocabulary size by breaking words into smaller units. ```php [ 'His', 'transform', '##ation', 'into', 'a', 'smart', 'young', 'man', 'was', 'remark', '##able' ] ``` -------------------------------- ### Multiple Audio Files Classification Output Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/audio-classification.md Example output when classifying multiple audio files, presenting labels and scores for each. ```php [ ['label' => 'Dog Barking', 'score' => 0.9321], ['label' => 'Car Horn', 'score' => 0.8234], ['label' => 'Siren', 'score' => 0.7123] ] ``` -------------------------------- ### Running Natural Language Inference (NLI) Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/text-classification.md Example of performing Natural Language Inference using a specific model. ```APIDOC ## Running Natural Language Inference (NLI) Example of performing Natural Language Inference using a specific model. ### Method Signature ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $nli = pipeline('text-classification', 'Xenova/roberta-large-mnli'); $result = $nli('A person is eating, there is no food left'); ``` ### Output Example ```php [ 'label' => 'contradiction', 'score' => 0.9595358059835 ] ``` ``` -------------------------------- ### Zero-Shot Object Detection Output (Percentage Coordinates) Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/zero-shot-object-detection.md Example output format when the 'percentage' option is set to true. Bounding box coordinates are represented as percentages of the image dimensions. ```php [ [ "score" => 0.99796805983403, "label" => "car", "box" => [ "xmin" => 0.05, "ymin" => 0.15, "xmax" => 0.25, "ymax" => 0.30 ] ], // Additional detected objects with their scores, labels, and bounding boxes ] ``` -------------------------------- ### Basic Text Generation Output Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/text-generation.md Example of the standard output format for the text-generation pipeline, where each input corresponds to an entry with a 'generated_text' key. ```php [ ['generated_text' => 'Once upon a time, there was a curious child who wanted to explore the world. She packed her bag and set off on an adventure that would take her to the most amazing places...'] ] ``` -------------------------------- ### Run Image Feature Extraction Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/image-feature-extraction.md Instantiate the image-feature-extraction pipeline and process an image to get its feature vector. Ensure the image path is correct. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $extractor = pipeline('image-feature-extraction'); $result = $extractor('path/to/image.jpg'); ``` -------------------------------- ### Zero-Shot Image Classification Output Example Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/zero-shot-image-classification.md The output format for zero-shot image classification, showing the predicted label and its associated confidence score. ```json [ ['label' => 'zebra', 'score' => 0.83534494664876], ['label' => 'elephant', 'score' => 0.03534494664876], ['label' => 'giraffe', 'score' => 0.00534494664876] ] ``` -------------------------------- ### Run Natural Language Inference (NLI) Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/text-classification.md Perform Natural Language Inference using a specified model. This example uses Xenova/roberta-large-mnli to determine the relationship between two sentences. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $nli = pipeline('text-classification', 'Xenova/roberta-large-mnli'); $result = $nli('A person is eating, there is no food left'); ``` -------------------------------- ### Object Detection Output (Absolute Coordinates) Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/object-detection.md Example of object detection results when the 'percentage' option is set to false, showing absolute pixel coordinates for bounding boxes. ```php [ [ "score" => 0.99796805983403, "label" => "remote", "box" => [ "xmin" => 29, "ymin" => 65, "xmax" => 188, "ymax" => 122 ] ], [ "score" => 0.99609794521754 "label" => "couch" "box" => array:4 [ "xmin" => 2, "ymin" => 0, "xmax" => 636, "ymax" => 472] ], [ "score" => 0.99781166261151 "label" => "cat" "box" => array:4 [ "xmin" => 5, "ymin" => 54, "xmax" => 323, "ymax" => 467 ] ], // Additional detected objects with their scores, labels, and bounding boxes ] ``` -------------------------------- ### Zero-Shot Object Detection Output (Absolute Coordinates) Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/zero-shot-object-detection.md Example output format when the 'percentage' option is set to false. Bounding box coordinates are represented as absolute pixel values. ```php [ [ "score" => 0.99796805983403, "label" => "car", "box" => [ "xmin" => 29, "ymin" => 65, "xmax" => 188, "ymax" => 122 ] ], // Additional detected objects with their scores, labels, and bounding boxes ] ``` -------------------------------- ### Token Classification: AggregationStrategy::FIRST Example Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/token-classification.md Shows how AggregationStrategy::FIRST groups subwords and tokens with similar entities, assigning the score of the first token in the group. The 'entity' key changes to 'entity_group'. ```php // For "Onitsha" [ // ... ['entity_group' => 'LOC', 'word' => 'Onitsha', 'score' => 0.9980088367015,], ] // For "United States of America" [ // ... ['entity_group' => 'LOC', 'word' => 'United States of America', 'score' => 0.99959621338567,], ] ``` -------------------------------- ### Get Minimum Value of Tensor Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/utils/tensor.md Finds the minimum value in a tensor. Specify an axis to get minimum values along that dimension. ```php $data = [[1, 2, 3], [4, 5, 6]]; $tensor = Tensor::fromArray($data); $min = $tensor->min(); // 1 $min = $tensor->min(1); // [1, 4] ``` -------------------------------- ### Get Maximum Value of Tensor Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/utils/tensor.md Finds the maximum value in a tensor. Specify an axis to get maximum values along that dimension. ```php $data = [[1, 2, 3], [4, 5, 6]]; $tensor = Tensor::fromArray($data); $max = $tensor->max(); // 6 $max = $tensor->max(1); // [3, 6] ``` -------------------------------- ### Global Configuration with Transformers::setup() Source: https://context7.com/codewithkyrian/transformers-php/llms.txt Configure global defaults for cache directory, model host, authentication, image driver, and logging. This should be called once in your bootstrap script before using any pipelines or models. ```php require_once 'vendor/autoload.php'; use Codewithkyrian\Transformers\Transformers; use Codewithkyrian\Transformers\Utils\ImageDriver; use Monolog\Logger; use Monolog\Handler\StreamHandler; // Create a PSR-3 compatible logger (optional) $logger = new Logger('transformers'); $logger->pushHandler(new StreamHandler('logs/transformers.log', Logger::INFO)); Transformers::setup() ->setCacheDir('/var/app/storage/transformers') // Default: .transformers-cache/models ->setRemoteHost('https://huggingface.co') // Default HF hub; change for private hosting ->setRemotePathTemplate('{model}/resolve/{revision}/{file}') // Default HF path pattern ->setAuthToken('hf_your_token_here') // For private/gated models ->setUserAgent('my-app/1.0') // Identifies your app in HTTP requests ->setImageDriver(ImageDriver::VIPS) // VIPS (default), IMAGICK, or GD ->setLogger($logger) // PSR-3 logger; NullLogger if omitted ->apply(); // Laravel: place in AppServiceProvider::boot() // Transformers::setup()->setCacheDir(storage_path('app/transformers'))->setLogger(Log::getLogger())->apply(); // Symfony: place in Kernel::boot() // Transformers::setup()->setCacheDir('/path/to/models')->setLogger($container->get(LoggerInterface::class))->apply(); ``` -------------------------------- ### Global Configuration - Transformers::setup() Source: https://context7.com/codewithkyrian/transformers-php/llms.txt Configures global defaults for cache directory, model host, authentication, image driver, and logging. This should be called once in your bootstrap script before any pipeline or model usage. ```APIDOC ## Global Configuration — `Transformers::setup()` Configures global defaults for cache directory, model host, authentication, image driver, and logging. Call once in your bootstrap script before any pipeline or model usage. ```php require_once 'vendor/autoload.php'; use Codewithkyrian\Transformers\Transformers; use Codewithkyrian\Transformers\Utils\ImageDriver; use Monolog\Logger; use Monolog\Handler\StreamHandler; // Create a PSR-3 compatible logger (optional) $logger = new Logger('transformers'); $logger->pushHandler(new StreamHandler('logs/transformers.log', Logger::INFO)); Transformers::setup() ->setCacheDir('/var/app/storage/transformers') // Default: .transformers-cache/models ->setRemoteHost('https://huggingface.co') // Default HF hub; change for private hosting ->setRemotePathTemplate('{model}/resolve/{revision}/{file}') // Default HF path pattern ->setAuthToken('hf_your_token_here') // For private/gated models ->setUserAgent('my-app/1.0') // Identifies your app in HTTP requests ->setImageDriver(ImageDriver::VIPS) // VIPS (default), IMAGICK, or GD ->setLogger($logger) // PSR-3 logger; NullLogger if omitted ->apply(); // Laravel: place in AppServiceProvider::boot() // Transformers::setup()->setCacheDir(storage_path('app/transformers'))->setLogger(Log::getLogger())->apply(); // Symfony: place in Kernel::boot() // Transformers::setup()->setCacheDir('/path/to/models')->setLogger($container->get(LoggerInterface::class))->apply(); ``` ``` -------------------------------- ### sliceWithBounds(array $start, array $size) Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/utils/tensor.md Slices the tensor using explicit start indices and sizes for each dimension. This provides precise control over the extracted sub-tensor. ```APIDOC ## sliceWithBounds(array $start, array $size) ### Description Slices the tensor with the given bounds. ### Parameters - `$start`: The starting indices of the slice. - `$size`: The size of the slice. ### Returns - A new tensor with the specified slice. ### Example ```php $tensor = Tensor::fromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); $slicedTensor = $tensor->sliceWithBounds([0, 1], [2, 2]); // [[2, 3], // [5, 6]] ``` ``` -------------------------------- ### Initialize Audio Classifier Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/audio-classification.md Instantiate the audio classification pipeline with a specific model. Ensure the model is compatible with audio classification tasks. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $classifier = pipeline('audio-classification', 'Xenova/ast-finetuned-audioset-10-10-0.4593'); $audioUrl = __DIR__ . '/../sounds/cat_meow.wav'; $output = $classifier($audioUrl, topK: 4); ``` -------------------------------- ### Get Top K Classifications Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/text-classification.md Specify the `topK` option to retrieve a specific number of top classification labels and their scores. Set to -1 to get all possible classifications. ```php $result = $classifier("I love TransformersPHP!", topK: 3); ``` -------------------------------- ### Download Models via CLI Source: https://github.com/codewithkyrian/transformers-php/blob/main/README.md Pre-download model weights in ONNX format using the command-line tool to avoid delays during initial model usage. Specify the model identifier, an optional task, and options like cache directory or quantization. ```bash ./vendor/bin/transformers download [] [options] ``` -------------------------------- ### Initialize Image Classification Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/image-classification.md Instantiate the image classification pipeline. This is the first step before performing any classification tasks. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $classifier = pipeline('image-classification'); $result = $classifier('path/to/image.jpg'); ``` -------------------------------- ### Running Text Classification with Multiple Texts Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/text-classification.md Demonstrates how to pass an array of texts to the classifier to get predictions for each sentence. ```APIDOC ## Running Text Classification with Multiple Texts Demonstrates how to pass an array of texts to the classifier to get predictions for each sentence. ### Method Signature ```php $result = $classifier(['I love TransformersPHP!', 'I hate TransformersPHP!']); ``` ``` -------------------------------- ### Create Hugging Face Repository Source: https://github.com/codewithkyrian/transformers-php/blob/main/scripts/convert_upload_hf.ipynb Creates a new repository on the Hugging Face Hub with the determined `repo_id`. `exist_ok=True` prevents errors if the repository already exists. ```python repo_url = create_repo(repo_id, exist_ok=True) ``` -------------------------------- ### Initialize Text-to-Text Generation Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/text-to-text-generation.md Instantiate the text-to-text generation pipeline with a specified model. Ensure the pipeline function and model name are correctly imported and referenced. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $generator = pipeline('text2text-generation', 'Xenova/flan-t5-small'); $output = $generator('Please let me know your thoughts on the given place and why you think it deserves to be visited: "Barcelona, Spain"''); ``` -------------------------------- ### Classify Multiple Texts Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/text-classification.md Pass an array of strings to the classifier to get predictions for each sentence. This is useful for batch processing. ```php $result = $classifier(['I love TransformersPHP!', 'I hate TransformersPHP!']); ``` -------------------------------- ### Run Zero-Shot Object Detection Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/zero-shot-object-detection.md Initialize the zero-shot object detection pipeline and run it with an image path and candidate labels. The output includes detected objects with their scores, labels, and bounding boxes. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $detector = pipeline('zero-shot-object-detection'); $result = $detector('path/to/image.jpg', ['person', 'car', 'traffic light']); ``` ```php [ [ "score" => 0.99796805983403, "label" => "car", "box" => [ "xmin" => 29, "ymin" => 65, "xmax" => 188, "ymax" => 122 ] ], // Additional detected objects with their scores, labels, and bounding boxes ] ``` -------------------------------- ### Tensor Statistical Operations in PHP Source: https://context7.com/codewithkyrian/transformers-php/llms.txt Provides examples for calculating standard deviation and mean along specified axes of a tensor. ```php [$std, $mean2] = $t2->stdMean(0); // $std = [1.5, 1.5, 1.5] $mean2 = [2.5, 3.5, 4.5] ``` -------------------------------- ### Running the Zero-Shot Object Detection Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/zero-shot-object-detection.md Initialize the zero-shot object detection pipeline and run it with an image and candidate labels. ```APIDOC ## Running the Zero-Shot Object Detection Pipeline ### Description Initialize the zero-shot object detection pipeline and run it with an image and candidate labels. ### Method Signature ```php $detector = pipeline('zero-shot-object-detection'); $result = $detector(string|array $texts, array $candidateLabels, array $options = []); ``` ### Parameters #### Positional Arguments - **texts** (string|array) - Required - The image(s) to analyze. Can be a local file path, a file resource, a URL to a remote image, or an array of these inputs. - **candidateLabels** (array) - Required - An array of candidate labels to consider when detecting objects in the image. #### Options - **threshold** (float) - Optional - The minimum confidence score required for an object to be considered a valid detection. Defaults to `0.1`. - **percentage** (bool) - Optional - Whether to return bounding box coordinates as percentages of image dimensions (0 to 1). Defaults to `false` (absolute pixel values). - **topK** (int) - Optional - The number of top objects to return. By default, returns all detected objects passing the threshold. ### Request Example ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $detector = pipeline('zero-shot-object-detection'); $result = $detector('path/to/image.jpg', ['person', 'car', 'traffic light']); ``` ### Response Example ```php [ [ "score" => 0.99796805983403, "label" => "car", "box" => [ "xmin" => 29, "ymin" => 65, "xmax" => 188, "ymax" => 122 ] ] // Additional detected objects... ] ``` ``` -------------------------------- ### Create a Text Generation Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/pipelines.md Initializes a text generation pipeline using a specific model. Ensure the model is compatible with the 'text-generation' task. ```php $generator = pipeline('text-generation', 'Xenova/codegen-350M-mono'); ``` -------------------------------- ### Get Multiple Answers with topK Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/question-answering.md Specify the 'topK' argument to retrieve multiple potential answers, sorted by confidence score. ```php $result = $pipeline($question, $context, topK: 2); ``` -------------------------------- ### Run Image-to-Image Translation Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/image-to-image.md Initialize the image-to-image pipeline with a specific model and process an image. Ensure the 'saveTo' path is provided to save the translated image. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $upscaler = pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64'); $result = $upscaler('path/to/image.jpg', saveTo: 'path/to/super-resolved-image.jpg'); ``` -------------------------------- ### Run Automatic Speech Recognition Inference Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/automatic-speech-recognition.md Initialize the ASR pipeline and transcribe an audio file. Ensure the audio file path is correct. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $transcriber = pipeline('automatic-speech-recognition', 'onnx-community/whisper-tiny.en'); $audioUrl = __DIR__ . '/preamble.wav'; $output = $transcriber($audioUrl, maxNewTokens: 256); ``` -------------------------------- ### Image to Tensor Conversion and Back Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/utils/image.md Demonstrates reading an image, converting it to a tensor, performing operations (placeholder), converting it back to an image, and saving the result. Ensure the image path is correct and the tensor operations are defined. ```php use Codewithkyrian\Transformers\Utils\Image; // Read an image $image = Image::read('path/to/image.jpg'); // Convert the image to a tensor $tensor = $image->toTensor(); // Perform tensor operations // ... // Convert the tensor back to an image $newImage = Image::fromTensor($tensor); // Save the new image $newImage->save('path/to/new_image.jpg'); ``` -------------------------------- ### Single Label Classification Output Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/zero-shot-image-classification.md Example output when classifying an image against a specific set of labels, returning the most probable label and its score. ```json ['label' => 'zebra', 'score' => 0.63534494664876] ``` -------------------------------- ### Create and Run a Translation Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/pipelines.md Initializes a translation pipeline with a specific model and runs it with source and target languages specified. Requires a compatible translation model. ```php $translator = pipeline('translation', 'Xenova/m2m100_418M'); $result = $translator('I love TransformersPHP!', srcLang: 'en', tgtLang: 'fr'); ``` -------------------------------- ### Initialize Summarization Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/summarization.md Instantiate the summarization pipeline with a specific model. Provide the task name 'summarization' and the model identifier. The pipeline can then be used to process text. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $summarizer = pipeline('summarization', 'Xenova/distilbart-cnn-6-6'); $article = 'The Amazon rainforest, known as the "lungs of the Earth," is the largest tropical rainforest in the world, ' . 'covering over 5.5 million square kilometers. It is home to millions of species of flora and fauna, many of which are ' . 'still undiscovered. The rainforest plays a crucial role in regulating the planet\'s climate by absorbing large ' . 'amounts of carbon dioxide. However, it is under threat from deforestation due to logging, mining, and farming, ' . 'leading to a loss of biodiversity and contributing to global warming. Conservation efforts are underway to protect ' . 'this vital ecosystem, including initiatives to promote sustainable land use and reduce human impact.'; $summary = $summarizer($article, maxNewTokens: 512, temperature: 0.7); ``` -------------------------------- ### Single Audio File Classification Output Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/audio-classification.md Example output for a single audio file classification, showing the predicted label and its confidence score. ```php ['label' => 'Dog Barking', 'score' => 0.9321] ``` -------------------------------- ### Get Indices of Minimum Value of Tensor Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/utils/tensor.md Retrieves the indices of the minimum values in a tensor. Specify an axis to find indices along that dimension. ```php $data = [[1, 2, 3], [4, 5, 6]]; $tensor = Tensor::fromArray($data); $argmin = $tensor->argMin(); // 0 $argmin = $tensor->argMin(1); // [0, 0] ``` -------------------------------- ### Run Image Captioning Inference Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/image-to-text.md Initialize the image-to-text pipeline and generate a caption for a local image file. Ensure the default model Xenova/vit-gpt2-image-captioning is suitable for captioning. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $captioner = pipeline('image-to-text'); $result = $captioner('path/to/image.jpg'); ``` -------------------------------- ### Get Indices of Maximum Value of Tensor Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/utils/tensor.md Retrieves the indices of the maximum values in a tensor. Specify an axis to find indices along that dimension. ```php $data = [[1, 2, 3], [4, 5, 6]]; $tensor = Tensor::fromArray($data); $argmax = $tensor->argMax(); // 5 $argmax = $tensor->argMax(1); // [2, 2] ``` -------------------------------- ### Tensor Creation and Properties in PHP Source: https://context7.com/codewithkyrian/transformers-php/llms.txt Demonstrates various methods for creating Tensor objects and accessing their fundamental properties like shape, data type, and size. ```php use Codewithkyrian\Transformers\Tensor\Tensor; // --- Creation --- $t1 = new Tensor([1,2,3,4,5,6], Tensor::float32, [2,3]); $t2 = Tensor::fromArray([[1,2,3],[4,5,6]]); $t3 = Tensor::zeros([2,3]); // [[0,0,0],[0,0,0]] $t4 = Tensor::ones([2,3]); // [[1,1,1],[1,1,1]] $t5 = Tensor::fill([2,3], 7); // [[7,7,7],[7,7,7]] $t6 = Tensor::zerosLike($t2); // same shape as $t2, filled with 0 $t7 = Tensor::repeat($t2, 2, axis: 0); // repeat rows twice // --- Properties --- $t2->shape(); // [2, 3] $t2->dtype(); // Tensor::float32 $t2->size(); // 6 $t2->ndim(); // 2 $t2->toArray(); // [[1,2,3],[4,5,6]] $t2->toBufferArray(); // [1,2,3,4,5,6] ``` -------------------------------- ### Control Number of Predictions (topK) Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/fill-mask.md Specify the number of top predictions to retrieve using the `topK` option. Set to -1 to get all predictions. ```php $result = $fillMask('My name is Kyrian and I am a [MASK] developer.', topK: 2); ``` -------------------------------- ### Configure Transformers-PHP Source: https://github.com/codewithkyrian/transformers-php/blob/main/README.md Set up the TransformersPHP library with custom configurations for cache directory, remote host, authentication token, user agent, image driver, and logger. Defaults are used if not specified. ```php use Codewithkyrian\Transformers\Transformers; Transformers::setup() ->setCacheDir('...') // Set the default cache directory for transformers models. Defaults to `.transformers-cache/models` ->setRemoteHost('...') // Set the remote host for downloading models. Defaults to `https://huggingface.co` ->setRemotePathTemplate('...') // Set the remote path template for downloading models. Defaults to `{model}/resolve/{revision}/{file}` ->setAuthToken('...') // Set the auth token for downloading models. Defaults to `null` ->setUserAgent('...') // Set the user agent for downloading models. Defaults to `transformers-php/{version}` ->setImageDriver('...') // Set the image driver for processing images. Defaults to `VIPS` ->setLogger($logger) // Set a PSR-3 compatible logger. Defaults to `NullLogger` if not set ->apply(); // Apply the configuration ``` -------------------------------- ### Slice Tensor with Bounds Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/utils/tensor.md Extracts a sub-tensor using explicit start indices and size for each dimension. Provides precise control over the slice region. ```php $tensor = Tensor::fromArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); $slicedTensor = $tensor->sliceWithBounds([0, 1], [2, 2]); // [[2, 3], // [5, 6]] ``` -------------------------------- ### Pipeline Output with Word-Level Timestamps Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/automatic-speech-recognition.md This output format provides word-level timestamps. Each word in the transcription is associated with its precise start and end time. ```php [ "text" => "...", "chunks" => [ ["text" => "We,", "timestamp" => [0.6, 0.94]], ["text" => "the", "timestamp" => [0.94, 1.3]], ["text" => "people", "timestamp" => [1.3, 1.52]], ["text" => "of", "timestamp" => [1.52, 1.62]], ["text" => "the", "timestamp" => [1.62, 1.82]], ["text" => "United", "timestamp" => [1.82, 2.52]], ["text" => "States", "timestamp" => [2.52, 2.72]], ["text" => "in", "timestamp" => [2.72, 2.88]], ["text" => "order", "timestamp" => [2.88, 3.1]], ... ] ] ``` -------------------------------- ### Token Classification: AggregationStrategy::MAX Example Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/token-classification.md Demonstrates AggregationStrategy::MAX, which groups tokens like FIRST but assigns the maximum score of the tokens in the group. ```php // For "Onitsha" [ // ... ['entity_group' => 'LOC', 'word' => 'Onitsha', 'score' => 0.9980088367015,], ] // For "United States of America" [ // ... ['entity_group' => 'LOC', 'word' => 'United States of America', 'score' => 0.99959621338567,], ] ``` -------------------------------- ### Running Question Natural Language Inference (QNLI) Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/text-classification.md Demonstrates how to perform Question Natural Language Inference for question-answering tasks. ```APIDOC ## Running Question Natural Language Inference (QNLI) Demonstrates how to perform Question Natural Language Inference for question-answering tasks. ### Method Signature ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $qnli = pipeline('text-classification', 'Xenova/qnli-electra-base'); $result = $qnli('Where is the capital of Nigeria?', 'The capital of Nigeria is Abuja.'); ``` ### Output Example ```php [ 'label' => 'entailment', 'score' => 0.9995358059835 ] ``` ``` -------------------------------- ### Token Classification: AggregationStrategy::AVERAGE Example Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/token-classification.md Illustrates AggregationStrategy::AVERAGE, which groups tokens similarly to FIRST but assigns the average score of the tokens in the group. ```php // For "Onitsha" [ // ... ['entity_group' => 'LOC', 'word' => 'Onitsha', 'score' => 0.85583420296134,], ] // For "United States of America" [ // ... ['entity_group' => 'LOC', 'word' => 'United States of America', 'score' => 0.99910416963452,], ] ``` -------------------------------- ### Configure Transformers PHP in Standalone PHP Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/configuration.md Set global configuration options like cache directory, remote host, and authentication token in a standalone PHP project's bootstrap script. Ensure this script runs before library usage. ```php require_once 'vendor/autoload.php'; use Codewithkyrian\Transformers\Transformers; Transformers::setup() ->setCacheDir('/path/to/models') ->setRemoteHost('https://yourmodelshost.com') ->setRemotePathTemplate('custom/path/{model}/{file}') ->setAuthToken('your-token') ->setUserAgent('your-user-agent') ->apply(); ``` -------------------------------- ### Sentiment Analysis Pipeline in PHP Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/introduction.md Shows how to allocate a sentiment-analysis pipeline in PHP using the TransformersPHP library. This mirrors the Python example for local inference. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; // Allocate a pipeline for sentiment-analysis $pipe = pipeline('sentiment-analysis'); $out = $pipe('I love transformers!'); // [{'label': 'POSITIVE', 'score': 0.999808732}] ``` -------------------------------- ### Create a Sentiment Analysis Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/basic-usage.md Instantiate a pipeline for sentiment analysis. The first run downloads and caches the default model. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $classifier = pipeline('sentiment-analysis'); ``` -------------------------------- ### Get Top K Classifications Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/audio-classification.md Specify the `topK` option to retrieve a specified number of top classification results. The default value for `topK` is 1. ```php $output = $classifier('https://example.com/audio.wav', topK: 4); ``` -------------------------------- ### Image To Text Pipeline Input Options Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/image-to-text.md Demonstrates passing a remote image URL as input to the image-to-text pipeline. The pipeline accepts URLs, local paths, or file resources. ```php $result = $captioner('https://example.com/image.jpg'); ``` -------------------------------- ### Translation Pipeline with Specific Model (PHP) Source: https://github.com/codewithkyrian/transformers-php/blob/main/README.md Allocate a translation pipeline using a specific model ID. This example demonstrates how to specify a model for translation tasks. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; // Allocate a pipeline for translation $pipe = pipeline('translation', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english'); ``` -------------------------------- ### Initialize Zero-Shot Image Classification Pipeline Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/zero-shot-image-classification.md Initialize the zero-shot image classification pipeline. This pipeline requires an image and a list of candidate labels to classify the image. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; $classifier = pipeline('zero-shot-image-classification'); $result = $classifier('path/to/image.jpg', ['zebra', 'elephant', 'giraffe']); ``` -------------------------------- ### Enable PHP Extensions and Settings Source: https://context7.com/codewithkyrian/transformers-php/llms.txt Ensure the FFI extension is enabled and set appropriate memory limits in your php.ini file. Enabling JIT compilation can significantly improve performance. ```ini extension = ffi ffi.enable = true ; Optional but recommended for >2x speedup on math-heavy tasks: opcache.jit = tracing ; Increase for large models: memory_limit = 512M ``` -------------------------------- ### Get Top K Elements Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/utils/tensor.md Retrieves the top k largest elements and their indices from a tensor along a specified axis. Useful for finding the most significant values. ```php $data = [[1, 2, 3], [4, 5, 6]]; $tensor = Tensor::fromArray($data); [$values, $indices] = $tensor->topk(2); $values->toArray(); // [[3, 2], [6, 5]] $indices->toArray(); // [[2, 1], [2, 1]] ``` -------------------------------- ### Configuring Text Generation Pipeline Options in PHP Source: https://context7.com/codewithkyrian/transformers-php/llms.txt Shows how to configure a text-generation pipeline with various options for controlling output length, sampling strategy, stopping criteria, and output formatting. ```php use function Codewithkyrian\Transformers\Pipelines\pipeline; use Codewithkyrian\Transformers\Generation\Streamers\TextStreamer; $generator = pipeline('text-generation', 'Xenova/gpt2'); $output = $generator('Once upon a time', // Length control maxNewTokens: 200, // Max tokens to add (ignores prompt length) maxLength: 250, // Hard cap on total sequence length minNewTokens: 10, // Force at least N new tokens // Decoding strategy doSample: true, // true = sampling, false = greedy numBeams: 4, // Beam search width (1 = greedy/sampling) temperature: 0.8, // 0 = deterministic, >1 = creative/random topK: 50, // Keep top-K candidate tokens topP: 0.92, // Nucleus sampling threshold repetitionPenalty: 1.2, // >1 penalizes repeated tokens noRepeatNgramSize: 3, // Forbid repeating any 3-gram // Stopping earlyStopping: true, // Stop when numBeams complete sequences are found maxTime: 10, // Hard wall-clock timeout in seconds // Output control numReturnSequences: 3, // Generate N independent sequences returnFullText: false, // Return only new tokens, not the prompt // Streaming streamer: TextStreamer::make($generator->tokenizer), ); ``` -------------------------------- ### Specify Image Driver for Image Processing Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/configuration.md Select the image processing backend (GD, IMAGICK, VIPS) by setting the ImageDriver enum. Ensure the required extensions are installed. ```php use Codewithkyrian\Transformers\Utils\ImageDriver; Transformers::setup() ->setImageDriver(ImageDriver::GD) ->apply(); ``` -------------------------------- ### Instantiate a Model with AutoModel Source: https://github.com/codewithkyrian/transformers-php/blob/main/docs/models.md Use `AutoModel::fromPretrained` to load any model from the Hugging Face model hub. This method accepts various arguments for customization, including quantization and caching. ```php use Codewithkyrian\Transformers\Models\Auto\AutoModel; $model = AutoModel::fromPretrained('Xenova/bert-base-uncased'); ```