Spaces:
Build error
Build error
Update selfapi_writer.py
Browse files- 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 |
-
|
| 31 |
-
|
| 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
|
| 69 |
try:
|
| 70 |
-
system_prompt = """You are an expert book planner analyzing a blueprint
|
| 71 |
-
Extract
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
Return a JSON structure with the following format:
|
| 73 |
{
|
| 74 |
-
"
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
{blueprint}
|
| 87 |
|
| 88 |
-
Return only the JSON structure
|
| 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 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
except Exception as e:
|
| 103 |
st.error(f"Error processing blueprint: {str(e)}")
|
| 104 |
-
return
|
| 105 |
|
| 106 |
def write_introduction(self) -> str:
|
| 107 |
-
"""Generate the book's introduction"""
|
|
|
|
|
|
|
|
|
|
| 108 |
try:
|
| 109 |
-
system_prompt = """You are writing the introduction
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
-
intro_prompt = """Write the introduction
|
| 114 |
|
| 115 |
-
|
| 116 |
-
1.
|
| 117 |
-
2.
|
| 118 |
-
3.
|
| 119 |
-
4.
|
| 120 |
-
5. What readers will gain from this "operating manual for the human spirit"
|
| 121 |
|
| 122 |
-
|
| 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
|
|
|
|
|
|
|
|
|
|
| 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 '
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 165 |
-
1.
|
| 166 |
-
2.
|
| 167 |
-
3.
|
| 168 |
-
4.
|
| 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 |
+
}
|