cryogenic22 commited on
Commit
1866509
·
verified ·
1 Parent(s): 0de9ac4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -26
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # File: app.py
2
 
3
  import streamlit as st
4
  import json
@@ -15,11 +15,30 @@ class SelfApiApp:
15
  layout="wide"
16
  )
17
 
18
- # Initialize data manager
19
- self.data_manager = DataManager()
 
20
 
21
  # Initialize session state
22
  self._initialize_session_state()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  def _initialize_session_state(self):
25
  """Initialize session state variables"""
@@ -38,6 +57,9 @@ class SelfApiApp:
38
 
39
  if 'structure_initialized' not in st.session_state:
40
  st.session_state.structure_initialized = False
 
 
 
41
 
42
  @property
43
  def default_blueprint(self):
@@ -101,45 +123,74 @@ Psychographic: Analytical minds seeking spiritual depth without the woo-woo
101
  - Links to both ancient wisdom and modern science"""
102
 
103
  def save_current_state(self):
104
- """Save current state to data directory"""
105
  try:
106
- # Save blueprint if it exists
107
  if st.session_state.blueprint:
108
  blueprint_file = self.data_manager.save_blueprint(st.session_state.blueprint)
109
- st.success(f"Blueprint saved: {blueprint_file}")
 
 
 
 
 
 
110
 
111
- # Save book content if it exists
112
  if st.session_state.book_content:
113
  content_file = self.data_manager.save_book_content(st.session_state.book_content)
114
- st.success(f"Book content saved: {content_file}")
115
-
116
- # Save individual chapters
117
- for part_idx, part in enumerate(st.session_state.book_content.get('parts', [])):
118
- for ch_idx, chapter in enumerate(part.get('chapters', [])):
119
- if chapter.get('content'):
120
- self.data_manager.save_chapter(part_idx, ch_idx, chapter)
121
 
122
  except Exception as e:
123
  st.error(f"Error saving state: {e}")
 
 
124
 
125
  def load_latest_state(self):
126
- """Load latest state from data directory"""
127
  try:
128
  # Load latest blueprint
129
  blueprint = self.data_manager.load_latest_blueprint()
130
  if blueprint:
131
  st.session_state.blueprint = blueprint
 
132
 
133
  # Load latest book content
134
  content = self.data_manager.load_latest_book_content()
135
  if content:
136
  st.session_state.book_content = content
137
-
138
- st.success("Latest state loaded successfully!")
139
 
 
 
 
 
 
 
 
 
140
  except Exception as e:
141
  st.error(f"Error loading state: {e}")
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  def render_blueprint_editor(self):
144
  """Render the blueprint editor interface"""
145
  st.header("📝 Blueprint Editor")
@@ -250,11 +301,25 @@ Psychographic: Analytical minds seeking spiritual depth without the woo-woo
250
  intro_col1, intro_col2 = st.columns([3, 1])
251
  with intro_col1:
252
  st.markdown("### Introduction")
 
 
 
 
 
 
 
 
 
 
 
253
  if st.session_state.book_content.get('introduction'):
254
  st.success("✓ Generated")
 
255
  with intro_col2:
256
  if st.button("Generate Introduction"):
257
  with st.spinner("Generating introduction..."):
 
 
258
  intro_content = st.session_state.writer.write_introduction()
259
  st.session_state.book_content["introduction"] = intro_content
260
  self.save_current_state()
@@ -269,7 +334,21 @@ Psychographic: Analytical minds seeking spiritual depth without the woo-woo
269
  for ch_idx, ch_title in enumerate(part["chapters"]):
270
  ch_col1, ch_col2 = st.columns([3, 1])
271
  with ch_col1:
272
- st.markdown(f"- {ch_title}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
  chapter_exists = (
274
  len(st.session_state.book_content.get('parts', [])) > part_idx and
275
  len(st.session_state.book_content['parts'][part_idx].get('chapters', [])) > ch_idx and
@@ -277,9 +356,16 @@ Psychographic: Analytical minds seeking spiritual depth without the woo-woo
277
  )
278
  if chapter_exists:
279
  st.success("✓ Generated")
 
280
  with ch_col2:
281
  if st.button(f"Generate", key=f"gen_{part_idx}_{ch_idx}"):
282
  with st.spinner(f"Generating {ch_title}..."):
 
 
 
 
 
 
283
  chapter_content = st.session_state.writer.write_chapter(part_idx, ch_idx)
284
 
285
  # Ensure part exists
@@ -310,6 +396,9 @@ Psychographic: Analytical minds seeking spiritual depth without the woo-woo
310
  if st.button("Generate All"):
311
  with st.spinner("Generating entire book..."):
312
  # Generate introduction
 
 
 
313
  intro_content = st.session_state.writer.write_introduction()
314
  st.session_state.book_content["introduction"] = intro_content
315
 
@@ -326,6 +415,15 @@ Psychographic: Analytical minds seeking spiritual depth without the woo-woo
326
 
327
  for ch_idx, ch_title in enumerate(part["chapters"]):
328
  with st.spinner(f"Generating {ch_title}..."):
 
 
 
 
 
 
 
 
 
329
  chapter_content = st.session_state.writer.write_chapter(part_idx, ch_idx)
330
 
331
  # Ensure chapter exists
@@ -362,10 +460,29 @@ Psychographic: Analytical minds seeking spiritual depth without the woo-woo
362
  st.warning("Please process the blueprint first in the Blueprint Editor tab.")
363
  return
364
 
365
- if not st.session_state.book_content.get('introduction') and not st.session_state.book_content.get('parts'):
366
- st.info("No content generated yet. Use the Generator tab to create content.")
367
- return
368
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
369
  # Add export button
370
  if st.button("Export Book"):
371
  try:
@@ -388,11 +505,15 @@ Psychographic: Analytical minds seeking spiritual depth without the woo-woo
388
  st.subheader("Book Information")
389
  st.json(st.session_state.book_content['book_info'])
390
 
391
- # Show introduction
392
  if st.session_state.book_content.get('introduction'):
393
  st.subheader("Introduction")
394
  with st.expander("View Introduction", expanded=True):
395
  st.markdown(st.session_state.book_content['introduction'])
 
 
 
 
396
 
397
  # Show generated parts and chapters
398
  for part_idx, part in enumerate(st.session_state.book_content.get('parts', [])):
@@ -405,8 +526,7 @@ Psychographic: Analytical minds seeking spiritual depth without the woo-woo
405
 
406
  # Add copy button for chapter
407
  if st.button(f"Copy Chapter", key=f"copy_{part_idx}_{ch_idx}"):
408
- st.write("Chapter content copied to clipboard!")
409
- st.toast("Chapter copied!")
410
 
411
  def run(self):
412
  """Run the Streamlit application"""
@@ -432,4 +552,4 @@ def main():
432
  app.run()
433
 
434
  if __name__ == "__main__":
435
- main()
 
1
+ # app.py
2
 
3
  import streamlit as st
4
  import json
 
15
  layout="wide"
16
  )
17
 
18
+ # Initialize data manager with explicit path
19
+ self.data_path = os.path.join(os.getcwd(), 'data')
20
+ self.data_manager = DataManager(self.data_path)
21
 
22
  # Initialize session state
23
  self._initialize_session_state()
24
+
25
+ # Create necessary directories
26
+ self._ensure_directories()
27
+
28
+ def _ensure_directories(self):
29
+ """Create necessary directories"""
30
+ directories = [
31
+ self.data_path,
32
+ os.path.join(self.data_path, 'blueprints'),
33
+ os.path.join(self.data_path, 'book_content'),
34
+ os.path.join(self.data_path, 'exports'),
35
+ os.path.join(self.data_path, 'chapters'),
36
+ os.path.join(self.data_path, 'manual_content')
37
+ ]
38
+
39
+ for dir_path in directories:
40
+ os.makedirs(dir_path, exist_ok=True)
41
+ st.write(f"Directory exists: {dir_path} - {os.path.exists(dir_path)}")
42
 
43
  def _initialize_session_state(self):
44
  """Initialize session state variables"""
 
57
 
58
  if 'structure_initialized' not in st.session_state:
59
  st.session_state.structure_initialized = False
60
+
61
+ if 'manual_content' not in st.session_state:
62
+ st.session_state.manual_content = {}
63
 
64
  @property
65
  def default_blueprint(self):
 
123
  - Links to both ancient wisdom and modern science"""
