ILLERRAPS commited on
Commit
a374f3a
·
verified ·
1 Parent(s): cf4c406

Upload folder using huggingface_hub

Browse files
book_generator.py CHANGED
@@ -7,13 +7,13 @@ from typing import Dict
7
  import gradio as gr # Import Gradio
8
 
9
  # Step 3: Set the environment variable for the Groq API Key
10
- os.environ["GROQ_API_KEY"] = os.getenv("GROQ_API_KEY") # Use environment variable for API Key
11
 
12
  # Step 4: Define helper functions for structured book generation
13
  def create_book_agent(
14
  model_name: str = os.getenv("MODEL_NAME", "llama-3.1-8b-instant"), # Use environment variable for model name
15
  temperature: float = 0.7,
16
- max_tokens: int = 16384, # Increased token limit
17
  **kwargs
18
  ) -> ChatGroq:
19
  """Create a LangChain agent for book writing."""
@@ -21,41 +21,37 @@ def create_book_agent(
21
  ("system", "You are a creative writer. Write high-quality, engaging books for any genre."),
22
  ("human", "{input}")
23
  ])
24
- token = os.getenv("HUGGINGFACE_TOKEN") # Get Hugging Face token from environment variable
25
- llm = ChatGroq(model=model_name, temperature=temperature, max_tokens=max_tokens, token=token, **kwargs)
26
  chain = prompt_template | llm | StrOutputParser()
27
  return chain
28
 
29
- def generate_chapter(title: str, synopsis: str, agent) -> str:
30
- """Generate a full chapter given a title and synopsis."""
31
- query = f"Write a detailed chapter based on the following synopsis:\n\nTitle: {title}\n\nSynopsis: {synopsis}"
32
  try:
33
  return agent.invoke({"input": query})
34
  except Exception as e:
35
  print(f"An error occurred while generating the chapter: {e}")
36
  return ""
37
 
38
- def write_book(agent, title: str, outline: Dict[str, str]) -> str:
39
  """
40
  Generate a complete book.
41
 
42
  Args:
43
- agent: The LangChain agent for generating text.
44
  title (str): The title of the book.
45
- outline (Dict[str, str]): A dictionary with chapter titles as keys and synopses as values.
46
 
47
  Returns:
48
  str: The full book as a single string.
49
  """
50
  book = f"# {title}\n\n"
51
- for chapter_title, chapter_synopsis in outline.items():
52
  book += f"## {chapter_title}\n\n"
53
- chapter_text = generate_chapter(chapter_title, chapter_synopsis, agent)
 
54
  book += chapter_text + "\n\n"
55
- return book
56
-
57
- # Step 5: Create the agent
58
- book_agent = create_book_agent()
59
 
60
  # Step 6: Gradio interface
61
  def gradio_interface(api_key: str = ""):
@@ -63,30 +59,62 @@ def gradio_interface(api_key: str = ""):
63
  with gr.Blocks() as demo:
64
  gr.Markdown("## Book Generator")
65
  gr.Markdown("This application was created by iLL-Ai AaronAllton and a team of Groq agents that write books.") # Updated note
66
- book_title = gr.Textbox(label="Book Title")
67
- book_outline = gr.Textbox(label="Book Outline (Structured format, e.g., 'Chapter 1: Synopsis 1; Chapter 2: Synopsis 2')") # Updated prompt
68
- generate_button = gr.Button("Generate Book")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  output = gr.Textbox(label="Generated Book", interactive=False)
70
 
71
- def generate_book_interface(title, outline):
72
  try:
73
  # Normalize the outline input
74
  outline_dict = {}
75
- chapters = outline.split(';') # Split by semicolon for each chapter
76
- for chapter in chapters:
77
- if ':' in chapter:
78
- title, synopsis = chapter.split(':', 1)
79
- outline_dict[title.strip()] = synopsis.strip()
80
- else:
81
- # Handle cases where the input might not follow the expected format
82
- outline_dict[chapter.strip()] = "No synopsis provided."
83
 
