File size: 3,601 Bytes
39da493
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python3
"""
Extract audio from Nigerian Common Voice parquet files and save as WAV.
"""
import os
from pathlib import Path
import pandas as pd
import json

BASE_DIR = Path.home() / "voice-training"
DATASETS_DIR = BASE_DIR / "datasets" / "nigerian_cv"
OUTPUT_DIR = BASE_DIR / "prepared_data"

LANGUAGES = ["yoruba", "hausa", "igbo"]  # Skip English for Nigerian TTS

def extract_language(lang: str, max_samples: int = 500):
    """Extract audio files for a language."""
    lang_dir = DATASETS_DIR / lang
    output_dir = OUTPUT_DIR / lang / "wavs"
    output_dir.mkdir(parents=True, exist_ok=True)
    
    manifest = []
    total_extracted = 0
    
    print(f"\n=== Extracting {lang.upper()} ===")
    
    for split in ["train", "validation"]:
        parquet_file = lang_dir / f"{split}-00000-of-00001.parquet"
        if not parquet_file.exists():
            continue
        
        print(f"  Processing {split}...")
        df = pd.read_parquet(parquet_file)
        
        for idx, row in df.iterrows():
            if total_extracted >= max_samples:
                break
                
            audio_data = row.get('audio')
            sentence = row.get('sentence', '')
            
            if audio_data is None or not sentence:
                continue
            
            # Audio data structure: {'array': [...], 'sampling_rate': 16000}
            if isinstance(audio_data, dict):
                array = audio_data.get('array')
                sr = audio_data.get('sampling_rate', 16000)
                
                if array is not None:
                    import numpy as np
                    import soundfile as sf
                    
                    audio_array = np.array(array).astype(np.float32)
                    
                    # Save audio
                    filename = f"{lang}_{split}_{idx:05d}.wav"
                    filepath = output_dir / filename
                    sf.write(str(filepath), audio_array, sr)
                    
                    # Add to manifest
                    manifest.append({
                        "audio_file": str(filepath),
                        "text": sentence.strip(),
                        "language": lang,
                        "speaker": row.get('client_id', 'unknown')[:8]
                    })
                    
                    total_extracted += 1
                    
                    if total_extracted % 100 == 0:
                        print(f"    Extracted {total_extracted} samples...")
        
        if total_extracted >= max_samples:
            break
    
    # Save manifest
    manifest_file = OUTPUT_DIR / lang / "manifest.json"
    with open(manifest_file, 'w', encoding='utf-8') as f:
        json.dump(manifest, f, indent=2, ensure_ascii=False)
    
    print(f"  Total extracted: {total_extracted} samples")
    print(f"  Manifest saved to: {manifest_file}")
    
    return total_extracted

def main():
    print("=== Extracting Nigerian Audio for TTS Training ===")
    
    # Install soundfile if needed
    try:
        import soundfile
    except ImportError:
        os.system("pip install soundfile")
        import soundfile
    
    total = 0
    for lang in LANGUAGES:
        if (DATASETS_DIR / lang).exists():
            count = extract_language(lang, max_samples=500)  # 500 samples per lang for quick training
            total += count
    
    print(f"\n=== Extraction Complete ===")
    print(f"Total samples extracted: {total}")
    print(f"Output directory: {OUTPUT_DIR}")

if __name__ == "__main__":
    main()