File size: 99,385 Bytes
577cd8e |
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 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 |
#This will download the booknlp files using my huggingface backup
import download_missing_booknlp_models
# @title Default title text
#this is code that will be used to turn numbers like 1,000 and in a txt file into 1000 go then booknlp doesnt make it weird and then when the numbers are generated it comes out fine
import re
def process_large_numbers_in_txt(file_path):
# Read the contents of the file
with open(file_path, 'r') as file:
content = file.read()
# Regular expression to match numbers with commas
pattern = r'\b\d{1,3}(,\d{3})+\b'
# Remove commas in numerical sequences
modified_content = re.sub(pattern, lambda m: m.group().replace(',', ''), content)
# Write the modified content back to the file
with open(file_path, 'w') as file:
file.write(modified_content)
# Usage example
#file_path = 'test_1.txt' # Replace with your actual file path
#process_large_numbers_in_txt(file_path)
#this code here will remove any blank text rows from the csv file
import pandas as pd
def remove_empty_text_rows(csv_file):
# Read the CSV file
data = pd.read_csv(csv_file)
# Remove rows where the 'Text' column is empty or NaN
data = data[data['Text'].notna() & (data['Text'] != '')]
# Write the modified DataFrame back to the CSV file
data.to_csv(csv_file, index=False)
print(f"Rows with empty 'Text' column have been removed from {csv_file}")
# Example usage
#csv_file = 'path_to_your_csv_file.csv' # Replace with your CSV file path
#remove_empty_text_rows(csv_file)
#this code here will split book.csv file by the custom weird chapter deliminator for amachines to see
import pandas as pd
def process_and_split_csv(file_path, split_string):
def split_text(text, split_string, original_row):
# Split the text at the specified string and find the index of the split
split_index = text.find(split_string)
parts = text.split(split_string)
new_rows = []
start_location = original_row['Start Location']
for index, part in enumerate(parts):
new_row = original_row.copy()
if index == 0:
new_row['Text'] = part
new_row['End Location'] = start_location + split_index
else:
new_row['Text'] = split_string + part
new_row['Start Location'] = start_location + split_index
new_row['End Location'] = start_location + split_index + len(split_string) + len(part)
split_index += len(split_string) + len(part) # Update for the next part
new_rows.append(new_row)
return new_rows
def process_csv(df, split_string):
new_rows = []
for _, row in df.iterrows():
text = row['Text']
if isinstance(text, str) and split_string in text:
new_rows.extend(split_text(text, split_string, row))
else:
new_rows.append(row)
return pd.DataFrame(new_rows)
# Read the CSV file
df = pd.read_csv(file_path)
# Process the DataFrame
new_df = process_csv(df, split_string)
# Write the modified DataFrame back to the CSV file
new_df.to_csv(file_path, index=False)
# Example usage
#file_path = 'Working_files/Book/book.csv'
#split_string = 'NEWCHAPTERABC'
#process_and_split_csv(file_path, split_string)
#this code right here isnt the book grabbing thing but its before to refrence in ordero to create the sepecial chapter labeled book thing with calibre idk some systems cant seem to get it so just in case but the next bit of code after this is the book grabbing code with booknlp
import os
import subprocess
import ebooklib
from ebooklib import epub
from bs4 import BeautifulSoup
import re
import csv
import nltk
import shutil
# Only run the main script if Value is True
def create_chapter_labeled_book(ebook_file_path):
# Function to ensure the existence of a directory
def ensure_directory(directory_path):
if not os.path.exists(directory_path):
os.makedirs(directory_path)
print(f"Created directory: {directory_path}")
ensure_directory('Working_files/Book')
def convert_to_epub(input_path, output_path):
# Convert the ebook to EPUB format using Calibre's ebook-convert
try:
subprocess.run(['ebook-convert', input_path, output_path], check=True)
except subprocess.CalledProcessError as e:
print(f"An error occurred while converting the eBook: {e}")
return False
return True
def save_chapters_as_text(epub_path):
# Create the directory if it doesn't exist
directory = "Working_files/temp_ebook"
#Clean up the text chapter folders by wiping it before creating chapters for selected ebook.
#Lazily done by just deleting the directly and everything in it.
if os.path.exists(directory):
shutil.rmtree(directory)
ensure_directory(directory)
# Open the EPUB file
book = epub.read_epub(epub_path)
previous_chapter_text = ''
previous_filename = ''
chapter_counter = 0
# Iterate through the items in the EPUB file
for item in book.get_items():
if item.get_type() == ebooklib.ITEM_DOCUMENT:
# Use BeautifulSoup to parse HTML content
soup = BeautifulSoup(item.get_content(), 'html.parser')
text = soup.get_text()
# Check if the text is not empty
if text.strip():
if len(text) < 2300 and previous_filename:
# Append text to the previous chapter if it's short
with open(previous_filename, 'a', encoding='utf-8') as file:
file.write('\n' + text)
else:
# Create a new chapter file and increment the counter
previous_filename = os.path.join(directory, f"chapter_{chapter_counter}.txt")
chapter_counter += 1
with open(previous_filename, 'w', encoding='utf-8') as file:
file.write(text)
print(f"Saved chapter: {previous_filename}")
# Example usage
input_ebook = ebook_file_path # Replace with your eBook file path
output_epub = 'Working_files/temp.epub'
if os.path.exists(output_epub):
os.remove(output_epub)
print(f"File {output_epub} has been removed.")
else:
print(f"The file {output_epub} does not exist.")
if convert_to_epub(input_ebook, output_epub):
save_chapters_as_text(output_epub)
# Download the necessary NLTK data (if not already present)
nltk.download('punkt')
"""
def process_chapter_files(folder_path, output_csv):
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
# Write the header row
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
# Process each chapter file
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
for filename in chapter_files:
if filename.startswith('chapter_') and filename.endswith('.txt'):
chapter_number = int(filename.split('_')[1].split('.')[0])
file_path = os.path.join(folder_path, filename)
try:
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read()
sentences = nltk.tokenize.sent_tokenize(text)
for sentence in sentences:
start_location = text.find(sentence)
end_location = start_location + len(sentence)
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
except Exception as e:
print(f"Error processing file {filename}: {e}")
"""
def process_chapter_files(folder_path, output_csv):
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
# Write the header row
writer.writerow(['Text', 'Start Location', 'End Location', 'Is Quote', 'Speaker', 'Chapter'])
# Process each chapter file
chapter_files = sorted(os.listdir(folder_path), key=lambda x: int(x.split('_')[1].split('.')[0]))
for filename in chapter_files:
if filename.startswith('chapter_') and filename.endswith('.txt'):
chapter_number = int(filename.split('_')[1].split('.')[0])
file_path = os.path.join(folder_path, filename)
try:
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read()
# Insert "NEWCHAPTERABC" at the beginning of each chapter's text
if text:
text = "NEWCHAPTERABC" + text
sentences = nltk.tokenize.sent_tokenize(text)
for sentence in sentences:
start_location = text.find(sentence)
end_location = start_location + len(sentence)
writer.writerow([sentence, start_location, end_location, 'True', 'Narrator', chapter_number])
except Exception as e:
print(f"Error processing file {filename}: {e}")
# Example usage
folder_path = "Working_files/temp_ebook" # Replace with your folder path
output_csv = 'Working_files/Book/Other_book.csv'
process_chapter_files(folder_path, output_csv)
def wipe_folder(folder_path):
# Check if the folder exists
if not os.path.exists(folder_path):
print(f"The folder {folder_path} does not exist.")
return
# Iterate through all files in the folder
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
# Check if it's a file and not a directory
if os.path.isfile(file_path):
try:
os.remove(file_path)
print(f"Removed file: {file_path}")
except Exception as e:
print(f"Failed to remove {file_path}. Reason: {e}")
else:
print(f"Skipping directory: {file_path}")
# Example usage
# folder_to_wipe = 'Working_files/temp_ebook' # Replace with the path to your folder
# wipe_folder(folder_to_wipe)
def sort_key(filename):
"""Extract chapter number for sorting."""
match = re.search(r'chapter_(\d+)\.txt', filename)
return int(match.group(1)) if match else 0
def combine_chapters(input_folder, output_file):
# Create the output folder if it doesn't exist
os.makedirs(os.path.dirname(output_file), exist_ok=True)
# List all txt files and sort them by chapter number
files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
sorted_files = sorted(files, key=sort_key)
with open(output_file, 'w') as outfile:
for i, filename in enumerate(sorted_files):
with open(os.path.join(input_folder, filename), 'r') as infile:
outfile.write(infile.read())
# Add the marker unless it's the last file
if i < len(sorted_files) - 1:
outfile.write("\nNEWCHAPTERABC\n")
# Paths
input_folder = 'Working_files/temp_ebook'
output_file = 'Working_files/Book/Chapter_Book.txt'
# Combine the chapters
combine_chapters(input_folder, output_file)
ensure_directory('Working_files/Book')
#create_chapter_labeled_book()
#this is the Booknlp book grabber code
import os
import subprocess
import tkinter as tk
from tkinter import filedialog, messagebox
from epub2txt import epub2txt
from booknlp.booknlp import BookNLP
import nltk
import re
nltk.download('averaged_perceptron_tagger')
epub_file_path = ""
chapters = []
ebook_file_path = ""
input_file_is_txt = False
def convert_epub_and_extract_chapters(epub_path):
# Regular expression to match the chapter lines in the output
chapter_pattern = re.compile(r'Detected chapter: \* (.*)')
# List to store the extracted chapter names
chapter_names = []
# Start the conversion process and capture the output
process = subprocess.Popen(['ebook-convert', epub_path, '/dev/null'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True)
# Read the output line by line
for line in iter(process.stdout.readline, ''):
print(line, end='') # You can comment this out if you don't want to see the output
match = chapter_pattern.search(line)
if match:
chapter_names.append(match.group(1))
# Wait for the process to finish
process.stdout.close()
process.wait()
return chapter_names
def calibre_installed():
"""Check if Calibre's ebook-convert tool is available."""
try:
subprocess.run(['ebook-convert', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return True
except FileNotFoundError:
print("""ERROR NO CALIBRE: running epub2txt convert version...
It appears you dont have the calibre commandline tools installed on your,
This will allow you to convert from any ebook file format:
Calibre supports the following input formats: CBZ, CBR, CBC, CHM, EPUB, FB2, HTML, LIT, LRF, MOBI, ODT, PDF, PRC, PDB, PML, RB, RTF, SNB, TCR, TXT.
If you want this feature please follow online instruction for downloading the calibre commandline tool.
For Linux its:
sudo apt update && sudo apt upgrade
sudo apt install calibre
""")
return False
def convert_with_calibre(file_path, output_format="txt"):
"""Convert a file using Calibre's ebook-convert tool."""
output_path = file_path.rsplit('.', 1)[0] + '.' + output_format
subprocess.run(['ebook-convert', file_path, output_path])
return output_path
import os
import subprocess
import sys
def process_file_headless():
# Ask for the file path via command line
while True:
file_path = input("Enter the file path of the ebook: ")
# Check if the file exists
if os.path.isfile(file_path):
# File exists, break out of the loop
break
else:
print("File not found. Please try again.")
ebook_file_path = file_path
input_file_is_txt = file_path.lower().endswith('.txt')
if not os.path.exists(file_path):
print("File not found. Please check the path and try again.")
return
if file_path.lower().endswith(('.cbz', '.cbr', '.cbc', '.chm', '.epub', '.fb2', '.html', '.lit', '.lrf',
'.mobi', '.odt', '.pdf', '.prc', '.pdb', '.pml', '.rb', '.rtf', '.snb', '.tcr')) and calibre_installed():
file_path = convert_with_calibre(file_path)
elif file_path.lower().endswith('.epub') and not calibre_installed():
content = epub2txt(file_path)
if not os.path.exists('Working_files'):
os.makedirs('Working_files')
file_path = os.path.join('Working_files', 'Book.txt')
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
elif not file_path.lower().endswith('.txt'):
print("Selected file format is not supported or Calibre is not installed.")
return
# Now process the TXT file with BookNLP
book_id = "Book"
output_directory = os.path.join('Working_files', book_id)
model_params = {
"pipeline": "entity,quote,supersense,event,coref",
"model": "big"
}
# Process large numbers in text file to prevent tokenization errors
process_large_numbers_in_txt(file_path)
booknlp = BookNLP("en", model_params)
if calibre_installed():
create_chapter_labeled_book(file_path)
booknlp.process('Working_files/Book/Chapter_Book.txt', output_directory, book_id)
# Clean up temporary files
if not input_file_is_txt:
os.remove(file_path)
print(f"Deleted file: {file_path} because it's not needed anymore after the ebook conversion to txt")
else:
booknlp.process(file_path, output_directory, book_id)
print("Success, File processed successfully!")
# To run the script from the command line
if __name__ == "__main__":
process_file_headless()
import pandas as pd
def filter_and_correct_quotes(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
corrected_lines = []
# Filter out lines with mismatched quotes
for line in lines:
if line.count('"') % 2 == 0:
corrected_lines.append(line)
with open(file_path, 'w', encoding='utf-8') as file:
file.writelines(corrected_lines)
print(f"Processed {len(lines)} lines.")
print(f"Removed {len(lines) - len(corrected_lines)} problematic lines.")
print(f"Wrote {len(corrected_lines)} lines back to the file.")
if __name__ == "__main__":
file_path = "Working_files/Book/Book.quotes"
filter_and_correct_quotes(file_path)
import pandas as pd
import re
import glob
import os
def process_files(quotes_file, tokens_file):
skip_rows = []
while True:
try:
df_quotes = pd.read_csv(quotes_file, delimiter="\t", skiprows=skip_rows)
break
except pd.errors.ParserError as e:
msg = str(e)
match = re.search(r'at row (\d+)', msg)
if match:
problematic_row = int(match.group(1))
print(f"Skipping problematic row {problematic_row} in {quotes_file}")
skip_rows.append(problematic_row)
else:
print(f"Error reading {quotes_file}: {e}")
return
df_tokens = pd.read_csv(tokens_file, delimiter="\t", on_bad_lines='skip', quoting=3)
last_end_id = 0
nonquotes_data = []
for index, row in df_quotes.iterrows():
start_id = row['quote_start']
end_id = row['quote_end']
filtered_tokens = df_tokens[(df_tokens['token_ID_within_document'] > last_end_id) &
(df_tokens['token_ID_within_document'] < start_id)]
words_chunk = ' '.join([str(token_row['word']) for index, token_row in filtered_tokens.iterrows()])
words_chunk = words_chunk.replace(" n't", "n't").replace(" n’", "n’").replace("( ", "(").replace(" ,", ",").replace("gon na", "gonna").replace(" n’t", "n’t")
words_chunk = re.sub(r' (?=[^a-zA-Z0-9\s])', '', words_chunk)
if words_chunk:
nonquotes_data.append([words_chunk, last_end_id, start_id, "False", "Narrator"])
last_end_id = end_id
nonquotes_df = pd.DataFrame(nonquotes_data, columns=["Text", "Start Location", "End Location", "Is Quote", "Speaker"])
output_filename = os.path.join(os.path.dirname(quotes_file), "non_quotes.csv")
nonquotes_df.to_csv(output_filename, index=False)
print(f"Saved nonquotes.csv to {output_filename}")
def main():
quotes_files = glob.glob('Working_files/**/*.quotes', recursive=True)
tokens_files = glob.glob('Working_files/**/*.tokens', recursive=True)
for q_file in quotes_files:
base_name = os.path.splitext(os.path.basename(q_file))[0]
matching_token_files = [t_file for t_file in tokens_files if os.path.splitext(os.path.basename(t_file))[0] == base_name]
if matching_token_files:
process_files(q_file, matching_token_files[0])
print("All processing complete!")
if __name__ == "__main__":
main()
import pandas as pd
import re
import glob
import os
import nltk
def process_files(quotes_file, entities_file):
# Load the files
df_quotes = pd.read_csv(quotes_file, delimiter="\t")
df_entities = pd.read_csv(entities_file, delimiter="\t")
character_info = {}
def is_pronoun(word):
tagged_word = nltk.pos_tag([word])
return 'PRP' in tagged_word[0][1] or 'PRP$' in tagged_word[0][1]
def get_gender(pronoun):
male_pronouns = ['he', 'him', 'his']
female_pronouns = ['she', 'her', 'hers']
if pronoun in male_pronouns:
return 'Male'
elif pronoun in female_pronouns:
return 'Female'
return 'Unknown'
# Process the quotes dataframe
for index, row in df_quotes.iterrows():
char_id = row['char_id']
mention = row['mention_phrase']
# Initialize character info if not already present
if char_id not in character_info:
character_info[char_id] = {"names": {}, "pronouns": {}, "quote_count": 0}
# Update names or pronouns based on the mention_phrase
if is_pronoun(mention):
character_info[char_id]["pronouns"].setdefault(mention.lower(), 0)
character_info[char_id]["pronouns"][mention.lower()] += 1
else:
character_info[char_id]["names"].setdefault(mention, 0)
character_info[char_id]["names"][mention] += 1
character_info[char_id]["quote_count"] += 1
# Process the entities dataframe
for index, row in df_entities.iterrows():
coref = row['COREF']
name = row['text']
if coref in character_info:
if is_pronoun(name):
character_info[coref]["pronouns"].setdefault(name.lower(), 0)
character_info[coref]["pronouns"][name.lower()] += 1
else:
character_info[coref]["names"].setdefault(name, 0)
character_info[coref]["names"][name] += 1
# Extract the most likely name and gender for each character
for char_id, info in character_info.items():
most_likely_name = max(info["names"].items(), key=lambda x: x[1])[0] if info["names"] else "Unknown"
most_common_pronoun = max(info["pronouns"].items(), key=lambda x: x[1])[0] if info["pronouns"] else None
gender = get_gender(most_common_pronoun) if most_common_pronoun else 'Unknown'
gender_suffix = ".M" if gender == 'Male' else ".F" if gender == 'Female' else ".?"
info["formatted_speaker"] = f"{char_id}:{most_likely_name}{gender_suffix}"
info["most_likely_name"] = most_likely_name
info["gender"] = gender
# Write the formatted data to quotes.csv
output_filename = os.path.join(os.path.dirname(quotes_file), "quotes.csv")
with open(output_filename, 'w', newline='') as outfile:
fieldnames = ["Text", "Start Location", "End Location", "Is Quote", "Speaker"]
writer = pd.DataFrame(columns=fieldnames)
for index, row in df_quotes.iterrows():
char_id = row['char_id']
if not re.search('[a-zA-Z0-9]', row['quote']):
print(f"Removing row with text: {row['quote']}")
continue
if character_info[char_id]["quote_count"] == 1:
formatted_speaker = "Narrator"
else:
formatted_speaker = character_info[char_id]["formatted_speaker"] if char_id in character_info else "Unknown"
new_row = {"Text": row['quote'], "Start Location": row['quote_start'], "End Location": row['quote_end'], "Is Quote": "True", "Speaker": formatted_speaker}
#turn the new_row into a data frame
new_row_df = pd.DataFrame([new_row])
# Concatenate 'writer' with 'new_row_df'
writer = pd.concat([writer, new_row_df], ignore_index=True)
writer.to_csv(output_filename, index=False)
print(f"Saved quotes.csv to {output_filename}")
def main():
# Use glob to get all .quotes and .entities files within the "Working_files" directory and its subdirectories
quotes_files = glob.glob('Working_files/**/*.quotes', recursive=True)
entities_files = glob.glob('Working_files/**/*.entities', recursive=True)
# Pair and process .quotes and .entities files with matching filenames (excluding the extension)
for q_file in quotes_files:
base_name = os.path.splitext(os.path.basename(q_file))[0]
matching_entities_files = [e_file for e_file in entities_files if os.path.splitext(os.path.basename(e_file))[0] == base_name]
if matching_entities_files:
process_files(q_file, matching_entities_files[0])
print("All processing complete!")
if __name__ == "__main__":
main()
import pandas as pd
import re
import glob
import os
def process_files(quotes_file, tokens_file):
# Load the files
df_quotes = pd.read_csv(quotes_file, delimiter="\t")
df_tokens = pd.read_csv(tokens_file, delimiter="\t", on_bad_lines='skip', quoting=3)
last_end_id = 0 # Initialize the last_end_id to 0
nonquotes_data = [] # List to hold data for nonquotes.csv
# Iterate through the quotes dataframe
for index, row in df_quotes.iterrows():
start_id = row['quote_start']
end_id = row['quote_end']
# Get tokens between the end of the last quote and the start of the current quote
filtered_tokens = df_tokens[(df_tokens['token_ID_within_document'] > last_end_id) &
(df_tokens['token_ID_within_document'] < start_id)]
# Build the word chunk
#words_chunk = ' '.join([token_row['word'] for index, token_row in filtered_tokens.iterrows()])
words_chunk = ' '.join([str(token_row['word']) for index, token_row in filtered_tokens.iterrows()])
words_chunk = words_chunk.replace(" n't", "n't").replace(" n’", "n’").replace(" ’", "’").replace(" ,", ",").replace(" .", ".").replace(" n’t", "n’t")
words_chunk = re.sub(r' (?=[^a-zA-Z0-9\s])', '', words_chunk)
# Append data to nonquotes_data if words_chunk is not empty
if words_chunk:
nonquotes_data.append([words_chunk, last_end_id, start_id, "False", "Narrator"])
last_end_id = end_id # Update the last_end_id to the end_id of the current quote
# Create a DataFrame for non-quote data
nonquotes_df = pd.DataFrame(nonquotes_data, columns=["Text", "Start Location", "End Location", "Is Quote", "Speaker"])
# Write to nonquotes.csv
output_filename = os.path.join(os.path.dirname(quotes_file), "non_quotes.csv")
nonquotes_df.to_csv(output_filename, index=False)
print(f"Saved nonquotes.csv to {output_filename}")
def main():
# Use glob to get all .quotes and .tokens files within the "Working_files" directory and its subdirectories
quotes_files = glob.glob('Working_files/**/*.quotes', recursive=True)
tokens_files = glob.glob('Working_files/**/*.tokens', recursive=True)
# Pair and process .quotes and .tokens files with matching filenames (excluding the extension)
for q_file in quotes_files:
base_name = os.path.splitext(os.path.basename(q_file))[0]
matching_token_files = [t_file for t_file in tokens_files if os.path.splitext(os.path.basename(t_file))[0] == base_name]
if matching_token_files:
process_files(q_file, matching_token_files[0])
print("All processing complete!")
if __name__ == "__main__":
main()
import pandas as pd
import numpy as np
# Read the CSV files
quotes_df = pd.read_csv("Working_files/Book/quotes.csv")
non_quotes_df = pd.read_csv("Working_files/Book/non_quotes.csv")
# Concatenate the dataframes
combined_df = pd.concat([quotes_df, non_quotes_df], ignore_index=True)
# Convert 'None' to NaN
combined_df.replace('None', np.nan, inplace=True)
# Drop rows with NaN in 'Start Location'
combined_df.dropna(subset=['Start Location'], inplace=True)
# Convert the 'Start Location' column to integers
combined_df["Start Location"] = combined_df["Start Location"].astype(int)
# Sort by 'Start Location'
sorted_df = combined_df.sort_values(by="Start Location")
# Save to 'book.csv'
sorted_df.to_csv("Working_files/Book/book.csv", index=False)
#if booknlp came up with nothing then just use the other_book.csv file thank god i still have that code
import os
import tkinter as tk
from tkinter import messagebox
def is_single_line_file(filename):
with open(filename, 'r') as file:
return len(file.readlines()) <= 1
def copy_if_single_line(source_file, destination_file):
if not os.path.isfile(source_file):
return f"The source file '{source_file}' does not exist."
elif is_single_line_file(destination_file):
with open(source_file, 'r') as source:
content = source.read()
with open(destination_file, 'w') as dest:
dest.write(content)
## Popup message
#root = tk.Tk()
#root.withdraw() # Hide the main window
#messagebox.showinfo("Notification", "The 'book.csv' file was found to be empty, so all lines in the book will be said by the narrator.")
#root.destroy()
print(f"Notification:")
print(f"The 'book.csv' file was found to be empty, so all lines in the book will be said by the narrator.")
return f"File '{destination_file}' had only one line or was empty and has been filled with the contents of '{source_file}'."
else:
return f"File '{destination_file}' had more than one line, and no action was taken."
source_file = 'Working_files/Book/Other_book.csv'
destination_file = 'Working_files/Book/book.csv'
result = copy_if_single_line(source_file, destination_file)
print(result)
#this is a clean up script to try to clean up the quotes.csv and non_quotes.csv files of any types formed by booknlp
import pandas as pd
import os
import re
def process_text(text):
# Apply the rule to remove spaces before punctuation and other non-alphanumeric characters
text = re.sub(r' (?=[^a-zA-Z0-9\s])', '', text)
# Replace " n’t" with "n’t"
text = text.replace(" n’t", "n’t").replace("[", "(").replace("]", ")").replace("gon na", "gonna").replace("—————–", "").replace(" n't", "n't")
return text
def process_file(filename):
# Load the file
df = pd.read_csv(filename)
# Check if the "Text" column exists
if "Text" in df.columns:
# Apply the rules to the "Text" column
df['Text'] = df['Text'].apply(lambda x: process_text(str(x)))
# Save the processed data back to the file
df.to_csv(filename, index=False)
print(f"Processed and saved {filename}")
else:
print(f"Column 'Text' not found in {filename}")
def main():
folder_path = "Working_files/Book/"
files = ["non_quotes.csv", "quotes.csv", "book.csv"]
for filename in files:
full_path = os.path.join(folder_path, filename)
if os.path.exists(full_path):
process_file(full_path)
else:
print(f"File {filename} not found in {folder_path}")
if __name__ == "__main__":
main()
#this code here will split the bookcsv file by the calibre chapter deliminators such if calibre is installed
if calibre_installed():
process_and_split_csv("Working_files/Book/book.csv", 'NEWCHAPTERABC')
remove_empty_text_rows("Working_files/Book/book.csv")
#this will wipe the computer of any current audio clips from a previous session
#but itll ask the user first
import os
import tkinter as tk
from tkinter import messagebox
def check_and_wipe_folder(directory_path):
# Check if the directory exists
if not os.path.exists(directory_path):
print(f"The directory {directory_path} does not exist!")
return
# Check for .wav files in the directory
wav_files = [f for f in os.listdir(directory_path) if f.endswith('.wav')]
if wav_files: # If there are .wav files
## Initialize tkinter
#root = tk.Tk()
#root.withdraw() # Hide the main window
## Ask the user if they want to delete the files
#response = messagebox.askyesno("Confirm Deletion", "Audio clips from a previous session have been found. Do you want to wipe them?")
#root.destroy() # Destroy the tkinter instance
#response = input("Audio clips from a previous session have been found. Do you want to wipe them? (yes/no): ").strip().lower()
response = "yes"
if response == 'yes': # If the user types 'yes'
# Iterate through files and delete them
for filename in wav_files:
file_path = os.path.join(directory_path, filename)
try:
os.remove(file_path)
print(f"Deleted: {file_path}")
except Exception as e:
print(f"Failed to delete {file_path}. Reason: {e}")
else:
print("Wipe operation cancelled by the user.")
else:
print("No audio clips from a previous session were found.")
# Usage
check_and_wipe_folder("Working_files/generated_audio_clips/")
from TTS.api import TTS
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox, simpledialog, filedialog
import threading
import pandas as pd
import random
import os
import time
import os
import pandas as pd
import random
import shutil
import torch
import torchaudio
import time
import pygame
import nltk
from nltk.tokenize import sent_tokenize
from TTS.tts.configs.xtts_config import XttsConfig
from TTS.tts.models.xtts import Xtts
nltk.download('punkt')
# Ensure that nltk punkt is downloaded
nltk.download('punkt', quiet=True)
demo_text = "Imagine a world where endless possibilities await around every corner."
# Load the CSV data
csv_file="Working_files/Book/book.csv"
data = pd.read_csv(csv_file)
#voice actors folder
voice_actors_folder ="tortoise/voices/"
# Get the list of voice actors
voice_actors = [va for va in os.listdir(voice_actors_folder) if va != "cond_latent_example"]
male_voice_actors = [va for va in voice_actors if va.endswith(".M")]
female_voice_actors = [va for va in voice_actors if va.endswith(".F")]
SILENCE_DURATION_MS = 750
# Dictionary to hold each character's selected language
character_languages = {}
models = TTS().list_models()
#selected_tts_model = 'tts_models/multilingual/multi-dataset/xtts_v2'
#I have to do this right now cause they made a weird change to coqui idk super weird the list models isnt working right now
#so this will chekc if its a list isk man and if not then the bug is still there and itll apply the fix
if isinstance(models, list):
print("good it's a list I can apply normal code for model list")
selected_tts_model = models[0]
else:
tts_manager = TTS().list_models()
all_models = tts_manager.list_models()
models = all_models
selected_tts_model = models[0]
# Map for speaker to voice actor
speaker_voice_map = {}
CHAPTER_KEYWORD = "CHAPTER"
multi_voice_model1 ="tts_models/en/vctk/vits"
multi_voice_model2 ="tts_models/en/vctk/fast_pitch"
multi_voice_model3 ="tts_models/ca/custom/vits"
#multi_voice_model_voice_list1 =speakers_list = TTS(multi_voice_model1).speakers
#multi_voice_model_voice_list2 =speakers_list = TTS(multi_voice_model2).speakers
#multi_voice_model_voice_list3 =speakers_list = TTS(multi_voice_model3).speakers
multi_voice_model_voice_list1 = []
multi_voice_model_voice_list2 = []
multi_voice_model_voice_list3 = []
# Dictionary to hold the comboboxes references
voice_comboboxes = {}
fast_voice_clone_models = [model for model in models if "multi-dataset" not in model]
# Creating a dictionary with specific values for the defined models
fast_voice_clone_models_dict = {
model: "p363" if model == multi_voice_model1 else
"VCTK_p226" if model == multi_voice_model2 else
"pep" if model == multi_voice_model3 else
None
for model in fast_voice_clone_models
}
def on_silence_duration_change(*args):
"""
Update the SILENCE_DURATION_MS based on the entry value.
"""
global SILENCE_DURATION_MS
try:
new_duration = int(silence_duration_var.get())
if new_duration >= 0:
SILENCE_DURATION_MS = new_duration
print(f"SILENCE_DURATION_MS changed to: {SILENCE_DURATION_MS}")
else:
raise ValueError
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid non-negative integer.")
def validate_integer(P):
"""
Validate if the entry is an integer.
"""
if P.isdigit() or P == "":
return True
else:
messagebox.showerror("Invalid Input", "Please enter a valid integer.")
return False
def update_silence_duration():
"""
Update the SILENCE_DURATION_MS based on the entry value.
"""
global SILENCE_DURATION_MS
try:
SILENCE_DURATION_MS = int(silence_duration_var.get())
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid integer.")
def add_languages_to_csv():
df = pd.read_csv('Working_files/Book/book.csv') # Make sure to use your actual CSV file path
if 'language' not in df.columns:
# Map the 'Speaker' column to the 'language' column using the character_languages dictionary
# The get method returns 'en' as a default value if the speaker is not found in the dictionary
df['language'] = df['Speaker'].apply(lambda speaker: character_languages.get(speaker, 'en'))
df.to_csv('Working_files/Book/book.csv', index=False) # Save the changes back to the CSV file
print("Added language data to the CSV file.")
def add_voice_actors_to_csv():
df = pd.read_csv(csv_file)
if 'voice_actor' not in df.columns:
df['voice_actor'] = df['Speaker'].map(speaker_voice_map)
df.to_csv(csv_file, index=False)
print(f"Added voice actor data to {csv_file}")
def get_random_voice_for_speaker(speaker):
selected_voice_actors = voice_actors # default to all voice actors
if speaker.endswith(".M") and male_voice_actors:
selected_voice_actors = male_voice_actors
elif speaker.endswith(".F") and female_voice_actors:
selected_voice_actors = female_voice_actors
if not selected_voice_actors: # If list is empty, default to all voice actors
selected_voice_actors = voice_actors
return random.choice(selected_voice_actors)
def get_random_voice_for_speaker_fast(speaker):
selected_voice_actors = voice_actors # default to all voice actors
male_voice_actors = {"p226", "p228","p229","p230","p231","p232","p233","p234","p236","p238","p239","p241","p251","p252","p253","p254","p255","p256","p258","p262","p264","p265","p266","p267","p269","p272","p279","p281","p282","p285","p286","p287","p292","p298","p299","p301","p302","p307","p312","p313","p317","p318","p326","p340"}
female_voice_actors = {"p225","p227","p237","p240","p243","p244","p245","p246","p247","p248","p249","p250","p257","p259","p260","p261","p263","p268","p270","p271","p273","p274","p275","p276","p277","p280","p283","p284","p288","p293","p294","p295","p297","p300","p303","p304","p305","p306","p308","p310","p311","p314","p316","p323","p329","p341","p343","p345","p347","p351","p360","p361","p362","p363","p364","p374"}
if speaker.endswith(".M") and male_voice_actors:
selected_voice_actors = male_voice_actors
elif speaker.endswith(".F") and female_voice_actors:
selected_voice_actors = female_voice_actors
elif speaker.endswith(".?") and female_voice_actors:
selected_voice_actors = male_voice_actors.union(female_voice_actors)
if not selected_voice_actors: # If list is empty, default to all voice actors
selected_voice_actors = male_voice_actors.union(female_voice_actors)
# Convert the set to a list before using random.choice
return random.choice(list(selected_voice_actors))
def ensure_output_folder():
if not os.path.exists("Working_files/generated_audio_clips"):
os.mkdir("Working_files/generated_audio_clips")
def ensure_temp_folder():
if not os.path.exists("Working_files/temp"):
os.mkdir("Working_files/temp")
import random
import time
def select_voices():
global speaker_voice_map
random.seed(int(time.time()))
ensure_output_folder()
total_rows = len(data) # Assuming 'data' contains your dataset with a 'Speaker' column
# Assign initial random voices
speaker_voice_map = {speaker: get_random_voice_for_speaker(speaker) for speaker in data['Speaker'].unique()}
# Function to display current voice selections and offer changes
def review_and_modify_speaker_voices():
while True:
# Display current selections
print("\nCurrent voice selections:")
for index, (speaker, voice) in enumerate(speaker_voice_map.items(), start=1):
print(f"{index}. {speaker}: {voice}")
# Ask if user wants to change any selection
#change = input("Would you like to change any voice assignments? (yes/no): ").lower()
change = "no"
if change != 'yes':
break
# Get user input for which speaker to change
try:
selection = int(input("Enter the number of the speaker to change the voice for: ")) - 1
if selection < 0 or selection >= len(speaker_voice_map):
raise ValueError("Selection out of range.")
selected_speaker = list(speaker_voice_map.keys())[selection]
except ValueError as e:
print(f"Invalid input: {e}")
continue
# Display available voices and allow user to choose
print(f"Available voices for {selected_speaker}:")
available_voices = [get_random_voice_for_speaker(selected_speaker) for _ in range(5)] # Assuming you can call this multiple times to get different options
for idx, voice in enumerate(available_voices, start=1):
print(f"{idx}. {voice}")
try:
new_voice_selection = int(input("Select the new voice by number: ")) - 1
if new_voice_selection < 0 or new_voice_selection >= len(available_voices):
raise ValueError("Selection out of range.")
# Update the speaker's voice in the map
speaker_voice_map[selected_speaker] = available_voices[new_voice_selection]
print(f"Voice for {selected_speaker} changed to {available_voices[new_voice_selection]}")
except ValueError as e:
print(f"Invalid input: {e}")
review_and_modify_speaker_voices()
print("Final voice assignments have been set.")
def select_voices_fast():
random.seed(int(time.time()))
ensure_output_folder()
total_rows = len(data)
for speaker in data['Speaker'].unique():
random_voice = get_random_voice_for_speaker_fast(speaker)
speaker_voice_map[speaker] = random_voice
for speaker, voice in speaker_voice_map.items():
print(f"Selected voice for {speaker}: {voice}")
# Update the comboboxes if they exist
if speaker in voice_comboboxes:
random_voice = get_random_voice_for_speaker_fast(speaker)
voice_comboboxes[speaker].set(random_voice)
print("Voices have been selected randomly.")
# Pre-select the voices before starting the GUI
select_voices()
## Main application window
#root = tk.Tk()
#root.title("coqui TTS GUI")
#root.geometry("1200x800")
#if calibre_installed():
# chapter_delimiter_var = tk.StringVar(value="NEWCHAPTERABC")
#else:
# chapter_delimiter_var = tk.StringVar(value="CHAPTER")
# Assume calibre_installed is a function that returns True if Calibre is installed, otherwise False
class Delimiter:
def __init__(self, value):
self._value = value
self._callbacks = []
def get(self):
return self._value
def set(self, new_value):
self._value = new_value
self._run_callbacks()
def _run_callbacks(self):
for callback in self._callbacks:
callback()
def trace_add(self, mode, callback):
if mode == "write":
self._callbacks.append(callback)
def update_chapter_keyword():
print("Chapter delimiter updated to:", chapter_delimiter_var.get())
if calibre_installed():
chapter_delimiter_var = Delimiter("NEWCHAPTERABC")
else:
chapter_delimiter_var = Delimiter("CHAPTER")
# Initialize the mixer module
try:
pygame.mixer.init()
print("mixer modual initialized successfully.")
except pygame.error:
print("mixer modual initialization failed")
print(pygame.error)
# This function is called when a voice actor is selected from the dropdown
def update_voice_actor(speaker):
selected_voice_actor = voice_comboboxes[speaker].get()
speaker_voice_map[speaker] = selected_voice_actor
print(f"Updated voice for {speaker}: {selected_voice_actor}")
# Get a random reference file for the selected voice actor
reference_files = list_reference_files(selected_voice_actor)
if reference_files: # Check if there are any reference files
random_file = random.choice(reference_files)
try:
# Stop any currently playing music or sound
pygame.mixer.music.stop()
pygame.mixer.stop()
if random_file.endswith('.mp3'):
# Use the music module for mp3 files
pygame.mixer.music.load(random_file)
pygame.mixer.music.play()
else:
# Use the Sound class for wav files
sound = pygame.mixer.Sound(random_file)
sound.play()
except Exception as e:
print(f"Could not play the audio file: {e}")
# Function to split long strings into parts
def split_long_sentence(sentence, max_length=230, max_pauses=8):
"""
Splits a sentence into parts based on length or number of pauses without recursion.
:param sentence: The sentence to split.
:param max_length: Maximum allowed length of a sentence.
:param max_pauses: Maximum allowed number of pauses in a sentence.
:return: A list of sentence parts that meet the criteria.
"""
parts = []
while len(sentence) > max_length or sentence.count(',') + sentence.count(';') + sentence.count('.') > max_pauses:
possible_splits = [i for i, char in enumerate(sentence) if char in ',;.' and i < max_length]
if possible_splits:
# Find the best place to split the sentence, preferring the last possible split to keep parts longer
split_at = possible_splits[-1] + 1
else:
# If no punctuation to split on within max_length, split at max_length
split_at = max_length
# Split the sentence and add the first part to the list
parts.append(sentence[:split_at].strip())
sentence = sentence[split_at:].strip()
# Add the remaining part of the sentence
parts.append(sentence)
return parts
def combine_wav_files(input_directory, output_directory, file_name):
# Get a list of all .wav files in the specified input directory
input_file_paths = [os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith(".wav")]
# Sort the file paths to ensure numerical order
input_file_paths.sort(key=lambda f: int(''.join(filter(str.isdigit, f))))
# Create an empty list to store the loaded audio tensors
audio_tensors = []
# Iterate through the sorted input file paths and load each audio file
for input_file_path in input_file_paths:
waveform, sample_rate = torchaudio.load(input_file_path)
audio_tensors.append(waveform)
# Concatenate the audio tensors along the time axis (dimension 1)
combined_audio = torch.cat(audio_tensors, dim=1)
# Ensure that the output directory exists, create it if necessary
os.makedirs(output_directory, exist_ok=True)
# Specify the output file path
output_file_path = os.path.join(output_directory, file_name)
# Save the combined audio to the output file path
torchaudio.save(output_file_path, combined_audio, sample_rate)
print(f"Combined audio saved to {output_file_path}")
def wipe_folder(directory_path):
# Ensure the directory exists
if not os.path.exists(directory_path):
print(f"The directory {directory_path} does not exist!")
return
# Iterate through files in the directory
for filename in os.listdir(directory_path):
file_path = os.path.join(directory_path, filename)
# Check if it's a regular file (not a subdirectory)
if os.path.isfile(file_path):
try:
os.remove(file_path)
print(f"Deleted: {file_path}")
except Exception as e:
print(f"Failed to delete {file_path}. Reason: {e}")
# List of available TTS models
tts_models = [
#'tts_models/multilingual/multi-dataset/xtts_v2',
# Add all other models here...
]
tts_models = TTS().list_models()
#This is another coqui bug fix i have to apply for the bug idk why but nwo there this lol it started in coqui V0.22.0
#this will make the models list actually work tho
if isinstance(tts_models, list):
print("good it's a list I can apply normal code for model list")
selected_tts_model = models[0]
else:
tts_manager = TTS().list_models()
all_models = tts_manager.list_models()
tts_models = all_models
# Function to update the selected TTS model
def update_tts_model(event):
global selected_tts_model
selected_tts_model = tts_model_combobox.get()
print(f"Selected TTS model: {selected_tts_model}")
multilingual_tts_models = [model for model in tts_models if "multi-dataset" in model]
multilingual_tts_models.append('StyleTTS2')
# modelse to be removed because i found that they are multi speaker and not single speaker
models_to_remove = [multi_voice_model1, multi_voice_model2, multi_voice_model3]
# List comprehension to remove the unwatned models
multilingual_tts_models = [model for model in multilingual_tts_models if model not in models_to_remove]
# Declare the button as global to access it in other functions
global select_voices_button
def update_voice_comboboxes():
global multi_voice_model_voice_list1
global multi_voice_model_voice_list2
global multi_voice_model_voice_list3
global voice_actors
global female_voice_actors
global male_voice_actors
#updating the values of the avalible voice actors too
voice_actors = [va for va in os.listdir(voice_actors_folder) if va != "cond_latent_example"]
male_voice_actors = [va for va in voice_actors if va.endswith(".M")]
female_voice_actors = [va for va in voice_actors if va.endswith(".F")]
# your code snippet to include single voice models
filtered_tts_models = [model for model in tts_models if "multi-dataset" not in model]
if not multi_voice_model_voice_list1: # This is True if the list is empty
print(f"{multi_voice_model_voice_list1} is empty populating it...")
multi_voice_model_voice_list1 = TTS(multi_voice_model1).speakers
if not multi_voice_model_voice_list2: # This is True if the list is empty
print(f"{multi_voice_model_voice_list2} is empty populating it...")
multi_voice_model_voice_list2 = TTS(multi_voice_model2).speakers
if not multi_voice_model_voice_list3: # This is True if the list is empty
print(f"{multi_voice_model_voice_list3} is empty populating it...")
multi_voice_model_voice_list3 = TTS(multi_voice_model3).speakers
combined_values = voice_actors + filtered_tts_models
combined_values += multi_voice_model_voice_list1 + multi_voice_model_voice_list2 + multi_voice_model_voice_list3
#this will remove unwatned models from the model list, thats cause these three are multi-speaker so im already including them as their voices
combined_values.remove(multi_voice_model1)
combined_values.remove(multi_voice_model2)
combined_values.remove(multi_voice_model3)
# Now update each combobox with the new combined_values
for speaker, combobox in voice_comboboxes.items():
combobox['values'] = combined_values
combobox.set(speaker_voice_map[speaker]) # Reset to the currently selected voice actor
longest_string_length = max((len(str(value)) for value in combobox['values']), default=0)
combobox.config(width=longest_string_length)
# Filter models that are not 'multi-dataset'
filtered_tts_models = [model for model in tts_models if "multi-dataset" not in model]
# Extend the model list with filtered models
multilingual_tts_models.extend(filtered_tts_models)
# Set default value if needed
#tts_model_combobox.set(selected_tts_model)
## Create a frame for the checkboxes
#checkbox_frame = ttk.Frame(root)
#checkbox_frame.pack(fill='x', pady=10)
# Call this function once initially to set the correct values from the start
update_voice_comboboxes()
def create_folder_if_not_exists(folder_path):
if not os.path.exists(folder_path):
os.makedirs(folder_path)
print(f"Folder '{folder_path}' created successfully.")
else:
print(f"Folder '{folder_path}' already exists.")
#i want to gigv ethis the voice actor name and have it turn that into the full directory of the voice actor location, and then use that to grab all the files inside of that voice actoers folder
def list_reference_files(voice_actor):
global multi_voice_model_voice_list1
global multi_voice_model_voice_list2
global multi_voice_model_voice_list3
if voice_actor in multi_voice_model_voice_list1:
create_folder_if_not_exists(f"tortoise/_model_demo_voices/{multi_voice_model1}/{voice_actor}")
reference_files = [os.path.join(f"tortoise/_model_demo_voices/{multi_voice_model1}/{voice_actor}", file) for file in os.listdir(f"tortoise/_model_demo_voices/{multi_voice_model1}/{voice_actor}") if file.endswith((".wav", ".mp3"))]
if len(reference_files)==0:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
fast_tts = TTS(multi_voice_model1, progress_bar=True).to(device)
fast_tts.tts_to_file(text=demo_text , file_path=f"tortoise/_model_demo_voices/{multi_voice_model1}/{voice_actor}/demo.wav", speaker = voice_actor)
reference_files = [os.path.join(f"tortoise/_model_demo_voices/{multi_voice_model1}/{voice_actor}", file) for file in os.listdir(f"tortoise/_model_demo_voices/{multi_voice_model1}/{voice_actor}") if file.endswith((".wav", ".mp3"))]
return reference_files
else:
return reference_files
elif voice_actor in multi_voice_model_voice_list2:
create_folder_if_not_exists(f"tortoise/_model_demo_voices/{multi_voice_model2}/{voice_actor}")
reference_files = [os.path.join(f"tortoise/_model_demo_voices/{multi_voice_model2}/{voice_actor}", file) for file in os.listdir(f"tortoise/_model_demo_voices/{multi_voice_model2}/{voice_actor}") if file.endswith((".wav", ".mp3"))]
if len(reference_files)==0:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
fast_tts = TTS(multi_voice_model2, progress_bar=True).to("cpu")
fast_tts.tts_to_file(text=demo_text , file_path=f"tortoise/_model_demo_voices/{multi_voice_model2}/{voice_actor}/demo.wav", speaker = voice_actor)
reference_files = [os.path.join(f"tortoise/_model_demo_voices/{multi_voice_model2}/{voice_actor}", file) for file in os.listdir(f"tortoise/_model_demo_voices/{multi_voice_model2}/{voice_actor}") if file.endswith((".wav", ".mp3"))]
return reference_files
else:
return reference_files
elif voice_actor in multi_voice_model_voice_list3:
create_folder_if_not_exists(f"tortoise/_model_demo_voices/{multi_voice_model3}/{voice_actor}")
reference_files = [os.path.join(f"tortoise/_model_demo_voices/{multi_voice_model3}/{voice_actor}", file) for file in os.listdir(f"tortoise/_model_demo_voices/{multi_voice_model3}/{voice_actor}") if file.endswith((".wav", ".mp3"))]
if len(reference_files)==0:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
fast_tts = TTS(multi_voice_model3, progress_bar=True).to(device)
fast_tts.tts_to_file(text=demo_text , file_path=f"tortoise/_model_demo_voices/{multi_voice_model3}/{voice_actor}/demo.wav", speaker = voice_actor)
reference_files = [os.path.join(f"tortoise/_model_demo_voices/{multi_voice_model3}/{voice_actor}", file) for file in os.listdir(f"tortoise/_model_demo_voices/{multi_voice_model3}/{voice_actor}") if file.endswith((".wav", ".mp3"))]
return reference_files
else:
return reference_files
elif "tts_models" in voice_actor:
create_folder_if_not_exists("tortoise/_model_demo_voices")
create_folder_if_not_exists(f"tortoise/_model_demo_voices/{voice_actor}")
reference_files = [os.path.join(f"tortoise/_model_demo_voices/{voice_actor}", file) for file in os.listdir(f"tortoise/_model_demo_voices/{voice_actor}") if file.endswith((".wav", ".mp3"))]
if len(reference_files)==0:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
fast_tts = TTS(voice_actor, progress_bar=True).to(device)
fast_tts.tts_to_file(text=demo_text , file_path=f"tortoise/_model_demo_voices/{voice_actor}/demo.wav")
reference_files = [os.path.join(f"tortoise/_model_demo_voices/{voice_actor}", file) for file in os.listdir(f"tortoise/_model_demo_voices/{voice_actor}") if file.endswith((".wav", ".mp3"))]
return reference_files
else:
return reference_files
single_voice_actor_folder = f"{voice_actors_folder}{voice_actor}/"
# List all .wav and .mp3 files in the folder
reference_files = [os.path.join(single_voice_actor_folder, file) for file in os.listdir(single_voice_actor_folder) if file.endswith((".wav", ".mp3"))]
return reference_files
# List of language codes and their display names
languages = {
'English': 'en', 'Spanish': 'es', 'French': 'fr', 'German': 'de',
'Italian': 'it', 'Portuguese': 'pt', 'Polish': 'pl', 'Turkish': 'tr',
'Russian': 'ru', 'Dutch': 'nl', 'Czech': 'cs', 'Arabic': 'ar',
'Chinese': 'zh-cn', 'Japanese': 'ja', 'Hungarian': 'hu', 'Korean': 'ko'
}
# Variable to hold the current language selection, default to English
current_language = 'en'
current_model =""
tts = None
STTS = None
def generate_file_ids(csv_file, chapter_delimiter):
data = pd.read_csv(csv_file)
if 'audio_id' not in data.columns:
data['audio_id'] = [''] * len(data)
chapter_num = 0
for index, row in data.iterrows():
text = row['Text'] # Adjust to the correct column name, e.g., 'Text' if it's uppercase in the CSV
print(f"{text}")
if chapter_delimiter in text: # Ensure both are uppercase for case-insensitive matching/edit: nah
chapter_num = chapter_num +1
data.at[index, 'audio_id'] = f"audio_{index}_{chapter_num}"
data.to_csv(csv_file, index=False)
print(f"'audio_id' column has been updated in {csv_file}")
#delim = chapter_delimiter_var.get()
generate_file_ids(csv_file, chapter_delimiter_var.get())
#function to generate audio for fine tuned speakers in xtts
import os
import torch
import torchaudio
from TTS.tts.configs.xtts_config import XttsConfig
from TTS.tts.models.xtts import Xtts
import time
import sys
from styletts2 import tts as stts
# Function to install package using pip
def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
def fineTune_audio_generate(text, file_path, speaker_wav, language, voice_actor):
global current_model
global tts
start_time = time.time() # Record the start time
# Get device
device = "cuda" if torch.cuda.is_available() else "cpu"
# Add here the xtts_config path
CONFIG_PATH = f"tortoise/voices/{voice_actor}/model/config.json"
# Add here the vocab file that you have used to train the model
TOKENIZER_PATH = f"tortoise/voices/{voice_actor}/model/vocab.json_"
# Add here the checkpoint that you want to do inference with
XTTS_CHECKPOINT = f"tortoise/voices/{voice_actor}/model/model.pth"
# Add here the speaker reference
SPEAKER_REFERENCE = speaker_wav
# output wav path
OUTPUT_WAV_PATH = file_path
if current_model != voice_actor:
print(f"found fine tuned for voice actor: {voice_actor}: loading custom model...")
config = XttsConfig()
config.load_json(CONFIG_PATH)
if 'tts' not in locals():
tts = Xtts.init_from_config(config)
tts.load_checkpoint(config, checkpoint_path=XTTS_CHECKPOINT, vocab_path=TOKENIZER_PATH, use_deepspeed=False)
#make sure it runs on cpu or cuda depending on whats avalible on the machine
if device == "cuda":
tts.cuda()
if device == "cpu":
tts.cpu()
current_model = voice_actor
else:
print(f"found fine tuned model for voice actor: {voice_actor} but {voice_actor} model is already loaded")
print("Computing speaker latents...")
gpt_cond_latent, speaker_embedding = tts.get_conditioning_latents(audio_path=[SPEAKER_REFERENCE])
print("Inference...")
out = tts.inference(
text,
language,
gpt_cond_latent,
speaker_embedding,
temperature=0.7, # Add custom parameters here
)
torchaudio.save(OUTPUT_WAV_PATH, torch.tensor(out["wav"]).unsqueeze(0), 24000)
end_time = time.time() # Record the end time
elapsed_time = end_time - start_time
print(f"Time taken for execution: {elapsed_time:.2f} seconds")
def select_tts_model():
models = TTS().list_models() # Fetches all available TTS models
additional_models = ["StyleTTS2"] # Manually add any special or last-minute models here
all_models = models + additional_models # Combine lists
current_model = all_models[0] # Default to the first model in the combined list
while True:
print(f"The TTS model currently selected is {current_model}.")
#response = input("Would you like to keep this model? (yes/no): ").strip().lower()
response = "yes"
if response == 'yes':
return current_model
elif response == 'no':
print("Available models:")
for model in all_models:
print(model)
while True:
selected_model = input("Please type the name of one of the above models: ").strip()
if selected_model in all_models:
current_model = selected_model
break
else:
print("Invalid model. Please select a model from the list.")
else:
print("Please answer 'yes' or 'no'.")
#this code will have the user add a fine tuned xtts modela and also be able to clone a voice in the terminal without a gui
import os
import shutil
from tkinter import filedialog
def clone_new_voice():
while True:
#confirm = input("Do you want to clone a new voice? (yes/no): ").lower()
confirm = "no"
if confirm == 'yes':
voice_actor_name = input("Enter the name of the new voice actor: ")
voice_actor_gender = input("Enter the gender of the new voice actor (M/F/?): ")
new_voice_path = f"tortoise/voices/{voice_actor_name}.{voice_actor_gender}"
if not os.path.exists(new_voice_path):
os.makedirs(new_voice_path)
print(f"New directory created at: {new_voice_path}")
print("Please enter the path to the voice sample file to copy:")
sample_file = input("Enter file path: ")
if os.path.exists(sample_file):
shutil.copy(sample_file, new_voice_path)
print("Sample file copied successfully.")
else:
print("The file does not exist. Please check the path and try again.")
else:
print("Voice actor folder already exists.")
repeat = input("Do you want to clone another new voice? (yes/no): ").lower()
if repeat != 'yes':
break
elif confirm == 'no':
break
else:
print("Please answer 'yes' or 'no'.")
def add_fine_tuned_model():
while True:
#confirm = input("Do you want to add a fine-tuned XTTS model to a voice actor? (yes/no): ").lower()
confirm = "no"
if confirm == 'yes':
base_directory = "tortoise/voices/"
folders = [folder for folder in os.listdir(base_directory) if os.path.isdir(os.path.join(base_directory, folder))]
print("Select a voice actor to add a fine-tuned model to:")
for index, folder in enumerate(folders):
print(f"{index}: {folder}")
selected_index = int(input("Enter the number corresponding to the voice actor: "))
selected_folder = folders[selected_index]
model_path = os.path.join(base_directory, selected_folder, "model")
if not os.path.exists(model_path):
os.makedirs(model_path)
print("Please enter the path to the folder containing fine-tuned XTTS model files to copy from:")
source_folder = input("Enter folder path: ")
if os.path.isdir(source_folder):
for file in os.listdir(source_folder):
source_file = os.path.join(source_folder, file)
destination_file = os.path.join(model_path, file)
shutil.copy2(source_file, destination_file)
print(f"Files copied successfully to {model_path}")
else:
print("The specified directory does not exist. Please check the path and try again.")
repeat = input("Do you want to add another fine-tuned model? (yes/no): ").lower()
if repeat != 'yes':
break
elif confirm == 'no':
break
else:
print("Please answer 'yes' or 'no'.")
def ask_if_user_wants_to_add_fine_tuned_xtts_model_or_clone_a_voice():
while True:
print("\n1. Clone a new voice")
print("2. Add a fine-tuned XTTS model to a voice actor")
print("3. Exit")
#choice = input("Enter your choice: ")
choice = "3"
if choice == '1':
clone_new_voice()
elif choice == '2':
add_fine_tuned_model()
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
#fucntion that will use the terminal to change the default language
def select_language_terminal():
# Default language setting
default_language = "en"
language = default_language
# Ask user to change the language
#change_lang = input(f"Do you want to change the language(Character accent) from {default_language}? (yes/no): ").strip().lower()
change_lang = "no"
if change_lang == "yes":
# List available languages
languages = ['en', 'es', 'fr', 'de', 'it', 'pt', 'pl', 'tr', 'ru', 'nl', 'cs', 'ar', 'zh-cn', 'hu', 'ko', 'ja', 'hi'] # Extend as needed
print("Available languages:")
for i, lang in enumerate(languages):
print(f"{i + 1}. {lang}")
# User selects the language
while True:
try:
choice = int(input("Select a language by number: "))
language = languages[choice - 1]
break
except (IndexError, ValueError):
print("Invalid selection. Please try again.")
# Confirm the selection
confirm = input(f"Confirm changing language to {language}? (yes/no): ").strip().lower()
if confirm == "yes":
print(f"Language set to {language}.")
else:
print("Language change canceled. Using default English.")
language = default_language
else:
print("No language change requested. Using default English.")
return language
# Usage example
#selected_language = select_language_terminal()
#print(f"The selected language for TTS is: {selected_language}")
from tqdm import tqdm
# Function to generate audio for the text
def generate_audio():
ask_if_user_wants_to_add_fine_tuned_xtts_model_or_clone_a_voice()
selected_tts_model = select_tts_model()
#This will ask the user in the terminal if they want to generate all of the audio with only the narrerator's voice
#use_narrator_voice = input("Do you want to generate all audio with the Narrator voice? (yes/no): ").strip().lower()
use_narrator_voice = "no"
while use_narrator_voice not in ['yes', 'no']:
print("Invalid input. Please type 'yes' or 'no'.")
use_narrator_voice = input("Do you want to generate all audio with the Narrator voice? (yes/no): ").strip().lower()
use_narrator_voice = use_narrator_voice == 'yes'
global current_language
current_language = select_language_terminal()
# Get device
start_timez = time.time()
global multi_voice_model_voice_list1
global multi_voice_model_voice_list2
global multi_voice_model_voice_list3
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
global current_model
global STTS
ensure_temp_folder()
# List available TTS models
#print(TTS().list_models())
# Initialize the TTS model and set the device
#tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(device)
# Update the model initialization to use the selected model
#tts = TTS(selected_tts_model, progress_bar=True).to(device)
#fast_tts = TTS(multi_voice_model1, progress_bar=True).to(device)
random.seed(int(time.time()))
ensure_output_folder()
total_rows = len(data)
chapter_num = 0
add_voice_actors_to_csv()
add_languages_to_csv()
for index, row in tqdm(data.iterrows(), total=data.shape[0], desc="Generating AudioBook"):
#update_progress(index, total_rows) # Update progress based on the current index and total rows
speaker = row['Speaker']
text = row['Text']
#update_progress(index, total_rows, text) # Update progress based on the current index and total rows and text
language_code = character_languages.get(speaker, current_language) # Default to 'en' if not found
if calibre_installed:
if "NEWCHAPTERABC" in text:
chapter_num += 1
print(f"chapter num: {chapter_num}")
print(f"CHAPTER KEYWORD IS: NEWCHAPTERABC")
text = text.replace("NEWCHAPTERABC", "")
elif CHAPTER_KEYWORD in text.upper():
chapter_num += 1
print(f"chapter num: {chapter_num}")
print(f"CHAPTER KEYWORD IS: {CHAPTER_KEYWORD}")
#This is the code for grabbing the current voice actor
#This will make it so that if the button for single voice is checked in the gui then the voice actor is always the narrerators:
if use_narrator_voice:
print(f"All audio is being generated with the Narrator voice.")
voice_actor = speaker_voice_map.get("Narrator")
else:
voice_actor = speaker_voice_map[speaker]
#voice_actor = speaker_voice_map[speaker]
sentences = sent_tokenize(text)
audio_tensors = []
temp_count =0
for sentence in sentences:
fragments = split_long_sentence(sentence)
for fragment in fragments:
# Check if the selected model is multilingual
if 'multilingual' in selected_tts_model:
language_code = character_languages.get(speaker, current_language)
else:
language_code = None # No language specification for non-multilingual models
print(f"Voice actor: {voice_actor}, {current_language}")
temp_count = temp_count +1
# Use the model and language code to generate the audio
#tts = TTS(model_name="tts_models/en/ek1/tacotron2", progress_bar=False).to(device)
#tts.tts_to_file(fragment, speaker_wav=list_reference_files(voice_actor), progress_bar=True, file_path=f"Working_files/temp/{temp_count}.wav")
#this will make it so that if your selecting a model as a voice actor name then itll initalize the voice actor name as the model
if voice_actor in multi_voice_model_voice_list1:
print(f"{voice_actor} is a fast model voice: {multi_voice_model1}")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if current_model != multi_voice_model1:
fast_tts = TTS(multi_voice_model1, progress_bar=True).to("cpu")
current_model = multi_voice_model1
print(f"The model used in fast_tts has been changed to {current_model}")
fast_tts.tts_to_file(text=fragment, file_path=f"Working_files/temp/{temp_count}.wav", speaker=voice_actor)
elif voice_actor in multi_voice_model_voice_list2:
print(f"{voice_actor} is a fast model voice: {multi_voice_model2}")
if current_model != multi_voice_model2:
fast_tts = TTS(multi_voice_model2, progress_bar=True).to("cpu")
current_model = multi_voice_model2
print(f"The model used in fast_tts has been changed to {current_model}")
fast_tts.tts_to_file(text=fragment, file_path=f"Working_files/temp/{temp_count}.wav", speaker=voice_actor)
elif voice_actor in multi_voice_model_voice_list3:
print(f"{voice_actor} is a fast model voice: {multi_voice_model3}")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if current_model != multi_voice_model3:
fast_tts = TTS(multi_voice_model3, progress_bar=True).to("cpu")
current_model = multi_voice_model3
print(f"The model used in fast_tts has been changed to {current_model}")
fast_tts.tts_to_file(text=fragment, file_path=f"Working_files/temp/{temp_count}.wav", speaker=voice_actor)
elif "tts_models" in voice_actor and "multi-dataset" not in voice_actor:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if current_model != voice_actor:
fast_tts = TTS(voice_actor, progress_bar=True).to(device)
current_model = voice_actor
print(f"The model used in fast_tts has been changed to {current_model}")
#selected_tts_model = voice_actor
#"Model is multi-lingual but no `language` is provided."
print(f"Model for this character has been switched to: {voice_actor} by user")
try:
fast_tts.tts_to_file(text=fragment, file_path=f"Working_files/temp/{temp_count}.wav")
except ValueError as e:
if str(e) == "Model is multi-lingual but no `language` is provided.":
print("attempting to correct....")
fast_tts.tts_to_file(text=fragment, file_path=f"Working_files/temp/{temp_count}.wav",language=language_code)
print("Successfully Corrected!")
#else:
# print(f"{voice_actor} is neither multi-dataset nor multilingual")
# tts.tts_to_file(text=fragment,file_path=f"Working_files/temp/{temp_count}.wav") # Assuming the tts_to_file function has default arguments for unspecified parameters
#If the voice actor has a custom fine tuned xtts model in its refrence folder ie if it has the model folder containing it
elif os.path.exists(f"tortoise/voices/{voice_actor}/model") and os.path.isdir(f"tortoise/voices/{voice_actor}/model") and 'xtts' in selected_tts_model:
speaker_wavz=list_reference_files(voice_actor)
fineTune_audio_generate(text=fragment, file_path=f"Working_files/temp/{temp_count}.wav", speaker_wav=speaker_wavz[0], language=language_code, voice_actor=voice_actor)
# If the model contains both "multilingual" and "multi-dataset"
elif "multilingual" in selected_tts_model and "multi-dataset" in selected_tts_model:
if 'tts' not in locals():
tts = TTS(selected_tts_model, progress_bar=True).to(device)
try:
if "bark" in selected_tts_model:
print(f"{selected_tts_model} is bark so multilingual but has no language code")
#device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#tts = TTS(selected_tts_model, progress_bar=True).to(device)
tts.tts_to_file(text=fragment, file_path=f"Working_files/temp/{temp_count}.wav", speaker_wav=list_reference_files(voice_actor))
else:
print(f"{selected_tts_model} is multi-dataset and multilingual")
#device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#tts = TTS(selected_tts_model, progress_bar=True).to(device)
tts.tts_to_file(text=fragment, file_path=f"Working_files/temp/{temp_count}.wav", speaker_wav=list_reference_files(voice_actor), language=language_code)
except ValueError as e:
if str(e) == "Model is not multi-lingual but `language` is provided.":
print("Caught ValueError: Model is not multi-lingual. Ignoring the language parameter.")
#device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#tts = TTS(selected_tts_model, progress_bar=True).to(device)
tts.tts_to_file(text=fragment, file_path=f"Working_files/temp/{temp_count}.wav", speaker_wav=list_reference_files(voice_actor))
# If the model only contains "multilingual"
elif "multilingual" in selected_tts_model:
print(f"{selected_tts_model} is multilingual")
#device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#tts = TTS(selected_tts_model, progress_bar=True).to(device)
if 'tts' not in locals():
tts = TTS(selected_tts_model, progress_bar=True).to(device)
tts.tts_to_file(text=fragment, file_path=f"Working_files/temp/{temp_count}.wav", language=language_code)
# If the model only contains "multi-dataset"
elif "multi-dataset" in selected_tts_model:
print(f"{selected_tts_model} is multi-dataset")
#device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#tts = TTS(selected_tts_model, progress_bar=True).to(device)
if 'tts' not in locals():
tts = TTS(selected_tts_model, progress_bar=True).to(device)
tts.tts_to_file(text=fragment, file_path=f"Working_files/temp/{temp_count}.wav")
elif 'StyleTTS2' in selected_tts_model:
print(f'{selected_tts_model} model is selected for voice cloning')
if 'STTS' not in locals():
STTS = stts.StyleTTS2()
STTS.inference(fragment, target_voice_path=list_reference_files(voice_actor)[0], output_wav_file=f"Working_files/temp/{temp_count}.wav")
#if the model selected is one of the fast voice clone models as in not really voice clone but use voice transfer
#right now im setting all of the fast voice cloning to be run on the cpu come can only be run on cpu and I'm lazy rn lol
elif selected_tts_model in fast_voice_clone_models_dict:
print(f"Using voice conversion voice cloning method and the selected model for this is {selected_tts_model}")
#device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if current_model != selected_tts_model:
if "tts" not in locals():
#tts = TTS(selected_tts_model).to(device)
tts = TTS(selected_tts_model).to("cpu")
current_model = selected_tts_model
try:
tts.tts_with_vc_to_file(
fragment,
speaker_wav=list_reference_files(voice_actor)[0],
file_path=f"Working_files/temp/{temp_count}.wav",
speaker=fast_voice_clone_models_dict[selected_tts_model]
)
except Exception as e:
print(f"An error occurred but was ignored: {e}")
print("But continuing anyway but you should probs look at that error: its probably that the input for the tts model is too short so idk find a way to fix it if it runs into an issue like this:")
# If the model contains neither "multilingual" nor "multi-dataset"
else:
print(f"{selected_tts_model} is neither multi-dataset nor multilingual")
#device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#tts = TTS(selected_tts_model, progress_bar=True).to(device)
if 'tts' not in locals():
tts = TTS(selected_tts_model, progress_bar=True).to(device)
tts.tts_to_file(text=fragment,file_path=f"Working_files/temp/{temp_count}.wav") # Assuming the tts_to_file function has default arguments for unspecified parameters
temp_input_directory = "Working_files/temp" # Replace with the actual input directory path
output_directory = "Working_files/generated_audio_clips" # Replace with the desired output directory path
combine_wav_files(temp_input_directory, output_directory, f"audio_{index}_{chapter_num}.wav")
wipe_folder("Working_files/temp")
end_timez = time.time()
durationz = end_timez - start_timez
print("GENERATION TIME:" + str(durationz))
#root.destroy()
from functools import partial
def format_time(seconds):
"""
Formats time in seconds to a more readable string with minutes, hours, days, and years if applicable.
"""
minute = 60
hour = minute * 60
day = hour * 24
year = day * 365
years = seconds // year
seconds %= year
days = seconds // day
seconds %= day
hours = seconds // hour
seconds %= hour
minutes = seconds // minute
seconds %= minute
time_string = ""
if years > 0:
time_string += f"{years:.0f} year{'s' if years > 1 else ''} "
if days > 0:
time_string += f"{days:.0f} day{'s' if days > 1 else ''} "
if hours > 0:
time_string += f"{hours:.0f} hour{'s' if hours > 1 else ''} "
if minutes > 0:
time_string += f"{minutes:.0f} min "
time_string += f"{seconds:.0f} sec"
return time_string.strip()
def update_progress(index, total, row_text):
current_time = time.time()
# Calculate elapsed time
elapsed_time = current_time - start_time
# Update total characters processed and count of processed rows
global total_chars_processed, processed_rows_count
total_chars_processed += len(row_text)
processed_rows_count += 1
# Calculate progress
progress = (index + 1) / total * 100
# Estimate remaining time
if processed_rows_count > 0: # Avoid division by zero
average_chars_per_row = total_chars_processed / processed_rows_count
estimated_chars_remaining = average_chars_per_row * (total - processed_rows_count)
average_time_per_char = elapsed_time / total_chars_processed
estimated_time_remaining = average_time_per_char * estimated_chars_remaining
remaining_time_string = format_time(estimated_time_remaining)
else:
remaining_time_string = "Calculating..."
# Update progress label with estimated time
progress_label.config(text=f"{progress:.2f}% done ({index+1}/{total} rows) - {remaining_time_string}")
root.update_idletasks()
# Start time capture and initialize counters
start_time = time.time()
total_chars_processed = 0
processed_rows_count = 0
def create_scrollable_frame(parent, height):
# Create a canvas with a specific height
canvas = tk.Canvas(parent, height=height)
scrollbar = ttk.Scrollbar(parent, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas)
canvas.configure(yscrollcommand=scrollbar.set)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
)
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
return scrollable_frame
def update_chapter_keyword(*args):
global CHAPTER_KEYWORD
CHAPTER_KEYWORD = chapter_delimiter_var.get()
# Add a trace to call update_chapter_keyword whenever the value changes
chapter_delimiter_var.trace_add("write", update_chapter_keyword)
## Frame for Language Selection Dropdown
#language_selection_frame = ttk.LabelFrame(root, text="Select TTS Language")
#language_selection_frame.pack(fill="x", expand="yes", padx=10, pady=10)
## Create a dropdown for language selection
#language_var = tk.StringVar()
#language_combobox = ttk.Combobox(language_selection_frame, textvariable=language_var, state="readonly")
#language_combobox['values'] = list(languages.keys()) # Use the display names for the user
#language_combobox.set('English') # Set default value
#def on_language_selected(event):
# global current_language
# # Update the current_language variable based on selection
# current_language = languages[language_combobox.get()]
# print(f"current language updated to: {current_language}")
#language_combobox.bind("<<ComboboxSelected>>", on_language_selected)
#language_combobox.pack(side="top", fill="x", expand="yes")
#fuck
## Progress Bar
#progress_var = tk.DoubleVar()
#progress_bar = ttk.Progressbar(root, variable=progress_var, maximum=100)
#progress_bar.pack()
#progress_label = ttk.Label(root, text="0% done")
#progress_label.pack()
## Create a frame to contain the buttons
#buttons_frame = ttk.Frame(root)
#buttons_frame.pack(pady=10)
## Generate Audio Button
#generate_button = ttk.Button(buttons_frame, text="Generate Audio", command=lambda: threading.Thread(target=generate_audio).start())
#generate_button.pack(side=tk.LEFT, padx=5)
#root.mainloop()
generate_audio()
#this code here will make sure the folder where all the chapter audio files go i whiped before it starts creating the chapter files cause there might be stuff from the last session
import os
import shutil
def wipe_folder(folder_path):
if os.path.exists(folder_path) and os.path.isdir(folder_path):
print(f"Folder '{folder_path}' found. Proceeding to wipe...")
shutil.rmtree(folder_path)
print(f"Folder '{folder_path}' has been wiped.")
else:
print(f"Folder '{folder_path}' does not exist. No action taken.")
# Usage
folder_to_wipe = "Final_combined_output_audio"
wipe_folder(folder_to_wipe)
#this code here will combined all the tiny generated audio files into chapter audio files
import os
import pandas as pd
import torch
import torchaudio
import pygame
colors = ['#FFB6C1', '#ADD8E6', '#FFDAB9', '#98FB98', '#D8BFD8']
speaker_colors = {}
currently_playing = None
INPUT_FOLDER = "Working_files/generated_audio_clips"
OUTPUT_FOLDER = "Final_combined_output_audio"
#marked out cause its not defined earlier on in the code in the field
#SILENCE_DURATION_MS = 0
try:
pygame.mixer.init()
print("mixer modual initialized successfully.")
except pygame.error:
print("mixer modual initialization failed")
print(pygame.error)
def combine_audio_files(silence_duration_ms):
folder_path = os.path.join(os.getcwd(), INPUT_FOLDER)
files = sorted([f for f in os.listdir(folder_path) if f.startswith("audio_") and f.endswith(".wav")],
key=lambda f: (int(f.split('_')[2].split('.')[0]), int(f.split('_')[1].split('.')[0])))
chapter_files = {}
for file in files:
chapter_num = int(file.split('_')[2].split('.')[0])
if chapter_num not in chapter_files:
chapter_files[chapter_num] = []
chapter_files[chapter_num].append(file)
for chapter_num, chapter_file_list in chapter_files.items():
combined_tensor = torch.Tensor()
for index, file in enumerate(chapter_file_list):
waveform, sample_rate = torchaudio.load(os.path.join(folder_path, file))
channels = waveform.shape[0]
silence_tensor = torch.zeros(channels, int(silence_duration_ms * sample_rate / 1000))
combined_tensor = torch.cat([combined_tensor, waveform, silence_tensor], dim=1)
print(f"Processing Chapter {chapter_num} - File {index + 1}/{len(chapter_file_list)}: {file}")
if not os.path.exists(os.path.join(os.getcwd(), OUTPUT_FOLDER)):
os.makedirs(os.path.join(os.getcwd(), OUTPUT_FOLDER))
output_path = os.path.join(os.getcwd(), OUTPUT_FOLDER, f"chapter_{chapter_num}.wav")
torchaudio.save(output_path, combined_tensor, sample_rate)
print("Combining audio files complete!")
combine_audio_files(SILENCE_DURATION_MS)
#this code here will create the actual nicely formatted m4b file with chapters and image metadata and everything located at output audiobook
import os
import subprocess
from pydub import AudioSegment
import shlex
def sort_chapters(file):
# Extract chapter number from the filename
number_part = re.findall(r'\d+', file)
if number_part:
return int(number_part[0])
return 0
def extract_ebook_metadata(ebook_file):
try:
metadata_cmd = ['ebook-meta', ebook_file]
metadata_output = subprocess.run(metadata_cmd, capture_output=True, text=True).stdout
metadata = {}
# Extracting various metadata fields
for line in metadata_output.splitlines():
if ':' in line:
key, value = line.split(':', 1)
metadata[key.strip()] = value.strip()
# Extracting the cover image
output_image = os.path.join('/tmp', os.path.basename(ebook_file) + '.jpg')
subprocess.run(['ebook-meta', ebook_file, '--get-cover', output_image], check=True)
if not os.path.exists(output_image):
output_image = None
return output_image, metadata
except Exception as e:
print(f"Error extracting eBook metadata: {e}")
return None, {}
def generate_chapter_metadata(wav_files, metadata_filename):
with open(metadata_filename, 'w') as file:
file.write(";FFMETADATA1\n")
start_time = 0
for index, wav_file in enumerate(wav_files):
duration = len(AudioSegment.from_wav(wav_file))
end_time = start_time + duration
file.write(f"[CHAPTER]\nTIMEBASE=1/1000\nSTART={start_time}\nEND={end_time}\ntitle=Chapter {index+1:02d}\n")
start_time = end_time
def combine_wav_to_m4b_ffmpeg(wav_files, m4b_filename, cover_image, metadata_filename, metadata):
print("Combining WAV files into an M4B audiobook using FFmpeg...")
with open('file_list.txt', 'w') as file:
for wav_file in wav_files:
file.write(f"file '{shlex.quote(wav_file)}'\n")
ffmpeg_cmd = f"ffmpeg -f concat -safe 0 -i file_list.txt -c copy combined.wav"
ffmpeg_cmd += f" && ffmpeg -i combined.wav -i {shlex.quote(metadata_filename)}"
if cover_image:
ffmpeg_cmd += f" -i {shlex.quote(cover_image)}"
for key, value in metadata.items():
ffmpeg_cmd += f" -metadata {key}=\"{value}\""
ffmpeg_cmd += f" -map_metadata 1"
if cover_image:
ffmpeg_cmd += f" -map 0 -map 2"
ffmpeg_cmd += f" -c:a aac -b:a 192k"
if cover_image:
ffmpeg_cmd += f" -c:v copy -disposition:v:0 attached_pic"
ffmpeg_cmd += f" {shlex.quote(m4b_filename)}"
os.system(ffmpeg_cmd)
print(f"M4B audiobook created: {m4b_filename}")
# Cleanup
os.remove('file_list.txt')
if os.path.exists('combined.wav'):
os.remove('combined.wav')
os.remove(metadata_filename)
if cover_image and os.path.exists(cover_image):
os.remove(cover_image)
def convert_all_wav_to_m4b(input_dir, ebook_file, output_dir, audiobook_name):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
print(f"Created output directory: {output_dir}")
cover_image, ebook_metadata = extract_ebook_metadata(ebook_file)
wav_files = [os.path.join(input_dir, f) for f in os.listdir(input_dir) if f.endswith('.wav')]
wav_files.sort(key=sort_chapters)
m4b_filename = os.path.join(output_dir, f'{audiobook_name}.m4b')
metadata_filename = 'chapter_metadata.txt'
# Setting up the metadata
metadata = {
'artist': ebook_metadata.get('Author(s)', 'Unknown Author'),
'album': ebook_metadata.get('Series', 'Unknown Series'),
'Title': ebook_metadata.get('Title', f'{audiobook_name}.m4b'),
'date': ebook_metadata.get('Published', 'Unknown Year'),
'Genre': ebook_metadata.get('Tags', 'Unknown Genre'),
'Comment': ebook_metadata.get('Tags', 'No description available.'),
# Add other metadata fields as needed
}
m4b_filename = ebook_metadata.get('Title', f"audiobook_name")
m4b_filename = os.path.join(output_dir, f'{m4b_filename}.m4b')
generate_chapter_metadata(wav_files, metadata_filename)
combine_wav_to_m4b_ffmpeg(wav_files, m4b_filename, cover_image, metadata_filename, metadata)
# Example usage
input_dir = "Final_combined_output_audio" # Update this path to your WAV files folder
ebook_file = ebook_file_path # Update this path to your eBook file
output_dir = 'output_audiobooks'
audiobook_name = os.path.splitext(os.path.basename(ebook_file))[0] # Update this path to your desired output directory
convert_all_wav_to_m4b(input_dir, ebook_file, output_dir, audiobook_name)
#this will convert all the audio files into a mp4 format instead of wav to save space
#at the same time it will also delete the wav files as it converts them
from moviepy.editor import *
def convert_wav_to_mp4(wav_filename, mp4_filename):
audio = AudioFileClip(wav_filename)
audio.write_audiofile(mp4_filename, codec='aac')
def convert_all_wav_to_mp4():
output_dir = "Final_combined_output_audio"
wav_files = [f for f in os.listdir(output_dir) if f.endswith('.wav')]
for wav_file in wav_files:
wav_filename = os.path.join(output_dir, wav_file)
mp4_filename = os.path.join(output_dir, wav_file.replace('.wav', '.mp4'))
convert_wav_to_mp4(wav_filename, mp4_filename)
print(f"{wav_filename} has been converted to {mp4_filename}.")
os.remove(wav_filename)
print(f"{wav_filename} as been deleted.")
convert_all_wav_to_mp4()
#this will add the cover of the epub file to the mp4 combined files
print("Adding Book Artwork to mp4 chatper files if calibre is installed")
import os
import subprocess
def extract_cover_image_calibre(ebook_file):
"""
Extracts the cover image from an eBook file using Calibre's ebook-meta tool.
Args:
ebook_file (str): The path to the eBook file.
Returns:
str: The path to the extracted cover image or None if not found.
"""
output_image = os.path.join('/tmp', os.path.basename(ebook_file) + '.jpg')
try:
subprocess.run(['ebook-meta', ebook_file, '--get-cover', output_image], check=True)
if os.path.exists(output_image):
return output_image
else:
return None
except Exception as e:
print(f"Error extracting cover image: {e}")
return None
def set_cover_to_mp4(cover_image, mp4_folder):
"""
Sets the extracted cover image to all mp4 files in a specified folder.
Args:
cover_image (str): The path to the cover image.
mp4_folder (str): The path to the folder containing mp4 files.
"""
if not cover_image or not os.path.exists(cover_image):
print("Cover image not found.")
return
# Process each mp4 file in the folder
for file in os.listdir(mp4_folder):
if file.lower().endswith('.mp4'):
mp4_path = os.path.join(mp4_folder, file)
# Set the cover image for the mp4 file
# Note: Requires ffmpeg
os.system(f'ffmpeg -i "{mp4_path}" -i "{cover_image}" -map 0 -map 1 -c copy -disposition:v:1 attached_pic "{mp4_path}.temp.mp4"')
os.rename(f"{mp4_path}.temp.mp4", mp4_path)
# Example usage
ebook_file = ebook_file_path # Update this path to your eBook file
mp4_folder = OUTPUT_FOLDER # Update this path to your MP4 folder
#if calibre is installed then set the cover image things
# Extract cover image from the eBook file
cover_image = extract_cover_image_calibre(ebook_file)
# Set cover image to all mp4 files in the specified folder
set_cover_to_mp4(cover_image, mp4_folder)
|