Spaces:
Sleeping
Sleeping
File size: 20,664 Bytes
b9c9746 0c97eed b9a6dd9 94b0033 b9a6dd9 36c0509 30a6fae b9a6dd9 0c97eed ba6bbdf 2c70930 5d0e89a b2af2e4 2c70930 5d0e89a f1eaa03 35bf227 0c97eed 24fbd43 b9a6dd9 bf1337a 0c97eed b9a6dd9 0c97eed b9a6dd9 0c97eed b9a6dd9 0c97eed b9a6dd9 0c97eed 30a6fae b9a6dd9 1e42459 30a6fae b9a6dd9 1e42459 94b0033 b9a6dd9 629762f b9a6dd9 629762f b9a6dd9 66ba863 b9a6dd9 629762f b9a6dd9 4cbe9dc b9a6dd9 66ba863 b9a6dd9 4cbe9dc b9a6dd9 4cbe9dc b2af2e4 b9a6dd9 66ba863 b9a6dd9 4cbe9dc b9a6dd9 8818ae1 b9a6dd9 94b0033 b9a6dd9 94b0033 b9a6dd9 94b0033 b9a6dd9 94b0033 b9a6dd9 94b0033 0c97eed b9a6dd9 0c97eed b9a6dd9 54d1a52 35bf227 ee1defa 35bf227 ee1defa 35bf227 ee1defa 54d1a52 ee1defa 54d1a52 ee1defa 35bf227 a6c8153 1acf95b b9a6dd9 71fd664 0c97eed b9a6dd9 1acf95b b9a6dd9 1acf95b b9a6dd9 1acf95b 35bf227 b9a6dd9 1acf95b b9a6dd9 1acf95b b9a6dd9 1acf95b b9a6dd9 1acf95b b9a6dd9 0c97eed 1acf95b 35bf227 1acf95b 55aeb9e 1acf95b 36c0509 1acf95b 71fd664 1acf95b 71fd664 1acf95b b9a6dd9 1acf95b b9a6dd9 1acf95b b9a6dd9 1acf95b 0c97eed b9a6dd9 1efc72a d07cbce 253edec d07cbce 1efc72a 1acf95b 1efc72a b9a6dd9 d07cbce 1acf95b f475e2f 1acf95b 1efc72a 2e2aa2d 5c51862 5389f8b e51021e 5389f8b 0e9feb4 5389f8b 5c51862 1efc72a e51021e 1acf95b 1efc72a b2af2e4 b9a6dd9 1efc72a b2af2e4 0e9feb4 253edec 0e9feb4 b2af2e4 1efc72a 1acf95b 1efc72a 35bf227 1efc72a ee1defa 1efc72a ee1defa 1efc72a b2af2e4 1efc72a | 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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 | import spaces
import os
import shutil
import time
from typing import Generator, Optional, Tuple
import gradio as gr
import nltk
import numpy as np
import torch
from huggingface_hub import HfApi
import librosa
from espnet2.sds.espnet_model import ESPnetSDSModelInterface
# ------------------------
# Hyperparameters
# ------------------------
access_token = os.environ.get("HF_TOKEN")
ASR_name="espnet/owsm_ctc_v4_1B"
LLM_name="Qwen/Qwen3-4B-Instruct-2507"
TTS_name="espnet/kan-bayashi_ljspeech_vits"
ASR_options="espnet/owsm_ctc_v4_1B".split(",")
LLM_options="Qwen/Qwen3-4B-Instruct-2507".split(",")
TTS_options="espnet/kan-bayashi_ljspeech_vits,espnet/kan-bayashi_jsut_full_band_vits_prosody,espnet/kan-bayashi_csmsc_full_band_vits".split(",")
# Create display names with language labels for TTS models
TTS_display_names = [
"English - espnet/kan-bayashi_ljspeech_vits",
"Japanese - espnet/kan-bayashi_jsut_full_band_vits_prosody",
"Chinese - espnet/kan-bayashi_csmsc_full_band_vits"
]
TTS_value_map = {display: value for display, value in zip(TTS_display_names, TTS_options)}
TTS_reverse_map = {value: display for display, value in zip(TTS_display_names, TTS_options)}
Eval_options="Latency,TTS Intelligibility,TTS Speech Quality,ASR WER,Text Dialog Metrics"
upload_to_hub=None
dialogue_model = ESPnetSDSModelInterface(
ASR_name, LLM_name, TTS_name, "Cascaded", access_token
)
ASR_curr_name=None
LLM_curr_name=None
TTS_curr_name=None
latency_ASR = 0.0
latency_LM = 0.0
latency_TTS = 0.0
LLM_response_arr = []
total_response_arr = []
enable_btn = gr.Button(interactive=True, visible=True)
# ------------------------
# Function Definitions
# ------------------------
def handle_eval_selection(
option: str,
TTS_audio_output: str,
LLM_Output: str,
ASR_audio_output: str,
ASR_transcript: str,
):
"""
Handles the evaluation of a selected metric based on
user input and provided outputs.
This function evaluates different aspects of a
casacaded conversational AI pipeline, such as:
Latency, TTS intelligibility, TTS speech quality,
ASR WER, and text dialog metrics.
It is designed to integrate with Gradio via
multiple yield statements,
allowing updates to be displayed in real time.
Parameters:
----------
option : str
The evaluation metric selected by the user.
Supported options include:
- "Latency"
- "TTS Intelligibility"
- "TTS Speech Quality"
- "ASR WER"
- "Text Dialog Metrics"
TTS_audio_output : np.ndarray
The audio output generated by the TTS module for evaluation.
LLM_Output : str
The text output generated by the LLM module for evaluation.
ASR_audio_output : np.ndarray
The audio input/output used for ASR evaluation.
ASR_transcript : str
The transcript generated by the ASR module for evaluation.
Returns:
-------
str
A string representation of the evaluation results.
The specific result depends on the selected evaluation metric:
- "Latency": Latencies of ASR, LLM, and TTS modules.
- "TTS Intelligibility": A range of scores indicating how intelligible
the TTS audio output is based on different reference ASR models.
- "TTS Speech Quality": A range of scores representing the
speech quality of the TTS audio output.
- "ASR WER": The Word Error Rate (WER) of the ASR output
based on different judge ASR models.
- "Text Dialog Metrics": A combination of perplexity,
diversity metrics, and relevance scores for the dialog.
Raises:
------
ValueError
If the `option` parameter does not match any supported evaluation metric.
Example:
-------
>>> result = handle_eval_selection(
option="Latency",
TTS_audio_output=audio_array,
LLM_Output="Generated response",
ASR_audio_output=audio_input,
ASR_transcript="Expected transcript"
)
>>> print(result)
"ASR Latency: 0.14
LLM Latency: 0.42
TTS Latency: 0.21"
"""
global LLM_response_arr
global total_response_arr
return None
def handle_eval_selection_E2E(
option: str,
TTS_audio_output: str,
LLM_Output: str,
):
"""
Handles the evaluation of a selected metric based on user input
and provided outputs.
This function evaluates different aspects of an E2E
conversational AI model, such as:
Latency, TTS intelligibility, TTS speech quality, and
text dialog metrics.
It is designed to integrate with Gradio via
multiple yield statements,
allowing updates to be displayed in real time.
Parameters:
----------
option : str
The evaluation metric selected by the user.
Supported options include:
- "Latency"
- "TTS Intelligibility"
- "TTS Speech Quality"
- "Text Dialog Metrics"
TTS_audio_output : np.ndarray
The audio output generated by the TTS module for evaluation.
LLM_Output : str
The text output generated by the LLM module for evaluation.
Returns:
-------
str
A string representation of the evaluation results.
The specific result depends on the selected evaluation metric:
- "Latency": Latency of the entire system.
- "TTS Intelligibility": A range of scores indicating how intelligible the
TTS audio output is based on different reference ASR models.
- "TTS Speech Quality": A range of scores representing the
speech quality of the TTS audio output.
- "Text Dialog Metrics": A combination of perplexity and
diversity metrics for the dialog.
Raises:
------
ValueError
If the `option` parameter does not match any supported evaluation metric.
Example:
-------
>>> result = handle_eval_selection(
option="Latency",
TTS_audio_output=audio_array,
LLM_Output="Generated response",
)
>>> print(result)
"Total Latency: 2.34"
"""
global LLM_response_arr
global total_response_arr
return
def start_warmup():
"""
Initializes and warms up the dialogue and evaluation model.
This function is designed to ensure that all
components of the dialogue model are pre-loaded
and ready for execution, avoiding delays during runtime.
"""
global dialogue_model
global ASR_options
global LLM_options
global TTS_options
global ASR_name
global LLM_name
global TTS_name
remove=0
for opt_count in range(len(ASR_options)):
opt_count-=remove
if opt_count>=len(ASR_options):
break
print(opt_count)
print(ASR_options)
opt = ASR_options[opt_count]
try:
for _ in dialogue_model.handle_ASR_selection(opt):
continue
except Exception as e:
print(e)
print("Removing " + opt + " from ASR options since it cannot be loaded.")
ASR_options = ASR_options[:opt_count] + ASR_options[(opt_count + 1) :]
remove+=1
if opt == ASR_name:
ASR_name = ASR_options[0]
for opt_count in range(len(LLM_options)):
opt_count-=remove
if opt_count>=len(LLM_options):
break
opt = LLM_options[opt_count]
try:
for _ in dialogue_model.handle_LLM_selection(opt):
continue
except Exception as e:
print(e)
print("Removing " + opt + " from LLM options since it cannot be loaded.")
LLM_options = LLM_options[:opt_count] + LLM_options[(opt_count + 1) :]
remove+=1
if opt == LLM_name:
LLM_name = LLM_options[0]
for opt_count in range(len(TTS_options)):
opt_count-=remove
if opt_count>=len(TTS_options):
break
opt = TTS_options[opt_count]
try:
for _ in dialogue_model.handle_TTS_selection(opt):
continue
except Exception as e:
print(e)
print("Removing " + opt + " from TTS options since it cannot be loaded.")
TTS_options = TTS_options[:opt_count] + TTS_options[(opt_count + 1) :]
remove+=1
if opt == TTS_name:
TTS_name = TTS_options[0]
# dialogue_model.handle_E2E_selection()
dialogue_model.client = None
for _ in dialogue_model.handle_TTS_selection(TTS_name):
continue
for _ in dialogue_model.handle_ASR_selection(ASR_name):
continue
for _ in dialogue_model.handle_LLM_selection(LLM_name):
continue
dummy_input = (
torch.randn(
(3000),
dtype=getattr(torch, "float16"),
device="cpu",
)
.cpu()
.numpy()
)
dummy_text = "This is dummy text"
for opt in Eval_options:
handle_eval_selection(opt, dummy_input, dummy_text, dummy_input, dummy_text)
def flash_buttons():
"""
Enables human feedback buttons after displaying system output.
"""
btn_updates = (enable_btn,) * 8
yield (
"",
"",
) + btn_updates
@spaces.GPU
def handle_TTS_selection_wrapper(display_name: str):
"""
Wrapper function to convert TTS display name to actual model name
before calling the dialogue model's handle_TTS_selection.
This runs model-selection side effects only and intentionally does
not update output widgets, so existing ASR/LLM/TTS outputs stay visible.
Args:
display_name: The display name of the TTS model (with language label)
Returns:
None
"""
# Convert display name to actual model name
actual_name = TTS_value_map.get(display_name, display_name)
# Run the original handler for side effects only.
for _ in dialogue_model.handle_TTS_selection(actual_name):
continue
@spaces.GPU
def handle_LLM_selection_wrapper(option: str):
"""
Run LLM model selection without clearing existing output widgets.
"""
for _ in dialogue_model.handle_LLM_selection(option):
continue
@spaces.GPU
def handle_ASR_selection_wrapper(option: str):
"""
Run ASR model selection without clearing existing output widgets.
"""
for _ in dialogue_model.handle_ASR_selection(option):
continue
@spaces.GPU
def process_audio_file(
audio_file: Optional[Tuple[int, np.ndarray]],
TTS_option: str,
ASR_option: str,
LLM_option: str,
type_option: str,
input_text: str,
):
"""
Processes a recorded audio file through the dialogue system.
This function handles the transcription of an uploaded audio file
and its transformation through a cascaded conversational AI system.
It processes the entire audio file at once (offline mode).
Args:
audio_file: A tuple containing:
- `sr`: Sample rate of the audio file.
- `y`: Audio data array.
TTS_option: Selected TTS model option (display name).
ASR_option: Selected ASR model option.
LLM_option: Selected LLM model option.
type_option: Type of system ("Cascaded" or "E2E").
input_text: System prompt for the LLM.
Returns:
Tuple[str, str, Optional[Tuple[int, np.ndarray]]]:
A tuple containing:
- ASR output text (transcription).
- Generated LLM output text (response).
- Audio output as a tuple of sample rate and audio waveform (TTS).
Notes:
- Processes the complete audio file in one go.
- Updates latency metrics.
"""
global latency_ASR
global latency_LM
global latency_TTS
global LLM_response_arr
global total_response_arr
# Convert display name to actual model name
TTS_option = TTS_value_map.get(TTS_option, TTS_option)
if audio_file is None:
gr.Info("Please upload an audio file.")
return "", "", None
# Ensure the selected models are actually loaded before processing
for _ in dialogue_model.handle_TTS_selection(TTS_option):
continue
for _ in dialogue_model.handle_ASR_selection(ASR_option):
continue
for _ in dialogue_model.handle_LLM_selection(LLM_option):
continue
# Extract sample rate and audio data
sr, y = audio_file
# Convert stereo to mono if needed
if len(y.shape) > 1:
print(f"Converting stereo audio (shape: {y.shape}) to mono")
y = np.mean(y, axis=1)
# Ensure audio is float32 and normalized
if y.dtype != np.float32:
y = y.astype(np.float32)
# Normalize if not already normalized
if np.abs(y).max() > 1.0:
y = y / np.abs(y).max()
# Resample to 16000 Hz if needed (required for VAD and ASR)
target_sr = 16000
if sr != target_sr:
print(f"Resampling audio from {sr} Hz to {target_sr} Hz")
y = librosa.resample(y, orig_sr=sr, target_sr=target_sr)
sr = target_sr
print(f"Processed audio: sr={sr}, shape={y.shape}, dtype={y.dtype}, range=[{y.min():.3f}, {y.max():.3f}]")
# Initialize chat with system prompt
dialogue_model.chat.init_chat(
{
"role": "system",
"content": input_text,
}
)
# Initialize variables
asr_output_str = ""
text_str = ""
audio_output = None
audio_output1 = None
stream = y # Use entire audio file as stream
# Process the audio file
(
asr_output_str,
text_str,
audio_output,
audio_output1,
latency_ASR,
latency_LM,
latency_TTS,
stream,
change,
) = dialogue_model(
y,
sr,
stream,
asr_output_str,
text_str,
audio_output,
audio_output1,
latency_ASR,
latency_LM,
latency_TTS,
)
# Store results
if change:
print("Processing completed")
if asr_output_str != "":
total_response_arr.append(asr_output_str.replace("\n", " "))
LLM_response_arr.append(text_str.replace("\n", " "))
total_response_arr.append(text_str.replace("\n", " "))
return asr_output_str, text_str, audio_output
# ------------------------
# Executable Script
# ------------------------
api = HfApi()
nltk.download("averaged_perceptron_tagger_eng")
start_warmup()
default_instruct=(
"You are a helpful and friendly AI "
"assistant. "
"You are polite, respectful, and aim to "
"provide concise and complete responses of "
"less than 15 words."
)
import pandas as pd
# Usage examples: (label, prompt, TTS_display_name)
# Use TTS_reverse_map[TTS_name] for default TTS; or a specific TTS_display_names entry
example_translate_ja_prompt = "You are a translator. Translate what user says into Japanese."
example_summarize_prompt = "Your task is to summarize what user says in one short sentence no more than 10 words."
example_story_prompt = (
"You are an Imaginative Story Writer.\n\n"
"Given user input, craft compelling fiction with:\n"
"- strong scene setting\n"
"- character voice\n"
"- emotional arc\n"
"- satisfying narrative progression\n\n"
"Guidelines:\n"
"- Respect user-provided anchors (characters, world, plot constraints).\n"
"- Expand creatively between anchors with sensory detail and subtext.\n"
"- Use \"show, don't tell\" where possible.\n"
"- Maintain internal logic and continuity.\n"
"- End scenes with momentum unless user requests a full ending.\n"
"- Output only story content."
)
example_audio_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "audio.wav")
examples = [
["Translation to Japanese", example_translate_ja_prompt, TTS_display_names[1]],
["Summarization (≤10 words)", example_summarize_prompt, TTS_reverse_map[TTS_name]],
["Imaginative Story Writer", example_story_prompt, TTS_reverse_map[TTS_name]],
]
with gr.Blocks(
title="ESPnet-SDS Offline Audio Processing",
) as demo:
with gr.Row():
gr.Markdown(
"""
## ESPnet Prompt Editing Demo
Welcome to our prompt editing demo using ESPnet-SDS toolkit.
**How to use:**
1. Upload or record an audio file
2. Configure the LLM prompt and select models
3. Click "Process Audio" to transcribe and generate a response
The system will:
- **Transcribe** your audio using ASR (Automatic Speech Recognition)
- **Generate** a response using the selected LLM
- **Synthesize** speech output using TTS (Text-to-Speech)
**Click the examples in the bottom** for sample prompts and configurations.
For more details, refer to the [README]
(https://github.com/siddhu001/espnet/tree/sds_demo_recipe/egs2/TEMPLATE/sds1#how-to-use).
"""
)
type_radio = gr.State("Cascaded")
with gr.Row():
with gr.Column(scale=1):
user_audio = gr.Audio(
sources=["upload", "microphone"],
type="numpy",
label="Upload or Record Audio File",
format="wav",
)
input_text = gr.Textbox(
label="LLM prompt",
visible=True,
interactive=True,
value=default_instruct,
)
ASR_radio = gr.Radio(
choices=ASR_options,
label="Choose ASR:",
value=ASR_name,
)
LLM_radio = gr.Radio(
choices=LLM_options,
label="Choose LLM:",
value=LLM_name,
)
radio = gr.Radio(
choices=TTS_display_names,
label="Choose TTS:",
value=TTS_reverse_map[TTS_name],
)
E2Eradio = gr.Radio(
choices=["mini-omni"],
label="Choose E2E model:",
value="mini-omni",
visible=False,
)
with gr.Column(scale=1):
process_btn = gr.Button("Process Audio", variant="primary")
output_asr_text = gr.Textbox(label="ASR Transcription", interactive=False)
output_text = gr.Textbox(label="LLM Response", interactive=False)
output_audio = gr.Audio(label="TTS Output", autoplay=True, visible=True, interactive=False)
eval_radio = gr.Radio(
choices=[
"Latency",
"TTS Intelligibility",
"TTS Speech Quality",
"ASR WER",
"Text Dialog Metrics",
],
label="Choose Evaluation metrics:",
visible=False,
)
eval_radio_E2E = gr.Radio(
choices=[
"Latency",
"TTS Intelligibility",
"TTS Speech Quality",
"Text Dialog Metrics",
],
label="Choose Evaluation metrics:",
visible=False,
)
output_eval_text = gr.Textbox(label="Evaluation Results", visible=False)
gr.Examples(
examples=[[row[1], row[2], example_audio_path] for row in examples],
inputs=[input_text, radio, user_audio],
label="Usage examples",
example_labels=[row[0] for row in examples],
)
natural_response = gr.Textbox(
label="natural_response", visible=False, interactive=False
)
diversity_response = gr.Textbox(
label="diversity_response", visible=False, interactive=False
)
ip_address = gr.Textbox(label="ip_address", visible=False, interactive=False)
# Process button click event
process_btn.click(
process_audio_file,
inputs=[user_audio, radio, ASR_radio, LLM_radio, type_radio, input_text],
outputs=[output_asr_text, output_text, output_audio],
)
radio.change(
fn=handle_TTS_selection_wrapper,
inputs=[radio],
)
LLM_radio.change(
fn=handle_LLM_selection_wrapper,
inputs=[LLM_radio],
)
ASR_radio.change(
fn=handle_ASR_selection_wrapper,
inputs=[ASR_radio],
)
output_audio.play(
flash_buttons, [], [natural_response, diversity_response]
)
demo.queue(max_size=10, default_concurrency_limit=1)
demo.launch(debug=True)
|