transcribeAudio method

Future<GptTranscriptionObject> transcribeAudio({
  1. required String apiKey,
  2. required String organizationId,
  3. required GptAudioTranscriptionRequest request,
  4. required Uint8List fileBytes,
})

Transcribes audio into the input language.

Implementation

Future<GptTranscriptionObject> transcribeAudio(
    {required String apiKey,
    required String organizationId,
    required GptAudioTranscriptionRequest request,
    required Uint8List fileBytes}) async {
  Map<String, String> headers = {
    "Authorization": "Bearer $apiKey",
    "OpenAI-Organization": organizationId,
    'Content-Type': 'application/json',
    "Access-Control-Allow-Origin": "*", // Required for CORS support to work
  };

  Uri endpoint;
  if (secure) {
    endpoint = Uri.https(baseUrl, "/v1/audio/transcriptions");
  } else {
    endpoint = Uri.http(baseUrl, "/v1/audio/transcriptions");
  }

  String? targetFilename = request.fileName;
  request.fileName = null;
  List<GptTimestampGranularity> granularities =
      request.timestampGranularities;

  // TODO convert ganularity to comman separated string.
  String outGranularities = granularities.map((e) => e.name).join(",");

  var httpRequest = http.MultipartRequest('POST', endpoint)
    ..headers.addAll(headers)
    ..fields.addAll(
      request.toJson().map(
            (key, value) {

              if(key == "timestamp_granularities[]") {
                return MapEntry(key, outGranularities);
              }

              return MapEntry(
                key,
                value.toString(),
              );
            }
          ),
    )
    ..files.add(http.MultipartFile.fromBytes("file", fileBytes,
        filename: targetFilename));

  var response = await httpRequest.send();

  if (response.statusCode == 200 || response.statusCode == 201) {
    return GptTranscriptionObject.fromJson(jsonDecode(
        const Utf8Decoder().convert(await response.stream.toBytes())));
  } else {
    var error = ServerError.fromJson(jsonDecode(
        const Utf8Decoder().convert(await response.stream.toBytes())));
    throw AudioException(
        statusCode: response.statusCode, message: error.message);
  }
}