### GoogleASR Configuration Options and Examples Source: https://context7.com/guiguicdd/googlesttext/llms.txt Details the configuration options available for the GoogleASR function, including default values and their effects. Provides examples for customizing language, profanity filtering, and API keys. ```typescript interface IOptions { // Required: Path to FLAC audio file (16kHz, mono) audioFilepath: string; // Optional: Custom Google API key (default: Chromium API key) key?: string; // Optional: Client identifier (default: 'chromium') client?: 'client'; // Optional: Audio content type (default: 'audio/x-flac; rate=16000;') contentType?: 'audio/x-flac; rate=16000;'; // Optional: Language code (default: 'pt-br') // Supported: 'en-us', 'es-es', 'fr-fr', 'de-de', etc. language?: string; // Optional: Profanity filter (default: 0) // 0 = disabled, 1 = enabled (replaces profanity with ****) profanityFilter?: 0 | 1; // Optional: Output format (default: 'json') output?: 'json'; // Optional: Return raw response string (default: false) raw?: boolean; } // Example: English transcription with profanity filter const englishResult = await GoogleASR({ audioFilepath: './english_audio.flac', language: 'en-us', profanityFilter: 1 }); // Example: Spanish transcription with custom API key const spanishResult = await GoogleASR({ audioFilepath: './spanish_audio.flac', language: 'es-es', key: 'YOUR_CUSTOM_API_KEY' }); // Example: Get raw response for debugging const rawResult = await GoogleASR({ audioFilepath: './audio.flac', raw: true }); if (rawResult && rawResult.type === 'raw') { console.log('Raw API response:', rawResult.result); // Output: Raw API response: {"result":[{"alternative":[{"transcript":"...","confidence":0.95}],"final":true}]} } ``` -------------------------------- ### Complete Audio Transcription Workflow with GoogleASR Source: https://context7.com/guiguicdd/googlesttext/llms.txt An end-to-end TypeScript example demonstrating audio conversion using ffmpeg, transcription using GoogleASR, and error handling for a production-ready pattern. It includes input validation, file cleanup, and asynchronous operations. ```typescript import { exec } from 'child_process'; import { GoogleASR } from 'googlesttext'; import fs from 'fs'; class AudioTranscriber { async convert(inputPath: string, outputPath: string): Promise { return new Promise((resolve, reject) => { // Check if input file exists if (!fs.existsSync(inputPath)) { reject(new Error(`Input file not found: ${inputPath}`)); return; } const ffmpeg = exec( `ffmpeg -i ${inputPath} -acodec flac -ar 16000 -ac 1 ${outputPath}` ); ffmpeg.on('exit', code => { if (code === 0) { resolve(outputPath); } else { reject(new Error(`FFmpeg conversion failed with code ${code}`)); } }); }); } async transcribe(audioPath: string, language = 'pt-br'): Promise { try { const response = await GoogleASR({ audioFilepath: audioPath, language: language, profanityFilter: 0 }); if (response !== null && response.type === 'success') { return response.alternative[0].transcript; } return null; } catch (error) { console.error('Transcription error:', error); throw error; } } async processAudio(inputFile: string): Promise { const outputFile = inputFile.replace(/\.[^.]+$/, '.flac'); try { console.log('Converting audio...'); await this.convert(inputFile, outputFile); console.log('Transcribing audio...'); const text = await this.transcribe(outputFile); // Cleanup converted file if (fs.existsSync(outputFile)) { fs.unlinkSync(outputFile); } return text; } catch (error) { console.error('Processing failed:', error); return null; } } } // Usage const transcriber = new AudioTranscriber(); transcriber.processAudio('./audios/audio.m4a').then(result => { if (result) { console.log('Final transcription:', result); // Output: Final transcription: "este é um teste de transcrição" } else { console.log('Transcription failed or returned no results'); } }); ``` -------------------------------- ### Audio Transcription Workflow Source: https://context7.com/guiguicdd/googlesttext/llms.txt This section demonstrates an end-to-end example of converting audio, transcribing it using Google Speech-to-Text, and handling potential errors in a production-ready pattern. ```APIDOC ## Audio Transcription Workflow Example This workflow demonstrates the process of converting an audio file to a format suitable for speech-to-text, transcribing the audio, and then cleaning up intermediate files. ### Key Steps 1. **Audio Conversion**: Convert input audio to FLAC format (16kHz, mono) using FFmpeg. 2. **Transcription**: Utilize the `GoogleASR` function to transcribe the converted audio file. 3. **Cleanup**: Remove the temporary FLAC file after transcription. ### Usage Example ```typescript import { GoogleASR } from 'googlesttext'; import fs from 'fs'; class AudioTranscriber { async convert(inputPath: string, outputPath: string): Promise { // ... implementation for audio conversion using ffmpeg ... return outputPath; } async transcribe(audioPath: string, language = 'pt-br'): Promise { const response = await GoogleASR({ audioFilepath: audioPath, language: language, profanityFilter: 0 }); if (response !== null && response.type === 'success') { return response.alternative[0].transcript; } return null; } async processAudio(inputFile: string): Promise { const outputFile = inputFile.replace(/\.[^.]+$/, '.flac'); try { console.log('Converting audio...'); await this.convert(inputFile, outputFile); console.log('Transcribing audio...'); const text = await this.transcribe(outputFile); if (fs.existsSync(outputFile)) { fs.unlinkSync(outputFile); } return text; } catch (error) { console.error('Processing failed:', error); return null; } } } // Example usage: const transcriber = new AudioTranscriber(); transcriber.processAudio('./audios/audio.m4a').then(result => { if (result) { console.log('Final transcription:', result); } else { console.log('Transcription failed or returned no results'); } }); ``` ``` -------------------------------- ### Audio Conversion Helper: Convert Audio to FLAC using FFmpeg (TypeScript) Source: https://context7.com/guiguicdd/googlesttext/llms.txt A utility function that converts audio files from various formats (M4A, MP3, WAV, etc.) to the FLAC format required by the Google Speech API. It utilizes the FFmpeg command-line tool and returns a Promise that resolves with the output FLAC file path or rejects if FFmpeg fails. ```typescript import { exec } from 'child_process'; function audioParser(inputFile: string, outputFile: string): Promise { return new Promise((resolve, reject) => { const ffmpegProcess = exec( `ffmpeg -i ${inputFile} -acodec flac -ar 16000 -ac 1 ${outputFile}` ); ffmpegProcess.on('exit', code => { if (code === 0) { resolve(outputFile); } else { reject(`FFmpeg failed with exit code: ${code}`); } }); }); } // Convert M4A to FLAC and transcribe async function transcribeAudio() { try { const flacFile = await audioParser('./audio.m4a', './audio.flac'); console.log('Audio converted:', flacFile); const result = await GoogleASR({ audioFilepath: flacFile }); if (result && result.type === 'success') { return result.alternative[0].transcript; } return null; } catch (error) { console.error('Transcription failed:', error); throw error; } } // Usage transcribeAudio().then(text => { console.log('Transcribed text:', text); // Output: Transcribed text: "hello this is a test recording" }); ``` -------------------------------- ### GoogleASR Configuration Options Source: https://context7.com/guiguicdd/googlesttext/llms.txt Explore the available configuration options for the `GoogleASR` function, including parameters for language, profanity filtering, API keys, and output formats. ```APIDOC ## GoogleASR Configuration Options The `GoogleASR` function accepts an `IOptions` object to customize its behavior. Below are the available options: ### Interface `IOptions` ```typescript interface IOptions { // Required: Path to FLAC audio file (16kHz, mono) audioFilepath: string; // Optional: Custom Google API key (default: Chromium API key) key?: string; // Optional: Client identifier (default: 'chromium') client?: 'client'; // Optional: Audio content type (default: 'audio/x-flac; rate=16000;') contentType?: 'audio/x-flac; rate=16000;'; // Optional: Language code (default: 'pt-br') // Supported: 'en-us', 'es-es', 'fr-fr', 'de-de', etc. language?: string; // Optional: Profanity filter (default: 0) // 0 = disabled, 1 = enabled (replaces profanity with ****) profanityFilter?: 0 | 1; // Optional: Output format (default: 'json') output?: 'json'; // Optional: Return raw response string (default: false) raw?: boolean; } ``` ### Usage Examples **1. English Transcription with Profanity Filter Enabled:** ```typescript const englishResult = await GoogleASR({ audioFilepath: './english_audio.flac', language: 'en-us', profanityFilter: 1 }); ``` **2. Spanish Transcription with Custom API Key:** ```typescript const spanishResult = await GoogleASR({ audioFilepath: './spanish_audio.flac', language: 'es-es', key: 'YOUR_CUSTOM_API_KEY' }); ``` **3. Get Raw API Response for Debugging:** ```typescript const rawResult = await GoogleASR({ audioFilepath: './audio.flac', raw: true }); if (rawResult && rawResult.type === 'raw') { console.log('Raw API response:', rawResult.result); // Example Output: Raw API response: {"result":[{"alternative":[{"transcript":"...","confidence":0.95}],"final":true}]} } ``` ``` -------------------------------- ### Handle GoogleASR Response Types in TypeScript Source: https://context7.com/guiguicdd/googlesttext/llms.txt Demonstrates how to process different response types from the GoogleASR function, such as success, nothing, raw, and null. It includes accessing transcription details, handling empty results, and managing raw output. The code requires the GoogleASR function and assumes audio files are provided. ```typescript // Type 1: Success response with transcription const successResponse = await GoogleASR({ audioFilepath: './audio.flac' }); if (successResponse && successResponse.type === 'success') { // Access transcript and confidence const transcript = successResponse.alternative[0].transcript; const confidence = successResponse.alternative[0].confidence; const isFinal = successResponse.final; console.log(`Text: ${transcript} (${confidence * 100}% confident)`); // Output: Text: hello world (95% confident) } // Type 2: Nothing response (empty result) const emptyResponse = await GoogleASR({ audioFilepath: './silent.flac' }); if (emptyResponse && emptyResponse.type === 'nothing') { console.log('No speech detected, result:', emptyResponse.result); // Output: No speech detected, result: [] } // Type 3: Raw response (when raw: true) const rawResponse = await GoogleASR({ audioFilepath: './audio.flac', raw: true }); if (rawResponse && rawResponse.type === 'raw') { console.log('Raw string:', rawResponse.result); // Output: Raw string: {"result":[...]}...{"result":[]} } // Type 4: Null response (error or no transcription) const nullResponse = await GoogleASR({ audioFilepath: './corrupt.flac' }); if (nullResponse === null) { console.log('Transcription failed or returned no valid results'); } ``` ```typescript // Complete error handling pattern async function safeTranscribe(filePath: string): Promise { try { const result = await GoogleASR({ audioFilepath: filePath }); if (result === null) { console.error('Null response received'); return null; } switch (result.type) { case 'success': return result.alternative[0].transcript; case 'nothing': console.warn('No speech detected in audio'); return null; case 'raw': console.log('Raw response (should not happen with raw: false)'); return null; default: return null; } } catch (error) { console.error('Transcription error:', error); return null; } } ``` -------------------------------- ### GoogleASR Function: Transcribe Audio to Text (TypeScript) Source: https://context7.com/guiguicdd/googlesttext/llms.txt Converts an audio file (FLAC format, 16kHz) to text using the Google Speech Recognition API. It supports language selection, profanity filtering, custom API keys, and raw response options. The function returns a structured object with transcription results or null if no transcription is available. ```typescript import { GoogleASR } from 'googlesttext'; // Basic usage with Portuguese audio const result = await GoogleASR({ audioFilepath: './audio.flac' }); if (result !== null && result.type === 'success') { console.log('Transcript:', result.alternative[0].transcript); console.log('Confidence:', result.alternative[0].confidence); // Output: Transcript: "olá mundo" // Output: Confidence: 0.95 } // Advanced usage with custom options const customResult = await GoogleASR({ audioFilepath: './audio.flac', language: 'en-us', profanityFilter: 1, key: 'YOUR_API_KEY', raw: false }); // Handle different response types if (customResult === null) { console.error('No transcription available'); } else if (customResult.type === 'nothing') { console.log('Empty result:', customResult.result); } else if (customResult.type === 'raw') { console.log('Raw response:', customResult.result); } else if (customResult.type === 'success') { // Access all alternatives with confidence scores customResult.alternative.forEach((alt, idx) => { console.log(`Alternative ${idx + 1}:`, alt.transcript, `(${alt.confidence})`); }); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.