ILLERRAPS commited on
Commit
a30be88
·
verified ·
1 Parent(s): 782ae97

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. book_generator.py +76 -78
  2. updated_book_generator.py +16 -11
book_generator.py CHANGED
@@ -2,99 +2,97 @@ import os
2
  from langchain_groq import ChatGroq
3
  from langchain.prompts import ChatPromptTemplate
4
  from langchain_core.output_parsers import StrOutputParser
 
5
  from typing import Dict
6
  import gradio as gr # Import Gradio
7
- import shutil # Import shutil for file operations
8
 
9
- # Step 1: Set the environment variable for the Groq API Key
10
- os.environ["GROQ_API_KEY"] = "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" # Use a valid Groq API key
11
 
12
- # Step 2: Define a function to create agents
13
- def create_agent(role: str, model_name: str = "llama3-70b-8192", temperature: float = 0.7) -> ChatGroq:
14
- """Create a LangChain agent for a specific role in book writing."""
 
 
 
 
 
15
  prompt_template = ChatPromptTemplate.from_messages([
16
- ("system", f"You are a {role}. Write high-quality, engaging content."),
17
  ("human", "{input}")
18
  ])
19
- llm = ChatGroq(model=model_name, temperature=temperature)
20
  chain = prompt_template | llm | StrOutputParser()
21
  return chain
22
 
23
- # Step 3: Create specific agents
24
- chapter_agent = create_agent("chapter writer")
25
- outline_agent = create_agent("outline creator")
26
- editing_agent = create_agent("editor")
27
- proofreading_agent = create_agent("proofreader")
28
- character_agent = create_agent("character developer")
 
 
 
 
29
 
30
- # Step 4: Define functions for generating content
31
- def generate_chapter(title: str, synopsis: str, agent) -> str:
32
- """Generate a chapter based on the title and synopsis."""
33
- query = f"Write a detailed chapter based on the following synopsis:\n\nTitle: {title}\n\nSynopsis: {synopsis}"
34
- return agent.invoke({"input": query})
35
-
36
- def generate_outline(book_title: str, agent) -> Dict[str, str]:
37
- """Generate an outline for the book."""
38
- query = f"Create an outline for a book titled '{book_title}'."
39
- return agent.invoke({"input": query})
40
-
41
- def edit_content(content: str, agent) -> str:
42
- """Edit the provided content."""
43
- query = f"Edit the following content for clarity and style:\n\n{content}"
44
- return agent.invoke({"input": query})
45
-
46
- def proofread_content(content: str, agent) -> str:
47
- """Proofread the provided content for grammar and spelling errors."""
48
- query = f"Proofread the following content:\n\n{content}"
49
- return agent.invoke({"input": query})
50
 
51
- def generate_character_profile(character_name: str, agent) -> str:
52
- """Generate a character profile for the given character name."""
53
- query = f"Create a character profile for '{character_name}'."
54
- return agent.invoke({"input": query})
 
 
 
 
 
 
55
 
56
- def save_chapter_to_file(chapter_text: str) -> str:
57
- """Save the generated chapter to a .txt file."""
58
- file_path = "generated_chapter.txt"
59
- with open(file_path, "w") as file:
60
- file.write(chapter_text)
61
- return file_path # Return the file path for downloading
 
 
 
62
 
63
- # Step 5: Define Gradio interface
64
- def gradio_interface(book_title: str, chapter_title: str, chapter_synopsis: str):
65
- """Gradio interface for generating book content."""
66
- outline = generate_outline(book_title, outline_agent)
67
- chapter_text = generate_chapter(chapter_title, chapter_synopsis, chapter_agent)
68
- edited_chapter = edit_content(chapter_text, editing_agent)
69
- proofread_chapter = proofread_content(edited_chapter, proofreading_agent)
70
-
71
- # Save and download buttons
72
- save_button = gr.Button("Save Chapter")
73
- download_button = gr.Button("Download Chapter")
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- # Define button actions
76
- save_button.click(fn=save_chapter_to_file, inputs=proofread_chapter, outputs="text")
77
- download_button.click(fn=shutil.copy, inputs="generated_chapter.txt", outputs="text")
78
 
79
- return outline, chapter_text, edited_chapter, proofread_chapter
80
 
81
- # Step 6: Launch Gradio app
82
  if __name__ == "__main__":