84
  print(f"Processed Outline: {outline_dict}") # Debug statement
85
- return write_book(book_agent, title, outline_dict)
 
86
  except Exception as e:
87
  return f"An error occurred: {e}"
88
 
89
- generate_button.click(generate_book_interface, inputs=[book_title, book_outline], outputs=output)
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  demo.launch(share=True) # Enable sharing of the Gradio app
92
 
 
7
  import gradio as gr # Import Gradio
8
 
9
  # Step 3: Set the environment variable for the Groq API Key
10
+ os.environ["GROQ_API_KEY"] = "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" # Use provided secret key
11
 
12
  # Step 4: Define helper functions for structured book generation
13
  def create_book_agent(
14
  model_name: str = os.getenv("MODEL_NAME", "llama-3.1-8b-instant"), # Use environment variable for model name
15
  temperature: float = 0.7,
16
+ max_tokens: int = 8000, # Set max_tokens to 8000
17
  **kwargs
18
  ) -> ChatGroq:
19
  """Create a LangChain agent for book writing."""
 
21
  ("system", "You are a creative writer. Write high-quality, engaging books for any genre."),
22
  ("human", "{input}")
23
  ])
24
+ llm = ChatGroq(model=model_name, temperature=temperature, max_tokens=max_tokens, **kwargs) # Removed token parameter
 
25
  chain = prompt_template | llm | StrOutputParser()
26
  return chain
27
 
28
+ def generate_chapter(title: str, agent) -> str:
29
+ """Generate a full chapter given a title."""
30
+ query = f"Write a detailed chapter titled '{title}'"
31
  try:
32
  return agent.invoke({"input": query})
33
  except Exception as e:
34
  print(f"An error occurred while generating the chapter: {e}")
35
  return ""
36
 
37
+ def write_book(title: str, outline: Dict[str, str]) -> str:
38
  """
39
  Generate a complete book.
40
 
41
  Args:
 
42
  title (str): The title of the book.
43
+ outline (Dict[str, str]): A dictionary with chapter titles as keys.
44
 
45
  Returns:
46
  str: The full book as a single string.
47
  """
48
  book = f"# {title}\n\n"
49
+ for chapter_title in outline.keys():
50
  book += f"## {chapter_title}\n\n"
51
+ agent = create_book_agent() # Create a new agent for each chapter
52
+ chapter_text = generate_chapter(chapter_title, agent)
53
  book += chapter_text + "\n\n"
54
+ return book # Return the complete book
 
 
 
55
 
56
  # Step 6: Gradio interface
57
  def gradio_interface(api_key: str = ""):
 
59
  with gr.Blocks() as demo:
60
  gr.Markdown("## Book Generator")
61
  gr.Markdown("This application was created by iLL-Ai AaronAllton and a team of Groq agents that write books.") # Updated note
62
+ book_title = gr.Textbox(label="Book Title", placeholder="Enter the title of your book") # Added placeholder
63
+ book_outline = gr.Textbox(label="Number of Chapters", placeholder="e.g., '10'", info="Specify the number of chapters you want in your book.") # Added info
64
+ api_key_input = gr.Textbox(label="API Key", type="password", placeholder="Enter your API key") # Added placeholder
65
+ book_description = gr.Textbox(label="Book Description", placeholder="Enter a brief description of the book") # New description textbox
66
+ book_type = gr.Dropdown(label="Type of Book", choices=[
67
+ "Erotic Novel",
68
+ "Step-by-Step Tutorial",
69
+ "Autobiography",
70
+ "Biography",
71
+ "Novel",
72
+ "Horror",
73
+ "Science Fiction",
74
+ "Fantasy",
75
+ "Mystery",
76
+ "Thriller",
77
+ "Romance",
78
+ "Historical Fiction",
79
+ "Self-Help",
80
+ "Cookbook",
81
+ "Children's Book",
82
+ "Graphic Novel"
83
+ ], value="Novel", info="Select the genre or type of book you want to create.") # Added info
84
+ generate_button = gr.Button("Generate Outline")
85
  output = gr.Textbox(label="Generated Book", interactive=False)
