const require_logger = require('./logger-CMp-NS-e.cjs');
require('./esm-gWVPXn3r.cjs');
require('./pythonUtils-rOCm9w_5.cjs');
require('./types-Cixl-wRO.cjs');
require('./util-CxWghxGa.cjs');
const require_fetch = require('./fetch-E3xbPP9w.cjs');
const require_cache = require('./cache-PWdK7nbt.cjs');
const require_openai = require('./openai-eZz8QsxY.cjs');
const require_util$1 = require('./util-Dqg4mr2c.cjs');
let fs = require("fs");
fs = require_logger.__toESM(fs);
let path = require("path");
path = require_logger.__toESM(path);

//#region src/providers/openai/transcription.ts
var OpenAiTranscriptionProvider = class OpenAiTranscriptionProvider extends require_openai.OpenAiGenericProvider {
	static OPENAI_TRANSCRIPTION_MODEL_NAMES = require_util$1.OPENAI_TRANSCRIPTION_MODELS.map((model) => model.id);
	config;
	constructor(modelName, options = {}) {
		if (!OpenAiTranscriptionProvider.OPENAI_TRANSCRIPTION_MODEL_NAMES.includes(modelName)) require_logger.logger_default.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 = require_util$1.OPENAI_TRANSCRIPTION_MODELS.find((m) => m.id === this.modelName);
		if (!model || !model.cost) return 0;
		return durationSeconds / 60 * model.cost.perMinute;
	}
	async callApi(prompt, context, _callApiOptions) {
		if (!this.getApiKey()) throw new Error("OpenAI API key is not set. Set the OPENAI_API_KEY environment variable or add `apiKey` to the provider config.");
		const config = {
			...this.config,
			...context?.prompt?.config
		};
		const audioFilePath = prompt.trim();
		if (!fs.default.existsSync(audioFilePath)) return { error: `Audio file not found: ${audioFilePath}` };
		try {
			const fileBuffer = fs.default.readFileSync(audioFilePath);
			const fileName = path.default.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.getOrganization() ? { "OpenAI-Organization": this.getOrganization() } : {}
			};
			let data, status, statusText;
			let cached = false;
			try {
				({data, cached, status, statusText} = await require_cache.fetchWithCache(`${this.getApiUrl()}/audio/transcriptions`, {
					method: "POST",
					headers,
					body: formData
				}, require_fetch.REQUEST_TIMEOUT_MS, "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) {
				require_logger.logger_default.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 = data.duration || 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,
					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) {
			require_logger.logger_default.error("Transcription error", { error: err });
			return { error: `Transcription error: ${String(err)}` };
		}
	}
};

//#endregion
exports.OpenAiTranscriptionProvider = OpenAiTranscriptionProvider;
//# sourceMappingURL=transcription-hPpt68W9.cjs.map