import { o as logger } from "./logger-CtGm8dC_.js";
import { y as getRequestTimeoutMs } from "./fetch-AchwhzAC.js";
import { r as fetchWithCache } from "./cache-wQj0h878.js";
import { o as OPENAI_TRANSCRIPTION_MODELS } from "./util-BKx_SQfl.js";
import { t as OpenAiGenericProvider } from "./openai-DWlt6qgx.js";
import fs from "fs/promises";
import path from "path";
//#region src/providers/openai/transcription.ts
var OpenAiTranscriptionProvider = class OpenAiTranscriptionProvider extends OpenAiGenericProvider {
	static OPENAI_TRANSCRIPTION_MODEL_NAMES = OPENAI_TRANSCRIPTION_MODELS.map((model) => model.id);
	config;
	constructor(modelName, options = {}) {
		if (!OpenAiTranscriptionProvider.OPENAI_TRANSCRIPTION_MODEL_NAMES.includes(modelName)) logger.debug(`Using unknown transcription model: ${modelName}`);
		super(modelName, options);
		this.config = options.config || {};
	}
	id() {
		return `openai:transcription:${this.modelName}`;
	}
	toString() {
		return `[OpenAI Transcription Provider ${this.modelName}]`;
	}
	calculateTranscriptionCost(durationSeconds) {
		const model = OPENAI_TRANSCRIPTION_MODELS.find((m) => m.id === this.modelName);
		if (!model || !model.cost || durationSeconds === void 0) return;
		return durationSeconds / 60 * model.cost.perMinute;
	}
	async callApi(prompt, context, _callApiOptions) {
		if (!this.getApiKey()) throw new Error(this.getMissingApiKeyErrorMessage());
		const config = {
			...this.config,
			...context?.prompt?.config
		};
		const audioFilePath = prompt.trim();
		let fileBuffer;
		try {
			fileBuffer = await fs.readFile(audioFilePath);
		} catch (err) {
			if (err.code === "ENOENT") return { error: `Audio file not found: ${audioFilePath}` };
			logger.error("Failed to read audio file", {
				error: err,
				audioFilePath
			});
			return { error: `Failed to read audio file ${audioFilePath}: ${String(err)}` };
		}
		try {
			const fileName = path.basename(audioFilePath);
			const file = new File([fileBuffer], fileName);
			const formData = new FormData();
			formData.append("file", file);
			formData.append("model", this.modelName);
			if (config.language) formData.append("language", config.language);
			if (config.prompt) formData.append("prompt", config.prompt);
			if (config.temperature !== void 0) formData.append("temperature", config.temperature.toString());
			if (config.timestamp_granularities && config.timestamp_granularities.length > 0) formData.append("timestamp_granularities", JSON.stringify(config.timestamp_granularities));
			if (this.modelName.includes("diarize")) {
				formData.append("response_format", "diarized_json");
				if (config.num_speakers !== void 0) formData.append("num_speakers", config.num_speakers.toString());
				if (config.speaker_labels && config.speaker_labels.length > 0) formData.append("speaker_labels", JSON.stringify(config.speaker_labels));
			} else {
				const responseFormat = this.modelName.startsWith("gpt-4o-") ? "json" : "verbose_json";
				formData.append("response_format", responseFormat);
			}
			const headers = {
				Authorization: `Bearer ${this.getApiKey()}`,
				...this.getOpenAiRequestHeaders()
			};
			let data, status, statusText;
			let cached = false;
			try {
				({data, cached, status, statusText} = await fetchWithCache(`${this.getApiUrl()}/audio/transcriptions`, {
					method: "POST",
					headers,
					body: formData
				}, getRequestTimeoutMs(), "json", context?.bustCache ?? context?.debug));
				if (status < 200 || status >= 300) return { error: `API error: ${status} ${statusText}\n${typeof data === "string" ? data : JSON.stringify(data)}` };
			} catch (err) {
				logger.error("API call error", { error: err });
				return { error: `API call error: ${String(err)}` };
			}
			if (data.error) return { error: typeof data.error === "string" ? data.error : JSON.stringify(data.error) };
			const durationSeconds = typeof data.duration === "number" ? data.duration : void 0;
			const cost = cached ? 0 : this.calculateTranscriptionCost(durationSeconds);
			const segments = data.segments || [];
			let avgLogprob;
			let avgCompressionRatio;
			let avgNoSpeechProb;
			if (segments.length > 0) {
				const validSegments = segments.filter((s) => s.avg_logprob !== void 0 || s.compression_ratio !== void 0 || s.no_speech_prob !== void 0);
				if (validSegments.length > 0) {
					const sumLogprob = validSegments.reduce((sum, s) => sum + (s.avg_logprob || 0), 0);
					const sumCompressionRatio = validSegments.reduce((sum, s) => sum + (s.compression_ratio || 0), 0);
					const sumNoSpeechProb = validSegments.reduce((sum, s) => sum + (s.no_speech_prob || 0), 0);
					avgLogprob = validSegments.some((s) => s.avg_logprob !== void 0) ? sumLogprob / validSegments.length : void 0;
					avgCompressionRatio = validSegments.some((s) => s.compression_ratio !== void 0) ? sumCompressionRatio / validSegments.length : void 0;
					avgNoSpeechProb = validSegments.some((s) => s.no_speech_prob !== void 0) ? sumNoSpeechProb / validSegments.length : void 0;
				}
			}
			let output;
			if (this.modelName.includes("diarize") && data.segments) output = data.segments.map((segment) => {
				const speaker = segment.speaker || "Unknown";
				const text = segment.text || "";
				return `[${segment.start?.toFixed(2) || "0.00"}s - ${segment.end?.toFixed(2) || "0.00"}s] ${speaker}: ${text}`;
			}).join("\n");
			else if (data.text) output = data.text;
			else return { error: "No transcription returned from API" };
			return {
				output,
				cached,
				cost,
				metadata: {
					task: data.task,
					...durationSeconds === void 0 ? {} : { duration: durationSeconds },
					language: data.language,
					segments: data.segments?.length || 0,
					...avgLogprob === void 0 ? {} : { avgLogprob },
					...avgCompressionRatio === void 0 ? {} : { avgCompressionRatio },
					...avgNoSpeechProb === void 0 ? {} : { avgNoSpeechProb },
					...this.modelName.includes("diarize") && data.speakers ? { speakers: data.speakers } : {}
				}
			};
		} catch (err) {
			logger.error("Transcription error", { error: err });
			return { error: `Transcription error: ${String(err)}` };
		}
	}
};
//#endregion
export { OpenAiTranscriptionProvider };

//# sourceMappingURL=transcription-DTs3pZxa.js.map