Uploading a File

๐Ÿ“‚ Upload a Local File for Transcription

Easily transcribe your local files by uploading them directly. Select the file from your device along with your user ID, service type, and preferred language. Optionally, specify a trigger word to insert line breaks in the transcript. Follow the instructions below to get started.

โš ๏ธ Notice: Ensure the file is accessible and in a supported format!

import json
import requests

#your api key
apiKey = 'xxxxx'
#language spoken in the audio file
language = 'en-US'
#local file path of the audio file
filepath = 'user/example.mp3'

params = {
  "language" : language,
  "file_name" : filepath.split("/")[-1]
}

headers = {
  "Authorization" : f"Bearer {apiKey}",
} 

url = 'https://api.tor.app/features/transcribe-file'

#first request to get the presigned url through which we will upload our audio file
resp = requests.get(url, params=params, headers=headers)

if resp.status_code != 200:
     raise Exception(resp.text)

decoded_resp = json.loads(resp.content)
url = decoded_resp['url']
given_order_id = decoded_resp["fields"]["key"].split("-+-")[0]

#attach the audio file
files = {'file': open(filepath, 'rb')}

#upload the audio file and initiate the transcription
r = requests.post(url, data= decoded_resp['fields'], files=files)

print(r.status_code)
print(given_order_id)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

// your API key
const apiKey = 'xxxxx';
// language spoken in the audio file
const language = 'en-US';
// local file path of the audio file
const filePath = 'user/example.mp3';

const fileName = path.basename(filePath);
const url = 'https://api.transkriptor.com/1/Upload';

// initial parameters
const params = {
    apiKey,
    language,
    fileName
};

// first request to get the presigned URL through which we will upload our audio file
axios.get(url, { params })
    .then(response => {
        const presignedUrl = response.data.url;
        const fields = response.data.fields;
        const givenOrderId = fields.key.split("-+-")[0];

        // attach the audio file
        const formData = new FormData();
        Object.entries(fields).forEach(([key, value]) => {
            formData.append(key, value);
        });
        formData.append('file', fs.createReadStream(filePath));

        // upload the audio file and initiate the transcription
        return axios.post(presignedUrl, formData, {
            headers: formData.getHeaders()
        });
    })
    .then(response => {
        console.log(response.status);
        console.log(givenOrderId);
    })
    .catch(error => {
        console.error(error);
    });

import org.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.nio.file.Paths;
import java.util.Map;

public class Main {

    private static final String API_KEY = "xxxxx"; // your API key
    private static final String LANGUAGE = "en-US"; // language spoken in the audio file
    private static final String FILE_PATH = "user/example.mp3"; // local file path of the audio file

