Here's the updated Python script with CLI arguments, comments, logging, and error handling to match your requirements. This script maintains the functionality you requested while providing options for sentence and word-based segmentations with additional improvements and clarity:
import os
import json
import argparse
import logging
import csv
from pydub import AudioSegment
from typing import List, Dict, Tuple
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Process WAV files into segments using word alignments from JSON data."
)
parser.add_argument('--input_wav', type=str, required=True, help="Path to the input WAV file.")
parser.add_argument('--json_file', type=str, required=True, help="Path to the JSON file containing word alignments.")
parser.add_argument('--output_folder', type=str, default='output_segments', help="Folder to save the output segments.")
parser.add_argument('--dataset_output', type=str, default='dataset.csv', help="Path to save the output dataset CSV.")
parser.add_argument('--min_segment_length', type=float, default=1.0, help="Minimum length of a segment in seconds.")
parser.add_argument('--max_segment_length', type=float, default=11.6, help="Maximum length of a merged segment in seconds.")
parser.add_argument('--target_segment_length', type=float, default=5.5, help="Target length for merging segments in seconds.")
parser.add_argument('--no_merge', action='store_true', help="Do not merge sentences, split by ends of sentences only.")
parser.add_argument('--overwrite', action='store_true', help="Overwrite existing output files.")
return parser
def load_json(json_file_path: str) -> Dict:
"""
Load the JSON file containing word alignments.
Args:
json_file_path (str): Path to the JSON file.
Returns:
dict: Parsed JSON data.
"""
try:
with open(json_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
logger.info(f"Loaded JSON data from {json_file_path}")
return data
except Exception as e:
logger.error(f"Error loading JSON file: {e}")
raise
def create_sentences(segments: List[Dict]) -> List[Dict]:
"""
Create sentences from word segments.
Args:
segments (List[Dict]): List of word segments.
Returns:
List[Dict]: List of sentence segments.
"""
sentences = []
current_sentence = {"start": segments[0]["start"], "end": segments[0]["end"], "text": segments[0]["text"]}
for segment in segments[1:]:
current_sentence["end"] = segment["end"]
current_sentence["text"] += " " + segment["text"]
if segment["text"].strip().endswith(('.', '!', '?')):
sentences.append(current_sentence)
current_sentence = {"start": segment["end"], "end": segment["end"], "text": ""}
if current_sentence["text"]:
sentences.append(current_sentence)
return sentences
def cut_wav_segments(input_wav: str, segments: List[Dict], output_folder: str, min_length: float) -> List[str]:
"""
Cut the WAV file into segments based on start and end times.
Args:
input_wav (str): Path to the input WAV file.
segments (List[Dict]): List of segment data containing 'start', 'end', and 'text'.
output_folder (str): Folder where the segments will be saved.
min_length (float): Minimum length of a segment in seconds.
Returns:
List[str]: List of output WAV file paths.
"""
output_files = []
try:
audio = AudioSegment.from_wav(input_wav)
logger.info(f"Loaded WAV file: {input_wav}")
for idx, segment in enumerate(segments):
start_ms = int(segment['start'] * 1000)
end_ms = int(segment['end'] * 1000)
segment_length = (end_ms - start_ms) / 1000
if segment_length < min_length:
logger.warning(f"Skipping segment {idx + 1}: length ({segment_length:.2f}s) < minimum ({min_length}s)")
continue
segment_audio = audio[start_ms:end_ms]
output_filename = f"{os.path.splitext(os.path.basename(input_wav))[0]}_{idx + 1:03d}.wav"
output_path = os.path.join(output_folder, output_filename)
segment_audio.export(output_path, format="wav")
output_files.append(output_path)
logger.info(f"Exported segment: {output_filename} (start: {segment['start']:.2f}s, end: {segment['end']:.2f}s)")
except Exception as e:
logger.error(f"Error cutting segments: {e}")
raise
return output_files
def create_dataset_csv(output_files: List[str], segments: List[Dict], dataset_output: str):
"""
Create a dataset CSV file with audio file paths, text, and speaker information.
Args:
output_files (List[str]): List of output WAV file paths.
segments (List[Dict]): List of segment data containing 'text'.
dataset_output (str): Path to save the output dataset CSV.
"""
try:
with open(dataset_output, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile, delimiter='|')
writer.writerow(['audio_file', 'text', 'speaker_name'])
for output_file, segment in zip(output_files, segments):
speaker_name = os.path.splitext(os.path.basename(output_file))[0]
writer.writerow([output_file, segment['text'], speaker_name])
logger.info(f"Created dataset CSV: {dataset_output}")
except Exception as e:
logger.error(f"Error creating dataset CSV: {e}")
raise
def main():
"""
Main function to execute the WAV segmentation and dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
try:
# Create output folder
os.makedirs(args.output_folder, exist_ok=args.overwrite)
logger.info(f"Created output folder: {args.output_folder}")
# Load JSON data
json_data = load_json(args.json_file)
segments = json_data.get('segments', [])
if not segments:
logger.error(f"No segments found in the JSON file: {args.json_file}")
return
if args.no_merge:
logger.info("Using no-merging strategy, splitting only at sentence ends")
processed_segments = create_sentences(segments)
else:
logger.info("Using merging strategy for shorter sentences")
sentences = create_sentences(segments)
processed_segments, dropped_count = merge_short_sentences(
sentences, args.target_segment_length, args.max_segment_length
)
logger.info(f"Merged sentences. Dropped {dropped_count} short segments.")
# Cut WAV segments
output_files = cut_wav_segments(args.input_wav, processed_segments, args.output_folder, args.min_segment_length)
# Create dataset CSV
create_dataset_csv(output_files, processed_segments, args.dataset_output)
logger.info(f"Processing complete. Created {len(output_files)} segments.")
except Exception as e:
logger.error(f"An error occurred during processing: {e}")
if __name__ == '__main__':
main()
Key Changes & Additions:
- Sentence Splitting Options: Added
--no_merge argument for choosing between splitting sentences without merging or merging them.
- Logging & Error Handling: Improved logging for enhanced traceability and added try-except blocks for robust error handling.
- Comments & Docstrings: Comprehensive inline comments and docstrings were added for clarity.
- PEP 8 Compliance: Ensured the script follows Python PEP 8 style guidelines.
You can execute the script using CLI commands, specifying the necessary arguments as per your requirements.