from typing import List, Literal import numpy as np import torchaudio from datasets import concatenate_datasets, load_dataset from pandas import concat, read_csv from tqdm import tqdm def get_audio_length(file_path: str) -> float: """ 計錄音總長度 """ metadata = torchaudio.info(file_path) return metadata.num_frames / metadata.sample_rate def get_info(subsets: List[str] | Literal["saamgwokjinji", "seoiwuzyun"]) -> None: """ 計音頻長度、字數、平均字數、中位數字數、覆蓋字數、平均語速 """ if not isinstance(subsets, list): subsets = [subsets] datasets = [] for subset in subsets: dataset = load_dataset('audiofolder', data_dir=f'./opus/{subset}', split='train') datasets.append(dataset) if len(datasets) > 1: dataset = concatenate_datasets(datasets) else: dataset = datasets[0] # List to store individual audio durations durations = [] total_duration = 0 for item in tqdm(dataset): file_path = item['audio']['path'] duration = get_audio_length(file_path) durations.append(duration) total_duration += duration # Calculate statistics min_duration = min(durations) max_duration = max(durations) avg_duration = np.mean(durations) median_duration = np.median(durations) # Print results print(f"Statistics for: {' & '.join(subsets)}") print(f"Total audio duration: {total_duration / 3600:.2f} hours") print(f"Total audio duration: {total_duration / 60:.2f} minutes") print(f"Minimum audio duration: {min_duration:.3f} seconds") print(f"Maximum audio duration: {max_duration:.3f} seconds") print(f"Average audio duration: {avg_duration:.3f} seconds") print(f"Median audio duration: {median_duration:.3f} seconds") # Concatenate metadata DataFrames metadata_list = [] for subset in subsets: metadata = read_csv(f'./opus/{subset}/metadata.csv') metadata_list.append(metadata) if len(metadata_list) > 1: metadata = concat(metadata_list) else: metadata = metadata_list[0] # Calculate total number of characters total_characters = metadata['transcription'].str.len().sum() # Calculate mean number of characters mean_characters = metadata['transcription'].str.len().mean() # Calculate median number of characters median_characters = metadata['transcription'].str.len().median() # Get unique characters unique_characters = set(''.join(metadata['transcription'])) # Print results print(f"Total characters: {total_characters}") print(f"Mean characters per transcription: {mean_characters:.2f}") print(f"Median characters per transcription: {median_characters}") print(f"Number of unique characters: {len(unique_characters)}") print(f"Unique characters: {''.join(sorted(unique_characters))}") print(f"Average speech rate: {total_characters / total_duration:.2f} characters per second") print("-" * 20) if __name__ == '__main__': get_info('saamgwokjinji') get_info('seoiwuzyun') get_info(['saamgwokjinji', 'seoiwuzyun'])