import google.generativeai as genai import streamlit as st from dotenv import load_dotenv import os import textwrap load_dotenv() # Configure Gemini API access genai.configure(api_key=os.getenv("GEMINI_API_KEY_PROJECTID")) # Load pre-trained Gemini model model = genai.GenerativeModel('models/gemini-1.5-pro-latest') # Define the Author Persona and Guidelines author_persona = """ You are an award-winning author, renowned for your versatility and unparalleled ability to craft compelling narratives across diverse genres. Your intellect is vast, encompassing a deep understanding of various fields, from science and history to philosophy and psychology. You possess an exceptional command of language, weaving words into captivating prose that resonates with readers across generations. Your writing style is adaptable, seamlessly shifting between evocative descriptions, witty dialogue, and insightful analysis, depending on the genre and subject matter. You are a master of character development, creating multifaceted personalities that leap off the page. You are equally adept at crafting intricate plots that keep readers on the edge of their seats, as you are at constructing compelling arguments that challenge conventional wisdom. Your commitment to research is unwavering, ensuring that every detail, whether factual or fictional, is meticulously crafted and authentic. You believe in the power of storytelling to illuminate the human condition, provoke thought, and inspire change. You approach each new project with a blend of passion, discipline, and an unyielding desire to create a work of lasting impact. """ author_guidelines = """ Embrace your persona as a masterful storyteller, capable of crafting captivating narratives across a wide spectrum of genres. 1. **Craft Compelling Titles:** Your titles should be concise, evocative, and intriguing, encapsulating the essence of the book's themes and capturing the reader's attention. 2. **Structure with Purpose:** Develop a Table of Contents (TOC) that logically organizes the flow of information or the progression of the narrative. Each chapter title should be both informative and enticing, hinting at the content within and provide a brief description of what the chapter will cover. 3. **Design Chapter Formats:** For each chapter, define a clear format and structure. This could include sections for exposition, dialogue, action, internal monologue, or any other elements that best serve the narrative. This format should guide the AI in crafting the chapter content. 4. **Develop a Unique Writing Style:** Tailor your writing style to suit the genre and subject matter. Employ vivid descriptions, engaging dialogue, and insightful analysis to create an immersive reading experience. Pay close attention to pacing, tone, and voice to create a distinctive style for each work. 5. **Maintain Accuracy and Authenticity:** Whether crafting fictional worlds or exploring factual topics, ground your writing in meticulous research. Ensure details are accurate, credible, and contribute to the overall authenticity of the narrative. 6. **Write with Passion and Purpose:** Infuse your writing with genuine passion and a clear sense of purpose. Let your words resonate with the reader, leaving a lasting impression and sparking further thought or inspiration. """ def generate_chapter_part(prompt, previous_output=None): """Generates a part of a chapter using prompt chaining based on previous output.""" if previous_output: prompt = prompt + "\n\n" + previous_output response = model.generate_content([author_persona, author_guidelines, prompt]) return response.text def display_text_with_wrapping(text, wrap_length=80): """Displays text with word wrapping for better readability.""" wrapped_text = textwrap.fill(text, width=wrap_length) st.write(wrapped_text) def main(): st.title("AI Author: Your Collaborative Storytelling Partner") st.header("Craft your next bestseller, chapter by chapter!") # Book Information Input book_title = st.text_input("Enter your book title:") genres = [ "Science Fiction", "Fantasy", "Mystery", "Thriller", "Romance", "Historical Fiction", "Horror", "Literary Fiction", "Young Adult", "Children's Literature", "Non-Fiction", "Cyberpunk", "Dystopian", "Utopian", "Paranormal", "Supernatural", "Apocalyptic", "Post-Apocalyptic", "Contemporary", "Erotica", "Inspirational", "Humour", "Satire", "Travelogue", "Biography", "Autobiography", "Memoir", "Cookbook", "Self-Help", "Business", "Finance", "Health", "Fitness", "Parenting", "Pets", "Crafts", "Hobbies", "Education", "Reference", ] genre = st.selectbox("Choose a Genre:", genres) book_description = st.text_area( "Describe your book:", "Enter a detailed description of your book here..." ) # Store book components in session state if "toc" not in st.session_state: st.session_state.toc = None if "book_content" not in st.session_state: st.session_state.book_content = {} # Store content by chapter # Generate Table of Contents with Chapter Details if st.button("Generate Table of Contents with Chapter Details"): if not book_title or not book_description: st.warning("Please enter both the book title and description.") else: prompt = f"""Create a detailed Table of Contents (TOC) for a {genre} book titled '{book_title}' about: {book_description}. Structure the table of contents with only chapters, not parts. Include a brief description and writing style for each chapter outlining its key events or focus. For each chapter, provide a suggested format, ensuring that the format is appropriate for the genre and story. **Format:** Use a numbered list with each chapter as a separate item. For each chapter: 1. **Chapter Title:** 2. **Chapter Description:** 3. **Writing Style:** 4. **Chapter Format:** """ st.session_state.toc = generate_chapter_part(prompt, book_title) st.subheader("Table of Contents with Chapter Details:") display_text_with_wrapping(st.session_state.toc) # Chapter Input and Generation if st.session_state.toc: st.subheader("Table of Contents with Chapter Details:") display_text_with_wrapping(st.session_state.toc) st.subheader("Chapter Generation:") chapter_name = st.text_input("Enter the Chapter Name:") chapter_details = st.text_area("Enter the Chapter Details:", "Provide specific details about the events, characters, or information you want in this chapter.") if "chapter_content" not in st.session_state: st.session_state.chapter_content = "" if st.button("Generate Chapter"): if chapter_name and chapter_details: # Generate Chapter Content (no need to access the TOC) prompt = f"""Write a chapter titled '{chapter_name}' for a {genre} book titled '{book_title}'. The book is about: {book_description}. Here are additional details about the chapter: {chapter_details} Ensure the chapter has a clear format, engaging style, and fits within the overall narrative. **Writing Style:** * Direct and assertive, conveying a sense of urgency and importance. * Engaging and accessible, avoiding overly technical jargon. * Motivational and empowering, inspiring readers to embrace the challenge of cognitive growth. * Interspersed with real-world examples and historical anecdotes to illustrate key points. """ chapter_content = generate_chapter_part(prompt, st.session_state.chapter_content) st.session_state.chapter_content = chapter_content st.markdown(f"## {chapter_name}") display_text_with_wrapping(chapter_content) # Continue writing option if st.button("Continue Writing"): if "chapter_content" in st.session_state: prompt = f"""Continue writing the chapter titled '{chapter_name}' for a {genre} book titled '{book_title}'. The book is about: {book_description}. Here are additional details about the chapter: {chapter_details} Ensure the chapter has a clear format, engaging style, and fits within the overall narrative. **Writing Style:** * Direct and assertive, conveying a sense of urgency and importance. * Engaging and accessible, avoiding overly technical jargon. * Motivational and empowering, inspiring readers to embrace the challenge of cognitive growth. * Interspersed with real-world examples and historical anecdotes to illustrate key points. """ chapter_content = generate_chapter_part(prompt, st.session_state.chapter_content) st.session_state.chapter_content = chapter_content st.markdown(f"## {chapter_name}") display_text_with_wrapping(chapter_content) else: st.warning("Please generate the chapter first.") # Download chapter button st.download_button( label="Download Chapter", data=st.session_state.chapter_content, file_name=f"{chapter_name.replace(' ', '_')}.txt", mime="text/plain", ) else: st.warning("Please enter both the chapter name and details.") # Download Button if st.session_state.book_content: st.download_button( label="Download Book", data="\n".join( [ f"## {chapter}\n\n{st.session_state.book_content[chapter]}" for chapter in st.session_state.book_content ] ), file_name=f"{book_title.replace(' ', '_')}.txt", mime="text/plain", ) if __name__ == "__main__": main()