Spaces:
Running
Running
File size: 119,636 Bytes
e228f58 | 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 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 | #!/usr/bin/env python3
"""
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Audio Enhancement Engine v8.4 โ "Source Tier Intelligence" โ
โ ุงูู
ุฑุฌุน: ุงูุดูุฎ ูุงุณุฑ ุงูุฏูุณุฑู โ 1425H โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ โ
โ ุงูุฃุฎุทุงุก ุงูู
ูุดุฎููุตุฉ ูู v7.6 (Forensic Deep-Dive): โ
โ โ
โ ๐ด BUG #1 โ SPECTRAL_BIAS ุงุชุฌุงู ู
ุนููุณ ูู 3 ูุทุงูุงุช ุญุฑุฌุฉ โ
โ 250Hz: bias=+11 โ cut ุจุฏู boost (output -7dB ุชุญุช ref!) โ
โ 4kHz: bias=-1.5 โ boost ุจุฏู cut (output +5dB ููู ref!) โ
โ 8kHz: bias=-4.0 โ boost ุจุฏู cut (output +10dB ููู ref!) โ
โ ุงูุฅุตูุงุญ: SPECTRAL_BIAS_V8 ุจุงูุงุชูุงููุฉ ุงูุตุญูุญุฉ (output-ref) โ
โ โ
โ ๐ด BUG #2 โ Double Compand Stacking ูุณุญู Crest โ
โ LRA compand + Main compand โ ุถุบุท ู
ุฒุฏูุฌ โ Crest ูููุงุฑ โ
โ ุงูุฅุตูุงุญ: ุญุฐู LRA compand ู
ู Pass1 โ Main compand ูุญูุฏ โ
โ โ
โ ๐ BUG #3 โ 5 ุชุทุจููุงุช alimiter ุชุทุญู Crest ุชุฑุงูู
ูุงู โ
โ P1(ร2) + P2 + P3 + P4 = 5 ู
ุฑุงุช limit=0.891 โ Crest ููุฎูุถ 0.8-1.5LU โ
โ ุงูุฅุตูุงุญ: WAV ูุณูุทุฉ = limit=0.9997 ููุท | MP3 ููุงุฆู = 0.891 โ
โ โ
โ ๐ BUG #4 โ build_compand_mds ูุณุชุฎุฏู
DR ุจุฏู LRA โ
โ lra_delta = damage.dr - TARGET['dr'] โ ุฎุทุฃ ููุน! โ
โ ุงูุฅุตูุงุญ: lra_delta = inp_lra - ref_fp.lra_clip (ุตุญูุญ) โ
โ โ
โ ๐ก BUG #5 โ Quality Gate ูุง ูุญู
ู Crest ุจุดูู ู
ููุตู โ
โ ุนุชุจุฉ 1.0 ููุทุฉ ุชุชุฌุงูู ุงูููุงุฑ Crest 3+LU โ
โ ุงูุฅุตูุงุญ: ุญุงุฑุณ ู
ุณุชูู Crest < P1-1.5LU AND < target-0.8 โ
โ โ
โ ุงูู
ุญุงูุธ ุนููู ู
ู v7.6 (Architecture ุณููู
): โ
โ โ
MDS System (SFM + DR + Spectral Distance + Per-Band SNR) โ
โ โ
SFM-Adaptive NR โ
โ โ
Full-File LRA Target 4.19 (v7.6 fix) โ
โ โ
Dual LRA: lra_clip ููู compand | lra ููู quality score โ
โ โ
9-Segment Full-File Spectral Average โ
โ โ
4-Pass WAV Pipeline (lossless ุญุชู Pass4) โ
โ โ
Crest-Aware Warmth Nodes โ
โ โ
Scipy Perceptual EQ (Bark + A-weight) โ
โ โ
Arabic Filename Safety โ
โ โ
โ ุงููุฏู: LUFS=-6.29 RMS=-10.01 Crest=10.25 LRA=4.19 โฅ96/100 โ
โ โ
โ ุฅุตูุงุญุงุช v8.1 โ Android Subprocess Hardening: โ
โ ๐ด PATCH #1 โ REF_CACHE: /tmp โ Path.home()/.tilawa_cache/ (persistent) โ
โ ๐ด PATCH #2 โ REF_FILES: hardcoded โ env var + ~/.tilawa_ref/ + legacy โ
โ ๐ด PATCH #3 โ ALL /tmp/ refs โ tempfile.gettempdir() (Android-safe) โ
โ ๐ PATCH #4 โ Adaptive EQ scale: tiered โ linear ramp (+3 quality pts) โ
โ ๐ก PATCH #5 โ 64K_FLOOR label: honest Crest ceiling for 64kbps sources โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
"""
from __future__ import annotations
import argparse, json, os, shutil, subprocess, sys, warnings, time, tempfile as _tempfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Optional, Tuple
warnings.filterwarnings('ignore')
# v8.1 PATCH #3: platform/context-aware temp dir
# Termux shell: /data/data/com.termux/files/usr/tmp/
# Android subprocess: /data/local/tmp/ or app cache dir
# Linux desktop: /tmp/
_TMP = _tempfile.gettempdir()
try:
import numpy as np
from scipy.fft import rfft, rfftfreq
from scipy.optimize import minimize
from scipy.interpolate import CubicSpline
NUMPY_OK = SCIPY_OK = True
except ImportError:
NUMPY_OK = SCIPY_OK = False
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# CONSTANTS
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
SR = 48000
TARGET = {
'lufs': -6.29,
'rms': -10.01,
'crest': 10.25,
'lra': 4.19, # full-file measurement (corrected in v7.6, kept in v8)
'true_peak': -1.0,
'bitrate': '320k',
'sfm': 0.0444,
'dr': 7.9,
}
# โโ v8.1 PATCH #2: REF_FILES โ env var โ home dir โ legacy (dev only) โโโโโ
def _resolve_ref_files() -> List[str]:
"""
Resolution order:
1. TILAWA_REF_DIR env var (set by Flutter before spawning subprocess)
2. ~/.tilawa_ref/ (user-populated in Termux home)
3. Legacy /mnt/user-data/uploads/ (Claude.ai sandbox โ dev only)
Returns [] if nothing found; get_reference_fingerprint() handles empty list.
"""
# 1. Flutter sets this env var before Process.start()
env_dir = os.environ.get('TILAWA_REF_DIR', '')
if env_dir and os.path.isdir(env_dir):
found = sorted([str(p) for p in Path(env_dir).glob('*.mp3')])
if found: return found
# 2. Termux home ref directory (user populates this once)
home_ref = Path.home() / '.tilawa_ref'
if home_ref.is_dir():
found = sorted([str(p) for p in home_ref.glob('*.mp3')])
if found: return found
# 3. v8.2: Docker /app/reference_audio/ self-location
container_ref = Path(__file__).parent / "reference_audio"
if container_ref.is_dir():
found = sorted([
str(p) for p in container_ref.glob("*.mp3")
if p.stat().st_size > 10_000
])
if found:
return found
# 4. Legacy Claude.ai sandbox paths (development only)
legacy = [
"/mnt/user-data/uploads/ref_araf_1425h.mp3",
"/mnt/user-data/uploads/ref_fath_1425h.mp3",
"/mnt/user-data/uploads/ref_fatir_1425h.mp3",
]
found = [p for p in legacy if os.path.exists(p)]
return found
REF_FILES = _resolve_ref_files()
# โโ v8.1 PATCH #1: REF_CACHE โ persistent home-dir path โโโโโโโโโโโโโโโโโโโโโ
# /tmp/ does NOT exist in Android's app subprocess sandbox.
# Path.home() resolves correctly in both Termux shell and Flutter subprocess.
_CACHE_DIR = Path.home() / '.tilawa_cache'
REF_CACHE = str(_CACHE_DIR / 'ref_fp.v85.json') # v8.5: cache version bump
CENTERS_31 = [
20,25,31.5,40,50,63,80,100,125,160,
200,250,315,400,500,630,800,1000,1250,1600,
2000,2500,3150,4000,5000,6300,8000,10000,12500,16000,20000,
]
A_WEIGHT: Dict[float,float] = {
20:-50.5,25:-44.7,31.5:-39.4,40:-34.6,50:-30.2,
63:-26.2,80:-22.5,100:-19.1,125:-16.1,160:-13.4,
200:-10.9,250:-8.6,315:-6.6,400:-4.8,500:-3.2,
630:-1.9,800:-0.8,1000:0.0,1250:0.6,1600:1.0,
2000:1.2,2500:1.3,3150:1.2,4000:1.0,5000:0.5,
6300:-0.1,8000:-1.1,10000:-2.5,12500:-4.3,16000:-6.6,20000:-9.3,
}
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# v8 BUG #1 FIX โ SPECTRAL_BIAS_V8: ุงุชูุงููุฉ ุตุญูุญุฉ ู
ูุญุฏุฉ
#
# ุงูุงุชูุงููุฉ: bias = (output - ref)
# ุณุงูุจ = output ุชุญุช ref โ g = -(-)*scale = ู
ูุฌุจ (boost) โ
# ู
ูุฌุจ = output ููู ref โ g = -(+)*scale = ุณุงูุจ (cut) โ
#
# v7.6 ูุงู ูุณุชุฎุฏู
"ุฑุบุจุฉ ูู ุงูุชุตุญูุญ" ุจุฏู "ุงูุฎุทุฃ ุงูู
ููุงุณ":
# 250Hz: +11 โ ููุทุน ุจุฏู ุฑูุน (output -7dB ุชุญุช ref) โ
# 4kHz: -1.5 โ ูุฑูุน ุจุฏู ูุทุน (output +5dB ููู ref) โ
# 8kHz: -4.0 โ ูุฑูุน ุจุฏู ูุทุน (output +10dB ููู ref) โ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
SPECTRAL_BIAS_V8: Dict[int,float] = {
# ุงููุทุงูุงุช ุงูุฏููุง โ ู
ุญุชุงุฌ ุฑูุน (output ุชุญุช ref ูู ู
ููุงุช 64kbps)
80: -2.50, # output -2.5dB ุชุญุช ref โ g=+0.625dB boost
100: -4.00, # output -4dB ุชุญุช ref โ g=+1.00dB boost
125: +3.50, # output +3.5dB ููู ref โ g=-0.875dB cut
200: -4.00, # output -4dB ุชุญุช ref โ g=+1.00dB boost
# โ ุฅุตูุงุญ v8 ุงูุญุฑุฌ: ูุงู +11.00 โ ููุทุน ุนูุถุงู ุนู ุงูุฑูุน!
250: -7.00, # output -7dB ุชุญุช ref โ g=+1.75dB boost โ v8 FIX ุงูุฃูุจุฑ
315: +6.00, # output +6dB ููู ref โ g=-1.50dB cut
400: -1.50, # output ุชุญุช ref โ g=+0.375dB boost
500: +1.50, # output ููู ref โ g=-0.375dB cut
630: -2.50, # output ุชุญุช ref โ g=+0.625dB boost
800: +1.50, # output ููู ref โ g=-0.375dB cut
1000: -1.00, # output ุชุญุช ref โ g=+0.25dB boost (v7.55: ูุงู ูุนุทู ูุทุน)
1250: +0.40, # ุตุบูุฑ ุฌุฏุงู โ ุชุฃุซูุฑ ุถุฆูู
2000: +0.50, # ุตุบูุฑ ุฌุฏุงู โ ุชุฃุซูุฑ ุถุฆูู
2500: +1.80, # output ููู ref โ g=-0.45dB cut
3150: +1.20, # output ููู ref โ g=-0.30dB cut
# โ ุฅุตูุงุญ v8 ุงูุญุฑุฌ: ูุงู -1.50 โ ูุฑูุน ุนูุถุงู ุนู ุงููุทุน!
4000: +5.00, # output +5dB ููู ref โ g=-1.25dB cut โ v8 FIX
# โ ุฅุตูุงุญ v8: ูุงู -0.80 ู-0.90 โ ูุฑูุน ูู ู
ูุทูุฉ ู
ุฑุชูุนุฉ ุฃุตูุงู
5000: +0.80, # output ููู ref โ g=-0.20dB cut โ v8 FIX (was -0.80)
6300: +0.90, # output ููู ref โ g=-0.225dB cut โ v8 FIX (was -0.90)
# โ ุฅุตูุงุญ v8 ุงูุญุฑุฌ: ูุงู -4.00 โ ูุฑูุน ุนูุถุงู ุนู ุงููุทุน!
8000: +8.00, # output +8-10dB ููู ref โ g=-2.00dB cut โ v8 FIX ุงูุฃูุจุฑ
10000: -2.00, # output ุชุญุช ref (rolloff) โ g=+0.50dB boost
}
BIAS_SCALE = 0.25 # ุงูุตูุบุฉ: g = round(-bias_db * BIAS_SCALE, 2)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# DATA CLASSES
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@dataclass
class ReferenceFingerprint:
third_oct: Dict[float,float] = field(default_factory=dict)
a_weighted: Dict[float,float] = field(default_factory=dict)
rms: float = TARGET['rms']
peak: float = TARGET['true_peak']
crest: float = TARGET['crest']
lra: float = TARGET['lra']
lra_clip: float = 2.94
tilt_slope: float = 0.0
warmth_ratio: float = 0.0
sfm: float = TARGET['sfm']
dr: float = TARGET['dr']
n_files: int = 0
# โโ v8.45: DeepReferenceModel fields โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
phrase_lra_p10: float = 2.50 # LRA at 10th percentile of phrases
phrase_lra_p50: float = 3.37 # LRA at 50th percentile (compand target)
phrase_lra_p90: float = 4.20 # LRA at 90th percentile
silence_floor_db: float = -73.0 # measured ref noise floor (NR ceiling = this - 3dB)
ref_codec_cutoff_hz: float = 14000.0 # highest freq with real content in refs
peak_distribution: str = 'uniform' # front_loaded / uniform / back_loaded
@dataclass
class DamageProfile:
"""v7.6 Multi-Metric Damage Score (MDS) โ ู
ุญุงููุธ ุนููู ูู v8"""
snr: float = 30.0
sfm: float = 0.05
dr: float = 8.0
hf_deficit: float = 0.0
spectral_dist: float = 0.0
crest: float = 10.0
src_br: int = 128000
band_snr: Dict[float,float] = field(default_factory=dict)
mds: float = 0.0
nr_intensity: float = 0.0
compand_score: float = 0.0
has_ringing: bool = False
rolloff_hz: float = 20000.0
quality_label: str = 'GOOD'
@dataclass
class QualityReport:
score: float = 0.0
spectral: float = 0.0
lufs: float = 0.0
crest: float = 0.0
lra: float = 0.0
warmth: float = 0.0
hf: float = 0.0
avg_err: float = 99.0
warmth_tilt: float = 0.0
warmth_ref: float = 0.0
lra_target: float = TARGET['lra']
notes: List[str] = field(default_factory=list)
# โโ v8.5: TierAdjustedScoring fields โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
score_absolute: float = 0.0 # scored vs original 1425H targets (always)
score_tier: float = 0.0 # scored vs tier-achievable targets (displayed)
ceiling_reason: str = '' # e.g. "TIER_COMPRESSED: Crestโค9.8LU LRAโค4.0LU
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# v8.4 โ SOURCE TIER DETECTOR
# SourceTierProfile + 6 detection functions
# ููุดุบููู ู
ุฑุฉ ูุงุญุฏุฉ ูู enhance() ุจุนุฏ DamageProfile ููุจู NR
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@dataclass
class SourceTierProfile:
"""
ูุชูุฌุฉ ุชุตููู ุฌูุฏุฉ ุงูู
ุตุฏุฑ โ ุชูุญุฏููุฏ ูุจู ุฃู ู
ุนุงูุฌุฉ.
ุชูู
ุฑููุฑ ููู ูุญุฏุฉ ูู ุงูู pipeline ูุชุถุจุท ุญุฏูุฏ ุงูุชุฏุฎู.
"""
# โโ ูุชุงุฆุฌ ุงูููุงุณ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
tier: str = 'TIER_PRISTINE'
input_cutoff_hz: float = 20000.0 # ุชุฑุฏุฏ ูุทุน ุงูููุฏู ุงูู
ููุงุณ
noise_type: str = 'none' # none|hiss|hum_50hz|hum_60hz|broadband|hiss+hum
clip_tier: str = 'none' # none|mild|moderate|severe
clip_ratio: float = 0.0 # ูุณุจุฉ ุงูุนููุงุช ุงูู
ูุทูุนุฉ 0โ1
hum_freq_hz: float = 0.0 # 50.0 ุฃู 60.0 ุฅุฐุง ููุฌุฏ hum
sfm_silence: float = 0.0 # SFM ูู ู
ูุงุทุน ุงูุตู
ุช
snr_effective: float = 30.0 # SNR ุงููุนูู
# โโ ู
ุนุงู
ูุงุช ุงูุชูุฌูู โ ุชูุดุชู ู
ู ุงูู tier โโโโโโโโโโโโโโโโโโโโโโโโโโ
bias_cutoff_hz: float = 20000.0 # ูุง BIAS g>0 ููู ูุฐุง ุงูุชุฑุฏุฏ
eq_ramp_scale: float = 1.0 # ู
ุถุงุนู ุนูู scale ูู adaptive EQ
nr_mandatory: bool = False # ุฃุฌุจุฑ NR ุญุชู ูู SFM ูููู ูุง
lra_expand_gate: bool = True # ุงุณู
ุญ ุจุชูุณูุน LRA ูู Pass 3
achievable_crest: float = 10.25 # ุณูู Crest ุงูููุฒูุงุฆู
achievable_lra: float = 4.19 # ูุฏู LRA ุงููุงุจู ููุชุญููู
achievable_lufs: float = -6.29 # ูุฏู LUFS ุงููุงุจู ููุชุญููู
def detect_codec_cutoff(inp_b: Dict[float, float]) -> float:
"""
ูู
ุณุญ CENTERS_31 ู
ู 20kHz ูุฒููุงู.
ุฃูู ูุทุงู ููู ุทุงูุฉ > (noise_floor_p10 + 6dB) = ุชุฑุฏุฏ ุงููุทุน.
ุงูููุฒูุงุก: ุถูุถุงุก ุงูุชูู
ูู
ุทูููุง ุดุจู ู
ุณุทุญ ุชุญุช ุงูุฅุดุงุฑุฉ.
ููู ุชุฑุฏุฏ ุงููุทุน: ุฅุดุงุฑุฉ ุชุณูุท ุชุญุช ุถูุถุงุก ุงูุชูู
ูู
.
Bypass: inp_b ูุงุฑุบุฉ โ 20000.0
"""
if not inp_b:
return 20000.0
all_vals = sorted(inp_b.values())
noise_floor = float(np.percentile(all_vals, 10)) if len(all_vals) >= 4 else -70.0
threshold = noise_floor + 6.0
for fc in sorted(inp_b.keys(), reverse=True):
if inp_b[fc] > threshold:
return float(fc)
return float(min(inp_b.keys(), default=20000.0))
def detect_noise_type(audio: 'np.ndarray',
sr: int = SR) -> Tuple[str, float, float]:
"""
ูุญุฏุฏ ููุน ุงูุถูุถุงุก ู
ู ู
ูุงุทุน ุงูุตู
ุช (ุฅุทุงุฑุงุช 200ms).
ุงูุฎูุงุฑุฒู
ูุฉ:
1. ุฅุทุงุฑุงุช ุงูุตู
ุช: (overall_rms-18dB) > frame_rms > -62dBFS
2. SFM ุนูู ุงูุตู
ุช ุงูู
ูุฏู
ุฌ โ SFM>0.65 = broadband noise
3. ุทุงูุฉ 50Hz / 60Hz ู
ูุงุจู ุงูุฌูุฑุงู +25Hz โ +15dB = hum
Bypass: audio ูุตูุฑ ุฌุฏุงู (<3 ุฅุทุงุฑุงุช ุตู
ุช) โ ('unknown', 0.0, 0.0)
Returns: (noise_type, sfm_silence, hum_freq_hz)
"""
frame_n = int(0.2 * sr)
if len(audio) < frame_n * 3:
return ('unknown', 0.0, 0.0)
overall_rms_db = rms_db(audio)
silence_thresh = overall_rms_db - 18.0
silence_floor = -62.0
frames = [audio[i:i+frame_n]
for i in range(0, len(audio) - frame_n, frame_n)]
silence_frames = [f for f in frames
if silence_floor < rms_db(f) < silence_thresh]
if len(silence_frames) < 3:
return ('unknown', 0.0, 0.0)
silence_audio = np.concatenate(silence_frames)
sfm_sil = compute_sfm(silence_audio, sr, f_lo=200.0, f_hi=8000.0)
hum_freq = 0.0
N_sil = len(silence_audio)
spec_sil = np.abs(rfft(silence_audio)) ** 2
freqs_sil = rfftfreq(N_sil, 1.0 / sr)
def _band_e(fc: float, bw: float = 3.0) -> float:
mask = (freqs_sil >= fc - bw) & (freqs_sil <= fc + bw)
return float(np.mean(spec_sil[mask])) if mask.sum() > 0 else 1e-30
for test_hz in [50.0, 60.0]:
ratio_db = 10 * np.log10(
_band_e(test_hz) /
(np.mean([_band_e(test_hz-25.0), _band_e(test_hz+25.0)]) + 1e-30)
+ 1e-30
)
if ratio_db > 15.0:
hum_freq = test_hz
break
has_hiss = sfm_sil > 0.65
has_hum = hum_freq > 0.0
if has_hiss and has_hum: noise_type = 'hiss+hum'
elif has_hiss: noise_type = 'hiss' if sfm_sil < 0.85 else 'broadband'
elif has_hum: noise_type = f'hum_{int(hum_freq)}hz'
else: noise_type = 'none'
return (noise_type, float(sfm_sil), float(hum_freq))
def detect_clip_tier_v84(audio: 'np.ndarray') -> Tuple[str, float]:
"""ููุตููู ู
ุณุชูู ุงููุทุน โ wrapper ุนูู count_clips()."""
n_clips = count_clips(audio, thr=0.99)
ratio = n_clips / max(len(audio), 1)
if ratio < 0.001: tier = 'none'
elif ratio < 0.02: tier = 'mild'
elif ratio < 0.20: tier = 'moderate'
else: tier = 'severe'
return tier, float(ratio)
def _classify_source_tier(src_br: int, cutoff_hz: float,
snr_db: float, noise_type: str) -> str:
"""
ุชุตููู ูุฆุฉ ุงูู
ุตุฏุฑ โ ุฃูู ูุงุนุฏุฉ ุชูุทุจู ุชูุญุฏุฏ ุงููุฆุฉ.
TIER_PRISTINE: 128kbps+ AND cutoff>14kHz AND SNR>25dB AND noise=none
TIER_COMPRESSED: 64kbps+ AND cutoff>10kHz AND SNR>15dB
TIER_DEGRADED: 32kbps+ AND cutoff>7kHz AND SNR>8dB
TIER_DAMAGED: ูู ู
ุง ุชุจูู
"""
if (src_br >= 128_000 and cutoff_hz > 14_000.0
and snr_db > 25.0 and noise_type == 'none'):
return 'TIER_PRISTINE'
if src_br >= 64_000 and cutoff_hz > 10_000.0 and snr_db > 15.0:
return 'TIER_COMPRESSED'
if src_br >= 32_000 and cutoff_hz > 7_000.0 and snr_db > 8.0:
return 'TIER_DEGRADED'
return 'TIER_DAMAGED'
def _build_routing_params(tier: str, cutoff_hz: float,
noise_type: str, inp_lra: float,
ref_lra_clip: float) -> dict:
"""ูููุชุฌ ู
ุนุงู
ูุงุช ุงูุชูุฌูู ู
ู ุงูู tier โ ู
ูููุตู ููุงุฎุชุจุงุฑ."""
lra_deficit = ref_lra_clip - inp_lra
if tier == 'TIER_PRISTINE':
return dict(
bias_cutoff_hz=20_000.0, eq_ramp_scale=1.0,
nr_mandatory=False, lra_expand_gate=True,
achievable_crest=10.25, achievable_lra=4.19, achievable_lufs=-6.29,
)
if tier == 'TIER_COMPRESSED':
return dict(
bias_cutoff_hz=cutoff_hz * 0.90, eq_ramp_scale=0.70,
nr_mandatory=(noise_type != 'none'), lra_expand_gate=True,
achievable_crest=9.5, achievable_lra=4.0, achievable_lufs=-6.29,
)
if tier == 'TIER_DEGRADED':
return dict(
bias_cutoff_hz=min(8_000.0, cutoff_hz * 0.85), eq_ramp_scale=0.40,
nr_mandatory=True, lra_expand_gate=(lra_deficit > 0.8),
achievable_crest=8.5, achievable_lra=3.6, achievable_lufs=-6.5,
)
# TIER_DAMAGED
return dict(
bias_cutoff_hz=4_000.0, eq_ramp_scale=0.20,
nr_mandatory=True, lra_expand_gate=False,
achievable_crest=7.5, achievable_lra=3.2, achievable_lufs=-7.0,
)
def build_source_tier_profile(audio: 'np.ndarray',
inp_b: Dict[float, float],
src_br: int,
snr_db: float,
inp_lra: float,
ref_lra_clip: float,
sr: int = SR) -> SourceTierProfile:
"""
ุงูุฏุงูุฉ ุงูุฑุฆูุณูุฉ โ ุชูุดุบูู ุฌู
ูุน ุงูู
ุณุชุดุนุฑุงุช ูุชูุฌู
ูุน SourceTierProfile.
ููุณุชุฏุนู ู
ุฑุฉ ูุงุญุฏุฉ ูู enhance() ุจุนุฏ DamageProfile ููุจู NR.
"""
cutoff_hz = detect_codec_cutoff(inp_b)
noise_type, sfm_sil, hum_freq = detect_noise_type(audio, sr)
effective_noise = noise_type if noise_type != 'unknown' else 'none'
clip_tier, clip_ratio = detect_clip_tier_v84(audio)
tier = _classify_source_tier(src_br, cutoff_hz, snr_db, effective_noise)
routing = _build_routing_params(tier, cutoff_hz, effective_noise,
inp_lra, ref_lra_clip)
return SourceTierProfile(
tier=tier, input_cutoff_hz=cutoff_hz,
noise_type=noise_type, clip_tier=clip_tier, clip_ratio=clip_ratio,
hum_freq_hz=hum_freq, sfm_silence=sfm_sil, snr_effective=snr_db,
**routing,
)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# AUDIO I/O
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _safe(path:str) -> Tuple[str,Optional[str]]:
"""v8.1 PATCH #3: use _TMP (platform-aware) instead of hardcoded /tmp/"""
try: path.encode('ascii'); return path,None
except UnicodeEncodeError:
import uuid as _u
ext=os.path.splitext(path)[1] or '.mp3'
tmp=os.path.join(_TMP, f'v81_safe_{_u.uuid4().hex[:8]}{ext}')
try:
shutil.copy2(path,tmp)
except OSError:
# last resort: write beside the output in cwd
tmp=os.path.join(os.getcwd(), f'v81_safe_{_u.uuid4().hex[:8]}{ext}')
shutil.copy2(path,tmp)
return tmp,tmp
def load_audio(path:str,sr:int=SR,mono:bool=True,
skip:int=0,duration:Optional[int]=None) -> 'np.ndarray':
sp,tc=_safe(path)
cmd=['ffmpeg','-i',sp]
if skip>0: cmd+=['-ss',str(skip)]
if duration: cmd+=['-t',str(duration)]
cmd+=['-f','s16le','-ac','1' if mono else '2',
'-ar',str(sr),'-loglevel','error','-']
r=subprocess.run(cmd,capture_output=True)
if tc:
try: os.remove(tc)
except: pass
if not r.stdout: raise RuntimeError(f'ูุดู ุชุญู
ูู: {path}')
return np.frombuffer(r.stdout,np.int16).astype(np.float32)/32768.0
def probe(path:str) -> Dict:
sp,tc=_safe(path)
r=subprocess.run(['ffprobe','-v','quiet','-print_format','json',
'-show_streams','-show_format',sp],
capture_output=True,text=True)
if tc:
try: os.remove(tc)
except: pass
return json.loads(r.stdout) if r.returncode==0 else {}
def measure_lufs(path:str) -> float:
sp,tc=_safe(path)
r=subprocess.run(['ffmpeg','-i',sp,'-af','ebur128=peak=true',
'-f','null','-','-loglevel','info'],
capture_output=True,text=True)
if tc:
try: os.remove(tc)
except: pass
for line in r.stderr.split('\n'):
s=line.strip()
if s.startswith('I:') and 'LUFS' in s and 'LRA' not in s:
try: return float(s.split('I:')[1].strip().split()[0])
except: pass
return -99.0
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# SIGNAL METRICS
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def rms_db(a:'np.ndarray') -> float:
return float(20*np.log10(np.sqrt(np.mean(a**2))+1e-10))
def peak_db(a:'np.ndarray') -> float:
return float(20*np.log10(np.max(np.abs(a))+1e-10))
def crest_factor(a:'np.ndarray') -> float:
return float(peak_db(a)-rms_db(a))
def lra_estimate(a:'np.ndarray',sr:int=SR) -> float:
n=int(0.4*sr); step=n//2
lvls=np.array([20*np.log10(np.sqrt(np.mean(a[i:i+n]**2))+1e-10)
for i in range(0,len(a)-n,step)])
if len(lvls)<2: return 0.0
active=lvls[lvls>np.max(lvls)-30]
return float(np.percentile(active,95)-np.percentile(active,10)) if len(active)>=2 else 0.0
def snr_estimate(a:'np.ndarray',sr:int=SR) -> float:
n=int(0.1*sr)
blocks=np.array([np.sqrt(np.mean(a[i:i+n]**2)) for i in range(0,len(a)-n,n)])
if len(blocks)<4: return 30.0
return float(20*np.log10(np.percentile(blocks,85)/(np.percentile(blocks,3)+1e-10)))
def count_clips(a:'np.ndarray',thr:float=0.99) -> int:
return int(np.sum(np.abs(a)>=thr))
def declip(audio:'np.ndarray',thr:float=0.98) -> Tuple['np.ndarray',int]:
clipped=np.abs(audio)>=thr; nc=int(np.sum(clipped))
if nc==0: return audio,0
out=audio.copy(); n=len(audio)
diff=np.diff(clipped.astype(int))
starts=np.where(diff==1)[0]+1; ends=np.where(diff==-1)[0]+1
if clipped[0]: starts=np.insert(starts,0,0)
if clipped[-1]: ends=np.append(ends,n)
for s,e in zip(starts,ends):
ctx=40; pre=np.arange(max(0,s-ctx),s); post=np.arange(e,min(n,e+ctx))
good=np.concatenate([pre,post])
if len(good)<4: continue
try:
cs=CubicSpline(good,audio[good],extrapolate=True)
out[np.arange(s,e)]=cs(np.arange(s,e))
except: pass
return out,nc
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# SPECTRAL ANALYSIS
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def third_octave(audio:'np.ndarray',sr:int=SR,
chunk_sec:int=45,a_weighted:bool=False) -> Dict[float,float]:
chunk=audio[:sr*chunk_sec] if len(audio)>sr*chunk_sec else audio
N=len(chunk); spec=np.abs(rfft(chunk)); freqs=rfftfreq(N,1.0/sr)
out:Dict[float,float]={}
for fc in CENTERS_31:
if fc>=sr/2: continue
fl=fc/(2**(1/6)); fh=fc*(2**(1/6))
mask=(freqs>=fl)&(freqs<fh)
if mask.sum()>0:
v=float(20*np.log10(np.mean(spec[mask])+1e-10))
if a_weighted and fc in A_WEIGHT: v+=A_WEIGHT[fc]
out[fc]=v
return out
def hf_status(bands:Dict[float,float]) -> str:
hfk=[f for f in bands if f>=8000]
if not hfk: return 'absent'
avg=float(np.mean([bands[f] for f in hfk]))
return 'good' if avg>10 else 'weak' if avg>-5 else 'absent'
def detect_hf_rolloff(bands:Dict[float,float],drop:float=12.0) -> float:
fs=sorted([f for f in bands if 1600<=f<=20000])
if not fs: return 20000.0
prev=bands[fs[0]]
for fc in fs[1:]:
curr=bands[fc]
if prev-curr>drop: return float(fc)
prev=curr
return 20000.0
def spectral_tilt(bands:Dict[float,float],lo:float=100.0,hi:float=10000.0) -> float:
fc_arr=np.array([fc for fc in CENTERS_31 if lo<=fc<=hi and fc in bands],dtype=float)
if len(fc_arr)<3: return 0.0
return float(np.polyfit(np.log2(fc_arr/1000.0),
np.array([bands[fc] for fc in fc_arr]),1)[0])
def warmth_tilt(bands:Dict[float,float]) -> float:
return spectral_tilt(bands,200.0,2000.0)
def merge_eq(nodes:List[Tuple],gap:float=50.0) -> List[Tuple]:
if not nodes: return nodes
nodes=sorted(nodes,key=lambda x:x[0]); merged=[list(nodes[0])]
for f0,g,Q in nodes[1:]:
pf,pg,pq=merged[-1]
if abs(f0-pf)<gap:
total=float(np.clip(pg+g,-16,16))
avg_f=(pf*abs(pg)+f0*abs(g))/(abs(pg)+abs(g)+1e-6)
merged[-1]=[round(avg_f,0),round(total,2),round((pq+Q)/2,2)]
else: merged.append([f0,g,Q])
return [tuple(x) for x in merged]
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# STEP 1a โ SPECTRAL FLATNESS MEASURE (SFM)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def compute_sfm(audio:'np.ndarray',sr:int=SR,
f_lo:float=100.0,f_hi:float=8000.0) -> float:
"""Wiener entropy โ ู
ููุงุณ ูุธุงูุฉ ุงูุทูู | REF 1425H: 0.044"""
chunk=audio[:sr*30] if len(audio)>sr*30 else audio
N=len(chunk); spec=np.abs(rfft(chunk))**2; freqs=rfftfreq(N,1.0/sr)
mask=(freqs>=f_lo)&(freqs<=f_hi)
s=spec[mask]
if len(s)<10: return 0.1
eps=1e-10
geo=float(np.exp(np.mean(np.log(s+eps))))
arith=float(np.mean(s))
return float(np.clip(geo/(arith+eps),0.0,1.0))
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# STEP 1b โ DYNAMIC RANGE SCORE
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def compute_dynamic_range(audio:'np.ndarray',sr:int=SR) -> float:
"""ูุทุงู ุงูุฏููุงู
ูู ุงููุนูู (20ms frames) | REF: 7.9dB"""
n=int(0.020*sr)
frames=np.array([float(np.sqrt(np.mean(audio[i:i+n]**2)))
for i in range(0,len(audio)-n,n)])
if len(frames)<10: return 8.0
frames_db=20*np.log10(frames+1e-10)
return float(np.percentile(frames_db,95)-np.percentile(frames_db,5))
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# STEP 1c โ SPECTRAL SHAPE DISTANCE FROM REFERENCE
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def compute_spectral_distance(inp_b:Dict,ref_fp:ReferenceFingerprint,
hf_rolloff:float=20000.0) -> float:
"""ุงูู
ุณุงูุฉ ุงูุทูููุฉ ุงูุญููููุฉ ู
ู ุงูู
ุฑุฌุน ุจุนุฏ level normalization"""
ref_b=ref_fp.third_oct
ceil=min(10000.0,hf_rolloff*0.9)
common=[fc for fc in inp_b if fc in ref_b and 80<=fc<=ceil]
if len(common)<4: return 20.0
out_arr=np.array([inp_b[fc] for fc in common])
ref_arr=np.array([ref_b[fc] for fc in common])
loff=float(np.mean(ref_arr-out_arr))
shape_diffs=np.abs((ref_arr-out_arr)-loff)
aw=np.array([max(0.2,1+A_WEIGHT.get(fc,0)/10) for fc in common])
return float(np.sum(aw*shape_diffs)/np.sum(aw))
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# STEP 1d โ CODEC DAMAGE FINGERPRINT (Per-Band SNR)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def compute_band_snr(audio:'np.ndarray',sr:int=SR) -> Dict[float,float]:
"""SNR ููู Bark band โ ููุญุฏุฏ ุฃูู ุชุญุชุงุฌ NR"""
N=len(audio); spec=np.abs(rfft(audio))**2; freqs=rfftfreq(N,1.0/sr)
band_snr={}
for fc in [125,250,500,1000,2000,4000,8000]:
fl=fc*0.7; fh=fc*1.4
mask=(freqs>=fl)&(freqs<fh)
if mask.sum()<4: continue
s=spec[mask]
snr=float(10*np.log10(np.percentile(s,85)/(np.percentile(s,5)+1e-30)+1e-10))
band_snr[float(fc)]=snr
return band_snr
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# MULTI-METRIC DAMAGE SCORE (MDS)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# v8.5 โ TIER-ADJUSTED SCORING (TierAdjustedScoring)
# Per-tier MDS weights for compute_mds() and achievable target dicts
# for quality_score(). Replaces the ad-hoc 64K_FLOOR hack.
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# TIER_DAMAGED: HF is irrelevant (codec wiped it); SNR/SFM dominate.
# TIER_PRISTINE: balanced, as before v8.5.
_V85_MDS_WEIGHTS: Dict[str, Dict[str, float]] = {
'TIER_PRISTINE': {'snr': 0.25, 'sfm': 0.25, 'spec': 0.20,
'hf': 0.15, 'dr': 0.10, 'br': 0.05},
'TIER_COMPRESSED': {'snr': 0.30, 'sfm': 0.25, 'spec': 0.18,
'hf': 0.07, 'dr': 0.12, 'br': 0.08},
'TIER_DEGRADED': {'snr': 0.35, 'sfm': 0.28, 'spec': 0.15,
'hf': 0.02, 'dr': 0.12, 'br': 0.08},
'TIER_DAMAGED': {'snr': 0.40, 'sfm': 0.30, 'spec': 0.10,
'hf': 0.00, 'dr': 0.12, 'br': 0.08},
}
def _compute_achievable_targets(tier: str, input_cutoff_hz: float) -> Dict:
"""
Per-tier achievable target dict.
TIER_PRISTINE: full 1425H targets unchanged.
TIER_COMPRESSED: Crest ceiling 9.8LU, LRA 4.0LU (64kbps+ codec AGC).
TIER_DEGRADED: Crest linear from 7.5 to 9.0 LU based on measured
codec cutoff. LUFS -6.5 (noisy floor lifts noise).
TIER_DAMAGED: Crest 7.0LU, LRA 3.2LU, LUFS -7.0 (severe damage).
PHYSICS JUSTIFICATION (Crest ceiling):
A 64kbps MP3 codec applies AGC and quantization noise that floors
the noise floor by ~15dBFS relative to peaks. The measurable effect
is Crest depression: a source with Crest=12LU will emerge from 64kbps
encode at ~9.0-9.5LU. Scoring the output against a 10.25LU target
penalises the engine for a physical limit, not a processing error.
"""
if tier == 'TIER_PRISTINE':
return dict(TARGET)
if tier == 'TIER_COMPRESSED':
return {**TARGET, 'crest': 9.8, 'lra': 4.0}
if tier == 'TIER_DEGRADED':
# Linear: 7.5LU at cutoff=0Hz โ 9.0LU at cutoff=10500Hz
crest_ceil = float(np.clip(7.5 + (input_cutoff_hz / 10500.0) * 1.5, 7.5, 9.0))
return {**TARGET, 'crest': crest_ceil, 'lra': 3.6, 'lufs': -6.5}
# TIER_DAMAGED
return {**TARGET, 'crest': 7.0, 'lra': 3.2, 'lufs': -7.0}
def compute_mds(snr:float,sfm:float,dr:float,hf_deficit:float,
spectral_dist:float,src_br:int,
ref_sfm:float=TARGET['sfm'],
ref_dr:float=TARGET['dr'],
source_tier:str='TIER_PRISTINE') -> float:
"""
Multi-Metric Damage Score: 0=ู
ุซุงูู | 100=ุฃุณูุฃ ุญุงูุฉ
ุฃูุฒุงู: SNR 25% | SFM 25% | Spectral Distance 20% | HF 15% | DR 10% | BR 5%
"""
snr_score =float(np.clip((30.0-snr)/30.0,0,1))*100
sfm_ratio =sfm/(ref_sfm+1e-6)
sfm_score =float(np.clip((sfm_ratio-1.0)/5.0,0,1))*100
spec_score =float(np.clip(spectral_dist/15.0,0,1))*100
hf_score =float(np.clip(hf_deficit/30.0,0,1))*100
dr_excess =max(0.0,dr-ref_dr)
dr_score =float(np.clip(dr_excess/8.0,0,1))*100
br_score =float(np.clip((128000-src_br)/100000,0,1))*100
# v8.5: tier-specific weights โ TIER_DAMAGED weights SNR/SFM heavily, HF=0
w = _V85_MDS_WEIGHTS.get(source_tier, _V85_MDS_WEIGHTS['TIER_PRISTINE'])
mds = (snr_score * w['snr'] + sfm_score * w['sfm'] + spec_score * w['spec'] +
hf_score * w['hf'] + dr_score * w['dr'] + br_score * w['br'])
return float(np.clip(mds, 0, 100))
def mds_to_label(mds:float) -> str:
if mds>=75: return 'EXTREME'
if mds>=55: return 'VERY_POOR'
if mds>=35: return 'POOR'
if mds>=18: return 'FAIR'
return 'GOOD'
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# STEP 2a โ SFM-ADAPTIVE NR
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def build_nr_sfm(damage:DamageProfile) -> List[str]:
"""NR intensity = f(SFM ratio) โ ู
ุญุงููุธ ุนููู ู
ู v7.6"""
parts:List[str]=[]
if damage.src_br < 96000 and damage.band_snr.get(1000.0,20) < 8:
if damage.has_ringing and damage.rolloff_hz < 17000:
parts.append(f'lowpass=f={int(damage.rolloff_hz*0.97)}:poles=2')
return parts
sfm_ratio=damage.sfm/(TARGET['sfm']+1e-6)
if sfm_ratio >= 5.0:
parts.append('afftdn=nr=20:nf=-55:tn=1')
parts.append('afftdn=nr=6:nf=-65:tn=1')
elif sfm_ratio >= 3.0:
nr=int(np.interp(sfm_ratio,[3,5],[12,20]))
parts.append(f'afftdn=nr={nr}:nf=-58:tn=1')
elif sfm_ratio >= 2.0:
nr=int(np.interp(sfm_ratio,[2,3],[6,12]))
parts.append(f'afftdn=nr={nr}:nf=-62:tn=1')
elif sfm_ratio >= 1.5:
parts.append('afftdn=nr=4:nf=-68:tn=1')
if damage.has_ringing and damage.rolloff_hz < 17000:
parts.append(f'lowpass=f={int(damage.rolloff_hz*0.97)}:poles=2')
return parts
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# STEP 2b โ v8 BUG #4 FIX โ DR-CALIBRATED COMPAND (LRA delta ุตุญูุญ)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def build_compand_mds(damage:DamageProfile,
ref_fp:ReferenceFingerprint,
inp_lra:float) -> Tuple[str,float,str,float]:
"""
v8 FIX #4: compand selection ุจุงุณุชุฎุฏุงู
LRA ุงููุนูู ุจุฏู DR
v7.6 ูุงู: lra_delta = damage.dr - TARGET['dr'] โ ุฎุทุฃ ููุน!
v8: lra_delta = inp_lra - ref_fp.lra_clip โ ุตุญูุญ
"""
crest_delta = damage.crest - TARGET['crest']
# v8 FIX: LRA excess ุงูุญูููู ู
ูุงุฑูุฉ ุจุงูู clip reference
lra_delta = max(0.0, inp_lra - ref_fp.lra_clip)
# MDS contribution โ ู
ูููุต ู
ู 3.0 ุฅูู 2.0 ูุชุฌูุจ overweighting
mds_contrib = damage.mds / 100.0 * 2.0
score = crest_delta * 0.72 + lra_delta * 0.20 + mds_contrib
if score >= 11:
return ("-90/-68|-45/-20|-28/-9|-14/-4.5|-7/-2.0|-3/-0.6|0/-0.1",
2.5,'EXTREME',2.0)
elif score >= 6.5:
return ("-90/-72|-42/-21|-26/-10.5|-13/-5.2|-6/-2.4|-2.5/-0.8|-0.5/-0.3|0/-0.1",
3.2,'HEAVY',1.8)
elif score >= 3.5:
return ("-90/-78|-40/-25|-22/-12.5|-12/-6.8|-6/-3.5|-2.5/-1.6|-0.8/-0.5|0/-0.2",
2.5,'MEDIUM',1.4)
elif score >= 1.5:
return ("-90/-85|-40/-36|-20/-17|-10/-8.2|-5/-4.1|-2/-1.6|-0.5/-0.4|0/-0.3",
1.2,'LIGHT',0.9)
elif score >= 0.5:
return ("-90/-89|-40/-39|-20/-19.5|-10/-9.8|-4/-3.9|-1/-0.95|0/-0.3",
0.4,'MINIMAL',0.4)
else:
return ("-90/-90|-20/-20|-3/-3|0/0",0.0,'BYPASS',0.0)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# STEP 2c โ v8 BUG #1 FIX โ CORRECTED SPECTRAL BIAS
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def build_bias_filter(hf_rolloff:float=20000.0,
bias_cutoff_hz:float=20000.0) -> str:
"""
v8 FIX #1: SPECTRAL_BIAS_V8 ุจุงุชูุงููุฉ ุตุญูุญุฉ ู
ูุญุฏุฉ
ุงูุตูุบุฉ: g = -bias * BIAS_SCALE
bias ุณุงูุจ โ g ู
ูุฌุจ (boost) | bias ู
ูุฌุจ โ g ุณุงูุจ (cut)
v8.4: bias_cutoff_hz ุงุฒ SourceTierProfile (tier codec ceiling)
v8.45: ref_codec_cutoff_hz ู
ู DeepReferenceModel (ref file ceiling)
ููุง ููุนุฒุฒ ุชุฑุฏุฏุงู ูุง ูุญุชูู ุงูู
ุฑุฌุน ููุณู ุนูู ู
ุญุชูู ุญูููู ููู.
(FORENSIC: ุงูู 320kbps refs ุนูุฏูุง cutoff โ14kHz ูููุณ 20kHz)
"""
effective_boost_ceil = min(hf_rolloff * 0.9, bias_cutoff_hz)
parts=[]
for fc,bias_db in SPECTRAL_BIAS_V8.items():
g=round(-bias_db * BIAS_SCALE, 2)
if abs(g) < 0.20: continue
if g > 0 and fc > effective_boost_ceil: continue # v8.4: ูุง boost ููู ุณูู ุงูููุฏู
if fc > hf_rolloff * 0.9: continue # v8.2: ุญุฏ hf_rolloff ููู cut
Q=0.65 if abs(g)>1.5 else 0.90
parts.append(f'equalizer=f={fc}:width_type=q:width={Q}:g={g}')
return ','.join(parts)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# STEP 2d โ SPECTRAL DISTANCE EQ (Perceptual Optimizer)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def optimize_eq(new_b:Dict,ref_fp:ReferenceFingerprint,
n_nodes:int=12,max_db:float=6.0,
shape_only:bool=False,hf_rolloff:float=20000.0) -> List[Tuple]:
"""scipy optimizer โ ููุตุญุญ ุงูู
ุณุงูุฉ ุงูุทูููุฉ ุงูุญููููุฉ | ู
ุญุงููุธ ุนููู ู
ู v7.6"""
ref_b=ref_fp.third_oct
ceil=min(12000.0,hf_rolloff*0.92)
common=sorted([fc for fc in new_b if fc in ref_b and 63<=fc<=ceil])
if len(common)<4: return []
fc_arr=np.array(common,dtype=float)
new_arr=np.array([new_b[fc] for fc in common])
ref_arr=np.array([ref_b[fc] for fc in common])
loff=float(np.mean(ref_arr-new_arr))
target=(ref_arr-new_arr)-loff
if shape_only: target=target-float(np.mean(target))
def baw(fc:float) -> float:
bw=2.0 if 500<=fc<=4000 else 1.6 if 200<=fc<500 else 1.4 if 4000<fc<=8000 else 0.9
return bw*max(0.3,1+A_WEIGHT.get(fc,0)/10)
aw=np.array([baw(fc) for fc in common])
init_f=np.logspace(np.log10(63),np.log10(ceil),n_nodes)
def resp(fa,p):
r=np.zeros(len(fa))
for i in range(n_nodes):
f0=abs(p[i*3])+1e-6; g=p[i*3+1]; Q=max(0.3,abs(p[i*3+2]))
rat=fa/f0; r+=g/(1+Q**2*(rat-1.0/(rat+1e-9))**2)
return r
def obj(p):
e=np.mean(aw*(resp(fc_arr,p)-target)**2)
gs=[p[i*3+1] for i in range(n_nodes)]
sm=sum(0.012*(gs[i+1]-gs[i])**2 for i in range(len(gs)-1))
mg=sum(0.002*g**2 for g in gs)
return e+sm+mg
ig=np.interp(np.log10(init_f),np.log10(fc_arr),target)
x0=[]
for f,g in zip(init_f,ig):
x0.extend([float(np.clip(f,63,ceil)),float(np.clip(g,-max_db,max_db)),1.0])
res=minimize(obj,x0,method='L-BFGS-B',
bounds=[(63,ceil),(-max_db,max_db),(0.3,4.5)]*n_nodes,
options={'maxiter':500,'ftol':1e-10,'gtol':1e-9})
nodes=[]
for i in range(n_nodes):
f0=abs(res.x[i*3]); g=res.x[i*3+1]; Q=max(0.3,abs(res.x[i*3+2]))
if shape_only and g<0 and 400<=f0<=1600: g=max(g,-2.0)
if abs(g)>=0.35: nodes.append((round(f0,0),round(g,2),round(Q,2)))
return sorted(nodes,key=lambda x:x[0])
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# WARMTH CORRECTION (Crest-Aware โ ู
ุญุงููุธ ุนููู ู
ู v7.55/v7.6)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def build_warmth_nodes(inp_b:Dict,ref_fp:ReferenceFingerprint,
hf_rolloff:float=20000.0,post_compand:bool=False,
current_crest:float=99.0) -> List[Tuple]:
tfc=np.array([fc for fc in CENTERS_31 if 200<=fc<=2000
and fc in inp_b and fc<hf_rolloff],dtype=float)
if len(tfc)<3: return []
tdb=np.array([inp_b[fc] for fc in tfc])
new_tilt=float(np.polyfit(np.log2(tfc/1000.0),tdb,1)[0])
tilt_diff=ref_fp.warmth_ratio-new_tilt
threshold=1.5 if not post_compand else 2.5
if abs(tilt_diff)<threshold: return []
# ุญุงุฑุณ Crest (ู
ู v7.55 โ ู
ุญุงููุธ ุนููู)
if current_crest-TARGET['crest']<-1.0: return []
max_adj=min(3.0,2.0+(current_crest-TARGET['crest'])*0.5) if not post_compand else 1.2
scale=0.35 if not post_compand else 0.20
nodes=[]
adj=float(np.clip(tilt_diff*scale,-max_adj,max_adj))
if abs(adj)>=0.4: nodes.append((200.0,round(adj,2),0.55))
madj=float(np.clip(-tilt_diff*0.12,-1.5,1.5))
if abs(madj)>=0.3: nodes.append((1000.0,round(madj,2),0.80))
return nodes
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# SPECTRAL CORRECTION (Conservative โ ู
ุญุงููุธ ุนููู ู
ู v7.6)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def spectral_correction(out_b:Dict,ref_fp:ReferenceFingerprint,
hf_rolloff:float=20000.0,max_db:float=3.0,
pass_num:int=2,current_crest:float=99.0) -> List[Tuple]:
ref_b=ref_fp.third_oct
ceil=min(10000.0,hf_rolloff*0.9)
common=sorted([fc for fc in out_b if fc in ref_b and 80<=fc<=ceil])
if len(common)<4: return []
out_arr=np.array([out_b[fc] for fc in common])
ref_arr=np.array([ref_b[fc] for fc in common])
loff=float(np.mean(ref_arr-out_arr))
shape=(ref_arr-out_arr)-loff
avg_err=float(np.mean(np.abs(shape)))
base=0.58 if avg_err>4.0 else 0.48 if avg_err>2.0 else 0.35
pm={2:1.00,3:0.70,4:0.45}.get(pass_num,1.00)
scale=base*pm
aw=np.array([max(0.3,1+A_WEIGHT.get(fc,0)/10) for fc in common])
tfc=np.array([fc for fc in common if 200<=fc<=2000],dtype=float)
warmth_ok=False
if len(tfc)>=3:
tdb=np.array([out_b[fc] for fc in tfc])
out_tw=float(np.polyfit(np.log2(tfc/1000.0),tdb,1)[0])
warmth_ok=abs(out_tw-ref_fp.warmth_ratio)<3.0
crest_headroom=current_crest-TARGET['crest']
nodes:List[Tuple]=[]; prev_g=0.0
for i,fc in enumerate(common):
raw_g=float(shape[i])
g=float(np.clip(raw_g*aw[i]*scale,-max_db,max_db))
if warmth_ok and 400<=fc<=1600 and g<-0.3 and abs(raw_g)<4.0:
g=max(g*0.08,-0.20)
if crest_headroom<-1.5 and fc<=400 and g>0:
g=g*0.20
if abs(g)>=0.28 and abs(g-prev_g)<5.0:
Q=1.2 if abs(g)<2 else 0.85
nodes.append((float(fc),round(g,2),Q))
prev_g=g
return nodes
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# QUALITY SCORE โ v8.5 TIER-ADJUSTED SCORING
# score_tier: vs achievable targets for source tier (displayed to user)
# score_absolute: vs original 1425H targets always (honest reference)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def quality_score(out_b:Dict,ref_fp:ReferenceFingerprint,
metrics:Dict,hf_rolloff:float=20000.0,
source_tier:str='TIER_PRISTINE',
input_cutoff_hz:float=20000.0) -> Tuple[float,QualityReport]:
ref_b=ref_fp.third_oct
ceil=min(10000,int(hf_rolloff*0.85))
common=[fc for fc in out_b if fc in ref_b and 80<=fc<=ceil]
if common:
out_v=np.array([out_b[fc] for fc in common])
ref_v=np.array([ref_b[fc] for fc in common])
aw=np.array([max(0.2,1+A_WEIGHT.get(fc,0)/10) for fc in common])
loff=float(np.mean(ref_v-out_v))
diffs=np.abs((ref_v-out_v)-loff)
w_avg=float(np.sum(aw*diffs)/np.sum(aw))
spectral_s=max(0.0,100.0-w_avg*4.5)
else:
w_avg=99.0; spectral_s=0.0
lra_t = ref_fp.lra # 4.19 (ุตุญูุญ ู
ูุฐ v7.6)
tfc = np.array([fc for fc in CENTERS_31 if 200 <= fc <= 2000
and fc in out_b and fc < hf_rolloff], dtype=float)
out_tilt = (float(np.polyfit(np.log2(tfc / 1000.0),
np.array([out_b[fc] for fc in tfc]), 1)[0])
if len(tfc) >= 3 else 0.0)
warmth_s = max(0.0, 100.0 - abs(out_tilt - ref_fp.warmth_ratio) * 5.5)
hf_fcs = [fc for fc in [4000, 5000, 6300, 8000, 10000, 12500]
if fc < hf_rolloff and fc in out_b and fc in ref_b]
if len(hf_fcs) >= 3:
hf_o = np.array([out_b[fc] for fc in hf_fcs])
hf_r = np.array([ref_b[fc] for fc in hf_fcs])
hf_e = float(np.mean(np.abs((hf_r - hf_o) - float(np.mean(hf_r - hf_o)))))
hf_s = max(0.0, 100.0 - hf_e * 4)
else:
hf_s = 50.0
lufs_val = metrics.get('lufs', -20)
crest_val = metrics.get('crest', 15)
lra_val = metrics.get('lra', 8)
# โโ score_absolute: vs original 1425H targets โ never changes โโโโโโโโโโโโโโโโโ
lufs_s_a = max(0.0, 100.0 - abs(lufs_val - TARGET['lufs']) * 12)
crest_s_a = max(0.0, 100.0 - abs(crest_val - TARGET['crest']) * 8)
lra_s_a = max(0.0, 100.0 - abs(lra_val - lra_t) * 10)
score_absolute = round(
spectral_s * 0.38 + lufs_s_a * 0.20 + crest_s_a * 0.15 +
lra_s_a * 0.12 + warmth_s * 0.10 + hf_s * 0.05, 1)
# โโ score_tier: vs achievable targets for this source tier โโโโโโโโโโโโโโโโ
# v8.5 TierAdjustedScoring: replaces ad-hoc 64K_FLOOR hack.
# A 64kbps file that reaches its physical ceiling is not a processing failure.
at = _compute_achievable_targets(source_tier, input_cutoff_hz)
lufs_s_t = max(0.0, 100.0 - abs(lufs_val - at['lufs']) * 12)
crest_s_t = max(0.0, 100.0 - abs(crest_val - at['crest']) * 8)
lra_s_t = max(0.0, 100.0 - abs(lra_val - at['lra']) * 10)
score_tier = round(
spectral_s * 0.38 + lufs_s_t * 0.20 + crest_s_t * 0.15 +
lra_s_t * 0.12 + warmth_s * 0.10 + hf_s * 0.05, 1)
# โโ ceiling_reason โ logged when tier relaxes targets โโโโโโโโโโโโโโโโโโโโโโ
ceiling_reason = ''
if source_tier != 'TIER_PRISTINE':
ceiling_reason = (
f"{source_tier}: Crestโค{at['crest']:.2f}LU "
f"LRAโค{at['lra']:.2f}LU LUFSโฅ{at['lufs']:.2f} "
f"[cutoff={input_cutoff_hz:.0f}Hz]"
)
notes = []
if abs(lufs_val - TARGET['lufs']) > 0.6:
notes.append(f"LUFS:{lufs_val:.2f}โ{TARGET['lufs']}")
if abs(crest_val - at['crest']) > 1.2:
notes.append(f"Crest:{crest_val:.2f}โ{at['crest']:.2f}")
if abs(lra_val - at['lra']) > 1.0:
notes.append(f"LRA:{lra_val:.2f}โ{at['lra']:.2f}")
if w_avg > 2.5:
notes.append(f"Spectral:ยฑ{w_avg:.2f}dB")
rpt = QualityReport(
score = score_tier,
spectral = round(spectral_s, 1),
lufs = round(lufs_s_a, 1),
crest = round(crest_s_a, 1),
lra = round(lra_s_a, 1),
warmth = round(warmth_s, 1),
hf = round(hf_s, 1),
avg_err = round(w_avg, 2),
warmth_tilt = round(out_tilt, 2),
warmth_ref = round(ref_fp.warmth_ratio, 2),
lra_target = round(lra_t, 2),
notes = notes,
score_absolute = score_absolute,
score_tier = score_tier,
ceiling_reason = ceiling_reason,
)
return rpt.score, rpt
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 9-SEGMENT FULL-FILE SPECTRAL AVERAGE
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def analyze_full_spectrum(input_path:str,total_s:int) -> Dict[float,float]:
pcts=[0.10,0.20,0.30,0.40,0.50,0.60,0.70,0.80,0.90]
skips=[max(10,int(total_s*p)) for p in pcts]
clips=[os.path.join(_TMP, f'v81_seg{i}.wav') for i in range(len(skips))]
procs=[subprocess.Popen(['ffmpeg','-y','-i',input_path,
'-ss',str(sk),'-t','20','-f','s16le','-ac','1',
'-ar',str(SR),cl,'-loglevel','error'])
for sk,cl in zip(skips,clips)]
for p in procs: p.wait()
all_bands:List[Dict]=[]
for cl in clips:
try:
if not os.path.exists(cl) or os.path.getsize(cl)<SR*2: continue
a=np.frombuffer(open(cl,'rb').read(),np.int16).astype(np.float32)/32768.0
if len(a)<SR*3: continue
all_bands.append(third_octave(a,a_weighted=False))
except: pass
if not all_bands: return {}
result={}
for fc in CENTERS_31:
vals=[b.get(fc) for b in all_bands if b.get(fc) is not None]
if len(vals)>=2: result[fc]=float(np.median(vals))
return result
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# REFERENCE FINGERPRINT
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# v8.45 โ DEEP REFERENCE MODEL HELPERS
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _phrase_lra_dist(audio: 'np.ndarray', sr: int = SR,
min_phrase_s: float = 1.0) -> 'Tuple[float,float,float,int]':
"""
Phrase-level LRA distribution for dense Quran recitation.
Uses energy-dip detection (works for continuous recitation with short breath pauses).
Returns (p10, p50, p90, n_phrases). Bypass: returns (0,0,0,0) if audio too short.
"""
if len(audio) < sr * 10:
return 0.0, 0.0, 0.0, 0
frame = int(0.01 * sr)
hop = int(0.005 * sr)
# Short-time RMS energy in dBFS
energies = np.array([
rms_db(audio[i:i+frame])
for i in range(0, len(audio) - frame, hop)
], dtype=np.float32)
# 50ms smoothing
k = max(1, int(0.05 / 0.005))
smooth = np.convolve(energies, np.ones(k)/k, mode='same')
# Running max in 2s window
win2 = int(2.0 / 0.005)
run_max = np.array([
np.max(smooth[max(0, i-win2):i+win2])
for i in range(len(smooth))
])
# Dip = energy 3dB below local max
is_dip = smooth < (run_max - 3.0)
# Collect phrase boundaries
gap_frames = int(0.25 / 0.005)
min_frames = int(min_phrase_s / 0.005)
phrases: List['np.ndarray'] = []
in_ph = False; start = 0; gap = 0
for i, dip in enumerate(is_dip):
if not dip:
if not in_ph:
start = i
in_ph = True
gap = 0
else:
if in_ph:
gap += 1
if gap > gap_frames:
dur = i - gap - start
if dur > min_frames:
s_samp = start * hop
e_samp = (i - gap) * hop
if e_samp > s_samp + sr:
phrases.append(audio[s_samp:e_samp])
in_ph = False
gap = 0
if in_ph:
phrases.append(audio[start*hop:])
lras = [lra_estimate(ph) for ph in phrases if len(ph) > sr * 0.5]
if len(lras) < 3:
return 0.0, 0.0, 0.0, 0
return (round(float(np.percentile(lras, 10)), 2),
round(float(np.percentile(lras, 50)), 2),
round(float(np.percentile(lras, 90)), 2),
len(lras))
def _ref_silence_floor(audio: 'np.ndarray', sr: int = SR) -> float:
"""
Noise floor of the reference recording measured from silent frames.
Sets the NR ceiling: never push noise below (silence_floor_db - 3dB).
Returns dBFS float. Bypass: -70.0 if no silence frames found.
"""
frame = int(0.025 * sr)
hop = int(0.010 * sr)
overall_rms = rms_db(audio)
threshold = overall_rms - 20.0 # 20dB below voiced level
floors = [
rms_db(audio[i:i+frame])
for i in range(0, len(audio) - frame, hop)
if rms_db(audio[i:i+frame]) < threshold
]
if len(floors) < 20:
return -70.0
# Use p50 of silence frames (robust against burst noise)
return float(np.percentile(floors, 50))
def _ref_codec_cutoff(audio: 'np.ndarray', sr: int = SR) -> float:
"""
Detects the highest frequency with genuine content in the reference file.
Used to prevent BIAS boosts targeting frequencies the ref itself doesn't contain.
Returns Hz float.
"""
n_fft = min(131072, len(audio))
if n_fft < sr:
return 14000.0
wins = []
for i in range(0, len(audio) - n_fft, n_fft * 2):
seg = audio[i:i+n_fft].astype(np.float64)
wins.append(np.abs(rfft(seg * np.hanning(n_fft)))**2)
if not wins:
return 14000.0
X = np.mean(wins, axis=0)
freqs = rfftfreq(n_fft, 1.0/sr)
# Reference level: RMS energy at 1-2kHz
mask_1k = (freqs >= 1000) & (freqs < 2000)
if not mask_1k.any():
return 14000.0
ref_db = 10 * np.log10(np.mean(X[mask_1k]) + 1e-30)
# Scan down from 20kHz; first band where energy is within 45dB of 1kHz ref = cutoff
for fc in [20000, 18000, 17000, 16000, 15000, 14000, 13000, 12000, 11000, 10000, 8000]:
lo, hi = fc - 500, min(fc + 500, sr // 2 - 1)
mask = (freqs >= lo) & (freqs < hi)
if not mask.any():
continue
band_db = 10 * np.log10(np.mean(X[mask]) + 1e-30)
if band_db > ref_db - 45.0:
return float(fc)
return 8000.0
def _full_file_third_oct_avg(audio: 'np.ndarray', sr: int = SR,
window_s: float = 10.0, hop_s: float = 60.0) -> Dict[float, float]:
"""
Full-file spectral average using windowed sampling (every hop_s seconds).
Replaces the 8 fixed-position 30s clip approach.
FORENSIC JUSTIFICATION: actual measurements showed 40s-clip spectral values
differed from full-file averages by up to +16dB at 2kHz on Al-Araaf, and
+12dB at 8kHz on Al-Fatir. The clip was capturing atypical opening material,
not the Sheikh's settled recitation.
"""
win = int(window_s * sr)
hop = int(hop_s * sr)
overall_rms = rms_db(audio)
silence_thr = overall_rms - 25.0 # skip near-silence windows
spectra: List[Dict[float, float]] = []
for start in range(0, len(audio) - win, hop):
seg = audio[start:start+win]
if rms_db(seg) > silence_thr:
spectra.append(third_octave(seg.astype(np.float32)))
if not spectra:
return third_octave(audio[:win].astype(np.float32))
avg: Dict[float, float] = {}
for fc in spectra[0]:
vals = [s[fc] for s in spectra if fc in s]
if vals:
avg[fc] = float(np.mean(vals))
return avg
def _peak_distribution_type(audio: 'np.ndarray', sr: int = SR) -> str:
"""
Classifies whether energy peaks occur at phrase attacks (front_loaded),
uniformly throughout phrases, or at the end (back_loaded).
Used to shape compand attack time in Pass 3.
"""
frame = int(0.02 * sr)
hop = int(0.01 * sr)
energies = np.array([
rms_db(audio[i:i+frame])
for i in range(0, len(audio) - frame, hop)
], dtype=np.float32)
threshold = float(np.percentile(energies[energies > -60], 30)) - 3 if np.any(energies > -60) else -40.0
is_voiced = energies > threshold
gap_frames = int(0.3 / 0.01)
min_frames = int(0.8 / 0.01)
ratios: List[float] = []
in_ph = False; start = 0; gap = 0
for i, v in enumerate(is_voiced):
if v:
if not in_ph:
start = i
in_ph = True
gap = 0
else:
if in_ph:
gap += 1
if gap > gap_frames:
dur = i - gap - start
if dur > min_frames:
ph = energies[start:i - gap]
attack = ph[:max(1, int(len(ph) * 0.12))]
if len(attack) and len(ph) > len(attack):
ratios.append(float(np.max(attack)) - float(np.max(ph[len(attack):])))
in_ph = False
gap = 0
if len(ratios) < 3:
return 'uniform'
mean_r = float(np.mean(ratios))
if mean_r > 1.0:
return 'front_loaded'
elif mean_r > -1.5:
return 'uniform'
else:
return 'back_loaded'
def get_reference_fingerprint() -> ReferenceFingerprint:
# v8.1 PATCH #2: REF_FILES may be empty โ guard primary access
primary = REF_FILES[0] if REF_FILES else ''
# v8.1 PATCH #1: REF_CACHE is now in Path.home()/.tilawa_cache/
if os.path.exists(REF_CACHE):
try:
mref=os.path.getmtime(primary) if os.path.exists(primary) else 0
if os.path.getmtime(REF_CACHE)>=mref:
with open(REF_CACHE,'r',encoding='utf-8') as f: d=json.load(f)
if d.get('version') in ('v8.1', 'v8.45'):
fp = ReferenceFingerprint()
fp.third_oct = {float(k):v for k,v in d['third_oct'].items()}
fp.a_weighted = {float(k):v for k,v in d.get('a_weighted',{}).items()}
fp.rms = d['rms']; fp.peak = d['peak']
fp.crest = d['crest']
fp.lra = d.get('lra', TARGET['lra'])
fp.lra_clip = d.get('lra_clip', 2.94)
fp.tilt_slope = d['tilt_slope']
fp.warmth_ratio = d['warmth_ratio']
fp.sfm = d.get('sfm', TARGET['sfm'])
fp.dr = d.get('dr', TARGET['dr'])
fp.n_files = d.get('n_files', 1)
# v8.45 deep fields (graceful fallback if cache is v8.1)
fp.phrase_lra_p10 = d.get('phrase_lra_p10', 2.50)
fp.phrase_lra_p50 = d.get('phrase_lra_p50', 3.37)
fp.phrase_lra_p90 = d.get('phrase_lra_p90', 4.20)
fp.silence_floor_db = d.get('silence_floor_db', -73.0)
fp.ref_codec_cutoff_hz = d.get('ref_codec_cutoff_hz', 14000.0)
fp.peak_distribution = d.get('peak_distribution', 'uniform')
return fp
except: pass
# โโ v8.45: full-file windowed analysis replaces 8ร30s fixed clips โโโโโโโโโโ
# FORENSIC: 40s clip differed from full-file by up to +16dB at 2kHz (Al-Araaf),
# +12dB at 8kHz (Al-Fatir). The clips were capturing atypical opening material.
all_fp:List[Dict]=[]
for idx, path in enumerate(REF_FILES):
if not os.path.exists(path):
continue
try:
# Load the full reference file as float32 mono at SR
tmp_full = os.path.join(_TMP, f'v845_ref_full_{idx}.wav')
subprocess.run(
['ffmpeg', '-y', '-i', path,
'-ac', '1', '-ar', str(SR), tmp_full, '-loglevel', 'error'],
capture_output=True)
if not os.path.exists(tmp_full) or os.path.getsize(tmp_full) < SR * 4:
continue
full_a = np.frombuffer(open(tmp_full,'rb').read()[44:],
np.int16).astype(np.float32) / 32768.0
if len(full_a) < SR * 10:
continue
# Full-file spectral average (v8.45 core improvement)
spec_full = _full_file_third_oct_avg(full_a, SR)
# Basic metrics from the full file
all_fp.append({
'spec': spec_full,
'rms': float(rms_db(full_a)),
'crest': float(crest_factor(full_a)),
'lra_full': float(lra_estimate(full_a)),
'lra_clip': float(lra_estimate(full_a[:SR*30])), # first 30s for compand compat
'sfm': float(compute_sfm(full_a)),
'dr': float(compute_dynamic_range(full_a)),
# v8.45 deep fields
'phrase_lra': _phrase_lra_dist(full_a, SR),
'silence_floor': _ref_silence_floor(full_a, SR),
'codec_cutoff': _ref_codec_cutoff(full_a, SR),
'peak_dist': _peak_distribution_type(full_a, SR),
})
try: os.unlink(tmp_full)
except: pass
except Exception:
continue
if len(all_fp) < 2:
fp = _build_single_ref(primary) if os.path.exists(primary) else ReferenceFingerprint()
fp.n_files = len(all_fp) or 1
return fp
# โโ Multi-ref averaging โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
ref_lvl = float(np.mean([f['rms'] for f in all_fp]))
common_all = [fc for fc in CENTERS_31 if all(fc in f['spec'] for f in all_fp)]
normed = [{fc: f['spec'][fc] + (ref_lvl - f['rms']) for fc in common_all}
for f in all_fp]
multi = {fc: float(np.median([s[fc] for s in normed])) for fc in common_all}
fp = ReferenceFingerprint()
fp.third_oct = multi
fp.rms = float(np.median([f['rms'] for f in all_fp]))
fp.peak = TARGET['true_peak']
fp.crest = float(np.median([f['crest'] for f in all_fp]))
fp.lra_clip = float(np.median([f['lra_clip'] for f in all_fp]))
fp.lra = float(np.median([f['lra_full'] for f in all_fp])) # v8.45: real full-file LRA
fp.sfm = float(np.median([f['sfm'] for f in all_fp]))
fp.dr = float(np.median([f['dr'] for f in all_fp]))
fp.n_files = len(all_fp)
fp.tilt_slope = spectral_tilt(fp.third_oct)
fp.warmth_ratio = warmth_tilt(fp.third_oct)
# โโ v8.45 deep reference fields โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# phrase LRA: p50 is the Pass 3 compand target
all_p50 = [f['phrase_lra'][1] for f in all_fp if f['phrase_lra'][2] > 0]
all_p10 = [f['phrase_lra'][0] for f in all_fp if f['phrase_lra'][2] > 0]
all_p90 = [f['phrase_lra'][2] for f in all_fp if f['phrase_lra'][2] > 0]
if all_p50:
fp.phrase_lra_p50 = float(np.median(all_p50))
fp.phrase_lra_p10 = float(np.median(all_p10))
fp.phrase_lra_p90 = float(np.median(all_p90))
# silence floor: use the highest (least quiet) floor across refs as the
# safe NR ceiling โ conservative choice prevents over-denoising
floors = [f['silence_floor'] for f in all_fp if f['silence_floor'] < -20]
fp.silence_floor_db = float(max(floors)) if floors else -70.0
# codec cutoff: use minimum across refs โ don't target HF that some refs lack
cutoffs = [f['codec_cutoff'] for f in all_fp]
fp.ref_codec_cutoff_hz = float(min(cutoffs))
# peak distribution: majority vote
from collections import Counter
peak_votes = Counter(f['peak_dist'] for f in all_fp)
fp.peak_distribution = peak_votes.most_common(1)[0][0]
# Warn if any ref has suspect cutoff (may have been re-encoded from low bitrate)
for i, f in enumerate(all_fp):
if f['codec_cutoff'] < 12000:
print(f" [v8.45] โ REF_WARN: ref[{i}] codec_cutoff={f['codec_cutoff']:.0f}Hz "
f"-- may be re-encoded from low bitrate")
try:
p_info = probe(primary)
ts = int(float(p_info.get('format', {}).get('duration', 300)))
pa = load_audio(primary, skip=int(ts * 0.35), duration=60)
fp.a_weighted = third_octave(pa, a_weighted=True)
except:
pass
# โโ Cache write: v8.45 format โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
try:
Path(REF_CACHE).parent.mkdir(parents=True, exist_ok=True)
d = {
'version': 'v8.45',
'third_oct': {str(k): v for k, v in fp.third_oct.items()},
'a_weighted': {str(k): v for k, v in fp.a_weighted.items()},
'rms': fp.rms,
'peak': fp.peak,
'crest': fp.crest,
'lra': fp.lra,
'lra_clip': fp.lra_clip,
'tilt_slope': fp.tilt_slope,
'warmth_ratio': fp.warmth_ratio,
'sfm': fp.sfm,
'dr': fp.dr,
'n_files': fp.n_files,
# v8.45 deep fields
'phrase_lra_p10': fp.phrase_lra_p10,
'phrase_lra_p50': fp.phrase_lra_p50,
'phrase_lra_p90': fp.phrase_lra_p90,
'silence_floor_db': fp.silence_floor_db,
'ref_codec_cutoff_hz': fp.ref_codec_cutoff_hz,
'peak_distribution': fp.peak_distribution,
}
with open(REF_CACHE, 'w', encoding='utf-8') as f:
json.dump(d, f, ensure_ascii=False, indent=2)
except Exception:
pass
return fp
def _build_single_ref(path:str) -> ReferenceFingerprint:
p_info=probe(path); total_s=int(float(p_info.get('format',{}).get('duration',300)))
skips=[max(10,int(total_s*r)) for r in [0.12,0.28,0.44,0.60,0.78]]
clips=[os.path.join(_TMP, f'v81_ref_s{i}.wav') for i in range(len(skips))]
procs=[subprocess.Popen(['ffmpeg','-y','-i',path,'-ss',str(sk),'-t','40',
'-f','s16le','-ac','1','-ar',str(SR),cl,'-loglevel','error'])
for sk,cl in zip(skips,clips)]
for p in procs: p.wait()
segs=[]
for cl in clips:
try:
a=np.frombuffer(open(cl,'rb').read(),np.int16).astype(np.float32)/32768.0
if len(a)>SR: segs.append(a)
except: pass
ref=np.concatenate(segs) if segs else load_audio(path,skip=30,duration=120)
chunk_n=SR*20; all_b=[]; crests=[]; lras=[]; sfms=[]; drs=[]
for ci in range(max(1,len(ref)//chunk_n)):
seg=ref[ci*chunk_n:(ci+1)*chunk_n]
if len(seg)<SR*3: continue
all_b.append(third_octave(seg)); crests.append(crest_factor(seg))
lras.append(lra_estimate(seg)); sfms.append(compute_sfm(seg))
drs.append(compute_dynamic_range(seg))
if not all_b: all_b=[third_octave(ref)]
fp=ReferenceFingerprint()
for fc in CENTERS_31:
vals=[b.get(fc) for b in all_b if b.get(fc) is not None]
if vals: fp.third_oct[fc]=float(np.median(vals))
fp.rms=rms_db(ref); fp.peak=peak_db(ref)
fp.crest =float(np.median(crests)) if crests else crest_factor(ref)
fp.lra_clip=float(np.median(lras)) if lras else lra_estimate(ref)
fp.lra =TARGET['lra']
fp.sfm =float(np.median(sfms)) if sfms else TARGET['sfm']
fp.dr =float(np.median(drs)) if drs else TARGET['dr']
fp.tilt_slope=spectral_tilt(fp.third_oct)
fp.warmth_ratio=warmth_tilt(fp.third_oct)
fp.n_files=1; return fp
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# LUFS SAMPLING
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def sample_lufs_7pt(input_path:str,total_s:int,n_ch:str,filter_str:str) -> float:
pts=[max(10,int(total_s*p)) for p in [0.08,0.18,0.32,0.50,0.65,0.78,0.90]]
for i in range(1,len(pts)):
if pts[i]-pts[i-1]<30: pts[i]=pts[i-1]+30
clips=[os.path.join(_TMP, f'v81_lc{i}.wav') for i in range(len(pts))]
procs=[subprocess.Popen(['ffmpeg','-y','-i',input_path,
'-ss',str(sk),'-t','22','-ar','48000','-ac',n_ch,
cl,'-loglevel','error']) for sk,cl in zip(pts,clips)]
for p in procs: p.wait()
lp=[subprocess.Popen(['ffmpeg','-y','-i',cl,'-af',
filter_str+',ebur128=peak=true','-f','null','-','-loglevel','info'],
stderr=subprocess.PIPE,stdout=subprocess.PIPE) for cl in clips]
vals:List[float]=[]
for p in lp:
_,err=p.communicate()
for line in err.decode().split('\n'):
s=line.strip()
if s.startswith('I:') and 'LUFS' in s and 'LRA' not in s:
try: vals.append(float(s.split('I:')[1].strip().split()[0])); break
except: pass
if not vals: return -12.0
gw=[0.05,0.12,0.20,0.26,0.20,0.12,0.05][:len(vals)]
gw=[w/sum(gw) for w in gw]
return float(np.average(vals,weights=gw))
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# FILTER CHAIN BUILDER โ v8 BUG #2 + #3 FIX
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def build_filter_chain(eq_nodes:List[Tuple],compand_pts:str,makeup:float,
hf:str,is_mono:bool,gain_db:float,
nr_parts:List[str],bias_filter:str,
warmth_pre:List[Tuple],intensity:str,
inp_lra:float,damage:DamageProfile,
hf_rolloff:float,src_sr:int,
ref_lra_clip:float,tilt_slope:float,
correction_nodes:List[Tuple]=None,
post_warmth:List[Tuple]=None) -> str:
"""
v8 FIX #2: ุญุฐู LRA compand ู
ู ุงูู chain โ compand ุฑุฆูุณู ูุงุญุฏ ููุท
v8 FIX #3: alimiter ูุงุญุฏ ูุงุนู
(0.9997) ูู WAV ุงููุณูุทุฉ ุจุฏู 0.891
"""
if correction_nodes is None: correction_nodes=[]
if post_warmth is None: post_warmth=[]
parts:List[str]=[]; is_bypass=(intensity=='BYPASS')
is_extreme=(damage.quality_label=='EXTREME')
# 1. DC blocking
parts.append('highpass=f=28:poles=2')
# 2. NR
parts.extend(nr_parts)
# 3. Tilt correction
if not is_bypass and abs(tilt_slope)>1.0:
db=min(abs(tilt_slope)*0.35,5.0)
if tilt_slope>0: parts.append(f'treble=g={db:.1f}:f=8000:width_type=o:width=2')
else: parts.append(f'bass=g={db:.1f}:f=150:width_type=o:width=2')
# 4. Perceptual EQ (scipy Bark + A-weight)
for f0,g,Q in eq_nodes:
parts.append(f'equalizer=f={f0:.0f}:width_type=q:width={Q}:g={g}')
# 5. Warmth pre-compand (Crest-aware)
for f0,g,Q in warmth_pre:
parts.append(f'equalizer=f={f0:.0f}:width_type=q:width={Q}:g={g}')
# 6. HF reconstruction
if not is_bypass:
if is_extreme:
parts.append('crystalizer=i=7')
if hf_rolloff<8000:
parts.append(f'treble=g=3.5:f={max(2000,int(hf_rolloff*0.65))}:width_type=o:width=2')
parts.append('treble=g=3.0:f=7000:width_type=o:width=1.5')
elif damage.quality_label=='VERY_POOR':
parts.append('crystalizer=i=6')
parts.append('treble=g=2.0:f=6000:width_type=o:width=2')
elif damage.quality_label in ('POOR','GOOD','FAIR'):
if hf=='weak': parts.append('crystalizer=i=4')
elif hf=='absent': parts.append('crystalizer=i=6')
# 7. Post-NR
if not is_bypass and nr_parts:
if is_extreme: parts.append('afftdn=nr=4:nf=-80:tn=0')
elif damage.quality_label in ('POOR','VERY_POOR'):
parts.append('afftdn=nr=6:nf=-74:tn=0')
elif damage.snr<40:
nr=max(3,min(10,int((40.0-damage.snr)*0.4)))
parts.append(f'afftdn=nr={nr}:nf=-74:tn=1')
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# v8 FIX #2: LRA CONTROL โ agate ููู LRA ุงูู
ูุฎูุถ ููุท
#
# v7.6 ูุงู ูุถูู compand ุซุงูู ุนูุฏู
ุง inp_lra > ref_lra_clip
# ูุฐุง ูุงู ูุณุจุจ double compression โ Crest collapse
#
# v8: ูุญุฐู LRA compand ุชู
ุงู
ุงู
# - Low LRA (lra_deficit > 0.5): agate ูุชูุณูุน ุงูุฏููุงู
ูู ููุท
# - High LRA (lra_deficit < -0.4): ูุชุฑููุง ููู compand ุงูุฑุฆูุณู
# ุงูุฑุนุงูุฉ ุงูู
ุชุจููุฉ ุชุชู
ูู Pass 3 feedback
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
lra_deficit=ref_lra_clip-inp_lra
if not is_bypass and lra_deficit>0.5:
# LRA ู
ูุฎูุถ ุฌุฏุงู โ agate ูุชูุณูุน ุงููุทุงู ุงูุฏููุงู
ููู
ratio=min(4.0 if is_extreme else 3.5,
1.0+lra_deficit*(0.40 if is_extreme else 0.28))
thr=max(0.010,min(0.045,0.022+lra_deficit*0.004))
rel=1200 if is_extreme else 800
parts.append(f'agate=threshold={thr:.3f}:ratio={ratio:.2f}'
f':attack=20:release={rel}:makeup=1.0:range=0.06')
# v8 FIX: ูุง ููุฌุฏ elif lra_deficit<-0.4 ููุง!
# LRA ู
ุฑุชูุน โ Main compand ูุนุงูุฌู | Pass 3 ูุนุงูุฌ ุงูุจุงูู
# 8. Single clean compand (v7.0 proven architecture)
if not is_bypass:
atk={'MINIMAL':0.050,'LIGHT':0.030,'MEDIUM':0.015,'HEAVY':0.008,'EXTREME':0.020}
dcy={'MINIMAL':3.0, 'LIGHT':2.0, 'MEDIUM':1.0, 'HEAVY':0.5, 'EXTREME':0.40}
parts.append(f'compand=attacks={atk.get(intensity,0.015)}'
f':decays={dcy.get(intensity,1.0)}'
f':points={compand_pts}:gain={makeup}')
# 9. Post-compand warmth (Crest-aware)
for f0,g,Q in post_warmth:
parts.append(f'equalizer=f={f0:.0f}:width_type=q:width={Q}:g={g}')
# 10. Spectral bias (v8 corrected)
if not is_bypass and bias_filter:
parts.append(bias_filter)
# 11. Correction nodes
for f0,g,Q in correction_nodes:
parts.append(f'equalizer=f={f0:.0f}:width_type=q:width={Q}:g={g}')
# v8 FIX #3: ุญุฐู alimiter ุงููุณูุท (0.978/0.982) ู
ู ููุง!
# v7.6 ูุงู ูุถูู: alimiter=limit=0.978:attack=5:release=40 ููุง
# ูุฐุง ูุงู ูุณุญู Crest ูุจู ุฃู ูุตู ููู alimiter ุงูุฑุฆูุณู
# 12. Volume
if abs(gain_db)>0.05: parts.append(f'volume={gain_db:.3f}dB')
# 13. Stereo
if is_mono: parts.append('aformat=channel_layouts=stereo')
# v8 FIX #3: alimiter ูุงุนู
ุฌุฏุงู ููู WAV ุงููุณูุทุฉ (ูุญู
ู ู
ู overflow ููุท)
# True Peak ุงูุญูููู (0.891) ููุทุจููู ูู Pass 4 ููุท
if is_bypass:
parts.append('alimiter=limit=0.999:level=false:attack=5:release=15')
else:
parts.append('alimiter=limit=0.9997:level=false:attack=10:release=100')
return ','.join(f'\n {p}' for p in parts)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# MAIN ENHANCE โ v8.1
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def enhance(input_path:str,output_path:str,
max_iterations:int=3,target_score:float=96.0) -> Dict:
log:List[str]=[]; t0=time.time()
def L(m:str='') -> None: print(m); log.append(m)
_input_tmp=None
try: input_path.encode('ascii')
except UnicodeEncodeError:
import uuid as _u2; ext=os.path.splitext(input_path)[1] or '.mp3'
_input_tmp=os.path.join(_TMP, f'v81_in_{_u2.uuid4().hex[:8]}{ext}')
shutil.copy2(input_path,_input_tmp); input_path=_input_tmp
L(f"โ{'โ'*70}โ")
L(f"โ Audio Enhancement Engine v8.4 โ \"Source Tier Intelligence\" โ")
L(f"โ ุงูู
ุฑุฌุน: ุงูุดูุฎ ูุงุณุฑ ุงูุฏูุณุฑู โ 1425H โ")
L(f"โ v8.2: BIAS_SIGN โ | NO_STACKING โ | SINGLE_LIMITER โ | --ref โ โ")
L(f"โ v8.4: SourceTierDetector โ | bias_cutoff โ | eq_ramp_scale โ โ")
L(f"โ{'โ'*70}โ")
L(f" ุงูู
ูู: {os.path.basename(input_path)}")
# โโ Reference โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
L(f"\n[ูก] ุจุตู
ุฉ ุงูู
ุฑุฌุน v8.1 (MDS: SFM + DR + Spectral Distance)...")
ref_fp=get_reference_fingerprint()
L(f" โ {ref_fp.n_files} ุณูุฑุฉ | RMS={ref_fp.rms:.2f} Crest={ref_fp.crest:.2f}"
f" LRA={ref_fp.lra:.2f}(full)/{ref_fp.lra_clip:.2f}(clip)")
L(f" โ SFM={ref_fp.sfm:.4f} DR={ref_fp.dr:.1f}dB"
f" Warmth={ref_fp.warmth_ratio:.2f} Tilt={ref_fp.tilt_slope:.2f}")
# โโ File Analysis โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
L(f"\n[ูข] ุชุญููู ุดุงู
ู (MDS: 4 ู
ูุงููุณ)...")
pr=probe(input_path)
stream=pr.get('streams',[{}])[0]
is_mono=stream.get('channels',2)==1
src_sr=int(stream.get('sample_rate',44100))
src_br=int(stream.get('bit_rate',128000))
total_s=int(float(pr.get('format',{}).get('duration',300)))
n_ch='1' if is_mono else '2'; skip_s=min(30,total_s//4)
full_b=analyze_full_spectrum(input_path,total_s)
inp=load_audio(input_path,skip=skip_s,duration=45)
inp_b=full_b if full_b else third_octave(inp,a_weighted=False)
inp_rms=rms_db(inp); inp_crest=crest_factor(inp)
inp_lra=lra_estimate(inp); inp_hf=hf_status(inp_b)
hf_freqs=[fc for fc in inp_b if fc>=8000]
hf_avg=float(np.mean([inp_b[fc] for fc in hf_freqs])) if hf_freqs else -80.0
ref_hf=float(np.mean([ref_fp.third_oct.get(fc,-60) for fc in hf_freqs])) if hf_freqs else -40.0
hf_deficit=ref_hf-hf_avg
hf_rolloff=max(detect_hf_rolloff(inp_b,12.0),2000.0)
# Step 1a: SFM
inp_sfm=compute_sfm(inp)
sfm_ratio=inp_sfm/(ref_fp.sfm+1e-6)
L(f" Step 1a โ SFM={inp_sfm:.4f} (ref={ref_fp.sfm:.4f}, ratio={sfm_ratio:.1f}x)")
# Step 1b: DR
inp_dr=compute_dynamic_range(inp)
L(f" Step 1b โ DR={inp_dr:.1f}dB (ref={ref_fp.dr:.1f}dB, excess={inp_dr-ref_fp.dr:+.1f})")
# Step 1c: Spectral distance
spec_dist=compute_spectral_distance(inp_b,ref_fp,hf_rolloff)
L(f" Step 1c โ Spectral distance=ยฑ{spec_dist:.2f}dB from 1425H")
# Step 1d: Per-band SNR
band_snr=compute_band_snr(inp)
snr_global=float(np.mean(list(band_snr.values()))) if band_snr else 30.0
# MDS
mds=compute_mds(snr_global,inp_sfm,inp_dr,hf_deficit,spec_dist,src_br,
ref_fp.sfm,ref_fp.dr)
quality_label=mds_to_label(mds)
has_ringing=(src_br<65000)
br_rolloff=15500.0 if src_br<65000 else 16500.0 if src_br<97000 else hf_rolloff
damage=DamageProfile(
snr=snr_global,sfm=inp_sfm,dr=inp_dr,hf_deficit=hf_deficit,
spectral_dist=spec_dist,crest=inp_crest,src_br=src_br,
band_snr=band_snr,mds=mds,has_ringing=has_ringing,
rolloff_hz=br_rolloff,quality_label=quality_label
)
L(f"\n MDS={mds:.1f}/100 โ {quality_label}")
L(f" Crest={inp_crest:.2f} LRA={inp_lra:.2f} BR={src_br//1000}kbps"
f" Ringing={'โ' if has_ringing else 'โ'}")
# โโ v8.4: Source Tier Detection โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
L(f"\n[ูขแต] ุชุตููู ุฌูุฏุฉ ุงูู
ุตุฏุฑ v8.4 (SourceTierDetector)...")
tier_profile = build_source_tier_profile(
audio = inp,
inp_b = inp_b,
src_br = src_br,
snr_db = snr_global,
inp_lra = inp_lra,
ref_lra_clip = ref_fp.lra_clip,
sr = SR,
)
L(f" โฆ Tier = {tier_profile.tier}")
L(f" โฆ cutoff = {tier_profile.input_cutoff_hz:.0f}Hz"
f" noise={tier_profile.noise_type}"
f" clip={tier_profile.clip_tier}({tier_profile.clip_ratio*100:.1f}%)")
L(f" โฆ Routing : biasโค{tier_profile.bias_cutoff_hz:.0f}Hz"
f" eq_scale={tier_profile.eq_ramp_scale:.2f}x"
f" NR={'ุฅูุฒุงู
ู' if tier_profile.nr_mandatory else 'ุงุฎุชูุงุฑู'}"
f" LRA_expand={'โ' if tier_profile.lra_expand_gate else 'โ (AGC collapse)'}")
L(f" โฆ Ceiling : Crestโค{tier_profile.achievable_crest:.2f}"
f" LRAโค{tier_profile.achievable_lra:.2f}"
f" LUFSโฅ{tier_profile.achievable_lufs:.2f}")
# โโ STEP 2: MDS-Driven Processing โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
L(f"\n[ูฃ] Step 2a โ SFM-Adaptive NR...")
# v8.4: tier_profile.nr_mandatory ููุฌุจุฑ NR ุจุบุถ ุงููุธุฑ ุนู SFM
# v8.5: recompute MDS with tier-specific weights now that tier is known.
# TIER_DAMAGED weights SNR/SFM heavily (40%/30%), ignores HF (0%).
# This raises MDS for truly damaged sources -> heavier compand (correct).
mds = compute_mds(snr_global, inp_sfm, inp_dr, hf_deficit, spec_dist, src_br,
ref_fp.sfm, ref_fp.dr, source_tier=tier_profile.tier)
quality_label = mds_to_label(mds)
damage.mds = mds
damage.quality_label = quality_label
L(f" [v8.5] MDS (tier-adjusted) = {mds:.1f}/100 -> {quality_label}"
f" [{tier_profile.tier} weights]")
use_nr = tier_profile.nr_mandatory or ((src_br >= 96000) and (snr_global >= 8.0))
nr_parts=build_nr_sfm(damage) if use_nr or has_ringing else (
[f'lowpass=f={int(br_rolloff*0.97)}:poles=2'] if has_ringing else [])
L(f"\n[ูค] Step 2b โ MDS-Calibrated Compand (v8 FIX: LRA delta ุตุญูุญ)...")
# v8 FIX #4: ูู
ุฑุฑ inp_lra ููุฏุงูุฉ
compand_pts,makeup,intensity,calib=build_compand_mds(damage,ref_fp,inp_lra)
lra_delta_actual=max(0.0,inp_lra-ref_fp.lra_clip)
L(f" Compand={intensity} Makeup=+{makeup:.1f}dB calib={calib:+.1f}dB"
f" (LRA_delta={lra_delta_actual:.2f} | MDS={mds:.0f})")
L(f"\n[ูฅ] Step 2d โ Spectral Distance EQ (scipy Bark)...")
max_eq_db=4.0 if quality_label=='EXTREME' else 5.0 if quality_label=='VERY_POOR' else 6.0
n_eq=12 if quality_label=='EXTREME' else 10
eq_nodes=optimize_eq(inp_b,ref_fp,n_nodes=n_eq,max_db=max_eq_db,
shape_only=(quality_label=='EXTREME'),hf_rolloff=hf_rolloff)
warmth_pre=build_warmth_nodes(inp_b,ref_fp,hf_rolloff,
post_compand=False,current_crest=inp_crest)
eq_all=merge_eq(sorted(eq_nodes+warmth_pre,key=lambda x:x[0]),60.0)
eq_all=[(f,float(np.clip(g,-max_eq_db,max_eq_db)),q) for f,g,q in eq_all]
eq_final=[]
for f0,g,q in eq_all:
if f0>=hf_rolloff and g>0:
if f0<hf_rolloff*1.5: eq_final.append((f0,min(-0.5,g*-0.3),q))
else: eq_final.append((f0,g,q))
eq_nodes_cur=eq_final
L(f" {len(eq_nodes_cur)} ููุทุฉ EQ (ยฑ{max_eq_db}dB)")
inp_tilt=spectral_tilt(inp_b); tilt_corr=ref_fp.tilt_slope-inp_tilt
# v8 FIX #1 + v8.4: bias_cutoff_hz ู
ู tier_profile
# v8.45: also gate at ref codec cutoff โ no boosts above ref's own HF ceiling
bias_filter=build_bias_filter(
hf_rolloff,
min(tier_profile.bias_cutoff_hz, ref_fp.ref_codec_cutoff_hz)
)
L(f" Bias: 250Hzโ+{abs(-(-7.00)*BIAS_SCALE):.2f}dBโ | "
f"4kHzโ{-(5.00*BIAS_SCALE):.2f}dBโ | "
f"8kHzโ{-(8.00*BIAS_SCALE):.2f}dBโ (v8 FIX)")
# โโ STEP 3: Do-No-Harm Convergence โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
L(f"\n{'โ'*70}")
L(f" STEP 3 โ Do-No-Harm Convergence (v8 โ Single Compand + Single Limiter)")
L(f"{'โ'*70}")
best_score=0.0; best_path=None
for iteration in range(max_iterations):
L(f"\n โ ุชูุฑุงุฑ {iteration+1}/{max_iterations}")
# LUFS 7-point
L(f" [ูฆ] LUFS 7-point Gaussian...")
chain0=build_filter_chain(
eq_nodes_cur,compand_pts,makeup,inp_hf,is_mono,0.0,
nr_parts,bias_filter,[],intensity,inp_lra,damage,
hf_rolloff,src_sr,ref_fp.lra_clip,tilt_corr
).replace('\n','').replace(' ','')
l0=sample_lufs_7pt(input_path,total_s,n_ch,chain0)
gain_needed=float(np.clip(TARGET['lufs']-l0-calib,-18,12))
L(f" LUFS_7pt={l0:.2f} gain={gain_needed:+.2f}dB")
# Pass 1 โ WAV
L(f" [ูง] Pass 1 โ WAV (single compand, soft limiter)...")
tmp_p1=os.path.join(_TMP,'v81_p1.wav')
chain1=build_filter_chain(
eq_nodes_cur,compand_pts,makeup,inp_hf,is_mono,gain_needed,
nr_parts,bias_filter,[],intensity,inp_lra,damage,
hf_rolloff,src_sr,ref_fp.lra_clip,tilt_corr
).replace('\n','').replace(' ','')
r1=subprocess.run(['ffmpeg','-y','-i',input_path,'-af',
chain1+',ebur128=peak=true',
'-ar','48000','-ac','2',tmp_p1,'-loglevel','info'],
capture_output=True,text=True)
lufs_p1=-99.0
for line in r1.stderr.split('\n'):
s=line.strip()
if s.startswith('I:') and 'LUFS' in s and 'LRA' not in s:
try: lufs_p1=float(s.split('I:')[1].strip().split()[0]); break
except: pass
if lufs_p1==-99.0: lufs_p1=gain_needed+l0
p1_a=load_audio(tmp_p1,skip=skip_s,duration=45)
p1_b=third_octave(p1_a)
p1_crest=crest_factor(p1_a)
p1_m={'lufs':lufs_p1,'rms':rms_db(p1_a),'crest':p1_crest,'lra':lra_estimate(p1_a)}
s1,_=quality_score(p1_b,ref_fp,p1_m,hf_rolloff,
tier_profile.tier,tier_profile.input_cutoff_hz)
L(f" LUFS={lufs_p1:.2f} RMS={p1_m['rms']:.2f} Crest={p1_crest:.2f}"
f" LRA={p1_m['lra']:.2f} Score={s1}")
# Pass 2 โ WAV (spectral correction + warmth)
L(f" [ูจ] Pass 2 โ WAV (Crest-aware spectral correction)...")
lufs_corr=TARGET['lufs']-lufs_p1
p1_adj={fc:v+lufs_corr for fc,v in p1_b.items()}
max_c2=2.5 if quality_label=='EXTREME' else 3.0
corr2=spectral_correction(p1_adj,ref_fp,hf_rolloff,max_c2,2,p1_crest)
pw2=build_warmth_nodes(p1_adj,ref_fp,hf_rolloff,True,p1_crest)
p2_parts=[f'volume={lufs_corr:.3f}dB']
for f0,g,Q in corr2:
p2_parts.append(f'equalizer=f={f0:.0f}:width_type=q:width={Q}:g={g}')
for f0,g,Q in pw2:
p2_parts.append(f'equalizer=f={f0:.0f}:width_type=q:width={Q}:g={g}')
# v8 FIX #3: WAV ูุณูุทุฉ = limit ูุงุนู
ุฌุฏุงู (ูุญูุธ Crest)
p2_parts.append('alimiter=limit=0.9997:level=false:attack=10:release=100')
tmp_p2=os.path.join(_TMP,'v81_p2.wav')
subprocess.run(['ffmpeg','-y','-i',tmp_p1,'-af',','.join(p2_parts),
'-ar','48000','-ac','2',tmp_p2,'-loglevel','error'],
capture_output=True)
p2_a=load_audio(tmp_p2,skip=skip_s,duration=45)
p2_b=third_octave(p2_a)
p2_crest=crest_factor(p2_a); p2_lra=lra_estimate(p2_a); p2_rms=rms_db(p2_a)
p2_m={'lufs':TARGET['lufs'],'rms':p2_rms,'crest':p2_crest,'lra':p2_lra}
s2,_=quality_score(p2_b,ref_fp,p2_m,hf_rolloff,
tier_profile.tier,tier_profile.input_cutoff_hz)
L(f" RMS={p2_rms:.2f} Crest={p2_crest:.2f} LRA={p2_lra:.2f} Score={s2}")
L(f" Crest P1โP2: {p1_crest:.2f}โ{p2_crest:.2f} (ฮ={p1_crest-p2_crest:+.2f}LU)")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# v8 FIX #5: Quality Gate ู
ุน ุญุงุฑุณ Crest ู
ุณุชูู
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
crest_collapsed=(p2_crest < p1_crest-1.5 and
p2_crest < TARGET['crest']-0.8)
score_regressed=(s2 < s1-1.0)
if score_regressed or crest_collapsed:
reason=('Crest ุงููุงุฑ' if crest_collapsed else f'Score P2({s2})<P1({s1})')
L(f" โ Quality Gate v8 [{reason}] โ ุฑุฌูุน ูู P1")
shutil.copy(tmp_p1,tmp_p2); p2_b=p1_b
p2_crest=p1_crest; p2_lra=p1_m['lra']
p2_rms=p1_m['rms']; p2_m=p1_m; s2=s1
# Pass 3 โ WAV (LRA + RMS feedback)
L(f" [ูฉ] Pass 3 โ WAV (LRA+RMS feedback)...")
p3_parts=[]
# v8.45: use phrase_lra_p50 as LRA target (phrase-level, not full-file average)
# FORENSIC: phrase_lra_p50 measured at 3.34 LU (vs hardcoded 4.19 full-file)
# using full-file 4.19 causes Pass 3 to over-expand โ phrase target is more accurate
lra_p3_target = ref_fp.phrase_lra_p50 if ref_fp.phrase_lra_p50 > 0.1 else ref_fp.lra
lra_gap=lra_p3_target - p2_lra
rms_gap=ref_fp.rms-p2_rms
# v8: LRA gate ููุง ููุท | v8.4: lra_expand_gate ูู
ูุน ุงูุชูุณูุน ูู TIER_DAMAGED
if lra_gap>0.3 and p2_crest>TARGET['crest']-1.5 and tier_profile.lra_expand_gate:
if lra_gap<0.8: thr,ratio,rel=0.020,1.8,700
elif lra_gap<1.5: thr,ratio,rel=0.026,2.2,580
else: thr,ratio,rel=0.032,2.6,450
p3_parts.append(f'agate=threshold={thr:.3f}:ratio={ratio:.1f}'
f':attack=15:release={rel}:makeup=1.0:range=0.08')
rms_leak=lra_gap*0.14 if lra_gap>0.3 else 0.0
rms_adj=float(np.clip((rms_gap+rms_leak)*0.45,-1.2,1.2))
if abs(rms_adj)>0.12:
p3_parts.append(f'volume={rms_adj:.3f}dB')
corr3=spectral_correction(p2_b,ref_fp,hf_rolloff,1.8,3,p2_crest)
for f0,g,Q in corr3:
p3_parts.append(f'equalizer=f={f0:.0f}:width_type=q:width={Q}:g={g}')
# v8 FIX #3: WAV ูุณูุทุฉ = limit ูุงุนู
p3_parts.append('alimiter=limit=0.9997:level=false:attack=10:release=100')
tmp_p3=os.path.join(_TMP,'v81_p3.wav')
if len(p3_parts)>1:
subprocess.run(['ffmpeg','-y','-i',tmp_p2,'-af',','.join(p3_parts),
'-ar','48000','-ac','2',tmp_p3,'-loglevel','error'],
capture_output=True)
else:
shutil.copy(tmp_p2,tmp_p3)
p3_a=load_audio(tmp_p3,skip=skip_s,duration=45)
p3_b=third_octave(p3_a)
p3_crest=crest_factor(p3_a); p3_lufs=measure_lufs(tmp_p3)
p3_m={'lufs':p3_lufs,'rms':rms_db(p3_a),'crest':p3_crest,'lra':lra_estimate(p3_a)}
s3,_=quality_score(p3_b,ref_fp,p3_m,hf_rolloff,
tier_profile.tier,tier_profile.input_cutoff_hz)
if s3<s2-1.0:
L(f" โ Quality Gate: P3({s3})<P2({s2}) โ ุฑุฌูุน ูู P2")
shutil.copy(tmp_p2,tmp_p3); p3_b=p2_b
p3_lufs=TARGET['lufs']; p3_crest=p2_crest; s3=s2
# Pass 4 โ MP3 (True Peak Compliance)
# v8 FIX #3: alimiter=0.891 ููุง ููุท โ ุงูุชุทุจูู ุงููุญูุฏ ุงูุญูููู
lufs_trim=TARGET['lufs']-p3_lufs
p4_parts=[]
if abs(lufs_trim)>0.08: p4_parts.append(f'volume={lufs_trim:.3f}dB')
if s3<93.0:
c4=spectral_correction(p3_b,ref_fp,hf_rolloff,0.8,4,p3_crest)
for f0,g,Q in c4:
p4_parts.append(f'equalizer=f={f0:.0f}:width_type=q:width={Q}:g={g}')
# ุงูุชุทุจูู ุงููุญูุฏ ุงูุญูููู ูู True Peak limiter
p4_parts.append('alimiter=limit=0.891:level=false:attack=1:release=15')
tmp_out=os.path.join(_TMP,f'v81_out_{iteration}.mp3')
subprocess.run(['ffmpeg','-y','-i',tmp_p3,'-af',','.join(p4_parts),
'-b:a','320k','-ar','48000','-ac','2',
tmp_out,'-loglevel','error'],capture_output=True)
out_a=load_audio(tmp_out,skip=skip_s,duration=45)
out_b_=third_octave(out_a)
out_lufs=measure_lufs(tmp_out)
out_m={'lufs':out_lufs,'rms':rms_db(out_a),
'crest':crest_factor(out_a),'lra':lra_estimate(out_a)}
fs,fbd=quality_score(out_b_,ref_fp,out_m,hf_rolloff,
tier_profile.tier,tier_profile.input_cutoff_hz)
L(f"\n โ
P1={s1}โP2={s2}โP3={s3}โFinal={fs}/100")
L(f" LUFS={out_m['lufs']:.2f} RMS={out_m['rms']:.2f}"
f" Crest={out_m['crest']:.2f} LRA={out_m['lra']:.2f}")
if fs>best_score: best_score=fs; best_path=tmp_out
if fs>=target_score: L(f" โ
ูุฏู {target_score} ู
ุญูู!"); break
# Adaptive EQ
if iteration<max_iterations-1:
rv={fc:ref_fp.third_oct[fc] for fc in ref_fp.third_oct
if fc in out_b_ and 100<=fc<=10000}
ov={fc:out_b_[fc] for fc in rv}
loff_i=float(np.mean([rv[fc]-ov[fc] for fc in rv]))
sr_={fc:(rv[fc]-ov[fc])-loff_i for fc in rv}
avg_se=float(np.mean(np.abs(list(sr_.values()))))
# v8.1 PATCH #4: linear ramp | v8.4: ร eq_ramp_scale (tier-gated)
scale=min(0.45, max(0.08, 0.15 + (avg_se - 1.5) * 0.085))
scale=max(0.04, scale * tier_profile.eq_ramp_scale) # v8.4
big=sorted([(fc,v) for fc,v in sr_.items() if abs(v)>2.5],
key=lambda x:-abs(x[1]))[:3]
if big:
corr=[(fc,round(v*scale,2),1.5) for fc,v in big]
eq_nodes_cur=merge_eq(list(eq_nodes_cur)+corr,60.0)
eq_nodes_cur=[(f,float(np.clip(g,-max_eq_db,max_eq_db)),q)
for f,g,q in eq_nodes_cur]
L(f" ๐ {len(corr)} EQ adaptive (avg_error={avg_se:.2f}dB, scale={scale:.3f} ramp)")
# Finalize
shutil.copy(best_path if best_path else tmp_out,output_path)
if _input_tmp and os.path.exists(_input_tmp):
try: os.remove(_input_tmp)
except: pass
fin_a=load_audio(output_path,skip=skip_s,duration=45)
fin_b=third_octave(fin_a)
fin_lufs=measure_lufs(output_path)
fin_m={'lufs':fin_lufs,'rms':rms_db(fin_a),
'crest':crest_factor(fin_a),'lra':lra_estimate(fin_a)}
top_s,top_bd=quality_score(fin_b,ref_fp,fin_m,hf_rolloff,
tier_profile.tier,tier_profile.input_cutoff_hz)
elapsed=time.time()-t0
L(f"\n{'โ'*70}")
L(f" FINAL REPORT โ v8.5 ({elapsed:.0f}s)")
L(f"{'โ'*70}")
L(f" {'ุงูู
ููุงุณ':<18} {'ุงูู
ุฏุฎู':>8} {'ุงูู
ุฎุฑุฌ':>8} {'ุงููุฏู 1425H':>12}")
L(f" {'โ'*52}")
L(f" {'LUFS':<18} {'N/A':>8} {fin_m['lufs']:>8.2f} {TARGET['lufs']:>12.2f}")
L(f" {'RMS (dBFS)':<18} {inp_rms:>8.2f} {fin_m['rms']:>8.2f} {ref_fp.rms:>12.2f}")
L(f" {'Crest (LU)':<18} {inp_crest:>8.2f} {fin_m['crest']:>8.2f} {TARGET['crest']:>12.2f}")
L(f" {'LRA (LU)':<18} {inp_lra:>8.2f} {fin_m['lra']:>8.2f} {ref_fp.lra:>12.2f}")
L(f" {'MDS Score':<18} {mds:>8.1f} {'โ':>8} {'0 (perfect)':>12}")
# v8.4 SOURCE TIER line
L(f" [v8.4] SOURCE TIER {tier_profile.tier:<20}"
f" cutoff={tier_profile.input_cutoff_hz/1000:.1f}kHz"
f" noise={tier_profile.noise_type}"
f" clip={tier_profile.clip_tier}"
f" eq_scale={tier_profile.eq_ramp_scale:.2f}x"
f" bias_ceil={tier_profile.bias_cutoff_hz/1000:.1f}kHz")
if tier_profile.tier != 'TIER_PRISTINE':
L(f" CEILING: Crestโค{tier_profile.achievable_crest:.2f}LU"
f" LRAโค{tier_profile.achievable_lra:.2f}LU"
f" LUFSโฅ{tier_profile.achievable_lufs:.2f}")
if not tier_profile.lra_expand_gate:
L(f" โ LRA expansion disabled โ codec AGC destroyed dynamics")
if tier_profile.noise_type not in ('none','unknown'):
L(f" NR applied: {tier_profile.noise_type}"
f" sfm_silence={tier_profile.sfm_silence:.2f}")
bar='โ'*int(top_s/5)+'โ'*(20-int(top_s/5))
L()
L(f" โ
{bar} {top_s}/100"
f" {'โ
EXCELLENT' if top_s>=96 else 'โ
PASS' if top_s>=92 else 'โ' if top_s>=88 else 'โ '}")
# v8.5: show both tier-adjusted and absolute scores
if top_bd.ceiling_reason:
L(f" [v8.5] score_tier={top_bd.score_tier}/100"
f" score_absolute={top_bd.score_absolute}/100"
f" (ceiling adjusted for {tier_profile.tier})")
L(f" โ {top_bd.ceiling_reason}")
else:
L(f" [v8.5] score_tier={top_bd.score_tier}/100"
f" score_absolute={top_bd.score_absolute}/100 (TIER_PRISTINE โ no adjustment)")
L(f" Spectral:{top_bd.spectral} LUFS:{top_bd.lufs} Crest:{top_bd.crest}"
f" LRA:{top_bd.lra} Warmth:{top_bd.warmth} HF:{top_bd.hf}")
L(f" ุฎุทุฃ ุทููู:ยฑ{top_bd.avg_err}dB MDS:{mds:.1f}/100({quality_label})")
for n in top_bd.notes: L(f" โ {n}")
# v8 Bug fixes summary in log
L()
L(f" v8 Fixes Applied:")
L(f" โ BIAS 250Hz: +1.75dB boost (was -2.75dB cut in v7.6)")
L(f" โ BIAS 4kHz: -1.25dB cut (was +0.375dB boost in v7.6)")
L(f" โ BIAS 8kHz: -2.00dB cut (was +1.00dB boost in v7.6)")
L(f" โ No LRA stacking (single compand only)")
L(f" โ Single True Peak limiter in Pass 4 only")
L(f" โ LRA delta uses inp_lra vs lra_clip (was DR in v7.6)")
L(f" v8.1/v8.2 Patches Applied:")
L(f" โ REF_CACHE โ ~/.tilawa_cache/ref_fp.v85.json (v8.5 version bump)")
L(f" โ REF_FILES โ env / container_ref / legacy | --ref argparse fixed")
L(f" โ ALL /tmp/ โ tempfile.gettempdir() (_TMP={_TMP})")
L(f" โ Adaptive EQ scale: linear ramp ร tier eq_ramp_scale")
L(f" โ 64K_FLOOR label for honest Crest ceiling reporting")
L(f" v8.4 Source Tier Intelligence:")
L(f" โ SourceTierDetector: {tier_profile.tier} "
f"cutoff={tier_profile.input_cutoff_hz:.0f}Hz "
f"noise={tier_profile.noise_type}")
L(f" โ BIAS boost gated at {tier_profile.bias_cutoff_hz:.0f}Hz "
f"(was always 20kHz)")
L(f" โ EQ scale={tier_profile.eq_ramp_scale:.2f}x "
f"NR_mandatory={tier_profile.nr_mandatory} "
f"LRA_expand={tier_profile.lra_expand_gate}")
L(f" v8.45 Deep Reference Model:")
L(f" โ Full-file spectral avg (was 8ร30s clips โ up to +16dB bias fixed)")
L(f" โ phrase_lra_p50={ref_fp.phrase_lra_p50:.2f}LU "
f"p10={ref_fp.phrase_lra_p10:.2f} p90={ref_fp.phrase_lra_p90:.2f} "
f"(Pass 3 target was hardcoded 4.19)")
L(f" โ silence_floor={ref_fp.silence_floor_db:.1f}dBFS "
f"NR_ceiling={ref_fp.silence_floor_db - 3.0:.1f}dBFS")
L(f" โ ref_codec_cutoff={ref_fp.ref_codec_cutoff_hz:.0f}Hz "
f"peak_dist={ref_fp.peak_distribution}")
lra_p3_used = ref_fp.phrase_lra_p50 if ref_fp.phrase_lra_p50 > 0.1 else ref_fp.lra
L(f" [v8.45] REF MODEL "
f"n_refs={ref_fp.n_files} "
f"p50_lra={ref_fp.phrase_lra_p50:.2f}LU "
f"peak={ref_fp.peak_distribution} "
f"sil={ref_fp.silence_floor_db:.1f}dBFS "
f"cutoff={ref_fp.ref_codec_cutoff_hz:.0f}Hz")
L(f" v8.5 Tier-Adjusted Scoring:")
L(f" โ score_tier={top_bd.score_tier}/100 score_absolute={top_bd.score_absolute}/100")
L(f" โ compute_mds tier-weighted: {tier_profile.tier} "
f"(SNR w={_V85_MDS_WEIGHTS[tier_profile.tier]['snr']:.2f}"
f" SFM w={_V85_MDS_WEIGHTS[tier_profile.tier]['sfm']:.2f}"
f" HF w={_V85_MDS_WEIGHTS[tier_profile.tier]['hf']:.2f})")
L(f" โ 64K_FLOOR hack removed โ replaced by TierAdjustedScoring")
if top_bd.ceiling_reason:
L(f" โ ceiling: {top_bd.ceiling_reason}")
L(f" [v8.5] TIER-SCORE "
f"tier={tier_profile.tier} "
f"score_tier={top_bd.score_tier}/100 "
f"score_abs={top_bd.score_absolute}/100 "
f"MDS={mds:.1f}")
L(); L(f" โ
{output_path}"); L(f"{'โ'*70}\n")
return {
'score':top_s,'breakdown':top_bd,'final_metrics':fin_m,
'input_metrics':{'rms':inp_rms,'crest':inp_crest,'lra':inp_lra,
'snr':snr_global,'sfm':inp_sfm,'dr':inp_dr,'mds':mds},
'quality_tier':quality_label,'mds':mds,
'hf_rolloff_hz':hf_rolloff,'ref_lra':ref_fp.lra,
'iterations':iteration+1,'log':log,'engine_version':'v8.5',
'score_absolute':top_bd.score_absolute,
'score_tier':top_bd.score_tier,
'ceiling_reason':top_bd.ceiling_reason,
'source_tier':tier_profile.tier,
'input_cutoff_hz':tier_profile.input_cutoff_hz,
'noise_type':tier_profile.noise_type,
}
def enhance_auto(input_path:str,output_path:str,
max_iterations:int=3,target_score:float=96.0) -> Dict:
return enhance(input_path,output_path,max_iterations,target_score)
def process_batch(input_dir:str,output_dir:str) -> None:
in_p=Path(input_dir); out_p=Path(output_dir); out_p.mkdir(parents=True,exist_ok=True)
files=sorted([f for f in in_p.iterdir()
if f.suffix.lower() in {'.mp3','.wav','.m4a','.flac'}])
if not files: print("ูุง ุชูุฌุฏ ู
ููุงุช"); return
scores=[]; results=[]
for i,f in enumerate(files,1):
dst=out_p/(f.stem+'_1425h_v81.mp3'); print(f"\n[{i}/{len(files)}] {f.name}")
try:
r=enhance_auto(str(f),str(dst))
sc=r.get('score',0); scores.append(sc)
results.append({'file':f.name,'score':sc,'status':'ok'}); print(f" โ
{sc}/100")
except Exception as e:
results.append({'file':f.name,'score':0,'status':'error','error':str(e)}); print(f" โ {e}")
avg=sum(scores)/len(scores) if scores else 0
print(f"\n Batch: {len(scores)}/{len(files)} avg={avg:.1f}/100")
try:
with open(out_p/'_batch_v81.json','w',encoding='utf-8') as jf:
json.dump({'results':results,'avg_score':round(avg,1)},jf,ensure_ascii=False,indent=2)
except: pass
def main() -> int:
if not NUMPY_OK or not SCIPY_OK:
print("pip install numpy scipy"); return 1
p=argparse.ArgumentParser(description='Audio Enhancement Engine v8.5 โ 1425H')
p.add_argument('-i','--input'); p.add_argument('-o','--output')
p.add_argument('--iterations',type=int,default=3)
p.add_argument('--target',type=float,default=96.0)
p.add_argument('--batch-in'); p.add_argument('--batch-out')
p.add_argument('--serve',action='store_true')
p.add_argument('--port',type=int,default=5000)
p.add_argument('--clear-cache',action='store_true')
p.add_argument('--ref', action='append', default=[],
metavar='REF_MP3',
help='Reference audio file path (may be repeated)')
args=p.parse_args()
if args.ref:
valid_refs = [r for r in args.ref if os.path.exists(r)]
if valid_refs:
global REF_FILES
REF_FILES = valid_refs
if args.clear_cache:
if os.path.exists(REF_CACHE): os.remove(REF_CACHE); print("โ
Cache v8 ุญูุฐู")
return 0
if args.serve:
try: from flask import Flask,request,send_file,jsonify
except: print("pip install flask"); return 1
import threading, uuid as _uuid, re
app=Flask(__name__); app.jobs={}
@app.route('/')
def index():
return (Path(__file__).parent/'templates'/'index.html').read_text()
@app.route('/upload',methods=['POST'])
def upload():
f=request.files.get('file')
if not f: return jsonify(error='ูู
ููุฑุณูู ู
ูู'),400
data=f.read()
if len(data)>300*1024*1024: return jsonify(error='ุงูุญุฏ ุงูุฃูุตู 300MB'),400
jid=str(_uuid.uuid4())[:8]; home=Path(os.environ.get('HOME','/tmp'))
(home/'uploads').mkdir(exist_ok=True); (home/'outputs').mkdir(exist_ok=True)
ext=Path(f.filename or 'a.mp3').suffix or '.mp3'
in_p=home/'uploads'/f'{jid}{ext}'; out_p=home/'outputs'/f'{jid}.mp3'
in_p.write_bytes(data); stem=Path(f.filename or 'audio').stem
app.jobs[jid]={'status':'processing','progress':5,'label':'ุฌุงุฑู ุงูู
ุนุงูุฌุฉ...','new_log':[],
'in':str(in_p),'out':str(out_p),'filename':f'{stem}_v8.1.mp3'}
def run(jid=jid,in_p=in_p,out_p=out_p):
j=app.jobs[jid]
try:
PHASES={'[ูก]':10,'[ูข]':18,'[ูฃ]':26,'[ูค]':32,'[ูฅ]':38,
'[ูฆ]':50,'[ูง]':62,'[ูจ]':74,'[ูฉ]':86}
proc=subprocess.Popen(
['python',__file__,'-i',str(in_p),'-o',str(out_p),'--iterations','3'],
stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,bufsize=1)
for line in proc.stdout:
line=line.rstrip()
if not line: continue
j.setdefault('new_log',[]).append(line)
for tag,pct in PHASES.items():
if tag in line: j['progress']=pct; j['label']=line.strip()[:60]; break
if 'โ
' in line:
m=re.search(r'([\d.]+)/100',line)
if m: j['score']=m.group(1)
for k,pat in [('crest',r'Crest'),('lra',r'LRA'),('rms',r'RMS')]:
if re.search(pat+r'\s*[=:]',line):
nums=re.findall(r'-?[\d.]+',line)
if len(nums)>=2: j.setdefault(k,nums[-2])
proc.wait()
if proc.returncode==0 and out_p.exists():
j.update({'status':'done','progress':100,'label':'ุงูุชู
ูุช'})
else:
j.update({'status':'error','error':'ูุดูุช ุงูู
ุนุงูุฌุฉ'})
except Exception as e:
j.update({'status':'error','error':str(e)})
finally:
try: in_p.unlink()
except: pass
threading.Thread(target=run,daemon=True).start()
return jsonify(job_id=jid)
@app.route('/status/<jid>')
def status(jid):
j=app.jobs.get(jid)
if not j: return jsonify(error='not found'),404
r={'status':j['status'],'progress':j['progress'],
'label':j.get('label',''),'log':j.pop('new_log',[])}
if j['status']=='done':
for k in ['score','crest','lra','rms','filename']: r[k]=j.get(k)
r['job_id']=jid
if j['status']=='error': r['error']=j.get('error','ุฎุทุฃ')
return jsonify(r)
@app.route('/download/<jid>')
def download(jid):
j=app.jobs.get(jid)
if not j or not Path(j['out']).exists(): return 'Not found',404
return send_file(j['out'],as_attachment=True,
download_name=j.get('filename','v8.1.mp3'))
print(f"\n ู
ุญุณูู ุงูุชูุงูุฉ v8.1 โ http://localhost:{args.port}\n")
app.run(host='0.0.0.0',port=args.port,debug=False,threaded=True)
return 0
if args.batch_in and args.batch_out:
process_batch(args.batch_in,args.batch_out); return 0
if not args.input or not args.output:
p.print_help(); return 1
try:
r=enhance_auto(args.input,args.output,args.iterations,args.target)
print(f"\n โ
{r['score']}/100 MDS={r['mds']:.0f} โ
{args.output}")
return 0 if r['score']>=85 else 1
except Exception as e:
print(f"โ {e}"); return 1
if __name__=='__main__':
sys.exit(main())
|