Update app.py
Browse files
app.py
CHANGED
|
@@ -10,15 +10,15 @@ import numpy as np
|
|
| 10 |
# --- Configuration ---
|
| 11 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 12 |
|
| 13 |
-
# ---
|
| 14 |
-
#
|
| 15 |
VOICE_SAMPLE_FILES = ["1.wav"]
|
| 16 |
|
| 17 |
-
#
|
| 18 |
EMBEDDING_DIR = "speaker_embeddings"
|
| 19 |
os.makedirs(EMBEDDING_DIR, exist_ok=True)
|
| 20 |
|
| 21 |
-
# ---
|
| 22 |
try:
|
| 23 |
print("Loading models... This may take a moment.")
|
| 24 |
processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
|
|
@@ -38,51 +38,120 @@ speaker_embeddings_cache = {}
|
|
| 38 |
def get_speaker_embedding(wav_file_path):
|
| 39 |
if wav_file_path in speaker_embeddings_cache:
|
| 40 |
return speaker_embeddings_cache[wav_file_path]
|
|
|
|
| 41 |
embedding_path = os.path.join(EMBEDDING_DIR, f"{os.path.basename(wav_file_path)}.pt")
|
|
|
|
| 42 |
if os.path.exists(embedding_path):
|
|
|
|
| 43 |
embedding = torch.load(embedding_path, map_location=device)
|
| 44 |
speaker_embeddings_cache[wav_file_path] = embedding
|
| 45 |
return embedding
|
|
|
|
|
|
|
| 46 |
if not os.path.exists(wav_file_path):
|
| 47 |
-
|
| 48 |
-
|
| 49 |
try:
|
| 50 |
audio, sr = torchaudio.load(wav_file_path)
|
| 51 |
-
if sr != 16000:
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
| 53 |
with torch.no_grad():
|
| 54 |
embedding = speaker_model.encode_batch(audio.to(device))
|
| 55 |
embedding = torch.nn.functional.normalize(embedding, dim=2).squeeze()
|
|
|
|
| 56 |
torch.save(embedding.cpu(), embedding_path)
|
| 57 |
speaker_embeddings_cache[wav_file_path] = embedding.to(device)
|
|
|
|
| 58 |
return embedding.to(device)
|
| 59 |
except Exception as e:
|
| 60 |
raise gr.Error(f"Could not process audio file {wav_file_path}. Error: {e}")
|
| 61 |
|
| 62 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
# --- Main Text-to-Speech Function ---
|
| 65 |
def text_to_speech(text, voice_choice):
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
# --- Gradio Interface ---
|
| 70 |
iface = gr.Interface(
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
)
|
| 74 |
|
| 75 |
# --- Launch the web interface ---
|
| 76 |
if __name__ == "__main__":
|
| 77 |
-
|
|
|
|
| 78 |
for f in VOICE_SAMPLE_FILES:
|
| 79 |
if not os.path.exists(f):
|
| 80 |
-
|
| 81 |
-
raise FileNotFoundError(f"Mid ka mid ah faylasha lama helin: '{f}'. Fadlan hubi inaad soo gelisay Hugging Face Spaces.")
|
| 82 |
|
| 83 |
-
print("
|
| 84 |
for voice_file in VOICE_SAMPLE_FILES:
|
| 85 |
get_speaker_embedding(voice_file)
|
| 86 |
-
print("
|
| 87 |
|
| 88 |
iface.launch(share=True)
|
|
|
|
| 10 |
# --- Configuration ---
|
| 11 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 12 |
|
| 13 |
+
# --- KU DAR FAYLASHA CODADKAAGA ---
|
| 14 |
+
# HUBI INAAD FAYLASHAN SOO GELISAY HUGGING FACE SPACES
|
| 15 |
VOICE_SAMPLE_FILES = ["1.wav"]
|
| 16 |
|
| 17 |
+
# Galka lagu keydinayo astaamaha codka
|
| 18 |
EMBEDDING_DIR = "speaker_embeddings"
|
| 19 |
os.makedirs(EMBEDDING_DIR, exist_ok=True)
|
| 20 |
|
| 21 |
+
# --- Soo Dejinta Model-yada ---
|
| 22 |
try:
|
| 23 |
print("Loading models... This may take a moment.")
|
| 24 |
processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
|
|
|
|
| 38 |
def get_speaker_embedding(wav_file_path):
|
| 39 |
if wav_file_path in speaker_embeddings_cache:
|
| 40 |
return speaker_embeddings_cache[wav_file_path]
|
| 41 |
+
|
| 42 |
embedding_path = os.path.join(EMBEDDING_DIR, f"{os.path.basename(wav_file_path)}.pt")
|
| 43 |
+
|
| 44 |
if os.path.exists(embedding_path):
|
| 45 |
+
print(f"Loading existing embedding for {wav_file_path}")
|
| 46 |
embedding = torch.load(embedding_path, map_location=device)
|
| 47 |
speaker_embeddings_cache[wav_file_path] = embedding
|
| 48 |
return embedding
|
| 49 |
+
|
| 50 |
+
print(f"Creating new speaker embedding for {wav_file_path}...")
|
| 51 |
if not os.path.exists(wav_file_path):
|
| 52 |
+
raise gr.Error(f"Audio file not found: {wav_file_path}.")
|
| 53 |
+
|
| 54 |
try:
|
| 55 |
audio, sr = torchaudio.load(wav_file_path)
|
| 56 |
+
if sr != 16000:
|
| 57 |
+
audio = torchaudio.functional.resample(audio, sr, 16000)
|
| 58 |
+
if audio.shape[0] > 1:
|
| 59 |
+
audio = torch.mean(audio, dim=0, keepdim=True)
|
| 60 |
+
|
| 61 |
with torch.no_grad():
|
| 62 |
embedding = speaker_model.encode_batch(audio.to(device))
|
| 63 |
embedding = torch.nn.functional.normalize(embedding, dim=2).squeeze()
|
| 64 |
+
|
| 65 |
torch.save(embedding.cpu(), embedding_path)
|
| 66 |
speaker_embeddings_cache[wav_file_path] = embedding.to(device)
|
| 67 |
+
print(f"Embedding created and saved for {wav_file_path}.")
|
| 68 |
return embedding.to(device)
|
| 69 |
except Exception as e:
|
| 70 |
raise gr.Error(f"Could not process audio file {wav_file_path}. Error: {e}")
|
| 71 |
|
| 72 |
+
# --- Text Processing Functions ---
|
| 73 |
+
number_words = {
|
| 74 |
+
0: "eber", 1: "kow", 2: "labo", 3: "saddex", 4: "afar", 5: "shan",
|
| 75 |
+
6: "lix", 7: "toddobo", 8: "siddeed", 9: "sagaal", 10: "toban",
|
| 76 |
+
11: "kow iyo toban", 12: "labo iyo toban", 13: "saddex iyo toban",
|
| 77 |
+
14: "afar iyo toban", 15: "shan iyo toban", 16: "lix iyo toban",
|
| 78 |
+
17: "toddobo iyo toban", 18: "siddeed iyo toban", 19: "sagaal iyo toban",
|
| 79 |
+
20: "labaatan", 30: "soddon", 40: "afartan", 50: "konton",
|
| 80 |
+
60: "lixdan", 70: "toddobaatan", 80: "siddeetan", 90: "sagaashan",
|
| 81 |
+
100: "boqol", 1000: "kun",
|
| 82 |
+
}
|
| 83 |
+
def number_to_words(n):
|
| 84 |
+
if n in number_words: return number_words[n]
|
| 85 |
+
if n < 100: return number_words[n//10 * 10] + (" iyo " + number_words[n%10] if n%10 else "")
|
| 86 |
+
if n < 1000: return (number_words[n//100] + " boqol" if n//100 > 1 else "boqol") + (" iyo " + number_to_words(n%100) if n%100 else "")
|
| 87 |
+
if n < 1000000: return (number_to_words(n//1000) + " kun" if n//1000 > 1 else "kun") + (" iyo " + number_to_words(n%1000) if n%1000 else "")
|
| 88 |
+
return str(n)
|
| 89 |
+
def replace_numbers_with_words(text):
|
| 90 |
+
return re.sub(r'\b\d+\b', lambda m: number_to_words(int(m.group())), text)
|
| 91 |
+
def normalize_text(text):
|
| 92 |
+
text = text.lower()
|
| 93 |
+
text = replace_numbers_with_words(text)
|
| 94 |
+
text = re.sub(r'[^\w\s\']', '', text)
|
| 95 |
+
return text
|
| 96 |
|
| 97 |
+
# --- Main Text-to-Speech Function (with quality improvements) ---
|
| 98 |
def text_to_speech(text, voice_choice):
|
| 99 |
+
if not text:
|
| 100 |
+
gr.Warning("Please enter some text.")
|
| 101 |
+
return None, None
|
| 102 |
+
if not voice_choice:
|
| 103 |
+
gr.Warning("Please select a voice from the dropdown.")
|
| 104 |
+
return None, None
|
| 105 |
+
|
| 106 |
+
speaker_embedding = get_speaker_embedding(voice_choice)
|
| 107 |
+
normalized_text = normalize_text(text)
|
| 108 |
+
inputs = processor(text=normalized_text, return_tensors="pt").to(device)
|
| 109 |
+
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
# Using model.generate with sampling for more natural speech
|
| 112 |
+
speech = model.generate(
|
| 113 |
+
input_ids=inputs["input_ids"],
|
| 114 |
+
speaker_embeddings=speaker_embedding.unsqueeze(0),
|
| 115 |
+
do_sample=True,
|
| 116 |
+
top_k=50,
|
| 117 |
+
)
|
| 118 |
+
# Apply the vocoder separately
|
| 119 |
+
speech = vocoder(speech)
|
| 120 |
+
|
| 121 |
+
return (16000, speech.cpu().numpy())
|
| 122 |
|
| 123 |
# --- Gradio Interface ---
|
| 124 |
iface = gr.Interface(
|
| 125 |
+
fn=text_to_speech,
|
| 126 |
+
inputs=[
|
| 127 |
+
gr.Textbox(label="Geli qoraalka af-Soomaaliga (Enter Somali Text)"),
|
| 128 |
+
gr.Dropdown(
|
| 129 |
+
VOICE_SAMPLE_FILES,
|
| 130 |
+
label="Select Voice",
|
| 131 |
+
info="Choose the voice you want to use for the speech.",
|
| 132 |
+
value=VOICE_SAMPLE_FILES[0] if VOICE_SAMPLE_FILES else None
|
| 133 |
+
)
|
| 134 |
+
],
|
| 135 |
+
outputs=gr.Audio(label="Codka La Abuuray (Generated Voice)", type="numpy"),
|
| 136 |
+
title="Multi-Voice Somali Text-to-Speech",
|
| 137 |
+
description="Enter Somali text, choose a voice from the dropdown, and click submit to generate speech.",
|
| 138 |
+
examples=[
|
| 139 |
+
["Sidee tahay saaxiib? Maanta waa maalin wanaagsan.", VOICE_SAMPLE_FILES[0] if VOICE_SAMPLE_FILES else ''],
|
| 140 |
+
["Nabad gelyo, is arag dambe.", VOICE_SAMPLE_FILES[1] if len(VOICE_SAMPLE_FILES) > 1 else (VOICE_SAMPLE_FILES[0] if VOICE_SAMPLE_FILES else '')],
|
| 141 |
+
]
|
| 142 |
)
|
| 143 |
|
| 144 |
# --- Launch the web interface ---
|
| 145 |
if __name__ == "__main__":
|
| 146 |
+
# This check will run first. If it fails, the app will stop.
|
| 147 |
+
print("Checking for voice files...")
|
| 148 |
for f in VOICE_SAMPLE_FILES:
|
| 149 |
if not os.path.exists(f):
|
| 150 |
+
raise FileNotFoundError(f"Voice file not found: '{f}'. Please upload it to your Hugging Face Space.")
|
|
|
|
| 151 |
|
| 152 |
+
print("Pre-loading all voice embeddings...")
|
| 153 |
for voice_file in VOICE_SAMPLE_FILES:
|
| 154 |
get_speaker_embedding(voice_file)
|
| 155 |
+
print("All voices are ready. Launching interface.")
|
| 156 |
|
| 157 |
iface.launch(share=True)
|