cryogenic22 commited on
Commit
5177798
·
verified ·
1 Parent(s): 65cf9e6

Update selfapi_writer.py

Browse files
Files changed (1) hide show
  1. selfapi_writer.py +107 -94
selfapi_writer.py CHANGED
@@ -4,7 +4,7 @@ import anthropic
4
  import streamlit as st
5
  import json
6
  import os
7
- from typing import Dict, Any
8
 
9
  class SelfApiWriter:
10
  def __init__(self):
@@ -17,75 +17,58 @@ class SelfApiWriter:
17
 
18
  if not api_key:
19
  raise ValueError("ANTHROPIC_API_KEY not found in environment variables or Streamlit secrets.")
20
-
21
- # Print debug info (remove in production)
22
- print("Environment variables available:", [k for k in os.environ.keys()])
23
- print("API key found:", bool(api_key))
24
 
25
- self.client = anthropic.Anthropic(
26
- api_key=api_key
27
- )
28
  self.context = {}
29
- self.book_structure = {
30
- "introduction": "System Requirements: A Human's Guide to Being Human",
31
- "parts": [
32
- {
33
- "title": "The Human Input/Output System",
34
- "chapters": [
35
- "Rate Limiting Your Reality",
36
- "Debugging Your Attention Span",
37
- "The Mindfulness Microservice"
38
- ]
39
- },
40
- {
41
- "title": "Your Internal Neural Network",
42
- "chapters": [
43
- "Training Your Gut Algorithm",
44
- "The Wisdom Cache",
45
- "Pattern Recognition Beyond Logic"
46
- ]
47
- },
48
- {
49
- "title": "The Source Code of Being",
50
- "chapters": [
51
- "Quantum Mechanics of Consciousness",
52
- "The Purpose Protocol",
53
- "Refactoring Your Reality"
54
- ]
55
- },
56
- {
57
- "title": "The Universal Runtime Environment",
58
- "chapters": [
59
- "Distributed Consciousness Systems",
60
- "The Empathy Protocol",
61
- "Scaling Your Impact"
62
- ]
63
- }
64
- ]
65
- }
66
 
67
  def process_blueprint(self, blueprint: str) -> Dict[str, Any]:
68
- """Process updated blueprint to generate new book structure"""
69
  try:
70
- system_prompt = """You are an expert book planner analyzing a blueprint for 'Self.api: A Modern Spiritual Operating System'.
71
- Extract and organize the book structure from the provided blueprint.
 
 
 
 
 
 
 
 
 
 
72
  Return a JSON structure with the following format:
73
  {
74
- "introduction": "Introduction title",
75
- "parts": [
76
- {
77
- "title": "Part title",
78
- "chapters": ["Chapter 1 title", "Chapter 2 title", ...]
79
- }
80
- ]
81
- }
82
- Ensure all sections from the blueprint are included and properly organized."""
83
-
84
- prompt = f"""Analyze this book blueprint and extract the structure:
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  {blueprint}
87
 
88
- Return only the JSON structure with no additional text."""
89
 
90
  response = self.client.messages.create(
91
  model="claude-3-sonnet-20240229",
@@ -95,31 +78,45 @@ class SelfApiWriter:
95
  messages=[{"role": "user", "content": prompt}]
96
  )
97
 
98
- new_structure = json.loads(response.content[0].text)
99
- self.book_structure = new_structure
100
- return new_structure
 
 
 
 
 
 
101
 
102
  except Exception as e:
103
  st.error(f"Error processing blueprint: {str(e)}")
104
- return self.book_structure # Return existing structure on error
105
 
106
  def write_introduction(self) -> str:
107
- """Generate the book's introduction"""
 
 
 
108
  try:
109
- system_prompt = """You are writing the introduction to 'Self.api: A Modern Spiritual Operating System'.
110
- The introduction should hook tech professionals by speaking their language while introducing the book's core premise.
111
- Include the author's journey from debugging code to debugging consciousness."""
 
 
 
 
 
 
112
 
113
- intro_prompt = """Write the introduction "System Requirements: A Human's Guide to Being Human"
114
 
115
- Key elements to include:
116
- 1. Opening hook: "In a world where we can Google anything except our own purpose..."
117
- 2. Author's personal journey
118
- 3. The core premise of viewing spirituality through an API/systems lens
119
- 4. Overview of the book's structure and approach
120
- 5. What readers will gain from this "operating manual for the human spirit"
121
 
122
- Make it compelling, technical yet accessible, and set the tone for the entire book."""
123
 
