# Exports

Download a finished transcript as plain text or as SRT or WebVTT subtitles, with speaker names.

> **Needs batch transcription.** Exports read the transcripts of files, so they work once batch is open on your workspace ([Batch transcription](https://platform.vatis.tech/docs/batch)). A live session keeps no transcript to export.

## Download a file

`GET /v1/transcripts/{id}/export`

A completed transcript as a text file or as subtitles, the same files the console downloads.

Send the id of a completed transcript, and the format you want:

```bash
ID=tr_ae35f8db719b4d9c   # the id of your transcript
curl -sS -H "Authorization: Bearer $VATIS_KEY" "https://api.eu.vatis.tech/v1/transcripts/$ID/export?format=txt"
```

```javascript
const transcriptId = "tr_ae35f8db719b4d9c"; // the id of your transcript
const url = `https://api.eu.vatis.tech/v1/transcripts/${transcriptId}/export?format=txt`;
const response = await fetch(url, {
  headers: { Authorization: `Bearer ${process.env.VATIS_KEY}` },
});
const answer = await response.text();
if (!response.ok) {
  console.error(`${response.status}: ${answer}`);
  process.exit(1);
}
console.log(answer);
```

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	transcriptID := "tr_ae35f8db719b4d9c" // the id of your transcript
	url := "https://api.eu.vatis.tech/v1/transcripts/" + transcriptID + "/export?format=txt"

	request, err := http.NewRequest("GET", url, nil)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()

	answer, err := io.ReadAll(response.Body)
	check(err)
	if response.StatusCode >= 400 {
		check(fmt.Errorf("%d: %s", response.StatusCode, answer))
	}
	fmt.Println(string(answer))
}

// check stops the program on an error.
func check(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```python
import os

import httpx

transcript_id = "tr_ae35f8db719b4d9c"  # the id of your transcript
url = f"https://api.eu.vatis.tech/v1/transcripts/{transcript_id}/export"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}
params = {"format": "txt"}

response = httpx.get(url, headers=headers, params=params, timeout=60)
if response.is_error:
    raise SystemExit(f"{response.status_code}: {response.text}")
print(response.text)
```

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Sample {
    public static void main(String[] args) throws Exception {
        String transcriptId = "tr_ae35f8db719b4d9c"; // the id of your transcript
        String url = "https://api.eu.vatis.tech/v1/transcripts/" + transcriptId
            + "/export?format=txt";

        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.statusCode() + ": " + response.body());
            System.exit(1);
        }
        System.out.println(response.body());
    }
}
```

```csharp
using System.Net.Http.Headers;

var transcriptId = "tr_ae35f8db719b4d9c"; // the id of your transcript
var url = $"https://api.eu.vatis.tech/v1/transcripts/{transcriptId}/export?format=txt";

using var http = new HttpClient();
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);

using var response = await http.GetAsync(url);
var answer = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine($"{(int)response.StatusCode}: {answer}");
    return 1;
}
Console.WriteLine(answer);
return 0;
```

**Expected result:** one paragraph for each turn, with its time and its speaker (trimmed). The files name the speakers for people: `speaker_0` of the JSON is `Speaker 1`, `speaker_1` is `Speaker 2`, and `channel_0` is `Channel 1`.

```
[00:00] Speaker 1: Bună ziua, luați loc.

[00:02] Speaker 2: Am venit pentru contractul din 12 martie.
```

To save the file, give it a name of your own, or keep the one the API gives in the `Content-Disposition` header, `<id>.<format>` (in cURL, `-o` and `-OJ`):

```bash
curl -sS -H "Authorization: Bearer $VATIS_KEY" -o speech.srt "https://api.eu.vatis.tech/v1/transcripts/$ID/export?format=srt"
curl -sS -H "Authorization: Bearer $VATIS_KEY" -OJ "https://api.eu.vatis.tech/v1/transcripts/$ID/export?format=txt&timestamps=false"
```

```javascript
import { writeFile } from "node:fs/promises";

const transcriptId = "tr_ae35f8db719b4d9c"; // the id of your transcript
const url = `https://api.eu.vatis.tech/v1/transcripts/${transcriptId}/export`;
const headers = { Authorization: `Bearer ${process.env.VATIS_KEY}` };

// The export's answer, or the error and exit
async function download(query) {
  const response = await fetch(`${url}?${query}`, { headers });
  if (!response.ok) {
    console.error(`${response.status}: ${await response.text()}`);
    process.exit(1);
  }
  return response;
}

// A name of your own
const srt = await download("format=srt");
await writeFile("speech.srt", await srt.text());

// The name the API gives, from the Content-Disposition header
const txt = await download("format=txt&timestamps=false");
const [, name] = /filename="([^"]+)"/.exec(txt.headers.get("content-disposition"));
await writeFile(name, await txt.text());
```

```go
package main