83
- # Define the Gradio interface
84
- iface = gr.Interface(
85
- fn=gradio_interface,
86
- inputs=[
87
- gr.Textbox(label="Book Title"),
88
- gr.Textbox(label="Chapter Title"),
89
- gr.Textbox(label="Chapter Synopsis")
90
- ],
91
- outputs=[
92
- gr.Textbox(label="Generated Outline", lines=5),
93
- gr.Textbox(label="Generated Chapter", lines=5),
94
- gr.Textbox(label="Edited Chapter", lines=5),
95
- gr.Textbox(label="Proofread Chapter", lines=5)
96
- ],
97
- title="Book Generator",
98
- description="Generate book content using AI."
99
- )
100
- iface.launch(share=True) # Launch the Gradio app
 
2
  from langchain_groq import ChatGroq
3
  from langchain.prompts import ChatPromptTemplate
4
  from langchain_core.output_parsers import StrOutputParser
5
+ from langchain_core.runnables import RunnablePassthrough
6
  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"] = "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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."""
20
  prompt_template = ChatPromptTemplate.from_messages([
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):
29
+ """Generate a full chapter given a title."""
30
+ query = f"Write a detailed chapter titled '{title}'"
31
+ try:
32
+ # Yield chunks of text instead of returning all at once
33
+ for chunk in agent.invoke({"input": query}):
34
+ yield chunk # Yield each chunk as it is generated
35
+ except Exception as e:
36
+ print(f"An error occurred while generating the chapter: {e}")
37
+ yield ""
38
 
39
+ def write_book(title: str, outline: Dict[str, str]):
40
+ """
41
+ Generate a complete book.
42
+
43
+ Args:
44
+ title (str): The title of the book.
45
+ outline (Dict[str, str]): A dictionary with chapter titles as keys.
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ Returns:
48
+ str: The full book as a single string.
49
+ """
50
+ book = f"# {title}\n\n"
51
+ for chapter_title in outline.keys():
52
+ book += f"## {chapter_title}\n\n"
53
+ agent = create_book_agent() # Create a new agent for each chapter
54
+ for chapter_text in generate_chapter(chapter_title, agent):
55
+ book += chapter_text # Append each chunk to the book
56
+ return book # Return the complete book
57
 
58
+ # Step 6: Gradio interface
59
+ def gradio_interface(api_key: str = ""):
60
+ """Create a Gradio interface for book generation."""
61
+ with gr.Blocks() as demo:
62
+ gr.Markdown("## Book Generator")
63
+ gr.Markdown("This application was created by iLL-Ai AaronAllton and a team of Groq agents that write books.") # Updated note
64
+ user_input = gr.Textbox(label="Enter Book Title, Number of Chapters, and Type of Book (e.g., 'My Book, 10, Novel')", placeholder="Title, Chapters, Type") # Combined input
65
+ generate_button = gr.Button("Generate Outline")
66
+ output = gr.Textbox(label="Generated Book", interactive=False)
67
 
68
+ def generate_book_interface(user_input):
69
+ try:
70
+ # Ensure the input is properly formatted
71
+ parts = user_input.split(",")
72
+ if len(parts) < 3:
73
+ return "Please provide input in the format: 'Title, Number of Chapters, Type of Book'."
74
+
75
+ title = parts[0].strip() # First part is the title
76
+ outline = parts[1].strip() if len(parts) > 1 else "1" # Default to 1 chapter if not provided
77
+ book_type = parts[2].strip() if len(parts) > 2 else "General" # Default to "General" if not provided
78
+
79
+ outline_dict = {}
80
+ if not outline.strip(): # Check if outline is empty
81
+ return "Please provide a valid outline." # Prompt user for valid outline
82
+
83
+ # Generate outline based on user input and book type
84
+ num_chapters = int(outline) # Extract number of chapters
85
+ outline_dict = {f"{book_type} Chapter {i}": None for i in range(1, num_chapters + 1)} # Create outline dictionary with style
86
+
87
+ print(f"Processed Outline: {outline_dict}") # Debug statement
88
+ agent = create_book_agent(api_key) # Create agent with user-provided API key
89
+ return write_book(title, outline_dict) # Call the generator
90
+ except Exception as e:
91
+ return f"An error occurred: {e}"
92
 
93
+ generate_button.click(generate_book_interface, inputs=user_input, outputs=output)
 
 
94
 
95
+ demo.launch(share=True) # Enable sharing of the Gradio app
96
 
 
97
  if __name__ == "__main__":
98
+ gradio_interface()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
updated_book_generator.py CHANGED
@@ -24,9 +24,9 @@ novel_agent = create_agent("novel writer")
24
  guide_agent = create_agent("guide writer")
25
 
26
  # Step 4: Define functions for generating content
27
- def generate_novel(title: str, synopsis: str, chapters: int) -> str:
28
- """Generate a novel based on the title and synopsis, with chapter breakdown."""
29
- query = f"Generate a novel titled '{title}' with the following synopsis:\n\n{synopsis}\n\nBreak it down into {chapters} chapters with titles and word count estimates."
30
  return novel_agent.invoke({"input": query})
31
 
32
  def generate_guide(title: str, synopsis: str) -> str:
@@ -35,12 +35,14 @@ def generate_guide(title: str, synopsis: str) -> str:
35
  return guide_agent.invoke({"input": query})
36
 
37
  # Step 5: Define Gradio interface
38
- def gradio_interface(novel_title: str, novel_synopsis: str, chapters: int):
39
  """Gradio interface for generating book content."""
40
- if novel_title and novel_synopsis:
41
- novel_content = generate_novel(novel_title, novel_synopsis, chapters)
42
- return novel_content, "", "" # Return only novel content
43
- return "", "", "" # Return empty if no input
 
 
44
 
45
  # Step 6: Launch Gradio app
46
  if __name__ == "__main__":
@@ -48,11 +50,10 @@ if __name__ == "__main__":
48
  fn=gradio_interface,
49
  inputs=[
50
  gr.Textbox(label="Novel Title"),
51
- gr.Textbox(label="Novel Synopsis"),
52
- gr.Slider(minimum=1, maximum=10, label="Number of Chapters") # Slider for chapter count
53
  ],
54
  outputs=[
55
- gr.Textbox(label="Generated Novel Content", lines=10),
56
  gr.Textbox(label="Generated Guide Content", lines=5),
57
  gr.Textbox(label="Final Draft", lines=10) # Output for the final draft
58
  ],
@@ -60,5 +61,9 @@ if __name__ == "__main__":
60
  description="Generate content for novels and guides using AI."
61
  )
62
 
 
 
 
 
63
  # Launch the Gradio app
64
  iface.launch(share=True)
 
24
  guide_agent = create_agent("guide writer")
25
 
26
  # Step 4: Define functions for generating content
27
+ def generate_novel(title: str, synopsis: str) -> str:
28
+ """Generate a novel based on the title and synopsis."""
29
+ query = f"Write a detailed novel based on the following synopsis:\n\nTitle: {title}\n\nSynopsis: {synopsis}"
30
  return novel_agent.invoke({"input": query})
31
 
32
  def generate_guide(title: str, synopsis: str) -> str:
 
35
  return guide_agent.invoke({"input": query})
36
 
37
  # Step 5: Define Gradio interface
38
+ def gradio_interface(novel_title: str, novel_synopsis: str, guide_title: str, guide_synopsis: str):
39
  """Gradio interface for generating book content."""
40
+ novel_content = generate_novel(novel_title, novel_synopsis)
41
+ guide_content = generate_guide(guide_title, guide_synopsis)
42
+
43
+ final_draft = f"Final Draft:\n\nNovel Content:\n{novel_content}\n\nGuide Content:\n{guide_content}"
44
+
45
+ return novel_content, guide_content, final_draft # Ensure all three outputs are returned
46
 
47
  # Step 6: Launch Gradio app
48
  if __name__ == "__main__":
 
50
  fn=gradio_interface,
51
  inputs=[
52
  gr.Textbox(label="Novel Title"),
53
+ gr.Textbox(label="Guide Synopsis")
 
54
  ],
55
  outputs=[
56
+ gr.Textbox(label="Generated Novel Content", lines=5),
57
  gr.Textbox(label="Generated Guide Content", lines=5),
58
  gr.Textbox(label="Final Draft", lines=10) # Output for the final draft
59
  ],
 
61
  description="Generate content for novels and guides using AI."
62
  )
63
 
64
+ # Define the function for generating the final draft
65
+ def generate_final_draft(novel_content, guide_content):
66
+ return f"Final Draft:\n\nNovel Content:\n{novel_content}\n\nGuide Content:\n{guide_content}"
67
+
68
  # Launch the Gradio app
69
  iface.launch(share=True)