Spaces:
Running on Zero
Running on Zero
File size: 54,944 Bytes
fba9ebe 78498dd fba9ebe 78498dd fba9ebe 78498dd 65d5dac c93b3b8 26e0f70 78498dd 2b6e54a 78498dd fba9ebe 78498dd 84a194d 78498dd 40271e1 65d5dac a98c4d2 65d5dac 26e0f70 947596b 78498dd dba98b3 6ca1775 dba98b3 6ca1775 dba98b3 6ca1775 dba98b3 78498dd a98c4d2 78498dd fba9ebe d322e45 a98c4d2 d322e45 78498dd 4bcf81a 67ba0d5 78498dd 67ba0d5 4bcf81a 78498dd 67ba0d5 78498dd 2b6e54a 78498dd 67ba0d5 78498dd 67ba0d5 78498dd 67ba0d5 4bcf81a 78498dd 67ba0d5 78498dd 40271e1 78498dd 67ba0d5 78498dd 40271e1 78498dd fba9ebe 78498dd fba9ebe 78498dd 40271e1 c93b3b8 fba9ebe 29d3797 fba9ebe c93b3b8 fba9ebe c93b3b8 fba9ebe d322e45 40271e1 78498dd fba9ebe 78498dd fba9ebe 78498dd fba9ebe 78498dd 65d5dac dba98b3 65d5dac 78498dd 40271e1 78498dd fba9ebe d322e45 4bcf81a 4b7f3b6 78498dd 67ba0d5 78498dd d322e45 40271e1 fba9ebe 4bcf81a 65d5dac 78498dd d322e45 78498dd fba9ebe 78498dd fba9ebe 78498dd 4bcf81a d322e45 4bcf81a d322e45 fba9ebe 78498dd fba9ebe 78498dd fba9ebe 7772bb7 fba9ebe 7772bb7 78498dd fba9ebe 78498dd fba9ebe d322e45 78498dd fba9ebe 7772bb7 fba9ebe c93b3b8 fba9ebe 40271e1 fba9ebe 7772bb7 c93b3b8 fba9ebe c93b3b8 fba9ebe c93b3b8 fba9ebe d322e45 40271e1 fba9ebe 78498dd d322e45 78498dd fba9ebe d322e45 fba9ebe 4bcf81a 29d3797 fba9ebe 4bcf81a d322e45 fba9ebe 4bcf81a fba9ebe 78498dd fba9ebe 4bcf81a fba9ebe 78498dd 4bcf81a 78498dd 4bcf81a d322e45 4bcf81a d322e45 4bcf81a 78498dd 65d5dac a98c4d2 65d5dac 26e0f70 65d5dac 4b7f3b6 65d5dac 947596b 65d5dac 40271e1 dba98b3 a98c4d2 40271e1 4b7f3b6 40271e1 78498dd 40271e1 78498dd a98c4d2 4b7f3b6 a98c4d2 78498dd f812300 78498dd f812300 c4db08d f812300 40271e1 f812300 78498dd 5d34a71 78498dd | 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 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 | import io
import json
import math
import os
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.request
import warnings
from datetime import datetime
from pathlib import Path
from typing import List, Optional, Tuple
import gradio as gr
import librosa
import numpy as np
import soundfile as sf
import torch
import torchaudio
from datasets import (
Audio,
Dataset,
DatasetDict,
IterableDataset,
IterableDatasetDict,
Value,
concatenate_datasets,
load_dataset,
)
from dotenv import load_dotenv
from huggingface_hub import HfApi, hf_hub_download
from rich.console import Console
try:
import spaces
except Exception: # pragma: no cover - spaces is only available on HF Spaces
class _SpacesFallback:
def GPU(self, *args, **kwargs):
def decorator(fn):
return fn
return decorator
spaces = _SpacesFallback()
# Initialize console for pretty printing
console = Console()
DEFAULT_SAMPLE_RATE = 16000
AUDIO_EXTENSIONS = (".wav", ".mp3", ".flac")
DEFAULT_TARGET_DBFS = -20.0
DEFAULT_MAX_BOOST_DB = 20.0
DEFAULT_MAX_ATTEN_DB = 10.0
DEFAULT_AUTO_RESUME = bool(os.getenv("SPACE_ID"))
DEFAULT_ZERO_GPU_SHARD_SIZE = int(
os.getenv("CHIZZLER_ZERO_GPU_SHARD_SIZE", "25")
)
DEFAULT_ZERO_GPU_MAX_SHARDS = int(
os.getenv("CHIZZLER_ZERO_GPU_MAX_SHARDS", "1")
)
SPACE_ID = os.getenv("SPACE_ID")
warnings.filterwarnings(
"ignore",
message=(
"LoginButton created outside of a Blocks context\\. "
"May not work unless you call its `activate\\(\\)` method manually\\."
),
)
def log_progress(message: str, level: int = 1, enabled: bool = True) -> None:
"""Log a progress message with timestamp and indentation."""
if not enabled:
return
indent = " " * (level - 1)
timestamp = datetime.now().strftime("%H:%M:%S")
console.print(f"[dim]{timestamp}[/dim] {indent}[bold blue]>[/bold blue] {message}")
sys.stdout.flush()
# Load environment variables
load_dotenv()
_GPU_DURATION = os.getenv("CHIZZLER_GPU_DURATION")
_GPU_DURATION_MAX = os.getenv("CHIZZLER_GPU_DURATION_MAX")
if _GPU_DURATION is not None:
try:
DEFAULT_GPU_DURATION = int(_GPU_DURATION)
except ValueError:
DEFAULT_GPU_DURATION = 0
else:
DEFAULT_GPU_DURATION = 0
if _GPU_DURATION_MAX is not None:
try:
max_duration = int(_GPU_DURATION_MAX)
if max_duration > 0:
DEFAULT_GPU_DURATION = min(DEFAULT_GPU_DURATION, max_duration)
except ValueError:
pass
def gpu_decorator(duration: int):
if duration and duration > 0:
try:
return spaces.GPU(duration=duration)
except TypeError:
return spaces.GPU
return spaces.GPU
def get_hf_token() -> Optional[str]:
return (
os.getenv("HF_TOKEN")
or os.getenv("HUGGINGFACEHUB_API_TOKEN")
or os.getenv("HF_API_TOKEN")
)
def normalize_dataset_id(value: str) -> str:
if not value:
return ""
value = value.strip()
if value.startswith("http"):
if "datasets/" in value:
value = value.split("datasets/", 1)[1]
elif "huggingface.co/" in value:
value = value.split("huggingface.co/", 1)[1]
value = value.split("?")[0].split("#")[0].strip("/")
parts = [part for part in value.split("/") if part]
if len(parts) >= 2:
return "/".join(parts[:2])
return value
CURRENT_DIR = Path(__file__).parent.resolve()
DEFAULT_MP_SENET_DIR = Path(os.getenv("MPSENET_DIR", CURRENT_DIR / "MP-SENet"))
MPSENET_GIT_REPO = os.getenv(
"MPSENET_GIT_REPO", "https://github.com/yxlu-0102/MP-SENet.git"
)
CACHE_DIR = Path(os.getenv("CHIZZLER_CACHE_DIR", CURRENT_DIR / "chizzler_cache"))
_ENV_MAX_SHARDS = os.getenv("CHIZZLER_MAX_SHARDS_PER_RUN")
if _ENV_MAX_SHARDS is not None:
DEFAULT_MAX_SHARDS_PER_RUN = int(_ENV_MAX_SHARDS)
else:
DEFAULT_MAX_SHARDS_PER_RUN = 1 if os.getenv("SPACE_ID") else 0
_ENV_CACHE_TO_HUB = os.getenv("CHIZZLER_CACHE_TO_HUB")
if _ENV_CACHE_TO_HUB is None:
DEFAULT_CACHE_TO_HUB = bool(os.getenv("SPACE_ID"))
else:
DEFAULT_CACHE_TO_HUB = _ENV_CACHE_TO_HUB.strip().lower() in ("1", "true", "yes")
def ensure_mpsenet_repo() -> Path:
if DEFAULT_MP_SENET_DIR.exists():
return DEFAULT_MP_SENET_DIR
auto_download = os.getenv("MPSENET_AUTO_DOWNLOAD") == "1" or os.getenv("SPACE_ID")
if auto_download:
log_progress("MP-SENet repo not found. Cloning...", 2)
try:
subprocess.run(
[
"git",
"clone",
"--depth=1",
MPSENET_GIT_REPO,
str(DEFAULT_MP_SENET_DIR),
],
check=True,
)
except Exception as exc:
raise RuntimeError(
"Failed to clone MP-SENet. Clone it manually or set MPSENET_DIR."
) from exc
return DEFAULT_MP_SENET_DIR
raise FileNotFoundError(
"MP-SENet repo not found. Clone it into MP-SENet/ or set MPSENET_DIR."
)
def resolve_mpsenet_files(mp_senet_dir: Path) -> Tuple[Path, Path]:
config_path = mp_senet_dir / "best_ckpt" / "config.json"
ckpt_path = mp_senet_dir / "best_ckpt" / "g_best_dns"
if config_path.exists() and ckpt_path.exists():
return config_path, ckpt_path
repo_id = os.getenv("MPSENET_REPO")
if repo_id:
config_filename = os.getenv("MPSENET_CONFIG_FILENAME", "config.json")
ckpt_filename = os.getenv("MPSENET_CKPT_FILENAME", "g_best_dns")
config_path = Path(
hf_hub_download(repo_id=repo_id, filename=config_filename)
)
ckpt_path = Path(hf_hub_download(repo_id=repo_id, filename=ckpt_filename))
return config_path, ckpt_path
raise FileNotFoundError(
"MP-SENet checkpoint files not found. Place best_ckpt/config.json and "
"best_ckpt/g_best_dns under MP-SENet/ or set MPSENET_REPO."
)
mp_senet_dir = ensure_mpsenet_repo()
sys.path.append(str(mp_senet_dir))
from dataset import mag_pha_istft, mag_pha_stft # noqa: E402
from env import AttrDict # noqa: E402
from models.model import MPNet # noqa: E402
def select_device() -> torch.device:
override = os.getenv("CHIZZLER_DEVICE", "").strip().lower()
if override:
return torch.device(override)
if torch.cuda.is_available():
return torch.device("cuda")
if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
def initialize_models(device_override: Optional[torch.device] = None):
log_progress("Initializing models...")
device = device_override or select_device()
log_progress(f"Using {device.type.upper()} for all operations", 2)
log_progress("Loading Silero VAD model...", 2)
model, utils = torch.hub.load(
repo_or_dir="snakers4/silero-vad",
model="silero_vad",
force_reload=False,
trust_repo=True,
)
vad_model = model.to(device)
log_progress("Loading MP-SENet model...", 2)
config_path, ckpt_path = resolve_mpsenet_files(mp_senet_dir)
with open(config_path, "r") as f:
config = AttrDict(json.loads(f.read()))
mpnet_model = MPNet(config).to(device)
state = torch.load(ckpt_path, map_location=device)
if isinstance(state, dict):
if "generator" in state:
state = state["generator"]
elif "state_dict" in state:
state = state["state_dict"]
mpnet_model.load_state_dict(state)
mpnet_model.eval()
return vad_model, utils, mpnet_model, config, device
vad_model = None
vad_utils = None
mpnet_model = None
mpnet_config = None
device = None
def get_models():
global vad_model, vad_utils, mpnet_model, mpnet_config, device
desired_device = select_device()
if vad_model is None or mpnet_model is None or mpnet_config is None:
vad_model, vad_utils, mpnet_model, mpnet_config, device = (
initialize_models(desired_device)
)
return vad_model, vad_utils, mpnet_model, mpnet_config, device
if device is None or str(device) != str(desired_device):
log_progress(f"Moving models to {desired_device}...", 2)
vad_model = vad_model.to(desired_device)
mpnet_model = mpnet_model.to(desired_device)
device = desired_device
return vad_model, vad_utils, mpnet_model, mpnet_config, device
def ensure_mono(waveform: torch.Tensor) -> torch.Tensor:
if waveform.dim() == 1:
return waveform.unsqueeze(0)
if waveform.dim() == 2 and waveform.size(0) > waveform.size(1):
waveform = waveform.transpose(0, 1)
if waveform.size(0) > 1:
return torch.mean(waveform, dim=0, keepdim=True)
return waveform
def resample_waveform(
waveform: torch.Tensor, sample_rate: int, target_rate: int = DEFAULT_SAMPLE_RATE
) -> Tuple[torch.Tensor, int]:
if sample_rate == target_rate:
return waveform, sample_rate
resampler = torchaudio.transforms.Resample(sample_rate, target_rate)
return resampler(waveform), target_rate
def load_audio_file(file_path: str, log: bool = True) -> Tuple[torch.Tensor, int]:
log_progress(f"Loading audio: {Path(file_path).name}", enabled=log)
waveform = None
sample_rate = None
try:
waveform, sample_rate = torchaudio.load(file_path)
waveform = ensure_mono(waveform)
except Exception as exc:
log_progress(f"torchaudio load failed: {exc}", 2, enabled=log)
if waveform is None or sample_rate is None:
try:
data, sample_rate = sf.read(
file_path, always_2d=True, dtype="float32"
)
waveform = torch.from_numpy(data.T)
except Exception as exc:
log_progress(f"soundfile load failed: {exc}", 2, enabled=log)
data, sample_rate = librosa.load(
file_path, sr=None, mono=False, dtype=np.float32
)
if data.ndim == 1:
data = data[None, :]
waveform = torch.from_numpy(data)
waveform = ensure_mono(waveform)
if sample_rate != DEFAULT_SAMPLE_RATE:
log_progress(
f"Resampling from {sample_rate}Hz to {DEFAULT_SAMPLE_RATE}Hz...",
2,
enabled=log,
)
waveform, sample_rate = resample_waveform(
waveform, sample_rate, DEFAULT_SAMPLE_RATE
)
return waveform, sample_rate
def get_speech_timestamps(
waveform: torch.Tensor,
sample_rate: int,
threshold: float = 0.5,
log: bool = True,
) -> List[dict]:
log_progress("Detecting speech segments...", enabled=log)
vad_model, vad_utils, _, _, _ = get_models()
(get_speech_timestamps_fn, _, _, _, _) = vad_utils
speech_timestamps = get_speech_timestamps_fn(
waveform,
vad_model,
threshold=threshold,
return_seconds=True,
)
log_progress(f"Found {len(speech_timestamps)} speech segments", 2, enabled=log)
return speech_timestamps
def merge_close_segments(segments: List[dict], max_gap: float = 4.0) -> List[dict]:
if not segments:
return segments
merged = []
current_segment = segments[0].copy()
for segment in segments[1:]:
gap_duration = segment["start"] - current_segment["end"]
if gap_duration <= max_gap:
current_segment["end"] = segment["end"]
else:
merged.append(current_segment)
current_segment = segment.copy()
merged.append(current_segment)
return merged
def extract_speech_waveform(
waveform: torch.Tensor, sample_rate: int, segments: List[dict]
) -> Optional[torch.Tensor]:
if not segments:
return None
parts = []
total_samples = waveform.size(1)
for segment in segments:
start = max(0, int(segment["start"] * sample_rate))
end = min(total_samples, int(segment["end"] * sample_rate))
if end > start:
parts.append(waveform[:, start:end])
if not parts:
return None
return torch.cat(parts, dim=1)
def denoise_audio_chunk(
audio_tensor: torch.Tensor,
mpnet_model: torch.nn.Module,
mpnet_config: AttrDict,
chunk_size: int = 5 * DEFAULT_SAMPLE_RATE,
) -> torch.Tensor:
chunks = []
for i in range(0, audio_tensor.size(1), chunk_size):
chunk = audio_tensor[:, i : min(i + chunk_size, audio_tensor.size(1))]
energy = torch.sum(chunk**2.0, dim=1)
norm_factor = torch.sqrt(chunk.size(1) / (energy + 1e-8))
chunk = chunk * norm_factor.unsqueeze(1)
with torch.no_grad():
noisy_amp, noisy_pha, _ = mag_pha_stft(
chunk,
mpnet_config.n_fft,
mpnet_config.hop_size,
mpnet_config.win_size,
mpnet_config.compress_factor,
)
amp_g, pha_g, _ = mpnet_model(noisy_amp, noisy_pha)
audio_g = mag_pha_istft(
amp_g,
pha_g,
mpnet_config.n_fft,
mpnet_config.hop_size,
mpnet_config.win_size,
mpnet_config.compress_factor,
)
audio_g = audio_g / norm_factor.unsqueeze(1)
chunks.append(audio_g)
del chunk, noisy_amp, noisy_pha, amp_g, pha_g
return torch.cat(chunks, dim=1)
def process_waveform(
waveform: torch.Tensor,
sample_rate: int,
threshold: float = 0.5,
max_gap: float = 4.0,
log: bool = True,
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], str, bool]:
vad_model, vad_utils, mpnet_model, mpnet_config, device = get_models()
if waveform.device != device:
waveform = waveform.to(device)
log_progress("Stage 1: Voice Activity Detection", 2, enabled=log)
speech_timestamps = get_speech_timestamps(
waveform, sample_rate, threshold=threshold, log=log
)
merged_timestamps = merge_close_segments(speech_timestamps, max_gap)
details = ["Processing details:"]
if not merged_timestamps:
details.append("No speech detected in the audio.")
return None, None, "\n".join(details), False
for i, segment in enumerate(merged_timestamps, 1):
duration = segment["end"] - segment["start"]
details.append(
f"Segment {i}/{len(merged_timestamps)}: "
f"{segment['start']:.1f}s to {segment['end']:.1f}s "
f"(duration: {duration:.1f}s)"
)
vad_waveform = extract_speech_waveform(
waveform, sample_rate, merged_timestamps
)
if vad_waveform is None or vad_waveform.numel() == 0:
details.append("No speech detected after merging segments.")
return None, None, "\n".join(details), False
vad_duration = vad_waveform.size(1) / sample_rate
original_duration = waveform.size(1) / sample_rate
if original_duration > 0:
reduction = (1 - vad_duration / original_duration) * 100
else:
reduction = 0.0
details.append(f"VAD output duration: {vad_duration:.1f}s")
details.append(f"Reduced by: {reduction:.1f}%")
log_progress("Stage 2: MP-SENet denoising", 2, enabled=log)
with torch.no_grad():
denoised_waveform = denoise_audio_chunk(
vad_waveform, mpnet_model, mpnet_config
)
return vad_waveform, denoised_waveform, "\n".join(details), True
def process_audio_file(
audio_path: str,
threshold: float = 0.5,
max_gap: float = 4.0,
normalize_audio: bool = True,
target_dbfs: float = DEFAULT_TARGET_DBFS,
max_boost_db: float = DEFAULT_MAX_BOOST_DB,
max_atten_db: float = DEFAULT_MAX_ATTEN_DB,
) -> Tuple[str, str, str, str]:
log_progress(f"Processing: {Path(audio_path).name}")
waveform, sample_rate = load_audio_file(audio_path)
_, _, _, mpnet_config, _ = get_models()
vad_waveform, denoised_waveform, details, has_speech = process_waveform(
waveform, sample_rate, threshold=threshold, max_gap=max_gap, log=True
)
if not has_speech or vad_waveform is None or denoised_waveform is None:
return audio_path, audio_path, audio_path, details
if normalize_audio:
vad_waveform = normalize_waveform(
vad_waveform,
target_dbfs=target_dbfs,
max_boost_db=max_boost_db,
max_atten_db=max_atten_db,
)
denoised_waveform = normalize_waveform(
denoised_waveform,
target_dbfs=target_dbfs,
max_boost_db=max_boost_db,
max_atten_db=max_atten_db,
)
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as vad_file, \
tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as denoised_file:
vad_path = vad_file.name
denoised_path = denoised_file.name
sf.write(
vad_path,
vad_waveform.squeeze().cpu().numpy(),
mpnet_config.sampling_rate,
)
sf.write(
denoised_path,
denoised_waveform.squeeze().cpu().numpy(),
mpnet_config.sampling_rate,
)
return audio_path, vad_path, denoised_path, details
def load_audio_bytes(audio_bytes: bytes, log: bool = False) -> Tuple[torch.Tensor, int]:
data, sample_rate = sf.read(
io.BytesIO(audio_bytes), always_2d=True, dtype="float32"
)
waveform = torch.from_numpy(data.T)
waveform = ensure_mono(waveform)
if sample_rate != DEFAULT_SAMPLE_RATE:
log_progress(
f"Resampling from {sample_rate}Hz to {DEFAULT_SAMPLE_RATE}Hz...",
2,
enabled=log,
)
waveform, sample_rate = resample_waveform(
waveform, sample_rate, DEFAULT_SAMPLE_RATE
)
return waveform, sample_rate
def normalize_waveform(
waveform: Optional[torch.Tensor],
target_dbfs: float = DEFAULT_TARGET_DBFS,
max_boost_db: float = DEFAULT_MAX_BOOST_DB,
max_atten_db: float = DEFAULT_MAX_ATTEN_DB,
) -> Optional[torch.Tensor]:
if waveform is None or waveform.numel() == 0:
return waveform
rms = torch.sqrt(torch.mean(waveform**2))
if not torch.isfinite(rms) or rms <= 1e-8:
return waveform
current_db = 20.0 * torch.log10(rms)
gain_db = target_dbfs - current_db
gain_db = torch.clamp(gain_db, -max_atten_db, max_boost_db)
gain = torch.pow(torch.tensor(10.0, device=waveform.device), gain_db / 20.0)
normalized = waveform * gain
return torch.clamp(normalized, -1.0, 1.0)
def _is_http_url(value: str) -> bool:
return value.startswith("http://") or value.startswith("https://")
def _parse_hf_dataset_uri(uri: str) -> Optional[Tuple[str, str, Optional[str]]]:
prefix = "hf://datasets/"
if not uri.startswith(prefix):
return None
rest = uri[len(prefix) :]
if "/" not in rest:
return None
repo_id, file_path = rest.split("/", 1)
revision = None
if "@" in repo_id:
repo_id, revision = repo_id.split("@", 1)
return repo_id, file_path, revision
def load_audio_url(url: str, token: Optional[str], log: bool = False) -> Tuple[torch.Tensor, int]:
headers = {}
if token and "huggingface.co" in url:
headers["Authorization"] = f"Bearer {token}"
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request) as response:
data = response.read()
return load_audio_bytes(data, log=log)
def resolve_audio_path(
path: str, dataset_id: Optional[str], token: Optional[str]
) -> str:
if os.path.exists(path):
return path
parsed = _parse_hf_dataset_uri(path)
if parsed:
repo_id, filename, revision = parsed
try:
return hf_hub_download(
repo_id=repo_id,
repo_type="dataset",
filename=filename,
revision=revision,
token=token,
)
except Exception:
return path
if dataset_id and not os.path.isabs(path):
try:
return hf_hub_download(
repo_id=dataset_id,
repo_type="dataset",
filename=path,
token=token,
)
except Exception:
return path
return path
def prepare_waveform_from_entry(
entry,
log: bool = False,
dataset_id: Optional[str] = None,
token: Optional[str] = None,
) -> Tuple[torch.Tensor, int]:
if entry is None:
raise ValueError("Empty audio entry.")
if hasattr(entry, "get_all_samples"):
samples = entry.get_all_samples()
waveform = samples.data
sample_rate = samples.sample_rate
waveform = ensure_mono(waveform)
if sample_rate != DEFAULT_SAMPLE_RATE:
waveform, sample_rate = resample_waveform(
waveform, sample_rate, DEFAULT_SAMPLE_RATE
)
return waveform, sample_rate
if isinstance(entry, dict):
if entry.get("array") is not None:
sample_rate = entry.get("sampling_rate", DEFAULT_SAMPLE_RATE)
waveform = torch.tensor(entry["array"], dtype=torch.float32)
waveform = ensure_mono(waveform)
if sample_rate != DEFAULT_SAMPLE_RATE:
waveform, sample_rate = resample_waveform(
waveform, sample_rate, DEFAULT_SAMPLE_RATE
)
return waveform, sample_rate
if entry.get("bytes"):
audio_bytes = entry["bytes"]
if not isinstance(audio_bytes, (bytes, bytearray)):
audio_bytes = bytes(audio_bytes)
return load_audio_bytes(audio_bytes, log=log)
if entry.get("path"):
path = resolve_audio_path(entry["path"], dataset_id, token)
if _is_http_url(path):
return load_audio_url(path, token, log=log)
return load_audio_file(path, log=log)
if isinstance(entry, str):
path = resolve_audio_path(entry, dataset_id, token)
if _is_http_url(path):
return load_audio_url(path, token, log=log)
return load_audio_file(path, log=log)
raise ValueError("Unsupported audio entry format.")
def get_dataset_cache_dir(dataset_id: str, config: Optional[str]) -> Path:
slug = dataset_id.replace("/", "__")
if config:
slug = f"{slug}__{config}"
return CACHE_DIR / slug
def get_cache_slug(dataset_id: str, config: Optional[str]) -> str:
slug = dataset_id.replace("/", "__")
if config:
slug = f"{slug}__{config}"
return slug
def get_hub_cache_prefix(
dataset_id: str, config: Optional[str], split_name: str
) -> str:
slug = get_cache_slug(dataset_id, config)
return f"chizzler_cache/{slug}/{split_name}"
def load_split_meta(
split_cache_dir: Path,
hub_cache_prefix: str,
cache_on_hub: bool,
repo_id: str,
token: Optional[str],
) -> Optional[dict]:
meta_file = split_cache_dir / "_meta.json"
if meta_file.exists():
return json.loads(meta_file.read_text())
if cache_on_hub:
try:
meta_path = hf_hub_download(
repo_id=repo_id,
repo_type="dataset",
filename=f"{hub_cache_prefix}/_meta.json",
token=token,
)
return json.loads(Path(meta_path).read_text())
except Exception:
return None
return None
def infer_audio_column(dataset_obj) -> Optional[str]:
sample_ds = dataset_obj
if isinstance(dataset_obj, (DatasetDict, IterableDatasetDict)):
sample_ds = next(iter(dataset_obj.values()))
if hasattr(sample_ds, "features"):
for column, feature in sample_ds.features.items():
if isinstance(feature, Audio):
return column
if isinstance(sample_ds, Dataset) and len(sample_ds) > 0:
sample = sample_ds[0]
for column, value in sample.items():
if isinstance(value, dict) and (
"array" in value or "path" in value or "bytes" in value
):
return column
if isinstance(value, str) and value.lower().endswith(AUDIO_EXTENSIONS):
return column
return None
def default_output_repo(source_id: str, username: str) -> str:
name = source_id.split("/")[-1]
suffix = "representation-chizzler"
if not name.endswith(suffix):
name = f"{name}-{suffix}"
return f"{username}/{name}"
def _apply_zero_gpu_limits(
shard_size: int, max_shards: Optional[int]
) -> Tuple[int, Optional[int]]:
if not os.getenv("SPACE_ID"):
return shard_size, max_shards
adjusted_shard_size = min(shard_size, DEFAULT_ZERO_GPU_SHARD_SIZE)
if max_shards is None:
adjusted_max_shards = DEFAULT_ZERO_GPU_MAX_SHARDS
else:
adjusted_max_shards = min(max_shards, DEFAULT_ZERO_GPU_MAX_SHARDS)
return adjusted_shard_size, adjusted_max_shards
@gpu_decorator(DEFAULT_GPU_DURATION)
def _process_dataset_and_push_gpu(
dataset_id: str,
config: str,
split: str,
audio_column: str,
output_repo: str,
private_repo: bool,
vad_threshold: float,
max_silence_gap: float,
normalize_audio: bool,
target_dbfs: float,
max_boost_db: float,
max_atten_db: float,
max_examples: Optional[float],
resume_processing: bool,
shard_size: Optional[float],
cache_on_hub: bool,
max_shards_per_run: Optional[float],
request: gr.Request | None = None,
progress=gr.Progress(),
) -> str:
token = get_hf_token()
if not token:
return "Missing HF token. Set HF_TOKEN as a secret or env var."
dataset_id = normalize_dataset_id(dataset_id)
if not dataset_id:
return "Provide a dataset ID or URL."
# Ensure models are loaded on the correct device before heavy processing.
get_models()
config = config.strip() or None
split = split.strip()
audio_column = audio_column.strip()
output_repo = normalize_dataset_id(output_repo) if output_repo else ""
cache_on_hub = bool(cache_on_hub)
normalize_audio = bool(normalize_audio)
max_examples_int = int(max_examples) if max_examples and max_examples > 0 else None
shard_size_int = int(shard_size) if shard_size and shard_size > 0 else 1000
max_shards_int = (
int(max_shards_per_run)
if max_shards_per_run and max_shards_per_run > 0
else None
)
if os.getenv("SPACE_ID"):
adjusted_shard_size, adjusted_max_shards = _apply_zero_gpu_limits(
shard_size_int, max_shards_int
)
if adjusted_shard_size != shard_size_int:
log_progress(
f"ZeroGPU safe mode: shard size capped at {adjusted_shard_size}",
2,
)
shard_size_int = adjusted_shard_size
if adjusted_max_shards != max_shards_int:
log_progress(
f"ZeroGPU safe mode: max shards per run capped at {adjusted_max_shards}",
2,
)
max_shards_int = adjusted_max_shards
api = HfApi(token=token)
username = api.whoami()["name"]
repo_id = output_repo or default_output_repo(dataset_id, username)
if cache_on_hub:
api.create_repo(
repo_id, repo_type="dataset", private=private_repo, exist_ok=True
)
log_progress(
f"Caching shards to Hub repo: {repo_id}", 2
)
log_progress(f"Loading dataset: {dataset_id}")
progress(0, desc="Downloading dataset...")
if split and split.lower() != "all":
dataset_obj = load_dataset(
dataset_id, name=config, split=split, token=token
)
dataset_dict = DatasetDict({split: dataset_obj})
else:
dataset_obj = load_dataset(dataset_id, name=config, token=token)
dataset_dict = (
DatasetDict({"train": dataset_obj})
if isinstance(dataset_obj, Dataset)
else dataset_obj
)
progress(0.01, desc="Preparing splits...")
if not audio_column:
audio_column = infer_audio_column(dataset_dict) or ""
if not audio_column:
return (
"Could not infer audio column. Please specify the audio column "
"name manually."
)
processed_splits = {}
shards_processed = 0
cached_shards = 0
total_shards = 0
incomplete = False
repo_files = set()
if resume_processing and cache_on_hub:
try:
repo_files = set(
api.list_repo_files(repo_id, repo_type="dataset")
)
except Exception:
repo_files = set()
cache_root = get_dataset_cache_dir(dataset_id, config)
cache_root.mkdir(parents=True, exist_ok=True)
for split_name, split_ds in dataset_dict.items():
if (
hasattr(split_ds, "column_names")
and audio_column not in split_ds.column_names
):
return f"Audio column '{audio_column}' not found in split '{split_name}'."
try:
split_ds = split_ds.cast_column(
audio_column, Audio(sampling_rate=DEFAULT_SAMPLE_RATE)
)
except Exception:
split_ds = split_ds.cast_column(audio_column, Audio())
total = len(split_ds) if isinstance(split_ds, Dataset) else None
if max_examples_int and total is not None:
total = min(total, max_examples_int)
update_every = max(1, (total or max_examples_int or 100) // 100)
split_cache_dir = cache_root / split_name
if not resume_processing and split_cache_dir.exists():
shutil.rmtree(split_cache_dir)
split_cache_dir.mkdir(parents=True, exist_ok=True)
hub_cache_prefix = get_hub_cache_prefix(dataset_id, config, split_name)
features = split_ds.features.copy()
features[audio_column] = Audio(
sampling_rate=DEFAULT_SAMPLE_RATE
)
features["chizzler_ok"] = Value("bool")
features["chizzler_error"] = Value("string")
def make_map_fn(offset: int = 0):
def map_fn(example, idx):
entry = example.get(audio_column)
ok = True
error_message = ""
try:
waveform, sample_rate = prepare_waveform_from_entry(
entry, log=False, dataset_id=dataset_id, token=token
)
vad_waveform, denoised_waveform, _, has_speech = process_waveform(
waveform,
sample_rate,
threshold=vad_threshold,
max_gap=max_silence_gap,
log=False,
)
output_waveform = (
denoised_waveform
if has_speech and denoised_waveform is not None
else waveform
)
if normalize_audio:
output_waveform = normalize_waveform(
output_waveform,
target_dbfs=target_dbfs,
max_boost_db=max_boost_db,
max_atten_db=max_atten_db,
)
output_np = (
output_waveform.squeeze()
.detach()
.cpu()
.numpy()
.astype(np.float32)
)
if output_np.size == 0:
ok = False
error_message = (
"Empty output waveform; using original audio."
)
output_np = (
waveform.squeeze()
.detach()
.cpu()
.numpy()
.astype(np.float32)
)
output_entry = {
"array": output_np,
"sampling_rate": DEFAULT_SAMPLE_RATE,
}
except Exception as exc:
ok = False
error_message = str(exc)
output_entry = entry if entry is not None else {
"array": np.zeros(1, dtype=np.float32),
"sampling_rate": DEFAULT_SAMPLE_RATE,
}
example[audio_column] = output_entry
example["chizzler_ok"] = ok
example["chizzler_error"] = error_message
global_idx = offset + idx + 1
if total:
if global_idx % update_every == 0 or global_idx == total:
progress(
global_idx / total,
desc=(
f"Processing {split_name}: {global_idx}/{total}"
),
)
else:
if global_idx % update_every == 0:
progress(
0,
desc=f"Processing {split_name}: {global_idx} examples",
)
return example
return map_fn
if total:
num_shards = math.ceil(total / shard_size_int)
total_shards += num_shards
meta = {
"dataset_id": dataset_id,
"config": config or "",
"split": split_name,
"audio_column": audio_column,
"total": total,
"shard_size": shard_size_int,
"num_shards": num_shards,
}
meta_file = split_cache_dir / "_meta.json"
meta_file.write_text(json.dumps(meta, indent=2))
if cache_on_hub:
api.upload_file(
path_or_fileobj=str(meta_file),
path_in_repo=f"{hub_cache_prefix}/_meta.json",
repo_id=repo_id,
repo_type="dataset",
)
shards = []
for shard_idx in range(num_shards):
start = shard_idx * shard_size_int
end = min(total, start + shard_size_int)
cache_file = split_cache_dir / (
f"{split_name}-{start:07d}-{end:07d}.arrow"
)
hub_cache_path = f"{hub_cache_prefix}/{cache_file.name}"
if resume_processing and cache_file.exists():
processed_shard = Dataset.from_file(str(cache_file))
progress(
end / total,
desc=f"Processing {split_name}: {end}/{total}",
)
cached_shards += 1
elif resume_processing and cache_on_hub and hub_cache_path in repo_files:
cache_path = hf_hub_download(
repo_id=repo_id,
repo_type="dataset",
filename=hub_cache_path,
token=token,
)
processed_shard = Dataset.from_file(cache_path)
progress(
end / total,
desc=f"Processing {split_name}: {end}/{total}",
)
cached_shards += 1
else:
if max_shards_int and shards_processed >= max_shards_int:
incomplete = True
break
indices = range(start, end)
try:
shard_ds = split_ds.select(indices)
except Exception:
shard_ds = split_ds.select(list(indices))
processed_shard = shard_ds.map(
make_map_fn(offset=start),
with_indices=True,
load_from_cache_file=False,
cache_file_name=str(cache_file),
writer_batch_size=50,
num_proc=None,
features=features,
desc=(
f"Chizzling {split_name} "
f"({shard_idx + 1}/{num_shards})"
),
)
shards_processed += 1
if cache_on_hub:
api.upload_file(
path_or_fileobj=str(cache_file),
path_in_repo=hub_cache_path,
repo_id=repo_id,
repo_type="dataset",
)
repo_files.add(hub_cache_path)
shards.append(processed_shard)
if incomplete:
break
processed_split = (
concatenate_datasets(shards)
if len(shards) > 1
else shards[0]
)
else:
if max_shards_int and shards_processed >= max_shards_int:
incomplete = True
break
processed_split = split_ds.map(
make_map_fn(offset=0),
with_indices=True,
load_from_cache_file=False,
writer_batch_size=50,
num_proc=None,
features=features,
desc=f"Chizzling {split_name}",
)
shards_processed += 1
processed_splits[split_name] = processed_split
if incomplete:
total_done = cached_shards + shards_processed
progress_note = (
f" ({total_done}/{total_shards} shards ready)"
if total_shards
else ""
)
return (
f"Processed {shards_processed} new shard(s)"
f"{f', cached {cached_shards}' if cached_shards else ''}"
f"{progress_note}."
" Resume with cached shards to continue."
)
processed_dataset = (
DatasetDict(processed_splits)
if len(processed_splits) > 1
else next(iter(processed_splits.values()))
)
progress(0, desc="Uploading to the Hub...")
processed_dataset.push_to_hub(repo_id, private=private_repo, token=token)
progress(1.0, desc="Upload complete.")
return (
f"Uploaded cleaned dataset to {repo_id} "
f"(audio column: {audio_column})."
)
def process_dataset_and_push(
dataset_id: str,
config: str,
split: str,
audio_column: str,
output_repo: str,
private_repo: bool,
vad_threshold: float,
max_silence_gap: float,
normalize_audio: bool,
target_dbfs: float,
max_boost_db: float,
max_atten_db: float,
max_examples: Optional[float],
resume_processing: bool,
auto_resume: bool,
shard_size: Optional[float],
cache_on_hub: bool,
max_shards_per_run: Optional[float],
request: gr.Request | None = None,
progress=gr.Progress(),
) -> str:
if SPACE_ID and request is not None:
headers = getattr(request, "headers", None)
token_header = None
if headers and hasattr(headers, "get"):
token_header = headers.get("x-ip-token")
if not token_header:
log_progress(
"ZeroGPU auth header missing. Use the Space on huggingface.co "
"to attach your login to ZeroGPU quota.",
2,
)
attempts = 0
while True:
try:
result = _process_dataset_and_push_gpu(
dataset_id,
config,
split,
audio_column,
output_repo,
private_repo,
vad_threshold,
max_silence_gap,
normalize_audio,
target_dbfs,
max_boost_db,
max_atten_db,
max_examples,
resume_processing,
shard_size,
cache_on_hub,
max_shards_per_run,
request=request,
progress=progress,
)
except Exception as exc:
message = str(exc)
if "ZeroGPU proxy token expired" in message:
return (
"ZeroGPU login token expired. Click Process/Resume again "
"to refresh your session."
)
if auto_resume and "GPU task aborted" in message:
attempts += 1
log_progress(
f"ZeroGPU preempted. Retrying (attempt {attempts})...",
2,
)
time.sleep(2)
continue
raise
if not auto_resume:
return result
if "Resume with cached shards" in result:
attempts += 1
log_progress(
f"Auto-resume: continuing (attempt {attempts})...",
2,
)
time.sleep(2)
continue
return result
def assemble_cached_dataset_and_push(
dataset_id: str,
config: str,
split: str,
audio_column: str,
output_repo: str,
private_repo: bool,
cache_on_hub: bool,
progress=gr.Progress(),
) -> str:
token = get_hf_token()
if not token:
return "Missing HF token. Set HF_TOKEN as a secret or env var."
dataset_id = normalize_dataset_id(dataset_id)
if not dataset_id:
return "Provide a dataset ID or URL."
config = config.strip() or None
split = split.strip()
audio_column = audio_column.strip()
output_repo = normalize_dataset_id(output_repo) if output_repo else ""
cache_on_hub = bool(cache_on_hub)
api = HfApi(token=token)
username = api.whoami()["name"]
repo_id = output_repo or default_output_repo(dataset_id, username)
cache_root = get_dataset_cache_dir(dataset_id, config)
cache_slug = get_cache_slug(dataset_id, config)
if split and split.lower() != "all":
split_names = [split]
else:
if cache_on_hub:
repo_files = api.list_repo_files(repo_id, repo_type="dataset")
prefix = f"chizzler_cache/{cache_slug}/"
split_names = sorted(
{
path.split("/")[2]
for path in repo_files
if path.startswith(prefix) and len(path.split("/")) >= 3
}
)
else:
split_names = sorted(
[
path.name
for path in cache_root.iterdir()
if path.is_dir()
]
)
if not split_names:
return "No cached shards found. Run processing first."
repo_files = set()
if cache_on_hub:
try:
repo_files = set(
api.list_repo_files(repo_id, repo_type="dataset")
)
except Exception:
repo_files = set()
processed_splits = {}
for split_name in split_names:
split_cache_dir = cache_root / split_name
hub_cache_prefix = get_hub_cache_prefix(dataset_id, config, split_name)
meta = load_split_meta(
split_cache_dir, hub_cache_prefix, cache_on_hub, repo_id, token
)
if not meta:
return (
f"Missing cache metadata for split '{split_name}'. "
"Re-run processing to rebuild shards."
)
total = int(meta.get("total", 0))
shard_size = int(meta.get("shard_size", 0))
num_shards = int(meta.get("num_shards", 0))
if not total or not shard_size or not num_shards:
return (
f"Incomplete cache metadata for split '{split_name}'. "
"Re-run processing to rebuild shards."
)
shards = []
missing = []
for shard_idx in range(num_shards):
start = shard_idx * shard_size
end = min(total, start + shard_size)
cache_file = split_cache_dir / (
f"{split_name}-{start:07d}-{end:07d}.arrow"
)
hub_cache_path = f"{hub_cache_prefix}/{cache_file.name}"
if cache_file.exists():
cache_path = str(cache_file)
elif cache_on_hub and hub_cache_path in repo_files:
cache_path = hf_hub_download(
repo_id=repo_id,
repo_type="dataset",
filename=hub_cache_path,
token=token,
)
else:
missing.append(cache_file.name)
continue
shards.append(Dataset.from_file(cache_path))
if missing:
return (
f"Missing {len(missing)} shard(s) for split '{split_name}'. "
"Run processing with resume enabled."
)
processed_splits[split_name] = (
concatenate_datasets(shards)
if len(shards) > 1
else shards[0]
)
processed_dataset = (
DatasetDict(processed_splits)
if len(processed_splits) > 1
else next(iter(processed_splits.values()))
)
progress(0, desc="Uploading to the Hub...")
processed_dataset.push_to_hub(repo_id, private=private_repo, token=token)
progress(1.0, desc="Upload complete.")
inferred_audio_column = (
audio_column or infer_audio_column(processed_dataset) or "audio"
)
return (
f"Uploaded cleaned dataset to {repo_id} "
f"(audio column: {inferred_audio_column})."
)
@gpu_decorator(DEFAULT_GPU_DURATION)
def _gradio_single_file_gpu(
audio_file,
vad_threshold,
max_silence_gap,
normalize_audio,
target_dbfs,
max_boost_db,
max_atten_db,
request: gr.Request | None = None,
):
if audio_file is None:
return None, None, None, "Please upload an audio file."
return process_audio_file(
audio_file,
threshold=vad_threshold,
max_gap=max_silence_gap,
normalize_audio=normalize_audio,
target_dbfs=target_dbfs,
max_boost_db=max_boost_db,
max_atten_db=max_atten_db,
)
def gradio_single_file(
audio_file,
vad_threshold,
max_silence_gap,
normalize_audio,
target_dbfs,
max_boost_db,
max_atten_db,
request: gr.Request | None = None,
):
return _gradio_single_file_gpu(
audio_file,
vad_threshold,
max_silence_gap,
normalize_audio,
target_dbfs,
max_boost_db,
max_atten_db,
request=request,
)
with gr.Blocks(title="Representation Chizzler") as demo:
gr.Markdown(
"# Representation Chizzler\n"
"Two-stage audio processing: VAD-based speech extraction followed by MP-SENet "
"denoising. Use the Single File tab for ad-hoc processing or the Dataset tab "
"to clean and publish a dataset to the Hugging Face Hub."
)
with gr.Column():
with gr.Tabs():
with gr.Tab("Single File"):
audio_input = gr.Audio(label="Upload Audio File", type="filepath")
vad_slider = gr.Slider(
minimum=0.1,
maximum=0.9,
value=0.5,
step=0.1,
label="VAD Threshold (higher = stricter voice detection)",
)
gap_slider = gr.Slider(
minimum=1.0,
maximum=10.0,
value=4.0,
step=0.5,
label="Max Silence Gap (seconds)",
)
normalize_checkbox = gr.Checkbox(
label="Normalize volume", value=True
)
target_db_slider = gr.Slider(
minimum=-35.0,
maximum=-10.0,
value=DEFAULT_TARGET_DBFS,
step=1.0,
label="Target loudness (dBFS)",
)
max_boost_slider = gr.Slider(
minimum=0.0,
maximum=30.0,
value=DEFAULT_MAX_BOOST_DB,
step=1.0,
label="Max boost (dB)",
)
max_atten_slider = gr.Slider(
minimum=0.0,
maximum=20.0,
value=DEFAULT_MAX_ATTEN_DB,
step=1.0,
label="Max attenuation (dB)",
)
run_button = gr.Button("Process Audio")
original_audio = gr.Audio(label="Original Audio")
vad_audio = gr.Audio(label="VAD Processed (Speech Only)")
denoised_audio = gr.Audio(label="Final Denoised")
details_box = gr.Textbox(label="Processing Details", lines=10)
run_button.click(
fn=gradio_single_file,
inputs=[
audio_input,
vad_slider,
gap_slider,
normalize_checkbox,
target_db_slider,
max_boost_slider,
max_atten_slider,
],
outputs=[original_audio, vad_audio, denoised_audio, details_box],
concurrency_limit=1,
)
with gr.Tab("Dataset to Hub"):
with gr.Row():
gr.LoginButton()
dataset_id_input = gr.Textbox(
label="Dataset ID or URL",
value="https://huggingface.co/datasets/MohammadGholizadeh/fleurs-farsi",
)
config_input = gr.Textbox(label="Config (optional)", value="")
split_input = gr.Textbox(label="Split (optional, or 'all')", value="dev")
audio_column_input = gr.Textbox(
label="Audio column (optional, auto-detect if empty)", value=""
)
output_repo_input = gr.Textbox(
label="Output dataset repo (optional)", value=""
)
private_checkbox = gr.Checkbox(label="Create private repo", value=False)
max_examples_input = gr.Number(
label="Max examples per split (optional)", value=None
)
resume_checkbox = gr.Checkbox(
label="Resume from cached shards", value=True
)
auto_resume_checkbox = gr.Checkbox(
label="Auto-resume on ZeroGPU preemption",
value=DEFAULT_AUTO_RESUME,
)
cache_to_hub_checkbox = gr.Checkbox(
label="Cache shards on Hub (recommended for ZeroGPU)",
value=DEFAULT_CACHE_TO_HUB,
)
shard_size_input = gr.Number(
label="Shard size (examples)", value=25
)
max_shards_input = gr.Number(
label="Max shards per run (ZeroGPU: 1-5, 0 = no limit)",
value=DEFAULT_MAX_SHARDS_PER_RUN,
)
vad_slider_ds = gr.Slider(
minimum=0.1,
maximum=0.9,
value=0.5,
step=0.1,
label="VAD Threshold",
)
gap_slider_ds = gr.Slider(
minimum=1.0,
maximum=10.0,
value=4.0,
step=0.5,
label="Max Silence Gap (seconds)",
)
normalize_checkbox_ds = gr.Checkbox(
label="Normalize volume", value=True
)
target_db_slider_ds = gr.Slider(
minimum=-35.0,
maximum=-10.0,
value=DEFAULT_TARGET_DBFS,
step=1.0,
label="Target loudness (dBFS)",
)
max_boost_slider_ds = gr.Slider(
minimum=0.0,
maximum=30.0,
value=DEFAULT_MAX_BOOST_DB,
step=1.0,
label="Max boost (dB)",
)
max_atten_slider_ds = gr.Slider(
minimum=0.0,
maximum=20.0,
value=DEFAULT_MAX_ATTEN_DB,
step=1.0,
label="Max attenuation (dB)",
)
process_button = gr.Button(
"Process/Resume Dataset (cache & push when complete)"
)
assemble_button = gr.Button(
"Assemble & Push Cached Dataset"
)
status_box = gr.Textbox(label="Status", lines=6)
process_button.click(
fn=process_dataset_and_push,
inputs=[
dataset_id_input,
config_input,
split_input,
audio_column_input,
output_repo_input,
private_checkbox,
vad_slider_ds,
gap_slider_ds,
normalize_checkbox_ds,
target_db_slider_ds,
max_boost_slider_ds,
max_atten_slider_ds,
max_examples_input,
resume_checkbox,
auto_resume_checkbox,
shard_size_input,
cache_to_hub_checkbox,
max_shards_input,
],
outputs=[status_box],
concurrency_limit=1,
)
assemble_button.click(
fn=assemble_cached_dataset_and_push,
inputs=[
dataset_id_input,
config_input,
split_input,
audio_column_input,
output_repo_input,
private_checkbox,
cache_to_hub_checkbox,
],
outputs=[status_box],
concurrency_limit=1,
)
demo.queue()
if __name__ == "__main__":
demo.launch()
|