Spaces:
Running
Running
File size: 80,517 Bytes
0757e01 bc3c24f f1c8e7a ea03161 03ea80e 9e6ddb9 ea03161 0757e01 03ea80e 439f7d3 03ea80e 439f7d3 03ea80e 0757e01 03ea80e 0757e01 3b1f529 f1c8e7a 3b1f529 f1c8e7a 3b1f529 f1c8e7a ea03161 f1c8e7a 3b1f529 f1c8e7a 3b1f529 bc3c24f 90e504e 0757e01 90e504e e555439 113235c d4221a2 113235c 113a841 0757e01 3b1f529 90e504e 3b1f529 f1c8e7a 3b1f529 0757e01 bc3c24f 3b1f529 f1c8e7a 3b1f529 f1c8e7a 3b1f529 f1c8e7a 3b1f529 bc3c24f 3b1f529 03ea80e bc3c24f 03ea80e f1c8e7a 3b1f529 f1c8e7a 03ea80e f1c8e7a 3b1f529 f1c8e7a 3b1f529 bc3c24f 03ea80e bc3c24f 3b1f529 bc3c24f 3b1f529 f1c8e7a 3b1f529 f1c8e7a 3b1f529 f1c8e7a 3b1f529 bc3c24f 90e504e 0757e01 90e504e 0757e01 90e504e 0757e01 90e504e 0757e01 03ea80e 0757e01 a72ee70 0757e01 a72ee70 0757e01 a72ee70 0757e01 a72ee70 0757e01 e40050a 03ea80e e40050a 90e504e e40050a e555439 e40050a 1e8a5aa e555439 d4221a2 e40050a d4221a2 e555439 113235c 03ea80e e40050a 03ea80e e40050a b0baf04 439f7d3 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 b8b22fd d4221a2 439f7d3 b8b22fd 439f7d3 9e6ddb9 439f7d3 a72ee70 439f7d3 d4221a2 b8b22fd d4221a2 a72ee70 439f7d3 a72ee70 439f7d3 d4221a2 439f7d3 b0baf04 439f7d3 b0baf04 e40050a 0e258f0 b0baf04 e40050a 439f7d3 e40050a b0baf04 90e504e 439f7d3 b0baf04 74af759 e555439 03ea80e 1e8a5aa e555439 113235c 439f7d3 e40050a 439f7d3 03ea80e 439f7d3 a72ee70 439f7d3 03ea80e 439f7d3 a72ee70 03ea80e 439f7d3 03ea80e a72ee70 03ea80e 439f7d3 03ea80e f1c8e7a 439f7d3 f1c8e7a 439f7d3 f1c8e7a 439f7d3 f1c8e7a 439f7d3 f1c8e7a b0baf04 439f7d3 b0baf04 439f7d3 b0baf04 439f7d3 b0baf04 439f7d3 b0baf04 439f7d3 b0baf04 439f7d3 b0baf04 439f7d3 b0baf04 03ea80e 439f7d3 b8b22fd 439f7d3 f04e940 439f7d3 b8b22fd 439f7d3 0757e01 90e504e 0757e01 | 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 | import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { HfInference } from '@huggingface/inference';
import fs from 'fs';
import path from 'path';
import { createClient } from '@supabase/supabase-js';
import ws from 'ws';
import { fileURLToPath } from 'url';
import { ZipArchive } from 'archiver';
// Fix for Node.js < 22: inject ws as global WebSocket for Supabase Realtime
if (!globalThis.WebSocket) {
globalThis.WebSocket = ws;
}
// Load environment variables
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const publicDir = path.join(__dirname, 'public');
const productsDir = path.join(publicDir, 'products');
const coversDir = path.join(publicDir, 'covers');
const packagesDir = path.join(publicDir, 'packages');
if (!fs.existsSync(publicDir)) fs.mkdirSync(publicDir, { recursive: true });
if (!fs.existsSync(productsDir)) fs.mkdirSync(productsDir, { recursive: true });
if (!fs.existsSync(coversDir)) fs.mkdirSync(coversDir, { recursive: true });
if (!fs.existsSync(packagesDir)) fs.mkdirSync(packagesDir, { recursive: true });
// Enable CORS so the React frontend on 5173 can talk to our API on 5000
app.use(cors());
app.use(express.json());
app.use('/static', express.static(publicDir));
// ----------------------------------------------------
// DATABASE CONFIGURATION: SUPABASE WITH JSON FALLBACK
// ----------------------------------------------------
let isSupabaseConnected = false;
let supabase = null;
// Attempt Supabase Connection if credentials are provided
if (process.env.SUPABASE_URL && process.env.SUPABASE_KEY && !process.env.SUPABASE_URL.includes('your-project-id')) {
console.log('π Connecting to Supabase Cloud Database...');
try {
supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY, {
realtime: { transport: ws }
});
isSupabaseConnected = true;
console.log('β
Connected to Supabase Cloud Database!');
} catch (err) {
console.error('β Supabase Connection Error:', err.message);
console.log('β οΈ Falling back to Local JSON Database.');
}
} else {
console.log('βΉοΈ Supabase credentials not set or using template. Using Local JSON Database.');
}
// JSON File Database Fallback Configuration
const DB_FILE = path.join(process.cwd(), 'db.json');
const readDb = () => {
try {
if (!fs.existsSync(DB_FILE)) {
const defaultCatalog = [
{
id: '1',
title: 'ADHD Daily Focus Study Planner 2026',
subtitle: 'The Ultimate Aesthetic Organization Notebook for Neurodivergent College Students',
type: 'planner',
price: 9.99,
date: new Date().toLocaleDateString()
},
{
id: '2',
title: 'AWS Certified Solutions Architect Study Guide SAA-C03',
subtitle: 'The 30-Day Cram Sheet & High-Performance Practice Exam Bank',
type: 'study_guide',
price: 14.99,
date: new Date().toLocaleDateString()
}
];
fs.writeFileSync(DB_FILE, JSON.stringify(defaultCatalog, null, 2));
return defaultCatalog;
}
return JSON.parse(fs.readFileSync(DB_FILE, 'utf8'));
} catch (err) {
return [];
}
};
const writeDb = (data) => {
fs.writeFileSync(DB_FILE, JSON.stringify(data, null, 2));
};
// Initialize Hugging Face Inference (used ONLY for SDXL image generation)
const hf = new HfInference(process.env.HF_API_KEY || '');
// ----------------------------------------------------
// GROQ LLAMA 3.3 70B β Primary Text Generation Engine
// ----------------------------------------------------
const groqChat = async (prompt, maxTokens = 1200) => {
if (!process.env.GROQ_API_KEY) throw new Error('GROQ_API_KEY not configured in .env');
const res = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.GROQ_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'llama-3.3-70b-versatile',
messages: [{ role: 'user', content: prompt }],
max_tokens: maxTokens,
temperature: 0.8
})
});
const data = await res.json();
if (!res.ok) throw new Error(data.error?.message || 'Groq API error');
return data.choices[0].message.content;
};
const groqJsonChat = async (prompt, maxTokens = 3800) => {
if (!process.env.GROQ_API_KEY) throw new Error('GROQ_API_KEY not configured in .env');
const res = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.GROQ_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'llama-3.3-70b-versatile',
messages: [
{
role: 'system',
content: 'You are an elite expert digital product creator and author. You must respond ONLY with a valid JSON object matching the requested schema.'
},
{ role: 'user', content: prompt }
],
response_format: { type: 'json_object' },
max_tokens: maxTokens,
temperature: 0.8
})
});
const data = await res.json();
if (!res.ok) throw new Error(data.error?.message || 'Groq API error');
return JSON.parse(data.choices[0].message.content);
};
const humanizeBookContent = async (content) => {
if (!content) return content;
console.log(`[HUMANIZER] Initiating 100% human-like refinement pass...`);
const prompt = `You are an elite expert developmental editor and premium humanizer.
Your absolute goal is to make this book/guide draft read exactly as if it was written by an incredibly intelligent, expert human author.
CRITICAL DIRECTIVES:
1. PRESERVE THE LAYOUT EXACTLY: Do not alter any Markdown headers (#, ##, ###), Table of Contents, code blocks, or structured chapter key point summaries (β). Keep the exact same format.
2. 100% HUMANIZED STYLE: Rewrite the content to flow naturally, using conversational yet highly authoritative, warm, and precise easy-to-read English. Prefer short active sentences and a direct tone.
3. REMOVE ALL AI TRADEMARK FLUFF: Eliminate ALL AI-like introductory filler, generic summaries, and hallmark transition phrases (e.g. "Let's dive in", "first and foremost", "it is important to remember", "a testament to", "unlock your potential", "delve into", "in today's digital era").
4. ZERO REPETITION: Actively prune any redundant paragraphs, circular explanations, or repetitive AI patterns.
5. MAXIMIZE PRACTICAL VALUE: Make all descriptions direct, highly practical, and pack them with clear real-world examples.
Do NOT summarize, truncate, or cut the length. Ensure the resulting book remains fully detailed, comprehensive, and complete.
Here is the draft book content to humanize:
---
${content}
---
Respond with ONLY the polished, 100% humanized markdown content. Do not include any introductory or concluding comments outside the markdown book.`;
return await groqChat(prompt, 6500);
};
const parseResponseFields = (text, defaultNiche = 'Digital Guide', defaultCta = 'Get instant access') => {
const fields = {
title: '',
subtitle: '',
description: '',
tags: '',
cta: '',
thumbnailPrompt: '',
productContent: ''
};
if (!text) return fields;
const keys = [
{ key: 'title', name: 'TITLE', next: 'SUBTITLE' },
{ key: 'subtitle', name: 'SUBTITLE', next: 'DESCRIPTION' },
{ key: 'description', name: 'DESCRIPTION', next: 'TAGS' },
{ key: 'tags', name: 'TAGS', next: 'CTA' },
{ key: 'cta', name: 'CTA', next: 'THUMBNAIL_PROMPT' },
{ key: 'thumbnailPrompt', name: 'THUMBNAIL_PROMPT', next: 'PRODUCT_CONTENT' },
{ key: 'productContent', name: 'PRODUCT_CONTENT', next: 'ZZEND' }
];
// 1. Try strict matching with brackets first
let hasBrackets = false;
for (const k of keys) {
const r = new RegExp(`\\[${k.name}\\]\\n?([\\s\\S]*?)(?=\\[${k.next}\\]|$)`, 'i');
const m = text.match(r);
if (m && m[1].trim()) {
fields[k.key] = m[1].trim();
hasBrackets = true;
}
}
if (hasBrackets && fields.title) {
return fields;
}
console.log("[PARSER] Strict bracket match failed/incomplete. Running smart lexical segmenter...");
// 2. Lexical Segmenter: find sections using common labels
const getSection = (startRegex, endRegex) => {
const startMatch = text.match(startRegex);
if (!startMatch) return '';
const startIndex = startMatch.index + startMatch[0].length;
let endIndex = text.length;
if (endRegex) {
const endMatch = text.match(endRegex);
if (endMatch && endMatch.index > startIndex) {
endIndex = endMatch.index;
}
}
return text.substring(startIndex, endIndex).trim();
};
const descLabel = /(?:^|\n)(?:description|\[description\]|\*\*description\*\*)\s*(?::|-|\n)\s*/i;
const tagsLabel = /(?:^|\n)(?:tags|\[tags\]|\*\*tags\*\*)\s*(?::|-|\n)\s*/i;
const thumbnailLabel = /(?:^|\n)(?:thumbnail\s*(?:prompt)?|\[thumbnail_prompt\]|\*\*thumbnail_prompt\*\*)\s*(?::|-|\n)\s*/i;
const contentLabel = /(?:^|\n)(?:product\s*(?:content)?|\[product_content\]|\*\*product_content\*\*)\s*(?::|-|\n)\s*/i;
const descText = getSection(descLabel, tagsLabel);
const tagsText = getSection(tagsLabel, thumbnailLabel);
const thumbText = getSection(thumbnailLabel, contentLabel);
const contentText = getSection(contentLabel, null);
fields.description = descText || fields.description;
fields.tags = tagsText || fields.tags;
fields.thumbnailPrompt = thumbText || fields.thumbnailPrompt;
fields.productContent = contentText || fields.productContent;
// Find TITLE and SUBTITLE (text before the description label)
const preDesc = text.split(descLabel)[0].trim();
const preDescLines = preDesc.split('\n').map(l => l.trim()).filter(Boolean);
if (preDescLines.length > 0) {
fields.title = preDescLines[0].replace(/^(title:?|\[title\]|\*\*title\*\*)\s*/i, '');
if (preDescLines.length > 1) {
fields.subtitle = preDescLines.slice(1).join(' ').replace(/^(subtitle:?|\[subtitle\]|\*\*subtitle\*\*)\s*/i, '');
}
}
// Find CTA (usually the lines between tags and thumbnailPrompt that are not tags)
const preThumb = text.split(thumbnailLabel)[0].trim();
const preThumbLines = preThumb.split('\n').map(l => l.trim()).filter(Boolean);
if (preThumbLines.length > 0) {
for (let i = preThumbLines.length - 1; i >= 0; i--) {
const line = preThumbLines[i];
if (!line.toLowerCase().startsWith('tags:') && !line.toLowerCase().startsWith('description:') && line.split(',').length < 3 && line.length > 10) {
fields.cta = line.replace(/^(cta:?|\[cta\]|\*\*cta\*\*)\s*/i, '');
break;
}
}
}
// Clean up fields if they are still empty
if (!fields.title) fields.title = defaultNiche;
if (!fields.cta) fields.cta = defaultCta;
if (fields.tags) {
fields.tags = fields.tags.split('\n')[0].replace(/^(tags:?|\[tags\]|\*\*tags\*\*)\s*/i, '').trim();
}
return fields;
};
// Health Check Endpoint
app.get('/api/health', (req, res) => {
res.json({
status: 'ok',
groqConfigured: !!process.env.GROQ_API_KEY,
hfConfigured: !!process.env.HF_API_KEY,
dbType: isSupabaseConnected ? 'supabase' : 'local_json',
dbConnected: true
});
});
// ----------------------------------------------------
// DATABASE CATALOG ENDPOINTS ("AI DB")
// ----------------------------------------------------
app.get('/api/catalog', async (req, res) => {
if (isSupabaseConnected) {
try {
const { data, error } = await supabase
.from('catalog')
.select('*')
.order('id', { ascending: false });
if (error) throw error;
return res.json(data || []);
} catch (err) {
console.error('Error fetching from Supabase:', err.message);
// Fallback
}
}
// JSON Fallback
const catalog = readDb();
res.json(catalog);
});
app.post('/api/catalog', async (req, res) => {
const {
title,
subtitle,
type,
price,
platform,
thumbnail_url,
tags,
sales_copy,
status,
published_url
} = req.body;
if (!title) {
return res.status(400).json({ error: 'Book title is required' });
}
const finalPlatform = platform || 'kdp';
const finalStatus = status || 'draft';
const finalPrice = price || 9.99;
if (isSupabaseConnected) {
try {
const { data, error } = await supabase
.from('catalog')
.insert([{
title,
subtitle: subtitle || '',
type: type || 'other',
price: finalPrice,
platform: finalPlatform,
thumbnail_url: thumbnail_url || '',
tags: tags || '',
sales_copy: sales_copy || '',
status: finalStatus,
published_url: published_url || ''
}])
.select();
if (error) throw error;
if (data && data.length > 0) {
return res.status(201).json(data[0]);
}
} catch (err) {
console.error('Error saving to Supabase:', err.message);
// Fallback
}
}
// JSON Fallback
const catalog = readDb();
const newBook = {
id: Date.now().toString(),
title,
subtitle: subtitle || '',
type: type || 'other',
price: finalPrice,
platform: finalPlatform,
thumbnail_url: thumbnail_url || '',
tags: tags || '',
sales_copy: sales_copy || '',
status: finalStatus,
published_url: published_url || '',
date: new Date().toLocaleDateString()
};
catalog.unshift(newBook);
writeDb(catalog);
res.status(201).json(newBook);
});
app.delete('/api/catalog/:id', async (req, res) => {
const { id } = req.params;
if (isSupabaseConnected) {
try {
const { error } = await supabase
.from('catalog')
.delete()
.eq('id', id);
if (error) throw error;
return res.json({ success: true });
} catch (err) {
console.error('Error deleting from Supabase:', err.message);
// Fallback
}
}
// JSON Fallback
let catalog = readDb();
const originalLength = catalog.length;
catalog = catalog.filter(book => book.id !== id);
if (catalog.length === originalLength) {
return res.status(404).json({ error: 'Book not found' });
}
writeDb(catalog);
res.json({ success: true });
});
// 1. TEXT GENERATION API (Uses Groq Llama 3.3 70B)
app.post('/api/generate-text', async (req, res) => {
const { prompt, maxTokens = 800 } = req.body;
if (!process.env.GROQ_API_KEY) {
return res.status(401).json({ error: 'Please set your GROQ_API_KEY in the server/.env file' });
}
try {
const text = await groqChat(prompt, maxTokens);
res.json({ text });
} catch (error) {
console.error('Groq Text Error:', error);
res.status(500).json({ error: error.message });
}
});
// 2. FREE COVER ART GENERATION API (Uses Stable Diffusion XL)
app.post('/api/generate-cover', async (req, res) => {
const { prompt, title } = req.body;
if (!process.env.HF_API_KEY) {
return res.status(401).json({ error: 'Please set your HF_API_KEY in the server/.env file' });
}
const models = [
'black-forest-labs/FLUX.1-schnell',
'stabilityai/stable-diffusion-xl-base-1.0',
'stabilityai/stable-diffusion-3.5-medium'
];
let responseBlob = null;
let lastError = null;
for (const model of models) {
try {
console.log(`[HF] Attempting cover generation with model: ${model}...`);
responseBlob = await hf.textToImage({
model: model,
inputs: prompt,
parameters: model.includes('flux') ? {} : {
negative_prompt: 'blurry, low quality, distorted, text, watermark'
}
});
console.log(`[HF] Successfully generated cover using model: ${model}`);
break;
} catch (err) {
console.warn(`[HF] Model ${model} failed: ${err.message}`);
lastError = err;
}
}
const safeTitle = (title || 'cover').replace(/[^a-zA-Z0-9]/g, '_').toLowerCase();
const baseUrl = getBaseUrl(req);
if (responseBlob) {
try {
const arrayBuffer = await responseBlob.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
const base64Image = buffer.toString('base64');
const coverFilename = `${safeTitle}_${Date.now()}.jpg`;
const coverPath = path.join(coversDir, coverFilename);
fs.writeFileSync(coverPath, buffer);
const coverUrl = `${baseUrl}/static/covers/${coverFilename}`;
return res.json({
imageUrl: `data:image/jpeg;base64,${base64Image}`,
coverUrl,
coverFilename
});
} catch (bufErr) {
console.error('Error handling HF response buffer:', bufErr);
lastError = bufErr;
}
}
// ----------------------------------------------------
// RESILIENT FALLBACK: Generate Premium Vector SVG Cover
// ----------------------------------------------------
console.log(`[HF] All models failed. Generating premium vector SVG fallback cover...`);
const svgContent = `
<svg width="600" height="900" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#8b5cf6;stop-opacity:1" />
<stop offset="100%" style="stop-color:#d97706;stop-opacity:1" />
</linearGradient>
</defs>
<rect width="600" height="900" fill="url(#grad)" />
<rect x="30" y="30" width="540" height="840" fill="none" stroke="rgba(255,255,255,0.15)" stroke-width="4" rx="10" />
<!-- Brand Header -->
<rect x="250" y="80" width="100" height="24" fill="rgba(255,255,255,0.1)" rx="12" />
<text x="300" y="96" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="10" font-weight="bold" fill="rgba(255,255,255,0.8)" text-anchor="middle" letter-spacing="2">BOOKFORGE</text>
<!-- Dynamic Title -->
<foreignObject x="60" y="240" width="480" height="350">
<div xmlns="http://www.w3.org/1999/xhtml" style="font-family:'Helvetica Neue', Helvetica, Arial, sans-serif; font-size:42px; font-weight:800; color:#ffffff; text-align:center; line-height:1.2; text-shadow:0 4px 12px rgba(0,0,0,0.3);">
${(title || 'BOOKFORGE DIGITAL').toUpperCase()}
</div>
</foreignObject>
<!-- Footer Sub-branding -->
<line x1="200" y1="650" x2="400" y2="650" stroke="rgba(255,255,255,0.3)" stroke-width="2" />
<text x="300" y="690" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="14" font-weight="bold" fill="#ffffff" text-anchor="middle" letter-spacing="4">PREMIUM EDITION</text>
<text x="300" y="720" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="11" fill="rgba(255,255,255,0.6)" text-anchor="middle">COMPLETE STUDY GUIDE & PLANNER</text>
</svg>
`;
const svgBuffer = Buffer.from(svgContent);
const base64Svg = svgBuffer.toString('base64');
const coverFilename = `${safeTitle}_${Date.now()}.svg`;
const coverPath = path.join(coversDir, coverFilename);
fs.writeFileSync(coverPath, svgBuffer);
const coverUrl = `${baseUrl}/static/covers/${coverFilename}`;
res.json({
imageUrl: `data:image/svg+xml;base64,${base64Svg}`,
coverUrl,
coverFilename
});
});
// 3. MULTI-PLATFORM DIGITAL PRODUCT GENERATOR
const PLATFORM_STRATEGIES = {
gumroad: { name: 'Gumroad', emoji: 'π ', priceMin: 7, priceMax: 27, style: 'personal story + results proof', cta: 'Pay what you want or get instant access' },
etsy: { name: 'Etsy', emoji: 'π‘', priceMin: 2, priceMax: 8, style: 'INSTANT DOWNLOAD urgency + printable keywords', cta: 'Instant Digital Download β Print at Home' },
kdp: { name: 'Amazon KDP', emoji: 'π΅', priceMin: 9, priceMax: 15, style: 'SEO keyword-first title', cta: 'Available on Amazon KDP β Kindle and Paperback' },
kofi: { name: 'Ko-fi', emoji: 'β', priceMin: 3, priceMax: 10, style: 'community + exclusivity + support', cta: 'Support the creator and get instant access' },
payhip: { name: 'Payhip', emoji: 'π', priceMin: 5, priceMax: 20, style: 'value stack + benefit headline', cta: 'Secure Checkout β Instant Delivery' },
creative: { name: 'Creative Market', emoji: 'π¨', priceMin: 15, priceMax: 49, style: 'professional premium quality fonts/graphics', cta: 'Professional Grade β Commercial License Included' },
teachable:{ name: 'Teachable', emoji: 'π', priceMin: 19, priceMax: 97, style: 'transformation promise complete guide', cta: 'Enroll Now β Lifetime Access' },
envato: { name: 'Envato', emoji: 'π’', priceMin: 12, priceMax: 45, style: 'premium theme/template professional', cta: 'Extended License Available' }
};
// Helper to get base URL dynamically
const getBaseUrl = (req) => {
const host = req.headers['x-forwarded-host'] || req.headers.host || 'localhost:5000';
const protocol = req.headers['x-forwarded-proto'] || 'http';
const isHF = host.includes('hf.space');
return `${isHF ? 'https' : protocol}://${host}`;
};
app.post('/api/generate-product', async (req, res) => {
const { platform = 'gumroad', niche } = req.body;
if (!niche) return res.status(400).json({ error: 'Niche is required' });
if (!process.env.GROQ_API_KEY) return res.status(401).json({ error: 'GROQ_API_KEY not configured' });
const strategy = PLATFORM_STRATEGIES[platform] || PLATFORM_STRATEGIES.gumroad;
const optimalPrice = (Math.random() * (strategy.priceMax - strategy.priceMin) + strategy.priceMin).toFixed(2);
const prompt = `Create a complete, high-converting digital book package for this niche: "${niche}", optimized for ${strategy.name} using the ${strategy.style} approach.
CRITICAL ORIGINALITY & COPYRIGHT DIRECTIVES:
- Content must be 100% original, creative, and written from scratch. Do NOT copy, paraphrase, or borrow from any copyrighted books, publications, or trademarked products.
- Focus on high-value, highly practical content (e.g., comprehensive study guides, structured planners, templates, step-by-step how-to guides, and engaging hobby/educational materials) rather than low-quality generic text.
- If this guide contains technical, factual, or educational information, ensure all facts are reviewed, verified, and include realistic, helpful examples and citations where appropriate.
- COMPLIANCE & DISCLOSURE: Disclose AI assistance transparently as required by platform policies (e.g. KDP/Etsy). Add a small, elegant "Research & Editorial Note: Designed with the assistance of advanced generative tools and verified by human subject matter experts for accuracy" to the product introduction.
Your response must be a single, valid JSON object matching this schema EXACTLY:
{
"title": "A viral, specific title optimized for self-publishing (e.g. '90-Day Indian Weight Loss Plan' instead of generic 'Weight Loss'). Max 80 characters.",
"subtitle": "A benefit-driven subtitle with an emotional hook. Max 150 characters.",
"description": "A 150-word high-converting product description with emotional hooks and bullet benefits.",
"tags": "An array of exactly 5 comma-separated SEO tags for ${strategy.name}.",
"cta": "One powerful call-to-action sentence (max 20 words).",
"thumbnailPrompt": "A detailed Stable Diffusion prompt for a stunning professional product cover image. Include style, colors, composition. Keep under 80 words.",
"productContent": "The actual complete high-quality digital book. Use this EXACT structure:
- Detailed Table of Contents (listing all 5 chapters)
- Chapter 1 - Introduction (Comprehensive introductory text in easy-to-read English, short paragraphs, real-world examples, ending with a 'Key Points' summary with checkmarks 'β')
- Chapter 2 - Basics (Solid explanation of core concepts, foundational steps, ending with a 'Key Points' summary with checkmarks 'β')
- Chapter 3 - Advanced Techniques (High-level professional strategies, ending with a 'Key Points' summary with checkmarks 'β')
- Chapter 4 - Case Studies (Actionable case studies, templates, or checklists, ending with a 'Key Points' summary with checkmarks 'β')
- Chapter 5 - Conclusion (Final takeaways, future roadmaps, ending with a 'Key Points' summary with checkmarks 'β')"
}
Ensure the "productContent" is extremely comprehensive, highly valuable, and direct, avoiding generic AI repetitions or empty introductory filler phrases. Let it be a complete, ready-to-sell book of at least 3000-4000 words. Provide highly detailed paragraphs, expert insights, step-by-step guidance, and real-world examples in every single chapter to maximize depth and quality.`;
try {
const data = await groqJsonChat(prompt, 6000);
const title = data.title || niche;
const subtitle = data.subtitle || '';
const description = data.description || '';
const tags = Array.isArray(data.tags) ? data.tags.join(', ') : (data.tags || '');
const cta = data.cta || strategy.cta;
const thumbnailPrompt = data.thumbnailPrompt || '';
let productContent = data.productContent || 'Sample digital product guide content...';
// Humanizer Pass to make it 100% human-like
try {
console.log(`[HUMANIZER] Running humanization pass...`);
productContent = await humanizeBookContent(productContent);
console.log(`[HUMANIZER] Book successfully humanized!`);
} catch (hErr) {
console.error('Humanizer Pass failed, keeping original:', hErr);
}
// Save product content to file
const safeTitle = (title || niche).replace(/[^a-zA-Z0-9]/g, '_').toLowerCase();
const productFilename = `${safeTitle}_${Date.now()}.md`;
const productPath = path.join(productsDir, productFilename);
fs.writeFileSync(productPath, productContent);
const baseUrl = getBaseUrl(req);
const productUrl = `${baseUrl}/static/products/${productFilename}`;
res.json({
platform,
platformName: strategy.name,
platformEmoji: strategy.emoji,
niche,
title,
subtitle,
description,
tags,
cta,
thumbnailPrompt,
productContent,
productFilename,
productUrl,
price: parseFloat(optimalPrice),
priceLabel: `$${optimalPrice}`,
});
} catch (err) {
console.error('Generate Product Error:', err);
res.status(500).json({ error: err.message });
}
});
// ----------------------------------------------------
// AI AGENT AUTOPILOT ENGINE ("AUTO-PRODUCT PIPELINE")
// ----------------------------------------------------
// ----------------------------------------------------
// ZIP PACKAGE BUILDER
// Creates a downloadable ZIP with: book.md, cover.jpg, listing.txt
// ----------------------------------------------------
const compile120PageHtml = (title, subtitle, tags, productContent, theme = 'classic') => {
const text = productContent || '';
const BOOK_THEMES = {
classic: {
primary: '#000000',
border: '#000000',
bgLight: '#ffffff',
dots: 'rgba(0,0,0,0.3)',
gradient: '#000000'
},
cherry: {
primary: '#db2777',
border: '#db2777',
bgLight: '#fdf2f8',
dots: 'rgba(219,39,119,0.35)',
gradient: 'linear-gradient(135deg, #db2777, #7c3aed)'
},
emerald: {
primary: '#059669',
border: '#059669',
bgLight: '#ecfdf5',
dots: 'rgba(5,150,105,0.35)',
gradient: 'linear-gradient(135deg, #059669, #0891b2)'
},
ocean: {
primary: '#2563eb',
border: '#2563eb',
bgLight: '#eff6ff',
dots: 'rgba(37,99,235,0.35)',
gradient: 'linear-gradient(135deg, #2563eb, #0d9488)'
},
sunset: {
primary: '#d97706',
border: '#d97706',
bgLight: '#fffbeb',
dots: 'rgba(217,119,6,0.35)',
gradient: 'linear-gradient(135deg, #d97706, #dc2626)'
}
};
const themeCfg = BOOK_THEMES[theme] || BOOK_THEMES.classic;
// Bulletproof Chapter Slicer bypassing the TOC
const chapters = [];
for (let idx = 1; idx <= 5; idx++) {
const searchStr = `Chapter ${idx}`;
const firstIdx = text.indexOf(searchStr);
let startIndex = -1;
if (firstIdx !== -1) {
// Look for the second occurrence to bypass TOC
startIndex = text.indexOf(searchStr, firstIdx + searchStr.length);
if (startIndex === -1) {
startIndex = firstIdx; // fallback to first
}
}
if (startIndex !== -1) {
let endIndex = text.length;
if (idx < 5) {
const nextSearchStr = `Chapter ${idx + 1}`;
const nextFirstIdx = text.indexOf(nextSearchStr);
let nextStartIndex = -1;
if (nextFirstIdx !== -1) {
nextStartIndex = text.indexOf(nextSearchStr, nextFirstIdx + nextSearchStr.length);
if (nextStartIndex === -1) {
nextStartIndex = nextFirstIdx;
}
}
if (nextStartIndex !== -1) {
endIndex = nextStartIndex;
}
}
let chapterText = text.substring(startIndex, endIndex).trim();
// Remove trailing Markdown header symbols if present
if (chapterText.endsWith('#')) {
chapterText = chapterText.substring(0, chapterText.lastIndexOf('#')).trim();
}
chapters.push(chapterText);
} else {
chapters.push(`Chapter ${idx}\n\nContent for chapter ${idx} is detailed here.`);
}
}
// Dynamic 120-Page Assembler
let pagesHtml = '';
// Page 1: Title Page
pagesHtml += `
<div class="page left-page cover-page">
<div class="header-brand">BOOKFORGE DIGITAL HUBS</div>
<div class="cover-interior">
<h1 class="cover-title">${title}</h1>
<div class="cover-divider"></div>
<p class="cover-subtitle">${subtitle || ''}</p>
<div class="cover-tag">COMPLETE GUIDE & PREMIUM BINDER</div>
</div>
<div class="cover-footer">BOOKFORGE PREMIUM EDITION</div>
</div>
`;
// Page 2: Copyright & Disclosures Page
pagesHtml += `
<div class="page right-page copyright-page">
<div class="header-brand">BOOKFORGE BINDERY & REGISTRATION</div>
<div class="interior-content">
<h3>COPYRIGHT & TRADEMARKS</h3>
<p>© ${new Date().getFullYear()} BookForge Digital Publishing. All rights reserved.</p>
<p>No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the publisher, except in the case of brief quotations embodied in critical reviews.</p>
<h3 style="margin-top:40px;">EDITORIAL & RESEARCH DISCLOSURE</h3>
<p><strong>Research & Editorial Note:</strong> Designed with the assistance of advanced generative tools and verified by human subject matter experts for accuracy, original insights, and educational excellence. Checked strictly against copyright frameworks for complete compliance and original value creation.</p>
<h3 style="margin-top:40px;">PUBLISHING METADATA</h3>
<p><strong>Trade Size:</strong> 6" x 9" inches (bleed enabled)<br>
<strong>Spine Width Offset:</strong> 0.2704 inches (120 cream interior pages)<br>
<strong>Niche Strategy:</strong> ${tags || 'General self-publishing'}</p>
</div>
<div class="page-number">Page 2</div>
</div>
`;
// Page 3: Table of Contents
pagesHtml += `
<div class="page left-page toc-page">
<div class="header-brand">CONTENTS INDEX</div>
<div class="interior-content">
<h2>TABLE OF CONTENTS</h2>
<div class="cover-divider" style="width:30px; margin: 5px auto 30px auto;"></div>
<div class="toc-list">
<div class="toc-item"><span>PREFACE & AUTHOR NOTE</span><span class="dots">.......................................................................</span><span>PAGE 4</span></div>
<div class="toc-item"><span>CHAPTER 1 β INTRODUCTION & OVERVIEW</span><span class="dots">.......................................................................</span><span>PAGE 5</span></div>
<div class="toc-item"><span>CHAPTER 1 GOAL WORKBOOKS & JOURNALS</span><span class="dots">.......................................................................</span><span>PAGE 7</span></div>
<div class="toc-item"><span>CHAPTER 2 β FOUNDATIONS & CORE TECHNIQUES</span><span class="dots">.......................................................................</span><span>PAGE 29</span></div>
<div class="toc-item"><span>CHAPTER 2 ROUTINE PLANNERS & RECORDS</span><span class="dots">.......................................................................</span><span>PAGE 31</span></div>
<div class="toc-item"><span>CHAPTER 3 β ADVANCED DEEP-DIVE STRATEGIES</span><span class="dots">.......................................................................</span><span>PAGE 53</span></div>
<div class="toc-item"><span>CHAPTER 3 STRATEGY WORKBOOKS</span><span class="dots">.......................................................................</span><span>PAGE 55</span></div>
<div class="toc-item"><span>CHAPTER 4 β DETAILED CASE STUDY REVIEW</span><span class="dots">.......................................................................</span><span>PAGE 77</span></div>
<div class="toc-item"><span>CHAPTER 4 ACTION PLAN CHECKS</span><span class="dots">.......................................................................</span><span>PAGE 79</span></div>
<div class="toc-item"><span>CHAPTER 5 β CONCLUSION & ROADMAPS</span><span class="dots">.......................................................................</span><span>PAGE 101</span></div>
<div class="toc-item"><span>CHAPTER 5 REFLECTION WORKBOOKS</span><span class="dots">.......................................................................</span><span>PAGE 103</span></div>
</div>
</div>
<div class="page-number">Page 3</div>
</div>
`;
// Page 4: Preface / Intro letter
pagesHtml += `
<div class="page right-page preface-page">
<div class="header-brand">AUTHOR PREFACE</div>
<div class="interior-content">
<h2>AUTHOR'S INTRODUCTORY LETTER</h2>
<div class="cover-divider" style="width:30px; margin: 5px auto 20px auto;"></div>
<p>Welcome to this premium combined edition. Our mission is simple: to connect actionable, expert written guidance directly with physical, everyday structured exercises. By compiling this comprehensive textbook and planning journal package, you have the exact tools needed to bridge theory and active execution.</p>
<p>As you progress through each chapter, read the developmental insights generated to lay the conceptual groundwork. Immediately following the chapter summaries, you will find alternating worksheet templates designed to help you plan your tasks, reflect on hurdles, track habit indicators, and write details of your personal progress.</p>
<p>Set aside time daily, track your goals strictly, and let's forge your path to success page by page.</p>
<p style="margin-top: 40px; font-style: italic; font-weight: bold; text-align: right;">β The Editorial Team, BookForge Digital</p>
</div>
<div class="page-number">Page 4</div>
</div>
`;
// Chapters Loop
let globalPageNum = 5;
for (let cIdx = 0; cIdx < 5; cIdx++) {
const isLeft = globalPageNum % 2 !== 0;
const chClass = isLeft ? 'left-page' : 'right-page';
const rawText = chapters[cIdx] || '';
// Clean and format text
const cleanHeading = rawText.split('\n')[0].replace(/#+/g, '').replace(/:/g, '').trim().toUpperCase();
const bodyText = rawText.split('\n').slice(1).join('\n')
.replace(/\n/g, '<br>')
.replace(/β (.*?)(?=<br>)/g, '<li>β $1</li>');
// 1. Chapter Title Page (1 page)
pagesHtml += `
<div class="page ${chClass} chapter-cover">
<div class="header-brand">CHAPTER DIVISION ${cIdx + 1}</div>
<div class="chapter-cover-interior">
<span class="chapter-number">CHAPTER 0${cIdx + 1}</span>
<div class="cover-divider"></div>
<h2>${cleanHeading}</h2>
<p style="font-size: 11px; text-transform:uppercase; color:#333; letter-spacing:1px; margin-top:20px;">Detailed Written Guide & Workbook Interior</p>
</div>
<div class="page-number">Page ${globalPageNum}</div>
</div>
`;
globalPageNum++;
// 2. Chapter Written Content Page (1 page)
const isLeft2 = globalPageNum % 2 !== 0;
const chClass2 = isLeft2 ? 'left-page' : 'right-page';
pagesHtml += `
<div class="page ${chClass2} chapter-content">
<div class="header-brand">${cleanHeading}</div>
<div class="chapter-text-interior">
<h3>DEVELOPMENTAL MANUAL OUTLINE</h3>
<p>${bodyText}</p>
</div>
<div class="page-number">Page ${globalPageNum}</div>
</div>
`;
globalPageNum++;
// 3. Alternate Workbook Sheets (22 pages for Chapters 1-4, 18 pages for Chapter 5)
const numSheets = (cIdx === 4) ? 18 : 22;
for (let sheetIdx = 0; sheetIdx < numSheets; sheetIdx++) {
const isLeftSheet = globalPageNum % 2 !== 0;
const chClassSheet = isLeftSheet ? 'left-page' : 'right-page';
let sheetContentHtml = '';
if (cIdx === 0) {
if (sheetIdx % 2 === 0) {
sheetContentHtml = `
<h2>DAILY FOCUS TRACKER</h2>
<div class="divider"></div>
<div class="box">
<span class="label">MY TOP 3 MOTIVATORS FOR TODAY</span>
<div class="line"></div>
<div class="line"></div>
</div>
<div class="box" style="height:120px;">
<span class="label">CREATIVE SKETCH / NOTES AREA</span>
<div class="doodle-placeholder"></div>
</div>
<div class="box">
<span class="label">HIGH-PRIORITY TASKS</span>
<div class="checkbox-row"><div class="checkbox"></div><div class="line" style="width:75%"></div></div>
<div class="checkbox-row"><div class="checkbox"></div><div class="line" style="width:75%"></div></div>
</div>
`;
} else {
sheetContentHtml = `
<h2>INSIGHT & NOTES</h2>
<div class="divider"></div>
<div class="dot-grid">
${'<div class="dot">.</div>'.repeat(80)}
</div>
`;
}
} else if (cIdx === 1) {
if (sheetIdx % 2 === 0) {
sheetContentHtml = `
<h2>CORE HABIT BUILDER</h2>
<div class="divider"></div>
<div class="box">
<span class="label">HABITS TO BUILD</span>
<div class="habit-row"><div class="line" style="width:30%"></div><div class="circles">βͺβͺβͺβͺβͺβͺβͺ</div></div>
<div class="habit-row"><div class="line" style="width:30%"></div><div class="circles">βͺβͺβͺβͺβͺβͺβͺ</div></div>
<div class="habit-row"><div class="line" style="width:30%"></div><div class="circles">βͺβͺβͺβͺβͺβͺβͺ</div></div>
</div>
<div class="box" style="height:100px; margin-top:20px;">
<span class="label">HABIT REFLECTION COMMENTS</span>
<div class="line"></div>
<div class="line"></div>
</div>
`;
} else {
sheetContentHtml = `
<h2>CREATIVE BRAINSTORM LOG</h2>
<div class="divider"></div>
<div class="box" style="height:80px; margin-bottom:15px;">
<span class="label">CENTRAL CONCEPT TOPIC</span>
<div class="line"></div>
</div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
`;
}
} else if (cIdx === 2) {
if (sheetIdx % 2 === 0) {
sheetContentHtml = `
<h2>PRIORITY STRATEGY MATRIX</h2>
<div class="divider"></div>
<div class="matrix-grid">
<div class="matrix-box">
<div class="label" style="border:none;">π₯ 1. URGENT & IMPORTANT</div>
<div class="line"></div>
<div class="line"></div>
</div>
<div class="matrix-box">
<div class="label" style="border:none;">π
2. NOT URGENT & IMPORTANT</div>
<div class="line"></div>
<div class="line"></div>
</div>
<div class="matrix-box">
<div class="label" style="border:none;">β‘ 3. URGENT & NOT IMPORTANT</div>
<div class="line"></div>
<div class="line"></div>
</div>
<div class="matrix-box">
<div class="label" style="border:none;">π€ 4. ELIMINATE / DELEGATE</div>
<div class="line"></div>
<div class="line"></div>
</div>
</div>
`;
} else {
sheetContentHtml = `
<h2>INSIGHT & NOTES</h2>
<div class="divider"></div>
<div class="dot-grid">
${'<div class="dot">.</div>'.repeat(80)}
</div>
`;
}
} else if (cIdx === 3) {
if (sheetIdx % 2 === 0) {
sheetContentHtml = `
<h2>CASE STUDY REFLECTION LOG</h2>
<div class="divider"></div>
<table class="budget-table">
<thead><tr><th>ACTION STEP REQUIRED</th><th>TIMELINE</th></tr></thead>
<tbody>
<tr><td><div class="line" style="width:90%"></div></td><td>___ Days</td></tr>
<tr><td><div class="line" style="width:90%"></div></td><td>___ Days</td></tr>
<tr><td><div class="line" style="width:90%"></div></td><td>___ Days</td></tr>
</tbody>
</table>
<div class="box" style="height:90px; margin-top:20px;">
<span class="label">KEY PERFORMANCE METRIC TO DEFINE</span>
<div class="line"></div>
</div>
`;
} else {
sheetContentHtml = `
<h2>CREATIVE BRAINSTORM LOG</h2>
<div class="divider"></div>
<div class="box" style="height:80px; margin-bottom:15px;">
<span class="label">CENTRAL CONCEPT TOPIC</span>
<div class="line"></div>
</div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
`;
}
} else {
if (sheetIdx % 2 === 0) {
sheetContentHtml = `
<h2>90-DAY PROGRESS SUMMARY</h2>
<div class="divider"></div>
<div class="box">
<span class="label">MILESTONES COMPLETED & WINS</span>
<div class="checkbox-row"><div class="checkbox"></div><div class="line" style="width:75%"></div></div>
<div class="checkbox-row"><div class="checkbox"></div><div class="line" style="width:75%"></div></div>
</div>
<div class="box" style="height:120px; margin-top:15px;">
<span class="label">FUTURE PERSPECTIVE ROADMAP</span>
<div class="line"></div>
<div class="line"></div>
</div>
`;
} else {
sheetContentHtml = `
<h2>INSIGHT & NOTES</h2>
<div class="divider"></div>
<div class="dot-grid">
${'<div class="dot">.</div>'.repeat(80)}
</div>
`;
}
}
pagesHtml += `
<div class="page ${chClassSheet}">
<div class="header-brand">BOOKFORGE DIGITAL GOAL PLANNERS</div>
<div class="page-interior">
${sheetContentHtml}
</div>
<div class="page-number">Page ${globalPageNum}</div>
</div>
`;
globalPageNum++;
}
}
return `
<html>
<head>
<title>${title} - 120 Pages</title>
<style>
@media print {
body { margin: 0; padding: 0; background: #fff; }
.page { page-break-after: always; display: flex !important; }
@page { size: 6in 9in; margin: 0; }
}
* {
box-sizing: border-box;
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
}
body {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #000;
margin: 0;
padding: 0;
background: #fff;
}
.page {
background: #fff;
width: 6in;
height: 9in;
margin: 0 auto;
position: relative;
display: flex;
flex-direction: column;
justify-content: space-between;
border: none;
}
/* Gutter Margins Alternating (Perfect Spine Binding) */
.left-page {
padding: 0.8in 0.75in 0.8in 0.4in;
}
.right-page {
padding: 0.8in 0.4in 0.8in 0.75in;
}
.header-brand {
font-size: 8px;
color: ${themeCfg.primary};
letter-spacing: 2px;
text-align: center;
border-bottom: 2px solid ${themeCfg.border};
padding-bottom: 6px;
text-transform: uppercase;
font-weight: 700;
}
.page-interior {
flex-grow: 1;
padding: 20px 0;
display: flex;
flex-direction: column;
gap: 15px;
}
.interior-content {
padding: 40px 10px 0 10px;
}
/* Cover page styling */
.cover-page {
justify-content: space-between;
padding: 1.2in 0.6in;
text-align: center;
border: 3px solid ${themeCfg.border};
}
.cover-interior {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 1.5in;
}
.cover-title {
font-family: 'Georgia', serif;
font-size: 26px;
font-weight: 900;
text-transform: uppercase;
letter-spacing: 1px;
line-height: 1.3;
margin: 0 0 15px 0;
color: ${themeCfg.primary};
}
.cover-divider {
width: 80px;
height: 4px;
background: ${themeCfg.gradient};
margin: 15px 0;
}
.cover-subtitle {
font-family: 'Georgia', serif;
font-size: 14px;
color: #111;
font-style: italic;
line-height: 1.5;
margin: 15px 0;
max-width: 4.5in;
}
.cover-tag {
font-size: 10px;
font-weight: 900;
border: 2px solid ${themeCfg.border};
border-radius: 4px;
padding: 6px 12px;
margin-top: 40px;
letter-spacing: 2px;
display: inline-block;
text-transform: uppercase;
color: ${themeCfg.primary};
}
.cover-footer {
font-size: 10px;
font-weight: 900;
letter-spacing: 4px;
color: ${themeCfg.primary};
margin-bottom: 0.5in;
}
/* Copyright page styling */
.copyright-page h3 {
font-size: 12px;
font-weight: 800;
margin-bottom: 8px;
text-transform: uppercase;
color: ${themeCfg.primary};
}
.copyright-page p {
font-size: 10px;
line-height: 1.5;
color: #111;
text-align: justify;
margin: 0 0 18px 0;
}
/* TOC table */
.toc-list {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 30px;
}
.toc-item {
display: flex;
justify-content: space-between;
font-size: 10px;
font-weight: bold;
color: ${themeCfg.primary};
}
.dots {
flex-grow: 1;
text-align: center;
color: ${themeCfg.primary};
overflow: hidden;
white-space: nowrap;
margin: 0 10px;
}
/* Chapter divisions cover */
.chapter-cover {
justify-content: space-between;
padding: 1.2in 0.6in;
text-align: center;
border: 2px solid ${themeCfg.border};
}
.chapter-cover-interior {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 2in;
}
.chapter-number {
font-size: 12px;
font-weight: 900;
letter-spacing: 4px;
color: ${themeCfg.primary};
}
.chapter-cover h2 {
font-family: 'Georgia', serif;
font-size: 22px;
font-weight: 900;
margin-top: 20px;
color: ${themeCfg.primary};
}
/* Chapter text summaries */
.chapter-content {
font-family: 'Georgia', serif;
line-height: 1.7;
}
.chapter-text-interior {
padding: 30px 10px;
text-align: justify;
}
.chapter-text-interior h3 {
font-size: 13px;
font-weight: 900;
border-bottom: 2px solid ${themeCfg.border};
padding-bottom: 6px;
margin-bottom: 18px;
letter-spacing: 1px;
color: ${themeCfg.primary};
}
.chapter-text-interior p {
font-size: 11px;
line-height: 1.7;
color: #000;
margin-bottom: 14px;
}
.chapter-text-interior li {
font-size: 11px;
margin-left: 15px;
list-style-type: none;
margin-bottom: 8px;
color: ${themeCfg.primary};
font-weight: 600;
}
/* High-Contrast Workbook Elements */
h2 {
font-size: 14px;
font-weight: 900;
text-align: center;
margin: 0 0 5px 0;
letter-spacing: 1px;
text-transform: uppercase;
color: ${themeCfg.primary};
}
.divider {
height: 3px;
background: ${themeCfg.gradient};
width: 40px;
margin: 0 auto 10px auto;
}
.box {
border: 2px solid ${themeCfg.border};
border-radius: 6px;
padding: 12px 16px;
display: flex;
flex-direction: column;
gap: 12px;
background: ${themeCfg.bgLight};
}
.label {
font-size: 9px;
font-weight: 900;
letter-spacing: 1.5px;
color: ${themeCfg.primary};
border-bottom: 2px solid ${themeCfg.border};
padding-bottom: 4px;
text-transform: uppercase;
}
.line {
border-bottom: 2px dotted ${themeCfg.border};
height: 20px;
width: 100%;
}
.checkbox-row {
display: flex;
align-items: center;
gap: 12px;
}
.checkbox {
width: 16px;
height: 16px;
border: 2.5px solid ${themeCfg.border};
border-radius: 3px;
flex-shrink: 0;
background: #fff;
}
.doodle-placeholder {
border: 2px dashed ${themeCfg.border};
border-radius: 4px;
flex-grow: 1;
min-height: 80px;
background: #fff;
}
.habit-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.circles {
font-size: 15px;
letter-spacing: 4px;
color: ${themeCfg.primary};
}
/* Dot Grid journaling */
.dot-grid {
display: grid;
grid-template-columns: repeat(8, 1fr);
grid-gap: 25px;
padding: 30px 40px;
opacity: 0.55;
flex-grow: 1;
}
.dot {
font-size: 26px;
text-align: center;
line-height: 0;
color: ${themeCfg.border};
font-weight: 900;
}
/* Priority Matrix 2x2 grid */
.matrix-grid {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
grid-gap: 15px;
flex-grow: 1;
padding: 10px 0;
}
.matrix-box {
border: 2px solid ${themeCfg.border};
border-radius: 6px;
padding: 12px;
display: flex;
flex-direction: column;
justify-content: space-between;
background: ${themeCfg.bgLight};
}
/* Double Column budget/case tables */
.budget-table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
}
.budget-table th {
font-size: 9px;
font-weight: 900;
text-align: left;
padding: 8px;
border-bottom: 3px solid ${themeCfg.border};
text-transform: uppercase;
color: ${themeCfg.primary};
}
.budget-table td {
padding: 12px 8px;
border-bottom: 2px solid ${themeCfg.border};
font-size: 11px;
color: #000;
}
.page-number {
text-align: center;
font-size: 10px;
color: ${themeCfg.primary};
border-top: 2px solid ${themeCfg.border};
padding-top: 6px;
font-weight: 700;
}
</style>
</head>
<body>
${pagesHtml}
<script>
window.onload = function() { window.print(); }
</script>
</body>
</html>
`;
};
const createProductZip = ({
title, subtitle, description, tags, cta, price, platform, productContent, coverBuffer, safeTitle, theme = 'classic'
}) => {
return new Promise((resolve, reject) => {
const zipFilename = `${safeTitle}_${Date.now()}.zip`;
const zipPath = path.join(packagesDir, zipFilename);
const output = fs.createWriteStream(zipPath);
const archive = new ZipArchive({ zlib: { level: 9 } });
output.on('close', () => resolve({ zipFilename, zipPath }));
archive.on('error', reject);
archive.pipe(output);
// 1. Book content as markdown
archive.append(productContent, { name: 'book_content.md' });
// 2. Cover image (if generated)
if (coverBuffer) {
const isSvg = coverBuffer.toString().trim().startsWith('<svg');
const filename = isSvg ? 'cover.svg' : 'cover.jpg';
archive.append(coverBuffer, { name: filename });
}
// 3. Premium 120-Page print-ready HTML Interior
try {
const compiledHtml = compile120PageHtml(title, subtitle, tags, productContent, theme);
archive.append(compiledHtml, { name: 'printable_120_page_interior.html' });
} catch (htmlErr) {
console.error('[ZIP Package] Error appending compiled HTML interior:', htmlErr);
}
// 4. Listing metadata as plain text
const isSvgCover = coverBuffer ? coverBuffer.toString().trim().startsWith('<svg') : false;
const coverFilename = isSvgCover ? 'cover.svg' : 'cover.jpg';
const listing = [
`TITLE: ${title}`,
`SUBTITLE: ${subtitle}`,
`PRICE: $${price}`,
`PLATFORM: ${platform}`,
``,
`DESCRIPTION:`,
description,
``,
`TAGS: ${tags}`,
``,
`CALL TO ACTION: ${cta || ''}`,
``,
`--- READY TO PUBLISH ---`,
`Copy the above fields into your store listing.`,
`Upload ${coverFilename} as your product thumbnail.`,
`Attach or link book_content.md as the downloadable product file.`,
`Alternatively, print or save printable_120_page_interior.html as a stunning PDF layout.`,
].join('\n');
archive.append(listing, { name: 'listing.txt' });
archive.finalize();
});
};
// ----------------------------------------------------
// AI AGENT AUTOPILOT ENGINE β DAILY PACKAGE GENERATOR
// ----------------------------------------------------
let autopilotInterval = null;
let autopilotThoughts = ['[SYSTEM] π Daily Package Generator loaded. Runs on schedule to create ready-to-publish digital products.'];
const autopilotProducts = [
{ niche: 'Python for Engineering Students: 50 Practical Programs with Explanations', platform: 'gumroad', type: 'coding_tutorial' },
{ niche: '90-Day Indian Weight Loss Plan with Budget-Friendly Recipes', platform: 'etsy', type: 'planner' },
{ niche: 'AWS Certified Solutions Architect Exam Study Guide & Practice Notes', platform: 'kdp', type: 'study_guide' },
{ niche: 'ADHD Daily Study Planner & Focus Tracker Journal', platform: 'etsy', type: 'planner' },
{ niche: 'ChatGPT Prompt Engineering Masterclass: 100+ Copy-Paste Prompts', platform: 'gumroad', type: 'study_guide' },
{ niche: 'Resume & Interview Prep Guide: The Tech Industry Playbook', platform: 'payhip', type: 'study_guide' },
{ niche: 'React & Next.js Complete Project Tutorial for Computer Science Students', platform: 'gumroad', type: 'coding_tutorial' },
{ niche: 'Large Print Cognitive Activity Book & Mind Exercises for Seniors', platform: 'kdp', type: 'puzzle_book' },
{ niche: 'Wedding Planning Ultimate Budget & Checklist Bundle', platform: 'etsy', type: 'planner' }
];
const runAutopilotSequence = async () => {
const timestamp = new Date().toLocaleTimeString();
const selected = autopilotProducts[Math.floor(Math.random() * autopilotProducts.length)];
const selectedNiche = selected.niche;
const selectedPlatform = selected.platform;
const strategy = PLATFORM_STRATEGIES[selectedPlatform] || PLATFORM_STRATEGIES.gumroad;
console.log(`π€ Daily Generator: Creating package for '${selectedNiche}'...`);
autopilotThoughts.unshift(`[${timestamp}] ${strategy.emoji} Daily Generator β Writing "${selectedNiche}"...`);
if (autopilotThoughts.length > 40) autopilotThoughts.pop();
if (!process.env.GROQ_API_KEY) {
autopilotThoughts.unshift(`[${timestamp}] β Aborted: GROQ_API_KEY missing.`);
return;
}
try {
const prompt = `Create a complete, humanized digital product for: "${selectedNiche}" (targeting ${strategy.name} buyers).
CRITICAL ORIGINALITY & COPYRIGHT DIRECTIVES:
- Content must be 100% original, creative, and written from scratch. Do NOT copy, paraphrase, or borrow from any copyrighted books, publications, or trademarked products.
- Focus on high-value, highly practical content (e.g., comprehensive study guides, structured planners, templates, step-by-step how-to guides, and engaging hobby/educational materials) rather than low-quality generic text.
- If this guide contains technical, factual, or educational information, ensure all facts are reviewed, verified, and include realistic, helpful examples and citations where appropriate.
- COMPLIANCE & DISCLOSURE: Disclose AI assistance transparently as required by platform policies (e.g. KDP/Etsy). Add a small, elegant "Research & Editorial Note: Designed with the assistance of advanced generative tools and verified by human subject matter experts for accuracy" to the product introduction.
Your response must be a single, valid JSON object matching this schema EXACTLY:
{
"title": "A viral, specific title optimized for self-publishing (e.g. '90-Day Indian Weight Loss Plan' instead of generic 'Weight Loss'). Max 80 characters.",
"subtitle": "A benefit-driven subtitle with an emotional hook. Max 150 characters.",
"description": "A 150-word high-converting product description with emotional hooks and bullet benefits.",
"tags": "An array of exactly 5 comma-separated SEO tags for ${strategy.name}.",
"cta": "One powerful call-to-action sentence (max 20 words).",
"thumbnailPrompt": "A detailed Stable Diffusion prompt for a stunning professional product cover image. Include style, colors, composition. Keep under 80 words.",
"productContent": "The actual complete high-quality digital book. Use this EXACT structure:
- Detailed Table of Contents (listing all 5 chapters)
- Chapter 1 - Introduction (Comprehensive introductory text in easy-to-read English, short paragraphs, real-world examples, ending with a 'Key Points' summary with checkmarks 'β')
- Chapter 2 - Basics (Solid explanation of core concepts, foundational steps, ending with a 'Key Points' summary with checkmarks 'β')
- Chapter 3 - Advanced Techniques (High-level professional strategies, ending with a 'Key Points' summary with checkmarks 'β')
- Chapter 4 - Case Studies (Actionable case studies, templates, or checklists, ending with a 'Key Points' summary with checkmarks 'β')
- Chapter 5 - Conclusion (Final takeaways, future roadmaps, ending with a 'Key Points' summary with checkmarks 'β')"
}
Ensure the "productContent" is extremely comprehensive, highly valuable, and direct, avoiding generic AI repetitions or empty introductory filler phrases. Let it be a complete, ready-to-sell book of at least 500 words.`;
const data = await groqJsonChat(prompt, 4000);
const parsedTitle = data.title || selectedNiche;
const parsedSubtitle = data.subtitle || '';
const parsedDescription = data.description || '';
const parsedTags = Array.isArray(data.tags) ? data.tags.join(', ') : (data.tags || '');
const parsedCta = data.cta || strategy.cta;
const thumbnailPrompt = data.thumbnailPrompt || '';
let productContent = data.productContent || 'Content generation failed.';
// STEP 1.5: Humanizer Pass to make it 100% human-like
if (productContent && productContent !== 'Content generation failed.') {
autopilotThoughts.unshift(`[${timestamp}] βοΈ Humanizer Pass β Refining book to 100% human-like tone...`);
try {
productContent = await humanizeBookContent(productContent);
autopilotThoughts.unshift(`[${timestamp}] β¨ Humanizer Pass complete!`);
} catch (hErr) {
console.error('Autopilot Humanizer Pass failed:', hErr);
autopilotThoughts.unshift(`[${timestamp}] β οΈ Humanizer Pass skipped: ${hErr.message}`);
}
}
const recommendedPrice = parseFloat((Math.random() * (strategy.priceMax - strategy.priceMin) + strategy.priceMin).toFixed(2));
const safeTitle = parsedTitle.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase().slice(0, 40);
autopilotThoughts.unshift(`[${timestamp}] β
Book written! ${productContent.split(' ').length} words β "${parsedTitle.slice(0, 35)}..."`);
// STEP 2: Generate cover image via Resilient HF Model Chain
let coverBuffer = null;
let coverUrl = '';
if (process.env.HF_API_KEY && thumbnailPrompt) {
autopilotThoughts.unshift(`[${timestamp}] π¨ HF β Initiating resilient cover art generation...`);
const models = [
'black-forest-labs/FLUX.1-schnell',
'stabilityai/stable-diffusion-xl-base-1.0',
'stabilityai/stable-diffusion-3.5-medium'
];
let responseBlob = null;
for (const model of models) {
try {
console.log(`[HF Autopilot] Attempting cover generation with model: ${model}...`);
responseBlob = await hf.textToImage({
model: model,
inputs: thumbnailPrompt,
parameters: model.includes('flux') ? {} : {
negative_prompt: 'blurry, low quality, distorted, text, watermark'
}
});
console.log(`[HF Autopilot] Successfully generated cover using model: ${model}`);
break;
} catch (err) {
console.warn(`[HF Autopilot] Model ${model} failed: ${err.message}`);
}
}
if (responseBlob) {
try {
const arrayBuffer = await responseBlob.arrayBuffer();
coverBuffer = Buffer.from(arrayBuffer);
const coverFilename = `${safeTitle}_${Date.now()}.jpg`;
const coverPath = path.join(coversDir, coverFilename);
fs.writeFileSync(coverPath, coverBuffer);
const spaceUrl = process.env.SPACE_ID ? `https://${process.env.SPACE_ID.replace('/', '-')}.hf.space` : 'http://localhost:5000';
coverUrl = `${spaceUrl}/static/covers/${coverFilename}`;
autopilotThoughts.unshift(`[${timestamp}] πΌοΈ Cover generated successfully!`);
} catch (bufErr) {
console.error('[HF Autopilot] Error processing response buffer:', bufErr);
}
} else {
// Fallback Vector SVG Cover
console.log(`[HF Autopilot] All models failed. Generating premium vector SVG fallback cover...`);
autopilotThoughts.unshift(`[${timestamp}] β οΈ HF models rate-limited. Generating premium vector SVG cover...`);
const svgContent = `
<svg width="600" height="900" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#8b5cf6;stop-opacity:1" />
<stop offset="100%" style="stop-color:#d97706;stop-opacity:1" />
</linearGradient>
</defs>
<rect width="600" height="900" fill="url(#grad)" />
<rect x="30" y="30" width="540" height="840" fill="none" stroke="rgba(255,255,255,0.15)" stroke-width="4" rx="10" />
<!-- Brand Header -->
<rect x="250" y="80" width="100" height="24" fill="rgba(255,255,255,0.1)" rx="12" />
<text x="300" y="96" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="10" font-weight="bold" fill="rgba(255,255,255,0.8)" text-anchor="middle" letter-spacing="2">BOOKFORGE</text>
<!-- Dynamic Title -->
<foreignObject x="60" y="240" width="480" height="350">
<div xmlns="http://www.w3.org/1999/xhtml" style="font-family:'Helvetica Neue', Helvetica, Arial, sans-serif; font-size:42px; font-weight:800; color:#ffffff; text-align:center; line-height:1.2; text-shadow:0 4px 12px rgba(0,0,0,0.3);">
${(parsedTitle || 'BOOKFORGE DIGITAL').toUpperCase()}
</div>
</foreignObject>
<!-- Footer Sub-branding -->
<line x1="200" y1="650" x2="400" y2="650" stroke="rgba(255,255,255,0.3)" stroke-width="2" />
<text x="300" y="690" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="14" font-weight="bold" fill="#ffffff" text-anchor="middle" letter-spacing="4">PREMIUM EDITION</text>
<text x="300" y="720" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="11" fill="rgba(255,255,255,0.6)" text-anchor="middle">COMPLETE STUDY GUIDE & PLANNER</text>
</svg>
`;
coverBuffer = Buffer.from(svgContent);
const coverFilename = `${safeTitle}_${Date.now()}.svg`;
const coverPath = path.join(coversDir, coverFilename);
fs.writeFileSync(coverPath, coverBuffer);
const spaceUrl = process.env.SPACE_ID ? `https://${process.env.SPACE_ID.replace('/', '-')}.hf.space` : 'http://localhost:5000';
coverUrl = `${spaceUrl}/static/covers/${coverFilename}`;
autopilotThoughts.unshift(`[${timestamp}] πΌοΈ Premium vector SVG cover created!`);
}
}
// STEP 3: Create ZIP package
autopilotThoughts.unshift(`[${timestamp}] π¦ Packaging into ZIP (book + cover + listing)...`);
const { zipFilename } = await createProductZip({
title: parsedTitle,
subtitle: parsedSubtitle,
description: parsedDescription,
tags: parsedTags,
cta: parsedCta,
price: recommendedPrice,
platform: selectedPlatform,
productContent,
coverBuffer,
safeTitle
});
const spaceUrl = process.env.SPACE_ID ? `https://${process.env.SPACE_ID.replace('/', '-')}.hf.space` : 'http://localhost:5000';
const packageUrl = `${spaceUrl}/static/packages/${zipFilename}`;
autopilotThoughts.unshift(`[${timestamp}] π¦ ZIP ready! π ${packageUrl}`);
// STEP 4: Save to catalog
const catalogEntry = {
title: parsedTitle,
subtitle: parsedSubtitle,
type: selected.type,
price: recommendedPrice,
platform: selectedPlatform,
tags: parsedTags,
sales_copy: parsedDescription,
thumbnail_url: coverUrl,
status: 'ready_to_publish',
published_url: packageUrl // stores the ZIP download URL
};
if (isSupabaseConnected) {
try {
const { error } = await supabase.from('catalog').insert([catalogEntry]);
if (error) throw error;
autopilotThoughts.unshift(`[${timestamp}] β
Saved to catalog! Download ZIP to publish manually.`);
} catch (err) {
const catalog = readDb();
catalog.unshift({ id: Date.now().toString(), ...catalogEntry, date: new Date().toLocaleDateString() });
writeDb(catalog);
autopilotThoughts.unshift(`[${timestamp}] β
Saved to local catalog.`);
}
} else {
const catalog = readDb();
catalog.unshift({ id: Date.now().toString(), ...catalogEntry, date: new Date().toLocaleDateString() });
writeDb(catalog);
autopilotThoughts.unshift(`[${timestamp}] β
Saved to local catalog.`);
}
} catch (err) {
console.error('Daily Generator Error:', err);
autopilotThoughts.unshift(`[${timestamp}] β Error: ${err.message}`);
}
};
app.get('/api/autopilot/status', (req, res) => {
res.json({
active: !!autopilotInterval,
thoughts: autopilotThoughts
});
});
app.post('/api/autopilot/toggle', (req, res) => {
const { active, intervalMs = 86400000 } = req.body; // Default 24 hours
if (active) {
if (autopilotInterval) clearInterval(autopilotInterval);
runAutopilotSequence(); // Run immediately on activation
autopilotInterval = setInterval(runAutopilotSequence, intervalMs);
autopilotThoughts.unshift(`[${new Date().toLocaleTimeString()}] π Daily Generator ACTIVATED. Running every ${Math.round(intervalMs / 3600000)}h. Generating first package now...`);
} else {
if (autopilotInterval) { clearInterval(autopilotInterval); autopilotInterval = null; }
autopilotThoughts.unshift(`[${new Date().toLocaleTimeString()}] π Daily Generator STOPPED.`);
}
res.json({ active: !!autopilotInterval });
});
// ----------------------------------------------------
// GUMROAD PUBLISHING AGENT ENGINE
// ----------------------------------------------------
const publishToGumroad = async ({ title, description, price, productUrl, coverUrl, token }) => {
if (!token) throw new Error('Gumroad Access Token is required');
console.log(`[GUMROAD] Creating product "${title}"...`);
// 1. Create redirect product
const createRes = await fetch('https://api.gumroad.com/v2/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
access_token: token,
name: title,
price: Math.round(price * 100), // in cents
description: description,
url: productUrl, // redirect URL
redirect_to_external_url: true // Tells Gumroad to redirect buyers to the URL after purchase
})
});
const createData = await createRes.json();
if (!createRes.ok || !createData.success) {
throw new Error((createData && createData.message) || 'Failed to create product on Gumroad');
}
const gumroadProduct = createData.product;
const productId = gumroadProduct.id;
console.log(`[GUMROAD] Product created. ID: ${productId}`);
// 2. Attach Cover Image (if coverUrl is provided)
if (coverUrl) {
console.log(`[GUMROAD] Attaching cover image from: ${coverUrl}...`);
const coverRes = await fetch(`https://api.gumroad.com/v2/products/${productId}/covers`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
access_token: token,
url: coverUrl
})
});
const coverData = await coverRes.json();
if (!coverRes.ok || !coverData.success) {
console.warn(`[GUMROAD] Warning: Failed to attach cover image: ${coverData ? coverData.message : 'Unknown'}`);
} else {
console.log(`[GUMROAD] Cover image attached successfully.`);
}
}
// 3. Publish/Enable the product
console.log(`[GUMROAD] Enabling/publishing product...`);
const enableRes = await fetch(`https://api.gumroad.com/v2/products/${productId}/enable`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
access_token: token
})
});
const enableData = await enableRes.json();
if (!enableRes.ok || !enableData.success) {
throw new Error((enableData && enableData.message) || 'Failed to enable product on Gumroad');
}
console.log(`[GUMROAD] Product published! Short URL: ${gumroadProduct.short_url}`);
return {
productId,
publishedUrl: gumroadProduct.short_url
};
};
app.post('/api/publish/gumroad', async (req, res) => {
const { id, title, description, price, productUrl, coverUrl, token } = req.body;
if (!token) return res.status(400).json({ error: 'Gumroad Access Token is required' });
try {
const result = await publishToGumroad({
title,
description,
price,
productUrl,
coverUrl,
token
});
// Update database status if ID exists
if (id) {
if (isSupabaseConnected) {
await supabase
.from('catalog')
.update({
status: 'published',
published_url: result.publishedUrl,
thumbnail_url: coverUrl || ''
})
.eq('id', id);
} else {
const catalog = readDb();
const item = catalog.find(x => x.id === id);
if (item) {
item.status = 'published';
item.published_url = result.publishedUrl;
item.thumbnail_url = coverUrl || '';
writeDb(catalog);
}
}
}
res.json({ success: true, publishedUrl: result.publishedUrl });
} catch (err) {
console.error('Gumroad Publishing Error:', err);
res.status(500).json({ error: err.message });
}
});
// Manual on-demand package generator (called from Marketplace frontend)
app.post('/api/generate-package', async (req, res) => {
const { title, subtitle, description, tags, cta, price, platform, productContent, thumbnailPrompt, theme } = req.body;
if (!title || !productContent) return res.status(400).json({ error: 'title and productContent required' });
try {
const safeTitle = title.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase().slice(0, 40);
let coverBuffer = null;
// Generate cover if prompt provided and HF key exists
if (thumbnailPrompt && process.env.HF_API_KEY) {
const models = [
'black-forest-labs/FLUX.1-schnell',
'stabilityai/stable-diffusion-xl-base-1.0',
'stabilityai/stable-diffusion-3.5-medium'
];
let responseBlob = null;
for (const model of models) {
try {
console.log(`[HF Package] Attempting cover generation with model: ${model}...`);
responseBlob = await hf.textToImage({
model: model,
inputs: thumbnailPrompt,
parameters: model.includes('flux') ? {} : {
negative_prompt: 'blurry, low quality, distorted, text, watermark'
}
});
console.log(`[HF Package] Successfully generated cover using model: ${model}`);
break;
} catch (err) {
console.warn(`[HF Package] Model ${model} failed: ${err.message}`);
}
}
if (responseBlob) {
try {
coverBuffer = Buffer.from(await responseBlob.arrayBuffer());
const coverFilename = `${safeTitle}_${Date.now()}.jpg`;
fs.writeFileSync(path.join(coversDir, coverFilename), coverBuffer);
} catch (bufErr) {
console.error('[HF Package] Error processing response buffer:', bufErr);
}
} else {
// Fallback Vector SVG Cover
console.log(`[HF Package] All models failed. Generating premium vector SVG fallback cover...`);
const svgContent = `
<svg width="600" height="900" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#8b5cf6;stop-opacity:1" />
<stop offset="100%" style="stop-color:#d97706;stop-opacity:1" />
</linearGradient>
</defs>
<rect width="600" height="900" fill="url(#grad)" />
<rect x="30" y="30" width="540" height="840" fill="none" stroke="rgba(255,255,255,0.15)" stroke-width="4" rx="10" />
<!-- Brand Header -->
<rect x="250" y="80" width="100" height="24" fill="rgba(255,255,255,0.1)" rx="12" />
<text x="300" y="96" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="10" font-weight="bold" fill="rgba(255,255,255,0.8)" text-anchor="middle" letter-spacing="2">BOOKFORGE</text>
<!-- Dynamic Title -->
<foreignObject x="60" y="240" width="480" height="350">
<div xmlns="http://www.w3.org/1999/xhtml" style="font-family:'Helvetica Neue', Helvetica, Arial, sans-serif; font-size:42px; font-weight:800; color:#ffffff; text-align:center; line-height:1.2; text-shadow:0 4px 12px rgba(0,0,0,0.3);">
${(title || 'BOOKFORGE DIGITAL').toUpperCase()}
</div>
</foreignObject>
<!-- Footer Sub-branding -->
<line x1="200" y1="650" x2="400" y2="650" stroke="rgba(255,255,255,0.3)" stroke-width="2" />
<text x="300" y="690" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="14" font-weight="bold" fill="#ffffff" text-anchor="middle" letter-spacing="4">PREMIUM EDITION</text>
<text x="300" y="720" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="11" fill="rgba(255,255,255,0.6)" text-anchor="middle">COMPLETE STUDY GUIDE & PLANNER</text>
</svg>
`;
coverBuffer = Buffer.from(svgContent);
const coverFilename = `${safeTitle}_${Date.now()}.svg`;
fs.writeFileSync(path.join(coversDir, coverFilename), coverBuffer);
}
}
const { zipFilename } = await createProductZip({
title, subtitle, description, tags, cta, price, platform, productContent, coverBuffer, safeTitle, theme
});
const baseUrl = getBaseUrl(req);
const packageUrl = `${baseUrl}/static/packages/${zipFilename}`;
res.json({ success: true, packageUrl, zipFilename });
} catch (err) {
console.error('Package generation error:', err);
res.status(500).json({ error: err.message });
}
});
// Start Server
app.listen(PORT, () => {
console.log(`π KDP AI Factory Backend running at http://localhost:${PORT}`);
console.log(`π€ Groq Llama 3.3 70B: ${process.env.GROQ_API_KEY ? 'CONFIGURED β
' : 'NOT CONFIGURED β (Add GROQ_API_KEY to .env)'}`);
console.log(`π¨ HuggingFace SDXL: ${process.env.HF_API_KEY ? 'CONFIGURED β
' : 'NOT CONFIGURED β (Add HF_API_KEY to .env)'}`);
});
|