Building purposes with OpenAI Audio-to-Text

Building purposes with OpenAI Audio-to-Text

Building purposes with OpenAI Audio-to-Text

I’m within the course of of making a chatbot utilizing audio transcribed information. The Whisper OpenAI mannequin is understood for its accuracy in transcribing, translating, and creating speech. In this put up, I present two methods wherein one can use the OpenAI Whisper-1 mannequin: JavaScript fetch and Python.

JavaScript fetch

At the second I desire JavaScript over Node.js as a result of JavaScript is a core growth language that I’ve not but mastered. Unfortunately, the OpenAI Speech-to-text assist web page doesn’t give any examples in JavaScript fetch; examples are given in Python, Node.js, curl [1]. Fortunately, by looking out on-line Postman [2] and OpenAI group [3] gave hints on the best way to create a working workflow utilizing JavaScript fetch.

<!DOCTYPE html>
<html>
<head>
<base goal="_top">
</head>
<physique>

<label id="instructions" fashion="show:block">Enter OpenAI key to transcribe the audio information to textual content. All audio information within the repository can be transcribed.</label>

<br>

<enter id="OPENAI_API_KEY" kind="textual content" worth="" placeholder="OPENAI_API_KEY" rows="10" cols="100" fashion="show:block; text-align: left; width: 150px;">

<br><br>

<button id="readaudio" onclick="readaudio()">Transcribe audios</button>


<script>


// ----------------------------------------------------

async operate readaudio() {

return await get_file_objects()
.then(file_objects => { console.log("file_objects:", file_objects);
var dict_out = [];
file_objects.forEach(async operate(file_object, index) {

console.log("file_object:", file_object);

// REST API to transform .mp3 to textual content

// ------------------------------------------
// Form submission
// ------------------------------------------

// ------------------------------------------

// learn within the mp3 as file_download_url --> convert to blob_object
var text_out = await fetch(file_download_url)
.then(response => response.blob())
.then(async operate(blob_object) {
console.log("blob_object: ", blob_object);

// A blob_object could be instantly used OR the blob_object could be inserted right into a File
var text_out = await openai_transcription(blob_object, 'blob_object');
// OR
// var file_blob_object = new File ([blob_object], "recording.mp3", {kind: "audio/mp3"});
// var text_out = await openai_transcription(file_blob_object, 'file_blob_object');

return text_out;
})
.catch(error => { console.log(error); });

// ------------------------------------------

});

});
}


// ----------------------------------------------------


async operate openai_transcription(file_input, which_input) {

// https://www.postman.com/devrel/workspace/openai/documentation/13183464-90abb798-cb85-43cb-ba3a-ae7941e968da
const OPENAI_API_KEY = doc.getElementById("OPENAI_API_KEY").worth;

const url = 'https://api.openai.com/v1/audio/transcriptions';

const headers = new Headers();
headers.append("Authorization", 'Bearer ' + OPENAI_API_KEY);
headers.append("Accept", "utility/json");

const formData = new FormInformation();
if (which_input == 'blob_object') {
formData.append("file", file_input);
} else {
// utilizing a file_blob_object
formData.append("file", file_input, "recording.mp3"); // mp3, mp4, mpeg, mpga, m4a, wav, or webm
}
formData.append("mannequin", "whisper-1");
formData.append("immediate", "Transcribe the audio"); // Style context for the transcription
formData.append("response_format", "textual content"); // json, textual content, srt, verbose_json, or vtt
formData.append("temperature", "0"); // The sampling temperature, between 0 (correct) and 1 (random response)
formData.append("language", "en");
formData.append("transcription", "plain textual content"); // plain textual content, srt, vtt

const choices = {methodology: 'POST',
headers: headers,
physique: formData,
redirect: "comply with"
};

// Print textual content a part of JSON response solely with person message
return await fetch(url, choices)
.then(response => response.textual content())
.then(outcome => { console.log(outcome); return outcome; })
.catch(error => { console.log(error); });

}

// ----------------------------------------------------


