Spaces:
Sleeping
Sleeping
Update infer.py
Browse files
infer.py
CHANGED
|
@@ -1,153 +1,129 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import torch
|
| 3 |
-
import json
|
| 4 |
-
import numpy as np
|
| 5 |
-
import os
|
| 6 |
-
from datetime import datetime
|
| 7 |
-
from model import Image2Phoneme
|
| 8 |
-
from utils import ctc_post_process, audio_to_mel, mel_to_image, text_to_phonemes
|
| 9 |
-
import soundfile as sf
|
| 10 |
-
import shutil
|
| 11 |
-
import
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
model.
|
| 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 |
-
audio_input = gr.Audio(sources=[ "upload"], type="filepath", label="Upload Audio (.wav or .mp3)", interactive=True)
|
| 131 |
-
text_input = gr.Textbox(label="Enter Text", placeholder="Type a sentence to convert to phonemes")
|
| 132 |
-
process_button = gr.Button("Process")
|
| 133 |
-
|
| 134 |
-
audio_output = gr.JSON(label="Audio Processing Results (Audio Path, Phonemes, Post-Processed Phonemes)")
|
| 135 |
-
mel_image = gr.Image(label="Mel Spectrogram", type="filepath")
|
| 136 |
-
raw_phonemes = gr.Textbox(label="Raw Phonemes")
|
| 137 |
-
post_processed_phonemes = gr.Textbox(label="Post-Processed Phonemes")
|
| 138 |
-
text_output = gr.JSON(label="Text-to-Phoneme Results")
|
| 139 |
-
|
| 140 |
-
def process(audio_input, text_input):
|
| 141 |
-
print(f"Processing inputs - Audio: {audio_input}, Text: {text_input}")
|
| 142 |
-
audio_result, mel_image_path, raw_ph, post_ph = process_audio(audio_input) if audio_input else ({}, None, None, None)
|
| 143 |
-
text_result = text_to_phonemes(text_input) if text_input else {}
|
| 144 |
-
return audio_result, mel_image_path, raw_ph, post_ph, text_result
|
| 145 |
-
|
| 146 |
-
process_button.click(
|
| 147 |
-
fn=process,
|
| 148 |
-
inputs=[audio_input, text_input],
|
| 149 |
-
outputs=[audio_output, mel_image, raw_phonemes, post_processed_phonemes, text_output]
|
| 150 |
-
)
|
| 151 |
-
|
| 152 |
-
if __name__ == "__main__":
|
| 153 |
iface.launch(debug=True)
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import json
|
| 4 |
+
import numpy as np
|
| 5 |
+
import os
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from model import Image2Phoneme
|
| 8 |
+
from utils import ctc_post_process, audio_to_mel, mel_to_image, text_to_phonemes
|
| 9 |
+
import soundfile as sf
|
| 10 |
+
import shutil
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
# Configuration
|
| 14 |
+
DEVICE = torch.device("cpu")
|
| 15 |
+
PHMAP = "phoneme_to_id.json"
|
| 16 |
+
AUDIO_DIR = "audio_inputs"
|
| 17 |
+
|
| 18 |
+
# Ensure audio directory exists
|
| 19 |
+
os.makedirs(AUDIO_DIR, exist_ok=True)
|
| 20 |
+
|
| 21 |
+
# Load phoneme vocabulary
|
| 22 |
+
try:
|
| 23 |
+
vocab = json.load(open(PHMAP, "r"))
|
| 24 |
+
id_to_ph = {v: k for k, v in vocab.items()}
|
| 25 |
+
except FileNotFoundError:
|
| 26 |
+
raise FileNotFoundError(f"Phoneme mapping file not found at {PHMAP}")
|
| 27 |
+
|
| 28 |
+
# Build model
|
| 29 |
+
vocab_size = max(vocab.values()) + 1
|
| 30 |
+
model = Image2Phoneme(vocab_size=vocab_size).to(DEVICE)
|
| 31 |
+
try:
|
| 32 |
+
ckpt = torch.load("last_checkpoint.pt", map_location=DEVICE, weights_only=True)
|
| 33 |
+
model.load_state_dict(ckpt["model_state_dict"])
|
| 34 |
+
model.eval()
|
| 35 |
+
except FileNotFoundError:
|
| 36 |
+
raise FileNotFoundError(f"Checkpoint file not found at last_checkpoint.pt")
|
| 37 |
+
|
| 38 |
+
def process_audio(audio_input):
|
| 39 |
+
"""Process audio to predict phonemes and display mel spectrogram."""
|
| 40 |
+
try:
|
| 41 |
+
print(f"Received audio_input before processing: {audio_input}")
|
| 42 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 43 |
+
audio_path = os.path.join(AUDIO_DIR, f"input_{timestamp}.wav")
|
| 44 |
+
|
| 45 |
+
if audio_input is None:
|
| 46 |
+
print("Audio input is None")
|
| 47 |
+
return {"error": "No audio input provided"}, None, None, None
|
| 48 |
+
|
| 49 |
+
if isinstance(audio_input, str):
|
| 50 |
+
print(f"Processing uploaded file: {audio_input}")
|
| 51 |
+
if not os.path.exists(audio_input):
|
| 52 |
+
return {"error": f"Uploaded file not found: {audio_input}"}, None, None, None
|
| 53 |
+
if audio_input.endswith(".mp3"):
|
| 54 |
+
print("Converting .mp3 to .wav")
|
| 55 |
+
from pydub import AudioSegment
|
| 56 |
+
audio = AudioSegment.from_mp3(audio_input)
|
| 57 |
+
audio_path = audio_path.replace(".wav", "_converted.wav")
|
| 58 |
+
audio.export(audio_path, format="wav")
|
| 59 |
+
print(f"Converted file saved to: {audio_path}")
|
| 60 |
+
else:
|
| 61 |
+
shutil.copy(audio_input, audio_path)
|
| 62 |
+
print(f"Copied file to: {audio_path}")
|
| 63 |
+
else:
|
| 64 |
+
raise ValueError("Microphone input not supported in this configuration")
|
| 65 |
+
|
| 66 |
+
mel_path = audio_to_mel(audio_path)
|
| 67 |
+
print(f"Generated mel spectrogram: {mel_path}")
|
| 68 |
+
if not os.path.exists(mel_path):
|
| 69 |
+
return {"error": f"Mel spectrogram file not found: {mel_path}"}, None, None, None
|
| 70 |
+
|
| 71 |
+
mel_image_path = mel_to_image(mel_path)
|
| 72 |
+
print(f"Generated mel spectrogram image: {mel_image_path}")
|
| 73 |
+
if not os.path.exists(mel_image_path):
|
| 74 |
+
return {"error": f"Mel spectrogram image not found: {mel_image_path}"}, None, None, None
|
| 75 |
+
|
| 76 |
+
mel = np.load(mel_path)
|
| 77 |
+
print(f"Loaded mel spectrogram shape: {mel.shape}")
|
| 78 |
+
mel_tensor = torch.tensor(mel).unsqueeze(0).to(DEVICE)
|
| 79 |
+
mel_lens = torch.tensor([mel.shape[1]]).to(DEVICE)
|
| 80 |
+
|
| 81 |
+
with torch.no_grad():
|
| 82 |
+
ph_pred = model(mel_tensor)
|
| 83 |
+
ph_ids = ph_pred.argmax(-1)[0].cpu().numpy()
|
| 84 |
+
print(f"Predicted phoneme IDs: {ph_ids}")
|
| 85 |
+
|
| 86 |
+
ph_seq = [id_to_ph[i] for i in ph_ids if i > 0]
|
| 87 |
+
print(f"Raw phonemes: {ph_seq}")
|
| 88 |
+
|
| 89 |
+
post_processed = ctc_post_process(ph_seq)
|
| 90 |
+
print(f"Post-processed phonemes: {post_processed}")
|
| 91 |
+
|
| 92 |
+
return {
|
| 93 |
+
"audio_path": audio_path,
|
| 94 |
+
"phonemes": " ".join(ph_seq),
|
| 95 |
+
"post_processed_phonemes": " ".join(post_processed)
|
| 96 |
+
}, mel_image_path, " ".join(ph_seq), " ".join(post_processed)
|
| 97 |
+
except Exception as e:
|
| 98 |
+
print(f"Error in process_audio: {str(e)}")
|
| 99 |
+
return {"error": f"Processing failed: {str(e)}"}, None, None, None
|
| 100 |
+
|
| 101 |
+
# Gradio interface
|
| 102 |
+
with gr.Blocks() as iface:
|
| 103 |
+
gr.Markdown("# Speech to Phonemes Converter")
|
| 104 |
+
gr.Markdown("Upload audio to predict phonemes and display mel spectrogram. Enter text to convert to phonemes.")
|
| 105 |
+
|
| 106 |
+
audio_input = gr.Audio(sources=["upload"], type="filepath", label="Upload Audio (.wav or .mp3)", interactive=True)
|
| 107 |
+
text_input = gr.Textbox(label="Enter Text", placeholder="Type a sentence to convert to phonemes")
|
| 108 |
+
process_button = gr.Button("Process")
|
| 109 |
+
|
| 110 |
+
audio_output = gr.JSON(label="Audio Processing Results (Audio Path, Phonemes, Post-Processed Phonemes)")
|
| 111 |
+
mel_image = gr.Image(label="Mel Spectrogram", type="filepath")
|
| 112 |
+
raw_phonemes = gr.Textbox(label="Raw Phonemes")
|
| 113 |
+
post_processed_phonemes = gr.Textbox(label="Post-Processed Phonemes")
|
| 114 |
+
text_output = gr.JSON(label="Text-to-Phoneme Results")
|
| 115 |
+
|
| 116 |
+
def process(audio_input, text_input):
|
| 117 |
+
print(f"Processing inputs - Audio: {audio_input}, Text: {text_input}")
|
| 118 |
+
audio_result, mel_image_path, raw_ph, post_ph = process_audio(audio_input) if audio_input else ({}, None, None, None)
|
| 119 |
+
text_result = text_to_phonemes(text_input) if text_input and text_input.strip() else {}
|
| 120 |
+
return audio_result, mel_image_path, raw_ph, post_ph, text_result
|
| 121 |
+
|
| 122 |
+
process_button.click(
|
| 123 |
+
fn=process,
|
| 124 |
+
inputs=[audio_input, text_input],
|
| 125 |
+
outputs=[audio_output, mel_image, raw_phonemes, post_processed_phonemes, text_output]
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
iface.launch(debug=True)
|