File size: 77,271 Bytes
e103b22 | 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 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 | # -*- coding: utf-8 -*-
"""
Gradio 界面 - RVC AI 翻唱
"""
import os
import json
import re
import tempfile
import gradio as gr
from pathlib import Path
from typing import Optional, Tuple, Dict
from lib.logger import log
# 项目根目录
ROOT_DIR = Path(__file__).parent.parent
# 加载语言包
def load_i18n(lang: str = "zh_CN") -> dict:
"""加载语言包"""
i18n_path = ROOT_DIR / "i18n" / f"{lang}.json"
if i18n_path.exists():
with open(i18n_path, "r", encoding="utf-8") as f:
return json.load(f)
return {}
# 加载配置
def load_config() -> dict:
"""加载配置"""
config_path = ROOT_DIR / "configs" / "config.json"
if config_path.exists():
with open(config_path, "r", encoding="utf-8") as f:
return json.load(f)
return {}
def normalize_config(config: dict) -> dict:
"""Normalize legacy path keys to top-level entries."""
if not config:
return {}
paths = config.get("paths", {})
if "hubert_path" not in config and "hubert" in paths:
config["hubert_path"] = paths["hubert"]
if "rmvpe_path" not in config and "rmvpe" in paths:
config["rmvpe_path"] = paths["rmvpe"]
if "weights_dir" not in config and "weights" in paths:
config["weights_dir"] = paths["weights"]
if "output_dir" not in config and "outputs" in paths:
config["output_dir"] = paths["outputs"]
elif config.get("output_dir") == "output" and "outputs" in paths:
config["output_dir"] = paths["outputs"]
if "temp_dir" not in config and "temp" in paths:
config["temp_dir"] = paths["temp"]
return config
# 全局变量
i18n = load_i18n()
config = normalize_config(load_config())
pipeline = None
def t(key: str, section: str = None) -> str:
"""获取翻译文本"""
if section:
return i18n.get(section, {}).get(key, key)
return i18n.get(key, key)
def _to_int(value, fallback: int) -> int:
try:
return int(value)
except (TypeError, ValueError):
return fallback
def _to_float(value, fallback: float) -> float:
try:
return float(value)
except (TypeError, ValueError):
return fallback
def get_cover_mix_defaults() -> Dict[str, int]:
"""获取翻唱混音默认值"""
cover_cfg = config.get("cover", {})
return {
"vocals_volume": _to_int(cover_cfg.get("default_vocals_volume", 100), 100),
"accompaniment_volume": _to_int(cover_cfg.get("default_accompaniment_volume", 100), 100),
"reverb": _to_int(cover_cfg.get("default_reverb", 10), 10),
}
def get_cover_mix_presets() -> Tuple[Dict[str, Dict[str, int]], str]:
"""获取混音预设与默认预设名称"""
defaults = get_cover_mix_defaults()
presets = {
t("mix_preset_universal", "cover"): defaults.copy(),
t("mix_preset_vocal", "cover"): {
"vocals_volume": min(200, defaults["vocals_volume"] + 15),
"accompaniment_volume": max(0, defaults["accompaniment_volume"] - 10),
"reverb": max(0, defaults["reverb"] - 5),
},
t("mix_preset_accompaniment", "cover"): {
"vocals_volume": max(0, defaults["vocals_volume"] - 10),
"accompaniment_volume": min(200, defaults["accompaniment_volume"] + 15),
"reverb": max(0, defaults["reverb"] - 5),
},
t("mix_preset_live", "cover"): {
"vocals_volume": defaults["vocals_volume"],
"accompaniment_volume": defaults["accompaniment_volume"],
"reverb": min(100, defaults["reverb"] + 10),
},
}
default_name = t("mix_preset_universal", "cover")
return presets, default_name
def apply_cover_mix_preset(preset_name: str) -> Tuple[int, int, int]:
"""根据预设名称返回混音参数"""
presets, default_name = get_cover_mix_presets()
preset = presets.get(preset_name) or presets[default_name]
return preset["vocals_volume"], preset["accompaniment_volume"], preset["reverb"]
def get_vc_preprocess_option_maps() -> Tuple[Dict[str, str], Dict[str, str]]:
"""Build VC preprocess dropdown option maps."""
label_to_value = {
t("vc_preprocess_auto", "cover"): "auto",
t("vc_preprocess_direct", "cover"): "direct",
t("vc_preprocess_uvr_deecho", "cover"): "uvr_deecho",
t("vc_preprocess_legacy", "cover"): "legacy",
}
value_to_label = {value: label for label, value in label_to_value.items()}
return label_to_value, value_to_label
def get_source_constraint_option_maps() -> Tuple[Dict[str, str], Dict[str, str]]:
"""Build source constraint dropdown option maps."""
label_to_value = {
t("source_constraint_auto", "cover"): "auto",
t("source_constraint_off", "cover"): "off",
t("source_constraint_on", "cover"): "on",
}
value_to_label = {value: label for label, value in label_to_value.items()}
return label_to_value, value_to_label
def get_vc_pipeline_mode_option_maps() -> Tuple[Dict[str, str], Dict[str, str]]:
"""Build VC pipeline mode dropdown option maps."""
label_to_value = {
t("vc_pipeline_mode_current", "cover"): "current",
t("vc_pipeline_mode_official", "cover"): "official",
}
value_to_label = {value: label for label, value in label_to_value.items()}
return label_to_value, value_to_label
def update_singing_repair_visibility(vc_pipeline_mode: str):
"""Only show singing repair option for official mode."""
pipeline_label_to_value, _ = get_vc_pipeline_mode_option_maps()
normalized = pipeline_label_to_value.get(
str(vc_pipeline_mode),
str(vc_pipeline_mode or "").strip().lower(),
)
return gr.update(visible=(normalized == "official"))
def init_pipeline():
"""初始化推理管道"""
global pipeline
if pipeline is not None:
return pipeline
from infer.pipeline import VoiceConversionPipeline
device = config.get("device", "cuda")
pipeline = VoiceConversionPipeline(device=device)
pipeline.hubert_layer = config.get("hubert_layer", 12)
# 加载 HuBERT
hubert_path = ROOT_DIR / config.get("hubert_path", "assets/hubert/hubert_base.pt")
if hubert_path.exists():
pipeline.load_hubert(str(hubert_path))
# 加载 F0 提取器
rmvpe_path = ROOT_DIR / config.get("rmvpe_path", "assets/rmvpe/rmvpe.pt")
if rmvpe_path.exists():
pipeline.load_f0_extractor("rmvpe", str(rmvpe_path))
return pipeline
def download_base_models() -> str:
"""下载基础模型"""
from tools.download_models import download_required_models
try:
success = download_required_models()
if success:
return t("download_complete", "messages")
else:
return "下载过程中出现错误,请检查网络连接"
except Exception as e:
return f"{t('download_failed', 'messages')}: {str(e)}"
# ===== 翻唱功能相关函数 =====
def get_downloaded_character_list() -> list:
"""获取已下载的角色列表"""
from tools.character_models import list_downloaded_characters
return list_downloaded_characters()
def get_downloaded_character_series() -> list:
"""获取已下载角色的系列列表"""
characters = get_downloaded_character_list()
series = sorted({c.get("series", "未知") for c in characters})
return ["全部"] + series
def get_available_character_list() -> list:
"""获取可下载的角色列表"""
from tools.character_models import list_available_characters
return list_available_characters()
def get_available_character_series() -> list:
"""获取可用系列列表"""
from tools.character_models import list_available_series
return list_available_series()
def format_character_label(char_info: dict) -> str:
"""格式化角色展示名称:【语言】角色名(中/英/日) · 出处 · 内部名"""
display = char_info.get("display") or char_info.get("description") or char_info.get("name", "")
source = char_info.get("source", "未知")
name = char_info.get("name", "")
lang_tag = get_character_language_tag(char_info)
return f"【{lang_tag}】{display}(出自:{source})[{name}]"
def get_character_language_tag(char_info: dict) -> str:
"""推断语言类型,用于下拉前缀标签"""
lang = char_info.get("lang")
if lang:
return lang
text = " ".join(
str(char_info.get(k, "")) for k in ("display", "description", "name")
).lower()
if "韩" in text or "kr" in text or "korean" in text:
return "韩文"
if "日" in text or "jp" in text or "japanese" in text:
return "日文"
if "中" in text or "cn" in text or "chinese" in text:
return "中文"
if "en" in text or "english" in text:
return "英文"
source = char_info.get("source", "")
if source.startswith("Love Live!") or "ホロライブ" in source or "偶像大师" in source or "赛马娘" in source:
return "日文"
if "原神" in source or "崩坏" in source or "明日方舟" in source or "碧蓝航线" in source:
return "中文"
if "VOCALOID" in source or "Project SEKAI" in source:
return "日文"
if "Hololive" in source:
return "日文"
if "蔚蓝档案" in source or "绝区零" in source:
return "日文"
return "中文"
def get_downloaded_character_choices(series: str = "全部", keyword: str = "") -> list:
"""获取已下载角色的下拉选项"""
chars = get_downloaded_character_list()
if series and series != "全部":
chars = [c for c in chars if c.get("series") == series]
if keyword:
kw = keyword.strip().lower()
if kw:
chars = [
c for c in chars
if kw in c.get("name", "").lower()
or kw in c.get("display", "").lower()
or kw in c.get("source", "").lower()
]
return [(format_character_label(c), c["name"]) for c in chars]
def resolve_character_name(selection: str) -> str:
"""将下拉显示文本解析为实际角色名"""
if not selection:
return selection
from tools.character_models import list_downloaded_characters
for c in list_downloaded_characters():
if selection == c.get("name") or selection == format_character_label(c):
return c.get("name")
if " · " in selection:
return selection.split(" · ")[-1].strip()
parts = selection.strip().split()
return parts[-1] if parts else selection
def get_available_character_choices(series: str = "全部", keyword: str = "") -> list:
"""获取可下载角色的下拉选项"""
chars = get_available_character_list()
if series and series != "全部":
chars = [c for c in chars if c.get("series") == series]
if keyword:
kw = keyword.strip().lower()
if kw:
chars = [
c for c in chars
if kw in c.get("name", "").lower()
or kw in c.get("display", "").lower()
or kw in c.get("source", "").lower()
]
return [(format_character_label(c), c["name"]) for c in chars]
def _refresh_downloaded_updates(series: str, keyword: str) -> Tuple[Dict, Dict]:
series_choices = get_downloaded_character_series()
if series not in series_choices:
series = "全部"
return (
gr.update(choices=series_choices, value=series),
gr.update(choices=get_downloaded_character_choices(series, keyword))
)
def download_character(name: str, selected_series: str = "全部", keyword: str = "") -> Tuple[str, Dict, Dict]:
"""下载角色模型"""
from tools.character_models import download_character_model
if not name:
series_update, choices_update = _refresh_downloaded_updates(selected_series, keyword)
return "请选择要下载的角色", choices_update, series_update
try:
success = download_character_model(name)
series_update, choices_update = _refresh_downloaded_updates(selected_series, keyword)
if success:
return (
f"✅ {name} 模型下载完成",
choices_update,
series_update
)
else:
return (
f"❌ {name} 模型下载失败",
choices_update,
series_update
)
except Exception as e:
series_update, choices_update = _refresh_downloaded_updates(selected_series, keyword)
return (
f"❌ 下载失败: {str(e)}",
choices_update,
series_update
)
def download_all_characters(series: str = "全部", selected_series: str = "全部", keyword: str = "") -> Tuple[str, Dict, Dict]:
"""批量下载角色模型"""
from tools.character_models import download_all_character_models
try:
result = download_all_character_models(series=series)
ok = result.get("success", [])
failed = result.get("failed", [])
status = f"✅ 完成: 成功 {len(ok)} 个"
if failed:
status += f",失败 {len(failed)} 个: {', '.join(failed)}"
series_update, choices_update = _refresh_downloaded_updates(selected_series, keyword)
return status, choices_update, series_update
except Exception as e:
series_update, choices_update = _refresh_downloaded_updates(selected_series, keyword)
return f"❌ 批量下载失败: {str(e)}", choices_update, series_update
def update_download_choices(series: str, keyword: str) -> Dict:
"""更新下载下拉列表"""
return gr.update(choices=get_available_character_choices(series, keyword))
def update_downloaded_choices(series: str, keyword: str) -> Dict:
"""更新已下载角色下拉列表"""
return gr.update(choices=get_downloaded_character_choices(series, keyword))
def refresh_downloaded_controls(series: str, keyword: str) -> Tuple[Dict, Dict]:
"""刷新已下载角色的筛选和列表"""
return _refresh_downloaded_updates(series, keyword)
def process_cover(
audio_path: str,
character_name: str,
pitch_shift: int,
index_ratio: float,
speaker_id: float,
karaoke_separation: bool,
karaoke_merge_backing_into_accompaniment: bool,
vc_preprocess_mode: str,
source_constraint_mode: str,
vc_pipeline_mode: str,
singing_repair: bool,
vocals_volume: float,
accompaniment_volume: float,
reverb_amount: float,
rms_mix_rate: float,
backing_mix: float,
progress=gr.Progress()
) -> Tuple[Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], str]:
"""
处理翻唱
Returns:
Tuple[cover, converted_vocals, original_vocals, lead_vocals, backing_vocals, accompaniment, status]
"""
_none6 = (None, None, None, None, None, None)
if audio_path is None:
return *_none6, "请上传歌曲文件"
if not character_name:
return *_none6, "请选择角色"
try:
from tools.character_models import get_character_model_path
from infer.cover_pipeline import get_cover_pipeline
# 获取角色模型路径
resolved_name = resolve_character_name(character_name)
model_info = get_character_model_path(resolved_name)
if model_info is None:
return *_none6, f"角色模型不存在: {resolved_name}"
# 进度回调
def progress_callback(msg: str, step: int, total: int):
if total > 0:
progress(step / total, desc=msg)
# 获取流水线
device = config.get("device", "cuda")
pipeline = get_cover_pipeline(device)
cover_cfg = config.get("cover", {})
demucs_model = cover_cfg.get("demucs_model", "htdemucs")
demucs_shifts = int(cover_cfg.get("demucs_shifts", 2))
demucs_overlap = float(cover_cfg.get("demucs_overlap", 0.25))
demucs_split = bool(cover_cfg.get("demucs_split", True))
separator = cover_cfg.get("separator", "roformer")
uvr5_model = cover_cfg.get("uvr5_model")
uvr5_agg = int(cover_cfg.get("uvr5_agg", 10))
uvr5_format = cover_cfg.get("uvr5_format", "wav")
use_official = bool(cover_cfg.get("use_official", True))
f0_method = cover_cfg.get("f0_method", config.get("f0_method", "rmvpe"))
filter_radius = cover_cfg.get("filter_radius", config.get("filter_radius", 3))
protect = cover_cfg.get("protect", config.get("protect", 0.33))
silence_gate = cover_cfg.get("silence_gate", True)
silence_threshold_db = cover_cfg.get("silence_threshold_db", -40.0)
silence_smoothing_ms = cover_cfg.get("silence_smoothing_ms", 50.0)
silence_min_duration_ms = cover_cfg.get("silence_min_duration_ms", 200.0)
hubert_layer = cover_cfg.get("hubert_layer", config.get("hubert_layer", 12))
karaoke_model = cover_cfg.get("karaoke_model", "mel_band_roformer_karaoke_gabox.ckpt")
default_vc_preprocess_mode = str(cover_cfg.get("vc_preprocess_mode", "auto"))
default_source_constraint_mode = str(cover_cfg.get("source_constraint_mode", "auto"))
default_vc_pipeline_mode = str(cover_cfg.get("vc_pipeline_mode", "current"))
default_singing_repair = bool(cover_cfg.get("singing_repair", False))
vc_label_to_value, vc_value_to_label = get_vc_preprocess_option_maps()
source_label_to_value, source_value_to_label = get_source_constraint_option_maps()
pipeline_label_to_value, pipeline_value_to_label = get_vc_pipeline_mode_option_maps()
vc_preprocess_mode = vc_label_to_value.get(str(vc_preprocess_mode), str(vc_preprocess_mode or default_vc_preprocess_mode).strip().lower())
if vc_preprocess_mode not in {"auto", "direct", "uvr_deecho", "legacy"}:
vc_preprocess_mode = default_vc_preprocess_mode
source_constraint_mode = source_label_to_value.get(str(source_constraint_mode), str(source_constraint_mode or default_source_constraint_mode).strip().lower())
if source_constraint_mode not in {"auto", "off", "on"}:
source_constraint_mode = default_source_constraint_mode
vc_pipeline_mode = pipeline_label_to_value.get(str(vc_pipeline_mode), str(vc_pipeline_mode or default_vc_pipeline_mode).strip().lower())
if vc_pipeline_mode not in {"current", "official"}:
vc_pipeline_mode = default_vc_pipeline_mode
singing_repair = bool(singing_repair if singing_repair is not None else default_singing_repair)
index_ratio = max(0.0, min(1.0, float(index_ratio) / 100.0))
speaker_id = int(max(0, round(float(speaker_id))))
rms_mix_rate = max(0.0, min(1.0, float(rms_mix_rate) / 100.0))
backing_mix = max(0.0, min(1.0, float(backing_mix) / 100.0))
# 输出目录
output_dir = ROOT_DIR / config.get("paths", {}).get(
"outputs",
config.get("output_dir", "outputs")
)
# 执行翻唱
result = pipeline.process(
input_audio=audio_path,
model_path=model_info["model_path"],
index_path=model_info.get("index_path"),
pitch_shift=pitch_shift,
index_ratio=index_ratio,
filter_radius=filter_radius,
rms_mix_rate=rms_mix_rate,
protect=protect,
speaker_id=speaker_id,
f0_method=f0_method,
demucs_model=demucs_model,
demucs_shifts=demucs_shifts,
demucs_overlap=demucs_overlap,
demucs_split=demucs_split,
separator=separator,
uvr5_model=uvr5_model,
uvr5_agg=uvr5_agg,
uvr5_format=uvr5_format,
use_official=use_official,
hubert_layer=hubert_layer,
silence_gate=silence_gate,
silence_threshold_db=silence_threshold_db,
silence_smoothing_ms=silence_smoothing_ms,
silence_min_duration_ms=silence_min_duration_ms,
vocals_volume=vocals_volume / 100, # 转换为 0-2 范围
accompaniment_volume=accompaniment_volume / 100,
reverb_amount=reverb_amount / 100,
backing_mix=backing_mix,
karaoke_separation=bool(karaoke_separation),
karaoke_model=karaoke_model,
karaoke_merge_backing_into_accompaniment=bool(karaoke_merge_backing_into_accompaniment),
vc_preprocess_mode=vc_preprocess_mode,
source_constraint_mode=source_constraint_mode,
vc_pipeline_mode=vc_pipeline_mode,
singing_repair=singing_repair,
output_dir=str(output_dir),
model_display_name=resolved_name,
progress_callback=progress_callback
)
status_msg = "\u2705 \u7ffb\u5531\u5b8c\u6210!"
status_msg += f"\n{get_cover_vc_route_status(vc_preprocess_mode, vc_pipeline_mode).splitlines()[0]}"
status_msg += f"\nVC\u7ba1\u7ebf\u6a21\u5f0f: {pipeline_value_to_label.get(vc_pipeline_mode, vc_pipeline_mode)}"
status_msg += f"\n唱歌修复: {'开启' if singing_repair else '关闭'}"
status_msg += f"\n\u6e90\u7ea6\u675f\u7b56\u7565: {source_value_to_label.get(source_constraint_mode, source_constraint_mode)}"
if result.get("all_files_dir"):
status_msg += f"\n\u5168\u90e8\u6587\u4ef6\u76ee\u5f55: {result['all_files_dir']}"
return (
result["cover"],
result["converted_vocals"],
result.get("vocals"),
result.get("lead_vocals"),
result.get("backing_vocals"),
result["accompaniment"],
status_msg
)
except Exception as e:
import traceback
error_msg = str(e) if str(e) else traceback.format_exc()
log.error(f"处理失败: {error_msg}")
return None, None, None, None, None, None, f"❌ 处理失败: {error_msg}"
def check_mature_deecho_status() -> str:
"""Check mature DeEcho model availability."""
from tools.download_models import MATURE_DEECHO_MODELS, check_model, get_preferred_mature_deecho_model
status_lines = []
preferred = get_preferred_mature_deecho_model()
for name in MATURE_DEECHO_MODELS:
exists = check_model(name)
icon = "✅" if exists else "❌"
suffix = " ← 当前自动模式优先使用" if preferred == name else ""
status_lines.append(f"{icon} {name}{suffix}")
if preferred:
status_lines.append("")
status_lines.append(f"当前可用学习型 DeEcho: {preferred}")
else:
status_lines.append("")
status_lines.append("当前未检测到学习型 DeEcho 模型;翻唱自动模式将回退为主唱直通 RVC")
return "\n".join(status_lines)
def download_mature_deecho_models_ui() -> str:
"""Download mature DeEcho models."""
from tools.download_models import download_mature_deecho_models
try:
success = download_mature_deecho_models()
status = check_mature_deecho_status()
prefix = "✅ 下载完成" if success else "⚠️ 下载过程中存在失败项"
return f"{prefix}\n\n{status}"
except Exception as e:
return f"❌ 下载失败: {str(e)}"
def get_cover_vc_route_status(
vc_preprocess_mode: Optional[str] = None,
vc_pipeline_mode: Optional[str] = None,
) -> str:
"""Return the active VC route shown in the cover UI."""
from tools.download_models import get_preferred_mature_deecho_model
mode = str(vc_preprocess_mode or config.get("cover", {}).get("vc_preprocess_mode", "auto")).strip().lower()
pipeline_mode = str(vc_pipeline_mode or config.get("cover", {}).get("vc_pipeline_mode", "current")).strip().lower()
vc_label_to_value, _ = get_vc_preprocess_option_maps()
pipeline_label_to_value, _ = get_vc_pipeline_mode_option_maps()
mode = vc_label_to_value.get(mode, mode)
pipeline_mode = pipeline_label_to_value.get(pipeline_mode, pipeline_mode)
preferred = get_preferred_mature_deecho_model()
newline = chr(10)
if pipeline_mode == "official":
return newline.join([
"当前使用内置官方 RVC 实现",
"流程:主唱分离 → 官方音频加载 / 官方 VC → 混音",
"说明:跳过本项目自定义 VC 预处理、源约束与静音门限后处理",
])
if mode == "direct":
return newline.join([
"ℹ️ 当前固定为主唱直通 RVC",
"流程: 主唱分离 → 直接进入 RVC → 混音",
"说明: 不使用学习型 DeEcho,也不走旧版手工链",
])
if mode == "legacy":
return newline.join([
"⚠️ 当前固定为旧版手工链",
"流程: 主唱分离 → 手工去回声链 → RVC → 混音",
"说明: 仅用于对比,不是默认推荐路径",
])
if mode == "uvr_deecho":
if preferred:
return newline.join([
"✅ 当前固定优先使用学习型 DeEcho / DeReverb",
f"当前命中模型: {preferred}",
"流程: 主唱分离 → UVR DeEcho/DeReverb → RVC → 混音",
])
return newline.join([
"⚠️ 当前设为官方 DeEcho 优先,但本地缺少模型",
"当前将回退流程: 主唱分离 → 直接进入 RVC → 混音",
"建议: 先在模型管理页下载成熟 DeEcho 模型",
])
if preferred:
return newline.join([
"✅ 自动模式当前会优先使用学习型 DeEcho / DeReverb",
f"当前命中模型: {preferred}",
"流程: 主唱分离 → UVR DeEcho/DeReverb → RVC → 混音",
])
return newline.join([
"ℹ️ 自动模式当前会回退为主唱直通 RVC",
"原因: 本地未检测到成熟 DeEcho / DeReverb 模型",
"流程: 主唱分离 → 直接进入 RVC → 混音",
])
def check_models_status() -> str:
"""检查模型状态"""
from tools.download_models import check_model, REQUIRED_MODELS
status_lines = []
for name in REQUIRED_MODELS:
exists = check_model(name)
icon = "✅" if exists else "❌"
status_lines.append(f"{icon} {name}")
return "\n".join(status_lines)
def get_device_info() -> str:
"""获取设备信息"""
import torch
from lib.device import get_device_info as _get_info, _is_rocm, _has_xpu, _has_directml, _has_mps
lines = []
lines.append(f"PyTorch 版本: {torch.__version__}")
info = _get_info()
lines.append(f"可用后端: {', '.join(info['backends'])}")
for dev in info["devices"]:
mem = f"{dev['total_memory_gb']} GB" if dev.get("total_memory_gb") else "N/A"
lines.append(f"GPU: {dev['name']} ({dev['backend']}) - 显存: {mem}")
if torch.cuda.is_available():
ver = torch.version.hip if _is_rocm() else torch.version.cuda
label = "ROCm" if _is_rocm() else "CUDA"
lines.append(f"{label} 版本: {ver}")
if not info["devices"]:
lines.append("未检测到 GPU,将使用 CPU")
return "\n".join(lines)
# 自定义 CSS - 深灰 + 橙色强调配色
CUSTOM_CSS = """
/* 深色主题基础 - 纯色背景 */
.gradio-container {
background: #121212 !important;
min-height: 100vh;
}
.main-title {
text-align: center;
margin-bottom: 1rem;
color: #e0e0e0 !important;
}
/* 状态框样式 */
.status-box {
font-family: 'Consolas', 'Monaco', monospace;
white-space: pre-wrap;
background: #1e1e1e !important;
border: 1px solid #404040 !important;
color: #9e9e9e !important;
}
/* 提示框 */
.model-hint {
padding: 1rem;
background: #1e1e1e !important;
border: 1px solid #404040 !important;
border-radius: 8px;
margin: 1rem 0;
color: #e0e0e0 !important;
}
/* 成功/错误消息 */
.success-msg {
color: #4caf50 !important;
font-weight: bold;
}
.error-msg {
color: #f44336 !important;
font-weight: bold;
}
/* 标签页样式 */
.tabs > .tab-nav {
background: #1e1e1e !important;
border-bottom: 1px solid #404040 !important;
}
.tabs > .tab-nav > button {
color: #9e9e9e !important;
background: transparent !important;
border: none !important;
padding: 12px 24px !important;
transition: color 0.2s ease !important;
}
.tabs > .tab-nav > button:hover {
color: #e0e0e0 !important;
}
.tabs > .tab-nav > button.selected {
color: #ff9800 !important;
border-bottom: 2px solid #ff9800 !important;
background: transparent !important;
}
/* 输入框和下拉框 */
.gr-input, .gr-dropdown, textarea, input[type="text"] {
background: #2d2d2d !important;
border: 1px solid #404040 !important;
color: #e0e0e0 !important;
}
.gr-input:focus, .gr-dropdown:focus, textarea:focus, input[type="text"]:focus {
border-color: #ff9800 !important;
outline: none !important;
}
/* 滑块 */
.gr-slider input[type="range"] {
background: #404040 !important;
}
.gr-slider input[type="range"]::-webkit-slider-thumb {
background: #ff9800 !important;
}
.gr-slider input[type="range"]::-moz-range-thumb {
background: #ff9800 !important;
}
input[type="range"]::-webkit-slider-runnable-track {
background: #404040 !important;
}
input[type="range"]::-moz-range-track {
background: #404040 !important;
}
/* 按钮样式 - 主按钮橙色 */
.gr-button-primary, button.primary {
background: #ff9800 !important;
border: none !important;
color: #121212 !important;
font-weight: 600 !important;
transition: all 0.2s ease !important;
}
.gr-button-primary:hover, button.primary:hover {
background: #ffa726 !important;
transform: translateY(-1px) !important;
box-shadow: 0 4px 12px rgba(255, 152, 0, 0.3) !important;
}
.gr-button-primary:active, button.primary:active {
background: #f57c00 !important;
transform: translateY(0) !important;
}
/* 次要按钮 */
.gr-button-secondary, button.secondary {
background: #404040 !important;
border: none !important;
color: #e0e0e0 !important;
transition: all 0.2s ease !important;
}
.gr-button-secondary:hover, button.secondary:hover {
background: #4a4a4a !important;
}
/* 音频播放器 */
.gr-audio {
background: #1e1e1e !important;
border: 1px solid #404040 !important;
border-radius: 8px !important;
}
.gr-audio audio {
background: #1e1e1e !important;
color: #e0e0e0 !important;
accent-color: #ff9800 !important;
}
.gr-audio audio::-webkit-media-controls-panel {
background: #1e1e1e !important;
}
.gr-audio audio::-webkit-media-controls-enclosure {
background: #1e1e1e !important;
}
.gr-audio audio::-webkit-media-controls-timeline {
background: #404040 !important;
}
.gr-audio audio::-webkit-media-controls-current-time-display,
.gr-audio audio::-webkit-media-controls-time-remaining-display {
color: #e0e0e0 !important;
}
.gr-audio audio::-webkit-media-controls-play-button,
.gr-audio audio::-webkit-media-controls-mute-button,
.gr-audio audio::-webkit-media-controls-volume-slider {
filter: invert(1) sepia(1) saturate(5) hue-rotate(10deg) !important;
}
/* 折叠面板 */
.gr-accordion {
background: #1e1e1e !important;
border: 1px solid #404040 !important;
border-radius: 8px !important;
}
.gr-accordion > .label-wrap {
background: #1e1e1e !important;
}
/* 表格 */
.gr-dataframe {
background: #1e1e1e !important;
}
.gr-dataframe table {
color: #e0e0e0 !important;
}
.gr-dataframe th {
background: #2d2d2d !important;
color: #9e9e9e !important;
}
.gr-dataframe td {
background: #1e1e1e !important;
border-color: #404040 !important;
}
.gr-dataframe tr:hover td {
background: #333333 !important;
}
/* Gradio v4 Dataframe */
div[data-testid="dataframe"] {
background: #1e1e1e !important;
color: #e0e0e0 !important;
border: 1px solid #404040 !important;
}
div[data-testid="dataframe"] table {
color: #e0e0e0 !important;
}
div[data-testid="dataframe"] thead th {
background: #2d2d2d !important;
color: #9e9e9e !important;
border-color: #404040 !important;
}
div[data-testid="dataframe"] tbody td {
background: #1e1e1e !important;
color: #e0e0e0 !important;
border-color: #404040 !important;
}
div[data-testid="dataframe"] tbody tr:hover td {
background: #333333 !important;
}
div[data-testid="dataframe"] input,
div[data-testid="dataframe"] textarea {
background: #1e1e1e !important;
color: #e0e0e0 !important;
border: 1px solid #404040 !important;
}
/* Markdown 文本 */
.prose {
color: #e0e0e0 !important;
}
.prose h1, .prose h2, .prose h3, .prose h4 {
color: #e0e0e0 !important;
}
.prose a {
color: #ff9800 !important;
}
.prose a:hover {
color: #ffa726 !important;
}
.prose code {
background: #2d2d2d !important;
color: #ff9800 !important;
padding: 2px 6px !important;
border-radius: 4px !important;
}
.prose blockquote {
border-left: 3px solid #ff9800 !important;
background: #1e1e1e !important;
padding: 8px 16px !important;
color: #9e9e9e !important;
}
/* 单选按钮和复选框 */
.gr-radio label, .gr-checkbox label {
color: #e0e0e0 !important;
}
input[type="radio"]:checked + label, input[type="checkbox"]:checked + label {
color: #ff9800 !important;
}
/* 进度条 */
.progress-bar {
background: #404040 !important;
}
.progress-bar > div {
background: #ff9800 !important;
}
/* 分隔线 */
hr {
border-color: #404040 !important;
}
/* 标签 */
label {
color: #9e9e9e !important;
}
/* 信息文本 */
.gr-info {
color: #9e9e9e !important;
}
/* 块/面板背景 */
.gr-block, .gr-box, .gr-panel {
background: #1e1e1e !important;
border-color: #404040 !important;
}
/* 下拉菜单选项 */
.gr-dropdown option, select option {
background: #2d2d2d !important;
color: #e0e0e0 !important;
}
/* Gradio 下拉选择器完整样式 */
.gr-dropdown, .gr-dropdown select,
div[data-testid="dropdown"],
.dropdown-container,
.svelte-select,
.wrap-inner,
.secondary-wrap {
background: #2d2d2d !important;
border: 1px solid #404040 !important;
color: #e0e0e0 !important;
}
/* 下拉选择器输入框 */
.gr-dropdown input,
div[data-testid="dropdown"] input,
.svelte-select input {
background: #2d2d2d !important;
color: #e0e0e0 !important;
border: none !important;
}
/* 下拉菜单列表 */
.gr-dropdown ul,
.gr-dropdown .options,
div[data-testid="dropdown"] ul,
.svelte-select .listContainer,
.dropdown-menu,
ul[role="listbox"] {
background: #2d2d2d !important;
border: 1px solid #404040 !important;
color: #e0e0e0 !important;
}
/* 下拉菜单选项 */
.gr-dropdown li,
.gr-dropdown .option,
div[data-testid="dropdown"] li,
.svelte-select .listItem,
li[role="option"] {
background: #2d2d2d !important;
color: #e0e0e0 !important;
}
/* 下拉菜单选项悬停 */
.gr-dropdown li:hover,
.gr-dropdown .option:hover,
div[data-testid="dropdown"] li:hover,
.svelte-select .listItem:hover,
.svelte-select .listItem.hover,
li[role="option"]:hover {
background: #404040 !important;
color: #ff9800 !important;
}
/* 下拉菜单选中项 */
.gr-dropdown li.selected,
.gr-dropdown .option.selected,
.svelte-select .listItem.active,
li[role="option"][aria-selected="true"] {
background: #333333 !important;
color: #ff9800 !important;
}
/* 下拉箭头图标 */
.gr-dropdown svg,
div[data-testid="dropdown"] svg,
.svelte-select .indicator svg {
fill: #9e9e9e !important;
color: #9e9e9e !important;
}
/* Gradio 3.x 特定选择器样式 */
.wrap.svelte-1m1zvyj,
.wrap-inner.svelte-1m1zvyj,
.secondary-wrap.svelte-1m1zvyj {
background: #2d2d2d !important;
border-color: #404040 !important;
}
.dropdown.svelte-1m1zvyj,
.options.svelte-1m1zvyj {
background: #2d2d2d !important;
border: 1px solid #404040 !important;
}
.item.svelte-1m1zvyj {
background: #2d2d2d !important;
color: #e0e0e0 !important;
}
.item.svelte-1m1zvyj:hover,
.item.svelte-1m1zvyj.active {
background: #404040 !important;
color: #ff9800 !important;
}
/* 单选按钮组样式 */
.gr-radio,
.gr-radio-group,
div[data-testid="radio"] {
background: transparent !important;
}
.gr-radio label span,
div[data-testid="radio"] label span {
color: #e0e0e0 !important;
}
.gr-radio input[type="radio"],
div[data-testid="radio"] input[type="radio"] {
accent-color: #ff9800 !important;
}
/* Radio 按钮容器 */
.radio-group,
.gr-radio-row {
background: #1e1e1e !important;
}
.radio-group label,
.gr-radio-row label {
background: #2d2d2d !important;
border: 1px solid #404040 !important;
color: #e0e0e0 !important;
}
.radio-group label:hover,
.gr-radio-row label:hover {
background: #333333 !important;
}
.radio-group label.selected,
.gr-radio-row label.selected,
.radio-group input:checked + label,
.gr-radio-row input:checked + label {
background: #333333 !important;
border-color: #ff9800 !important;
color: #ff9800 !important;
}
/* 滚动条样式 */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #1e1e1e;
}
::-webkit-scrollbar-thumb {
background: #404040;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #4a4a4a;
}
/* Dataframe 表头修复 - 强制深色主题 */
table thead th,
table thead td,
.table-wrap thead th,
.table-wrap thead td,
[data-testid="table"] thead th,
[data-testid="table"] thead td {
background: #2d2d2d !important;
color: #ff9800 !important;
border-color: #404040 !important;
}
/* Gradio 4.x Dataframe 表头 */
.svelte-1kcgrqr thead th,
.svelte-1kcgrqr thead td,
.cell-wrap span,
th .cell-wrap,
th span.svelte-1kcgrqr {
background: #2d2d2d !important;
color: #ff9800 !important;
}
/* 音频播放器进度条修复 */
audio::-webkit-media-controls-timeline {
background: linear-gradient(to right, #ff9800 var(--buffered-width, 0%), #404040 var(--buffered-width, 0%)) !important;
border-radius: 4px !important;
height: 4px !important;
}
/* 音频播放器 - Gradio 组件内部 */
.audio-container input[type="range"],
.waveform-container input[type="range"],
div[data-testid="audio"] input[type="range"],
div[data-testid="waveform"] input[type="range"] {
accent-color: #ff9800 !important;
}
/* WaveSurfer 波形进度条 */
.wavesurfer-region,
.wavesurfer-handle,
wave > wave {
background: #ff9800 !important;
}
/* Gradio Audio 组件进度条 */
.audio-player input[type="range"]::-webkit-slider-runnable-track {
background: linear-gradient(to right, #ff9800 0%, #ff9800 var(--value, 0%), #404040 var(--value, 0%), #404040 100%) !important;
}
.audio-player input[type="range"]::-moz-range-track {
background: linear-gradient(to right, #ff9800 0%, #ff9800 var(--value, 0%), #404040 var(--value, 0%), #404040 100%) !important;
}
.audio-player input[type="range"]::-webkit-slider-thumb {
background: #ff9800 !important;
}
.audio-player input[type="range"]::-moz-range-thumb {
background: #ff9800 !important;
}
/* 通用 range input 进度样式 */
input[type="range"] {
accent-color: #ff9800 !important;
}
/* Gradio 4.x 音频波形 */
.waveform-container,
.audio-container {
--waveform-color: #ff9800 !important;
--progress-color: #ff9800 !important;
}
"""
def create_ui() -> gr.Blocks:
"""创建 Gradio 界面"""
with gr.Blocks(
title=i18n.get("app_title", "RVC AI 翻唱"),
theme=gr.themes.Base(
primary_hue="orange",
secondary_hue="gray",
neutral_hue="gray",
).set(
# 背景色
body_background_fill="#121212",
body_background_fill_dark="#121212",
# 面板/卡片背景
block_background_fill="#1e1e1e",
block_background_fill_dark="#1e1e1e",
# 边框
block_border_color="#404040",
block_border_color_dark="#404040",
# 标签背景
block_label_background_fill="#2d2d2d",
block_label_background_fill_dark="#2d2d2d",
# 标签文字
block_label_text_color="#9e9e9e",
block_label_text_color_dark="#9e9e9e",
# 标题文字
block_title_text_color="#e0e0e0",
block_title_text_color_dark="#e0e0e0",
# 输入框
input_background_fill="#2d2d2d",
input_background_fill_dark="#2d2d2d",
input_border_color="#404040",
input_border_color_dark="#404040",
# 主按钮 - 橙色
button_primary_background_fill="#ff9800",
button_primary_background_fill_dark="#ff9800",
button_primary_background_fill_hover="#ffa726",
button_primary_background_fill_hover_dark="#ffa726",
button_primary_text_color="#121212",
button_primary_text_color_dark="#121212",
# 次要按钮 - 深灰
button_secondary_background_fill="#404040",
button_secondary_background_fill_dark="#404040",
button_secondary_background_fill_hover="#4a4a4a",
button_secondary_background_fill_hover_dark="#4a4a4a",
button_secondary_text_color="#e0e0e0",
button_secondary_text_color_dark="#e0e0e0",
# 文字颜色
body_text_color="#e0e0e0",
body_text_color_dark="#e0e0e0",
body_text_color_subdued="#9e9e9e",
body_text_color_subdued_dark="#9e9e9e",
# 链接颜色 - 橙色
link_text_color="#ff9800",
link_text_color_dark="#ff9800",
link_text_color_hover="#ffa726",
link_text_color_hover_dark="#ffa726",
# 滑块颜色
slider_color="#ff9800",
slider_color_dark="#ff9800",
# 复选框/单选框
checkbox_background_color="#2d2d2d",
checkbox_background_color_dark="#2d2d2d",
checkbox_border_color="#404040",
checkbox_border_color_dark="#404040",
checkbox_label_text_color="#e0e0e0",
checkbox_label_text_color_dark="#e0e0e0",
),
css=CUSTOM_CSS
) as app:
# 标题
gr.Markdown(
f"# 🎤 {i18n.get('app_title', 'RVC AI 翻唱')}",
elem_classes=["main-title"]
)
gr.Markdown(
f"<center>{i18n.get('app_description', '基于 RVC v2 的 AI 翻唱系统')}</center>"
)
with gr.Tabs():
# ===== 模型管理标签页 =====
with gr.Tab(t("models", "tabs")):
gr.Markdown(f"### 📦 {t('base_models', 'models')}")
gr.Markdown(t("base_models_desc", "models"))
with gr.Row():
check_btn = gr.Button(
f"🔍 {t('check_status', 'models')}",
variant="secondary"
)
download_btn = gr.Button(
f"⬇️ {t('download_required', 'models')}",
variant="primary"
)
model_status = gr.Textbox(
label=t("model_status", "models"),
interactive=False,
lines=6,
elem_classes=["status-box"]
)
check_btn.click(
fn=check_models_status,
outputs=[model_status]
)
download_btn.click(
fn=download_base_models,
outputs=[model_status]
)
gr.Markdown("---")
gr.Markdown(f"### 🎛️ {t('mature_deecho_models', 'models')}")
gr.Markdown(t("mature_deecho_models_desc", "models"))
with gr.Row():
mature_deecho_check_btn = gr.Button(
f"🔍 {t('mature_deecho_check', 'models')}",
variant="secondary"
)
mature_deecho_download_btn = gr.Button(
f"⬇️ {t('download_mature_deecho', 'models')}",
variant="primary"
)
mature_deecho_status = gr.Textbox(
label=t("mature_deecho_status", "models"),
interactive=False,
lines=7,
value=check_mature_deecho_status(),
elem_classes=["status-box"]
)
gr.Markdown("---")
gr.Markdown(f"### 🎤 {t('voice_models', 'models')}")
gr.Markdown(t("voice_models_desc", "models"))
def get_model_table():
from infer.pipeline import list_voice_models
weights_dir = ROOT_DIR / config.get("weights_dir", "assets/weights")
models = list_voice_models(str(weights_dir))
if not models:
return [["(无模型)", "", ""]]
return [[m["name"], m["model_path"], m.get("index_path", "无")] for m in models]
model_table = gr.Dataframe(
headers=["模型名称", "模型路径", "索引路径"],
value=get_model_table(),
interactive=False
)
refresh_table_btn = gr.Button(
f"🔄 刷新模型列表",
variant="secondary"
)
refresh_table_btn.click(
fn=get_model_table,
outputs=[model_table]
)
# ===== 歌曲翻唱标签页 =====
with gr.Tab(t("cover", "tabs")):
gr.Markdown(f"### 🎵 {t('song_cover', 'cover')}")
gr.Markdown(
"""
**一键 AI 翻唱**:上传歌曲 → 自动分离人声 → 转换音色 → 混合伴奏 → 输出翻唱
**使用步骤:**
1. 先下载角色模型(展开下方「下载角色模型」)
2. 上传歌曲文件(支持 MP3/WAV/FLAC)
3. 选择已下载的角色
4. 调整参数后点击「开始翻唱」
> ⚠️ 首次运行会自动下载 Mel-Band Roformer 人声分离模型(约 200MB),请耐心等待
"""
)
with gr.Row():
# 左侧:输入和角色选择
with gr.Column(scale=1):
gr.Markdown(f"#### 📁 {t('upload_song', 'cover')}")
cover_input_audio = gr.Audio(
label=t("input_song", "cover"),
type="filepath"
)
gr.Markdown(f"#### 🎭 {t('select_character', 'cover')}")
downloaded_series = gr.Dropdown(
label="作品/分类",
choices=get_downloaded_character_series(),
value="全部",
interactive=True
)
downloaded_keyword = gr.Textbox(
label="关键词搜索",
placeholder="输入角色名/作品名",
interactive=True
)
character_dropdown = gr.Dropdown(
label="选择角色",
choices=get_downloaded_character_choices("全部", ""),
interactive=True,
info="括号中的信息为模型训练参数:epochs=训练轮数(越大通常越成熟),数字+k=训练采样率(如40k=40000Hz)"
)
with gr.Row():
refresh_char_btn = gr.Button(
"🔄 刷新",
size="sm",
variant="secondary"
)
# 角色下载区域
with gr.Accordion("下载角色模型", open=False):
series_choices = ["全部"] + get_available_character_series()
download_series = gr.Dropdown(
label="作品/分类",
choices=series_choices,
value="全部",
interactive=True
)
download_keyword = gr.Textbox(
label="关键词搜索",
placeholder="输入角色名/作品名",
interactive=True
)
download_char_dropdown = gr.Dropdown(
label="选择角色",
choices=get_available_character_choices("全部", ""),
interactive=True
)
download_char_btn = gr.Button(
"⬇️ 下载选中角色",
variant="primary"
)
download_all_series_btn = gr.Button(
"⬇️ 下载该分类全部",
variant="secondary"
)
download_all_btn = gr.Button(
"⬇️ 下载全部角色模型",
variant="secondary"
)
download_char_status = gr.Textbox(
label="下载状态",
interactive=False
)
# 右侧:参数设置
with gr.Column(scale=1):
gr.Markdown(f"#### ⚙️ {t('conversion_settings', 'cover')}")
cover_cfg = config.get("cover", {})
cover_pitch_shift = gr.Slider(
label=t("pitch_shift", "cover"),
minimum=-12,
maximum=12,
value=0,
step=1,
info="正数升调,负数降调"
)
cover_index_rate = gr.Slider(
label=t("index_rate", "cover"),
minimum=0,
maximum=100,
value=_to_int(
round(
_to_float(
cover_cfg.get("index_rate", config.get("index_rate", 0.35)),
0.35,
) * 100
),
35,
),
step=5,
info=t("index_rate_info", "cover"),
)
cover_speaker_id = gr.Slider(
label=t("speaker_id", "cover"),
minimum=0,
maximum=255,
value=_to_int(cover_cfg.get("speaker_id", 0), 0),
step=1,
info=t("speaker_id_info", "cover"),
)
gr.Markdown(f"#### 🎚️ {t('mix_settings', 'cover')}")
cover_karaoke = gr.Checkbox(
label=t("karaoke_separation", "cover"),
value=bool(cover_cfg.get("karaoke_separation", True)),
info=t("karaoke_separation_info", "cover")
)
cover_karaoke_merge_backing = gr.Checkbox(
label=t("karaoke_merge_backing", "cover"),
value=bool(
cover_cfg.get(
"karaoke_merge_backing_into_accompaniment",
True
)
),
info=t("karaoke_merge_backing_info", "cover")
)
vc_label_to_value, vc_value_to_label = get_vc_preprocess_option_maps()
source_label_to_value, source_value_to_label = get_source_constraint_option_maps()
pipeline_label_to_value, pipeline_value_to_label = get_vc_pipeline_mode_option_maps()
cover_vc_preprocess_mode = gr.Dropdown(
label=t("vc_preprocess_mode", "cover"),
choices=list(vc_label_to_value.keys()),
value=vc_value_to_label.get(str(cover_cfg.get("vc_preprocess_mode", "auto")), list(vc_label_to_value.keys())[0]),
info=t("vc_preprocess_mode_info", "cover"),
)
cover_source_constraint_mode = gr.Dropdown(
label=t("source_constraint_mode", "cover"),
choices=list(source_label_to_value.keys()),
value=source_value_to_label.get(str(cover_cfg.get("source_constraint_mode", "auto")), list(source_label_to_value.keys())[0]),
info=t("source_constraint_mode_info", "cover"),
)
cover_vc_pipeline_mode = gr.Dropdown(
label=t("vc_pipeline_mode", "cover"),
choices=list(pipeline_label_to_value.keys()),
value=pipeline_value_to_label.get(str(cover_cfg.get("vc_pipeline_mode", "current")), list(pipeline_label_to_value.keys())[0]),
info=t("vc_pipeline_mode_info", "cover"),
)
cover_singing_repair = gr.Checkbox(
label=t("singing_repair", "cover"),
value=bool(cover_cfg.get("singing_repair", False)),
info=t("singing_repair_info", "cover"),
visible=str(cover_cfg.get("vc_pipeline_mode", "current")).strip().lower() == "official",
)
cover_vc_route_status = gr.Textbox(
label=t("vc_preprocess_status", "cover"),
value=get_cover_vc_route_status(
cover_cfg.get("vc_preprocess_mode", "auto"),
cover_cfg.get("vc_pipeline_mode", "current"),
),
info=t("vc_preprocess_status_info", "cover"),
interactive=False,
lines=3,
elem_classes=["status-box"]
)
mix_presets, default_mix_preset = get_cover_mix_presets()
default_mix = mix_presets[default_mix_preset]
cover_mix_preset = gr.Dropdown(
label=t("mix_preset", "cover"),
choices=list(mix_presets.keys()),
value=default_mix_preset,
info=t("mix_preset_info", "cover"),
interactive=True
)
cover_vocals_volume = gr.Slider(
label=t("vocals_volume", "cover"),
minimum=0,
maximum=200,
value=default_mix["vocals_volume"],
step=5,
info="100% 为原始音量"
)
cover_accompaniment_volume = gr.Slider(
label=t("accompaniment_volume", "cover"),
minimum=0,
maximum=200,
value=default_mix["accompaniment_volume"],
step=5,
info="100% 为原始音量"
)
cover_reverb = gr.Slider(
label=t("vocals_reverb", "cover"),
minimum=0,
maximum=100,
value=default_mix["reverb"],
step=5,
info="为人声添加混响效果"
)
cover_rms_mix_rate = gr.Slider(
label=t("rms_mix_rate", "cover"),
minimum=0,
maximum=100,
value=_to_int(
round(
_to_float(
cover_cfg.get(
"rms_mix_rate",
config.get("rms_mix_rate", 0.15),
),
0.15,
) * 100
),
15,
),
step=5,
info=t("rms_mix_rate_info", "cover"),
)
cover_backing_mix = gr.Slider(
label=t("backing_mix", "cover"),
minimum=0,
maximum=100,
value=_to_int(
round(_to_float(cover_cfg.get("backing_mix", 0.0), 0.0) * 100),
0,
),
step=5,
info=t("backing_mix_info", "cover"),
)
# 开始按钮
cover_btn = gr.Button(
f"🚀 {t('start_cover', 'cover')}",
variant="primary",
size="lg"
)
# 状态显示
cover_status = gr.Textbox(
label=t("progress", "cover"),
interactive=False,
elem_classes=["status-box"]
)
# 输出区域
gr.Markdown(f"#### 🎵 {t('results', 'cover')}")
with gr.Row():
cover_output = gr.Audio(
label=t("final_cover", "cover"),
type="filepath",
interactive=False
)
with gr.Row():
cover_converted_vocals_output = gr.Audio(
label=t("converted_vocals", "cover"),
type="filepath",
interactive=False
)
cover_original_vocals_output = gr.Audio(
label=t("original_vocals", "cover"),
type="filepath",
interactive=False
)
with gr.Row():
cover_lead_vocals_output = gr.Audio(
label=t("lead_vocals", "cover"),
type="filepath",
interactive=False
)
cover_backing_vocals_output = gr.Audio(
label=t("backing_vocals", "cover"),
type="filepath",
interactive=False
)
with gr.Row():
cover_accompaniment_output = gr.Audio(
label=t("accompaniment", "cover"),
type="filepath",
interactive=False
)
# 事件绑定
refresh_char_btn.click(
fn=refresh_downloaded_controls,
inputs=[downloaded_series, downloaded_keyword],
outputs=[downloaded_series, character_dropdown]
)
downloaded_series.change(
fn=update_downloaded_choices,
inputs=[downloaded_series, downloaded_keyword],
outputs=[character_dropdown]
)
downloaded_keyword.change(
fn=update_downloaded_choices,
inputs=[downloaded_series, downloaded_keyword],
outputs=[character_dropdown]
)
download_series.change(
fn=update_download_choices,
inputs=[download_series, download_keyword],
outputs=[download_char_dropdown]
)
download_keyword.change(
fn=update_download_choices,
inputs=[download_series, download_keyword],
outputs=[download_char_dropdown]
)
download_char_btn.click(
fn=download_character,
inputs=[download_char_dropdown, downloaded_series, downloaded_keyword],
outputs=[download_char_status, character_dropdown, downloaded_series]
)
download_all_series_btn.click(
fn=download_all_characters,
inputs=[download_series, downloaded_series, downloaded_keyword],
outputs=[download_char_status, character_dropdown, downloaded_series]
)
download_all_btn.click(
fn=lambda series, keyword: download_all_characters("全部", series, keyword),
inputs=[downloaded_series, downloaded_keyword],
outputs=[download_char_status, character_dropdown, downloaded_series]
)
cover_mix_preset.change(
fn=apply_cover_mix_preset,
inputs=[cover_mix_preset],
outputs=[
cover_vocals_volume,
cover_accompaniment_volume,
cover_reverb
]
)
mature_deecho_check_btn.click(
fn=check_mature_deecho_status,
outputs=[mature_deecho_status]
)
mature_deecho_check_btn.click(
fn=get_cover_vc_route_status,
inputs=[cover_vc_preprocess_mode, cover_vc_pipeline_mode],
outputs=[cover_vc_route_status]
)
mature_deecho_download_btn.click(
fn=download_mature_deecho_models_ui,
outputs=[mature_deecho_status]
)
mature_deecho_download_btn.click(
fn=get_cover_vc_route_status,
inputs=[cover_vc_preprocess_mode, cover_vc_pipeline_mode],
outputs=[cover_vc_route_status]
)
cover_vc_preprocess_mode.change(
fn=get_cover_vc_route_status,
inputs=[cover_vc_preprocess_mode, cover_vc_pipeline_mode],
outputs=[cover_vc_route_status]
)
cover_vc_pipeline_mode.change(
fn=get_cover_vc_route_status,
inputs=[cover_vc_preprocess_mode, cover_vc_pipeline_mode],
outputs=[cover_vc_route_status]
)
cover_vc_pipeline_mode.change(
fn=update_singing_repair_visibility,
inputs=[cover_vc_pipeline_mode],
outputs=[cover_singing_repair]
)
cover_btn.click(
fn=process_cover,
inputs=[
cover_input_audio,
character_dropdown,
cover_pitch_shift,
cover_index_rate,
cover_speaker_id,
cover_karaoke,
cover_karaoke_merge_backing,
cover_vc_preprocess_mode,
cover_source_constraint_mode,
cover_vc_pipeline_mode,
cover_singing_repair,
cover_vocals_volume,
cover_accompaniment_volume,
cover_reverb,
cover_rms_mix_rate,
cover_backing_mix,
],
outputs=[
cover_output,
cover_converted_vocals_output,
cover_original_vocals_output,
cover_lead_vocals_output,
cover_backing_vocals_output,
cover_accompaniment_output,
cover_status
]
)
# ===== 设置标签页 =====
with gr.Tab(t("settings", "tabs")):
gr.Markdown(f"### 💻 {t('device_info', 'settings')}")
device_info = gr.Textbox(
label=t("current_device", "settings"),
value=get_device_info(),
interactive=False,
lines=5,
elem_classes=["status-box"]
)
refresh_device_btn = gr.Button(
f"🔄 {t('refresh_device', 'settings')}",
variant="secondary"
)
refresh_device_btn.click(
fn=get_device_info,
outputs=[device_info]
)
gr.Markdown("---")
gr.Markdown(f"### ⚙️ 运行设置")
def _build_device_choices():
from lib.device import _has_xpu, _has_directml, _has_mps, _is_rocm
import torch
choices = []
if torch.cuda.is_available():
label = "ROCm (AMD GPU)" if _is_rocm() else "CUDA (NVIDIA GPU)"
choices.append((label, "cuda"))
if _has_xpu():
choices.append(("XPU (Intel GPU)", "xpu"))
if _has_directml():
choices.append(("DirectML (AMD/Intel GPU)", "directml"))
if _has_mps():
choices.append(("MPS (Apple GPU)", "mps"))
choices.append(("CPU (较慢)", "cpu"))
return choices
device_radio = gr.Radio(
label="计算设备",
choices=_build_device_choices(),
value=config.get("device", "cuda")
)
save_settings_btn = gr.Button(
"💾 保存设置",
variant="primary"
)
settings_status = gr.Textbox(
label="状态",
interactive=False
)
def save_settings(device):
global config
config["device"] = device
config_path = ROOT_DIR / "configs" / "config.json"
with open(config_path, "w", encoding="utf-8") as f:
json.dump(config, f, indent=4, ensure_ascii=False)
return "✅ 设置已保存,重启后生效"
save_settings_btn.click(
fn=save_settings,
inputs=[device_radio],
outputs=[settings_status]
)
gr.Markdown("---")
gr.Markdown(f"### ℹ️ {t('about', 'settings')}")
gr.Markdown(
"""
**RVC AI 翻唱系统**
- 基于 RVC v2 + Mel-Band Roformer
- 使用 RMVPE 进行高质量 F0 提取
- 支持 CUDA GPU 加速
[GitHub](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI)
"""
)
gr.Markdown("---")
gr.Markdown(
"""
### 📥 角色模型来源
以下是本项目角色模型的 HuggingFace 仓库来源,你也可以手动下载模型后放入 `assets/weights/characters/<角色名>/` 目录使用:
**Love Live! 系列**
- [trioskosmos/rvc_models](https://huggingface.co/trioskosmos/rvc_models) — μ's / Aqours / 虹咲 / Liella! 多角色
- [Icchan/LoveLive](https://huggingface.co/Icchan/LoveLive) — 千歌、梨子、绘里、曜
- [0xMifune/LoveLive](https://huggingface.co/0xMifune/LoveLive) — 虹咲 / Liella! / 莲之空
- [Swordsmagus/Love-Live-RVC](https://huggingface.co/Swordsmagus/Love-Live-RVC) — 花丸、雪菜、小鸟、A-RISE 等
- [Zurakichi/RVC](https://huggingface.co/Zurakichi/RVC) — 妮可、彼方、雪菜、花丸
- [Phos252/RVCmodels](https://huggingface.co/Phos252/RVCmodels) — 涩谷香音
- [ChocoKat/Mari_Ohara](https://huggingface.co/ChocoKat/Mari_Ohara) — 小原鞠莉
- [HarunaKasuga/YoshikoTsushima](https://huggingface.co/HarunaKasuga/YoshikoTsushima) — 津岛善子
- [thebuddyadrian/RVC_Models](https://huggingface.co/thebuddyadrian/RVC_Models) — 鹿角姐妹
**原神 / 崩坏 / 绝区零 (米哈游)**
- [makiligon/RVC-Models](https://huggingface.co/makiligon/RVC-Models) — 芙宁娜、绫华、芙卡洛斯
- [kohaku12/RVC-MODELS](https://huggingface.co/kohaku12/RVC-MODELS) — 纳西妲、黑塔、流萤、停云、星见雅 等
- [jarari/RVC-v2](https://huggingface.co/jarari/RVC-v2) — 芙宁娜(韩语)、银狼(韩语)
- [mrmocciai/genshin-impact](https://huggingface.co/mrmocciai/genshin-impact) — 原神 50+ 角色(需手动下载)
**VOCALOID**
- [javinfamous/infamous_miku_v2](https://huggingface.co/javinfamous/infamous_miku_v2) — 初音未来 (1000 epochs)
**Hololive / VTuber**
- [megaaziib/my-rvc-models-collection](https://huggingface.co/megaaziib/my-rvc-models-collection) — 佩克拉、樱巫女、大空昴、Kobo、Kaela 等
- [Kit-Lemonfoot/kitlemonfoot_rvc_models](https://huggingface.co/Kit-Lemonfoot/kitlemonfoot_rvc_models) — Hololive JP/EN 多角色
**偶像大师 / 赛马娘**
- [trioskosmos/rvc_models](https://huggingface.co/trioskosmos/rvc_models) — 神崎兰子、梦见莉亚梦
- [makiligon/RVC-Models](https://huggingface.co/makiligon/RVC-Models) — 四条贵音、米浴
**Project SEKAI**
- [kohaku12/RVC-MODELS](https://huggingface.co/kohaku12/RVC-MODELS) — 草薙宁宁
> 💡 手动下载后,将 `.pth` 和 `.index` 文件放入 `assets/weights/characters/<角色名>/` 目录,刷新即可使用。
"""
)
return app
def _patch_gradio_file_download(blocks):
"""
Patch Gradio v3 的 /file= 路由,为文件添加 Content-Disposition header,
使浏览器下载时使用干净的文件名而非完整路径。
"""
try:
from starlette.responses import FileResponse
from urllib.parse import quote
import fastapi
def _clean_download_name(response: FileResponse, path_or_url: str) -> str:
candidates = [
getattr(response, "filename", None),
getattr(response, "path", None),
path_or_url,
]
for candidate in candidates:
if not candidate:
continue
name = Path(str(candidate)).name
if not name:
continue
name = re.sub(
r"^[A-Za-z]__.*?_gradio_[0-9a-f]{8,}_",
"",
name,
flags=re.IGNORECASE,
)
if name:
return name
return "download"
fastapi_app = getattr(blocks, "server_app", None)
if fastapi_app is None:
return
for route in fastapi_app.routes:
if hasattr(route, "path") and route.path == "/file={path_or_url:path}":
original_endpoint = route.endpoint
async def patched_file(
path_or_url: str,
request: fastapi.Request,
_orig=original_endpoint,
):
response = await _orig(path_or_url, request=request)
if isinstance(response, FileResponse) and "content-disposition" not in response.headers:
basename = _clean_download_name(response, path_or_url)
encoded = quote(basename)
if encoded != basename:
cd = f"inline; filename*=utf-8''{encoded}"
else:
cd = f'inline; filename="{basename}"'
response.headers["content-disposition"] = cd
return response
route.endpoint = patched_file
break
except Exception as e:
log.warning(f"Patch Gradio file download failed: {e}")
def launch(host: str = "127.0.0.1", port: int = 7860, share: bool = False):
"""启动 Gradio 界面"""
app = create_ui()
app.queue() # 启用队列以支持进度跟踪
app.launch(
server_name=host,
server_port=port,
share=share,
inbrowser=True,
prevent_thread_lock=True
)
_patch_gradio_file_download(app)
app.block_thread()
if __name__ == "__main__":
launch()
|