124
 
125
  def save_current_state(self):
126
+ """Save current state with verification"""
127
  try:
 
128
  if st.session_state.blueprint:
129
  blueprint_file = self.data_manager.save_blueprint(st.session_state.blueprint)
130
+ # Verify file was saved
131
+ blueprint_path = os.path.join(self.data_path, 'blueprints', blueprint_file)
132
+ if os.path.exists(blueprint_path):
133
+ st.success(f"Blueprint saved: {blueprint_file}")
134
+ st.write(f"File size: {os.path.getsize(blueprint_path)} bytes")
135
+ else:
136
+ st.error(f"Failed to save blueprint: File not found at {blueprint_path}")
137
 
 
138
  if st.session_state.book_content:
139
  content_file = self.data_manager.save_book_content(st.session_state.book_content)
140
+ # Verify file was saved
141
+ content_path = os.path.join(self.data_path, 'book_content', content_file)
142
+ if os.path.exists(content_path):
143
+ st.success(f"Book content saved: {content_file}")
144
+ st.write(f"File size: {os.path.getsize(content_path)} bytes")
145
+ else:
146
+ st.error(f"Failed to save book content: File not found at {content_path}")
147
 
148
  except Exception as e:
149
  st.error(f"Error saving state: {e}")
150
+ st.write(f"Current working directory: {os.getcwd()}")
151
+ st.write(f"Data path: {self.data_path}")
152
 