    public static void main(String[] args) {
        String fileName = Paths.get(FILE_PATH).getFileName().toString();
        String url = "https://api.transkriptor.com/1/Upload";

        // first request to get the presigned url through which we will upload our audio file
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url + "?apiKey=" + API_KEY + "&language=" + LANGUAGE + "&fileName=" + fileName);
            HttpResponse response = client.execute(request);
            String responseString = EntityUtils.toString(response.getEntity());
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new Exception(responseString);
            }

            JSONObject jsonResponse = new JSONObject(responseString);
            url = jsonResponse.getString("url");
            String givenOrderId = jsonResponse.getJSONObject("fields").getString("key").split("-+-")[0];

            // attach the audio file
            File file = new File(FILE_PATH);
            HttpEntity entity = MultipartEntityBuilder.create()
                    .addTextBody("key", jsonResponse.getJSONObject("fields").getString("key"))
                    .addTextBody("AWSAccessKeyId", jsonResponse.getJSONObject("fields").getString("AWSAccessKeyId"))
                    .addTextBody("x-amz-security-token", jsonResponse.getJSONObject("fields").getString("x-amz-security-token"))
                    .addTextBody("policy", jsonResponse.getJSONObject("fields").getString("policy"))
                    .addTextBody("signature", jsonResponse.getJSONObject("fields").getString("signature"))
                    .addBinaryBody("file", file)
                    .build();

            // upload the audio file and initiate the transcription
            HttpPost postRequest = new HttpPost(url);
            postRequest.setEntity(entity);
            HttpResponse postResponse = client.execute(postRequest);

            System.out.println(postResponse.getStatusLine().getStatusCode());
            System.out.println(givenOrderId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

using System;
using System.Net;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.Net.Http;

public class Program
{
    public static async void Main(string[] args)
    {
        //your api key
        var apiKey = "xxxxx";
        //language spoken in the audio file
        var language = "en-US";
        //local file path of the audio file
        var filepath = "user/example.mp3";

        //initial parameters
        var parameters = new Dictionary<string, string> {
            { "apiKey", apiKey },
            { "language", language },
            { "fileName", Path.GetFileName(filepath) }
        };

        var url = "https://api.transkriptor.com/1/Upload";

        //first request to get the presigned url through which we will upload our audio file
        using (var client = new HttpClient())
        {
            var response = await client.GetAsync(url + "?" + await new FormUrlEncodedContent(parameters).ReadAsStringAsync());

            if (!response.IsSuccessStatusCode)
                throw new Exception(response.Content.ReadAsStringAsync().Result);

            var decodedResp = JObject.Parse(response.Content.ReadAsStringAsync().Result);
            url = decodedResp["url"].ToString();
            var givenOrderId = decodedResp["fields"]["key"].ToString().Split("-+-")[0];

            //attach the audio file
            var multipartFormDataContent = new MultipartFormDataContent();
            foreach (var item in decodedResp["fields"])
                multipartFormDataContent.Add(new StringContent(item.First.ToString()), $"\"{item.Path

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"path/filepath"
)

// your API key
const apiKey = "xxxxx"
// language spoken in the audio file
const language = "en-US"
// local file path of the audio file
const fileLoc = "user/example.mp3"

type Response struct {
	Url    string            `json:"url"`
	Fields map[string]string `json:"fields"`
}

func main() {
	fileName := filepath.Base(fileLoc)
	url := "https://api.transkriptor.com/1/Upload"

	params := map[string]string{
		"apiKey":   apiKey,
		"language": language,
		"fileName": fileName,
	}

	// first request to get the presigned URL through which we will upload our audio file
	resp, err := http.Get(fmt.Sprintf("%s?apiKey=%s&language=%s&fileName=%s", url, params["apiKey"], params["language"], params["fileName"]))
	if err != nil || resp.StatusCode != 200 {
		fmt.Println("Error:", err)
		return
	}
	defer resp.Body.Close()

	// decoding the response
	decoder := json.NewDecoder(resp.Body)
	var decodedResp Response
	err = decoder.Decode(&decodedResp)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	// retrieving the given order ID
	orderId := decodedResp.Fields["key"]
	givenOrderId := orderId[:len(orderId)-len(fileName)-3]

	// reading the file
	file, err := ioutil.ReadFile(fileLoc)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	// creating the form data
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	for key, val := range decodedResp.Fields {
		_ = writer.WriteField(key, val)
	}
	part, err := writer.CreateFormFile("file", fileName)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	part.Write(file)
	err = writer.Close()
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	// uploading the audio file and initiating the transcription
	req, err := http.NewRequest("POST", decodedResp.Url, body)
	req.Header.Set("Content-Type", writer.FormDataContentType())
	client := &http.Client{}
	resp, err = client.Do(req)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer resp.Body.Close()

	fmt.Println(resp.StatusCode)
	fmt.Println(givenOrderId)
}

require 'uri'
require 'net/http'
require 'json'

# your API key
api_key = 'xxxxx'
# language spoken in the audio file
language = 'en-US'
# local file path of the audio file
file_path = 'user/example.mp3'

parameters = {
    "apiKey" => api_key,
    "language" => language,
    "fileName" => File.basename(file_path)
}

url = URI.parse('https://api.transkriptor.com/1/Upload')
url.query = URI.encode_www_form(parameters)

# first request to get the presigned url through which we will upload our audio file
resp = Net::HTTP.get_response(url)

if resp.code != "200"
    raise StandardError.new(resp.body)
end

decoded_resp = JSON.parse(resp.body)
url = URI.parse(decoded_resp['url'])
given_order_id = decoded_resp["fields"]["key"].split("-+-")[0]

# attach the audio file
fields = decoded_resp['fields'].map{ |k, v| [k, v] }
fields << ["file", File.open(file_path)]

# upload the audio file and initiate the transcription
req = Net::HTTP::Post.new(url.path)
req.set_form(fields, 'multipart/form-data')
resp = Net::HTTP.new(url.host, url.port).start do |http|
    http.request(req)
end

puts resp.code
puts given_order_id

<?php
// your API key
$apiKey = 'xxxxx';
// language spoken in the audio file
$language = 'en-US';
// local file path of the audio file
$filePath = 'user/example.mp3';

$fileName = basename($filePath);
$url = 'https://api.transkriptor.com/1/Upload';

$params = array(
    "apiKey" => $apiKey,
    "language" => $language,
    "fileName" => $fileName
);

// use http_build_query to build the GET request URL
$getUrl = $url . "?" . http_build_query($params);

// first request to get the presigned URL through which we will upload our audio file
$ch = curl_init($getUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode != 200) {
    throw new Exception($response);
}

$responseData = json_decode($response, true);
$uploadUrl = $responseData['url'];
$givenOrderId = explode("-+-", $responseData["fields"]["key"])[0];

// attach the audio file
$postFields = $responseData['fields'];
$postFields['file'] = new CURLFile($filePath);

// upload the audio file and initiate the transcription
$ch = curl_init($uploadUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$result = curl_exec($ch);
$postHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $postHttpCode . PHP_EOL;
echo $givenOrderId . PHP_EOL;
?>

import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.io.DataOutputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import org.json.JSONObject

// your API key
val apiKey = "xxxxx"
// language spoken in the audio file
val language = "en-US"
// local file path of the audio file
val filePath = "user/example.mp3"
val fileName = File(filePath).name

val parameters = mapOf(
    "apiKey" to apiKey,
    "language" to language,
    "fileName" to fileName
)

val url = URL("https://api.transkriptor.com/1/Upload?" + parameters.entries.joinToString("&") { "${it.key}=${it.value}" })

// first request to get the presigned URL through which we will upload our audio file
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"

if (connection.responseCode != 200) {
    throw Exception(connection.inputStream.reader().readText())
}

val response = JSONObject(connection.inputStream.reader().readText())
val uploadUrl = URL(response.getString("url"))
val givenOrderId = response.getJSONObject("fields").getString("key").split("-+-")[0]

// upload the audio file and initiate the transcription
val fileConnection = uploadUrl.openConnection() as HttpURLConnection
fileConnection.requestMethod = "POST"
fileConnection.doOutput = true

val boundary = "===" + System.currentTimeMillis() + "==="
fileConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary)
val outputStream = DataOutputStream(fileConnection.outputStream)

outputStream.writeBytes("--$boundary\r\n")
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"$fileName\"\r\n\r\n")

val bytes = File(filePath).readBytes()
outputStream.write(bytes)

outputStream.writeBytes("\r\n--$boundary--\r\n")
outputStream.flush()
outputStream.close()

println(fileConnection.responseCode)
println(givenOrderId)

import Foundation

// Your API key
let apiKey = "xxxxx"
// Language spoken in the audio file
let language = "en-US"
// Local file path of the audio file
let filePath = URL(fileURLWithPath: "user/example.mp3")

let fileName = filePath.lastPathComponent
let urlString = "https://api.transkriptor.com/1/Upload"

// Initial parameters
let parameters: [String: String] = [
    "apiKey": apiKey,
    "language": language,
    "fileName": fileName
]

var urlComponents = URLComponents(string: urlString)!
urlComponents.queryItems = parameters.map { URLQueryItem(name: $0, value: $1) }
guard let url = urlComponents.url else { fatalError("Could not create URL") }

// First request to get the presigned URL through which we will upload our audio file
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    guard let data = data, error == nil else {
        print(error?.localizedDescription ?? "Unknown error")
        return
    }

    do {
        guard let decodedData = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
            print("Response was not JSON")
            return
        }

        guard let presignedUrlString = decodedData["url"] as? String,
              let presignedUrl = URL(string: presignedUrlString),
              let fields = decodedData["fields"] as? [String: String],
              let key = fields["key"] else {
            print("Invalid response")
            return
        }

        let givenOrderId = key.split(separator: "-+-")[0]

        var request = URLRequest(url: presignedUrl)
        request.httpMethod = "POST"

        // Add the fields as headers
        for (name, value) in fields {
            request.addValue(value, forHTTPHeaderField: name)
        }

        // Add the audio file as the body
        let audioData = try Data(contentsOf: filePath)
        request.httpBody = audioData

        // Upload the audio file and initiate the transcription
        let uploadTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard error == nil else {
                print(error?.localizedDescription ?? "Unknown error")
                return
            }

            let statusCode = (response as! HTTPURLResponse).statusCode
            print(statusCode)
            print(givenOrderId)
        }

        uploadTask.resume()
    } catch {
        print("Failed to decode JSON: \(error)")
    }
}

