-
Notifications
You must be signed in to change notification settings - Fork 66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fixed the errors in the code! #25
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,23 @@ | ||
import openai | ||
from tqdm import tqdm | ||
import prompts | ||
|
||
import random | ||
from datetime import datetime, timezone, timedelta | ||
|
||
class Book: | ||
def __str__(self): | ||
book_structure = "Structure of the book:\n" | ||
for chapter_index, chapter_info in enumerate(self.chapters, start=1): | ||
chapter_title = chapter_info['title'] | ||
chapter_paragraphs = chapter_info['paragraphs'] | ||
book_structure += f"Chapter {chapter_index} ({len(chapter_paragraphs)} paragraphs): {chapter_title}\n" | ||
for paragraph_index, paragraph_info in enumerate(chapter_paragraphs, start=1): | ||
paragraph_title = paragraph_info['title'] | ||
paragraph_words = paragraph_info['words'] | ||
book_structure += f"\tParagraph {paragraph_index} ({paragraph_words} words): {paragraph_title}\n" | ||
|
||
return book_structure | ||
|
||
def __init__(self, **kwargs): | ||
# Joining the keyword arguments into a single string | ||
self.arguments = '; '.join([f'{key}: {value}' for key, value in kwargs.items() if key != 'tolerance']) | ||
|
@@ -49,9 +63,14 @@ def get_structure(self): | |
self.structure_prompt.append(self.get_message('user', structure_arguments)) | ||
self.structure = self.get_response(self.structure_prompt) | ||
self.chapters = self.convert_structure(self.structure) | ||
self.paragraph_amounts = self.get_paragraph_amounts(self.chapters) | ||
self.paragraph_words = self.get_paragraph_words(self.chapters) | ||
return self.structure, self.chapters | ||
|
||
# Ensure self.chapters contains the actual chapter information before assigning paragraph amounts and words. | ||
if isinstance(self.chapters, list): | ||
self.paragraph_amounts = self.get_paragraph_amounts(self.chapters) # updated line | ||
self.paragraph_words = self.get_paragraph_words(self.chapters) # updated line | ||
return str(self.structure), self.chapters | ||
else: | ||
self.output('Error in converting the book structure.') | ||
|
||
def finish_base(self): | ||
if not hasattr(self, 'title'): | ||
|
@@ -87,18 +106,26 @@ def get_content(self): | |
|
||
def save_book(self): | ||
# Save the book in md format | ||
with open(f'book.md', 'w') as file: | ||
# Corrected saving the book with the specified time | ||
desired_time = datetime.now(timezone(timedelta(hours=-5))) # EST timezone | ||
# Use the desired time as a seed for the random number generator | ||
random.seed(desired_time) | ||
# Generate a random 4-digit number | ||
random_number = random.randint(1000009, 9999999) | ||
# Ensure it's 4 digits long | ||
random_number = str(random_number).zfill(random.randint(7, 10)) | ||
with open(f'book{random_number}.md', 'w') as file: | ||
file.write(f'# {self.title}\n\n') | ||
for chapter in self.content: | ||
file.write(f'## {self.chapters[self.content.index(chapter)]["title"]}\n\n') | ||
for paragraph in chapter: | ||
file.write( | ||
f'### {self.chapters[self.content.index(chapter)]["paragraphs"][chapter.index(paragraph)]["title"]}\n\n') | ||
f'### {self.chapters[self.content.index(chapter)]["paragraphs"][chapter.index(paragraph)]["title"]}\n\n' | ||
) | ||
file.write(paragraph + '\n\n') | ||
file.write('\n\n') | ||
|
||
def get_chapter(self, chapter_index, prompt): | ||
if len(self.base_prompt) == 3: | ||
if len(self.base_prompt) <= 9: | ||
self.finish_base() | ||
|
||
paragraphs = [] | ||
|
@@ -136,19 +163,34 @@ def convert_structure(structure): | |
for chapter in chapters: | ||
for line in chapter.split("\n"): | ||
if 'paragraphs' in line.lower(): | ||
chapter_information.append({'title': line.split('): ')[1], 'paragraphs': []}) | ||
elif 'paragraph' in line.lower(): | ||
chapter_information.append( | ||
{'title': line.split('): ')[1], 'paragraphs': []} | ||
) | ||
if 'paragraph' in line.lower(): | ||
chapter_information[-1]['paragraphs'].append( | ||
{'title': line.split('): ')[1], 'words': line.split('(')[1].split(')')[0].split(' ')[0]}) | ||
chapter_information[-1]['paragraph_amount'] = len(chapter_information[-1]['paragraphs']) | ||
|
||
{'title': line.split('): ')[1], 'words': line.split( | ||
'(')[1].split(')' | ||
)[0].split( | ||
' ' | ||
)[0]} | ||
) | ||
elif chapter_information == []: | ||
## I can't figure out the code for this | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sounds unfinished, does it work? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes this part of the code works so far I just formatted it differently |
||
chapter_information[0]['paragraphs'].append( | ||
{'title': line.split('): ')[1], 'words': line.split( | ||
'(')[1].split(')' | ||
)[0].split( | ||
' ' | ||
)[0]} | ||
) | ||
|
||
return chapter_information | ||
|
||
@staticmethod | ||
def get_paragraph_amounts(structure): | ||
amounts = [] | ||
for chapter in structure: | ||
amounts.append(chapter['paragraph_amount']) | ||
amounts.append(len(chapter['paragraphs'])) | ||
return amounts | ||
|
||
@staticmethod | ||
|
@@ -161,7 +203,7 @@ def get_paragraph_words(structure): | |
@staticmethod | ||
def get_response(prompt): | ||
return openai.ChatCompletion.create( | ||
model="gpt-3.5-turbo-0301", | ||
model="gpt-3.5-turbo-16k-0613", | ||
messages=prompt | ||
)["choices"][0]["message"]["content"] | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,10 @@ | ||
# Imports | ||
from pyfiglet import Figlet | ||
from book import Book | ||
import json | ||
import openai | ||
import os | ||
import streamlit as st | ||
import json | ||
|
||
|
||
# Get the OpenAI API key from the config file | ||
|
@@ -12,7 +14,6 @@ def get_api_key(): | |
# Return the OpenAI key | ||
return json.load(f)['OpenAI_key'] | ||
|
||
|
||
# Draw the given text in a figlet | ||
def draw(text): | ||
# Create a new figlet object | ||
|
@@ -52,6 +53,7 @@ def get_option(options): | |
def main(): | ||
# Set the OpenAI API key | ||
openai.api_key = get_api_key() | ||
#openai.api_key = os.getenv("OPENAI_KEY") | ||
|
||
# Draw the title | ||
draw('BookGPT') | ||
|
@@ -63,14 +65,16 @@ def main(): | |
# Get the number of chapters | ||
print('How many chapters should the book have?') | ||
chapters = int(input('> ')) | ||
if chapters <= 1: | ||
words = 1 | ||
|
||
# Get the number of words per chapter | ||
print('How many words should each chapter have?') | ||
# Check if it is below 1200 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this comment probably needs to be updated as well, but I also found it weird to have min limit... There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I fooled around with a lot of the settings just testing what didn't work and I needed this to prevent something unwanted from happening. Right now the code works without all prompting because I have each setting fixed right now. I made it up to 10 chapters with 2000 words using the newer November gpt-3.5-turbo |
||
words = int(input('> ')) | ||
if words <= 1200: | ||
words = 1200 | ||
print('The number of words per chapter has been set to 1200. (The max number of words per chapter)') | ||
if words >= 2600: | ||
words = 2600 | ||
print('The number of words per chapter has been set to 2600. (The max number of words per chapter)') | ||
|
||
# Get the category of the book | ||
print('What is the category of the book?') | ||
|
@@ -83,7 +87,7 @@ def main(): | |
# What is the tolerance of the book? | ||
print('What is the tolerance of the book? (0.8 means that 80% of the words will be written 100%)') | ||
tolerance = float(input('> ')) | ||
if tolerance < 0 or tolerance > 1: | ||
if tolerance <= 0 or tolerance >= 0.9: | ||
tolerance = 0.8 | ||
|
||
# Do you want to add any additional parameters? | ||
|
@@ -116,15 +120,15 @@ def main(): | |
|
||
# Print the structure of the book | ||
print('Structure of the book:') | ||
structure, _ = book.get_structure() | ||
print(structure) | ||
structure = book.get_structure() | ||
print(book) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this seems like unwanted change? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is actually how I'm using it right now and there are some changes to make testing a bit easier but I'm only have a problem getting the structure and yeah I changed it back to print structure instead of print book https://replit.com/@CJSTRYKER/AuthorGPT |
||
|
||
# Ask if he wants to change the structure until he is satisfied | ||
while True: | ||
print('Do you want to generate a new structure?') | ||
if get_option(['No', 'Yes']) - 1: | ||
print('Structure of the book:') | ||
structure, _ = book.get_structure() | ||
structure = book.get_structure() | ||
print(structure) | ||
else: | ||
break | ||
|
@@ -138,7 +142,7 @@ def main(): | |
|
||
# Save the book | ||
book.save_book() | ||
print('Book saved as book.md.') | ||
print('Book saved.') | ||
|
||
|
||
# Run the main function | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This increase is because you're using 16k, right? So you can give more context?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This might have been the ghostwriter on replit but I'm not sure because I can't remember why I changed it in the first place