# All files / src/providers/openai Transcription.ts

63.01% Statements 46/73
37.7% Branches 23/61
71.42% Functions 5/7
66.66% Lines 46/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216

    40x
    40x

    2x

    2x
    1x

    1x

    1x
    1x

    1x
    1x
    1x
    1x
    1x

    1x

    1x

    1x
    1x

    1x

    1x

    1x

    1x
    1x

    3x

    1x
    1x
    1x

    1x
    1x
    1x

    1x

    1x

    1x

    1x

    1x

    1x

    1x
    1x

    1x

    1x

    1x
    1x
    1x

    1x
    1x

    1x

    1x

     import { TranscriptionRequest, TranscriptionResponse, TranscriptionSegment } from "../Provider.js";
    import { handleOpenAIError } from "./Errors.js";
    import { AudioUtils } from "../../utils/audio.js";
    import { DEFAULT_MODELS } from "../../constants.js";
    import { buildUrl } from "./utils.js";
    import { logger } from "../../utils/logger.js";
    import { fetchWithTimeout } from "../../utils/fetch.js";

    export class OpenAITranscription {
      constructor(
        private readonly baseUrl: string,
        private readonly apiKey: string
      ) {}

      async execute(request: TranscriptionRequest): Promise<TranscriptionResponse> {
        const model = request.model || DEFAULT_MODELS.TRANSCRIPTION;

        if (model.startsWith("gpt-4o")) {
          return this.transcribeViaChat(request);
        }

        return this.transcribeViaWhisper(request);
      }

      private async transcribeViaWhisper(
        request: TranscriptionRequest
      ): Promise<TranscriptionResponse> {
        const formData = new FormData();
        const { data, fileName, duration: estimatedDuration } = await AudioUtils.load(request.file);

        const mimeType = fileName.endsWith(".wav") ? "audio/wav" : "audio/mpeg";
        const file = new File([data as unknown as BlobPart], fileName, { type: mimeType });
        formData.append("file", file);
        formData.append("model", request.model || DEFAULT_MODELS.TRANSCRIPTION);
        formData.append("response_format", "verbose_json");

        Iif (request.prompt) {
          formData.append("prompt", request.prompt);
        }

        Iif (request.language) {
          formData.append("language", request.language);
        }

        const url = buildUrl(this.baseUrl, "/audio/transcriptions");
        logger.logRequest("OpenAI", "POST", url, {
          model: request.model || DEFAULT_MODELS.TRANSCRIPTION,
          file: fileName
        });

        const response = await fetchWithTimeout(
          url,
          {
            method: "POST",
            headers: {
              Authorization: `Bearer ${this.apiKey}`
            },
            body: formData
          },
          request.requestTimeout
        );

        Iif (!response.ok) {
          await handleOpenAIError(response, request.model || DEFAULT_MODELS.TRANSCRIPTION);
        }

        const json = (await response.json()) as {
          text: string;
          model: string;
          duration?: number;
          segments?: TranscriptionSegment[];
        };
        logger.logResponse("OpenAI", response.status, response.statusText, json);
        return {
          text: json.text,
          model: json.model || request.model || DEFAULT_MODELS.TRANSCRIPTION,
          duration: json.duration || estimatedDuration,
          segments: json.segments?.map((s) => ({
            id: s.id,
            start: s.start,
            end: s.end,
            text: s.text
          }))
        };
      }

      private async transcribeViaChat(request: TranscriptionRequest): Promise<TranscriptionResponse> {
        const { data, fileName, duration: estimatedDuration } = await AudioUtils.load(request.file);
        const base64Audio = Buffer.from(data).toString("base64");
        const model = request.model || "gpt-4o";

        const actualModel = "gpt-4o-audio-preview";
        let defaultPrompt = "Transcribe the audio exactly. Return only the transcription text.";
        let isDiarization = false;

        Iif (model.includes("diarize")) {
          isDiarization = true;
          const names = request.speakerNames?.join(", ") || "Speaker A, Speaker B";
          defaultPrompt = `Transcribe the audio and identify different speakers.
          I will provide reference clips for specific voices. Please map the voices in the main audio to these names: ${names}.
          Return the output as a JSON array of objects, each with 'speaker', 'text', 'start', and 'end' (in seconds).
          Example: [{"speaker": "Alice", "text": "Hello", "start": 0.5, "end": 1.2}]`;
        }

        Iif (request.language) {
          defaultPrompt += ` The audio is in ${request.language}.`;
        }

        const messagesContent: Record<string, unknown>[] = [
          {
            type: "text",
            text: request.prompt
              ? `${defaultPrompt}\n\nContext for transcription: ${request.prompt}`
              : defaultPrompt
          }
        ];

        Iif (request.speakerReferences && request.speakerNames) {
          for (let i = 0; i < request.speakerReferences.length; i++) {
            const refFile = request.speakerReferences[i];
            if (!refFile) continue;

            const name = request.speakerNames[i] || `Speaker ${i + 1}`;
            const { data: refData } = await AudioUtils.load(refFile);
            const refBase64 = Buffer.from(refData).toString("base64");

            messagesContent.push({
              type: "text",
              text: `The following audio clip is the voice of ${name}:`
            });
            messagesContent.push({
              type: "input_audio",
              input_audio: {
                data: refBase64,
                format: refFile.endsWith(".wav") ? "wav" : "mp3"
              }
            });
          }
          messagesContent.push({
            type: "text",
            text: "Now, transcribe this main audio file using identified names:"
          });
        }

        messagesContent.push({
          type: "input_audio",
          input_audio: {
            data: base64Audio,
            format: fileName.endsWith(".wav") ? "wav" : "mp3"
          }
        });

        const body = {
          model: actualModel,
          messages: [
            {
              role: "user",
              content: messagesContent
            }
          ]
        };

        const url = buildUrl(this.baseUrl, "/chat/completions");
        logger.logRequest("OpenAI", "POST", url, body);

        const response = await fetchWithTimeout(
          url,
          {
            method: "POST",
            headers: {
              Authorization: `Bearer ${this.apiKey}`,
              "Content-Type": "application/json"
            },
            body: JSON.stringify(body)
          },
          request.requestTimeout
        );

        Iif (!response.ok) {
          await handleOpenAIError(response, actualModel);
        }

        const json = await response.json();
        logger.logResponse("OpenAI", response.status, response.statusText, json);
        const content = json.choices[0]?.message?.content || "";

        let text = content;
        let segments: TranscriptionSegment[] = [];

        Iif (isDiarization) {
          try {
            const parsed = JSON.parse(content);
            if (Array.isArray(parsed)) {
              segments = parsed.map((s, i) => ({
                id: i,
                start: s.start || 0,
                end: s.end || 0,
                text: s.text || "",
                speaker: s.speaker
              }));
              text = segments.map((s) => `${s.speaker}: ${s.text}`).join("\n");
            }
          } catch {
            text = content;
          }
        }

        return {
          text,
          model,
          duration: estimatedDuration || 0,
          segments
        };
      }
    }