Search by

streams-sro / gaston

streams-sro

PHP client for the Gaston API (transcription, translation and sentence search).

v0.8.0 2026-11-15 17:42 UTC

This package is auto-updated.

Last update: 2026-11-15 17:44:56 UTC


README

A small, dependency-free PHP client for the Gaston API: transcription, translation, AI digests and full-text search of sentences within transcribed recordings.

Requires a Gaston account and an API token (see Configuration).

This is a PHP port of the official Python client and tracks the same API.

Requirements

  • PHP 7.0+
  • The curl and json extensions (both bundled with PHP by default)

No third-party runtime dependencies.

Installation

composer require streams-sro/gaston

Quick start

use StreamsSro\Gaston\GastonClient;

$client = new GastonClient('gapi-...');

// Who am I + remaining quota
$me = $client->me();
echo $me->email, ' files left: ', $me->usage->filesLeft, PHP_EOL;

// Transcribe a local file
$result = $client->transcribe('interview.mp4', 'en', null, 'My interview');
echo $result->id, ' ', $result->state, PHP_EOL;

// Transcribe from a URL (YouTube or web)
$client->transcribeUrl('https://youtu.be/dQw4w9WgXcQ', 'en');

// Translate an existing transcription
$client->translate($result->id, 'de');

// Word-level alignment of a translation against source timestamps
// (requires a completed translation in that language)
$client->alignTranslation($result->id, 'de', true);

// Speaker diarization (requires a completed translation in that language)
$client->diarize($result->id, 'de', 2);

// Fetch a media item with its sentences
$media = $client->getMedia($result->id, 'en');
foreach ($media->sentences as $sentence) {
    echo $sentence->id, ' ', $sentence->getText(), ' ', $sentence->speaker, PHP_EOL;
}

// Export a transcript (text, text_timestamps, csv, srt or audio)
$client->exportMediaToFile($result->id, 'subtitles.srt', 'srt', 'de');

// AI digest (summary) of a URL; see "Digest" below
$digest = $client->waitForDigest($client->createDigest('https://youtu.be/dQw4w9WgXcQ')->digestId);

// Full text search across the whole library
$results = $client->search('climate change', 0, 20);
echo 'total matches: ', $results->total, PHP_EOL;
foreach ($results as $hit) {
    echo $hit['_sentence']['body'], ' -> ', implode(' ', $hit['_highlight']['body']), PHP_EOL;
}

The constructor signature is:

new GastonClient(
    string $token = null,          // falls back to GASTON_API_TOKEN
    float  $timeout = 30.0,         // ordinary requests, seconds (0 = no limit)
    float  $uploadTimeout = 600.0,  // file uploads and audio exports, seconds
    float  $connectTimeout = 10.0,  // connection timeout, seconds
    HttpClientInterface $httpClient = null
);

Configuration

Generate an API token in the Gaston app under Settings -> API. Full endpoint documentation is available at https://www.gaston.live/en/api.

The token can be supplied directly or via the GASTON_API_TOKEN environment variable:

Argument Environment variable Default
$token GASTON_API_TOKEN (required)
// Uses GASTON_API_TOKEN from the environment
$client = new GastonClient();

Timeouts

Ordinary requests use a 30s timeout. The file upload in transcribe() and audio exports can take minutes for large files, so they use a separate, more generous $uploadTimeout (default 600s). All timeouts are in seconds; pass 0 to wait indefinitely.

// Customise the defaults for all calls
$client = new GastonClient('gapi-...', 30.0, 1800.0); // up to 30 min uploads

// Or override per call (e.g. no timeout for a very large file)
$client->transcribe('huge-recording.mp4', null, null, null, 0.0);

transcribe() accepts either a file path or an open stream resource:

$fh = fopen('interview.mp4', 'rb');
$client->transcribe($fh, 'en');

Exporting

exportMedia() returns the file in memory as a MediaExport (->content, ->filename, ->contentType, plus ->save($path)), while exportMediaToFile() streams it straight to disk. Use exportMediaToFile() for audio.

