Skip to content

Commit 779d527

Browse files
committed
Prepare Transcript Dock PHP client with local fixture checks and release workflow
0 parents  commit 779d527

12 files changed

Lines changed: 442 additions & 0 deletions

File tree

‎.ci/check.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from fixture import Fixture
2+
import os, subprocess, threading
3+
from http.server import ThreadingHTTPServer
4+
Fixture.calls = []
5+
server = ThreadingHTTPServer(('127.0.0.1', 0), Fixture)
6+
thread = threading.Thread(target=server.serve_forever, daemon=True)
7+
thread.start()
8+
try:
9+
env = dict(os.environ, TRANSCRIPTDOCK_TEST_BASE_URL=f'http://127.0.0.1:{server.server_port}')
10+
subprocess.run(['php', '-d', 'error_reporting=32767', 'tests/client_check.php'], env=env, check=True, timeout=120)
11+
assert not any('/credential-leak' in path for _, path in Fixture.calls), 'redirect leaked a request'
12+
assert sum(path == '/v1/rate-limit' for _, path in Fixture.calls) == 1, 'unexpected automatic retry'
13+
print(f'{len(Fixture.calls)} local fixture requests checked')
14+
finally:
15+
server.shutdown()
16+
server.server_close()
17+
thread.join()

‎.ci/fixture.py‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""Run SDK contract checks against local fixtures, never production."""
2+
import argparse
3+
import json
4+
import os
5+
from pathlib import Path
6+
import subprocess
7+
import threading
8+
import time
9+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
10+
from urllib.parse import urlsplit, parse_qs
11+
12+
ROOT = Path(__file__).resolve().parents[2]
13+
KEY = 'td_live_fixture_only'
14+
15+
16+
class Fixture(BaseHTTPRequestHandler):
17+
calls = []
18+
19+
def log_message(self, *args):
20+
pass
21+
22+
def do_GET(self): self.respond()
23+
def do_POST(self): self.respond()
24+
def do_DELETE(self): self.respond()
25+
def do_PATCH(self): self.respond()
26+
27+
def respond(self):
28+
self.calls.append((self.command, self.path))
29+
raw = self.rfile.read(int(self.headers.get('Content-Length', '0')))
30+
path = urlsplit(self.path).path
31+
status = 200
32+
content_type = 'application/json; charset=utf-8'
33+
payload = {'id': 'fixture', 'status': 'succeeded', 'result_id': 'transcript', 'future_field': 42,
34+
'words': [{'start_ms': 123, 'end_ms': 456}],
35+
'request': {'method': self.command, 'path': path, 'query': parse_qs(urlsplit(self.path).query),
36+
'body': json.loads(raw) if raw else None,
37+
'idempotency_key': self.headers.get('Idempotency-Key'),
38+
'authorized': self.headers.get('Authorization') == 'Bearer ' + KEY}}
39+
if path == '/v1/redirect':
40+
self.send_response(302)
41+
self.send_header('Location', '/v1/credential-leak')
42+
self.send_header('Content-Length', '0')
43+
self.end_headers()
44+
return
45+
if path == '/v1/rate-limit':
46+
status = 429
47+
payload = {'error': {'code': 'RATE_LIMITED', 'message': KEY, 'retryable': True, 'retry_after_seconds': 4}, 'request_id': 'fixture-request'}
48+
elif path in ('/v1/budget', '/v1/conflict', '/v1/jobs/not-owned'):
49+
status, code = {'/v1/budget': (402, 'BUDGET_EXCEEDED'), '/v1/conflict': (409, 'IDEMPOTENCY_CONFLICT'), '/v1/jobs/not-owned': (404, 'NOT_FOUND')}[path]
50+
payload = {'error': {'code': code, 'message': 'Fixture rejection', 'retryable': False}}
51+
elif path == '/v1/gateway':
52+
status, payload = 502, b'<html>gateway failed</html>'
53+
elif path == '/v1/error-shape':
54+
status, payload = 500, ['not an error object']
55+
elif path == '/v1/malformed':
56+
payload = b'not-json'
57+
elif path == '/v1/array':
58+
payload = []
59+
elif path == '/v1/slow':
60+
time.sleep(.3)
61+
elif path.endswith('/export'):
62+
content_type = 'text/plain; charset=utf-8'
63+
payload = '1\n00:00:00,000 --> 00:00:01,000\nCafé fixture\n'.encode()
64+
elif path.startswith('/v1/jobs/'):
65+
name = path.rsplit('/', 1)[-1]
66+
payload['status'] = name if name in ('succeeded', 'failed', 'cancelled', 'processing') else 'succeeded'
67+
if self.command == 'POST':
68+
status = 202
69+
data = payload if isinstance(payload, bytes) else json.dumps(payload).encode()
70+
try:
71+
self.send_response(status)
72+
self.send_header('Content-Type', content_type)
73+
self.send_header('Content-Length', str(len(data)))
74+
self.end_headers()
75+
self.wfile.write(data)
76+
except (BrokenPipeError, ConnectionResetError):
77+
pass

‎.github/workflows/release.yml‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
name: Check and release
2+
on:
3+
push:
4+
branches: [main]
5+
pull_request:
6+
workflow_dispatch:
7+
inputs:
8+
publish:
9+
description: Publish the checked package
10+
type: boolean
11+
default: false
12+
permissions:
13+
contents: read
14+
jobs:
15+
check:
16+
runs-on: ubuntu-latest
17+
steps:
18+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
19+
- run: php --version
20+
- run: composer validate --strict
21+
- run: python3 .ci/check.py

‎.gitignore‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
dist/
2+
vendor/
3+
4+
__pycache__/
5+
artifacts/

‎LICENSE‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2026 Transcript Dock
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

‎README.md‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Transcript Dock for PHP
2+
3+
A synchronous API client for PHP 8.1 or newer. Requires the PHP cURL and JSON
4+
extensions, with no third party runtime packages. Version 0.1.0.
5+
6+
Use Composer's path repository feature during local development, or load the
7+
three source files directly:
8+
9+
```php
10+
require 'src/ApiError.php';
11+
require 'src/JobTimeoutError.php';
12+
require 'src/Client.php';
13+
14+
$client = new TranscriptDock\Client(getenv('TRANSCRIPTDOCK_API_KEY'));
15+
// Generate once per intended operation and save with the returned job ID.
16+
$key = bin2hex(random_bytes(16));
17+
$job = $client->createJob([
18+
'source' => ['url' => 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'],
19+
'mode' => 'captions_only', 'max_credits' => 1,
20+
], $key);
21+
$job = $client->waitForJob($job['id'], timeout: 120);
22+
if ($job['status'] === 'succeeded') {
23+
echo $client->exportTranscript($job['result_id'], 'srt');
24+
}
25+
```
26+
27+
Composer autoloading maps `TranscriptDock\\` to `src/`. Install into a local
28+
application through a Composer `path` repository pointing to this directory,
29+
then require `transcriptdock/transcriptdock` with the local version constraint.
30+
31+
Creating a job can spend credits. The example requests captions only with a
32+
one credit ceiling and does not enable AI fallback. Save the key and reuse the
33+
same key and exact body if the submission response is lost. The client does
34+
not retry automatically.
35+
36+
Core methods: `capabilities`, `createJob`, `getJob`, `getTranscript`,
37+
`exportTranscript` and `waitForJob`. Use
38+
`request($method, $path, $body, $query, $idempotencyKey)` for the complete public
39+
API, including batches, discovery, upload slots, usage and webhook endpoints.
40+
Bodies use the [API contract's exact fields](https://www.transcriptdock.com/docs/openapi.yaml).
41+
42+
Responses are associative arrays preserving all API fields and timing units.
43+
Exports are raw JSON, TXT, SRT or VTT strings. Inspect status before using a
44+
terminal job's result. Polling returns failed and cancelled jobs normally;
45+
`JobTimeoutError::$job` retains the last observed response when polling expires.
46+
`ApiError` exposes `errorCode`, `status`, `retryable`, `requestId` and
47+
`retryAfterSeconds`. Error messages redact bearer keys and hide gateway HTML.
48+
49+
The default request timeout is 30 seconds. Custom constructor origins require
50+
HTTPS, except loopback HTTP development. Redirects are blocked. Signed storage
51+
uploads must be sent separately without the API key. Keep webhook secrets
52+
private and implement receiver signature checks from the API documentation.
53+
54+
## Check and build
55+
56+
From the application repository root with Python 3 and PHP installed:
57+
58+
```sh
59+
python3 .ci/check.py
60+
composer validate --strict
61+
composer install
62+
composer archive --format=zip --dir=dist --file=transcriptdock-0.1.0
63+
```
64+
65+
The shared fixture server is local and spends no credits. `composer.lock`
66+
records only platform requirements because there are no third party packages.
67+
Source and release checks: https://github.com/TranscriptDock/transcriptdock-php.

‎composer.json‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"name": "transcriptdock/transcriptdock",
3+
"description": "PHP client for the Transcript Dock video transcription API",
4+
"type": "library",
5+
"license": "MIT",
6+
"homepage": "https://www.transcriptdock.com/docs",
7+
"authors": [{"name": "Transcript Dock", "email": "transcriptdock@volods.com"}],
8+
"require": {"php": ">=8.1", "ext-curl": "*", "ext-json": "*"},
9+
"autoload": {"psr-4": {"TranscriptDock\\": "src/"}},
10+
"archive": {"exclude": ["/tests", "/vendor", "/composer.lock"]}
11+
}

‎composer.lock‎

Lines changed: 22 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/ApiError.php‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
declare(strict_types=1);
3+
namespace TranscriptDock;
4+
5+
final class ApiError extends \RuntimeException
6+
{
7+
public function __construct(
8+
public readonly string $errorCode,
9+
string $message,
10+
public readonly ?int $status = null,
11+
public readonly bool $retryable = false,
12+
public readonly ?string $requestId = null,
13+
public readonly ?int $retryAfterSeconds = null,
14+
) {
15+
parent::__construct($message);
16+
}
17+
}

‎src/Client.php‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
<?php
2+
declare(strict_types=1);
3+
namespace TranscriptDock;
4+
5+
final class Client
6+
{
7+
private string $baseUrl;
8+
9+
public function __construct(
10+
private readonly string $apiKey,
11+
string $baseUrl = 'https://www.transcriptdock.com',
12+
private readonly float $timeout = 30,
13+
) {
14+
if (!preg_match('/\A[!-~]+\z/', $apiKey)) {
15+
throw new \InvalidArgumentException('Provide an API key without whitespace or control characters.');
16+
}
17+
$url = parse_url($baseUrl);
18+
$host = trim($url['host'] ?? '', '[]');
19+
$loopback = $host === 'localhost' || $host === '::1' ||
20+
(filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) && str_starts_with($host, '127.'));
21+
if (!$url || $host === '' || (($url['scheme'] ?? '') !== 'https' && !(($url['scheme'] ?? '') === 'http' && $loopback)) ||
22+
isset($url['user'], $url['pass']) || isset($url['user']) || isset($url['query']) || isset($url['fragment']) ||
23+
!in_array($url['path'] ?? '', ['', '/'], true) || preg_match('/[\x00-\x20\x7f]/', $baseUrl)) {
24+
throw new \InvalidArgumentException('Use an HTTPS origin, or loopback HTTP, without credentials, path, query or fragment.');
25+
}
26+
self::positive($timeout);
27+
$this->baseUrl = rtrim($baseUrl, '/');
28+
}
29+
30+
/** Return all API fields as associative arrays, or raw export text. No redirects or retries. */
31+
public function request(string $method, string $path, ?array $body = null, array $query = [], ?string $idempotencyKey = null, bool $text = false, ?float $timeout = null): array|string
32+
{
33+
$method = strtoupper($method);
34+
if (!in_array($method, ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'], true)) throw new \InvalidArgumentException('Provide a supported HTTP method.');
35+
if (!str_starts_with($path, '/v1/') || preg_match('/[?#\\\\]/', $path) || array_intersect(explode('/', rawurldecode($path)), ['.', '..'])) {
36+
throw new \InvalidArgumentException('Use a /v1/ path and pass query parameters separately.');
37+
}
38+
$needsKey = $method === 'POST' && (in_array($path, ['/v1/jobs', '/v1/batches', '/v1/video-discoveries', '/v1/language-discoveries'], true) || str_ends_with($path, '/retry'));
39+
if (($needsKey || $idempotencyKey !== null) && !preg_match('/\A[ -~]{8,128}\z/', $idempotencyKey ?? '')) {
40+
throw new \InvalidArgumentException('Idempotency keys need 8 to 128 printable ASCII characters.');
41+
}
42+
$seconds = $timeout ?? $this->timeout;
43+
self::positive($seconds);
44+
$headers = ['Authorization: Bearer ' . $this->apiKey, 'Accept: application/json', 'User-Agent: transcriptdock-php/0.1.0'];
45+
if ($idempotencyKey !== null) $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
46+
$url = $this->baseUrl . $path;
47+
$query = array_filter($query, fn($v) => $v !== null);
48+
if ($query) $url .= '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986);
49+
$options = [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
50+
CURLOPT_TIMEOUT_MS => max(1, (int) ceil($seconds * 1000)), CURLOPT_CONNECTTIMEOUT_MS => max(1, (int) ceil($seconds * 1000)),
51+
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2];
52+
if ($body !== null) {
53+
$options[CURLOPT_POSTFIELDS] = json_encode((object) $body, JSON_THROW_ON_ERROR);
54+
$headers[] = 'Content-Type: application/json';
55+
}
56+
$options[CURLOPT_HTTPHEADER] = $headers;
57+
$curl = curl_init($url);
58+
curl_setopt_array($curl, $options);
59+
$raw = curl_exec($curl);
60+
$status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
61+
unset($curl);
62+
if ($raw === false) throw new ApiError('NETWORK_ERROR', 'Could not reach the API. Check the job before retrying a submission.', retryable: true);
63+
if ($status < 200 || $status >= 300) {
64+
$envelope = json_decode($raw, true);
65+
$error = is_array($envelope) && is_array($envelope['error'] ?? null) ? $envelope['error'] : [];
66+
throw new ApiError($this->redact(is_string($error['code'] ?? null) ? $error['code'] : 'HTTP_ERROR'),
67+
$this->redact(is_string($error['message'] ?? null) ? $error['message'] : "Request failed with status $status."), $status,
68+
is_bool($error['retryable'] ?? null) ? $error['retryable'] : ($status === 429 || $status >= 500),
69+
is_string($envelope['request_id'] ?? null) ? $this->redact($envelope['request_id']) : null,
70+
is_int($error['retry_after_seconds'] ?? null) ? $error['retry_after_seconds'] : null);
71+
}
72+
if ($text) return $raw;
73+
try {
74+
$decoded = json_decode($raw, false, 512, JSON_THROW_ON_ERROR);
75+
} catch (\JsonException) {
76+
throw new ApiError('INVALID_RESPONSE', 'The API did not return JSON.');
77+
}
78+
if (!$decoded instanceof \stdClass) throw new ApiError('INVALID_RESPONSE', 'The API did not return a JSON object.');
79+
return json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
80+
}
81+
82+
public function capabilities(): array { return $this->request('GET', '/v1/capabilities'); }
83+
public function createJob(array $body, string $idempotencyKey): array { return $this->request('POST', '/v1/jobs', $body, idempotencyKey: $idempotencyKey); }
84+
public function getJob(string $id): array { return $this->request('GET', '/v1/jobs/' . self::id($id)); }
85+
public function getTranscript(string $id): array { return $this->request('GET', '/v1/transcripts/' . self::id($id)); }
86+
public function exportTranscript(string $id, string $format = 'txt'): string
87+
{
88+
if (!in_array($format, ['json', 'txt', 'srt', 'vtt'], true)) throw new \InvalidArgumentException('Choose json, txt, srt or vtt.');
89+
return $this->request('GET', '/v1/transcripts/' . self::id($id) . '/export', query: ['format' => $format], text: true);
90+
}
91+
public function waitForJob(string $id, float $timeout = 120, float $pollInterval = 3): array
92+
{
93+
self::positive($timeout);
94+
self::positive($pollInterval);
95+
$deadline = hrtime(true) / 1e9 + $timeout;
96+
$last = null;
97+
while (true) {
98+
$remaining = $deadline - hrtime(true) / 1e9;
99+
if ($remaining <= 0) throw new JobTimeoutError($last);
100+
$last = $this->request('GET', '/v1/jobs/' . self::id($id), timeout: min($remaining, $this->timeout));
101+
if (in_array($last['status'] ?? '', ['succeeded', 'failed', 'cancelled'], true)) return $last;
102+
$remaining = $deadline - hrtime(true) / 1e9;
103+
if ($remaining <= 0) throw new JobTimeoutError($last);
104+
usleep((int) (min($remaining, $pollInterval) * 1e6));
105+
}
106+
}
107+
private static function positive(float $value): void
108+
{
109+
if (!is_finite($value) || $value <= 0 || $value > 86400) throw new \InvalidArgumentException('Timeout and poll intervals must be positive and at most one day.');
110+
}
111+
private static function id(string $id): string
112+
{
113+
if ($id === '' || $id === '.' || $id === '..') throw new \InvalidArgumentException('Provide a nonempty ID.');
114+
return rawurlencode($id);
115+
}
116+
private function redact(string $value): string
117+
{
118+
return preg_replace('/td_live_[A-Za-z0-9_-]+|Bearer\s+\S+/i', '[REDACTED]', str_replace($this->apiKey, '[REDACTED]', $value));
119+
}
120+
}

0 commit comments

Comments
 (0)