# app.py import streamlit as st import json import os from selfapi_writer import SelfApiWriter from data_manager import DataManager class SelfApiApp: def __init__(self): """Initialize the Streamlit application""" st.set_page_config( page_title="AI Book Writer", page_icon="📚", layout="wide" ) # Initialize data manager with explicit path self.data_path = os.path.join(os.getcwd(), 'data') self.data_manager = DataManager(self.data_path) # Initialize session state self._initialize_session_state() # Create necessary directories self._ensure_directories() def _ensure_directories(self): """Create necessary directories""" directories = [ self.data_path, os.path.join(self.data_path, 'blueprints'), os.path.join(self.data_path, 'book_content'), os.path.join(self.data_path, 'exports'), os.path.join(self.data_path, 'chapters'), os.path.join(self.data_path, 'manual_content') ] for dir_path in directories: os.makedirs(dir_path, exist_ok=True) st.write(f"Directory exists: {dir_path} - {os.path.exists(dir_path)}") def _initialize_session_state(self): """Initialize session state variables""" if 'current_tab' not in st.session_state: st.session_state.current_tab = 'Blueprint' if 'blueprint' not in st.session_state: st.session_state.blueprint = self.default_blueprint if 'book_content' not in st.session_state: st.session_state.book_content = { "book_info": {}, "introduction": "", "parts": [] } if 'structure_initialized' not in st.session_state: st.session_state.structure_initialized = False if 'manual_content' not in st.session_state: st.session_state.manual_content = {} @property def default_blueprint(self): """Get default blueprint content""" return """# Book Blueprint ## Core Vision Transform "Self.api" from a conceptual framework into a revolutionary guide that speaks to the modern seeker - the stressed executive who downloads meditation apps but can't stick to them, the engineering lead who understands distributed systems better than their own emotions, and the consultant who can optimize anything except their own life satisfaction. ## Target Audience Primary: Tech professionals, entrepreneurs, and knowledge workers (25-45) Secondary: Anyone feeling disconnected in our hyper-connected world Psychographic: Analytical minds seeking spiritual depth without the woo-woo ## Book Structure ### Introduction: "System Requirements: A Human's Guide to Being Human" - Opening hook: "In a world where we can Google anything except our own purpose..." - Key narrative: Author's journey from debugging code to debugging consciousness ### Part 1: The Human Input/Output System - Rate Limiting Your Reality - Debugging Your Attention Span - The Mindfulness Microservice ### Part 2: Your Internal Neural Network - Training Your Gut Algorithm - The Wisdom Cache - Pattern Recognition Beyond Logic ### Part 3: The Source Code of Being - Quantum Mechanics of Consciousness - The Purpose Protocol - Refactoring Your Reality ### Part 4: The Universal Runtime Environment - Distributed Consciousness Systems - The Empathy Protocol - Scaling Your Impact ## Style Guidelines 1. Technical Authenticity - Use API and tech metaphors naturally - Example: "Think of meditation as a daily health check for your consciousness microservices" 2. Voice & Tone - Witty But Wise - Blend humor with depth - Style: Think Douglas Adams meets Deepak Chopra 3. Chapter Structure - System Log (personal story) - Documentation (teaching) - Implementation Guide (practical steps) ## Content Requirements 1. Each chapter should have: - 3 "aha" moments - 2-3 quotable passages - Practical exercises every 5 pages - Balance: 60% practical, 40% philosophical - Links to both ancient wisdom and modern science""" def save_current_state(self): """Save current state with verification""" try: if st.session_state.blueprint: blueprint_file = self.data_manager.save_blueprint(st.session_state.blueprint) # Verify file was saved blueprint_path = os.path.join(self.data_path, 'blueprints', blueprint_file) if os.path.exists(blueprint_path): st.success(f"Blueprint saved: {blueprint_file}") st.write(f"File size: {os.path.getsize(blueprint_path)} bytes") else: st.error(f"Failed to save blueprint: File not found at {blueprint_path}") if st.session_state.book_content: content_file = self.data_manager.save_book_content(st.session_state.book_content) # Verify file was saved content_path = os.path.join(self.data_path, 'book_content', content_file) if os.path.exists(content_path): st.success(f"Book content saved: {content_file}") st.write(f"File size: {os.path.getsize(content_path)} bytes") else: st.error(f"Failed to save book content: File not found at {content_path}") except Exception as e: st.error(f"Error saving state: {e}") st.write(f"Current working directory: {os.getcwd()}") st.write(f"Data path: {self.data_path}") def load_latest_state(self): """Load latest state with verification""" try: # Load latest blueprint blueprint = self.data_manager.load_latest_blueprint() if blueprint: st.session_state.blueprint = blueprint st.success("Latest blueprint loaded") # Load latest book content content = self.data_manager.load_latest_book_content() if content: st.session_state.book_content = content st.success("Latest book content loaded") # Load manual content for part_idx in range(10): # Assuming max 10 parts for ch_idx in range(10): # Assuming max 10 chapters per part manual_content = self.data_manager.load_manual_content(part_idx, ch_idx) if manual_content: content_key = f"manual_content_p{part_idx}_ch{ch_idx}" st.session_state.manual_content[content_key] = manual_content except Exception as e: st.error(f"Error loading state: {e}") def copy_to_clipboard(self, text: str): """Copy text to clipboard using JavaScript""" js_code = f""" """ st.components.v1.html(js_code, height=50) def render_blueprint_editor(self): """Render the blueprint editor interface""" st.header("📝 Blueprint Editor") col1, col2 = st.columns([7, 3]) with col1: # Blueprint Editor edited_blueprint = st.text_area( "Edit Blueprint", value=st.session_state.blueprint, height=600, key="blueprint_editor" ) # Check if blueprint has changed if edited_blueprint != st.session_state.blueprint: st.session_state.blueprint = edited_blueprint st.session_state.structure_initialized = False with col2: st.subheader("Blueprint Controls") # Process Blueprint if st.button("Process Blueprint", help="Extract structure and guidelines"): try: with st.spinner("Processing blueprint..."): if 'writer' not in st.session_state: st.session_state.writer = SelfApiWriter() # Process blueprint result = st.session_state.writer.process_blueprint(st.session_state.blueprint) if result: st.session_state.book_content = { "book_info": result["book_info"], "introduction": "", "parts": [] } st.session_state.structure_initialized = True self.data_manager.save_blueprint(st.session_state.blueprint) st.success("Blueprint processed successfully!") else: st.error("Failed to process blueprint") except Exception as e: st.error(f"Error processing blueprint: {e}") # Save/Load Controls if st.button("Save Blueprint"): try: filename = self.data_manager.save_blueprint(st.session_state.blueprint) st.success(f"Blueprint saved as: {filename}") except Exception as e: st.error(f"Error saving blueprint: {e}") if st.button("Load Latest"): try: blueprint = self.data_manager.load_latest_blueprint() if blueprint: st.session_state.blueprint = blueprint st.session_state.structure_initialized = False st.success("Latest blueprint loaded!") st.experimental_rerun() except Exception as e: st.error(f"Error loading blueprint: {e}") if st.button("Reset to Default"): st.session_state.blueprint = self.default_blueprint st.session_state.structure_initialized = False st.experimental_rerun() # Show current structure if available if st.session_state.get('writer') and st.session_state.structure_initialized: st.divider() st.subheader("Current Structure") structure = st.session_state.writer.get_current_structure() if structure: st.markdown("### Book Info") st.json(structure["book_info"]) st.markdown("### Structure") st.json(structure["structure"]) with st.expander("Writing Guidelines"): st.json(structure["guidelines"]) def render_generator_interface(self): """Render the content generation interface""" st.header("⚙️ Content Generator") if not st.session_state.structure_initialized: st.warning("Please process the blueprint first in the Blueprint Editor tab.") return # Initialize writer if needed if 'writer' not in st.session_state: st.session_state.writer = SelfApiWriter() # Generation controls col1, col2 = st.columns([2, 1]) with col1: st.subheader("Generation Controls") # Introduction Generation intro_col1, intro_col2 = st.columns([3, 1]) with intro_col1: st.markdown("### Introduction") # Manual content for introduction manual_intro = st.text_area( "Pre-written content for introduction", value=st.session_state.manual_content.get('introduction', ''), height=200, key="manual_intro" ) # Additional prompt for introduction additional_intro_prompt = st.text_area( "Additional instructions or context for introduction", value=st.session_state.manual_content.get('intro_prompt', ''), height=100, key="intro_prompt", help="Add any specific instructions or additional context for the introduction" ) if manual_intro != st.session_state.manual_content.get('introduction', ''): st.session_state.manual_content['introduction'] = manual_intro self.data_manager.save_manual_content(-1, -1, manual_intro) if additional_intro_prompt != st.session_state.manual_content.get('intro_prompt', ''): st.session_state.manual_content['intro_prompt'] = additional_intro_prompt if st.session_state.book_content.get('introduction'): st.success("✓ Generated") with intro_col2: if st.button("Generate Introduction"): with st.spinner("Generating introduction..."): if manual_intro: st.session_state.writer.set_manual_content('introduction', manual_intro) intro_content = st.session_state.writer.write_introduction( additional_prompt=additional_intro_prompt ) st.session_state.book_content["introduction"] = intro_content self.save_current_state() st.success("Introduction generated!") # Parts and Chapters Generation structure = st.session_state.writer.get_current_structure() if structure: for part_idx, part in enumerate(structure["structure"]["parts"]): st.markdown(f"### Part {part_idx + 1}: {part['title']}") for ch_idx, ch_title in enumerate(part["chapters"]): ch_col1, ch_col2 = st.columns([3, 1]) with ch_col1: st.markdown(f"#### {ch_title}") # Manual content input for chapter content_key = f"manual_content_p{part_idx}_ch{ch_idx}" manual_content = st.text_area( "Pre-written content", value=st.session_state.manual_content.get(content_key, ''), height=200, key=content_key ) # Additional prompt for chapter prompt_key = f"prompt_p{part_idx}_ch{ch_idx}" additional_prompt = st.text_area( "Additional instructions or context", value=st.session_state.manual_content.get(prompt_key, ''), height=100, key=prompt_key, help="Add any specific instructions or additional context for this chapter" ) if manual_content != st.session_state.manual_content.get(content_key, ''): st.session_state.manual_content[content_key] = manual_content self.data_manager.save_manual_content(part_idx, ch_idx, manual_content) if additional_prompt != st.session_state.manual_content.get(prompt_key, ''): st.session_state.manual_content[prompt_key] = additional_prompt chapter_exists = ( len(st.session_state.book_content.get('parts', [])) > part_idx and len(st.session_state.book_content['parts'][part_idx].get('chapters', [])) > ch_idx and st.session_state.book_content['parts'][part_idx]['chapters'][ch_idx].get('content') ) if chapter_exists: st.success("✓ Generated") with ch_col2: if st.button(f"Generate", key=f"gen_{part_idx}_{ch_idx}"): with st.spinner(f"Generating {ch_title}..."): if manual_content: st.session_state.writer.set_manual_content( f"part_{part_idx}_chapter_{ch_idx}", manual_content ) chapter_content = st.session_state.writer.write_chapter( part_idx, ch_idx, additional_prompt=additional_prompt ) def render_content_preview(self): """Render the content preview interface""" st.header("📚 Content Preview") if not st.session_state.structure_initialized: st.warning("Please process the blueprint first in the Blueprint Editor tab.") return # Show current file status st.subheader("File Status") col1, col2 = st.columns(2) with col1: st.write("Blueprint Files:") blueprint_dir = os.path.join(self.data_path, 'blueprints') if os.path.exists(blueprint_dir): files = os.listdir(blueprint_dir) for f in files: st.write(f"- {f}") else: st.write("No blueprint directory found") with col2: st.write("Content Files:") content_dir = os.path.join(self.data_path, 'book_content') if os.path.exists(content_dir): files = os.listdir(content_dir) for f in files: st.write(f"- {f}") else: st.write("No content directory found") # Add export button if st.button("Export Book"): try: filepath = self.data_manager.export_markdown(st.session_state.book_content) with open(filepath, 'r') as f: markdown_content = f.read() st.download_button( label="Download Markdown", data=markdown_content, file_name="book_export.md", mime="text/markdown" ) st.success(f"Book exported to: {filepath}") except Exception as e: st.error(f"Error exporting book: {e}") # Show book info if st.session_state.book_content.get('book_info'): st.subheader("Book Information") st.json(st.session_state.book_content['book_info']) # Show introduction if st.session_state.book_content.get('introduction'): st.subheader("Introduction") with st.expander("View Introduction", expanded=True): st.markdown(st.session_state.book_content['introduction']) # Add copy button for introduction if st.button("Copy Introduction"): self.copy_to_clipboard(st.session_state.book_content['introduction']) # Show generated parts and chapters for part_idx, part in enumerate(st.session_state.book_content.get('parts', [])): st.subheader(f"Part {part_idx + 1}: {part['title']}") for ch_idx, chapter in enumerate(part.get('chapters', [])): if chapter.get('content'): with st.expander(f"Chapter: {chapter['title']}", expanded=False): st.markdown(chapter['content']) # Add copy button for chapter if st.button(f"Copy Chapter", key=f"copy_{part_idx}_{ch_idx}"): self.copy_to_clipboard(chapter['content']) def run(self): """Run the Streamlit application""" st.title("📚 AI Book Writer") # Main navigation tabs = ["Blueprint", "Generator", "Preview"] selected_tab = st.radio("Navigation", tabs, horizontal=True) st.session_state.current_tab = selected_tab st.divider() # Render appropriate content based on selected tab if selected_tab == "Blueprint": self.render_blueprint_editor() elif selected_tab == "Generator": self.render_generator_interface() else: self.render_content_preview() def main(): app = SelfApiApp() app.run() if __name__ == "__main__": main()