Spaces:
Running
on
L4
Running
on
L4
File size: 26,425 Bytes
be31546 dfa3d55 6265984 be31546 7ee1777 9cdf2c6 7ee1777 37d87af 0c542b8 c1ed71e 411df60 be31546 37d87af 0c542b8 37d87af 7ee1777 69da775 7ee1777 69da775 1f48149 6265984 5fd9f07 6265984 c1ed71e be31546 37d87af c1ed71e 37d87af c1ed71e 37d87af c1ed71e 37d87af c1ed71e 37d87af c1ed71e dfa3d55 c1ed71e 37d87af c1ed71e dfa3d55 be31546 dfa3d55 c1ed71e dfa3d55 be31546 dfa3d55 be31546 c1ed71e dfa3d55 c1ed71e 37d87af c1ed71e 37d87af c1ed71e dfa3d55 c1ed71e dfa3d55 c1ed71e dfa3d55 c1ed71e 37d87af c1ed71e 37d87af c1ed71e dfa3d55 c1ed71e 67347ea c1ed71e be31546 dfa3d55 67347ea dfa3d55 67347ea 31e64cf e85c61b dfa3d55 7ee1777 e43191e 0c542b8 e43191e dfa3d55 293a825 dfa3d55 6265984 394b922 cecba15 1f48149 dfa3d55 9c301cc 7e35447 dfa3d55 c1ed71e be31546 dfa3d55 c1ed71e dfa3d55 c1ed71e 37d87af c1ed71e 37d87af c1ed71e 67347ea c1ed71e 14db6ef c1ed71e dfa3d55 c1ed71e dfa3d55 c1ed71e 37f33b1 c1ed71e 37f33b1 c1ed71e 37f33b1 c1ed71e dfa3d55 c1ed71e 14db6ef c1ed71e 37d87af f1f2bc7 |
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 |
import os
import sys
import subprocess
import gradio as gr
import json
import yaml
import tempfile
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
import re
from pathlib import Path
# Set NLTK data directory - use the environment variable or default to a writable location
nltk_data_dir = os.environ.get("NLTK_DATA", "/home/user/local/share/nltk_data")
os.environ["NLTK_DATA"] = nltk_data_dir
os.makedirs(nltk_data_dir, exist_ok=True)
print(f"NLTK data directory set to: {nltk_data_dir}")
# VERSA paths - these are set by the Dockerfile
VERSA_ROOT = "/home/user/app/versa"
VERSA_BIN = os.path.join(VERSA_ROOT, "versa", "bin", "scorer.py")
VERSA_CONFIG_DIR = os.path.join(VERSA_ROOT, "egs", "demo")
# Data directories - also set up by the Dockerfile
DATA_DIR = "/home/user/app/data"
UPLOAD_DIR = os.path.join(DATA_DIR, "uploads")
RESULTS_DIR = os.path.join(DATA_DIR, "results")
CONFIG_DIR = os.path.join(DATA_DIR, "configs")
# Create directories if they don't exist
for directory in [DATA_DIR, UPLOAD_DIR, RESULTS_DIR, CONFIG_DIR]:
os.makedirs(directory, exist_ok=True)
# Debug information
print(f"Current user ID: {os.getuid()}")
print(f"Current effective user ID: {os.geteuid()}")
print(f"Current working directory: {os.getcwd()}")
print(f"Data directory permissions: {oct(os.stat(DATA_DIR).st_mode)}")
print(f"NLTK data directory permissions: {oct(os.stat(nltk_data_dir).st_mode) if os.path.exists(nltk_data_dir) else 'Not found'}")
# Custom function to handle mixed data types
def format_value(value):
return f"{value:.2f}" if isinstance(value, float) else value
def convert_python_dict_to_json(py_dict_str):
result = py_dict_str
# Handle dictionary keys
result = re.sub(r"'([^']*)'(?=\s*:)", r'"\1"', result)
# Handle string values (this is tricky with nested apostrophes)
result = re.sub(r':\s*\'([^\']*)\'', lambda m: ': "' + m.group(1).replace('"', '\\"') + '"', result)
# Replace Python's True/False/None with JSON equivalents
result = result.replace('True', 'true').replace('False', 'false').replace('None', 'null').replace("inf", "Infinity")
return result
# Check if VERSA is installed
def check_versa_installation():
"""Check if VERSA is properly installed"""
if not os.path.exists(VERSA_ROOT):
return False, "VERSA directory not found."
if not os.path.exists(VERSA_BIN):
return False, "VERSA binary not found."
if not os.path.exists(VERSA_CONFIG_DIR):
return False, "VERSA configuration directory not found."
# Check if the .installation_complete file exists (created by Dockerfile)
if not os.path.exists(os.path.join(VERSA_ROOT, ".installation_complete")):
return False, "VERSA installation indicator file not found."
return True, "VERSA is properly installed."
# Check VERSA installation at startup
versa_installed, versa_status = check_versa_installation()
print(f"VERSA installation status: {versa_status}")
# Find available metric configs
def get_available_metrics():
"""Get list of available metrics from VERSA config directory"""
metrics = []
if not versa_installed:
# If VERSA is not installed, return an empty list
return metrics
# Get all YAML files from the egs directory
for root, _, files in os.walk(VERSA_CONFIG_DIR):
for file in files:
if file.endswith('.yaml'):
path = os.path.join(root, file)
# Get relative path from VERSA_CONFIG_DIR
rel_path = os.path.relpath(path, VERSA_CONFIG_DIR)
metrics.append(rel_path)
# Add custom configs
for root, _, files in os.walk(CONFIG_DIR):
for file in files:
if file.endswith('.yaml'):
path = os.path.join(root, file)
rel_path = f"custom/{os.path.basename(path)}"
metrics.append(rel_path)
return sorted(metrics)
# Get all available metric names
def get_available_metric_names():
"""Get list of all available metric names in VERSA"""
metric_names = set()
if not versa_installed:
# If VERSA is not installed, return an empty list
return []
# First check the universal metrics file
universal_metrics_yaml = os.path.join(CONFIG_DIR, "universal_metrics.yaml")
if os.path.exists(universal_metrics_yaml):
try:
with open(universal_metrics_yaml, 'r') as f:
config = yaml.safe_load(f)
if isinstance(config, list):
for item in config:
if isinstance(item, dict) and 'name' in item:
metric_names.add(item['name'])
except Exception:
pass
# Then parse all YAML files to extract additional metric names
for root, _, files in os.walk(VERSA_CONFIG_DIR):
for file in files:
if file.endswith('.yaml'):
path = os.path.join(root, file)
try:
with open(path, 'r') as f:
config = yaml.safe_load(f)
if isinstance(config, list):
for item in config:
if isinstance(item, dict) and 'name' in item:
metric_names.add(item['name'])
except Exception:
pass
return sorted(list(metric_names))
# Get metric description from YAML file
def get_metric_description(metric_path):
"""Get description of a metric from its YAML file"""
if not versa_installed:
return "VERSA is not installed. Metric descriptions are unavailable."
if metric_path.startswith("custom/"):
# Handle custom metrics
filename = metric_path.split("/")[1]
full_path = os.path.join(CONFIG_DIR, filename)
else:
full_path = os.path.join(VERSA_CONFIG_DIR, metric_path)
try:
with open(full_path, 'r') as f:
config = yaml.safe_load(f)
# Check if the config has a description field
if isinstance(config, dict) and 'description' in config:
return config.get('description', 'No description available')
# If it's a list of metrics, return a summary
if isinstance(config, list):
metric_names = []
for item in config:
if isinstance(item, dict) and 'name' in item:
metric_names.append(item['name'])
if metric_names:
return f"Contains metrics: {', '.join(metric_names)}"
return "No description available"
except Exception as e:
return f"Could not load description: {str(e)}"
# Create custom metric config file
def create_custom_metric_config(selected_metrics, metric_parameters):
"""Create a custom metric configuration file from selected metrics"""
if not versa_installed:
return None, "VERSA is not installed. Cannot create custom metric configuration."
if not selected_metrics:
return None, "Please select at least one metric"
# Load universal metrics as reference
universal_metrics = []
universal_metrics_yaml = os.path.join(CONFIG_DIR, "universal_metrics.yaml")
try:
with open(universal_metrics_yaml, 'r') as f:
universal_metrics = yaml.safe_load(f)
except Exception as e:
return None, f"Error loading universal metrics: {str(e)}"
# Create new metric config
custom_metrics = []
for metric_name in selected_metrics:
# Find the metric in universal metrics
for metric in universal_metrics:
if metric.get('name') == metric_name:
# Add the metric to custom metrics
custom_metrics.append(metric.copy())
break
# Apply any custom parameters from metric_parameters
if metric_parameters:
try:
params = yaml.safe_load(metric_parameters)
if isinstance(params, dict):
for metric in custom_metrics:
metric_name = metric.get('name')
if metric_name in params and isinstance(params[metric_name], dict):
# Update metric parameters
metric.update(params[metric_name])
except Exception as e:
return None, f"Error parsing metric parameters: {str(e)}"
# Create a custom YAML file
timestamp = int(time.time())
custom_yaml_path = os.path.join(CONFIG_DIR, f"custom_metrics_{timestamp}.yaml")
try:
with open(custom_yaml_path, 'w') as f:
yaml.dump(custom_metrics, f, default_flow_style=False)
return f"custom/{os.path.basename(custom_yaml_path)}", f"Custom metric configuration created successfully with {len(custom_metrics)} metrics"
except Exception as e:
return None, f"Error creating custom metric configuration: {str(e)}"
# Load metric config file
def load_metric_config(config_path):
"""Load a metric configuration file and return its content"""
if not versa_installed and not config_path.startswith("custom/"):
return "VERSA is not installed. Cannot load metric configuration."
if config_path.startswith("custom/"):
# Handle custom metrics
filename = config_path.split("/")[1]
full_path = os.path.join(CONFIG_DIR, filename)
else:
full_path = os.path.join(VERSA_CONFIG_DIR, config_path)
try:
with open(full_path, 'r') as f:
content = f.read()
return content
except Exception as e:
return f"Error loading metric configuration: {str(e)}"
# Save uploaded YAML file
def save_uploaded_yaml(file_obj):
"""Save an uploaded YAML file to the configs directory"""
if file_obj is None:
return None, "No file uploaded"
try:
# Get the file name and create a new path
filename = os.path.basename(file_obj.name)
if not filename.endswith('.yaml'):
filename += '.yaml'
# Ensure unique filename
timestamp = int(time.time())
yaml_path = os.path.join(CONFIG_DIR, f"uploaded_{timestamp}_{filename}")
# Copy the file
with open(file_obj.name, 'rb') as src, open(yaml_path, 'wb') as dst:
dst.write(src.read())
# Validate YAML format
with open(yaml_path, 'r') as f:
yaml.safe_load(f)
return f"custom/{os.path.basename(yaml_path)}", f"YAML file uploaded successfully as {os.path.basename(yaml_path)}"
except yaml.YAMLError:
if os.path.exists(yaml_path):
os.remove(yaml_path)
return None, "Invalid YAML format. Please check your file."
except Exception as e:
if os.path.exists(yaml_path):
os.remove(yaml_path)
return None, f"Error uploading YAML file: {str(e)}"
# Process audio files and run VERSA evaluation
def evaluate_audio(gt_file, pred_file, metric_config, include_timestamps=False):
"""Evaluate audio files using VERSA"""
if not versa_installed:
return None, "VERSA is not installed. Evaluation cannot be performed."
if pred_file is None:
return None, "Please upload the audio file to be evaluated."
# Determine the metric config path
if metric_config.startswith("custom/"):
# Handle custom metrics
filename = metric_config.split("/")[1]
metric_config_path = os.path.join(CONFIG_DIR, filename)
else:
metric_config_path = os.path.join(VERSA_CONFIG_DIR, metric_config)
# Create temp directory for results
with tempfile.TemporaryDirectory() as temp_dir:
output_file = os.path.join(temp_dir, "result.json")
# Create SCP file
pred_scp_path = os.path.join(temp_dir, "pred.scp")
with open(pred_scp_path, "w") as pred_scp:
pred_scp.write("test {}\n".format(pred_file))
# For case without reference audio
if gt_file is not None:
gt_scp_path = os.path.join(temp_dir, "gt.scp")
with open(gt_scp_path, "w") as gt_scp:
gt_scp.write("test {}\n".format(gt_file))
else:
gt_scp_path = "None"
# Build command
cmd = [
sys.executable, VERSA_BIN,
"--score_config", metric_config_path,
"--gt", gt_scp_path,
"--pred", pred_scp_path,
"--output_file", output_file,
"--use_gpu", "true",
]
if include_timestamps:
cmd.append("--include_timestamp")
# Run VERSA evaluation
try:
# Set environment variables for the subprocess
env = os.environ.copy()
env["LIBROSA_CACHE_DIR"] = "/tmp/librosa_cache"
env["LIBROSA_CACHE_LEVEL"] = "0"
# Pass through the NLTK_DATA environment variable
env["NLTK_DATA"] = nltk_data_dir
# Set huggingface cache
env["HF_HOME"] = "/home/user/.cache/huggingface"
process = subprocess.run(
cmd,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
env=env,
)
# Read results
if os.path.exists(output_file):
with open(output_file, 'r') as f:
output_file_result = f.read().strip()
print(convert_python_dict_to_json(output_file_result))
results = json.loads(convert_python_dict_to_json(output_file_result))
results = {key: format_value(value) for key, value in results.items()}
# Format results as DataFrame
if results:
results_df = pd.DataFrame([results])
return results_df, json.dumps(results, indent=2)
else:
return None, "Evaluation completed but no results were generated."
else:
return None, "Evaluation completed but no results file was generated."
except subprocess.CalledProcessError as e:
return None, f"Error running VERSA: {e.stderr}"
# Create the Gradio interface
def create_gradio_demo():
"""Create the Gradio demo interface"""
available_metrics = get_available_metrics()
default_metric = "speech.yaml" if "speech.yaml" in available_metrics else available_metrics[0] if available_metrics else None
metric_names = get_available_metric_names()
with gr.Blocks(title="VERSA Speech & Audio Evaluation Demo") as demo:
gr.Markdown("# VERSA: Versatile Evaluation of Speech and Audio")
# Display installation status
with gr.Row():
installation_status = gr.Textbox(
value=f"VERSA Installation Status: {'Installed' if versa_installed else 'Not Installed - ' + versa_status}",
label="Installation Status",
interactive=False
)
if not versa_installed:
gr.Markdown(f"""
## ⚠️ VERSA Not Installed
VERSA does not appear to be properly installed. The Docker container may not have been set up correctly.
Error: {versa_status}
Please check the Docker build logs or contact the administrator.
""")
else:
gr.Markdown("Upload audio files and evaluate them using VERSA metrics.")
with gr.Tabs() as tabs:
# Standard evaluation tab
with gr.TabItem("Standard Evaluation"):
with gr.Row():
with gr.Column():
pred_audio = gr.Audio(label="Prediction Audio", type="filepath", sources=["upload", "microphone"])
gt_audio = gr.Audio(label="Ground Truth Audio", type="filepath", sources=["upload", "microphone"])
metric_dropdown = gr.Dropdown(
choices=available_metrics,
label="Evaluation Metric Configuration",
value=default_metric,
info="Select a pre-defined or custom metric configuration"
)
with gr.Accordion("Metric Configuration Details", open=False):
metric_description = gr.Textbox(
label="Metric Description",
value=get_metric_description(default_metric) if default_metric else "",
interactive=False
)
metric_content = gr.Code(
label="Configuration Content",
language="yaml",
value=load_metric_config(default_metric) if default_metric else "",
interactive=False
)
# include_timestamps = gr.Checkbox(
# label="Include Timestamps in Results",
# value=False
# )
eval_button = gr.Button("Evaluate")
with gr.Column():
results_table = gr.Dataframe(label="Evaluation Results")
raw_json = gr.Code(language="json", label="Raw Results")
# Custom metrics creation tab
with gr.TabItem("Create Custom Metrics"):
with gr.Row():
with gr.Column():
gr.Markdown("### Option 1: Select from Available Metrics")
metrics_checklist = gr.CheckboxGroup(
choices=metric_names,
label="Available Metrics",
info="Select the metrics you want to include in your custom configuration"
)
metric_params = gr.Code(
label="Custom Parameters (Optional, YAML format)",
language="yaml",
interactive=True
)
create_custom_button = gr.Button("Create Custom Configuration")
custom_status = gr.Textbox(label="Status", interactive=False)
with gr.Column():
gr.Markdown("### Option 2: Upload Your Own YAML File")
uploaded_yaml = gr.File(
label="Upload YAML Configuration",
file_types=[".yaml", ".yml"],
type="filepath"
)
upload_button = gr.Button("Upload Configuration")
upload_status = gr.Textbox(label="Upload Status", interactive=False)
gr.Markdown("### Generated Configuration")
custom_config_path = gr.Textbox(
label="Configuration Path",
interactive=False,
visible=False
)
custom_config_content = gr.Code(
label="Configuration Content",
language="yaml",
interactive=False
)
# About tab
with gr.TabItem("About VERSA"):
gr.Markdown("""
## VERSA: Versatile Evaluation of Speech and Audio
VERSA is a toolkit dedicated to collecting evaluation metrics in speech and audio quality.
It provides a comprehensive connection to cutting-edge evaluation techniques and is tightly integrated with ESPnet.
With full installation, VERSA offers over 80 metrics with 700+ metric variations based on different configurations.
These metrics encompass evaluations utilizing diverse external resources, including matching and non-matching
reference audio, text transcriptions, and text captions.
### Features
- Pythonic interface with flexible configuration
- Support for various audio formats and evaluation scenarios
- Integration with ESPnet
- Batch processing capabilities
- Customizable evaluation metrics
### Citation
```
@inproceedings{shi2025versa,
title={{VERSA}: A Versatile Evaluation Toolkit for Speech, Audio, and Music},
author={Jiatong Shi and Hye-jin Shim and Jinchuan Tian and Siddhant Arora and Haibin Wu and Darius Petermann and Jia Qi Yip and You Zhang and Yuxun Tang and Wangyou Zhang and Dareen Safar Alharthi and Yichen Huang and Koichi Saito and Jionghao Han and Yiwen Zhao and Chris Donahue and Shinji Watanabe},
booktitle={2025 Annual Conference of the North American Chapter of the Association for Computational Linguistics -- System Demonstration Track},
year={2025},
url={https://openreview.net/forum?id=zU0hmbnyQm}
}
@inproceedings{shi2024versaversatileevaluationtoolkit,
author={Shi, Jiatong and Tian, Jinchuan and Wu, Yihan and Jung, Jee-Weon and Yip, Jia Qi and Masuyama, Yoshiki and Chen, William and Wu, Yuning and Tang, Yuxun and Baali, Massa and Alharthi, Dareen and Zhang, Dong and Deng, Ruifan and Srivastava, Tejes and Wu, Haibin and Liu, Alexander and Raj, Bhiksha and Jin, Qin and Song, Ruihua and Watanabe, Shinji},
booktitle={2024 IEEE Spoken Language Technology Workshop (SLT)},
title={ESPnet-Codec: Comprehensive Training and Evaluation of Neural Codecs For Audio, Music, and Speech},
year={2024},
pages={562-569},
keywords={Training;Measurement;Codecs;Speech coding;Conferences;Focusing;Neural codecs;codec evaluation},
doi={10.1109/SLT61566.2024.10832289}
}
```
Learn more at [VERSA GitHub Repository](https://github.com/shinjiwlab/versa).
""")
# Event handlers
def update_metric_details(metric_path):
return get_metric_description(metric_path), load_metric_config(metric_path)
metric_dropdown.change(
fn=update_metric_details,
inputs=[metric_dropdown],
outputs=[metric_description, metric_content]
)
eval_button.click(
fn=evaluate_audio,
inputs=[gt_audio, pred_audio, metric_dropdown], # include_timestamps
outputs=[results_table, raw_json]
)
# Create custom metric configuration
def create_and_update_custom_config(selected_metrics, metric_parameters):
config_path, status = create_custom_metric_config(selected_metrics, metric_parameters)
if config_path:
content = load_metric_config(config_path)
# Refresh the available metrics list
metrics_list = get_available_metrics()
return status, config_path, content, gr.Dropdown.update(choices=metrics_list, value=config_path)
else:
return status, None, "", gr.Dropdown.update(choices=get_available_metrics())
create_custom_button.click(
fn=create_and_update_custom_config,
inputs=[metrics_checklist, metric_params],
outputs=[custom_status, custom_config_path, custom_config_content, metric_dropdown]
)
# Upload YAML file
def upload_and_update_yaml(file_obj):
config_path, status = save_uploaded_yaml(file_obj)
if config_path:
content = load_metric_config(config_path)
# Refresh the available metrics list
metrics_list = get_available_metrics()
return status, config_path, content, gr.Dropdown.update(choices=metrics_list, value=config_path)
else:
return status, None, "", gr.Dropdown.update(choices=get_available_metrics())
upload_button.click(
fn=upload_and_update_yaml,
inputs=[uploaded_yaml],
outputs=[upload_status, custom_config_path, custom_config_content, metric_dropdown]
)
return demo
# Launch the app
if __name__ == "__main__":
demo = create_gradio_demo()
# Use 0.0.0.0 to listen on all interfaces, which is required for Docker
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|