File size: 21,997 Bytes
1866509
7cb52d8
 
 
88e4af9
c03f854
 
7cb52d8
c03f854
7cb52d8
c03f854
 
 
 
 
 
 
1866509
 
 
7cb52d8
c03f854
 
1866509
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c03f854
 
 
 
 
88e4af9
c03f854
 
88e4af9
c03f854
 
 
 
 
d514e7b
c03f854
 
 
1866509
 
 
88e4af9
c03f854
 
 
 
88e4af9
c03f854
 
88e4af9
c03f854
 
 
 
88e4af9
c03f854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1866509
c03f854
 
 
1866509
 
 
 
 
 
 
d514e7b
c03f854
 
1866509
 
 
 
 
 
 
7cb52d8
d514e7b
c03f854
1866509
 
88e4af9
c03f854
1866509
88e4af9
c03f854
 
 
 
1866509
7cb52d8
c03f854
 
 
 
1866509
88e4af9
1866509
 
 
 
 
 
 
 
88e4af9
c03f854
88e4af9
1866509
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c03f854
 
 
 
 
 
 
 
 
 
 
 
 
804b8a9
88e4af9
c03f854
 
 
 
 
 
 
804b8a9
c03f854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1866509
 
 
 
 
 
 
f875ed2
 
 
 
 
 
 
 
 
 
1866509
 
 
 
f875ed2
 
 
c03f854
 
1866509
c03f854
 
 
1866509
 
f875ed2
 
 
c03f854
 
 
 
 
 
 
 
 
 
 
 
 
1866509
 
 
 
 
 
 
 
 
 
 
f875ed2
 
 
 
 
 
 
 
 
 
1866509
 
 
 
f875ed2
 
 
c03f854
 
 
 
 
 
 
1866509
c03f854
 
 
1866509
 
 
 
 
f875ed2
 
 
 
 
c03f854
 
 
 
 
 
 
 
 
1866509
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c03f854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1866509
c03f854
 
 
 
1866509
 
 
 
c03f854
 
 
 
 
 
 
 
 
 
 
 
1866509
c03f854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1866509
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# 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"""
        <script>
        function copyToClipboard() {{
            const text = {json.dumps(text)};
            navigator.clipboard.writeText(text)
                .then(() => alert('Copied to clipboard!'))
                .catch(err => alert('Failed to copy: ' + err));
        }}
        </script>
        <button onclick="copyToClipboard()">Copy to Clipboard</button>
        """
        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()