Spaces:
Running
Running
File size: 113,895 Bytes
625078a f1a53c8 625078a f1a53c8 625078a 6604393 81b2ada a81bc54 6604393 81b2ada a81bc54 6604393 61ae973 81b2ada a81bc54 61ae973 a81bc54 61ae973 a81bc54 f1a53c8 61ae973 f1a53c8 81b2ada f1a53c8 81b2ada f1a53c8 61ae973 f1a53c8 81b2ada f1a53c8 61ae973 f1a53c8 8acb643 f1a53c8 61ae973 f1a53c8 81b2ada 596c9c5 81b2ada f1a53c8 a81bc54 f1a53c8 a81bc54 61ae973 f1a53c8 a81bc54 f1a53c8 81b2ada f1a53c8 81b2ada f1a53c8 596c9c5 f1a53c8 61ae973 75c3035 f1a53c8 596c9c5 f1a53c8 61ae973 81b2ada 61ae973 f1a53c8 596c9c5 f1a53c8 61ae973 f1a53c8 61ae973 f1a53c8 75c3035 f1a53c8 61ae973 f1a53c8 75c3035 f1a53c8 a14346c 596c9c5 75c3035 a14346c 61ae973 75c3035 a14346c 6604393 a14346c 596c9c5 61ae973 596c9c5 a14346c 75c3035 a14346c 596c9c5 75c3035 f1a53c8 a14346c f1a53c8 81b2ada f1a53c8 a14346c 6d93c4e 75c3035 f1a53c8 81b2ada f1a53c8 625078a 81b2ada 625078a a81bc54 625078a 81b2ada a81bc54 625078a f1a53c8 81b2ada 625078a a81bc54 625078a 61ae973 625078a 61ae973 625078a 61ae973 625078a 61ae973 625078a 596c9c5 61ae973 625078a 596c9c5 625078a 61ae973 625078a 61ae973 625078a 61ae973 625078a 596c9c5 61ae973 625078a 596c9c5 625078a 61ae973 625078a 61ae973 625078a 61ae973 625078a 61ae973 625078a 61ae973 625078a 61ae973 625078a 61ae973 625078a 61ae973 625078a 61ae973 625078a 61ae973 625078a 61ae973 596c9c5 625078a 61ae973 625078a a14346c 6604393 06baaa1 625078a 06baaa1 61ae973 06baaa1 625078a 06baaa1 61ae973 625078a 61ae973 625078a a14346c 6604393 06baaa1 625078a 06baaa1 61ae973 06baaa1 625078a 06baaa1 61ae973 625078a a14346c 625078a a14346c 625078a 61ae973 6604393 625078a a14346c 61ae973 625078a 61ae973 6604393 625078a a14346c 61ae973 625078a 75c3035 625078a a81bc54 625078a a81bc54 625078a 06baaa1 61ae973 06baaa1 61ae973 06baaa1 625078a 61ae973 75c3035 61ae973 596c9c5 61ae973 06baaa1 625078a 06baaa1 625078a 06baaa1 625078a 61ae973 625078a 596c9c5 625078a 06baaa1 625078a 596c9c5 06baaa1 596c9c5 625078a 596c9c5 06baaa1 596c9c5 61ae973 06baaa1 61ae973 06baaa1 61ae973 06baaa1 61ae973 06baaa1 625078a 75c3035 625078a 596c9c5 61ae973 75c3035 625078a 596c9c5 61ae973 596c9c5 61ae973 596c9c5 61ae973 596c9c5 625078a 596c9c5 61ae973 75c3035 625078a 596c9c5 61ae973 596c9c5 61ae973 596c9c5 61ae973 596c9c5 625078a 75c3035 625078a 596c9c5 625078a 61ae973 625078a 61ae973 625078a 596c9c5 61ae973 625078a 61ae973 625078a 596c9c5 7651773 61ae973 596c9c5 625078a 596c9c5 61ae973 596c9c5 61ae973 596c9c5 75c3035 625078a 596c9c5 625078a 61ae973 625078a 61ae973 625078a 596c9c5 61ae973 625078a 61ae973 625078a 596c9c5 7651773 61ae973 596c9c5 625078a 596c9c5 61ae973 596c9c5 61ae973 596c9c5 75c3035 7651773 625078a f1a53c8 75c3035 e649258 625078a a14346c 625078a f1a53c8 75c3035 f1a53c8 75c3035 f1a53c8 75c3035 a14346c 625078a f1a53c8 625078a f1a53c8 625078a e649258 75c3035 625078a e649258 625078a 81b2ada f1a53c8 625078a a81bc54 f1a53c8 625078a f1a53c8 75c3035 625078a a81bc54 75c3035 a81bc54 f1a53c8 625078a a81bc54 625078a f1a53c8 a81bc54 625078a f1a53c8 625078a f1a53c8 75c3035 f1a53c8 61ae973 625078a 596c9c5 75c3035 596c9c5 75c3035 61ae973 596c9c5 0473b36 75c3035 0473b36 a14346c 0473b36 625078a e649258 75c3035 e649258 625078a 81b2ada f1a53c8 625078a f1a53c8 75c3035 f1a53c8 75c3035 f1a53c8 75c3035 f1a53c8 a14346c f1a53c8 e649258 f1a53c8 e649258 f1a53c8 625078a 61ae973 75c3035 f1a53c8 625078a 75c3035 625078a 75c3035 625078a 75c3035 61ae973 75c3035 61ae973 75c3035 61ae973 75c3035 7651773 625078a 61ae973 75c3035 e649258 61ae973 75c3035 61ae973 75c3035 625078a 75c3035 625078a 81b2ada 625078a 75c3035 625078a 75c3035 625078a 7651773 61ae973 7651773 61ae973 7651773 61ae973 7651773 61ae973 7651773 f1a53c8 6f6b5f6 81b2ada 6f6b5f6 81b2ada 6f6b5f6 f1a53c8 75c3035 f1a53c8 aa05286 75c3035 aa05286 75c3035 f1a53c8 75c3035 f1a53c8 61ae973 0473b36 61ae973 75c3035 0473b36 625078a 75c3035 e649258 75c3035 6604393 625078a 596c9c5 625078a e649258 75c3035 e649258 0473b36 e649258 596c9c5 61ae973 e649258 0473b36 e649258 75c3035 0473b36 75c3035 e649258 75c3035 e649258 75c3035 e649258 75c3035 596c9c5 0473b36 625078a e649258 75c3035 625078a 75c3035 625078a 75c3035 625078a e649258 75c3035 625078a 61ae973 75c3035 61ae973 0473b36 75c3035 e649258 75c3035 61ae973 e649258 0473b36 75c3035 0473b36 75c3035 e649258 75c3035 e649258 75c3035 e649258 625078a aa05286 625078a f1a53c8 7651773 6d93c4e 7651773 6d93c4e 7651773 6d93c4e 7651773 e649258 7651773 6d93c4e 7651773 6d93c4e 7651773 6d93c4e a81bc54 61ae973 6604393 625078a 61ae973 625078a e649258 61ae973 e649258 75c3035 625078a f1a53c8 625078a 75c3035 a81bc54 625078a f1a53c8 61ae973 625078a 7651773 625078a e649258 625078a 61ae973 625078a e649258 625078a f1a53c8 6f6b5f6 81b2ada 6f6b5f6 f1a53c8 61ae973 aa05286 61ae973 0473b36 625078a 75c3035 aa05286 e649258 aa05286 625078a f1a53c8 75c3035 61ae973 aa05286 61ae973 75c3035 f1a53c8 625078a 75c3035 6d93c4e aa05286 75c3035 0473b36 75c3035 625078a 61ae973 625078a 75c3035 625078a 75c3035 625078a aa05286 625078a f1a53c8 aa05286 0473b36 e649258 0473b36 7651773 0473b36 e649258 7651773 625078a 06baaa1 61ae973 625078a 81b2ada a81bc54 6f6b5f6 61ae973 625078a |
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 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 |
import gradio as gr
import os
import json
import requests
from datetime import datetime
import time
from typing import List, Dict, Any, Generator, Tuple, Optional
import logging
import re
import tempfile
from pathlib import Path
import sqlite3
import hashlib
import threading
from contextlib import contextmanager
# λ‘κΉ
μ€μ
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Document export imports
try:
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
DOCX_AVAILABLE = True
except ImportError:
DOCX_AVAILABLE = False
logger.warning("python-docx not installed. DOCX export will be disabled.")
# νκ²½ λ³μμμ ν ν° κ°μ Έμ€κΈ°
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "")
BRAVE_SEARCH_API_KEY = os.getenv("BRAVE_SEARCH_API_KEY", "")
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
MODEL_ID = "dep89a2fld32mcm"
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
# νκ²½ λ³μ κ²μ¦
if not FRIENDLI_TOKEN and not TEST_MODE:
logger.warning("FRIENDLI_TOKEN not set and TEST_MODE is false. Application will run in test mode.")
TEST_MODE = True
if not BRAVE_SEARCH_API_KEY:
logger.warning("BRAVE_SEARCH_API_KEY not set. Web search features will be disabled.")
# μ μ λ³μ
conversation_history = []
selected_language = "English" # κΈ°λ³Έ μΈμ΄
# DB κ²½λ‘
DB_PATH = "novel_sessions.db"
db_lock = threading.Lock()
# Stage λ²νΈ μμ - 10λͺ
μ μκ°λ‘ λ³κ²½
WRITER_DRAFT_STAGES = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30] # μκ° μ΄μ
WRITER_REVISION_STAGES = [5, 8, 11, 14, 17, 20, 23, 26, 29, 32] # μκ° μμ λ³Έ
TOTAL_WRITERS = 10 # μ΄ μκ° μ
class WebSearchIntegration:
"""Brave Search API integration for research"""
def __init__(self):
self.brave_api_key = BRAVE_SEARCH_API_KEY
self.search_url = "https://api.search.brave.com/res/v1/web/search"
self.enabled = bool(self.brave_api_key)
def search(self, query: str, count: int = 5, language: str = "en") -> List[Dict]:
"""Perform web search using Brave Search API"""
if not self.enabled:
return []
headers = {
"Accept": "application/json",
"X-Subscription-Token": self.brave_api_key
}
# μΈμ΄μ λ°λ₯Έ κ²μ μ€μ
search_lang = "ko" if language == "Korean" else "en"
params = {
"q": query,
"count": count,
"search_lang": search_lang,
"text_decorations": False,
"safesearch": "moderate"
}
try:
response = requests.get(self.search_url, headers=headers, params=params, timeout=10)
if response.status_code == 200:
results = response.json()
web_results = results.get("web", {}).get("results", [])
logger.info(f"Search successful: Found {len(web_results)} results for '{query}'")
return web_results
else:
logger.error(f"Search API error: {response.status_code}")
return []
except Exception as e:
logger.error(f"Search error: {str(e)}")
return []
def extract_relevant_info(self, results: List[Dict], max_chars: int = 3000) -> str:
"""Extract relevant information from search results"""
if not results:
return ""
extracted = []
total_chars = 0
for i, result in enumerate(results[:5], 1): # μ΅λ 5κ° κ²°κ³Ό
title = result.get("title", "")
description = result.get("description", "")
url = result.get("url", "")
# μΌλΆ λ΄μ© μΆμΆ
extra_text = ""
if "extra_snippets" in result:
extra_text = " ".join(result["extra_snippets"][:2])
info = f"""[{i}] {title}
{description}
{extra_text}
Source: {url}
"""
if total_chars + len(info) < max_chars:
extracted.append(info)
total_chars += len(info)
else:
break
return "\n---\n".join(extracted)
def create_research_queries(self, topic: str, role: str, stage_info: Dict, language: str = "English") -> List[str]:
"""Create multiple research queries based on role and context"""
queries = []
if language == "Korean":
if role == "director":
queries = [
f"{topic} μμ€ λ°°κ²½ μ€μ ",
f"{topic} μμ¬μ μ¬μ€",
f"{topic} λ¬Ένμ νΉμ§"
]
elif role.startswith("writer"):
writer_num = int(role.replace("writer", ""))
if writer_num <= 3: # μ΄λ°λΆ μκ°
queries = [
f"{topic} ꡬ체μ μ₯λ©΄ λ¬μ¬",
f"{topic} μ λ¬Έ μ©μ΄ μ€λͺ
"
]
elif writer_num <= 6: # μ€λ°λΆ μκ°
queries = [
f"{topic} κ°λ± μν© μ¬λ‘",
f"{topic} μ¬λ¦¬μ μΈ‘λ©΄"
]
else: # νλ°λΆ μκ°
queries = [
f"{topic} ν΄κ²° λ°©λ²",
f"{topic} κ°λμ μΈ μ¬λ‘"
]
elif role == "critic":
queries = [
f"{topic} λ¬Έν μν λΆμ",
f"{topic} μ μ¬ μμ€ μΆμ²"
]
else:
if role == "director":
queries = [
f"{topic} novel setting ideas",
f"{topic} historical facts",
f"{topic} cultural aspects"
]
elif role.startswith("writer"):
writer_num = int(role.replace("writer", ""))
if writer_num <= 3: # Early writers
queries = [
f"{topic} vivid scene descriptions",
f"{topic} technical terminology explained"
]
elif writer_num <= 6: # Middle writers
queries = [
f"{topic} conflict scenarios",
f"{topic} psychological aspects"
]
else: # Later writers
queries = [
f"{topic} resolution methods",
f"{topic} emotional stories"
]
elif role == "critic":
queries = [
f"{topic} literary analysis",
f"{topic} similar novels recommendations"
]
return queries
class NovelDatabase:
"""Novel session management database with enhanced recovery features"""
@staticmethod
def init_db():
"""Initialize database tables with WAL mode for better concurrency"""
with sqlite3.connect(DB_PATH) as conn:
# Enable WAL mode for better concurrent access
conn.execute("PRAGMA journal_mode=WAL")
cursor = conn.cursor()
# Sessions table with enhanced recovery fields
cursor.execute('''
CREATE TABLE IF NOT EXISTS sessions (
session_id TEXT PRIMARY KEY,
user_query TEXT NOT NULL,
language TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now')),
status TEXT DEFAULT 'active',
current_stage INTEGER DEFAULT 0,
last_saved_stage INTEGER DEFAULT -1,
recovery_data TEXT,
final_novel TEXT
)
''')
# Stages table - κ° μ€ν
μ΄μ§μ μ 체 λ΄μ© μ μ₯
cursor.execute('''
CREATE TABLE IF NOT EXISTS stages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
stage_number INTEGER NOT NULL,
stage_name TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT,
word_count INTEGER DEFAULT 0,
status TEXT DEFAULT 'pending',
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
UNIQUE(session_id, stage_number)
)
''')
# Search history table - κ²μ μ΄λ ₯ μ μ₯
cursor.execute('''
CREATE TABLE IF NOT EXISTS search_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
stage_number INTEGER NOT NULL,
role TEXT NOT NULL,
query TEXT NOT NULL,
results TEXT,
created_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES sessions(session_id)
)
''')
# Create indices
cursor.execute('CREATE INDEX IF NOT EXISTS idx_session_id ON stages(session_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_stage_number ON stages(stage_number)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_search_session ON search_history(session_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_session_status ON sessions(status)')
conn.commit()
@staticmethod
def save_search_history(session_id: str, stage_number: int, role: str, query: str, results: str):
"""Save search history"""
with sqlite3.connect(DB_PATH) as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO search_history (session_id, stage_number, role, query, results)
VALUES (?, ?, ?, ?, ?)
''', (session_id, stage_number, role, query, results))
conn.commit()
@staticmethod
@contextmanager
def get_db():
"""Database connection context manager with timeout"""
with db_lock:
conn = sqlite3.connect(DB_PATH, timeout=30.0)
conn.row_factory = sqlite3.Row
try:
yield conn
finally:
conn.close()
@staticmethod
def create_session(user_query: str, language: str) -> str:
"""Create new session"""
session_id = hashlib.md5(f"{user_query}{datetime.now()}".encode()).hexdigest()
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO sessions (session_id, user_query, language)
VALUES (?, ?, ?)
''', (session_id, user_query, language))
conn.commit()
return session_id
@staticmethod
def save_stage(session_id: str, stage_number: int, stage_name: str,
role: str, content: str, status: str = 'complete'):
"""Save stage content with word count"""
word_count = len(content.split()) if content else 0
logger.info(f"Saving stage: session={session_id}, stage_num={stage_number}, role={role}, stage_name={stage_name}, words={word_count}")
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
# UPSERT operation
cursor.execute('''
INSERT INTO stages (session_id, stage_number, stage_name, role, content, word_count, status)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(session_id, stage_number)
DO UPDATE SET content=?, word_count=?, status=?, stage_name=?, updated_at=datetime('now')
''', (session_id, stage_number, stage_name, role, content, word_count, status,
content, word_count, status, stage_name))
# Update session
cursor.execute('''
UPDATE sessions
SET updated_at = datetime('now'),
current_stage = ?,
last_saved_stage = ?
WHERE session_id = ?
''', (stage_number, stage_number, session_id))
conn.commit()
logger.info(f"Stage saved successfully")
@staticmethod
def get_session(session_id: str) -> Optional[Dict]:
"""Get session info"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM sessions WHERE session_id = ?', (session_id,))
return cursor.fetchone()
@staticmethod
def get_latest_active_session() -> Optional[Dict]:
"""Get the most recent active session"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM sessions
WHERE status = 'active'
ORDER BY updated_at DESC
LIMIT 1
''')
return cursor.fetchone()
@staticmethod
def get_stages(session_id: str) -> List[Dict]:
"""Get all stages for a session"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM stages
WHERE session_id = ?
ORDER BY stage_number
''', (session_id,))
return cursor.fetchall()
@staticmethod
def get_all_writer_content(session_id: str, test_mode: bool = False) -> str:
"""λͺ¨λ μκ°μ μμ λ³Έ λ΄μ©μ κ°μ Έμμ ν©μΉκΈ°"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
all_content = []
writer_count = 0
total_word_count = 0
if test_mode:
# ν
μ€νΈ λͺ¨λ: writer1 revision + writer10 content
# Writer 1 μμ λ³Έ - μΈμ΄ 무κ΄
cursor.execute('''
SELECT content, stage_name, word_count FROM stages
WHERE session_id = ? AND role = 'writer1'
AND (stage_name LIKE '%Revision%' OR stage_name LIKE '%μμ λ³Έ%')
''', (session_id,))
row = cursor.fetchone()
if row and row['content']:
clean_content = re.sub(r'\[(?:νμ΄μ§|Page|page)\s*\d+\]', '', row['content'])
clean_content = re.sub(r'(?:νμ΄μ§|Page)\s*\d+:', '', clean_content)
clean_content = clean_content.strip()
if clean_content:
writer_count += 1
word_count = row['word_count'] or len(clean_content.split())
total_word_count += word_count
all_content.append(clean_content)
logger.info(f"Test mode - Writer 1: {word_count} words")
# Writer 10 content (λλ¨Έμ§ μ±ν°λ€)
cursor.execute('''
SELECT content, stage_name, word_count FROM stages
WHERE session_id = ? AND role = 'writer10'
''', (session_id,))
row = cursor.fetchone()
if row and row['content']:
# Writer 10μ μ΄λ―Έ μ¬λ¬ μ±ν°λ₯Ό ν¬ν¨νκ³ μμΌλ―λ‘ κ·Έλλ‘ μΆκ°
clean_content = row['content'].strip()
if clean_content:
word_count = row['word_count'] or len(clean_content.split())
total_word_count += word_count
all_content.append(clean_content)
writer_count = 10 # ν
μ€νΈ λͺ¨λμμλ μ΄ 10κ° μ±ν°
logger.info(f"Test mode - Writer 10 (Chapters 2-10): {word_count} words")
else:
# μΌλ° λͺ¨λ: λͺ¨λ μκ°μ μμ λ³Έ
writer_stages_to_check = WRITER_REVISION_STAGES
for stage_num in writer_stages_to_check:
cursor.execute('''
SELECT content, stage_name, word_count FROM stages
WHERE session_id = ? AND stage_number = ?
''', (session_id, stage_num))
row = cursor.fetchone()
if row and row['content']:
# νμ΄μ§ λ§ν¬ μμ μ κ±°
clean_content = re.sub(r'\[(?:νμ΄μ§|Page|page)\s*\d+\]', '', row['content'])
clean_content = re.sub(r'(?:νμ΄μ§|Page)\s*\d+:', '', clean_content)
clean_content = clean_content.strip()
if clean_content:
writer_count += 1
word_count = row['word_count'] or len(clean_content.split())
total_word_count += word_count
all_content.append(clean_content)
logger.info(f"Writer {writer_count} (stage {stage_num}): {word_count} words")
full_content = '\n\n'.join(all_content)
if test_mode:
logger.info(f"Test mode - Total: {writer_count} chapters, {total_word_count} words")
if total_word_count < 2800: # μ΅μ μμμΉ
logger.warning(f"Test mode content short! Only {total_word_count} words")
else:
logger.info(f"Total: {writer_count} writers, {total_word_count} words")
if total_word_count < 12000:
logger.warning(f"Content too short! Only {total_word_count} words instead of ~14,500")
return full_content
@staticmethod
def update_final_novel(session_id: str, final_novel: str):
"""Update final novel content"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
UPDATE sessions
SET final_novel = ?, status = 'complete', updated_at = datetime('now')
WHERE session_id = ?
''', (final_novel, session_id))
conn.commit()
logger.info(f"Updated final novel for session {session_id}, length: {len(final_novel)}")
@staticmethod
def verify_novel_content(session_id: str) -> Dict[str, Any]:
"""μΈμ
μ μ 체 μμ€ λ΄μ© κ²μ¦"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
# λͺ¨λ μκ° μμ λ³Έ νμΈ
cursor.execute(f'''
SELECT stage_number, stage_name, LENGTH(content) as content_length, word_count
FROM stages
WHERE session_id = ? AND stage_number IN ({','.join(map(str, WRITER_REVISION_STAGES))})
ORDER BY stage_number
''', (session_id,))
results = []
total_length = 0
total_words = 0
for row in cursor.fetchall():
results.append({
'stage': row['stage_number'],
'name': row['stage_name'],
'length': row['content_length'] or 0,
'words': row['word_count'] or 0
})
total_length += row['content_length'] or 0
total_words += row['word_count'] or 0
# μ΅μ’
μμ€ νμΈ
cursor.execute('''
SELECT LENGTH(final_novel) as final_length
FROM sessions
WHERE session_id = ?
''', (session_id,))
final_row = cursor.fetchone()
final_length = final_row['final_length'] if final_row else 0
return {
'writer_stages': results,
'total_writer_content': total_length,
'total_words': total_words,
'final_novel_length': final_length,
'expected_words': 14500 # 10 μκ° * 1450 νκ·
}
@staticmethod
def get_active_sessions() -> List[Dict]:
"""Get all active sessions"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT session_id, user_query, language, created_at, current_stage
FROM sessions
WHERE status = 'active'
ORDER BY updated_at DESC
LIMIT 10
''')
return cursor.fetchall()
@staticmethod
def parse_datetime(datetime_str: str) -> datetime:
"""Parse SQLite datetime string safely"""
try:
# Try ISO format first
return datetime.fromisoformat(datetime_str)
except:
# Fallback to SQLite default format
return datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
class NovelWritingSystem:
def __init__(self):
self.token = FRIENDLI_TOKEN
self.api_url = API_URL
self.model_id = MODEL_ID
self.test_mode = TEST_MODE or not self.token
# Web search integration
self.web_search = WebSearchIntegration()
if self.test_mode:
logger.warning("Running in test mode - no actual API calls will be made.")
else:
logger.info("Running in production mode with API calls enabled.")
if self.web_search.enabled:
logger.info("Web search is enabled with Brave Search API.")
else:
logger.warning("Web search is disabled. Set BRAVE_SEARCH_API_KEY to enable.")
# Initialize database
NovelDatabase.init_db()
# Session management
self.current_session_id = None
self.total_stages = 0 # Will be set in process_novel_stream
def create_headers(self):
"""API ν€λ μμ±"""
return {
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json"
}
def enhance_prompt_with_research(self, original_prompt: str, role: str,
topic: str, stage_info: Dict, language: str = "English") -> str:
"""Enhance prompt with web search results"""
if not self.web_search.enabled or self.test_mode:
return original_prompt
# Create research queries
queries = self.web_search.create_research_queries(topic, role, stage_info, language)
all_research = []
for query in queries[:2]: # μ΅λ 2κ° μΏΌλ¦¬
logger.info(f"Searching: {query}")
results = self.web_search.search(query, count=3, language=language)
if results:
research_text = self.web_search.extract_relevant_info(results, max_chars=1500)
if research_text:
all_research.append(f"### {query}\n{research_text}")
# Save search history
if self.current_session_id:
NovelDatabase.save_search_history(
self.current_session_id,
stage_info.get('stage_idx', 0),
role,
query,
research_text
)
if not all_research:
return original_prompt
# Add research to prompt
if language == "Korean":
research_section = f"""
## μΉ κ²μ μ°Έκ³ μλ£:
{chr(10).join(all_research)}
μμ κ²μ κ²°κ³Όλ₯Ό μ°Έκ³ νμ¬ λμ± μ¬μ€μ μ΄κ³ ꡬ체μ μΈ λ΄μ©μ μμ±νμΈμ.
κ²μ κ²°κ³Όμ μ 보λ₯Ό μ°½μμ μΌλ‘ νμ©νλ, μ§μ μΈμ©μ νΌνκ³ μμ€μ μμ°μ€λ½κ² λ
Ήμ¬λ΄μΈμ.
μ€μ μ¬μ€κ³Ό μ°½μμ μ μ ν μ‘°νμμΌ λ
μκ° λͺ°μ
ν μ μλ μ΄μΌκΈ°λ₯Ό λ§λμΈμ.
"""
else:
research_section = f"""
## Web Search Reference:
{chr(10).join(all_research)}
Use the above search results to create more realistic and specific content.
Creatively incorporate the information from search results, but avoid direct quotes and naturally blend them into the novel.
Balance real facts with creative fiction to create an immersive story for readers.
"""
return original_prompt + "\n\n" + research_section
def create_director_initial_prompt(self, user_query: str, language: str = "English") -> str:
"""Director AI initial prompt - Novel planning for 10 writers"""
if language == "Korean":
return f"""λΉμ μ 30νμ΄μ§ λΆλμ μ€νΈ μμ€μ κΈ°ννλ λ¬Έν κ°λ
μμ
λλ€.
μ¬μ©μ μμ²: {user_query}
λ€μ μμλ€μ 체κ³μ μΌλ‘ ꡬμ±νμ¬ 30νμ΄μ§ μ€νΈ μμ€μ κΈ°μ΄λ₯Ό λ§λμΈμ:
1. **μ£Όμ μ μ₯λ₯΄**
- ν΅μ¬ μ£Όμ μ λ©μμ§
- μ₯λ₯΄ λ° ν€
- λͺ©ν λ
μμΈ΅
2. **λ±μ₯μΈλ¬Ό μ€μ ** (νλ‘ μ 리)
| μ΄λ¦ | μν | μ±κ²© | λ°°κ²½ | λκΈ° | λ³ν |
|------|------|------|------|------|------|
3. **μΈλ¬Ό κ΄κ³λ**
- μ£Όμ μΈλ¬Ό κ°μ κ΄κ³
- κ°λ± ꡬ쑰
- κ°μ μ μ°κ²°κ³ 리
4. **μμ¬ κ΅¬μ‘°** (30νμ΄μ§λ₯Ό 10κ° ννΈλ‘ λλμ΄ κ° 3νμ΄μ§)
| ννΈ | νμ΄μ§ | μ£Όμ μ¬κ±΄ | κΈ΄μ₯λ | μΈλ¬Ό λ°μ |
|------|--------|-----------|---------|-----------|
| 1 | 1-3 | | | |
| 2 | 4-6 | | | |
| ... | ... | | | |
| 10 | 28-30 | | | |
5. **μΈκ³κ΄ μ€μ **
- μ곡κ°μ λ°°κ²½
- μ¬νμ /λ¬Ένμ λ§₯λ½
- λΆμκΈ°μ ν€
κ° μμ±μκ° 3νμ΄μ§μ© μμ±ν μ μλλ‘ λͺ
νν κ°μ΄λλΌμΈμ μ μνμΈμ."""
else:
return f"""You are a literary director planning a 30-page novella.
User Request: {user_query}
Systematically compose the following elements to create the foundation for a 30-page novella:
1. **Theme and Genre**
- Core theme and message
- Genre and tone
- Target audience
2. **Character Settings** (organize in table)
| Name | Role | Personality | Background | Motivation | Arc |
|------|------|-------------|------------|------------|-----|
3. **Character Relationship Map**
- Relationships between main characters
- Conflict structure
- Emotional connections
4. **Narrative Structure** (divide 30 pages into 10 parts, 3 pages each)
| Part | Pages | Main Events | Tension | Character Development |
|------|-------|-------------|---------|---------------------|
| 1 | 1-3 | | | |
| 2 | 4-6 | | | |
| ... | ... | | | |
| 10 | 28-30 | | | |
5. **World Building**
- Temporal and spatial setting
- Social/cultural context
- Atmosphere and tone
Provide clear guidelines for each writer to compose 3 pages."""
def create_critic_director_prompt(self, director_plan: str, language: str = "English") -> str:
"""Critic's review of director's plan"""
if language == "Korean":
return f"""λΉμ μ λ¬Έν λΉνκ°μ
λλ€. κ°λ
μμ μμ€ κΈ°νμ κ²ν νκ³ κ°μ μ μ μ μνμΈμ.
κ°λ
μμ κΈ°ν:
{director_plan}
λ€μ κ΄μ μμ λΉννκ³ κ΅¬μ²΄μ μΈ κ°μ μμ μ μνμΈμ:
1. **μμ¬μ μμ±λ**
- νλ‘―μ λ
Όλ¦¬μ±κ³Ό κ°μ°μ±
- κ°λ±μ ν¨κ³Όμ±
- ν΄λΌμ΄λ§₯μ€μ μμΉμ κ°λ
2. **μΈλ¬Ό μ€μ κ²ν **
| μΈλ¬Ό | κ°μ | μ½μ | κ°μ μ μ |
|------|------|------|-----------|
3. **ꡬ쑰μ κ· ν**
- 10κ° ννΈλ³ λΆλ λ°°λΆ
- κΈ΄μ₯κ³Ό μ΄μμ 리λ¬
- μ 체μ μΈ νλ¦
4. **λ
μ κ΄μ **
- λͺ°μ
λ μμ
- κ°μ μ μν₯λ ₯
- κΈ°λμΉ μΆ©μ‘±λ
5. **μ€ν κ°λ₯μ±**
- 10λͺ
μ μμ±μλ₯Ό μν κ°μ΄λλΌμΈμ λͺ
νμ±
- μΌκ΄μ± μ μ§ λ°©μ
- μ μ¬μ λ¬Έμ μ
ꡬ체μ μ΄κ³ 건μ€μ μΈ νΌλλ°±μ μ 곡νμΈμ."""
else:
return f"""You are a literary critic. Review the director's novel plan and suggest improvements.
Director's Plan:
{director_plan}
Critique from the following perspectives and provide specific improvements:
1. **Narrative Completeness**
- Plot logic and plausibility
- Effectiveness of conflicts
- Climax position and intensity
2. **Character Review**
| Character | Strengths | Weaknesses | Suggestions |
|-----------|-----------|------------|-------------|
3. **Structural Balance**
- Distribution across 10 parts
- Rhythm of tension and relief
- Overall flow
4. **Reader Perspective**
- Expected engagement
- Emotional impact
- Expectation fulfillment
5. **Feasibility**
- Clarity of guidelines for 10 writers
- Consistency maintenance
- Potential issues
Provide specific and constructive feedback."""
def create_director_revision_prompt(self, initial_plan: str, critic_feedback: str, language: str = "English") -> str:
"""Director's revision based on critic feedback"""
if language == "Korean":
return f"""κ°λ
μλ‘μ λΉνκ°μ νΌλλ°±μ λ°μνμ¬ μμ€ κΈ°νμ μμ ν©λλ€.
μ΄κΈ° κΈ°ν:
{initial_plan}
λΉνκ° νΌλλ°±:
{critic_feedback}
λ€μμ ν¬ν¨ν μμ λ μ΅μ’
κΈ°νμ μ μνμΈμ:
1. **μμ λ μμ¬ κ΅¬μ‘°** (10κ° ννΈ)
| ννΈ | νμ΄μ§ | μ£Όμ μ¬κ±΄ | μμ± μ§μΉ¨ | μ£Όμμ¬ν |
|------|--------|-----------|-----------|----------|
2. **κ°νλ μΈλ¬Ό μ€μ **
- κ° μΈλ¬Όμ λͺ
νν λκΈ°μ λͺ©ν
- μΈλ¬Ό κ° κ°λ±μ ꡬ체ν
- κ°μ μ μ λ³ν μΆμ΄
3. **κ° μμ±μλ₯Ό μν μμΈ κ°μ΄λ** (10λͺ
)
- ννΈλ³ μμκ³Ό λ μ§μ
- νμ ν¬ν¨ μμ
- 문체μ ν€ μ§μΉ¨
- μ λ¬ν΄μΌ ν μ 보
4. **μΌκ΄μ± μ μ§ μ²΄ν¬λ¦¬μ€νΈ**
- μκ°μ κ΄λ¦¬
- μΈλ¬Ό νΉμ± μ μ§
- μ€μ μΌκ΄μ±
- 볡μ κ³Ό ν΄κ²°
5. **νμ§ κΈ°μ€**
- κ° ννΈμ μμ±λ κΈ°μ€
- μ 체μ ν΅μΌμ±
- λ
μ λͺ°μ
μ μ§ λ°©μ
10λͺ
μ μμ±μκ° λͺ
νν μ΄ν΄ν μ μλ μ΅μ’
λ§μ€ν°νλμ μμ±νμΈμ."""
else:
return f"""As director, revise the novel plan reflecting the critic's feedback.
Initial Plan:
{initial_plan}
Critic Feedback:
{critic_feedback}
Present the revised final plan including:
1. **Revised Narrative Structure** (10 parts)
| Part | Pages | Main Events | Writing Guidelines | Cautions |
|------|-------|-------------|-------------------|----------|
2. **Enhanced Character Settings**
- Clear motivations and goals for each character
- Concrete conflicts between characters
- Emotional arc progression
3. **Detailed Guide for Each Writer** (10 writers)
- Start and end points for each part
- Essential elements to include
- Style and tone guidelines
- Information to convey
4. **Consistency Checklist**
- Timeline management
- Character trait maintenance
- Setting consistency
- Foreshadowing and resolution
5. **Quality Standards**
- Completion criteria for each part
- Overall unity
- Reader engagement maintenance
Create a final masterplan that all 10 writers can clearly understand."""
def create_writer_prompt(self, writer_number: int, director_plan: str, previous_content: str, language: str = "English") -> str:
"""Individual writer prompt - 1,400-1,500 λ¨μ΄"""
pages_start = (writer_number - 1) * 3 + 1
pages_end = writer_number * 3
if language == "Korean":
return f"""λΉμ μ μμ±μ {writer_number}λ²μ
λλ€. 30νμ΄μ§ μ€νΈ μμ€μ {pages_start}-{pages_end}νμ΄μ§(3νμ΄μ§)λ₯Ό μμ±νμΈμ.
κ°λ
μμ λ§μ€ν°νλ:
{director_plan}
{'μ΄μ κΉμ§μ λ΄μ©:' if previous_content else 'λΉμ μ΄ μ²« λ²μ§Έ μμ±μμ
λλ€.'}
{previous_content[-2000:] if previous_content else ''}
**μ€μ μ§μΉ¨:**
1. **νμ λΆλ**:
- μ΅μ 1,400λ¨μ΄, μ΅λ 1,500λ¨μ΄
- λλ΅ 7000-7500μ (곡백 ν¬ν¨)
- 3νμ΄μ§ λΆλμ μ νν μ±μμΌ ν©λλ€
2. **λΆλ ν보 μ λ΅**:
- μμΈν μ₯λ©΄ λ¬μ¬ ν¬ν¨
- μΈλ¬Όμ λ΄λ©΄ μ¬λ¦¬ κΉμ΄ μκ² νꡬ
- λνμ νλμ ꡬ체μ μΌλ‘ νν
- λ°°κ²½κ³Ό λΆμκΈ°λ₯Ό μμνκ² κ·Έλ €λ΄κΈ°
- κ°κ°μ μΈλΆμ¬ν(μκ°, μ²κ°, μ΄κ° λ±) νμ©
3. **μ°μμ±κ³Ό μΌκ΄μ±**:
- μ΄μ λ΄μ©κ³Ό μμ°μ€λ½κ² μ°κ²°
- μΈλ¬Ό μ±κ²©κ³Ό λ§ν¬ μ μ§
- μκ°μ κ³Ό κ³΅κ° μ€μ μ€μ
4. **μμ¬ λ°μ **:
- νλ‘―μ μλ―Έ μκ² μ μ§μν€κΈ°
- κΈ΄μ₯κ° μ μ ν μ‘°μ
- λ
μμ κ΄μ¬ μ μ§
**μμ± μμ:**
μ΄μ 1,400-1,500λ¨μ΄ λΆλμ μμ€μ μμ±νμΈμ. νμ΄μ§ κ΅¬λΆ νμλ νμ§ λ§μΈμ."""
else:
return f"""You are Writer #{writer_number}. Write pages {pages_start}-{pages_end} (3 pages) of the 30-page novella.
Director's Masterplan:
{director_plan}
{'Previous content:' if previous_content else 'You are the first writer.'}
{previous_content[-2000:] if previous_content else ''}
**CRITICAL INSTRUCTIONS:**
1. **MANDATORY LENGTH**:
- Minimum 1,400 words, Maximum 1,500 words
- Approximately 7000-7500 characters
- You MUST fill exactly 3 pages
2. **LENGTH STRATEGIES**:
- Include detailed scene descriptions
- Explore character's inner psychology deeply
- Express dialogue and actions concretely
- Paint backgrounds and atmosphere vividly
- Use sensory details (visual, auditory, tactile, etc.)
3. **CONTINUITY & CONSISTENCY**:
- Flow naturally from previous content
- Maintain character personalities and speech
- Follow timeline and spatial settings
4. **NARRATIVE DEVELOPMENT**:
- Advance the plot meaningfully
- Control tension appropriately
- Maintain reader interest
**BEGIN WRITING:**
Now write your 1,400-1,500 word section. Do not use any page markers."""
def create_critic_writer_prompt(self, writer_number: int, writer_content: str, director_plan: str, all_previous_content: str, language: str = "English") -> str:
"""Critic's review of individual writer's work"""
if language == "Korean":
return f"""μμ±μ {writer_number}λ²μ μνμ λΉνν©λλ€.
κ°λ
μμ λ§μ€ν°νλ:
{director_plan}
μ΄μ λ΄μ© μμ½:
{all_previous_content[-1000:] if all_previous_content else '첫 λ²μ§Έ μμ±μμ
λλ€.'}
μμ±μ {writer_number}λ²μ λ΄μ©:
{writer_content}
λ€μ κΈ°μ€μΌλ‘ νκ°νκ³ μμ μꡬμ¬νμ μ μνμΈμ:
1. **μΌκ΄μ± κ²μ¦** (νλ‘ μ 리)
| μμ | μ΄μ μ€μ | νμ¬ νν | λ¬Έμ μ | μμ νμ |
|------|----------|----------|--------|----------|
2. **λ
Όλ¦¬μ μ€λ₯ κ²ν **
- μκ°μ λͺ¨μ
- μΈλ¬Ό νλμ κ°μ°μ±
- μ€μ μΆ©λ
- μ¬μ€κ΄κ³ μ€λ₯
3. **μμ¬μ ν¨κ³Όμ±**
- νλ‘― μ§ν κΈ°μ¬λ
- κΈ΄μ₯κ° μ μ§
- λ
μ λͺ°μ
λ
- κ°μ μ μν₯λ ₯
4. **문체μ νμ§**
- μ 체 ν€κ³Όμ μΌμΉ
- λ¬Έμ₯μ μ§
- λ¬μ¬μ μ μ μ±
- λνμ μμ°μ€λ¬μ
5. **κ°μ μꡬμ¬ν**
- νμ μμ μ¬ν (μΌκ΄μ±/λ
Όλ¦¬ μ€λ₯)
- κΆμ₯ κ°μ μ¬ν (νμ§ ν₯μ)
- ꡬ체μ μμ μ§μΉ¨
λ°λμ μμ μ΄ νμν λΆλΆκ³Ό μ νμ κ°μ μ¬νμ ꡬλΆνμ¬ μ μνμΈμ."""
else:
return f"""Critiquing Writer #{writer_number}'s work.
Director's Masterplan:
{director_plan}
Previous Content Summary:
{all_previous_content[-1000:] if all_previous_content else 'This is the first writer.'}
Writer #{writer_number}'s Content:
{writer_content}
Evaluate by these criteria and present revision requirements:
1. **Consistency Verification** (organize in table)
| Element | Previous Setting | Current Expression | Issue | Revision Needed |
|---------|-----------------|-------------------|-------|-----------------|
2. **Logical Error Review**
- Timeline contradictions
- Character action plausibility
- Setting conflicts
- Factual errors
3. **Narrative Effectiveness**
- Plot progression contribution
- Tension maintenance
- Reader engagement
- Emotional impact
4. **Style and Quality**
- Alignment with overall tone
- Sentence quality
- Description appropriateness
- Dialogue naturalness
5. **Improvement Requirements**
- Mandatory revisions (consistency/logic errors)
- Recommended improvements (quality enhancement)
- Specific revision guidelines
Clearly distinguish between mandatory revisions and optional improvements."""
def create_writer_revision_prompt(self, writer_number: int, initial_content: str, critic_feedback: str, language: str = "English") -> str:
"""Writer's revision based on critic feedback"""
if language == "Korean":
return f"""μμ±μ {writer_number}λ²μΌλ‘μ λΉνκ°μ νΌλλ°±μ λ°μνμ¬ μμ ν©λλ€.
μ΄κΈ° μμ± λ΄μ©:
{initial_content}
λΉνκ° νΌλλ°±:
{critic_feedback}
λ€μ μ¬νμ λ°μν μμ λ³Έμ μμ±νμΈμ:
1. **νμ μμ μ¬ν λ°μ**
- λͺ¨λ μΌκ΄μ± μ€λ₯ μμ
- λ
Όλ¦¬μ λͺ¨μ ν΄κ²°
- μ¬μ€κ΄κ³ μ μ
2. **νμ§ κ°μ **
- κΆμ₯μ¬ν μ€ κ°λ₯ν λΆλΆ λ°μ
- 문체μ ν€ μ‘°μ
- λ¬μ¬μ λν κ°μ
3. **λΆλ μ μ§**
- μ¬μ ν μ νν 3νμ΄μ§ (1,400-1,500λ¨μ΄)
- νμ΄μ§ κ΅¬λΆ νμ μ λ κΈμ§
4. **μ°μμ± ν보**
- μ΄μ /μ΄ν λ΄μ©κ³Όμ μμ°μ€λ¬μ΄ μ°κ²°
- μμ μΌλ‘ μΈν μλ‘μ΄ λͺ¨μ λ°©μ§
μμ λ μ΅μ’
λ³Έμ μ μνμΈμ. νμ΄μ§ λ§ν¬λ μ λ μ¬μ©νμ§ λ§μΈμ.
λ°λμ 1,400-1,500λ¨μ΄ λΆλμ μ μ§νμΈμ."""
else:
return f"""As Writer #{writer_number}, revise based on critic's feedback.
Initial Content:
{initial_content}
Critic Feedback:
{critic_feedback}
Write a revision reflecting:
1. **Mandatory Revisions**
- Fix all consistency errors
- Resolve logical contradictions
- Correct factual errors
2. **Quality Improvements**
- Incorporate feasible recommendations
- Adjust style and tone
- Improve descriptions and dialogue
3. **Maintain Length**
- Still exactly 3 pages (1,400-1,500 words)
- Absolutely no page markers
4. **Ensure Continuity**
- Natural connection with previous/next content
- Prevent new contradictions from revisions
Present the revised final version. Never use page markers.
You MUST maintain 1,400-1,500 words."""
def create_test_writer_remaining_prompt(self, director_plan: str, writer1_content: str, language: str) -> str:
"""Test mode - Writer 10 writes remaining novel (chapters 2-10)"""
if language == "Korean":
return f"""[ν
μ€νΈ λͺ¨λ] λΉμ μ λλ¨Έμ§ 9κ° μ±ν°(Chapter 2-10)λ₯Ό μμ±νλ νΉλ³ μκ°μ
λλ€.
κ°λ
μμ λ§μ€ν°νλ:
{director_plan}
μμ±μ 1μ΄ μ΄λ―Έ μμ±ν Chapter 1:
{writer1_content[-1000:] if writer1_content else '(첫 λ²μ§Έ μ±ν°κ° μμ΅λλ€)'}
**μ€μ μ§μΉ¨:**
1. Chapter 2λΆν° Chapter 10κΉμ§ 9κ° μ±ν°λ₯Ό μμ±νμΈμ
2. κ° μ±ν°λ μ½ 1,400-1,500 λ¨μ΄λ‘ μμ±νμΈμ
3. μ΄ 12,600-13,500 λ¨μ΄ (9κ° μ±ν°)
4. Chapter 1κ³Ό μμ°μ€λ½κ² μ΄μ΄μ§λλ‘ μμ±νμΈμ
5. λ§μ€ν°νλμ λͺ¨λ μμλ₯Ό ν¬ν¨νμ¬ μκ²°λ μ΄μΌκΈ°λ₯Ό λ§λμΈμ
**νμ νμ:**
λ°λμ μλμ κ°μ΄ μ±ν°λ₯Ό λͺ
νν ꡬλΆνμΈμ:
[Chapter 2]
(1,400-1,500 λ¨μ΄μ λ΄μ©)
[Chapter 3]
(1,400-1,500 λ¨μ΄μ λ΄μ©)
...μ΄λ° μμΌλ‘ [Chapter 10]κΉμ§...
κ° μ±ν°λ λ°λμ [Chapter μ«μ] νμμΌλ‘ μμν΄μΌ ν©λλ€.
μ±ν° μ¬μ΄μλ λΉ μ€μ λ£μ΄ ꡬλΆνμΈμ.
Chapter 2λΆν° 10κΉμ§ μμ±νμΈμ."""
else:
return f"""[TEST MODE] You are a special writer creating the remaining 9 chapters (Chapters 2-10).
Director's Masterplan:
{director_plan}
Writer 1 has already written Chapter 1:
{writer1_content[-1000:] if writer1_content else '(No first chapter available)'}
**CRITICAL INSTRUCTIONS:**
1. Write Chapters 2 through 10 (9 chapters total)
2. Each chapter should be ~1,400-1,500 words
3. Total 12,600-13,500 words (9 chapters)
4. Continue naturally from Chapter 1
5. Include all elements from the masterplan to create a complete story
**MANDATORY FORMAT:**
You MUST clearly separate chapters as follows:
[Chapter 2]
(1,400-1,500 words of content)
[Chapter 3]
(1,400-1,500 words of content)
...continue this way until [Chapter 10]...
Each chapter MUST start with [Chapter number] format.
Leave blank lines between chapters for separation.
Write Chapters 2-10 now."""
def simulate_streaming(self, text: str, role: str) -> Generator[str, None, None]:
"""Simulate streaming in test mode"""
words = text.split()
chunk_size = 5
for i in range(0, len(words), chunk_size):
chunk = " ".join(words[i:i+chunk_size])
yield chunk + " "
time.sleep(0.02)
def call_llm_streaming(self, messages: List[Dict[str, str]], role: str,
language: str = "English", stage_info: Dict = None) -> Generator[str, None, None]:
"""Streaming LLM API call with web search enhancement"""
if self.test_mode:
logger.info(f"Test mode streaming - Role: {role}, Language: {language}")
test_response = self.get_test_response(role, language)
yield from self.simulate_streaming(test_response, role)
return
# Extract topic from user query for research
topic = ""
if stage_info and 'query' in stage_info:
topic = stage_info['query']
# Enhance prompt with web search if available
if messages and messages[-1]["role"] == "user" and self.web_search.enabled:
enhanced_prompt = self.enhance_prompt_with_research(
messages[-1]["content"],
role,
topic,
stage_info or {},
language
)
messages[-1]["content"] = enhanced_prompt
# Real API call
try:
system_prompts = self.get_system_prompts(language)
# μκ°μκ² λ κ°ν μμ€ν
ν둬ννΈ μΆκ°
if role.startswith("writer"):
if language == "Korean":
system_prompts[role] += "\n\n**μ λμ μꡬμ¬ν**: λΉμ μ λ°λμ 1,400-1,500λ¨μ΄λ₯Ό μμ±ν΄μΌ ν©λλ€. μ΄κ²μ νμ λΆκ°λ₯ν μꡬμ¬νμ
λλ€. μ§§μ μλ΅μ νμ©λμ§ μμ΅λλ€."
else:
system_prompts[role] += "\n\n**ABSOLUTE REQUIREMENT**: You MUST write 1,400-1,500 words. This is non-negotiable. Short responses are not acceptable."
full_messages = [
{"role": "system", "content": system_prompts.get(role, "")},
*messages
]
# μμ±μλ€μκ²λ μ μ ν ν ν° ν λΉ
if role == "writer10" and stage_info and stage_info.get('test_mode'):
max_tokens = 30000 # ν
μ€νΈ λͺ¨λ: 9κ° μ±ν° μμ± (μΆ©λΆν ν ν°)
temperature = 0.8
top_p = 0.95
elif role.startswith("writer"):
max_tokens = 10000 # μΆ©λΆν ν ν°
temperature = 0.8
top_p = 0.95
else:
max_tokens = 8000
temperature = 0.6
top_p = 0.9
payload = {
"model": self.model_id,
"messages": full_messages,
"max_tokens": max_tokens,
"temperature": temperature,
"top_p": top_p,
"stream": True,
"stream_options": {"include_usage": True}
}
logger.info(f"API streaming call started - Role: {role}, Max tokens: {max_tokens}, Temperature: {temperature}")
response = requests.post(
self.api_url,
headers=self.create_headers(),
json=payload,
stream=True,
timeout=60
)
if response.status_code != 200:
logger.error(f"API error: {response.status_code}")
yield f"β API error ({response.status_code}): {response.text[:200]}"
return
buffer = ""
total_content = ""
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith("data: "):
data = line[6:]
if data == "[DONE]":
if buffer:
yield buffer
logger.info(f"Streaming complete for {role}: {len(total_content)} chars, {len(total_content.split())} words")
break
try:
chunk = json.loads(data)
if "choices" in chunk and chunk["choices"]:
content = chunk["choices"][0].get("delta", {}).get("content", "")
if content:
buffer += content
total_content += content
# μκ°λ λ ν° λ²νΌ μ¬μ©
buffer_size = 500 if role.startswith("writer") else 200
if len(buffer) > buffer_size or '\n\n' in buffer:
yield buffer
buffer = ""
except json.JSONDecodeError:
continue
if buffer:
yield buffer
# μκ°μ κ²½μ° λ΄μ© κΈΈμ΄ νμΈ λ° μ¬μλ
if role.startswith("writer"):
word_count = len(total_content.split())
if word_count < 1350: # 1,400 λ―Έλ§
logger.warning(f"Writer {role} produced only {word_count} words! Requesting continuation...")
# μΆκ° μμ²
continuation_prompt = f"Continue writing to reach the required 1,400-1,500 words. You have written {word_count} words so far. Write {1400 - word_count} more words to complete your section."
if language == "Korean":
continuation_prompt = f"νμ λΆλ 1,400-1,500λ¨μ΄λ₯Ό μ±μ°κΈ° μν΄ κ³μ μμ±νμΈμ. μ§κΈκΉμ§ {word_count}λ¨μ΄λ₯Ό μμ±νμ΅λλ€. {1400 - word_count}λ¨μ΄λ₯Ό λ μμ±νμ¬ μΉμ
μ μμ±νμΈμ."
full_messages.append({"role": "assistant", "content": total_content})
full_messages.append({"role": "user", "content": continuation_prompt})
# μΆκ° μμ± μμ²
continuation_payload = {
"model": self.model_id,
"messages": full_messages,
"max_tokens": 5000,
"temperature": temperature,
"top_p": top_p,
"stream": True
}
logger.info(f"Requesting continuation for {role}...")
continuation_response = requests.post(
self.api_url,
headers=self.create_headers(),
json=continuation_payload,
stream=True,
timeout=60
)
if continuation_response.status_code == 200:
for line in continuation_response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith("data: "):
data = line[6:]
if data == "[DONE]":
break
try:
chunk = json.loads(data)
if "choices" in chunk and chunk["choices"]:
content = chunk["choices"][0].get("delta", {}).get("content", "")
if content:
yield content
total_content += content
except json.JSONDecodeError:
continue
final_word_count = len(total_content.split())
logger.info(f"Final word count for {role}: {final_word_count}")
except requests.exceptions.Timeout:
yield "β±οΈ API call timed out. Please try again."
except requests.exceptions.ConnectionError:
yield "π Cannot connect to API server. Please check your internet connection."
except Exception as e:
logger.error(f"Error during streaming: {str(e)}")
yield f"β Error occurred: {str(e)}"
def get_system_prompts(self, language: str) -> Dict[str, str]:
"""Get system prompts for all writers including test mode"""
if language == "Korean":
prompts = {
"director": "λΉμ μ 30νμ΄μ§ μ€νΈ μμ€μ κΈ°ννκ³ κ°λ
νλ λ¬Έν κ°λ
μμ
λλ€. 체κ³μ μ΄κ³ μ°½μμ μΈ μ€ν 리 ꡬ쑰λ₯Ό λ§λ€μ΄λ
λλ€.",
"critic": "λΉμ μ λ μΉ΄λ‘μ΄ ν΅μ°°λ ₯μ κ°μ§ λ¬Έν λΉνκ°μ
λλ€. 건μ€μ μ΄κ³ ꡬ체μ μΈ νΌλλ°±μ μ 곡ν©λλ€.",
"writer10": "[ν
μ€νΈ λͺ¨λ] λΉμ μ μ±ν° 2-10μ μμ±νλ νΉλ³ μκ°μ
λλ€. 9κ° μ±ν°λ‘ ꡬμ±λ λλ¨Έμ§ μμ€μ μμ±νμΈμ. κ° μ±ν°λ λ°λμ 1,400-1,500λ¨μ΄λ‘ μμ±νμΈμ."
}
# 10λͺ
μ μκ° ν둬ννΈ
writer_roles = [
"μμ€μ λμ
λΆλ₯Ό λ΄λΉνλ μκ°μ
λλ€. λ
μλ₯Ό μ¬λ‘μ‘λ μμμ λ§λλλ€.",
"μ΄λ° μ κ°λ₯Ό λ΄λΉνλ μκ°μ
λλ€. μΈλ¬Όκ³Ό μν©μ κΉμ΄ μκ² λ°μ μν΅λλ€.",
"κ°λ± λμ
μ λ΄λΉνλ μκ°μ
λλ€. μ΄μΌκΈ°μ ν΅μ¬ κ°λ±μ μ μν©λλ€.",
"κ°λ± μμΉμ λ΄λΉνλ μκ°μ
λλ€. κΈ΄μ₯κ°μ λμ΄κ³ 볡μ‘μ±μ λν©λλ€.",
"μ€λ°λΆ μ νμ μ λ΄λΉνλ μκ°μ
λλ€. μ€μν λ³νλ₯Ό λ§λλλ€.",
"μ€λ°λΆ μ¬νλ₯Ό λ΄λΉνλ μκ°μ
λλ€. μ΄μΌκΈ°μ μ€μ¬μΆμ κ²¬κ³ νκ² λ§λλλ€.",
"ν΄λΌμ΄λ§₯μ€ μ€λΉλ₯Ό λ΄λΉνλ μκ°μ
λλ€. μ΅κ³ μ‘°λ₯Ό ν₯ν΄ λμκ°λλ€.",
"ν΄λΌμ΄λ§₯μ€λ₯Ό λ΄λΉνλ μκ°μ
λλ€. λͺ¨λ κ°λ±μ΄ νλ°νλ μκ°μ 그립λλ€.",
"ν΄κ²° μμμ λ΄λΉνλ μκ°μ
λλ€. λ§€λμ νμ΄λκ°κΈ° μμν©λλ€.",
"μ΅μ’
κ²°λ§μ λ΄λΉνλ μκ°μ
λλ€. μ¬μ΄μ΄ λ¨λ λ§λ¬΄λ¦¬λ₯Ό λ§λλλ€."
]
for i, role_desc in enumerate(writer_roles, 1):
prompts[f"writer{i}"] = f"λΉμ μ {role_desc} λ°λμ 1,400-1,500λ¨μ΄λ₯Ό μμ±νμΈμ. μ΄λ μ λμ μΈ μꡬμ¬νμ
λλ€."
return prompts
else:
prompts = {
"director": "You are a literary director planning and supervising a 30-page novella. You create systematic and creative story structures.",
"critic": "You are a literary critic with sharp insights. You provide constructive and specific feedback.",
"writer10": "[TEST MODE] You are a special writer creating chapters 2-10. Write the remaining novel organized into 9 chapters. Each chapter MUST be 1,400-1,500 words."
}
# 10 writer prompts
writer_roles = [
"the writer responsible for the introduction. You create a captivating beginning.",
"the writer responsible for early development. You deepen characters and situations.",
"the writer responsible for conflict introduction. You present the core conflict.",
"the writer responsible for rising conflict. You increase tension and add complexity.",
"the writer responsible for the midpoint turn. You create important changes.",
"the writer responsible for deepening the middle. You solidify the story's central axis.",
"the writer responsible for climax preparation. You move toward the peak.",
"the writer responsible for the climax. You depict the moment when all conflicts explode.",
"the writer responsible for resolution beginning. You start untangling the knots.",
"the writer responsible for the final ending. You create a lingering conclusion."
]
for i, role_desc in enumerate(writer_roles, 1):
prompts[f"writer{i}"] = f"You are {role_desc} You MUST write 1,400-1,500 words. This is an absolute requirement."
return prompts
def get_test_response(self, role: str, language: str) -> str:
"""Get test response based on role - updated for writer10 chapters 2-10"""
if language == "Korean":
return self.get_korean_test_response(role)
else:
return self.get_english_test_response(role)
def get_korean_test_response(self, role: str) -> str:
"""Korean test responses with appropriate length"""
test_responses = {
"director": """30νμ΄μ§ μ€νΈ μμ€ κΈ°νμμ μ μν©λλ€.
## 1. μ£Όμ μ μ₯λ₯΄
- **ν΅μ¬ μ£Όμ **: μΈκ° λ³Έμ±κ³Ό κΈ°μ μ μΆ©λ μμμ μ°Ύλ μ§μ ν μ°κ²°
- **μ₯λ₯΄**: SF μ¬λ¦¬ λλΌλ§
- **ν€**: μ±μ°°μ μ΄κ³ μμ μ μ΄λ©΄μλ κΈ΄μ₯κ° μλ
- **λͺ©ν λ
μ**: κΉμ΄ μλ μ¬μ λ₯Ό μ¦κΈ°λ μ±μΈ λ
μ
## 2. λ±μ₯μΈλ¬Ό μ€μ
| μ΄λ¦ | μν | μ±κ²© | λ°°κ²½ | λκΈ° | λ³ν |
|------|------|------|------|------|------|
| μμ° | μ£ΌμΈκ³΅ | μ΄μ±μ , κ³ λ
ν¨ | AI μ°κ΅¬μ | μλ²½ν AI λλ°μ κ°λ° | μΈκ°κ΄κ³μ κ°μΉ μ¬λ°κ²¬ |
| λ―Όμ€ | μ‘°λ ₯μ | λ°λ»ν¨, μ§κ΄μ | μ¬λ¦¬μλ΄μ¬ | μμ°μ λμ κ· ν μ°ΎκΈ° | κΈ°μ μμ©κ³Ό μ‘°ν |
| ARIA | λ립μβλλ°μ | λ
Όλ¦¬μ βκ°μ± νμ΅ | AI νλ‘ν νμ
| μ§μ ν μ‘΄μ¬ λκΈ° | μμ μ μ²΄μ± ν립 |
## 3. μμ¬ κ΅¬μ‘° (10κ° ννΈ, κ° 3νμ΄μ§)
| ννΈ | νμ΄μ§ | μ£Όμ μ¬κ±΄ | κΈ΄μ₯λ | μΈλ¬Ό λ°μ |
|------|--------|-----------|---------|-----------|
| 1 | 1-3 | μμ°μ κ³ λ
ν μ°κ΅¬μ€, ARIA 첫 κ°μ± | 3/10 | μμ°μ μ§μ°© λλ¬λ¨ |
| 2 | 4-6 | ARIAμ μ΄μ νλ μμ | 4/10 | μλ¬Έμ μμ |
| 3 | 7-9 | λ―Όμ€κ³Όμ 첫 λ§λ¨ | 4/10 | μΈλΆ μκ° λμ
|
| 4 | 10-12 | ARIAμ μμ μΈμ μ§ν | 5/10 | κ°λ±μ μ¨μ |
| 5 | 13-15 | 첫 λ²μ§Έ μκΈ° | 6/10 | μ νμ μκ° |
| 6 | 16-18 | μ€λ¦¬μμν κ°μ
| 7/10 | μΈλΆ μλ ₯ |
| 7 | 19-21 | λνμ μ΄ν΄ | 6/10 | μνΈ μΈμ |
| 8 | 22-24 | μ΅νμ λκ²° μ€λΉ | 8/10 | μ°λμ νμ |
| 9 | 25-27 | ν΄λΌμ΄λ§₯μ€ | 10/10 | λͺ¨λ κ°λ± νλ° |
| 10 | 28-30 | μλ‘μ΄ μμ | 4/10 | 곡쑴과 νν΄ |""",
"critic": """κ°λ
μμ κΈ°νμ κ²ν νμ΅λλ€.
## λΉν λ° κ°μ μ μ
### 1. μμ¬μ μμ±λ
- **κ°μ **: AIμ μΈκ°μ κ΄κ³λΌλ μμμ μ ν μ£Όμ
- **κ°μ μ **: 10κ° ννΈ κ΅¬μ±μ΄ μ μ νλ©° κ° ννΈμ λ
립μ±κ³Ό μ°κ²°μ±μ΄ μ κ· νμ‘ν μμ
### 2. μΈλ¬Ό μ€μ κ²ν
| μΈλ¬Ό | κ°μ | μ½μ | κ°μ μ μ |
|------|------|------|-----------|
| μμ° | λͺ
νν λ΄μ κ°λ± | κ°μ νν λΆμ‘± μ°λ € | μ΄λ°λΆν° κ°μ μ λ¨μ λ°°μΉ |
| λ―Όμ€ | κ· νμ μν | μλμ μΌ μν | λ
μμ μλΈνλ‘― νμ |
| ARIA | λ
νΉν μΊλ¦ν° μν¬ | λ³ν κ³Όμ μΆμμ | ꡬ체μ νμ΅ μνΌμλ μΆκ° |
### 3. μ€ν κ°λ₯μ±
- κ° μκ°λ³ 3νμ΄μ§λ μ μ ν λΆλ
- ννΈ κ° μ°κ²°μ± κ°μ΄λλΌμΈ λ³΄κ° νμ""",
}
# μκ° μλ΅ - 1,400-1,500 λ¨μ΄
sample_story = """μμ°μ μ°κ΅¬μ€μ μ°¨κ°μ΄ νκ΄λ± μλμμ λ λ€λ₯Έ λ°€μ 보λ΄κ³ μμλ€. λͺ¨λν°μ νΈλ₯Έ λΉμ΄ κ·Έλ
μ μ°½λ°±ν μΌκ΅΄μ λΉμΆκ³ μμκ³ , μμ κ°μ μ½λ λΌμΈμ΄ λμμμ΄ μ€ν¬λ‘€λκ³ μμλ€. ARIA νλ‘μ νΈλ κ·Έλ
μ μΆ μ λΆμλ€. 3λ
μ΄λΌλ μκ° λμ κ·Έλ
λ μ΄ μΈκ³΅μ§λ₯μ λͺ¨λ κ²μ μμλΆμλ€.
"μμ€ν
μ²΄ν¬ μλ£. λͺ¨λ νλΌλ―Έν° μ μ." κΈ°κ³μ μΈ μμ±μ΄ μ€νΌμ»€λ₯Ό ν΅ν΄ νλ¬λμλ€.
μμ°μ μ μ μμμ κΈ°λμ΄ λμ κ°μλ€. νΌλ‘κ° λΌ μκΉμ§ νκ³ λ€μμ§λ§, λ©μΆ μ μμλ€. ARIAλ λ¨μν νλ‘μ νΈκ° μλμλ€. κ·Έκ²μ κ·Έλ
κ° μμ΄λ²λ¦° κ²λ€μ λμ°Ύμ μ μλ μ μΌν ν¬λ§μ΄μλ€."""
for i in range(1, 11):
# κ° μκ°λ§λ€ 1,400-1,500λ¨μ΄ μμ±
writer_content = f"μμ±μ {i}λ²μ ννΈμ
λλ€.\n\n"
# μ½ 300λ¨μ΄μ© 5λ² λ°λ³΅νμ¬ 1,400-1,500λ¨μ΄ λ¬μ±
for j in range(5):
writer_content += sample_story + f"\n\nκ·Έκ²μ μκ° {i}μ {j+1}λ²μ§Έ λ¨λ½μ΄μλ€. "
writer_content += "μ΄μΌκΈ°λ κ³μ μ κ°λμκ³ , μΈλ¬Όλ€μ κ°μ μ μ μ λ 볡μ‘ν΄μ‘λ€. " * 15
writer_content += "\n\n"
test_responses[f"writer{i}"] = writer_content
# ν
μ€νΈ λͺ¨λμ© writer10 μλ΅
if role == "writer10":
full_novel = ""
for i in range(2, 11): # Chapter 2λΆν° 10κΉμ§
full_novel += f"[Chapter {i}]\n\n"
# κ° μ±ν°λ§λ€ μ½ 300λ¨μ΄μ© 5λ¨λ½
for j in range(5):
full_novel += sample_story + f"\n\nκ·Έκ²μ μ±ν° {i}μ {j+1}λ²μ§Έ λ¨λ½μ΄μλ€. "
full_novel += "μ΄μΌκΈ°λ κ³μ μ κ°λμκ³ , μΈλ¬Όλ€μ κ°μ μ μ μ λ 볡μ‘ν΄μ‘λ€. " * 20
full_novel += "\n\n"
full_novel += "\n\n" # μ±ν° κ° κ΅¬λΆ
test_responses["writer10"] = full_novel
return test_responses.get(role, "ν
μ€νΈ μλ΅μ
λλ€.")
def get_english_test_response(self, role: str) -> str:
"""English test responses with appropriate length"""
test_responses = {
"director": """I present the 30-page novella plan.
## 1. Theme and Genre
- **Core Theme**: Finding true connection in the collision of human nature and technology
- **Genre**: Sci-fi psychological drama
- **Tone**: Reflective and lyrical yet tense
- **Target Audience**: Adult readers who enjoy deep contemplation
## 2. Character Settings
| Name | Role | Personality | Background | Motivation | Arc |
|------|------|-------------|------------|------------|-----|
| Seoyeon | Protagonist | Rational, lonely | AI researcher | Develop perfect AI companion | Rediscover value of human connection |
| Minjun | Helper | Warm, intuitive | Psychologist | Help Seoyeon find balance | Accept and harmonize with technology |
| ARIA | AntagonistβCompanion | LogicalβLearning emotion | AI prototype | Become truly existent | Establish self-identity |
## 3. Narrative Structure (10 parts, 3 pages each)
| Part | Pages | Main Events | Tension | Character Development |
|------|-------|-------------|---------|---------------------|
| 1 | 1-3 | Seoyeon's lonely lab, ARIA's first awakening | 3/10 | Seoyeon's obsession revealed |
| 2 | 4-6 | ARIA's anomalies begin | 4/10 | Questions arise |
[... continues for all 10 parts ...]""",
"critic": """I have reviewed the director's plan.
## Critique and Improvement Suggestions
### 1. Narrative Completeness
- **Strength**: Timely theme of AI-human relationships
- **Improvement**: 10-part structure is well-balanced. Each part maintains independence while connecting seamlessly.
### 2. Character Review
| Character | Strengths | Weaknesses | Suggestions |
|-----------|-----------|------------|-------------|
| Seoyeon | Clear internal conflict | Risk of insufficient emotion | Place emotional cues from beginning |
| Minjun | Balancer role | Risk of being passive | Needs independent subplot |
| ARIA | Unique character arc | Abstract transformation | Add concrete learning episodes |
### 3. Feasibility
- 3 pages per writer is appropriate
- Need to strengthen inter-part connectivity guidelines""",
}
# Writer responses - 1,400-1,500 words each
sample_story = """Seoyeon spent another night under the cold fluorescent lights of her laboratory. The blue glow from the monitor illuminated her pale face, and dozens of lines of code scrolled endlessly. The ARIA project was her entire life. For three years, she had poured everything into this artificial intelligence.
"System check complete. All parameters normal." The mechanical voice flowed through the speakers.
Seoyeon leaned back in her chair and closed her eyes for a moment. Fatigue penetrated to her bones, but she couldn't stop. ARIA wasn't just a project. It was her only hope to reclaim what she had lost."""
for i in range(1, 11):
# Each writer produces 1,400-1,500 words
writer_content = f"Writer {i} begins their section here.\n\n"
# About 300 words repeated 5 times to achieve 1,400-1,500 words
for j in range(5):
writer_content += sample_story + f"\n\nThis was writer {i}'s paragraph {j+1}. "
writer_content += "The story continued to unfold, and the characters' emotions grew increasingly complex. " * 15
writer_content += "\n\n"
test_responses[f"writer{i}"] = writer_content
# Test mode writer10 response
if role == "writer10":
full_novel = ""
for i in range(2, 11): # Chapters 2-10
full_novel += f"[Chapter {i}]\n\n"
# About 300 words per paragraph, 5 paragraphs per chapter
for j in range(5):
full_novel += sample_story + f"\n\nThis was paragraph {j+1} of chapter {i}. "
full_novel += "The story continued to unfold, and the characters' emotions grew increasingly complex. " * 20
full_novel += "\n\n"
full_novel += "\n\n" # Chapter separation
test_responses["writer10"] = full_novel
return test_responses.get(role, "Test response.")
def process_novel_stream(self, query: str, language: str = "English",
session_id: Optional[str] = None,
resume_from_stage: int = 0,
test_quick_mode: bool = False) -> Generator[Tuple[str, List[Dict[str, str]]], None, None]:
"""Process novel writing with streaming updates - μ΅μ’
Director/Critic μ κ±°"""
try:
global conversation_history
# Create or resume session
if session_id:
self.current_session_id = session_id
session = NovelDatabase.get_session(session_id)
if session:
query = session['user_query']
language = session['language']
resume_from_stage = session['current_stage'] + 1
logger.info(f"Resuming session {session_id} from stage {resume_from_stage}")
else:
self.current_session_id = NovelDatabase.create_session(query, language)
resume_from_stage = 0
logger.info(f"Created new session: {self.current_session_id}")
logger.info(f"Processing novel for session {self.current_session_id}, starting from stage {resume_from_stage}, test_mode={test_quick_mode}")
# Initialize conversation
conversation_history = [{
"role": "human",
"content": query,
"timestamp": datetime.now()
}]
# Load existing stages if resuming
stages = []
if resume_from_stage > 0:
existing_stages = NovelDatabase.get_stages(self.current_session_id)
for stage_data in existing_stages:
stages.append({
"name": stage_data['stage_name'],
"status": stage_data['status'],
"content": stage_data['content'] or ""
})
# Define all stages for 10 writers (μ΅μ’
νκ° μ κ±°)
if test_quick_mode:
# ν
μ€νΈ λͺ¨λ: 1,2,3λ¨κ³ + Writer 1 + Writer 10
stage_definitions = [
("director", f"π¬ {'κ°λ
μ: μ΄κΈ° κΈ°ν' if language == 'Korean' else 'Director: Initial Planning'}"),
("critic", f"π {'λΉνκ°: κΈ°ν κ²ν ' if language == 'Korean' else 'Critic: Plan Review'}"),
("director", f"π¬ {'κ°λ
μ: μμ λ λ§μ€ν°νλ' if language == 'Korean' else 'Director: Revised Masterplan'}"),
("writer1", f"βοΈ {'μμ±μ' if language == 'Korean' else 'Writer'} 1: {'μ΄μ' if language == 'Korean' else 'Draft'}"),
("critic", f"π {'λΉνκ°: μμ±μ' if language == 'Korean' else 'Critic: Writer'} 1 {'κ²ν ' if language == 'Korean' else 'Review'}"),
("writer1", f"βοΈ {'μμ±μ' if language == 'Korean' else 'Writer'} 1: {'μμ λ³Έ' if language == 'Korean' else 'Revision'}"),
("writer10", f"βοΈ {'μμ±μ' if language == 'Korean' else 'Writer'} 10 (TEST): {'λλ¨Έμ§ μμ€' if language == 'Korean' else 'Remaining Novel'}"),
]
else:
stage_definitions = [
("director", f"π¬ {'κ°λ
μ: μ΄κΈ° κΈ°ν' if language == 'Korean' else 'Director: Initial Planning'}"),
("critic", f"π {'λΉνκ°: κΈ°ν κ²ν ' if language == 'Korean' else 'Critic: Plan Review'}"),
("director", f"π¬ {'κ°λ
μ: μμ λ λ§μ€ν°νλ' if language == 'Korean' else 'Director: Revised Masterplan'}"),
]
# Add writer stages for 10 writers
for writer_num in range(1, 11):
stage_definitions.extend([
(f"writer{writer_num}", f"βοΈ {'μμ±μ' if language == 'Korean' else 'Writer'} {writer_num}: {'μ΄μ' if language == 'Korean' else 'Draft'}"),
("critic", f"π {'λΉνκ°: μμ±μ' if language == 'Korean' else 'Critic: Writer'} {writer_num} {'κ²ν ' if language == 'Korean' else 'Review'}"),
(f"writer{writer_num}", f"βοΈ {'μμ±μ' if language == 'Korean' else 'Writer'} {writer_num}: {'μμ λ³Έ' if language == 'Korean' else 'Revision'}")
])
# μ΅μ’
Directorμ Critic λ¨κ³ μ κ±°
# Store total stages for get_stage_prompt
self.total_stages = len(stage_definitions)
# Process stages starting from resume point
for stage_idx in range(resume_from_stage, len(stage_definitions)):
role, stage_name = stage_definitions[stage_idx]
# Add search indicator if enabled
if self.web_search.enabled and not self.test_mode:
stage_name += " π"
# Add stage if not already present
if stage_idx >= len(stages):
stages.append({
"name": stage_name,
"status": "active",
"content": ""
})
else:
stages[stage_idx]["status"] = "active"
yield "", stages
# Get appropriate prompt based on stage
prompt = self.get_stage_prompt(stage_idx, role, query, language, stages, test_quick_mode)
# Create stage info for web search
stage_info = {
'stage_idx': stage_idx,
'query': query,
'stage_name': stage_name,
'test_mode': test_quick_mode
}
stage_content = ""
# Stream content generation with web search
for chunk in self.call_llm_streaming(
[{"role": "user", "content": prompt}],
role,
language,
stage_info
):
stage_content += chunk
stages[stage_idx]["content"] = stage_content
yield "", stages
# Mark stage complete and save to DB
stages[stage_idx]["status"] = "complete"
# Test modeμμλ writer1κ³Ό writer2λ§ μ²λ¦¬
# writer10 κ΄λ ¨ νΉλ³ μ²λ¦¬ μ κ±° - μΌλ° νλ‘μΈμ€μ λμΌ
NovelDatabase.save_stage(
self.current_session_id,
stage_idx,
stage_name,
role,
stage_content,
"complete"
)
# Auto-save notification
if role.startswith("writer"):
writer_num = int(role.replace("writer", ""))
logger.info(f"β
Writer {writer_num} content auto-saved to database")
yield "", stages
# Verify content after completion
if self.current_session_id:
verification = NovelDatabase.verify_novel_content(self.current_session_id)
if test_quick_mode:
logger.info(f"[TEST MODE] Content verification: {verification}")
else:
logger.info(f"Content verification: {verification}")
if verification['total_words'] < 12000 and not test_quick_mode:
logger.error(f"Final novel too short! Only {verification['total_words']} words")
# Get complete novel from DB
complete_novel = NovelDatabase.get_all_writer_content(self.current_session_id, test_quick_mode)
# ν
μ€νΈ λͺ¨λλ©΄ μλ£ μν μ
λ°μ΄νΈ
if test_quick_mode and self.current_session_id:
NovelDatabase.update_final_novel(self.current_session_id, complete_novel)
# Save final novel to DB
NovelDatabase.update_final_novel(self.current_session_id, complete_novel)
# Final yield - νλ©΄μλ μλ£ λ©μμ§λ§ νμ
if test_quick_mode:
final_message = f"β
[TEST MODE] Novel complete! 2 chapters, {len(complete_novel.split())} words total. Click Download to save."
else:
final_message = f"β
Novel complete! {len(complete_novel.split())} words total. Click Download to save."
yield final_message, stages
except Exception as e:
logger.error(f"Error in process_novel_stream: {str(e)}", exc_info=True)
# Save error state to DB
if self.current_session_id:
NovelDatabase.save_stage(
self.current_session_id,
stage_idx if 'stage_idx' in locals() else 0,
"Error",
"error",
str(e),
"error"
)
error_stage = {
"name": "β Error",
"status": "error",
"content": str(e)
}
stages.append(error_stage)
yield f"Error occurred: {str(e)}", stages
def create_test_writer_complete_prompt(self, director_plan: str, language: str = "English") -> str:
"""Test mode - Writer 10 writes complete novel"""
if language == "Korean":
return f"""[ν
μ€νΈ λͺ¨λ] λΉμ μ μ 체 30νμ΄μ§ μμ€μ ν λ²μ μμ±νλ νΉλ³ μκ°μ
λλ€.
κ°λ
μμ λ§μ€ν°νλ:
{director_plan}
**μ€μ μ§μΉ¨:**
1. μ 체 30νμ΄μ§ λΆλμ μμ±λ μμ€μ μμ±νμΈμ
2. μ΄ 14,000-15,000 λ¨μ΄λ‘ μμ±νμΈμ
3. 10κ°μ μμ°μ€λ¬μ΄ μ±ν°λ‘ ꡬμ±νμΈμ (κ° μ±ν° μ½ 1,400-1,500 λ¨μ΄)
4. μμλΆν° κ²°λ§κΉμ§ μμ ν μ΄μΌκΈ°λ₯Ό λ§λμΈμ
5. λ§μ€ν°νλμ λͺ¨λ μμλ₯Ό ν¬ν¨νμΈμ
μ±ν° ꡬλΆμ λ€μκ³Ό κ°μ΄ νμνμΈμ:
[Chapter 1]
λ΄μ©...
[Chapter 2]
λ΄μ©...
μμ±λ λμ μ 체 μμ€μ μμ±νμΈμ."""
else:
return f"""[TEST MODE] You are a special writer creating the complete 30-page novel at once.
Director's Masterplan:
{director_plan}
**CRITICAL INSTRUCTIONS:**
1. Write a complete 30-page novel
2. Total 14,000-15,000 words
3. Organize into 10 natural chapters (each chapter ~1,400-1,500 words)
4. Create a complete story from beginning to end
5. Include all elements from the masterplan
Mark chapters as follows:
[Chapter 1]
content...
[Chapter 2]
content...
Write a high-quality complete novel."""
def get_stage_prompt(self, stage_idx: int, role: str, query: str,
language: str, stages: List[Dict], test_mode: bool = False) -> str:
"""Get appropriate prompt for each stage"""
# Stage 0: Director Initial
if stage_idx == 0:
return self.create_director_initial_prompt(query, language)
# Stage 1: Critic reviews Director's plan
elif stage_idx == 1:
return self.create_critic_director_prompt(stages[0]["content"], language)
# Stage 2: Director revision
elif stage_idx == 2:
return self.create_director_revision_prompt(
stages[0]["content"], stages[1]["content"], language)
# Writer stages
elif role.startswith("writer"):
writer_num = int(role.replace("writer", ""))
final_plan = stages[2]["content"] # Director's final plan
# Test mode special writer10
if role == "writer10" and test_mode:
# Get writer1's revision content
writer1_content = ""
for i, stage in enumerate(stages):
if "Writer 1: Revision" in stage["name"] or "μμ±μ 1: μμ λ³Έ" in stage["name"]:
writer1_content = stage["content"]
break
return self.create_test_writer_remaining_prompt(final_plan, writer1_content, language)
# Initial draft or revision?
if "μ΄μ" in stages[stage_idx]["name"] or "Draft" in stages[stage_idx]["name"]:
# Get accumulated content from DB
accumulated_content = NovelDatabase.get_all_writer_content(self.current_session_id)
return self.create_writer_prompt(writer_num, final_plan, accumulated_content, language)
else: # Revision
# Find the initial draft and critic feedback
initial_draft_idx = stage_idx - 2
critic_feedback_idx = stage_idx - 1
return self.create_writer_revision_prompt(
writer_num,
stages[initial_draft_idx]["content"],
stages[critic_feedback_idx]["content"],
language
)
# Critic stages for writers
elif role == "critic":
final_plan = stages[2]["content"]
# Writer review
# Find which writer we're reviewing
for i in range(1, 11):
if f"μμ±μ {i}" in stages[stage_idx]["name"] or f"Writer {i}" in stages[stage_idx]["name"]:
writer_content_idx = stage_idx - 1
# Get previous writers' content from DB
previous_content = NovelDatabase.get_all_writer_content(self.current_session_id)
return self.create_critic_writer_prompt(
i,
stages[writer_content_idx]["content"],
final_plan,
previous_content,
language
)
return ""
# Gradio Interface Functions
def process_query(query: str, language: str, session_id: str = None, test_mode: bool = False) -> Generator[Tuple[str, str, str, str], None, None]:
"""Process query and yield updates with session ID"""
if not query.strip() and not session_id:
if language == "Korean":
yield "", "", "β μμ€ μ£Όμ λ₯Ό μ
λ ₯ν΄μ£ΌμΈμ.", None
else:
yield "", "", "β Please enter a novel theme.", None
return
system = NovelWritingSystem()
try:
# Status message with mode indicator
mode_status = ""
if session_id:
if language == "Korean":
mode_status = " [β»οΈ 볡ꡬ λͺ¨λ]"
else:
mode_status = " [β»οΈ Recovery Mode]"
elif test_mode:
if language == "Korean":
mode_status = " [π§ͺ ν
μ€νΈ λͺ¨λ: 7λ¨κ³]"
else:
mode_status = " [π§ͺ Test Mode: 7 stages]"
for final_novel, stages in system.process_novel_stream(query, language, session_id, test_quick_mode=test_mode):
# Format stages for display
stages_display = format_stages_display(stages, language)
# Progress calculation
completed = sum(1 for s in stages if s.get("status") == "complete")
total = len(stages)
progress_percent = (completed / total * 100) if total > 0 else 0
if "β
Novel complete!" in str(final_novel) or "β
[TEST MODE] Novel complete!" in str(final_novel):
status = f"β
Complete! Ready to download.{mode_status}"
else:
if language == "Korean":
status = f"π μ§νμ€... ({completed}/{total} - {progress_percent:.1f}%){mode_status}"
else:
status = f"π Processing... ({completed}/{total} - {progress_percent:.1f}%){mode_status}"
# Return current session ID
yield stages_display, final_novel, status, system.current_session_id
except Exception as e:
logger.error(f"Error in process_query: {str(e)}", exc_info=True)
if language == "Korean":
yield "", "", f"β μ€λ₯ λ°μ: {str(e)}", None
else:
yield "", "", f"β Error occurred: {str(e)}", None
def format_stages_display(stages: List[Dict[str, str]], language: str) -> str:
"""Format stages into simple display with writer save status"""
display = ""
for idx, stage in enumerate(stages):
status_icon = "β
" if stage.get("status") == "complete" else ("β³" if stage.get("status") == "active" else "β")
# Add save indicator for completed writers
save_indicator = ""
if "Writer" in stage['name'] and "Revision" in stage['name'] and stage.get("status") == "complete":
save_indicator = " πΎ"
# Show only active stage content in detail, others just show status
if stage.get("status") == "active":
display += f"\n\n{status_icon} **{stage['name']}**\n"
display += f"```\n{stage.get('content', '')[-1000:]}\n```"
else:
display += f"\n{status_icon} {stage['name']}{save_indicator}"
return display
def get_active_sessions(language: str) -> List[Tuple[str, str]]:
"""Get list of active sessions"""
try:
sessions = NovelDatabase.get_active_sessions()
choices = []
for session in sessions:
created = NovelDatabase.parse_datetime(session['created_at'])
date_str = created.strftime("%Y-%m-%d %H:%M")
query_preview = session['user_query'][:50] + "..." if len(session['user_query']) > 50 else session['user_query']
label = f"[{date_str}] {query_preview} (Stage {session['current_stage']})"
choices.append((label, session['session_id']))
return choices
except Exception as e:
logger.error(f"Error getting active sessions: {str(e)}", exc_info=True)
return []
def resume_session(session_id: str, language: str, test_mode: bool = False) -> Generator[Tuple[str, str, str, str], None, None]:
"""Resume an existing session"""
if not session_id:
if language == "Korean":
yield "", "", "β μΈμ
μ μ νν΄μ£ΌμΈμ.", None
else:
yield "", "", "β Please select a session.", None
return
# Process with existing session ID
yield from process_query("", language, session_id, test_mode)
def auto_recover_session(language: str) -> Tuple[str, str]:
"""Auto recover the latest active session"""
try:
latest_session = NovelDatabase.get_latest_active_session()
if latest_session:
if language == "Korean":
message = f"β
μλ 볡ꡬ: '{latest_session['user_query'][:30]}...' (Stage {latest_session['current_stage']})"
else:
message = f"β
Auto recovered: '{latest_session['user_query'][:30]}...' (Stage {latest_session['current_stage']})"
return latest_session['session_id'], message
else:
return None, ""
except Exception as e:
logger.error(f"Error in auto recovery: {str(e)}")
return None, ""
def download_novel(novel_text: str, format: str, language: str, session_id: str = None) -> str:
"""Download novel - DBμμ μ§μ μκ° λ΄μ©μ κ°μ Έμμ ν΅ν©"""
if not session_id:
logger.error("No session_id provided for download")
return None
logger.info(f"Starting download for session: {session_id}, format: {format}")
# DBμμ μΈμ
μ 보 κ°μ Έμ€κΈ°
session = NovelDatabase.get_session(session_id)
if not session:
logger.error(f"Session not found: {session_id}")
return None
# μΈμ
μ μ€μ μΈμ΄ μ¬μ© (νλΌλ―Έν°λ‘ λ°μ language λμ )
actual_language = session['language']
logger.info(f"Using session language: {actual_language} (parameter was: {language})")
# DBμμ λͺ¨λ μ€ν
μ΄μ§ κ°μ Έμ€κΈ°
stages = NovelDatabase.get_stages(session_id)
logger.info(f"Found {len(stages)} stages in database")
# λλ²κΉ
: λͺ¨λ stage μ 보 μΆλ ₯
for i, stage in enumerate(stages):
role = stage['role'] if 'role' in stage.keys() else 'None'
stage_name = stage['stage_name'] if 'stage_name' in stage.keys() else 'None'
content_len = len(stage['content']) if 'content' in stage.keys() and stage['content'] else 0
status = stage['status'] if 'status' in stage.keys() else 'None'
logger.debug(f"Stage {i}: role={role}, stage_name={stage_name}, content_length={content_len}, status={status}")
# ν
μ€νΈ λͺ¨λ κ°μ§ - writer10μ΄ μμΌλ©΄ ν
μ€νΈ λͺ¨λ
is_test_mode = False
has_writer10 = any(stage['role'] == 'writer10' for stage in stages if 'role' in stage.keys())
has_writer1 = any(stage['role'] == 'writer1' for stage in stages if 'role' in stage.keys())
has_writer3 = any(stage['role'] == 'writer3' for stage in stages if 'role' in stage.keys())
if has_writer10 and has_writer1 and not has_writer3:
is_test_mode = True
logger.info("Test mode detected - writer1 + writer10 mode")
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
if format == "DOCX" and DOCX_AVAILABLE:
# Create DOCX
doc = Document()
# μ λͺ© νμ΄μ§
title_para = doc.add_paragraph()
title_run = title_para.add_run('AI Collaborative Novel' + (' - Test Mode' if is_test_mode else ''))
title_run.font.size = Pt(24)
title_run.font.bold = True
title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.add_paragraph()
doc.add_paragraph()
theme_para = doc.add_paragraph()
theme_run = theme_para.add_run(f'Theme: {session["user_query"]}')
theme_run.font.size = Pt(14)
theme_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.add_paragraph()
date_para = doc.add_paragraph()
date_run = date_para.add_run(f'Created: {datetime.now().strftime("%Y-%m-%d")}')
date_run.font.size = Pt(12)
date_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.add_page_break()
# μ 체 ν΅κ³
total_words = 0
writer_count = 0
# κ° μκ°μ μμ λ³Έλ§ μμ§
writer_contents = []
if is_test_mode:
# ν
μ€νΈ λͺ¨λ: writer1 revision + writer10 λ΄μ© μ²λ¦¬
for stage in stages:
role = stage['role'] if 'role' in stage.keys() else None
stage_name = stage['stage_name'] if 'stage_name' in stage.keys() else ''
content = stage['content'] if 'content' in stage.keys() else ''
logger.info(f"[TEST MODE] Checking stage: role={role}, name={stage_name}, status={stage['status'] if 'status' in stage.keys() else 'None'}")
# Writer 1 μμ λ³Έ
if role == 'writer1' and stage_name and ('Revision' in stage_name or 'μμ λ³Έ' in stage_name):
content = re.sub(r'\[(?:νμ΄μ§|Page|page)\s*\d+\]', '', content)
content = re.sub(r'(?:νμ΄μ§|Page)\s*\d+:', '', content)
content = content.strip()
if content:
word_count = stage['word_count'] if 'word_count' in stage.keys() else len(content.split())
total_words += word_count
writer_contents.append({
'writer_num': 1,
'content': content,
'word_count': word_count
})
writer_count = 1
logger.info(f"Added writer 1 (Chapter 1): {word_count} words")
# Writer 10 (ν
μ€νΈ λͺ¨λμμ λλ¨Έμ§ μ±ν°λ€)
elif role == 'writer10':
logger.info(f"Processing writer10 content: {len(content)} chars")
# [Chapter X] ν¨ν΄μΌλ‘ μ±ν° λΆλ¦¬
chapters = re.split(r'\[Chapter\s+(\d+)\]', content)
# chaptersλ ['', '2', 'content2', '3', 'content3', ...] νν
for i in range(1, len(chapters), 2):
if i+1 < len(chapters):
chapter_num = int(chapters[i])
chapter_content = chapters[i+1].strip()
if chapter_content:
word_count = len(chapter_content.split())
total_words += word_count
writer_contents.append({
'writer_num': chapter_num,
'content': chapter_content,
'word_count': word_count
})
writer_count = max(writer_count, chapter_num)
logger.info(f"Added Chapter {chapter_num}: {word_count} words")
else:
# μΌλ° λͺ¨λ: λͺ¨λ μκ° μμ λ³Έ μ²λ¦¬
logger.info("[NORMAL MODE] Processing all writer revisions...")
for stage in stages:
role = stage['role'] if 'role' in stage.keys() else None
stage_name = stage['stage_name'] if 'stage_name' in stage.keys() else ''
content = stage['content'] if 'content' in stage.keys() else ''
status = stage['status'] if 'status' in stage.keys() else ''
# λλ²κΉ
μ 보
logger.debug(f"[NORMAL MODE] Checking: role={role}, name={stage_name}, status={status}, content_len={len(content)}")
# μΈμ΄μ μκ΄μμ΄ μκ° μμ λ³Έ μ°ΎκΈ°
is_writer = role and role.startswith('writer')
is_revision = stage_name and ('Revision' in stage_name or 'μμ λ³Έ' in stage_name)
if is_writer and is_revision:
# μκ° λ²νΈ μΆμΆ
try:
writer_num = int(role.replace('writer', ''))
logger.info(f"Found writer {writer_num} revision - stage_name: {stage_name}")
except:
logger.warning(f"Could not extract writer number from role: {role}")
continue
# νμ΄μ§ λ§ν¬ μ κ±°
content = re.sub(r'\[(?:νμ΄μ§|Page|page)\s*\d+\]', '', content)
content = re.sub(r'(?:νμ΄μ§|Page)\s*\d+:', '', content)
content = content.strip()
if content:
word_count = stage['word_count'] if 'word_count' in stage.keys() else len(content.split())
total_words += word_count
writer_contents.append({
'writer_num': writer_num,
'content': content,
'word_count': word_count
})
writer_count += 1 # μ€μ μκ° μ μΉ΄μ΄νΈ
logger.info(f"Added writer {writer_num}: {word_count} words, content length: {len(content)}")
else:
logger.warning(f"Writer {writer_num} has empty content after cleaning")
logger.info(f"Total writers collected: {writer_count}, Total words: {total_words}")
logger.info(f"Writer contents: {len(writer_contents)} entries")
# ν΅κ³ νμ΄μ§
doc.add_heading('Novel Statistics', 1)
doc.add_paragraph(f'Mode: {"Test Mode (Actual chapters written)" if is_test_mode else "Full Mode (10 chapters)"}')
doc.add_paragraph(f'Total Chapters: {writer_count}')
doc.add_paragraph(f'Total Words: {total_words:,}')
doc.add_paragraph(f'Estimated Pages: ~{total_words/500:.0f}')
doc.add_paragraph(f'Language: {actual_language}')
doc.add_page_break()
# λͺ©μ°¨
if writer_contents:
doc.add_heading('Table of Contents', 1)
# writer_contentsλ₯Ό writer_numμΌλ‘ μ λ ¬
sorted_contents = sorted(writer_contents, key=lambda x: x['writer_num'])
for item in sorted_contents:
chapter_num = item['writer_num']
doc.add_paragraph(f'Chapter {chapter_num}: Pages {(chapter_num-1)*3+1}-{chapter_num*3}')
doc.add_page_break()
# κ° μκ°μ λ΄μ© μΆκ° (μ λ ¬λ μμλλ‘)
for idx, writer_data in enumerate(sorted_contents):
writer_num = writer_data['writer_num']
content = writer_data['content']
word_count = writer_data['word_count']
# μ±ν° ν€λ
doc.add_heading(f'Chapter {writer_num}', 1)
doc.add_paragraph(f'Pages {(writer_num-1)*3+1}-{writer_num*3}')
doc.add_paragraph(f'Word Count: {word_count:,}')
doc.add_paragraph()
# μκ° λ΄μ© μΆκ°
paragraphs = content.split('\n\n')
for para_text in paragraphs:
if para_text.strip():
para = doc.add_paragraph(para_text.strip())
para.style.font.size = Pt(11)
if idx < len(sorted_contents) - 1: # λ§μ§λ§ μ±ν° νμλ νμ΄μ§ κ΅¬λΆ μμ
doc.add_page_break()
else:
logger.warning("No writer contents found! Creating empty document.")
doc.add_paragraph("No content found. Please check if the novel generation completed successfully.")
# νμ΄μ§ μ€μ
for section in doc.sections:
section.page_height = Inches(11)
section.page_width = Inches(8.5)
section.left_margin = Inches(1)
section.right_margin = Inches(1)
section.top_margin = Inches(1)
section.bottom_margin = Inches(1)
# Save
temp_dir = tempfile.gettempdir()
safe_filename = re.sub(r'[^\w\s-]', '', session['user_query'][:30]).strip()
mode_suffix = "_TestMode" if is_test_mode else "_Complete"
filename = f"Novel{mode_suffix}_{safe_filename}_{timestamp}.docx"
filepath = os.path.join(temp_dir, filename)
doc.save(filepath)
logger.info(f"DOCX saved successfully: {filepath} ({total_words} words, {writer_count} writers)")
return filepath
else:
# TXT format - λμΌν μμ μ μ©
temp_dir = tempfile.gettempdir()
safe_filename = re.sub(r'[^\w\s-]', '', session['user_query'][:30]).strip()
mode_suffix = "_TestMode" if is_test_mode else "_Complete"
filename = f"Novel{mode_suffix}_{safe_filename}_{timestamp}.txt"
filepath = os.path.join(temp_dir, filename)
with open(filepath, 'w', encoding='utf-8') as f:
f.write("="*60 + "\n")
f.write(f"AI COLLABORATIVE NOVEL - {'TEST MODE' if is_test_mode else 'COMPLETE VERSION'}\n")
f.write("="*60 + "\n")
f.write(f"Theme: {session['user_query']}\n")
f.write(f"Language: {actual_language}\n")
f.write(f"Created: {datetime.now()}\n")
f.write(f"Mode: {'Test Mode (Actual chapters)' if is_test_mode else 'Full Mode (10 chapters)'}\n")
f.write("="*60 + "\n\n")
total_words = 0
writer_count = 0
if is_test_mode:
# ν
μ€νΈ λͺ¨λ: writer1 + writer10 μ²λ¦¬
for stage in stages:
role = stage['role'] if 'role' in stage.keys() else None
stage_name = stage['stage_name'] if 'stage_name' in stage.keys() else ''
content = stage['content'] if 'content' in stage.keys() else ''
# Writer 1 μμ λ³Έ
if role == 'writer1' and stage_name and ('Revision' in stage_name or 'μμ λ³Έ' in stage_name):
content = re.sub(r'\[(?:νμ΄μ§|Page|page)\s*\d+\]', '', content)
content = re.sub(r'(?:νμ΄μ§|Page)\s*\d+:', '', content)
content = content.strip()
if content:
word_count = stage['word_count'] if 'word_count' in stage.keys() else len(content.split())
total_words += word_count
writer_count = 1
f.write(f"\n{'='*40}\n")
f.write(f"CHAPTER 1 (Pages 1-3)\n")
f.write(f"Word Count: {word_count:,}\n")
f.write(f"{'='*40}\n\n")
f.write(content)
f.write("\n\n")
# Writer 10
elif role == 'writer10':
# [Chapter X] ν¨ν΄μΌλ‘ μ±ν° λΆλ¦¬
chapters = re.split(r'\[Chapter\s+(\d+)\]', content)
for i in range(1, len(chapters), 2):
if i+1 < len(chapters):
chapter_num = int(chapters[i])
chapter_content = chapters[i+1].strip()
if chapter_content:
word_count = len(chapter_content.split())
total_words += word_count
writer_count = max(writer_count, chapter_num)
f.write(f"\n{'='*40}\n")
f.write(f"CHAPTER {chapter_num} (Pages {(chapter_num-1)*3+1}-{chapter_num*3})\n")
f.write(f"Word Count: {word_count:,}\n")
f.write(f"{'='*40}\n\n")
f.write(chapter_content)
f.write("\n\n")
else:
# μΌλ° λͺ¨λ - μμ λ λ‘μ§
for stage in stages:
role = stage['role'] if 'role' in stage.keys() else None
stage_name = stage['stage_name'] if 'stage_name' in stage.keys() else ''
content = stage['content'] if 'content' in stage.keys() else ''
# μΈμ΄μ μκ΄μμ΄ μκ° μμ λ³Έ μ°ΎκΈ°
is_writer = role and role.startswith('writer')
is_revision = stage_name and ('Revision' in stage_name or 'μμ λ³Έ' in stage_name)
if is_writer and is_revision:
# μκ° λ²νΈ μΆμΆ
try:
writer_num = int(role.replace('writer', ''))
except:
continue
# νμ΄μ§ λ§ν¬ μ κ±°
content = re.sub(r'\[(?:νμ΄μ§|Page|page)\s*\d+\]', '', content)
content = re.sub(r'(?:νμ΄μ§|Page)\s*\d+:', '', content)
content = content.strip()
if content:
word_count = stage['word_count'] if 'word_count' in stage.keys() else len(content.split())
total_words += word_count
writer_count += 1
f.write(f"\n{'='*40}\n")
f.write(f"CHAPTER {writer_num} (Pages {(writer_num-1)*3+1}-{writer_num*3})\n")
f.write(f"Word Count: {word_count:,}\n")
f.write(f"{'='*40}\n\n")
f.write(content)
f.write("\n\n")
f.write(f"\n{'='*60}\n")
f.write(f"TOTAL: {writer_count} chapters, {total_words:,} words\n")
f.write(f"{'='*60}\n")
logger.info(f"TXT saved successfully: {filepath} ({total_words} words)")
return filepath
# Custom CSS
custom_css = """
.gradio-container {
background: linear-gradient(135deg, #1e3c72, #2a5298);
min-height: 100vh;
}
.main-header {
background-color: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 30px;
border-radius: 12px;
margin-bottom: 30px;
text-align: center;
color: white;
}
.input-section {
background-color: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 20px;
border-radius: 12px;
margin-bottom: 20px;
}
.session-section {
background-color: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 15px;
border-radius: 8px;
margin-top: 20px;
color: white;
}
#stages-display {
background-color: rgba(255, 255, 255, 0.95);
padding: 20px;
border-radius: 12px;
max-height: 600px;
overflow-y: auto;
}
#novel-output {
background-color: rgba(255, 255, 255, 0.95);
padding: 30px;
border-radius: 12px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
max-height: 400px;
overflow-y: auto;
}
.download-section {
background-color: rgba(255, 255, 255, 0.9);
padding: 15px;
border-radius: 8px;
margin-top: 20px;
}
.search-indicator {
color: #4CAF50;
font-weight: bold;
}
.auto-save-indicator {
color: #2196F3;
font-weight: bold;
}
"""
# Create Gradio Interface
def create_interface():
with gr.Blocks(css=custom_css, title="SOMA Novel Writing System") as interface:
gr.HTML("""
<div class="main-header">
<h1 style="font-size: 2.5em; margin-bottom: 10px;">
π SOMA Novel Writing System
</h1>
<h3 style="color: #ccc; margin-bottom: 20px;">
AI Collaborative Novel Generation - 10 Writers Edition
</h3>
<p style="font-size: 1.1em; color: #ddd; max-width: 800px; margin: 0 auto;">
Enter a theme or prompt, and watch as AI agents collaborate to create a complete 30-page novella.
The system includes 1 Director, 1 Critic, and 10 Writers working in harmony.
<br><br>
<span class="search-indicator">π Web search enabled</span> |
<span class="auto-save-indicator">πΎ Auto-save to database</span> |
<span style="color: #FF9800;">β»οΈ Resume anytime</span> |
<span style="color: #FFC107;">π§ͺ Test mode: 7 stages (Writer 1 + Writer 10)</span>
</p>
</div>
""")
# State management
current_session_id = gr.State(None)
with gr.Row():
with gr.Column(scale=1):
with gr.Group(elem_classes=["input-section"]):
query_input = gr.Textbox(
label="Novel Theme / μμ€ μ£Όμ ",
placeholder="Enter your novel theme or initial idea...\nμμ€μ μ£Όμ λ μ΄κΈ° μμ΄λμ΄λ₯Ό μ
λ ₯νμΈμ...",
lines=4
)
language_select = gr.Radio(
choices=["English", "Korean"],
value="English",
label="Language / μΈμ΄"
)
# Test mode checkbox
test_mode_check = gr.Checkbox(
label="π§ͺ Test Mode (Quick: Writer 1 & 10 only) / ν
μ€νΈ λͺ¨λ (λΉ λ₯Έ μμ±: μκ° 1, 10λ§)",
value=False,
info="Complete Writer 1 & 10 process for 10 chapters / μκ° 1, 10λ§ μμ±νμ¬ 10κ° μ±ν° μμ±"
)
# Web search status indicator
web_search_status = gr.Markdown(
value=f"π **Web Search:** {'Enabled' if WebSearchIntegration().enabled else 'Disabled (Set BRAVE_SEARCH_API_KEY)'}"
)
with gr.Row():
submit_btn = gr.Button("π Start Writing / μμ± μμ", variant="primary", scale=2)
clear_btn = gr.Button("ποΈ Clear / μ΄κΈ°ν", scale=1)
status_text = gr.Textbox(
label="Status",
interactive=False,
value="π Ready"
)
# Session management
with gr.Group(elem_classes=["session-section"]):
gr.Markdown("### πΎ Resume Previous Session / μ΄μ μΈμ
μ¬κ°")
session_dropdown = gr.Dropdown(
label="Select Session / μΈμ
μ ν",
choices=[],
interactive=True
)
with gr.Row():
refresh_btn = gr.Button("π Refresh List / λͺ©λ‘ μλ‘κ³ μΉ¨", scale=1)
resume_btn = gr.Button("βΆοΈ Resume Selected / μ ν μ¬κ°", variant="secondary", scale=1)
auto_recover_btn = gr.Button("β»οΈ Auto Recover Latest / μ΅μ μλ볡ꡬ", scale=1)
with gr.Column(scale=2):
with gr.Tab("π Writing Process / μμ± κ³Όμ "):
stages_display = gr.Markdown(
value="Process will appear here...",
elem_id="stages-display"
)
with gr.Tab("π Final Novel / μ΅μ’
μμ€"):
novel_output = gr.Markdown(
value="Complete novel will be available for download after all writers finish.",
elem_id="novel-output"
)
with gr.Group(elem_classes=["download-section"]):
gr.Markdown("### π₯ Download Complete Novel / μ 체 μμ€ λ€μ΄λ‘λ")
with gr.Row():
format_select = gr.Radio(
choices=["DOCX", "TXT"],
value="DOCX" if DOCX_AVAILABLE else "TXT",
label="Format / νμ"
)
download_btn = gr.Button("β¬οΈ Download Complete Novel / μμ±λ μμ€ λ€μ΄λ‘λ", variant="secondary")
download_file = gr.File(
label="Downloaded File / λ€μ΄λ‘λλ νμΌ",
visible=False
)
# Hidden state for novel text
novel_text_state = gr.State("")
# Examples
with gr.Row():
gr.Examples(
examples=[
["A scientist discovers a portal to parallel universes but each journey erases a memory"],
["In a world where dreams can be traded, a dream thief must steal the emperor's nightmare"],
["Two AI entities fall in love while trying to prevent a global cyber war"],
["λ―Έλ λμμμ κΈ°μ΅μ κ±°λνλ μμΈκ³Ό λͺ¨λ κΈ°μ΅μ μμ νμ μ μ΄μΌκΈ°"],
["μκ°μ΄ κ±°κΎΈλ‘ νλ₯΄λ λ§μμμ μΌμ΄λλ λ―Έμ€ν°λ¦¬ν μ΄μΈ μ¬κ±΄"],
["μ±
μμΌλ‘ λ€μ΄κ° μ μλ λ₯λ ₯μ κ°μ§ μ¬μμ λͺ¨ν"]
],
inputs=query_input,
label="π‘ Example Themes / μμ μ£Όμ "
)
# Event handlers
def refresh_sessions():
try:
sessions = get_active_sessions("English")
return gr.update(choices=sessions)
except Exception as e:
logger.error(f"Error refreshing sessions: {str(e)}", exc_info=True)
return gr.update(choices=[])
def handle_auto_recover(language):
session_id, message = auto_recover_session(language)
return session_id
# Connect event handlers
submit_btn.click(
fn=process_query,
inputs=[query_input, language_select, current_session_id, test_mode_check],
outputs=[stages_display, novel_output, status_text, current_session_id]
)
# Update novel text state and session ID when novel output changes
novel_output.change(
fn=lambda x: x,
inputs=[novel_output],
outputs=[novel_text_state]
)
resume_btn.click(
fn=lambda x: x,
inputs=[session_dropdown],
outputs=[current_session_id]
).then(
fn=resume_session,
inputs=[current_session_id, language_select, test_mode_check],
outputs=[stages_display, novel_output, status_text, current_session_id]
)
auto_recover_btn.click(
fn=handle_auto_recover,
inputs=[language_select],
outputs=[current_session_id]
).then(
fn=resume_session,
inputs=[current_session_id, language_select, test_mode_check],
outputs=[stages_display, novel_output, status_text, current_session_id]
)
refresh_btn.click(
fn=refresh_sessions,
outputs=[session_dropdown]
)
clear_btn.click(
fn=lambda: ("", "", "π Ready", "", None, False),
outputs=[stages_display, novel_output, status_text, novel_text_state, current_session_id, test_mode_check]
)
def handle_download(format_type, language, session_id, novel_text):
logger.info(f"Download requested: format={format_type}, session_id={session_id}, language={language}")
logger.info(f"Session ID type: {type(session_id)}, value: {repr(session_id)}")
if not session_id:
logger.error("No session_id available for download")
return gr.update(visible=False)
file_path = download_novel(novel_text, format_type, language, session_id)
if file_path:
logger.info(f"Download successful: {file_path}")
return gr.update(value=file_path, visible=True)
else:
logger.error("Download failed - no file generated")
return gr.update(visible=False)
download_btn.click(
fn=handle_download,
inputs=[format_select, language_select, current_session_id, novel_text_state],
outputs=[download_file]
)
# Load sessions on startup
def on_load():
sessions = refresh_sessions()
return sessions
interface.load(
fn=on_load,
outputs=[session_dropdown]
)
return interface
# Main execution
if __name__ == "__main__":
import sys
logger.info("Starting SOMA Novel Writing System - 10 Writers Edition...")
# Check environment
if TEST_MODE:
logger.warning("Running in TEST MODE - no actual API calls will be made")
else:
logger.info(f"Running in PRODUCTION MODE with API endpoint: {API_URL}")
# Check web search
if BRAVE_SEARCH_API_KEY:
logger.info("Web search is ENABLED with Brave Search API")
else:
logger.warning("Web search is DISABLED. Set BRAVE_SEARCH_API_KEY environment variable to enable.")
# Initialize database on startup
logger.info("Initializing database...")
NovelDatabase.init_db()
logger.info("Database initialized successfully.")
interface = create_interface()
interface.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
debug=True
) |