task.resume()

import 'dart:convert';
import 'dart:io';

// your API key
const apiKey = 'xxxxx';
// language spoken in the audio file
const language = 'en-US';
// local file path of the audio file
const filePath = 'user/example.mp3';

void main() async {
  final fileName = filePath.split('/').last;
  final url = Uri.parse('https://api.transkriptor.com/1/Upload');

  // first request to get the presigned URL through which we will upload our audio file
  final response = await HttpClient().getUrl(url..replace(queryParameters: {
    'apiKey': apiKey,
    'language': language,
    'fileName': fileName,
  }));

  if (response.statusCode != HttpStatus.ok) {
    throw Exception('Failed to get presigned URL: ${response.reasonPhrase}');
  }

  final respData = await response.transform(utf8.decoder).join();
  final data = jsonDecode(respData) as Map<String, dynamic>;

  final uploadUrl = data['url'];
  final givenOrderId = (data['fields']['key'] as String).split('-+-')[0];

  // attach the audio file
  final request = await HttpClient().postUrl(Uri.parse(uploadUrl));
  final file = File(filePath);
  data['fields'].forEach((k, v) => request.headers.add(k, v));
  request.headers.contentType = ContentType('multipart', 'form-data');
  request.headers.add(HttpHeaders.contentLengthHeader, await file.length());

  // upload the audio file and initiate the transcription
  final fileStream = file.openRead();
  await fileStream.cast<List<int>>().pipe(request);

  final resp = await request.close();

  print(resp.statusCode);
  print(givenOrderId);
}