import (
	"fmt"
	"io"
	"mime"
	"net/http"
	"os"
)

const transcriptID = "tr_ae35f8db719b4d9c" // the id of your transcript

// download reads an export: its content and its Content-Disposition header,
// or the error and exit.
func download(query string) ([]byte, string) {
	url := "https://api.eu.vatis.tech/v1/transcripts/" + transcriptID + "/export?" + query
	request, err := http.NewRequest("GET", url, nil)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()

	answer, err := io.ReadAll(response.Body)
	check(err)
	if response.StatusCode >= 400 {
		check(fmt.Errorf("%d: %s", response.StatusCode, answer))
	}
	return answer, response.Header.Get("Content-Disposition")
}

func main() {
	// A name of your own
	srt, _ := download("format=srt")
	check(os.WriteFile("speech.srt", srt, 0o644))

	// The name the API gives, from the Content-Disposition header
	txt, disposition := download("format=txt&timestamps=false")
	_, params, err := mime.ParseMediaType(disposition)
	check(err)
	check(os.WriteFile(params["filename"], txt, 0o644))
}

// check stops the program on an error.
func check(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```python
import os
import re

import httpx

transcript_id = "tr_ae35f8db719b4d9c"  # the id of your transcript
url = f"https://api.eu.vatis.tech/v1/transcripts/{transcript_id}/export"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}

def download(params):
    """The export's answer, or the error and exit."""
    response = httpx.get(url, headers=headers, params=params, timeout=60)
    if response.is_error:
        raise SystemExit(f"{response.status_code}: {response.text}")
    return response

# A name of your own
with open("speech.srt", "wb") as f:
    f.write(download({"format": "srt"}).content)

# The name the API gives, from the Content-Disposition header
txt = download({"format": "txt", "timestamps": "false"})
name = re.search(r'filename="([^"]+)"', txt.headers["content-disposition"]).group(1)
with open(name, "wb") as f:
    f.write(txt.content)
```

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.nio.charset.StandardCharsets.UTF_8;

public class Sample {
    static final String transcriptId = "tr_ae35f8db719b4d9c"; // the id of your transcript

    // The export's answer, or the error and exit.
    static HttpResponse<byte[]> download(String query) throws Exception {
        String url = "https://api.eu.vatis.tech/v1/transcripts/" + transcriptId
            + "/export?" + query;
        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .build();
        HttpResponse<byte[]> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofByteArray());
        if (response.statusCode() >= 400) {
            String answer = new String(response.body(), UTF_8);
            System.err.println(response.statusCode() + ": " + answer);
            System.exit(1);
        }
        return response;
    }

    public static void main(String[] args) throws Exception {
        // A name of your own
        Files.write(Path.of("speech.srt"), download("format=srt").body());

        // The name the API gives, from the Content-Disposition header
        HttpResponse<byte[]> txt = download("format=txt&timestamps=false");
        String disposition = txt.headers().firstValue("Content-Disposition").orElseThrow();
        String name = disposition.replaceFirst(".*filename=\"([^\"]+)\".*", "$1");
        Files.write(Path.of(name), txt.body());
    }
}
```

```csharp
using System.Net.Http.Headers;

var transcriptId = "tr_ae35f8db719b4d9c"; // the id of your transcript
var url = $"https://api.eu.vatis.tech/v1/transcripts/{transcriptId}/export";

using var http = new HttpClient();
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);

// A name of your own
using var srt = await Download("format=srt");
await File.WriteAllBytesAsync("speech.srt", await srt.Content.ReadAsByteArrayAsync());

// The name the API gives, from the Content-Disposition header (quoted)
using var txt = await Download("format=txt&timestamps=false");
var name = txt.Content.Headers.ContentDisposition!.FileName!.Trim('"');
await File.WriteAllBytesAsync(name, await txt.Content.ReadAsByteArrayAsync());