124
  response = self.client.messages.create(
125
  model="claude-3-sonnet-20240229",
@@ -138,35 +135,40 @@ class SelfApiWriter:
138
  return f"Error generating introduction: {str(e)}"
139
 
140
  def write_chapter(self, part_idx: int, chapter_idx: int) -> str:
141
- """Generate a specific chapter"""
 
 
 
142
  try:
143
  part = self.book_structure["parts"][part_idx]
144
  chapter_title = part["chapters"][chapter_idx]
145
  part_title = part["title"]
146
  previous_chapter = self.context.get(f'part_{part_idx}_chapter_{chapter_idx-1}', '')
147
 
148
- system_prompt = """You are writing 'Self.api: A Modern Spiritual Operating System', a book that bridges technology and spirituality for tech professionals.
149
- Follow these guidelines:
150
- - Use API and technical metaphors naturally and accurately
151
- - Maintain a voice that's witty but wise (Douglas Adams meets Deepak Chopra)
152
- - Structure each chapter with: System Log (personal story), Documentation (teaching), Implementation Guide (practical steps)
153
- - Balance is 60% practical, 40% philosophical
154
- - Include 3 "aha" moments and 2-3 quotable passages
155
- - Ensure every concept links to both ancient wisdom and modern science
156
- - Write for analytical minds seeking spiritual depth without woo-woo
157
- - Include practical exercises every few pages"""
 
 
 
158
 
159
  chapter_prompt = f"""
160
  Write Chapter: "{chapter_title}" in Part {part_idx + 1}: "{part_title}"
161
 
162
  Previous Chapter Context: {previous_chapter[:1000] if previous_chapter else 'Starting new part'}
163
 
164
- Requirements:
165
- 1. Open with a compelling "System Log" that relates to {chapter_title}
166
- 2. Use technically accurate API/programming metaphors
167
- 3. Include at least two practical exercises
168
- 4. End with clear implementation steps
169
- 5. Maintain the tech-spiritual bridge throughout
170
 
171
  Begin writing the complete chapter now."""
172
 
@@ -184,4 +186,15 @@ class SelfApiWriter:
184
 
185
  except Exception as e:
186
  st.error(f"Error generating chapter: {str(e)}")
187
- return f"Error generating chapter {chapter_title}: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
4
  import streamlit as st
5
  import json
6
  import os
7
+ from typing import Dict, Any, Optional
8
 
9
  class SelfApiWriter:
10
  def __init__(self):
 
17
 
18
  if not api_key:
19
  raise ValueError("ANTHROPIC_API_KEY not found in environment variables or Streamlit secrets.")
 
 
 
 
20
 
21
+ self.client = anthropic.Anthropic(api_key=api_key)
 
 
22
  self.context = {}
23
+ self.book_structure = None
24
+ self.writing_guidelines = None
25
+ self.initialized = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  def process_blueprint(self, blueprint: str) -> Dict[str, Any]:
28
+ """Process blueprint to extract complete writing guidelines and structure"""
29
  try:
30
+ system_prompt = """You are an expert book planner analyzing a blueprint.
31
+ Extract ALL relevant information and return it in a structured format.
32
+ Include:
33
+ 1. Book title and high-level information
34
+ 2. Complete structure (introduction, parts, chapters)
35
+ 3. All writing style guidelines
36
+ 4. Content requirements and constraints
37
+ 5. Target audience details
38
+ 6. Chapter structure requirements
39
+ 7. Tone and voice requirements
40
+ 8. Any other relevant guidelines or requirements
41
+
42
  Return a JSON structure with the following format:
43
  {
44
+ "book_info": {
45
+ "title": "Book title",
46
+ "vision": "Core vision/purpose",
47
+ "target_audience": "Detailed audience description"
48
+ },
49
+ "structure": {
50
+ "introduction": "Introduction title",
51
+ "parts": [
52
+ {
53
+ "title": "Part title",
54
+ "chapters": ["Chapter 1 title", "Chapter 2 title", ...]
55
+ }
56
+ ]
57
+ },
58
+ "guidelines": {
59
+ "style": "Writing style description",
60
+ "tone": "Tone requirements",
61
+ "chapter_structure": ["Required chapter components"],
62
+ "content_requirements": ["Specific content requirements"],
63
+ "practical_elements": ["Required practical elements"]
64
+ }
65
+ }"""
66
+
67
+ prompt = f"""Analyze this book blueprint and extract ALL information:
68
 
69
  {blueprint}
70
 
71
+ Return only the JSON structure without any additional text."""
72
 
73
  response = self.client.messages.create(
74
  model="claude-3-sonnet-20240229",
 
78
  messages=[{"role": "user", "content": prompt}]
79
  )
80
 
81
+ extracted_info = json.loads(response.content[0].text)
82
+
83
+ # Store extracted information
84
+ self.book_info = extracted_info["book_info"]
85
+ self.book_structure = extracted_info["structure"]
86
+ self.writing_guidelines = extracted_info["guidelines"]
87
+ self.initialized = True
88
+
89
+ return extracted_info
90
 
91
  except Exception as e:
92
  st.error(f"Error processing blueprint: {str(e)}")
93
+ return None
94
 
95
  def write_introduction(self) -> str:
96
+ """Generate the book's introduction based on extracted guidelines"""
97
+ if not self.initialized:
98
+ raise ValueError("Writer not initialized. Process blueprint first.")
99
+
100
  try:
101
+ system_prompt = f"""You are writing the introduction for '{self.book_info["title"]}'
102
+ Core Vision: {self.book_info["vision"]}
103
+ Target Audience: {self.book_info["target_audience"]}
104
+
105
+ Writing Style: {self.writing_guidelines["style"]}
106
+ Tone: {self.writing_guidelines["tone"]}
107
+
108
+ Content Requirements:
109
+ {', '.join(self.writing_guidelines["content_requirements"])}"""
110
 
111
+ intro_prompt = f"""Write the introduction: "{self.book_structure['introduction']}"
112
 
113
+ Create an engaging opening that:
114
+ 1. Introduces the book's core concept
115
+ 2. Speaks directly to the target audience
116
+ 3. Outlines the book's approach and structure
117
+ 4. Sets the tone for the entire book
 
118
 
119
+ Follow ALL provided guidelines for style, tone, and content."""
120
 
121
  response = self.client.messages.create(
122
  model="claude-3-sonnet-20240229",
 
135
  return f"Error generating introduction: {str(e)}"
136
 
137
  def write_chapter(self, part_idx: int, chapter_idx: int) -> str:
138
+ """Generate a chapter using extracted guidelines"""
139
+ if not self.initialized:
140
+ raise ValueError("Writer not initialized. Process blueprint first.")
141
+
142
  try:
143
  part = self.book_structure["parts"][part_idx]
144
  chapter_title = part["chapters"][chapter_idx]
145
  part_title = part["title"]
146
  previous_chapter = self.context.get(f'part_{part_idx}_chapter_{chapter_idx-1}', '')
147
 
148
+ system_prompt = f"""You are writing '{self.book_info["title"]}'
149
+ Target Audience: {self.book_info["target_audience"]}
150
+ Writing Style: {self.writing_guidelines["style"]}
151
+ Tone: {self.writing_guidelines["tone"]}
152
+
153
+ Chapter Structure Requirements:
154
+ {', '.join(self.writing_guidelines["chapter_structure"])}
155
+
156
+ Content Requirements:
157
+ {', '.join(self.writing_guidelines["content_requirements"])}
158
+
159
+ Practical Elements to Include:
160
+ {', '.join(self.writing_guidelines["practical_elements"])}"""
161
 
162
  chapter_prompt = f"""
163
  Write Chapter: "{chapter_title}" in Part {part_idx + 1}: "{part_title}"
164
 
165
  Previous Chapter Context: {previous_chapter[:1000] if previous_chapter else 'Starting new part'}
166
 
167
+ Follow ALL provided guidelines for:
168
+ 1. Structure and organization
169
+ 2. Style and tone
170
+ 3. Practical elements and exercises
171
+ 4. Content depth and requirements
 
172
 
173
  Begin writing the complete chapter now."""
174
 
 
186
 
187
  except Exception as e:
188
  st.error(f"Error generating chapter: {str(e)}")
189
+ return f"Error generating chapter {chapter_title}: {str(e)}"
190
+
191
+ def get_current_structure(self) -> Optional[Dict[str, Any]]:
192
+ """Get current book structure and guidelines"""
193
+ if not self.initialized:
194
+ return None
195
+
196
+ return {
197
+ "book_info": self.book_info,
198
+ "structure": self.book_structure,
199
+ "guidelines": self.writing_guidelines
200
+ }