File size: 5,275 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#!/usr/bin/env python3
"""
Fine-tune XTTS v2 for Nigerian Languages (Yoruba, Hausa, Igbo, Pidgin).

This script uses Coqui TTS to fine-tune the XTTS model for better
Nigerian language support.
"""
import os
import sys
import json
from pathlib import Path
import torch

# Check GPU
print("=" * 60)
print("XTTS Nigerian Languages Fine-tuning")
print("=" * 60)
print(f"\nPyTorch: {torch.__version__}")
print(f"CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
    print(f"GPU: {torch.cuda.get_device_name(0)}")
    mem = torch.cuda.get_device_properties(0).total_memory / 1024**3
    print(f"GPU Memory: {mem:.1f} GB")
else:
    print("WARNING: No GPU found. Training will be very slow on CPU.")

BASE_DIR = Path.home() / "voice-training"
PREPARED_DIR = BASE_DIR / "prepared_data"
OPENSLR_DIR = BASE_DIR / "datasets" / "openslr_yoruba"
OUTPUT_DIR = BASE_DIR / "output"

def check_data():
    """Check available training data."""
    print("\n=== Available Training Data ===")
    
    total_files = 0
    
    # Check Nigerian CV data
    for lang in ["yoruba", "hausa", "igbo"]:
        manifest_file = PREPARED_DIR / lang / "manifest.json"
        if manifest_file.exists():
            with open(manifest_file) as f:
                data = json.load(f)
            print(f"  {lang.upper()}: {len(data)} samples")
            total_files += len(data)
    
    # Check OpenSLR Yoruba
    if OPENSLR_DIR.exists():
        wav_count = len(list(OPENSLR_DIR.glob("*.wav")))
        print(f"  OpenSLR Yoruba: {wav_count} high-quality WAV files")
        total_files += wav_count
    
    print(f"\nTotal audio files: {total_files}")
    return total_files > 0

def prepare_xtts_dataset():
    """Prepare dataset in XTTS format."""
    print("\n=== Preparing XTTS Dataset ===")
    
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    
    all_samples = []
    
    # Load Nigerian CV manifests
    for lang in ["yoruba", "hausa", "igbo"]:
        manifest_file = PREPARED_DIR / lang / "manifest.json"
        if manifest_file.exists():
            with open(manifest_file) as f:
                samples = json.load(f)
            for s in samples:
                s['lang_code'] = lang[:2]  # yo, ha, ig
            all_samples.extend(samples)
    
    # Load OpenSLR Yoruba
    if OPENSLR_DIR.exists():
        tsv_file = OPENSLR_DIR / "line_index.tsv"
        if tsv_file.exists():
            with open(tsv_file, 'r', encoding='utf-8') as f:
                for line in f:
                    parts = line.strip().split('\t')
                    if len(parts) >= 2:
                        wav_file = OPENSLR_DIR / f"{parts[0]}.wav"
                        if wav_file.exists():
                            all_samples.append({
                                "audio_file": str(wav_file),
                                "text": parts[1],
                                "language": "yoruba",
                                "lang_code": "yo"
                            })
    
    # Save combined dataset
    dataset_file = OUTPUT_DIR / "nigerian_tts_dataset.json"
    with open(dataset_file, 'w', encoding='utf-8') as f:
        json.dump(all_samples, f, indent=2, ensure_ascii=False)
    
    print(f"  Created dataset with {len(all_samples)} samples")
    print(f"  Saved to: {dataset_file}")
    
    return all_samples

def run_xtts_finetuning():
    """Run XTTS fine-tuning using Coqui TTS."""
    print("\n=== Starting XTTS Fine-tuning ===")
    
    try:
        from TTS.tts.configs.xtts_config import XttsConfig
        from TTS.tts.models.xtts import Xtts
        from TTS.utils.manage import ModelManager
        
        print("  TTS modules loaded successfully")
        
        # Download base XTTS model
        print("  Downloading base XTTS v2 model...")
        model_manager = ModelManager()
        
        # The model will be downloaded to ~/.local/share/tts/
        model_path = model_manager.download_model("tts_models/multilingual/multi-dataset/xtts_v2")
        print(f"  Model path: {model_path}")
        
        print("\n  To fine-tune XTTS, use the Coqui TTS training recipes:")
        print("  https://github.com/coqui-ai/TTS/tree/dev/recipes/ljspeech/xtts_v2")
        print("\n  Or use the XTTS fine-tuning demo:")
        print("  python -m TTS.demos.xtts_ft_demo")
        
        return True
        
    except Exception as e:
        print(f"  Error: {e}")
        return False

def main():
    if not check_data():
        print("ERROR: No training data found!")
        sys.exit(1)
    
    samples = prepare_xtts_dataset()
    
    if samples:
        print("\n" + "=" * 60)
        print("Dataset prepared! Next steps:")
        print("=" * 60)
        print(f"1. Dataset: {OUTPUT_DIR / 'nigerian_tts_dataset.json'}")
        print(f"2. Total samples: {len(samples)}")
        print("\nTo start training:")
        print("  python -m TTS.demos.xtts_ft_demo")
        print("\nOr for voice cloning (no training needed):")
        print("  from TTS.api import TTS")
        print("  tts = TTS('tts_models/multilingual/multi-dataset/xtts_v2')")
        print("  tts.tts_to_file('Hello', speaker_wav='your_voice.wav', language='en')")
    
    run_xtts_finetuning()

if __name__ == "__main__":
    main()