# -*- coding: utf-8 -*-"""Command Line Interface for AudinotaThis module provides the CLI for audio transcription using Python Fire."""importiofrompathlibimportPathfromtypingimportOptionalimportfirefromaudinota.apiimporttranscribe_audio_in_parallel
[docs]defresolve_output_path(input_path:str,output_path:Optional[str],overwrite:bool,)->Path:""" Resolve the final output file path based on input parameters. :param input_path: Path to the input audio file :param output_path: Optional output path (file or directory) :param overwrite: Whether to overwrite existing files :return: Resolved output file path :raises FileExistsError: If output file exists and overwrite is False """input_file=Path(input_path).absolute()ifoutput_pathisNone:# Case 1: No output specified - create .txt next to input filebase_name=input_file.stemoutput_dir=input_file.parentreturn_find_unique_filename(output_dir,base_name,".txt")output_path_obj=Path(output_path)ifoutput_path_obj.is_dir():# Case 2: Output is a directory - create .txt file in that directorybase_name=input_file.stemreturn_find_unique_filename(output_path_obj,base_name,".txt")# Case 3: Output is a file pathifoutput_path_obj.exists()andnotoverwrite:raiseFileExistsError(f"Output file '{output_path_obj}' already exists. ""Use --overwrite to overwrite the existing file.")returnoutput_path_obj
def_find_unique_filename(directory:Path,base_name:str,extension:str,)->Path:""" Find a unique filename by appending numbers if necessary. :param directory: Directory where the file will be created :param base_name: Base name of the file (without extension) :param extension: File extension (including the dot) :return: Path to a unique filename """# Try the base name firstcandidate=directory/f"{base_name}{extension}"ifnotcandidate.exists():returncandidate# Try numbered variations (01, 02, 03, ...)counter=1whileTrue:candidate=directory/f"{base_name}_{counter:02d}{extension}"ifnotcandidate.exists():returncandidatecounter+=1# Safety check to avoid infinite loopifcounter>999:raiseRuntimeError("Cannot find unique filename after 999 attempts")
[docs]classAudioTranscriber:""" Audio transcription command-line interface. This class provides the main CLI functionality for transcribing audio files using the audinota library with intelligent parallel processing. """
[docs]deftranscribe(self,input:str,output:Optional[str]=None,overwrite:bool=False,)->None:""" Transcribe an audio file to text using parallel processing. :param input: Path to the input audio file (required) :param output: Path to output file or directory (optional) :param overwrite: Whether to overwrite existing output files Example usage: audinota transcribe --input="podcast.mp3" audinota transcribe --input="lecture.mp4" --output="transcripts/" audinota transcribe --input="interview.wav" --output="result.txt" --overwrite """# Validate input file existsinput_path=Path(input)ifnotinput_path.exists():raiseFileNotFoundError(f"Input audio file not found: {input}")ifnotinput_path.is_file():raiseValueError(f"Input path is not a file: {input}")print(f"🎵 Transcribing audio file: {input_path}")# Resolve output path with all the logictry:output_path=resolve_output_path(input,output,overwrite)print(f"📝Output will be saved to: {output_path}")exceptFileExistsErrorase:print(f"❌Error: {e}")returntry:# Load audio fileprint("🔄Loading audio data...")audio_bytes=input_path.read_bytes()audio_stream=io.BytesIO(audio_bytes)# Perform transcriptionprint("🚀Starting parallel transcription...")transcribed_text=transcribe_audio_in_parallel(audio_stream)# Save to output fileprint("💾Saving transcription...")try:output_path.write_text(transcribed_text,encoding="utf-8")exceptFileNotFoundError:output_path.parent.mkdir(parents=True,exist_ok=True)output_path.write_text(transcribed_text,encoding="utf-8")print(f"✅Transcription completed successfully!")print(f"📄Output saved to: file://{output_path}")print(f"📊Text length: {len(transcribed_text)} characters")exceptExceptionase:print(f"❌ Transcription failed: {e}")raise
[docs]defmain():""" Main entry point for the audinota CLI. This function is called when the 'audinota' command is run from the terminal. """fire.Fire(AudioTranscriber)