// The export's answer, or the error and exit
async Task<HttpResponseMessage> Download(string query)
{
    var response = await http.GetAsync($"{url}?{query}");
    if (!response.IsSuccessStatusCode)
    {
        var answer = await response.Content.ReadAsStringAsync();
        Console.Error.WriteLine($"{(int)response.StatusCode}: {answer}");
        Environment.Exit(1);
    }
    return response;
}
```

In your own code, as a function that takes the options:

```bash
# WebVTT subtitles with one line of at most 5 words per caption, saved as speech.vtt
curl -sS -H "Authorization: Bearer $VATIS_KEY" -o speech.vtt \
  "https://api.eu.vatis.tech/v1/transcripts/$ID/export?format=vtt&lines=1&words_per_line=5"
```

```javascript
import { writeFile } from "node:fs/promises";

const headers = { Authorization: `Bearer ${process.env.VATIS_KEY}` };

// Saves a transcript as a file: format txt, srt or vtt; options such as { lines: 1 } or { speakers: false }
async function exportFile(id, format, path, options = {}) {
  const query = new URLSearchParams({ format, ...options });
  const response = await fetch(`https://api.eu.vatis.tech/v1/transcripts/${id}/export?${query}`, { headers });
  if (!response.ok) { // param names the option at fault, when one is
    const { error } = await response.json();
    throw new Error(`${response.status} ${error.code}: ${error.message}`);
  }
  await writeFile(path, await response.text());
}

await exportFile("tr_ae35f8db719b4d9c", "txt", "speech.txt");
await exportFile("tr_ae35f8db719b4d9c", "vtt", "speech.vtt", { lines: 1, words_per_line: 5 });
```

```go
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
)

// exportFile saves a transcript as a file: format txt, srt or vtt; options such as
// url.Values{"lines": {"1"}} or url.Values{"speakers": {"false"}}
func exportFile(id, format, path string, options url.Values) {
	query := url.Values{"format": {format}}
	for name, values := range options {
		query[name] = values
	}
	address := "https://api.eu.vatis.tech/v1/transcripts/" + id + "/export?" + query.Encode()
	request, err := http.NewRequest("GET", address, nil)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()

	content, err := io.ReadAll(response.Body)
	check(err)
	if response.StatusCode >= 400 { // param names the option at fault, when one is
		var answer struct{ Error struct{ Code, Message string } }
		check(json.Unmarshal(content, &answer))
		e := answer.Error
		check(fmt.Errorf("%d %s: %s", response.StatusCode, e.Code, e.Message))
	}
	check(os.WriteFile(path, content, 0o644))
}

func main() {
	exportFile("tr_ae35f8db719b4d9c", "txt", "speech.txt", nil)
	exportFile("tr_ae35f8db719b4d9c", "vtt", "speech.vtt",
		url.Values{"lines": {"1"}, "words_per_line": {"5"}})
}

