PHP code example of tigusigalpa / yandex-speechkit-php

1. Go to this page and download the library: Download tigusigalpa/yandex-speechkit-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tigusigalpa / yandex-speechkit-php example snippets


use Tigusigalpa\YandexCloudClient\YandexCloudClient;
use Tigusigalpa\YandexSpeechKit\YandexSpeechKitClient;
use Tigusigalpa\YandexSpeechKit\Models\RecognitionRequest;
use Tigusigalpa\YandexSpeechKit\Models\AudioFormat;

// Настройка
$cloudClient = new YandexCloudClient('ваш_oauth_токен');
$client = new YandexSpeechKitClient($cloudClient, 'ваш_folder_id');

// Собираем запрос
$request = new RecognitionRequest(
    uri: 'https://storage.yandexcloud.net/my-bucket/audio.wav',
    model: 'general',
    audioFormat: AudioFormat::container('WAV'),
);

// Самый простой способ — recognizeAndWait() сам опрашивает статус и дождётся результата
$result = $client->recognizeAndWait($request);
echo "Транскрипция: " . $result->fullText . "\n";

// Если нужен контроль, можно опрашивать вручную:
$operation = $client->recognizeFileAsync($request);
echo "ID операции: " . $operation->id . "\n";

do {
    sleep(10);
    $operation = $client->getOperation($operation->id);
    echo "Статус: " . ($operation->isDone() ? 'готово' : 'в работе') . "\n";
} while (!$operation->isDone());

$result = $client->getRecognition($operation->id);
echo "Транскрипция: " . $result->fullText . "\n";

use Tigusigalpa\YandexSpeechKit\Laravel\Facades\YandexSpeechKit;
use Tigusigalpa\YandexSpeechKit\Models\RecognitionRequest;
use Tigusigalpa\YandexSpeechKit\Models\AudioFormat;

$request = new RecognitionRequest(
    uri: 'https://storage.yandexcloud.net/my-bucket/audio.wav',
    audioFormat: AudioFormat::container('WAV'),
);

$result = YandexSpeechKit::recognizeAndWait($request);
echo $result->fullText;

use Tigusigalpa\YandexSpeechKit\Models\RecognitionRequest;
use Tigusigalpa\YandexSpeechKit\Models\AudioFormat;
use Tigusigalpa\YandexSpeechKit\Models\TextNormalization;
use Tigusigalpa\YandexSpeechKit\Models\LanguageRestriction;
use Tigusigalpa\YandexSpeechKit\Models\SpeakerLabeling;

// Настраиваем всё: нормализацию, языки, разделение по спикерам
$request = new RecognitionRequest(
    uri: 'https://storage.yandexcloud.net/my-bucket/audio.wav',
    model: 'general',
    audioFormat: AudioFormat::container('WAV'),
    textNormalization: new TextNormalization(
        textNormalization: 'TEXT_NORMALIZATION_ENABLED',
        profanityFilter: true,
        literatureText: false
    ),
    languageRestriction: new LanguageRestriction(
        restrictionType: 'WHITELIST',
        languageCode: ['ru-RU', 'en-US']
    ),
    speakerLabeling: new SpeakerLabeling('SPEAKER_LABELING_ENABLED')
);

// Запускаем распознавание
$operation = $client->recognizeFileAsync($request);
echo "ID операции: " . $operation->id . "\n";

// Ждём...
do {
    sleep(10);
    $operation = $client->getOperation($operation->id);
    echo "Статус: " . ($operation->isDone() ? 'готово' : 'в работе') . "\n";
} while (!$operation->isDone());

// Что-то пошло не так?
if ($operation->hasError()) {
    throw new \RuntimeException($operation->getErrorMessage());
}

// Забираем результат
$result = $client->getRecognition($operation->id);
echo "Транскрипция: " . $result->fullText . "\n";
echo "Слов: " . count($result->words) . "\n";

// Можно пройтись по отдельным словам с таймкодами
foreach ($result->words as $word) {
    echo sprintf(
        "%s [%s - %s]\n",
        $word['text'],
        $word['startTimeMs'],
        $word['endTimeMs']
    );
}

// Не забудьте почистить за собой
$client->deleteRecognition($operation->id);
echo "Результаты удалены.\n";

$audioContent = base64_encode(file_get_contents('/path/to/audio.wav'));

$request = new RecognitionRequest(
    content: $audioContent,
    audioFormat: AudioFormat::container('WAV')
);

$result = $client->recognizeAndWait($request);

use Tigusigalpa\YandexSpeechKit\Models\AudioFormat;

$request = new RecognitionRequest(
    uri: 'https://storage.yandexcloud.net/my-bucket/audio.pcm',
    audioFormat: AudioFormat::raw(
        audioEncoding: 'LINEAR16_PCM',
        sampleRateHertz: 16000,
        audioChannelCount: 1
    )
);

$operation = $client->recognizeFileAsync($request);

$cancelledOperation = $client->cancelOperation($operation->id);
echo "Операция отменена: " . $cancelledOperation->id . "\n";

use Tigusigalpa\YandexSpeechKit\Exceptions\AuthenticationException;
use Tigusigalpa\YandexSpeechKit\Exceptions\RecognitionException;
use Tigusigalpa\YandexSpeechKit\Exceptions\OperationException;

try {
    $result = $client->recognizeAndWait($request);
} catch (AuthenticationException $e) {
    // Плохой токен, истёкшие credentials и т.п.
    echo "Ошибка авторизации: " . $e->getMessage();
} catch (RecognitionException $e) {
    // Что-то не так с аудио или запросом
    echo "Ошибка распознавания: " . $e->getMessage();
    echo "Код ошибки API: " . $e->getApiErrorCode();
} catch (OperationException $e) {
    // Таймаут, отменённая операция и т.д.
    echo "Ошибка операции: " . $e->getMessage();
}
bash
composer 
bash
php artisan vendor:publish --tag=yandex-speechkit-config