File size: 3,104 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
#!/usr/bin/env python3
"""
Extract audio from Nigerian Common Voice parquet files - MP3 bytes format.
"""
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"]

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 is {'bytes': b'...'} - raw MP3 bytes
            if isinstance(audio_data, dict) and 'bytes' in audio_data:
                audio_bytes = audio_data['bytes']
                
                # Save as MP3 (faster than converting to WAV)
                filename = f"{lang}_{split}_{idx:05d}.mp3"
                filepath = output_dir / filename
                
                with open(filepath, 'wb') as f:
                    f.write(audio_bytes)
                
                # Add to manifest
                manifest.append({
                    "audio_file": str(filepath),
                    "text": sentence.strip(),
                    "language": lang,
                    "speaker": str(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 ===")
    
    total = 0
    for lang in LANGUAGES:
        if (DATASETS_DIR / lang).exists():
            count = extract_language(lang, max_samples=500)
            total += count
    
    print(f"\n=== Extraction Complete ===")
    print(f"Total samples extracted: {total}")
    print(f"Output directory: {OUTPUT_DIR}")

if __name__ == "__main__":
    main()