#!/usr/bin/env python3 import json from pathlib import Path from gtts import gTTS import pandas as pd def create_audio_directory(): audio_dir = Path("audio") if not audio_dir.exists(): audio_dir.mkdir(parents=True) return audio_dir def generate_mp3_from_text(text, output_path, lang="vi"): try: tts = gTTS(text=text, lang=lang, slow=False) tts.save(output_path) return True except Exception as e: print(f"Error generating audio for '{text}': {e}") return False def process_dataset(jsonl_file="vietnamese_ipa_dataset.jsonl"): create_audio_directory() # Read JSONL file records = [] with open(jsonl_file, "r", encoding="utf-8") as f: for line in f: records.append(json.loads(line)) df = pd.DataFrame(records) total = len(df) success = 0 failed = [] print(f"Processing {total} words from {jsonl_file}...") print("-" * 50) for idx, row in df.iterrows(): word = row["word"] ipa = row["ipa"] audio_path = row["audio"]["path"] if isinstance(row["audio"], dict) else row["audio"] full_path = Path(audio_path) print(f"[{idx + 1}/{total}] Generating: {word} [{ipa}]") if generate_mp3_from_text(word, str(full_path)): success += 1 print(f" ✓ Saved to: {full_path}") else: failed.append(word) print(" ✗ Failed to generate audio") print("-" * 50) print("\nResults:") print(f" Successfully generated: {success}/{total}") if failed: print(f" Failed words: {', '.join(failed)}") return success, failed def add_new_word(word, ipa, jsonl_file="vietnamese_ipa_dataset.jsonl"): audio_filename = f"audio/{word.replace(' ', '_')}.mp3" # Create new record record = { "word": word, "ipa": ipa, "audio": { "path": audio_filename, "sampling_rate": 22050 } } # Append to JSONL file with open(jsonl_file, "a", encoding="utf-8") as f: f.write(json.dumps(record, ensure_ascii=False) + "\n") create_audio_directory() if generate_mp3_from_text(word, audio_filename): print(f"Added '{word}' with IPA [{ipa}] and generated audio") return True else: print(f"Added '{word}' to CSV but failed to generate audio") return False def display_dataset(jsonl_file="vietnamese_ipa_dataset.jsonl"): # Read JSONL file records = [] with open(jsonl_file, "r", encoding="utf-8") as f: for line in f: records.append(json.loads(line)) df = pd.DataFrame(records) print("\nVietnamese IPA Dataset:") print("-" * 70) print(f"{'Word':<20} {'IPA':<30} {'Audio File':<20}") print("-" * 70) for _, row in df.iterrows(): audio_path = row["audio"]["path"] if isinstance(row["audio"], dict) else row["audio"] print(f"{row['word']:<20} {row['ipa']:<30} {audio_path:<20}") print("-" * 70) print(f"Total entries: {len(df)}") if __name__ == "__main__": import sys if len(sys.argv) > 1: if sys.argv[1] == "generate": process_dataset() elif sys.argv[1] == "display": display_dataset() elif sys.argv[1] == "add" and len(sys.argv) >= 4: word = sys.argv[2] ipa = sys.argv[3] add_new_word(word, ipa) else: print("Usage:") print(" python generate_audio.py generate # Generate all MP3 files") print(" python generate_audio.py display # Display dataset") print(" python generate_audio.py add # Add new word") else: print("Generating audio files for Vietnamese IPA dataset...") process_dataset() print("\nDataset overview:") display_dataset()