import OpenAI from 'openai'; import { store } from '../utils/tempStore'; import config from '../config'; import fs from 'fs'; export class TranscriptionService { private openai: OpenAI; constructor() { this.openai = new OpenAI({ apiKey: config.openai.apiKey, }); } async transcribeAudio( filePath: string, language?: string ): Promise<{ text: string; transcriptionId: string }> { try { const transcription = await this.openai.audio.transcriptions.create({ file: fs.createReadStream(filePath), model: 'whisper-1', language: language, response_format: 'json', }); // Generate a unique ID for this transcription const transcriptionId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; // Store the transcription store.saveTranscription(transcriptionId, transcription.text, { language, timestamp: new Date(), }); // Clean up the temporary file fs.unlink(filePath, (err) => { if (err) console.error('Error deleting temporary file:', err); }); return { text: transcription.text, transcriptionId, }; } catch (error) { // Clean up the temporary file in case of error fs.unlink(filePath, (err) => { if (err) console.error('Error deleting temporary file:', err); }); console.error('Transcription error:', error); throw new Error('Failed to transcribe audio file'); } } } export const transcriptionService = new TranscriptionService();