// Transcript as plain text (format: text, text_timestamps, csv, srt, audio)
$export = $client->exportMedia('me...', 'text', 'en');
echo $export->filename, PHP_EOL; // filename suggested by the server, e.g. "My interview.txt"
echo $export->content;

// Subtitles split into blocks of at most 8 words, prefixed with speaker names
// (speaker names require diarization)
$client->exportMediaToFile('me...', 'interview.srt', 'srt', null, 8, true);

// Audio (a finished dubbed track for $lang if one exists, otherwise the
// original). Passing an existing directory saves it under the server-suggested
// filename.
$path = $client->exportMediaToFile('me...', '.', 'audio', 'de');

The full signatures are:

$client->exportMedia($mediaId, $format, $lang = null, $maxWordsPerBlock = 0, $includeSpeakers = false, $timeout = -1.0);
$client->exportMediaToFile($mediaId, $path, $format, $lang = null, $maxWordsPerBlock = 0, $includeSpeakers = false, $timeout = -1.0);

$lang defaults to the media's original language. $maxWordsPerBlock and $includeSpeakers only apply to srt. Exporting audio, or any media longer than 30 minutes, requires a paid plan; otherwise an AuthenticationException (HTTP 403) is thrown. Audio exports use the client's $uploadTimeout by default. exportMediaToFile() downloads to a temporary file next to the target first, so a failed export never leaves a partial file behind. The supported formats are listed in Languages::EXPORT_FORMATS.

Digest

A digest is an AI-generated summary of a recording, optionally with the answer to a question about it. createDigest() adds the media behind a URL (like transcribeUrl()) and requests the digest; it is generated once the media is transcribed, so poll getDigest() or let waitForDigest() do it.

$digest = $client->createDigest(
    'https://youtu.be/dQw4w9WgXcQ',
    null,                       // source language hint (auto-detected if null)
    null,                       // directory id
    'detailed',                 // "brief" (default) or "detailed"
    'What does the singer promise?',
    'de'                        // language of the summary and answer
);
echo $digest->digestId, ' ', $digest->digestState, PHP_EOL; // e.g. "dg... pending"

// Polls every 10s for up to 15 minutes; throws a GastonException on timeout
$digest = $client->waitForDigest($digest->digestId);

if ($digest->isFailed()) {
    echo 'Digest failed: ', $digest->error, PHP_EOL;
} else {
    echo $digest->summary->text, PHP_EOL;
    foreach ($digest->summary->citations as $citation) {
        // marker as used in the text, e.g. "[S12-S15]", with its position in seconds
        echo $citation->marker, ' ', $citation->start, '-', $citation->end, PHP_EOL;
    }
    if ($digest->answer !== null) {
        echo $digest->answer->text !== null ? $digest->answer->text : 'No answer: ' . $digest->answer->error, PHP_EOL;
    }
}

The full signatures are:

$client->createDigest($url, $lang = null, $dirId = null, $detail = 'brief', $question = null, $answerLang = null);
$client->getDigest($digestId);
$client->waitForDigest($digestId, $timeout = 900.0, $interval = 10.0);

Digest::$digestState is one of pending, generating, ready or error (Languages::DIGEST_STATE_*), with the helpers isReady(), isFailed() and isFinished(). Digest::$id and Digest::$state describe the underlying media, and $transcriptionProgress is reported while it is still being transcribed. Things to know:

  • createDigest() returns only the ids and states; $summary, $answer, $language and the rest are filled in by getDigest().
  • A failed digest is returned, not thrown: isFailed() is true and $error says why. Exceptions are reserved for failed requests (an unknown digest id throws NotFoundException; an account with AI features disabled throws AuthenticationException).
  • If the summary succeeded but the question could not be answered, the digest is still ready: $answer->text is null and $answer->error is set.
  • Requesting the same digest of the same media again returns the existing one.
  • $answerLang is validated by the server, whose list differs from Languages::SUPPORTED; an unsupported code throws a BadRequestException with the accepted codes in ->getDetails(). Questions are limited to 2000 characters.
  • Transcribing a long recording takes minutes, so keep the waitForDigest() timeout generous (pass 0 to wait indefinitely).