153
  def load_latest_state(self):
154
+ """Load latest state with verification"""
155
  try:
156
  # Load latest blueprint
157
  blueprint = self.data_manager.load_latest_blueprint()
158
  if blueprint:
159
  st.session_state.blueprint = blueprint
160
+ st.success("Latest blueprint loaded")
161
 
162
  # Load latest book content
163
  content = self.data_manager.load_latest_book_content()
164
  if content:
165
  st.session_state.book_content = content
166
+ st.success("Latest book content loaded")
 
167
 
168
+ # Load manual content
169
+ for part_idx in range(10): # Assuming max 10 parts
170
+ for ch_idx in range(10): # Assuming max 10 chapters per part
171
+ manual_content = self.data_manager.load_manual_content(part_idx, ch_idx)
172
+ if manual_content:
173
+ content_key = f"manual_content_p{part_idx}_ch{ch_idx}"
174
+ st.session_state.manual_content[content_key] = manual_content
175
+
176
  except Exception as e:
177
  st.error(f"Error loading state: {e}")
178
 
179
+ def copy_to_clipboard(self, text: str):
180
+ """Copy text to clipboard using JavaScript"""
181
+ js_code = f"""
182
+ <script>
183
+ function copyToClipboard() {{
184
+ const text = {json.dumps(text)};
185
+ navigator.clipboard.writeText(text)
186
+ .then(() => alert('Copied to clipboard!'))
187
+ .catch(err => alert('Failed to copy: ' + err));
188
+ }}
189
+ </script>
190
+ <button onclick="copyToClipboard()">Copy to Clipboard</button>
191
+ """
192
+ st.components.v1.html(js_code, height=50)
193
+
194
  def render_blueprint_editor(self):
195
  """Render the blueprint editor interface"""
196
  st.header("📝 Blueprint Editor")
 
301
  intro_col1, intro_col2 = st.columns([3, 1])
302
  with intro_col1:
303
  st.markdown("### Introduction")
304
+ # Manual content for introduction
305
+ manual_intro = st.text_area(
306
+ "Pre-written content for introduction",
307
+ value=st.session_state.manual_content.get('introduction', ''),
308
+ height=200,
309
+ key="manual_intro"
310
+ )
311
+ if manual_intro != st.session_state.manual_content.get('introduction', ''):
312
+ st.session_state.manual_content['introduction'] = manual_intro
313
+ self.data_manager.save_manual_content(-1, -1, manual_intro)
314
+
315
  if st.session_state.book_content.get('introduction'):
316
  st.success("✓ Generated")
317
+
318
  with intro_col2:
319
  if st.button("Generate Introduction"):
320
  with st.spinner("Generating introduction..."):
321
+ if manual_intro:
322
+ st.session_state.writer.set_manual_content('introduction', manual_intro)
323
  intro_content = st.session_state.writer.write_introduction()
324
  st.session_state.book_content["introduction"] = intro_content
325
  self.save_current_state()
 
334
  for ch_idx, ch_title in enumerate(part["chapters"]):
335
  ch_col1, ch_col2 = st.columns([3, 1])
336
  with ch_col1:
