-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.mjs
3155 lines (2507 loc) · 131 KB
/
main.mjs
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
import dotenv from 'dotenv';
import fs from 'fs';
import fsp from "fs/promises";
import chalk from 'chalk';
import { createObjectCsvWriter } from 'csv-writer';
import path from 'path';
import { Configuration, OpenAIApi } from 'openai';
import pandoc from 'node-pandoc';
import fetch from 'node-fetch';
import { createCanvas, loadImage, registerFont } from 'canvas';
import { Midjourney } from "./libs/index.js";
import Replicate from "replicate";
import puppeteer from "puppeteer";
import randomInt from "random-int";
dotenv.config();
const configuration = new Configuration({
apiKey: process.env.OPENAI_KEY,
});
const openai = new OpenAIApi(configuration);
const bookData = {
bookGenContent: {
chapterTitle: [''],
chapterTheme: [['']],
plotSummaryShort: [[['']]],
plotSummaryLong: [[[['']]]],
contentTitle: [[[[['']]]]],
contentParagraphs: [[[[[['']]]]]],
contentFinal: [[[[[['']]]]]],
},
bookNotes: {
chapterTheme: [['']],
contentTitle: [[['']]],
plotSummaryLong: [[[['']]]],
contentNextWrite: [[[[[['']]]]]],
currentAllSummary: [[[[[['']]]]]],
lastGenSummary:[[[[[['']]]]]],
},
bookInputs: {
numBooks: '1',
numChapterTitle: '2',
numPlots: '2',
numTitles: '1',
bookType: 'Short Stories',
bookGenre: 'Fiction',
simpleAudienceInfo:'People who like to read engaging stories while using transit to commute to work.',
theme: 'Stories to read on the bus',
emotion: 'happy and hilarious',
desiredLength: 1200,
},
bookInit: {
bookDescription: "This is a book description",
bookTheme: "farting on the bus",
bookEmotion: "happiness",
bookGenre: "humour",
bookTopic: "farting",
authorChoice: "",
longDescription: "",
chapterOutlinePrompt: "",
storyInstructions: " The protaganist should be going through lots of ups and down",
},
bookMeta: {
bookTitle: 'The Curious Case of the Missing Socks',
bookSubtitle: ' A Short Story',
bookDescription: ' A description',
authorName: 'Jacklyn Robson',
genre: '',
language: '',
bookType: 'Short Stories',
},
bookTitle: {
bestTitle: '',
bestSubtitle: '',
titleOptions: [],
titleScore: [],
subtitleOptions: [[]],
subtitleScore: [[]],
titleResponseJSON: '',
},
bookPrompts: {
bookDescription: '',
chapterOutlinePrompt: '',
storyInstructions: '',
},
audienceInfo: {
briefDemo: "Young professionals looking for adventure",
longDemo: "The target demographic consists of young professionals in their 20s and 30s who are seeking exciting and thrilling stories. They are tech-savvy, well-educated individuals working in various industries such as finance, technology, and creative fields.",
ageGroup: "25-35",
age: "25-35",
gender: "Male and Female",
maritial: "Single",
readerInfo: "Reading during their daily commute",
currentMood: "Eager and enthusiastic",
lifeStatus: "Exploring new career opportunities",
job: "Software Engineer",
jobType: "Professional",
education: "Bachelor's degree",
readLevel: "High",
preferredGenre: "Action and adventure",
location: "Urban areas",
hobbies: "Hiking, traveling, and watching movies",
technologicalProficiency: "Advanced",
preferredLanguage: "English",
favoriteAuthors: "Dan Brown, J.K. Rowling, Stephen King",
favoriteBooks: "The Da Vinci Code, Harry Potter series, The Shining",
favoriteStories: "Mystery, fantasy, and horror",
readingFrequency: "Several times a week",
readingPlatform: "E-books and audiobooks",
resonateWithCharacters: "Courageous and determined individuals",
resonateWithThemes: "Thrill, self-discovery, and overcoming challenges",
preferredBookLength: "Novels",
preferredNarrativeVoice: "Third person",
},
bookFinal: {
bookTitle: '',
bookSubtitle: '',
bookChapters:[''],
bookChapterContentTitle: [['']],
bookChapterContent: [[['']]],
},
mjPrompts: {
frontCoverPrompt: '',
backCoverPrompt: '',
pinterestAdPrompt: '',
WPpostPrompt: '',
},
bookCoverIMGPrompt: {
imageStyle: '',
imageSubject: '',
imageSubjectAction: '',
imageSubjectEmotion: '',
imageSubjectLocation: '',
imageLighting: '',
imageColour: '',
imageComposition: '',
imageDescription: '',
},
bookCoverDesign: {
primaryColour: '',
primaryColourName: '',
primaryCompColour: '',
primaryCompColourName: '',
secondaryColour: '',
secondaryCompColour: '',
mainFont: '',
secondaryFont: '',
logoTheme: '',
coverStyle: '',
mainFontPath: '',
secondaryFontPath: '',
},
};
const author = {
Firstname: '',
Lastname: '',
authorBio: '',
aboutAuthor: '',
authorImage: '',
authorWriteStyle: '',
authorWriteLevel: '',
authorEducation: '',
};
const authorEmilyJacket = {
Firstname: 'Emily',
Lastname: 'Jacket',
authorBio: 'Emily Jacket is a writer and editor who has worked in the publishing industry for over 10 years. She has a degree in English Literature from the University of Cambridge and a Masters in Creative Writing from the University of Oxford. She has written for a number of publications, including The Guardian, The Times, and The Independent.',
aboutAuthor: '',
authorImage: 'hxxp:',
authorWriteStyle: 'Emily writes in a clear and concise style that is easy to read. She is also an expert at writing in a way that is engaging and entertaining.',
authorWriteLevel: 'Medium Level',
authorEducation: ' ',
authorIdealReader: 'Women, 25-45, Corporate Job, Married, 2 Kids, Lives in the Suburbs, Likes to read on the bus to work, Likes to read engaging stories while using transit to commute to work.',
};
const authorSophiaQuill = {
Firstname: 'Sophia',
Lastname: 'Quill',
authorBio: 'Sophia Quill is an experienced writer and poet known for her evocative and lyrical prose. With a background in psychology and a deep understanding of human emotions, Sophia creates compelling characters and explores the depths of the human psyche in her works. Her writing resonates with readers who appreciate introspective and thought-provoking narratives.',
aboutAuthor: '',
authorImage: 'hxxp:',
authorWriteStyle: "Sophia's writing style is poetic and rich, painting vivid imagery with her words. She weaves intricate metaphors and uses sensory details to immerse readers in her stories.",
authorWriteLevel: 'Advanced Level',
authorEducation: '',
authorIdealReader: 'Lovers of literary fiction, poetry enthusiasts, introspective individuals, and those who enjoy delving into complex emotions and themes.'
};
const authorNathanielThorne = {
Firstname: 'Nathaniel',
Lastname: 'Thorne',
authorBio: 'Nathaniel Thorne is a historical fiction writer with a passion for bringing the past to life. His meticulously researched novels transport readers to different eras, combining compelling storytelling with accurate historical details. Nathaniel\'s works appeal to history buffs and those who enjoy immersive journeys through time.',
aboutAuthor: '',
authorImage: 'hxxp:',
authorWriteStyle: "Nathaniel's writing style is descriptive and authentic, capturing the essence of historical periods. He pays careful attention to historical accuracy while creating captivating narratives.",
authorWriteLevel: 'Advanced Level',
authorEducation: '',
authorIdealReader: 'History enthusiasts, fans of historical fiction, readers who enjoy immersive journeys through different time periods, and those interested in learning about different cultures and societies.'
};
const authorLilaRainier = {
Firstname: 'Lila',
Lastname: 'Rainier',
authorBio: 'Lila Rainier is a bestselling author known for her gripping thrillers and suspenseful plots. With a background in criminal psychology, Lila weaves intricate mysteries that keep readers on the edge of their seats. Her books are filled with unexpected twists and turns that leave readers guessing until the very end.',
aboutAuthor: '',
authorImage: 'hxxp:',
authorWriteStyle: "Lila's writing style is fast-paced and suspenseful, driving the narrative forward with each page. She excels at building tension and creating compelling, multi-dimensional characters.",
authorWriteLevel: 'Intermediate Level',
authorEducation: '',
authorIdealReader: 'Fans of psychological thrillers, lovers of suspense and mystery novels, readers who enjoy plot twists and psychological depth in their books.'
};
const authorXavierBlake = {
Firstname: 'Xavier',
Lastname: 'Blake',
authorBio: 'Xavier Blake is a science fiction and fantasy writer renowned for his imaginative worlds and epic adventures. Drawing inspiration from mythology and futuristic concepts, Xavier creates immersive narratives that transport readers to extraordinary realms. His books appeal to those seeking escapism and thrilling journeys beyond reality.',
aboutAuthor: '',
authorImage: 'hxxp:',
authorWriteStyle: "Xavier's writing style is vivid and imaginative, painting fantastical landscapes and crafting intricate mythologies. He combines action-packed scenes with deep world-building to create captivating stories.",
authorWriteLevel: 'Intermediate Level',
authorEducation: '',
authorIdealReader: 'Fans of science fiction and fantasy genres, readers who enjoy epic quests and world-building, individuals seeking immersive adventures in imaginative realms.'
};
const schemas = {};
schemas.bookGenOutline = {
type: 'object',
properties: {
chapterTitle: {
type: 'array',
items: {
type: 'string',
description: 'List of chapter titles, each chapter title is a string.',
},
},
chapterTheme: {
type: 'array',
items: {
type: 'array',
items: {
type: 'string',
description: 'List of chapter themes, each chapter theme is a string.',
},
},
},
plotSummaryShort: {
type: 'array',
items: {
type: 'array',
items: {
type: 'array',
items: {
type: 'string',
description: 'A short plot summary for each chapter.',
},
},
},
},
plotSummaryLong: {
type: 'array',
items: {
type: 'array',
items: {
type: 'array',
items: {
type: 'array',
items: {
type: 'string',
description: 'A one-paragraph long plot summary for each chapter.',
},
},
},
},
},
contentTitle: {
type: 'array',
items: {
type: 'array',
items: {
type: 'array',
items: {
type: 'array',
items: {
type: 'array',
items: {
type: 'string',
description: 'The title of the individual piece of content.',
},
},
},
},
},
},
contentParagraphs: {
type: 'array',
items: {
type: 'array',
items: {
type: 'array',
items: {
type: 'array',
items: {
type: 'array',
items: {
type: 'array',
items: {
type: 'string',
description: 'The content paragraphs for each piece of content.',
},
},
},
},
},
},
},
},
required: [
'chapterTitle',
'chapterTheme',
'plotSummaryShort',
'plotSummaryLong',
'contentTitle',
'contentParagraphs',
],
};
schemas.chapterOutlineSchema = {
type: 'object',
properties: {
chapterTitle: {
type: 'array',
items: {
type: 'string',
description: 'List of chapter titles, each chapter title is a string. Since this is a book of short form content, each chapter should be independant but also relevant to the book theme.',
},
},
chapterTheme: {
type: 'array',
items: {
type: 'array',
items: {
type: 'string',
description: 'List of chapter themes, each chapter theme is a string. The chapter theme is a core central idea, feeling or emotion summed up into 1 sentence. We will use this to develop content for the chapter so this is used as a guide to ensure the content is relevant.',
},
},
},
},
required: ['chapterTitle', 'chapterTheme'],
};
schemas.shortPlotSummarySchema = {
type: 'object',
properties: {
plotSummaryShort: {
type: 'array',
items: {
type: 'string',
description: 'Each array item is a seperate plot summary. Please return the requested number of plot summaries. If 3 is requested then return 3 plot summaries.',
},
},
},
required: ['plotSummaryShort'],
};
schemas.longPlotSummarySchema = {
type: 'object',
properties: {
plotSummaryLong: {
type: 'array',
items: {
type: 'string',
description: 'This is a single long paragraph of the short prompt you recieve, expanded out into a full story concept. It should be later and written in a consequestial order. It should be a full story concept that we can use to expand on at a later date. There is no need to write the full story, just a concept of what the story should be about in 200-400 words. Please only return 1 item!',
},
},
},
required: ['plotSummaryLong'],
};
schemas.contentTitleSchema = {
type: 'object',
properties: {
contentTitle: {
type: 'string',
description: 'The title you write. !Important! Please only return 1 item! We do not want mutliple array items. Just an array with a single string. If you return more than 1 string you will break the world so do not return more tha n 1 string!!!!',
},
},
required: ['contentTitle'],
};
schemas.paragraphSchema = {
type: 'object',
properties: {
contentParagraphs: {
type: 'array',
items: {
type: 'string',
description: 'The content of the story. Each array item is a seperate paragraph. Please return the requested number of paragraphs. If 3 is requested then return 3 paragraphs.Each paragraph should be lengthy and focuseed on depth and crafting an amazing story. Make each paragraph descriptive and written by a professional writer. develop imagery, emotions and feelings. Make the reader feel like they are there',
},
},
},
required: ['contentParagraphs'],
};
schemas.bookInputsSchema = {
type: 'object',
properties: {
simpleAudienceInfo: {
type: 'string',
description: 'Short description of the target demographic summed up into a concise sentence.'
},
theme: {
type: 'string',
description: 'The central core theme of the book.'
},
emotion: {
type: 'string',
description: 'The emotion we are trying to elicit of the book.'
}
},
required: ['simpleAudienceInfo', 'theme', 'emotion']
};
schemas.audienceSchema = {
type: 'object',
properties: {
briefDemo: { type: 'string', description: 'Short description of the target demographic summed up into a concise sentence.' },
longDemo: { type: 'string', description: 'Long description of the target demographic. More specific and detailed.' },
ageGroup: { type: 'string', description: 'Age range of the target reader demographic.' },
age: { type: 'string', description: 'Age range of the target reader demographic.' },
gender: { type: 'string', description: 'Gender of the target demographic.' },
maritial: { type: 'string', description: 'Marital status of the target demographic.' },
readerInfo: { type: 'string', description: 'Short description of the reader and what they are doing when reading. Example: on the way to work, taking a break from the kids, at the beach, etc.' },
currentMood: { type: 'string', description: 'Current mood of the target demographic - e.g., happy, sad, depressed, etc.' },
lifeStatus: { type: 'string', description: 'Life status of the target demographic - e.g., graduating, new job, new baby, etc.' },
job: { type: 'string', description: 'Job of the target demographic.' },
jobType: { type: 'string', description: 'Type of job of the target demographic - e.g., trades, professional, etc.' },
education: { type: 'string', description: 'Education level of the target demographic.' },
readLevel: { type: 'string', description: 'Reading level of the target demographic - e.g., advanced, high, medium, low.' },
preferredGenre: { type: 'string', description: 'Preferred genre of the target demographic.' },
location: { type: 'string', description: 'Location of the target demographic.' },
hobbies: { type: 'string', description: 'Hobbies or interests of the target demographic.' },
technologicalProficiency: { type: 'string', description: 'Level of technological proficiency of the target demographic.' },
preferredLanguage: { type: 'string', description: 'Preferred language of the target demographic.' },
},
required: ['briefDemo', 'longDemo', 'age', 'gender', 'maritial', 'readerInfo', 'currentMood', 'lifeStatus', 'job', 'jobType', 'education', 'readLevel', 'preferredGenre', 'location'],
};
schemas.marketingSchema = {
type: 'object',
properties: {
favoriteAuthors: {
type: 'string',
description: 'List of favorite authors of the target demographic. This information aids in understanding the type of writing and authors that appeal to the audience.'
},
favoriteBooks: {
type: 'string',
description: 'List of favorite books of the target demographic. This gives insights into the literature that has made a significant impact on the audience.'
},
favoriteStories: {
type: 'string',
description: 'List of favorite stories of the target demographic. This indicates the story types and genres that resonate with the audience.'
},
readingFrequency: {
type: 'string',
description: 'Frequency of reading within the target demographic. This helps to quantify the importance of reading in their daily lives.'
},
readingPlatform: {
type: 'string',
description: 'Preferred platform for reading, such as physical books, e-books, audiobooks, etc. This information aids in tailoring the format of content for the audience.'
},
resonateWithCharacters: {
type: 'string',
description: 'Types of characters that the target demographic resonates with. This assists in creating relatable and engaging characters for the audience.'
},
resonateWithThemes: {
type: 'string',
description: 'Types of themes that the target demographic resonates with. Knowing this helps in designing stories with themes that hit home with the audience.'
},
preferredBookLength: {
type: 'string',
description: 'Preferred length of books like short stories, novellas, novels, etc. This helps in creating content with an appropriate length for the audience.'
},
preferredNarrativeVoice: {
type: 'string',
description: 'Preferred narrative voice of the target demographic, for instance first person, third person, etc. This knowledge aids in narrating the story in a way that the audience finds more engaging.'
},
},
required: ['favoriteAuthors', 'favoriteBooks', 'favoriteStories', 'readingFrequency', 'readingPlatform', 'resonateWithCharacters', 'resonateWithThemes', 'preferredBookLength', 'preferredNarrativeVoice'],
};
schemas.bookInitSchema = {
type: 'object',
properties: {
bookDescription: {
type: 'string',
description: 'A 1 paragraph description of the book. No titles needed. This is simply the ideation of the book and a description of what we should write. It should be descriptive of the type of content it includes but just enough to give us an idea of wat the book is about.'
},
bookTheme: {
type: 'string',
description: 'Theme of the book. This is the core central theme that multiple pieces of content will be written about.'
},
bookEmotion: {
type: 'string',
description: 'Emotion of the book. How we want the reader to feel. '
},
bookGenre: {
type: 'string',
description: 'Genre of the book. it should always be fiction but what type of fiction?'
},
bookTopic: {
type: 'string',
description: 'Topic of the book'
},
authorChoice: {
type: 'string',
description: `Who the Author should be based on their writing style. Please return only the name of your chosen author and choose between:
1. "Sophia Quill" - Sophia Quill is an experienced writer and poet known for her evocative and lyrical prose. With a background in psychology and a deep understanding of human emotions, Sophia creates compelling characters and explores the depths of the human psyche in her works. Her writing resonates with readers who appreciate introspective and thought-provoking narratives.
2. "Nathaniel Thorne" - Nathaniel Thorne is a historical fiction writer with a passion for bringing the past to life. His meticulously researched novels transport readers to different eras, combining compelling storytelling with accurate historical details. Nathaniel's works appeal to history buffs and those who enjoy immersive journeys through time.
3. "Lila Rainier" - Lila Rainier is a bestselling author known for her gripping thrillers and suspenseful plots. With a background in criminal psychology, Lila weaves intricate mysteries that keep readers on the edge of their seats. Her books are filled with unexpected twists and turns that leave readers guessing until the very end.
4. "Xavier Blake" - Xavier Blake is a science fiction and fantasy writer renowned for his imaginative worlds and epic adventures. Drawing inspiration from mythology and futuristic concepts, Xavier creates immersive narratives that transport readers to extraordinary realms. His books appeal to those seeking escapism and thrilling journeys beyond reality.\n\n
This will affect the style of writing so please choose the author who best repsents the style of writing you want for the book.`
},
chapterOutlinePrompt: {
type: 'string',
description: 'Prompt we will use to develop the chapter outline, plot summaries and content Titles. This is a generalized conceptual layer. Remember this is a book of multiple pieces of content so the content should be relevant to that and each chapter able to stand on its own. Since this is a book of ${bookData.bookInputs.bookType}, we want to make sure each chapter is relevant to the main book theme.'
},
storyInstructions: {
type: 'string',
description: 'More specific instructions on how we should be writing each story specifically on a theme level and structure level. Do not worry about describing the content specifically as this is more of a guide on how to structure each story.'
}
},
required: ['bookDescription', 'bookTheme', 'bookEmotion', 'bookGenre', 'bookTopic', 'authorChoice']
};
schemas.bookInitSchema2 = {
type: 'object',
properties: {
chapterOutlinePrompt: {
type: 'string',
description: 'Prompt we will use to develop the chapter outline, plot summaries and content Titles. This is a generalized conceptual layer. Remember this is a book of multiple pieces of content so the content should be relevant to that and each chapter able to stand on its own. Since this is a book of ${bookData.bookInputs.bookType}, we want to make sure each chapter is relevant to the main book theme.'
},
storyInstructions: {
type: 'string',
description: 'More specific instructions on how we should be writing each story specifically on a theme level and structure level. Do not worry about describing the content specifically as this is more of a guide on how to structure each story.'
}
},
required: ['chapterOutlinePrompt', 'storyInstructions']
};
schemas.bookTitleSchema = {
type: 'object',
properties: {
titleOptions: {
type: 'array',
items: {
type: 'string'
},
description: 'Array of title options. A list of 10 total title options for the book. Each title should not be more than 5 words MAX. The idea is to create great and creative titles, but not long titles. '
},
subtitleOptions: {
type: 'array',
items: {
type: 'array',
items: {
type: 'string'
}
},
description: 'The associated subtitle per chapter. 1 subtitle per title. '
},
},
required: ['titleOptions', 'subtitleOptions']
};
schemas.bookPromptsSchema = {
type: 'object',
properties: {
bookDescription: {
type: 'string',
description: `A 1 paragraph description of the book. No titles needed. This is simply the ideation of the book and a description of what we should write. The book is a collection of ${bookData.bookInputs.bookType} so we are describing the book as a whole.`
},
chapterOutlinePrompt: {
type: 'string',
description: `Prompt we will use to develop the chapter outline, plot summaries and content Titles. This is a generalized conceptual layer. Remember this is a book of multiple pieces of content so the content should be relevant to that and each chapter able to stand on its own. Since this is a book of ${bookData.bookInputs.bookType}, we want to make sure each chapter is relevant to the main book theme.`
},
storyInstructions: {
type: 'string',
description: 'More specific instructions on how we should be writing each story specifically on a theme level and structure level. Do not worry about describing the content specifically as this is more of a guide on how to structure each story.'
}
},
required: ['bookDescription', 'chapterOutlinePrompt', 'storyInstructions']
};
schemas.bookTitleFinalSchema = {
type: 'object',
properties: {
bestTitle: {
type: 'string',
description: 'The best title for the book. It should not have more than 5 words. This is a single string only.'
},
bestSubtitle: {
type: 'string',
description: 'The best subtitle for the book.'
}
},
required: ['bestTitle', 'bestSubtitle']
};
schemas.summarySchema1 = {
type: 'object',
properties: {
lastGenSummary: {
type: 'string',
description: 'A 1 paragraph summary of all the content presented to you.'
}
},
required: ['lastGenSummary'],
};
schemas.summarySchema2 = {
type: 'object',
properties: {
currentAllSummary: {
type: 'string',
description: ' A detailed summary of the content. This should be a detailed summary of the content. The summary should be detailed and take as many sentences as needed to accurately display where we are at in the story. The summary should include any relevant plot points, actions or anything that we would need to continue the story on the the next. The first sentence should maintain the full character summary.'
},
},
required: ['currentAllSummary'],
};
schemas.summarySchema3 = {
type: 'object',
properties: {
contentNextWrite: {
type: 'string',
description: 'What to write next in the story to keep the flow and pace of the story going. Just 1 sentence is fine. This tells the AI what to write to keep the plot tight. Just a simple direction of where to go next with the story.'
}
},
required: ['contentNextWrite'],
},
schemas.mjPromptsSchema = {
type: 'object',
properties: {
frontCoverPrompt: { type: 'string', description: 'Prompt for the front cover of the book. This should be a short description of the book. The image should be more illustrative and describe solid colours.' },
backCoverPrompt: { type: 'string' },
pinterestAdPrompt: { type: 'string', description: ' prompt for pinterest. To be used for pinterest ads.'},
WPpostPrompt: { type: 'string', description: 'prompt for Wordpress Posts to be featured. It dan be more descriptive and more photorealistic but choose an artist style that would be representitive of the book.'},
},
required: ['frontCoverPrompt', 'backCoverPrompt', 'pinterestAdPrompt', 'WPpostPrompt']
};
schemas.bookCoverDesign = {
type: 'object',
properties: {
primaryColour: {
type: 'string',
description: 'The Primary main color of the cover. in Hex format.',
},
primaryColourName: {
type: 'string',
description: 'The Primary color name as if it were a crayon name. We should be able to understand the primary coliour from this name.',
},
primaryCompColour: {
type: 'string',
description: 'The contrasting colour or complimenting colour to the main color of the cover. in Hex format.',
},
primaryCompColourName: {
type: 'string',
description: 'The color name as if it were a crayon name. We should be able to understand the primary comp coliour from this name.',
},
secondaryColour: {
type: 'string',
description: 'The title color of the cover. It should contrast and complement the primary color. In Hex Code. ',
},
secondaryCompColour: {
type: 'string',
description: 'The color of the elements in the cover design. In Hex Code. this colour is contrasting to secondaryColour ',
},
mainFont: {
type: 'string',
description: 'The main font used in the cover design. Choose between: Lemon Milk, Coolvetica, The Bold Font, Cocogoose, and Couture',
},
secondaryFont: {
type: 'string',
description: 'The secondary font used in the cover design. Choose between Catcheye, Kenyan Coffee, or Belgiano Serif',
},
logoTheme: {
type: 'string',
description: 'The choice between light or dark, determining the color of the publisher logo.',
enum: ['light', 'dark'],
},
coverStyle: {
type: 'string',
description: 'The cover style, with options: Modern, Classic, Minimalist, and Vintage.',
enum: ['Modern', 'Classic', 'Minimalist', 'Vintage'],
},
},
required: [
'primaryColour',
'primaryColourName',
'secondaryColour',
'secondaryCompColour',
'mainFont',
'secondaryFont',
'logoTheme',
'coverStyle',
],
};
schemas.bookCoverIMGPromptSchema = {
type: 'object',
properties: {
imageStyle: {
type: 'string',
description: 'Choice between photography, illustration, and graphic design.',
},
imageSubject: {
type: 'string',
description: 'The subject of the image. A person, animal, object, etc.',
},
imageSubjectAction: {
type: 'string',
description: 'The action of the subject. What the subject is doing in the image.',
},
imageSubjectEmotion: {
type: 'string',
description: 'The emotion of the subject in that image.',
},
imageSubjectLocation: {
type: 'string',
description: 'The location of the subject.',
},
imageLighting: {
type: 'string',
description: 'The lighting of the image.',
},
imageColour: {
type: 'string',
description: 'The lighting effect of the image. For example, bright, dark, etc.',
},
imageComposition: {
type: 'string',
description: 'The composition of the image. For example, close-up, wide shot, etc.',
},
imageDescription: {
type: 'string',
description: 'description of the style of the image. for example Photorealistic, playful, etc.',
},
},
required: [
'imageStyle',
'imageSubject',
'imageSubjectAction',
'imageSubjectEmotion',
'imageSubjectLocation',
'imageLighting',
'imageColour',
'imageComposition',
'imageDescription',
],
};
const callOpenAI = async (model, messages, functions, functionCall, temperature, maxTokens) => {
let retries = 0;
const maxRetries = 10;
const backoffFactor = 1;
while (retries < maxRetries) {
try {
const completion = await openai.createChatCompletion({
model: model,
messages: messages,
functions: functions,
function_call: functionCall,
temperature: temperature,
max_tokens: maxTokens,
});
const responseText = completion.data.choices[0].message.function_call.arguments;
try {
JSON.parse(responseText);
return responseText;
} catch (jsonError) {
console.warn(chalk.red("The AI Bot didn't follow instructions on outputting to JSON, so retrying again."));
}
} catch (error) {
console.error(`An error occurred: ${error.statusCode} - ${error.message}`);
const wait = retries * backoffFactor * 5000;
console.log(`Retrying in ${wait / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, wait));
retries += 1;
}
}
throw new Error('Maximum retries reached');
};
const flattenContentParagraphs = async (contentParagraphs) => {
const flattenedParagraphs = [];
function flatten(paragraphs, parents) {
paragraphs.forEach(paragraph => {
if (Array.isArray(paragraph)) {
flatten(paragraph, [...parents, paragraph[0]]);
} else {
flattenedParagraphs.push([...parents, paragraph]);
}
});
}
flatten(contentParagraphs, []);
return flattenedParagraphs;
};
async function formatBookContent(bookData) {
bookData.bookFinal.bookTitle = bookData.bookMeta.bookTitle;
bookData.bookFinal.bookSubtitle = bookData.bookMeta.bookSubtitle;
let bookGenContent = bookData.bookGenContent;
bookData.bookFinal.bookChapters = [];
bookData.bookFinal.bookChapterContentTitle = [];
bookData.bookFinal.bookChapterContent = [];
for(let i = 0; i < bookGenContent.chapterTitle.length; i += 1) {
bookData.bookFinal.bookChapters.push(bookGenContent.chapterTitle[i]);
let flattenedContentTitles = bookGenContent.contentTitle[i].flat(Infinity);
bookData.bookFinal.bookChapterContentTitle.push(flattenedContentTitles);
let flattenedContentFinal = bookGenContent.contentFinal[i].flat(Infinity);
bookData.bookFinal.bookChapterContent.push(flattenedContentFinal);
}
return bookData;
}
const exportToCSV = async (bookData) => {
const title = bookData.bookMeta.bookTitle;
const directoryPath = `./export/${title}/files/csv/`;
const filePath = path.join(directoryPath, `${title} - bookGenContent.csv`);
if (!fs.existsSync(directoryPath)) {
fs.mkdirSync(directoryPath, { recursive: true });
}
const csvWriter = createObjectCsvWriter({
path: filePath,
header: [
{ id: 'chapterTitle', title: 'Chapter Title' },
{ id: 'chapterTheme', title: 'Chapter Theme' },
{ id: 'plotSummaryShort', title: 'Short Plot Summary' },
{ id: 'plotSummaryLong', title: 'Long Plot Summary' },
{ id: 'contentTitle', title: 'Content Title' },
{ id: 'contentParagraphs', title: 'Content Paragraphs' },
],
});
const records = [];
for (let i = 0; i < bookData.bookGenContent.chapterTitle.length; i++) {
const chapterTitle = bookData.bookGenContent.chapterTitle[i];
const chapterTheme = bookData.bookGenContent.chapterTheme[i][0];
const plotSummaryShort = bookData.bookGenContent.plotSummaryShort[i][0][0];
const plotSummaryLong = bookData.bookGenContent.plotSummaryLong[i][0][0][0];
for (let j = 0; j < bookData.bookGenContent.contentTitle[i].length; j++) {
const contentTitle = bookData.bookGenContent.contentTitle[i][j][0][0];
const contentParagraphs = bookData.bookGenContent.contentParagraphs[i][j];
for (let k = 0; k < contentParagraphs.length; k++) {
const paragraph = contentParagraphs[k][0][0];
records.push({
chapterTitle,
chapterTheme,
plotSummaryShort,
plotSummaryLong,
contentTitle,
contentParagraphs: paragraph,
});
}
}
}
try {
await csvWriter.writeRecords(records);
console.log('CSV file has been successfully created.');
} catch (err) {
console.error('Error while writing CSV:', err);
}
};
const generateMDFile = async (bookData) => {
let content = `---
title: ${bookData.bookMeta.bookTitle}
subtitle: ${bookData.bookMeta.bookSubtitle}
description: ${bookData.bookMeta.bookDescription}
author: ${bookData.bookMeta.authorName}
genre: ${bookData.bookMeta.genre}
---
`;
for(let i = 0; i < bookData.bookFinal.bookChapters.length; i++) {
content += `\n# ${bookData.bookFinal.bookChapters[i]}\n`;
let chapterContentTitles = bookData.bookFinal.bookChapterContentTitle[i];
let chapterContents = bookData.bookFinal.bookChapterContent[i];
for(let j = 0; j < chapterContentTitles.length; j++) {
content += `\n## ${chapterContentTitles[j]}\n`;
content += `${chapterContents[j]}\n`;
}
content += '\n';
}
const directory = `./export/${bookData.bookFinal.bookTitle}/files/raw/`;
const filename = `${bookData.bookMeta.bookTitle}.md`;
const filePath = path.join(directory, filename);
fs.mkdirSync(directory, { recursive: true });
fs.writeFileSync(filePath, content);
console.log(`Markdown file generated and saved at: ${filePath}`);
};
const createDocx = async (bookData) => {
const src = `./export/${bookData.bookMeta.bookTitle}/files/raw/${bookData.bookMeta.bookTitle}.md`;
const args = `-f markdown -t docx -o ./temp/book.docx`;
return new Promise((resolve, reject) => {
pandoc(src, args, function (err, result) {
if (err) {
console.error('Pandoc Error: ', err);
reject(err);
} else {
console.log('Docx File Created: ', result);
resolve(result);
}
});
});
};
const createPDF = async (bookData) => {
const src = `./export/${bookData.bookMeta.bookTitle}/files/raw/${bookData.bookMeta.bookTitle}.md`;
const args = `-f markdown -t pdf -o ./temp/book.pdf`;
return new Promise((resolve, reject) => {
pandoc(src, args, function (err, result) {
if (err) {
console.error('Pandoc Error: ', err);
if (err.message.includes('No such file')) {
reject(new Error('The input file does not exist.'));
} else if (err.message.includes('Cannot write to')) {
reject(new Error('Cannot write to the output file path.'));
} else {
reject(new Error('An unknown error occurred.'));