Directories

$folder = $client->createDirectory('Podcasts');
$client->updateDirectory($folder->id, 'Podcast archive');
$moved = $client->moveMedia('me...', $folder->id); // returns the updated Media
$tree = $client->directoryTree();
$client->deleteDirectory($folder->id);

Search

$client->search($query, $from = 0, $max = 50, $dirIds = null, $lang = null, $mediaId = null) runs a full-text search over every sentence in your transcribed media.

Query syntax

The query supports a subset of the Lucene query_string syntax:

Feature Example Notes
Boolean AND cats AND dogs both terms must appear
Boolean OR cats OR dogs either term
Boolean NOT cats NOT dogs exclude a term
Grouping (cats OR dogs) AND vet combine operators with parentheses
Exact phrase "climate change" quoted terms match as a phrase
Trailing wildcard transcri* matches transcribe, transcription...

Leading wildcards (*tion), field selectors, fuzzy (~), boosts (^) and ranges are not supported and are stripped server-side. Queries must be at least 3 characters.

$results = $client->search('(invoice OR receipt) AND "due date" NOT draft');

Filtering and pagination

// Search within a single directory
$client->search('budget', 0, 50, [42]);

// Search across several directories
$client->search('budget', 0, 50, [42, 43, 7]);

// Restrict to one language, and page through results
$page2 = $client->search('budget', 50, 50, null, 'en');

// Search within a single media
$client->search('budget', 0, 50, null, null, 'me...');

Reading results

search() returns a SearchResults object. Iterate it for hits, or read ->total for the overall match count. Each hit is an array with:

  • _sentence - the matched sentence plus its media metadata (id, title, duration, directory, thumbnail, file, originUrl).
  • _highlight - matched fragments with the hit terms wrapped in <hlt>...</hlt> tags.
$results = $client->search('climate change', 0, 20);
echo 'total matches: ', $results->total, PHP_EOL;
foreach ($results as $hit) {
    $sentence = $hit['_sentence'];
    echo $sentence['media']['title'], ' | ', implode(' ', $hit['_highlight']['body']), PHP_EOL;
}

Error handling

All failures throw a subclass of GastonException:

use StreamsSro\Gaston\Exception\AuthenticationException;
use StreamsSro\Gaston\Exception\NotFoundException;
use StreamsSro\Gaston\Exception\RateLimitException;

try {
    $client->transcribe('clip.mp4');
} catch (RateLimitException $e) {
    echo 'File limit reached';
} catch (AuthenticationException $e) {
    echo 'Bad token / disabled account';
} catch (NotFoundException $e) {
    echo 'Not found: ', $e->getMessage();
}
Exception Trigger
AuthenticationException HTTP 403, invalid token / disabled user
BadRequestException HTTP 400, invalid parameters
NotFoundException HTTP 404, resource not found
RateLimitException HTTP 429, usage limit exceeded
ExternalServiceException HTTP 502, an external dependency failed upstream
GastonApiException any other API error

Every API exception carries ->getStatusCode(), ->getMessage(), ->getDetails() and the raw ->getPayload(). GastonException is the base class for all of the above (including transport-level failures).

Supported languages

use StreamsSro\Gaston\Languages;

Languages::SUPPORTED;                  // transcription source languages
Languages::translationLanguages();     // available translation targets
Languages::isSupported('en');          // bool
Languages::isTranslationTarget('de');  // bool
Languages::EXPORT_FORMATS;             // formats accepted by exportMedia()
Languages::DIGEST_DETAILS;             // detail levels accepted by createDigest()

Development

The test suite uses PHPUnit (a dev-only dependency; the library itself has none):

composer install
composer test

License

MIT - see LICENSE.