337
+ st.markdown(f"#### {ch_title}")
338
+
339
+ # Manual content input for chapter
340
+ content_key = f"manual_content_p{part_idx}_ch{ch_idx}"
341
+ manual_content = st.text_area(
342
+ "Pre-written content",
343
+ value=st.session_state.manual_content.get(content_key, ''),
344
+ height=200,
345
+ key=content_key
346
+ )
347
+
348
+ if manual_content != st.session_state.manual_content.get(content_key, ''):
349
+ st.session_state.manual_content[content_key] = manual_content
350
+ self.data_manager.save_manual_content(part_idx, ch_idx, manual_content)
351
+
352
  chapter_exists = (
353
  len(st.session_state.book_content.get('parts', [])) > part_idx and
354
  len(st.session_state.book_content['parts'][part_idx].get('chapters', [])) > ch_idx and
 
356
  )
357
  if chapter_exists:
358
  st.success("✓ Generated")
359
+
360
  with ch_col2:
361
  if st.button(f"Generate", key=f"gen_{part_idx}_{ch_idx}"):
362
  with st.spinner(f"Generating {ch_title}..."):
363
+ if manual_content:
364
+ st.session_state.writer.set_manual_content(
365
+ f"part_{part_idx}_chapter_{ch_idx}",
366
+ manual_content
367
+ )
368
+
369
  chapter_content = st.session_state.writer.write_chapter(part_idx, ch_idx)
370
 
371
  # Ensure part exists
 
396
  if st.button("Generate All"):
397
  with st.spinner("Generating entire book..."):
398
  # Generate introduction
399
+ manual_intro = st.session_state.manual_content.get('introduction', '')
400
+ if manual_intro:
401
+ st.session_state.writer.set_manual_content('introduction', manual_intro)
402
  intro_content = st.session_state.writer.write_introduction()
403
  st.session_state.book_content["introduction"] = intro_content
404
 
 
415
 
416
  for ch_idx, ch_title in enumerate(part["chapters"]):
417
  with st.spinner(f"Generating {ch_title}..."):
418
+ content_key = f"manual_content_p{part_idx}_ch{ch_idx}"
419
+ manual_content = st.session_state.manual_content.get(content_key, '')
420
+
421
+ if manual_content:
422
+ st.session_state.writer.set_manual_content(
423
+ f"part_{part_idx}_chapter_{ch_idx}",
424
+ manual_content
425
+ )
426
+
427
  chapter_content = st.session_state.writer.write_chapter(part_idx, ch_idx)
428
 
429
  # Ensure chapter exists
 
460
  st.warning("Please process the blueprint first in the Blueprint Editor tab.")
461
  return
462
 
463
+ # Show current file status
464
+ st.subheader("File Status")
465
+ col1, col2 = st.columns(2)
466
+ with col1:
467
+ st.write("Blueprint Files:")
468
+ blueprint_dir = os.path.join(self.data_path, 'blueprints')
469
+ if os.path.exists(blueprint_dir):
470
+ files = os.listdir(blueprint_dir)
471
+ for f in files:
472
+ st.write(f"- {f}")
473
+ else:
474
+ st.write("No blueprint directory found")
475
+
476
+ with col2:
477
+ st.write("Content Files:")
478
+ content_dir = os.path.join(self.data_path, 'book_content')
479
+ if os.path.exists(content_dir):
480
+ files = os.listdir(content_dir)
481
+ for f in files:
482
+ st.write(f"- {f}")
483
+ else:
484
+ st.write("No content directory found")
485
+
486
  # Add export button
487
  if st.button("Export Book"):
488
  try:
 
505
  st.subheader("Book Information")
506
  st.json(st.session_state.book_content['book_info'])
507
 
508
+ # Show introduction
509
  if st.session_state.book_content.get('introduction'):
510
  st.subheader("Introduction")
511
  with st.expander("View Introduction", expanded=True):
512
  st.markdown(st.session_state.book_content['introduction'])
513
+
514
+ # Add copy button for introduction
515
+ if st.button("Copy Introduction"):
516
+ self.copy_to_clipboard(st.session_state.book_content['introduction'])
517
 
518
  # Show generated parts and chapters
519
  for part_idx, part in enumerate(st.session_state.book_content.get('parts', [])):
 
526
 
527
  # Add copy button for chapter
528
  if st.button(f"Copy Chapter", key=f"copy_{part_idx}_{ch_idx}"):
529
+ self.copy_to_clipboard(chapter['content'])
 
530
 
531
  def run(self):
532
  """Run the Streamlit application"""
 
552
  app.run()
553
 
554
  if __name__ == "__main__":
555
+ main()