transcription.service.ts412 lines, 14 KB
| 1 | import { protos, SpeechClient } from "@google-cloud/speech"; |
| 2 | import { Storage } from "@google-cloud/storage"; |
| 3 | import logger from "../utils/logger"; |
| 4 | import { AppError } from "../utils/errors"; |
| 5 | import { StatusCodes } from "http-status-codes"; |
| 6 | import path from "path"; |
| 7 | import ffmpeg from "fluent-ffmpeg"; |
| 8 | import { unlink } from "fs/promises"; |
| 9 | import ffmpegInstaller from "@ffmpeg-installer/ffmpeg"; |
| 10 | |
| 11 | ffmpeg.setFfmpegPath(ffmpegInstaller.path); |
| 12 | |
| 13 | // Interface for word-level timestamps |
| 14 | export interface WordTimestamp { |
| 15 | word: string; |
| 16 | startTime: number; // seconds |
| 17 | endTime: number; // seconds |
| 18 | } |
| 19 | |
| 20 | // Updated TranscriptionResult interface |
| 21 | export interface TranscriptionResult { |
| 22 | text: string; |
| 23 | confidence: number; |
| 24 | isMusic?: boolean; |
| 25 | wordTimestamps?: WordTimestamp[]; // Added field for word timestamps |
| 26 | } |
| 27 | |
| 28 | export class TranscriptionService { |
| 29 | private static readonly BUCKET_NAME = "ai-video-summarizer-audio"; |
| 30 | private static readonly speechClient = new SpeechClient(); |
| 31 | private static readonly storage = new Storage(); |
| 32 | |
| 33 | static async ensureBucketExists() { |
| 34 | try { |
| 35 | const [exists] = await this.storage.bucket(this.BUCKET_NAME).exists(); |
| 36 | |
| 37 | if (!exists) { |
| 38 | await this.storage.createBucket(this.BUCKET_NAME, { |
| 39 | location: "US", |
| 40 | storageClass: "STANDARD", |
| 41 | }); |
| 42 | logger.info(`Bucket ${this.BUCKET_NAME} created`); |
| 43 | } |
| 44 | } catch (error) { |
| 45 | logger.error(`Error creating bucket ${this.BUCKET_NAME}`, { error }); |
| 46 | throw new AppError( |
| 47 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 48 | "Failed to create bucket" |
| 49 | ); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | static async uploadToGCS(filePath: string): Promise<string> { |
| 54 | const fileName = path.basename(filePath); |
| 55 | const bucket = this.storage.bucket(this.BUCKET_NAME); |
| 56 | |
| 57 | try { |
| 58 | await bucket.upload(filePath, { |
| 59 | destination: fileName, |
| 60 | metadata: { |
| 61 | contentType: "audio/wav", |
| 62 | }, |
| 63 | }); |
| 64 | |
| 65 | const gcsUrl = `gs://${this.BUCKET_NAME}/${fileName}`; |
| 66 | logger.info(`Audio uploaded to GCS: ${gcsUrl}`); |
| 67 | return gcsUrl; |
| 68 | } catch (error: any) { |
| 69 | logger.error(`Error uploading audio to GCS: ${error.message}`, { error }); |
| 70 | throw new AppError( |
| 71 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 72 | "Failed to upload audio to GCS" |
| 73 | ); |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | static async deleteFromGCS(gcsUrl: string): Promise<void> { |
| 78 | try { |
| 79 | const fileName = gcsUrl.split("/").pop(); |
| 80 | if (!fileName) return; |
| 81 | |
| 82 | const file = this.storage.bucket(this.BUCKET_NAME).file(fileName); |
| 83 | const [exists] = await file.exists(); |
| 84 | |
| 85 | if (exists) { |
| 86 | await file.delete(); |
| 87 | logger.info(`Audio deleted from GCS: ${gcsUrl}`); |
| 88 | } |
| 89 | } catch (error: any) { |
| 90 | logger.error(`Error deleting audio from GCS: ${error.message}`, { |
| 91 | error, |
| 92 | }); |
| 93 | // Don't throw here, just log the error |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | static async convertToWav(inputPath: string): Promise<string> { |
| 98 | const outputPath = path.join( |
| 99 | path.dirname(inputPath), |
| 100 | `${path.basename(inputPath, path.extname(inputPath))}.wav` |
| 101 | ); |
| 102 | |
| 103 | return new Promise((resolve, reject) => { |
| 104 | ffmpeg(inputPath) |
| 105 | .toFormat("wav") |
| 106 | .audioFilters([ |
| 107 | "aresample=resampler=soxr", // High quality resampling |
| 108 | "highpass=f=50", // Remove low frequency noise |
| 109 | "lowpass=f=3000", // Focus on speech frequencies |
| 110 | "afftdn=nf=-25", // Reduce noise |
| 111 | "loudnorm=I=-16:LRA=11:TP=-1.5", // Normalize audio levels |
| 112 | "aformat=channel_layouts=mono", // Ensure mono output |
| 113 | ]) |
| 114 | .outputOptions(["-acodec pcm_s16le", "-ac 1", "-ar 16000"]) |
| 115 | .save(outputPath) |
| 116 | .on("start", (commandLine) => { |
| 117 | logger.info("FFmpeg process started:", commandLine); |
| 118 | }) |
| 119 | .on("end", () => { |
| 120 | logger.info(`Audio converted to WAV: ${outputPath}`); |
| 121 | resolve(outputPath); |
| 122 | }) |
| 123 | .on("error", (err) => { |
| 124 | logger.error(`Error converting audio to WAV: ${err.message}`, { |
| 125 | error: err, |
| 126 | }); |
| 127 | reject( |
| 128 | new AppError( |
| 129 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 130 | "Failed to convert audio to WAV" |
| 131 | ) |
| 132 | ); |
| 133 | }); |
| 134 | }); |
| 135 | } |
| 136 | |
| 137 | static async detectContentType( |
| 138 | audioPath: string |
| 139 | ): Promise<"speech" | "music"> { |
| 140 | const analysisPath = path.join( |
| 141 | path.dirname(audioPath), |
| 142 | `${path.basename(audioPath, path.extname(audioPath))}_analysis.wav` |
| 143 | ); |
| 144 | |
| 145 | // Ensure analysis file path is unique if running concurrently |
| 146 | const uniqueAnalysisPath = `${analysisPath}_${Date.now()}`; |
| 147 | |
| 148 | return new Promise((resolve, reject) => { |
| 149 | let musicScore = 0; |
| 150 | let totalSamples = 0; |
| 151 | let ffmpegStderr = ""; |
| 152 | |
| 153 | ffmpeg(audioPath) |
| 154 | .toFormat("wav") |
| 155 | .audioFrequency(16000) // Standard audio frequency for speech |
| 156 | .audioFilter(["silencedetect=n=-50dB:d=0.5", "volumedetect"]) |
| 157 | .save(uniqueAnalysisPath) |
| 158 | .on("stderr", (stderrLine: string) => { |
| 159 | // Accumulate stderr for better analysis later if needed |
| 160 | ffmpegStderr += stderrLine + "\n"; |
| 161 | }) |
| 162 | .on("end", async () => { |
| 163 | logger.debug( |
| 164 | `FFmpeg stderr for content type detection:\n${ffmpegStderr}` |
| 165 | ); |
| 166 | // Analyze the accumulated stderr |
| 167 | if (ffmpegStderr.includes("silence_duration")) { |
| 168 | musicScore -= 1; // less silence, more music |
| 169 | } |
| 170 | if (ffmpegStderr.includes("max_volume")) { |
| 171 | const match = ffmpegStderr.match(/max_volume:\s*([-\d.]+)/); |
| 172 | if (match) { |
| 173 | const maxVolume = parseFloat(match[1]); |
| 174 | if (maxVolume > -5) musicScore += 1; // High volume peaks suggest music |
| 175 | } |
| 176 | } |
| 177 | if (ffmpegStderr.includes("mean_volume")) { |
| 178 | const match = ffmpegStderr.match(/mean_volume:\s*([-\d.]+)/); |
| 179 | if (match) { |
| 180 | const meanVolume = parseFloat(match[1]); |
| 181 | if (meanVolume > -10) musicScore += 0.5; // Louder average suggests music |
| 182 | } |
| 183 | } |
| 184 | totalSamples = ffmpegStderr.split("\n").length; // Rough estimate |
| 185 | |
| 186 | await unlink(uniqueAnalysisPath).catch((err: any) => |
| 187 | logger.warn( |
| 188 | `Could not delete analysis file ${uniqueAnalysisPath}: ${err.message}` |
| 189 | ) |
| 190 | ); |
| 191 | const ratio = totalSamples > 0 ? musicScore / totalSamples : 0; |
| 192 | logger.info( |
| 193 | `Music detection score: ${musicScore}, Samples: ${totalSamples}, Ratio: ${ratio}` |
| 194 | ); |
| 195 | // Adjust threshold based on testing if needed |
| 196 | resolve(ratio > 0.1 ? "music" : "speech"); |
| 197 | }) |
| 198 | .on("error", async (err: Error) => { |
| 199 | logger.error(`Error detecting content type: ${err.message}`, { |
| 200 | error: err, |
| 201 | }); |
| 202 | await unlink(uniqueAnalysisPath).catch(() => {}); |
| 203 | // Fallback to assuming speech on error? |
| 204 | // reject( new AppError(...) ); |
| 205 | resolve("speech"); // Or reject, depending on desired behavior |
| 206 | }); |
| 207 | }); |
| 208 | } |
| 209 | |
| 210 | static async transcribe(audioPath: string): Promise<TranscriptionResult> { |
| 211 | let wavePath: string | undefined; |
| 212 | let gcsUrl: string | undefined; |
| 213 | |
| 214 | try { |
| 215 | if (!audioPath) { |
| 216 | throw new AppError(StatusCodes.BAD_REQUEST, "No audio file provided"); |
| 217 | } |
| 218 | |
| 219 | await this.ensureBucketExists(); |
| 220 | |
| 221 | wavePath = await this.convertToWav(audioPath); |
| 222 | logger.info(`Converted audio to WAV: ${wavePath}`); |
| 223 | |
| 224 | const contentType = await this.detectContentType(wavePath); |
| 225 | logger.info(`Detected content type: ${contentType}`); |
| 226 | |
| 227 | if (contentType === "music") { |
| 228 | await unlink(wavePath).catch((err: any) => |
| 229 | logger.warn(`Failed to delete music WAV file: ${err.message}`) |
| 230 | ); |
| 231 | return { |
| 232 | text: "[MUSIC CONTENT DETECTED]", |
| 233 | confidence: 1.0, |
| 234 | isMusic: true, |
| 235 | wordTimestamps: [], // Return empty array for music |
| 236 | }; |
| 237 | } |
| 238 | |
| 239 | gcsUrl = await this.uploadToGCS(wavePath); |
| 240 | logger.info(`Uploaded audio to GCS: ${gcsUrl}`); |
| 241 | |
| 242 | const request: protos.google.cloud.speech.v1.ILongRunningRecognizeRequest = |
| 243 | { |
| 244 | audio: { uri: gcsUrl }, |
| 245 | config: { |
| 246 | encoding: |
| 247 | protos.google.cloud.speech.v1.RecognitionConfig.AudioEncoding |
| 248 | .LINEAR16, |
| 249 | sampleRateHertz: 16000, |
| 250 | languageCode: process.env.SPEECH_TO_TEXT_LANGUAGE || "en-US", |
| 251 | enableAutomaticPunctuation: true, |
| 252 | // model: "long", // Use 'long' model for better handling of longer audio |
| 253 | useEnhanced: false, // Set to false as 'long' model doesn't support enhanced version |
| 254 | metadata: { |
| 255 | interactionType: "DISCUSSION", // Reverted from "VIDEO" |
| 256 | microphoneDistance: "MIDFIELD", // Adjust if needed |
| 257 | recordingDeviceType: "RECORDING_DEVICE_TYPE_UNSPECIFIED", // Changed from "UNKNOWN" |
| 258 | }, |
| 259 | enableWordTimeOffsets: true, // Ensure this is true |
| 260 | enableWordConfidence: true, |
| 261 | maxAlternatives: 1, |
| 262 | profanityFilter: true, |
| 263 | diarizationConfig: undefined, // Explicitly undefined if not used |
| 264 | adaptation: { |
| 265 | phraseSetReferences: [], |
| 266 | customClasses: [], |
| 267 | }, |
| 268 | audioChannelCount: 1, |
| 269 | enableSeparateRecognitionPerChannel: false, |
| 270 | speechContexts: [ |
| 271 | { |
| 272 | phrases: [ |
| 273 | "video", |
| 274 | "youtube", |
| 275 | "subscribe", |
| 276 | "like", |
| 277 | "comment", |
| 278 | "tutorial", |
| 279 | "review", |
| 280 | "vlog", |
| 281 | "channel", |
| 282 | ], |
| 283 | boost: 20, |
| 284 | }, |
| 285 | ], |
| 286 | }, |
| 287 | }; |
| 288 | |
| 289 | const [operation] = await this.speechClient.longRunningRecognize(request); |
| 290 | const [response] = await operation.promise(); |
| 291 | logger.info(`Transcription response received.`); // Simplified log |
| 292 | |
| 293 | // Clean up GCS file immediately after response |
| 294 | if (gcsUrl) { |
| 295 | await this.deleteFromGCS(gcsUrl); |
| 296 | gcsUrl = undefined; // Mark as deleted |
| 297 | } |
| 298 | // Clean up local WAV file |
| 299 | if (wavePath) { |
| 300 | await unlink(wavePath).catch((err: any) => |
| 301 | logger.warn( |
| 302 | `Failed to delete WAV file after transcription: ${err.message}` |
| 303 | ) |
| 304 | ); |
| 305 | wavePath = undefined; // Mark as deleted |
| 306 | } |
| 307 | |
| 308 | if (!response.results || response.results.length === 0) { |
| 309 | logger.warn("No transcription results found in response."); |
| 310 | throw new AppError( |
| 311 | StatusCodes.BAD_REQUEST, |
| 312 | "No transcription results found" |
| 313 | ); |
| 314 | } |
| 315 | |
| 316 | // Process results to extract text and word timestamps |
| 317 | let fullText = ""; |
| 318 | const wordTimestamps: WordTimestamp[] = []; |
| 319 | let totalConfidence = 0; |
| 320 | let wordCount = 0; |
| 321 | |
| 322 | response.results.forEach((result) => { |
| 323 | if (result.alternatives && result.alternatives[0]) { |
| 324 | const alternative = result.alternatives[0]; |
| 325 | fullText += (alternative.transcript || "").trim() + " "; // Trim individual transcripts and add space |
| 326 | |
| 327 | if (alternative.words) { |
| 328 | alternative.words.forEach((wordInfo) => { |
| 329 | if (wordInfo.word && wordInfo.startTime && wordInfo.endTime) { |
| 330 | // Convert proto time {seconds, nanos} to seconds (float) |
| 331 | const startTimeSec = |
| 332 | (wordInfo.startTime.seconds |
| 333 | ? Number(wordInfo.startTime.seconds) |
| 334 | : 0) + |
| 335 | (wordInfo.startTime.nanos |
| 336 | ? wordInfo.startTime.nanos / 1e9 |
| 337 | : 0); |
| 338 | const endTimeSec = |
| 339 | (wordInfo.endTime.seconds |
| 340 | ? Number(wordInfo.endTime.seconds) |
| 341 | : 0) + |
| 342 | (wordInfo.endTime.nanos ? wordInfo.endTime.nanos / 1e9 : 0); |
| 343 | |
| 344 | wordTimestamps.push({ |
| 345 | word: wordInfo.word, |
| 346 | startTime: startTimeSec, |
| 347 | endTime: endTimeSec, |
| 348 | }); |
| 349 | |
| 350 | // Use word confidence if available |
| 351 | totalConfidence += wordInfo.confidence || 0; |
| 352 | wordCount++; |
| 353 | } |
| 354 | }); |
| 355 | } |
| 356 | } |
| 357 | }); |
| 358 | |
| 359 | fullText = fullText.trim(); // Remove final trailing space |
| 360 | // Use overall result confidence if word confidence wasn't available everywhere |
| 361 | const averageConfidence = |
| 362 | wordCount > 0 |
| 363 | ? totalConfidence / wordCount |
| 364 | : response.results[0]?.alternatives?.[0]?.confidence || 0; |
| 365 | |
| 366 | if (!fullText) { |
| 367 | logger.warn("Empty transcription text after processing results."); |
| 368 | throw new AppError( |
| 369 | StatusCodes.BAD_REQUEST, |
| 370 | "Empty transcription result" |
| 371 | ); |
| 372 | } |
| 373 | |
| 374 | logger.info( |
| 375 | `Transcription successful. Text length: ${ |
| 376 | fullText.length |
| 377 | }, Word count: ${ |
| 378 | wordTimestamps.length |
| 379 | }, Avg Confidence: ${averageConfidence.toFixed(3)}` |
| 380 | ); |
| 381 | |
| 382 | return { |
| 383 | text: fullText, |
| 384 | confidence: averageConfidence, |
| 385 | isMusic: false, |
| 386 | wordTimestamps: wordTimestamps, |
| 387 | }; |
| 388 | } catch (error: any) { |
| 389 | // Ensure cleanup happens even on error |
| 390 | await Promise.allSettled([ |
| 391 | wavePath ? unlink(wavePath).catch(() => {}) : Promise.resolve(), |
| 392 | gcsUrl ? this.deleteFromGCS(gcsUrl) : Promise.resolve(), |
| 393 | ]); |
| 394 | |
| 395 | logger.error(`Error in transcribe function: ${error.message}`, { |
| 396 | stack: error.stack, |
| 397 | error, |
| 398 | }); |
| 399 | |
| 400 | // Re-throw specific known errors or a generic one |
| 401 | if (error instanceof AppError) { |
| 402 | throw error; |
| 403 | } |
| 404 | throw new AppError( |
| 405 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 406 | `Failed to transcribe audio: ${ |
| 407 | error.message || "Unknown transcription error" |
| 408 | }` |
| 409 | ); |
| 410 | } |
| 411 | } |
| 412 | } |