Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions transcribing/file.bal
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import ballerina/io;
import ballerina/http;
import ballerina/lang.runtime;

configurable string API_TOKEN = ?;

http:Client assemblyaiClient = check new ("https://api.assemblyai.com/v2", auth = {
token: API_TOKEN
});

public function uploadFile(string path) returns string|error {
http:Request request = new;
// Sets the file as the request payload.
request.setFileAsPayload(path);

//Sends the request to the receiver service with the file content.
json res = check assemblyaiClient->/upload.post(request);
string uploadUrl = check res?.upload_url;
return uploadUrl;
}

public function createTranscript(string audio_url) returns Transcription|error {
json result = check assemblyaiClient->/transcript.post({
audio_url
});

string transcriptId = check result?.id;
while true {
json pollingJson = check assemblyaiClient->/transcript/[transcriptId].get();
string status = check pollingJson?.status;
if status == "completed" {
return pollingJson.cloneWithType();
} else if status == "error" {
string cause = check pollingJson?.'error;
panic error(string `Transcription failed due to ${cause}`);
} else {
runtime:sleep(5);
}
}
}

type Transcription record {
string text;
float confidence;
};

public function main(string filePath) returns error? {
string uploadUrl = check uploadFile(filePath);
Transcription transcript = check createTranscript(uploadUrl);
io:println(string `Transcription: "${transcript.text}" with confidence ${transcript.confidence}`);
}