// check stops the program on an error.
func check(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```python
import os
import sys

import httpx

headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}

def export(transcript_id, fmt, path, **options):
    """Saves a transcript as a file: fmt txt, srt or vtt; options such as lines=1 or speakers="false"."""
    response = httpx.get(f"https://api.eu.vatis.tech/v1/transcripts/{transcript_id}/export",
                         params={"format": fmt, **options}, headers=headers, timeout=60)
    if response.is_error:  # param names the option at fault, when one is
        error = response.json()["error"]
        sys.exit(f"{response.status_code} {error['code']}: {error['message']}")
    with open(path, "wb") as f:
        f.write(response.content)

export("tr_ae35f8db719b4d9c", "txt", "speech.txt")
export("tr_ae35f8db719b4d9c", "vtt", "speech.vtt", lines=1, words_per_line=5)
```

```java
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.nio.charset.StandardCharsets.UTF_8;

public class Export {
    static final HttpClient client = HttpClient.newHttpClient();

    // Saves a transcript as a file: format txt, srt or vtt; options such as
    // Map.of("lines", "1") or Map.of("speakers", "false")
    static void exportFile(String id, String format, String path,
            Map<String, String> options) throws Exception {
        String query = "format=" + format;
        for (Map.Entry<String, String> option : options.entrySet()) {
            String value = URLEncoder.encode(option.getValue(), UTF_8);
            query += "&" + option.getKey() + "=" + value;
        }
        String url = "https://api.eu.vatis.tech/v1/transcripts/" + id + "/export?" + query;
        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .build();
        HttpResponse<byte[]> response =
            client.send(request, HttpResponse.BodyHandlers.ofByteArray());
        if (response.statusCode() >= 400) { // param names the option at fault, when one is
            String error = new String(response.body(), UTF_8);
            throw new RuntimeException(response.statusCode() + " " + field(error, "code")
                + ": " + field(error, "message"));
        }
        Files.write(Path.of(path), response.body());
    }

    public static void main(String[] args) throws Exception {
        exportFile("tr_ae35f8db719b4d9c", "txt", "speech.txt", Map.of());
        exportFile("tr_ae35f8db719b4d9c", "vtt", "speech.vtt",
            Map.of("lines", "1", "words_per_line", "5"));
    }

    // Reads a text field of the JSON: Java has no JSON parser built in,
    // a real program would use a library.
    static String field(String json, String name) {
        String value = "\"" + name + "\":\\s*\"((?:[^\"\\\\]++|\\\\.)*+)\"";
        Matcher match = Pattern.compile(value).matcher(json);
        if (!match.find()) {
            return null;
        }
        Pattern escaped = Pattern.compile("\\\\(u....|.)");
        return escaped.matcher(match.group(1)).replaceAll((escape) -> {
            String code = escape.group(1);
            if (code.equals("n")) {
                return "\n";
            }
            if (code.length() > 1) {
                int number = Integer.parseInt(code.substring(1), 16);
                code = String.valueOf((char) number);
            }
            return Matcher.quoteReplacement(code);
        });
    }
}
```

```csharp
using System.Net.Http.Headers;
using System.Text.Json;

using var http = new HttpClient();
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);

await ExportFile("tr_ae35f8db719b4d9c", "txt", "speech.txt", new());
await ExportFile("tr_ae35f8db719b4d9c", "vtt", "speech.vtt",
    new() { ["lines"] = "1", ["words_per_line"] = "5" });

// Saves a transcript as a file: format txt, srt or vtt; options such as
// new() { ["lines"] = "1" } or new() { ["speakers"] = "false" }
async Task ExportFile(string id, string format, string path,
    Dictionary<string, string> options)
{
    var query = $"format={format}";
    foreach (var (name, value) in options)
    {
        query += $"&{name}={Uri.EscapeDataString(value)}";
    }
    var url = $"https://api.eu.vatis.tech/v1/transcripts/{id}/export?{query}";
    using var response = await http.GetAsync(url);
    if (!response.IsSuccessStatusCode)
    {
        // param names the option at fault, when one is
        var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
        var error = body.RootElement.GetProperty("error");
        var code = error.GetProperty("code");
        var message = error.GetProperty("message");
        throw new HttpRequestException($"{(int)response.StatusCode} {code}: {message}");
    }
    await File.WriteAllBytesAsync(path, await response.Content.ReadAsByteArrayAsync());
}
```

## Options

| Parameter | Formats | Values | Default | What it does |
|---|---|---|---|---|
| `format` |  | `txt`, `srt`, `vtt` | required | Plain text, SRT subtitles, or WebVTT subtitles. |
| `timestamps` | `txt` | `true`, `false` | `true` | Each paragraph starts with its time, `[01:05]`, or `[1:02:03]` past the first hour. |
| `speakers` | all | `true`, `false` | `true` | Name the speaker: `Speaker 1` for `speaker_0`, `Channel 1` for `channel_0`. A transcript without speakers has none to name. |
| `lines` | `srt`, `vtt` | 1 to 3 | `2` | Lines per caption. |
| `words_per_line` | `srt`, `vtt` | 3 to 12 | `7` | Words per line. |

| Format | Content-Type |
|---|---|
| `txt` | `text/plain; charset=utf-8` |
| `srt` | `application/x-subrip; charset=utf-8` |
| `vtt` | `text/vtt; charset=utf-8` |

- The answer is the file, in UTF-8, with `Content-Disposition: attachment; filename="<id>.<format>"`.
- Booleans are `true` or `false` (also `1` or `0`). An empty value counts as not sent.

## What the files look like

For the example of [The transcript object](https://platform.vatis.tech/docs/transcript-object), `format=txt`:

```
[00:00] Speaker 1: Bună ziua, luați loc.

[00:02] Speaker 2: Am venit pentru contractul din 12 martie.
```

`format=srt`:

```
1
00:00:00,120 --> 00:00:01,700
Speaker 1: Bună ziua, luați loc.

2
00:00:02,480 --> 00:00:05,100
Speaker 2: Am venit pentru contractul din 12 martie.
```

`format=vtt`:

```
WEBVTT

1
00:00:00.120 --> 00:00:01.700
<v Speaker 1>Bună ziua, luați loc.

2
00:00:02.480 --> 00:00:05.100
<v Speaker 2>Am venit pentru contractul din 12 martie.
```

## How the files are made

- **Text:** a paragraph for each turn (the consecutive segments of one speaker; without speakers, each segment), a blank line between paragraphs, and a newline at the end.
- **Captions** follow the segments and their word times. A caption never spans a change of speaker or a pause longer than 1 s, and ends after a sentence where it can. A sentence too long for one caption is split into even parts, after a comma where possible; short sentences are joined while the caption is less than half full.
- Without punctuation (`punctuation=false`), phrases are cut at pauses longer than 1 s only, and a phrase too long for one caption is split where the speaker pauses for 0.3 s or more.
- A caption stays on screen at most about 0.42 s for each word it can hold, from 3 to 7 s (6 s at 2 lines of 7 words), and at least 0.3 s. Its lines are balanced. When two people talk at once, their captions overlap in time, as both formats allow, numbered by their start.
- **Speaker names:** SRT starts a caption with `Speaker 1: ` where the speaker changes (the first caption too). WebVTT gives every caption a voice tag, `<v Speaker 1>`, which players can show or style, and escapes `&`, `<` and `>` in the text.
- Times come from the words: `00:00:01,250` in SRT, `00:00:01.250` in WebVTT.
- An empty transcript gives an empty file (`WEBVTT` alone for `vtt`).

## Files with the transcript itself

An export reads a transcript the API keeps. With `store=false` nothing is kept, so ask for the files with the request instead: `exports` lists the formats, and the finished transcript carries them, made with the default options. `store=false` needs a webhook, whose delivery's `data` is then the only copy ([Webhooks](https://platform.vatis.tech/docs/batch/webhooks)).

```bash
WEBHOOK_ID=wh_a97581d905c54b46   # the "id" of your webhook
curl -sS -H "Authorization: Bearer $VATIS_KEY" https://api.eu.vatis.tech/v1/speech-to-text \
  -F model_id=vatis_ro_v9 -F diarize=true -F webhook_id=$WEBHOOK_ID -F store=false -F exports=txt,srt \
  -F file=@speech.wav
```

```javascript
import { openAsBlob } from "node:fs";

const form = new FormData();
form.append("model_id", "vatis_ro_v9");
form.append("diarize", "true");
form.append("webhook_id", "wh_a97581d905c54b46"); // your webhook's id
form.append("store", "false");
form.append("exports", "txt,srt");
form.append("file", await openAsBlob("speech.wav"), "speech.wav");

const response = await fetch("https://api.eu.vatis.tech/v1/speech-to-text", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.VATIS_KEY}` },
  body: form,
});
const answer = await response.text();
if (!response.ok) {
  console.error(`${response.status}: ${answer}`);
  process.exit(1);
}
console.log(answer);
```

```go
package main

