Spaces:
Running
Running
Upload folder using huggingface_hub
Browse files- book_generator.py +76 -78
- 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
|
10 |
-
os.environ["GROQ_API_KEY"] = "
|
11 |
|
12 |
-
# Step
|
13 |
-
def
|
14 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
15 |
prompt_template = ChatPromptTemplate.from_messages([
|
16 |
-
("system",
|
17 |
("human", "{input}")
|
18 |
])
|
19 |
-
llm = ChatGroq(model=model_name, temperature=temperature)
|
20 |
chain = prompt_template | llm | StrOutputParser()
|
21 |
return chain
|
22 |
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
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 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
with
|
60 |
-
|
61 |
-
|
|
|
|
|
|
|
62 |
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
|
75 |
-
|
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 |
-
|
80 |
|
81 |
-
# Step 6: Launch Gradio app
|
82 |
if __name__ == "__main__":
|
83 |
-
|
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
|
28 |
-
"""Generate a novel based on the title and synopsis
|
29 |
-
query = f"
|
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,
|
39 |
"""Gradio interface for generating book content."""
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
|
|
|
|
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="
|
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=
|
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)
|