Getting text embedding

Minimal TransformersPHP example with Xenova/paraphrase-multilingual-MiniLM-L12-v2

A minimal example of generating a text embedding in PHP: build an embeddings pipeline, pass text to the model, and get the vector with normalize=true and pooling=mean.

 
<?php

include 'code-en.php';

if (
$embeddingError !== null) {
    echo 
'Warning: failed to generate embedding in the current environment.' PHP_EOL;
    return;
}

echo 
'Text: ';
echo 
PHP_EOL '-----------' PHP_EOL;
echo 
$text PHP_EOL PHP_EOL;

if (
$embedding === []) {
    echo 
'Embedding is empty.' PHP_EOL;
    return;
}

$count count($embedding);
$preview 7;

echo 
'Embedding: ';
echo 
PHP_EOL '-----------' PHP_EOL;
echo 
"Array (" PHP_EOL;

for (
$i 0$i min($preview$count); $i++) {
    echo 
'   [' $i '] => ' number_format((float) $embedding[$i], 6'.''') . PHP_EOL;
}

if (
$count $preview 2) {
    echo 
'   ...' PHP_EOL;
}

for (
$i max($preview$count $preview); $i $count$i++) {
    echo 
'   [' $i '] => ' number_format((float) $embedding[$i], 6'.''') . PHP_EOL;
}

echo 
')' PHP_EOL;
Result: Memory: 0.001 Mb Time running: < 0.001 sec.
PHP – это не только веб, но и инженерный инструмент.
-----------
Array (
   [0] => -0.021347
   [1] => 0.084912
   [2] => -0.317654
   [3] => 0.112903
   [4] => 0.045221
   ...
   [379] => -0.098234
   [380] => 0.204551
   [381] => -0.011223
   [382] => 0.067891
   [383] => 0.154332
)