import (
	"bytes"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	url := "https://api.eu.vatis.tech/v1/speech-to-text"

	var body bytes.Buffer
	form := multipart.NewWriter(&body)
	check(form.WriteField("model_id", "vatis_ro_v9"))
	check(form.WriteField("diarize", "true"))
	check(form.WriteField("webhook_id", "wh_a97581d905c54b46")) // your webhook's id
	check(form.WriteField("store", "false"))
	check(form.WriteField("exports", "txt,srt"))
	audio, err := os.Open("speech.wav")
	check(err)
	defer audio.Close()
	part, err := form.CreateFormFile("file", "speech.wav")
	check(err)
	_, err = io.Copy(part, audio)
	check(err)
	check(form.Close())

	request, err := http.NewRequest("POST", url, &body)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))
	request.Header.Set("Content-Type", form.FormDataContentType())

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()

	answer, err := io.ReadAll(response.Body)
	check(err)
	if response.StatusCode >= 400 {
		check(fmt.Errorf("%d: %s", response.StatusCode, answer))
	}
	fmt.Println(string(answer))
}

// check stops the program on an error.
func check(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```python
import os

import httpx

url = "https://api.eu.vatis.tech/v1/speech-to-text"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}
data = {
    "model_id": "vatis_ro_v9",
    "diarize": "true",
    "webhook_id": "wh_a97581d905c54b46",  # your webhook's id
    "store": "false",
    "exports": "txt,srt",
}

with open("speech.wav", "rb") as audio:
    files = {"file": audio}
    response = httpx.post(url, headers=headers, data=data, files=files, timeout=600)
if response.is_error:
    raise SystemExit(f"{response.status_code}: {response.text}")
print(response.text)
```

```java
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.nio.charset.StandardCharsets.UTF_8;

public class Sample {
    static final String boundary = "vatis" + System.nanoTime();

    public static void main(String[] args) throws Exception {
        String url = "https://api.eu.vatis.tech/v1/speech-to-text";

        ByteArrayOutputStream form = new ByteArrayOutputStream();
        addPart(form, "name=\"model_id\"", "vatis_ro_v9".getBytes(UTF_8));
        addPart(form, "name=\"diarize\"", "true".getBytes(UTF_8));
        // your webhook's id
        addPart(form, "name=\"webhook_id\"", "wh_a97581d905c54b46".getBytes(UTF_8));
        addPart(form, "name=\"store\"", "false".getBytes(UTF_8));
        addPart(form, "name=\"exports\"", "txt,srt".getBytes(UTF_8));
        addPart(form, "name=\"file\"; filename=\"speech.wav\"",
            Files.readAllBytes(Path.of("speech.wav")));
        form.write(("--" + boundary + "--\r\n").getBytes(UTF_8));

        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .header("Content-Type", "multipart/form-data; boundary=" + boundary)
            .POST(HttpRequest.BodyPublishers.ofByteArray(form.toByteArray()))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.statusCode() + ": " + response.body());
            System.exit(1);
        }
        System.out.println(response.body());
    }

    // Adds one part to the form: Java has no multipart body built in.
    static void addPart(ByteArrayOutputStream form, String disposition,
            byte[] value) throws Exception {
        String head = "--" + boundary + "\r\n"
            + "Content-Disposition: form-data; " + disposition + "\r\n\r\n";
        form.write(head.getBytes(UTF_8));
        form.write(value);
        form.write("\r\n".getBytes(UTF_8));
    }
}
```

```csharp
using System.Net.Http.Headers;

var url = "https://api.eu.vatis.tech/v1/speech-to-text";

using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(10) };
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);

using var form = new MultipartFormDataContent();
form.Add(new StringContent("vatis_ro_v9"), "model_id");
form.Add(new StringContent("true"), "diarize");
form.Add(new StringContent("wh_a97581d905c54b46"), "webhook_id"); // your webhook's id
form.Add(new StringContent("false"), "store");
form.Add(new StringContent("txt,srt"), "exports");
using var audio = File.OpenRead("speech.wav");
form.Add(new StreamContent(audio), "file", "speech.wav");

using var response = await http.PostAsync(url, form);
var answer = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine($"{(int)response.StatusCode}: {answer}");
    return 1;
}
Console.WriteLine(answer);
return 0;
```

**Expected result:** the answer comes at once, with the transcript queued. When it is done, the delivery's `data` (trimmed) is the transcript, with the files in `exports`:

```json
{"id": "tr_118a9bbfc46f4df7", "status": "completed", "text": "...", "words": [...], "segments": [...],
 "speakers": ["speaker_0", "speaker_1"],
 "exports": {"txt": "[00:00] Speaker 1: Bună ziua, luați loc.\n\n[00:02] Speaker 2: ...",
             "srt": "1\n00:00:00,120 --> 00:00:01,700\nSpeaker 1: Bună ziua, luați loc.\n\n2\n..."}}
```

- A transcript the API keeps carries `exports` too when you asked for them: in the webhook delivery and `GET /v1/transcripts/{id}`, but not in the list.
- `srt` or `vtt` with `timestamps=none` is refused: subtitles need word times (`400` `invalid_parameter`, `param` `exports`).

## Errors

| Status and code | When | What to do |
|---|---|---|
| `400` `invalid_parameter` | A parameter unknown, sent twice, out of range, or not one the format takes (`lines` with `txt`, `timestamps` with `srt`); or subtitles of a transcript made with `timestamps=none` (`param` `format`). | Fix the parameter `param` names. |
| `400` `missing_parameter` | No `format`. | Add it. |
| `404` `not_found` | An unknown or deleted transcript, one past its 7 days, one sent with `store=false`, or another key's to a Member key. | Check the id. With `store=false`, ask for `exports` in the request. |
| `409` `not_completed` | The transcript is still `queued` or `processing`, or it `failed`. | Wait until it is `completed`. |

## Next steps

- [Speakers](https://platform.vatis.tech/docs/transcript-object#speakers): get the speaker names into your files.
- [Manage transcripts](https://platform.vatis.tech/docs/batch/manage-transcripts): read, list and delete transcripts.
- [Webhooks](https://platform.vatis.tech/docs/batch/webhooks): have each transcript, and its files, posted to your server.
