Before you start
- Start the local studio, sign in and select a project with test credits.
- Use Python 3.11 or later and an English media file up to 192 MiB. The script uses the Python standard library.
1. Set your project credential
Open the developer console in the local studio, create a project API key and copy it when shown. Start Bash, then run the following commands. Paste the key at the prompt. Run the later commands in that shell.
export VELOSYLL_URL=http://127.0.0.1:8464
read -rsp 'Project API key: ' VELOSYLL_API_KEY
printf '\n'
export VELOSYLL_API_KEY2. Save the uploader
The uploader fingerprints the file and stores the upload ID beside it. On restart it asks the server for the committed byte offset, seeks there, then sends chunks up to 4 MiB. Keep the file unchanged and run one uploader per file.
"""Upload one media file. Run again with the same file to resume."""
import hashlib
import json
import os
import sys
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
CHUNK = 4 * 1024 * 1024
BASE = os.getenv("VELOSYLL_URL", "http://127.0.0.1:8464").rstrip("/")
def request(method, path, data=None, **headers):
headers["Authorization"] = "Bearer " + os.environ["VELOSYLL_API_KEY"]
if isinstance(data, dict):
data = json.dumps(data).encode()
headers["Content-Type"] = "application/json"
with urlopen(Request(BASE + path, data, headers, method=method), timeout=60) as response:
return json.load(response)
def upload(source):
size = source.stat().st_size
if not 0 < size <= 192 * 1024 * 1024:
raise ValueError("Choose a nonempty file of up to 192 MiB.")
with source.open("rb") as audio:
fingerprint = hashlib.file_digest(audio, "sha256").hexdigest()
state = source.with_name(source.name + ".velosyll-upload.json")
if state.exists():
saved = json.loads(state.read_text())
if (saved["sha256"], saved["base"]) != (fingerprint, BASE):
raise ValueError("This checkpoint belongs to a different file or server.")
upload_id = saved["id"]
else:
upload_id = request("POST", "/v1/uploads", {"name": source.name})["id"]
with state.open("x") as checkpoint:
json.dump({"sha256": fingerprint, "base": BASE, "id": upload_id}, checkpoint)
path = "/v1/uploads/" + upload_id
try:
offset = request("GET", path)["offset"]
except HTTPError as error:
if error.code != 404:
raise
existing = request("GET", "/v1/transcriptions/" + upload_id)
print("Existing transcription:", existing["id"], existing["status"])
return
if not 0 <= offset <= size:
raise ValueError("Server offset is outside this file.")
audio.seek(offset)
while offset < size:
chunk = audio.read(CHUNK)
if not chunk:
raise ValueError("File changed during upload.")
result = request("PATCH", path, chunk, **{
"Content-Type": "application/octet-stream", "Upload-Offset": str(offset),
})
if result["offset"] != offset + len(chunk):
raise ValueError("Unexpected server offset. Rerun to recover.")
offset = result["offset"]
print("Uploaded", offset, "of", size, flush=True)
job = request("POST", path + "/finish", {"language": "en"})
print("Transcription:", job["id"], job["status"])
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("Usage: python3 resume_upload.py RECORDING")
try:
upload(Path(sys.argv[1]))
except (OSError, KeyError, ValueError, URLError) as error:
sys.exit(str(error))
3. Upload and resume
Download a sample into a new directory. Run the uploader. To try resuming, interrupt a larger upload after the first progress line and run the same command again. Keep the .velosyll-upload.json checkpoint while you need to resume.
curl -fsS "$VELOSYLL_URL/assets/speech-sample.wav" -o speech-sample.wav
python3 resume_upload.py speech-sample.wav4. Retrieve the finished recording
The finish request creates a transcription using the upload ID. If the response was lost after the job was created, running the uploader again retrieves its status. Use the returned ID in the curl guide to poll or export the recording.
Expected result
One transcription ID identifies the finished upload. A repeat run reports the existing transcription and creates no second job.
Troubleshooting
- PATCH returns 409 or the connection drops.
- Rerun with the same file and checkpoint to fetch the current server offset. If you lost the upload-creation response before the checkpoint was saved, recover the ID from your request logs if available. Starting another upload creates a separate ID. Up to ten may be open across all projects in a workspace.
- HTTP 413 or 429.
- For 413 check the 192 MiB file and 4 MiB chunk limits. For 429, check unfinished uploads, retained workspace storage, daily intake and concurrency at GET /v1/limits.