Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -37,6 +37,42 @@ load_dotenv()
|
|
37 |
PIXABAY_API_KEY = os.getenv('PIXABAY_API_KEY')
|
38 |
|
39 |
class EnhancedBookGenerator:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
def __init__(self):
|
41 |
self.initialize_models()
|
42 |
self.initialize_quality_metrics()
|
@@ -134,12 +170,27 @@ class EnhancedBookGenerator:
|
|
134 |
}
|
135 |
|
136 |
def generate_chapter_content(self, chapter_info: Dict) -> str:
|
137 |
-
"""Generate chapter content
|
138 |
try:
|
139 |
-
prompt
|
140 |
-
|
141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
return enhanced_content
|
|
|
143 |
except Exception as e:
|
144 |
st.error(f"Error generating chapter: {str(e)}")
|
145 |
return f"Error generating chapter {chapter_info['title']}"
|
@@ -176,8 +227,11 @@ class EnhancedBookGenerator:
|
|
176 |
|
177 |
return ' '.join(content_parts)
|
178 |
|
179 |
-
def _enhance_content(self, content: str, facts: List[str]) -> str:
|
180 |
"""Enhance content with facts and structure"""
|
|
|
|
|
|
|
181 |
# Clean text
|
182 |
content = re.sub(r'\s+', ' ', content).strip()
|
183 |
|
@@ -192,8 +246,8 @@ class EnhancedBookGenerator:
|
|
192 |
for i, sentence in enumerate(sentences):
|
193 |
current_section.append(sentence)
|
194 |
|
195 |
-
# Add a fact every few sentences
|
196 |
-
if i % 5 == 0 and fact_index < len(facts):
|
197 |
current_section.append(f"\nInteresting fact: {facts[fact_index]}\n")
|
198 |
fact_index += 1
|
199 |
|
@@ -371,9 +425,20 @@ def main():
|
|
371 |
display_preview_download()
|
372 |
|
373 |
def display_book_settings(templates):
|
374 |
-
"""Display the book settings page"""
|
375 |
st.header("Book Settings")
|
376 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
377 |
col1, col2 = st.columns(2)
|
378 |
|
379 |
with col1:
|
@@ -408,19 +473,32 @@ def display_book_settings(templates):
|
|
408 |
key="words_per_chapter_input"
|
409 |
)
|
410 |
|
411 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
412 |
st.subheader("Chapter Titles")
|
413 |
-
|
414 |
cols = st.columns(3)
|
415 |
for i in range(num_chapters):
|
416 |
with cols[i % 3]:
|
417 |
-
default_title = templates[template]["example_titles"][i % len(templates[template]["example_titles"])]
|
418 |
title = st.text_input(
|
419 |
f"Chapter {i+1}",
|
420 |
-
value=
|
421 |
key=f"chapter_title_{i}"
|
422 |
)
|
423 |
-
|
424 |
|
425 |
if st.button("Save Settings", key="save_settings_button"):
|
426 |
st.session_state.book_settings = {
|
@@ -429,11 +507,31 @@ def display_book_settings(templates):
|
|
429 |
"genre": genre,
|
430 |
"num_chapters": num_chapters,
|
431 |
"words_per_chapter": words_per_chapter,
|
432 |
-
"chapter_titles":
|
433 |
-
"total_words": num_chapters * words_per_chapter
|
|
|
434 |
}
|
435 |
st.success("✅ Settings saved successfully! You can now proceed to Generate Content.")
|
436 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
437 |
def display_generate_content():
|
438 |
"""Display the content generation page"""
|
439 |
if not st.session_state.book_settings:
|
|
|
37 |
PIXABAY_API_KEY = os.getenv('PIXABAY_API_KEY')
|
38 |
|
39 |
class EnhancedBookGenerator:
|
40 |
+
def _enhance_content(self, content: str, facts: Optional[List[str]] = None) -> str:
|
41 |
+
"""Enhance content with facts and structure"""
|
42 |
+
if facts is None:
|
43 |
+
facts = []
|
44 |
+
|
45 |
+
# Clean text
|
46 |
+
content = re.sub(r'\s+', ' ', content).strip()
|
47 |
+
|
48 |
+
# Process with NLTK
|
49 |
+
sentences = sent_tokenize(content)
|
50 |
+
|
51 |
+
# Add structure and facts
|
52 |
+
structured_content = []
|
53 |
+
current_section = []
|
54 |
+
fact_index = 0
|
55 |
+
|
56 |
+
for i, sentence in enumerate(sentences):
|
57 |
+
current_section.append(sentence)
|
58 |
+
|
59 |
+
# Add a fact every few sentences if available
|
60 |
+
if facts and i % 5 == 0 and fact_index < len(facts):
|
61 |
+
current_section.append(f"\nInteresting fact: {facts[fact_index]}\n")
|
62 |
+
fact_index += 1
|
63 |
+
|
64 |
+
if (i + 1) % 5 == 0:
|
65 |
+
section_text = ' '.join(current_section)
|
66 |
+
if self.summarizer:
|
67 |
+
heading = self.summarizer(section_text, max_length=10, min_length=5)[0]['summary_text']
|
68 |
+
structured_content.append(f"\n## {heading.title()}\n")
|
69 |
+
structured_content.append(section_text)
|
70 |
+
current_section = []
|
71 |
+
|
72 |
+
if current_section:
|
73 |
+
structured_content.append(' '.join(current_section))
|
74 |
+
|
75 |
+
return '\n'.join(structured_content)
|
76 |
def __init__(self):
|
77 |
self.initialize_models()
|
78 |
self.initialize_quality_metrics()
|
|
|
170 |
}
|
171 |
|
172 |
def generate_chapter_content(self, chapter_info: Dict) -> str:
|
173 |
+
"""Generate chapter content incorporating user prompt"""
|
174 |
try:
|
175 |
+
# Include user prompt in chapter generation
|
176 |
+
base_prompt = self._create_chapter_prompt(chapter_info)
|
177 |
+
user_prompt = st.session_state.book_settings.get('user_prompt', '')
|
178 |
+
|
179 |
+
if user_prompt:
|
180 |
+
enhanced_prompt = f"""
|
181 |
+
User's book vision: {user_prompt}
|
182 |
+
|
183 |
+
Based on this vision, write a chapter that fits the following:
|
184 |
+
{base_prompt}
|
185 |
+
"""
|
186 |
+
else:
|
187 |
+
enhanced_prompt = base_prompt
|
188 |
+
|
189 |
+
content = self._generate_raw_content(enhanced_prompt, chapter_info['word_count'])
|
190 |
+
# Pass empty list for facts if none available
|
191 |
+
enhanced_content = self._enhance_content(content, facts=[])
|
192 |
return enhanced_content
|
193 |
+
|
194 |
except Exception as e:
|
195 |
st.error(f"Error generating chapter: {str(e)}")
|
196 |
return f"Error generating chapter {chapter_info['title']}"
|
|
|
227 |
|
228 |
return ' '.join(content_parts)
|
229 |
|
230 |
+
def _enhance_content(self, content: str, facts: Optional[List[str]] = None) -> str:
|
231 |
"""Enhance content with facts and structure"""
|
232 |
+
if facts is None:
|
233 |
+
facts = []
|
234 |
+
|
235 |
# Clean text
|
236 |
content = re.sub(r'\s+', ' ', content).strip()
|
237 |
|
|
|
246 |
for i, sentence in enumerate(sentences):
|
247 |
current_section.append(sentence)
|
248 |
|
249 |
+
# Add a fact every few sentences if available
|
250 |
+
if facts and i % 5 == 0 and fact_index < len(facts):
|
251 |
current_section.append(f"\nInteresting fact: {facts[fact_index]}\n")
|
252 |
fact_index += 1
|
253 |
|
|
|
425 |
display_preview_download()
|
426 |
|
427 |
def display_book_settings(templates):
|
428 |
+
"""Display the book settings page with enhanced user prompts"""
|
429 |
st.header("Book Settings")
|
430 |
|
431 |
+
# User's creative prompt
|
432 |
+
st.subheader("Tell us about your book idea")
|
433 |
+
user_prompt = st.text_area(
|
434 |
+
"Describe your book idea, themes, feelings, and key elements you want to include",
|
435 |
+
value=st.session_state.get('user_prompt', ''),
|
436 |
+
height=150,
|
437 |
+
help="Be as detailed as possible. Include themes, mood, character ideas, plot elements, or any other aspects you want in your book.",
|
438 |
+
placeholder="Example: I want to write a book about a journey of self-discovery in a dystopian world. The main themes should include hope, resilience, and the power of human connection..."
|
439 |
+
)
|
440 |
+
st.session_state.user_prompt = user_prompt
|
441 |
+
|
442 |
col1, col2 = st.columns(2)
|
443 |
|
444 |
with col1:
|
|
|
473 |
key="words_per_chapter_input"
|
474 |
)
|
475 |
|
476 |
+
# Generate intelligent chapter titles based on user prompt
|
477 |
+
if user_prompt and st.button("Generate Chapter Titles"):
|
478 |
+
with st.spinner("Generating chapter titles based on your prompt..."):
|
479 |
+
chapter_titles = generate_intelligent_chapter_titles(
|
480 |
+
user_prompt,
|
481 |
+
num_chapters,
|
482 |
+
template,
|
483 |
+
genre
|
484 |
+
)
|
485 |
+
st.session_state.generated_chapter_titles = chapter_titles
|
486 |
+
else:
|
487 |
+
chapter_titles = st.session_state.get('generated_chapter_titles',
|
488 |
+
[f"Chapter {i+1}" for i in range(num_chapters)])
|
489 |
+
|
490 |
+
# Display and allow editing of generated chapter titles
|
491 |
st.subheader("Chapter Titles")
|
492 |
+
edited_chapter_titles = []
|
493 |
cols = st.columns(3)
|
494 |
for i in range(num_chapters):
|
495 |
with cols[i % 3]:
|
|
|
496 |
title = st.text_input(
|
497 |
f"Chapter {i+1}",
|
498 |
+
value=chapter_titles[i] if i < len(chapter_titles) else f"Chapter {i+1}",
|
499 |
key=f"chapter_title_{i}"
|
500 |
)
|
501 |
+
edited_chapter_titles.append(title)
|
502 |
|
503 |
if st.button("Save Settings", key="save_settings_button"):
|
504 |
st.session_state.book_settings = {
|
|
|
507 |
"genre": genre,
|
508 |
"num_chapters": num_chapters,
|
509 |
"words_per_chapter": words_per_chapter,
|
510 |
+
"chapter_titles": edited_chapter_titles,
|
511 |
+
"total_words": num_chapters * words_per_chapter,
|
512 |
+
"user_prompt": user_prompt
|
513 |
}
|
514 |
st.success("✅ Settings saved successfully! You can now proceed to Generate Content.")
|
515 |
|
516 |
+
def generate_intelligent_chapter_titles(prompt, num_chapters, template, genre):
|
517 |
+
"""Generate intelligent chapter titles based on user input"""
|
518 |
+
# This is a placeholder for the actual AI generation
|
519 |
+
# You would typically use an LLM API here
|
520 |
+
system_prompt = f"""
|
521 |
+
Based on the following user's book idea, generate {num_chapters} chapter titles.
|
522 |
+
The book is in the {genre} genre and follows the {template} style.
|
523 |
+
|
524 |
+
User's book idea:
|
525 |
+
{prompt}
|
526 |
+
|
527 |
+
Generate unique, engaging chapter titles that follow a logical progression
|
528 |
+
and reflect the themes and elements mentioned in the user's prompt.
|
529 |
+
"""
|
530 |
+
|
531 |
+
# For now, returning placeholder titles
|
532 |
+
# Replace this with actual AI generation
|
533 |
+
return [f"Generated Chapter {i+1}" for i in range(num_chapters)]
|
534 |
+
|
535 |
def display_generate_content():
|
536 |
"""Display the content generation page"""
|
537 |
if not st.session_state.book_settings:
|