86
 
87
+ def generate_book_interface(title, outline, api_key): # Add api_key parameter
88
  try:
89
  # Normalize the outline input
90
  outline_dict = {}
91
+ if not outline.strip(): # Check if outline is empty
92
+ return "Please provide a valid outline." # Prompt user for valid outline
93
+
94
+ # Generate outline based on user input
95
+ num_chapters = int(outline) # Extract number of chapters
96
+ for i in range(1, num_chapters + 1):
97
+ outline_dict[f"Chapter {i}"] = None # No synopsis needed
 
98
 
99
  print(f"Processed Outline: {outline_dict}") # Debug statement
100
+ agent = create_book_agent(api_key) # Create agent with user-provided API key
101
+ return write_book(title, outline_dict) # Call the generator
102
  except Exception as e:
103
  return f"An error occurred: {e}"
104
 
105
+ generate_button.click(generate_book_interface, inputs=[book_title, book_outline, api_key_input], outputs=output)
106
+
107
+ # New button to generate the book from the outline
108
+ generate_book_button = gr.Button("Generate Book")
109
+ generate_book_output = gr.Textbox(label="Final Book", interactive=False)
110
+
111
+ def generate_final_book(title, outline):
112
+ if not outline.strip():
113
+ return "Please provide a valid outline."
114
+ outline_dict = {title: outline}
115
+ return write_book(title, outline_dict)
116
+
117
+ generate_book_button.click(generate_final_book, inputs=[book_title, book_outline], outputs=generate_book_output)
118
 
119
  demo.launch(share=True) # Enable sharing of the Gradio app
120
 
button_functionality_overview.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Button Functionality Overview for the Book Generator
2
+
3
+ ## 1. Generate Outline Button
4
+ - **Description**: Initiates the outline generation process based on user input.
5
+ - **Functionality**: Takes the provided book title and number of chapters to generate an outline for the book.
6
+
7
+ ## 2. Generate Book Button
8
+ - **Description**: Generates the complete book based on the outline.
9
+ - **Functionality**: Takes the book title and outline to create the full book content.
10
+
11
+ ## 3. Clear Button
12
+ - **Description**: Clears all input fields.
13
+ - **Functionality**: Resets the application to its initial state, allowing the user to start fresh.
14
+
15
+ ## 4. Save Button
16
+ - **Description**: Saves the generated book content.
17
+ - **Functionality**: Allows the user to download or save the content to a specified location.
18
+
19
+ ## 5. Load Button
20
+ - **Description**: Loads a previously saved book.
21
+ - **Functionality**: Enables the user to import existing book content for editing or continuation.
22
+
23
+ ## 6. Settings Button
24
+ - **Description**: Opens the settings menu.
25
+ - **Functionality**: Allows the user to adjust application settings, such as model selection or output format.
26
+
27
+ ## 7. Help Button
28
+ - **Description**: Provides assistance or documentation.
29
+ - **Functionality**: Displays help information or guides on how to use the application.
outline_for_iLLAi_book.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Outline for iLLAi-book
2
+
3
+ ## Title
4
+ - iLLAi-book
5
+
6
+ ## Introduction
7
+ - Brief overview of the project and its purpose.
8
+
9
+ ## Requirements
10
+ - List of dependencies and environment variables needed to run the application.
11
+ - `GROQ_API_KEY`: Your Groq API key.
12
+ - `MODEL_NAME`: The name of the model to be used (optional, defaults to "llama-3.1-8b-instant").
13
+
14
+ ## Installation
15
+ - Instructions on how to set up the project locally.
16
+
17
+ ## Usage
18
+ - How to run the application and any relevant commands.
19
+
20
+ ## Features
21
+ - Key functionalities of the book generator.
22
+
23
+ ## Contributing
24
+ - Guidelines for contributing to the project.
25
+
26
+ ## License
27
+ - Information about the project's licensing.
28
+
29
+ ## Contact
30
+ - How to reach the maintainers for questions or support.