import google.generativeai as genai import streamlit as st from dotenv import load_dotenv import os 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 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. 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. 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_book_component(prompt, previous_output=None): """Generates a book component 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 main(): st.title("AI Author") st.header("Write your next bestseller!") # 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"] 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 'chapter_formats' not in st.session_state: st.session_state.chapter_formats = {} if 'book_content' not in st.session_state: st.session_state.book_content = "" # Generate Table of Contents if st.button("Generate Table of Contents"): 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 for a {genre} book titled '{book_title}' about: {book_description}" st.session_state.toc = generate_book_component(prompt, book_title) st.subheader("Table of Contents:") st.write(st.session_state.toc) # Generate Chapter Format and Chapter Content if st.session_state.toc: chapters = st.session_state.toc.split("\n") for i, chapter in enumerate(chapters): if chapter: st.markdown(f"## Chapter {i+1}: {chapter}") # Generate Chapter Format if chapter not in st.session_state.chapter_formats: if st.button(f"Generate Format for Chapter {i+1}"): format_prompt = f"Suggest a detailed format for writing chapter '{chapter}' of the {genre} book '{book_title}'. Consider the narrative flow and genre conventions." st.session_state.chapter_formats[chapter] = generate_book_component(format_prompt, st.session_state.toc) if chapter in st.session_state.chapter_formats: st.write("**Chapter Format:**") st.write(st.session_state.chapter_formats[chapter]) # Generate Chapter Content if st.button(f"Generate Chapter {i+1}"): chapter_content = "" format_sections = st.session_state.chapter_formats[chapter].split("\n") for section in format_sections: if section: section_prompt = f"Write the '{section.strip()}' section of chapter '{chapter}' for the {genre} book '{book_title}', ensuring it fits into the overall narrative and follows the previous content." section_content = generate_book_component(section_prompt, chapter_content) chapter_content += f"{section.strip()}:\n{section_content}\n\n" st.session_state.book_content += f"## Chapter {i+1}: {chapter}\n\n{st.session_state.chapter_formats[chapter]}\n\n{chapter_content}\n\n" st.write("**Chapter Content:**") st.write(chapter_content) # Download Button if st.session_state.book_content: st.download_button( label="Download Book", data=st.session_state.book_content, file_name=f"{book_title.replace(' ', '_')}.txt", mime="text/plain" ) if __name__ == "__main__": main()