async operate get_file_objects() {

const repoOwner = 'CodeSolutions2';
const repoName = 'audio_2_text_webapp';
var url = `https://api.github.com/repos/${repoOwner}/${repoName}/contents`;

var file_objects = [];
var date = [];
await fetch(url).then(res => res.json()).then(information => {
information.forEach(file => {
if (file.kind === 'file' && file.title.match(/.(mp3)$/i)) {
file_objects.push(file);
}
});
}).catch(error => { outp.innerHTML += error; });

console.log('file_objects: ', file_objects);

return file_objects;
}


// ----------------------------------------------------



</script>

</physique>
</html>
SUCCESS! There had been two .mp3 information within the public repository (https://github.com/CodeSolutions2/audio_2_text_webapp). The for loop learn in each information: within the first file the audio was ‘Hello, audio journal’, and within the second file the audio was ‘This is an audio journal. It’s a check for the audio-to-text utility’.

Troubleshooting points

Note, that utilizing this endpoint was harder than different OpenAI endpoints as a result of I used to be not acquainted with the required enter file format and a given piece of header info isn’t required (headers.append(“Content-Type”, “multipart/form-data”);). The OpenAI information [1] says to incorporate multipart/form-data for curl, however it isn’t wanted for JavaScript fetch REST API.

A blob with kind mp3, mp4, mpeg, mpga, m4a, wav, or webm is all that’s wanted as an enter file. I wasted quite a lot of time, attempting to comply with pre-processing audio file examples for already encoded base64 information. If one is retrieving information from a repository that use an API that routinely encrypts information, just like the GitHub API, it’s essential to decrypt the information from base64. Decrypting the information requires that one: convert the blob to a base64_string, convert the base64_string to a binaryString, convert the binaryString to a byteArray, convert the byteArray again right into a blob and/or File format. In the instance, I don’t use the GitHub API [4] with token verification (which ought to base64 encrypt the downloaded information), as an alternative I simply did a GET fetch on public repository .mp3 information (GET simply returns the unique file_objects).

Python

The python transcription instance was simple from OpenAI’s information [1]. In the spirit of MLOps, from a frontend perspective, I attempted to attach the python Openai whisper mannequin to pyscript. However, it requires some by-hand utilization of async HTTP request [5].

# [Step 0] Install the API 
!pip set up openai
!git clone https://github.com/CodeSolutions2/data2download.git
import os
os.listdir('/kaggle/working/data2download')
# ['2024_03_13_09_57_51_test0.mp3', '.git', 'README.md']
# [Step 1] Load libraries
# https://pypi.org/undertaking/python-dotenv/
from dotenv import load_dotenv, find_dotenv
dot_env_file_exist = load_dotenv(find_dotenv()) # learn native .env file
# Returns true or false if .env exists in present listing
print('dot_env_file_exist: ', dot_env_file_exist)

import openai

# Load the OPENAI_API_KEY as an environmental variable
# Direct copy from Transcriptions
from openai import OpenAI
consumer = OpenAI(api_key = OPENAI_API_KEY)

audio_file= open("/kaggle/working/data2download/2024_03_13_09_57_51_test0.mp3", "rb")
transcription = consumer.audio.transcriptions.create(
mannequin="whisper-1",
file=audio_file
)
print(transcription.textual content)

I hope this brief information was useful for getting began with utilizing OpenAI’s Whisper-1 transcription mannequin together with your LLM net purposes!

Happy Practicing! 👋

💻 GitHub | 🔔 Subscribe

References

  1. OpenAI Speech-to-Text information: https://platform.openai.com/docs/guides/speech-to-text
  2. Postman OpenAI REST API useful resource: https://www.postman.com/devrel/workspace/openai/request/13183464-f5c8da69-7b34-4250-abf8-d98cb40e19fe
  3. Great useful resource for troubleshooting errors utilizing JavaScript fetch: https://group.openai.com/t/calling-whisper-api-using-curl-request-keeps-giving-error/81510/20
  4. GitHub API: https://docs.github.com/en/relaxation/repos/contents?apiVersion=2022-11-28
  5. Using python OpenAI in pyscript: https://stackoverflow.com/questions/75738343/how-can-i-use-pip-install-when-using-pyscript/75738539

HI-FI News

through Python on Medium https://ift.tt/OJjg1F0

April 16, 2024 at 04:30PM