here is my app.py code along with the index.html code "… · The Chat Archive
Explore / Programming here is my app.py code along with the index.html code " from flask import Flask,… Save Share Download ▾ Reporthere is my app.py code along with the index.html code
"
from flask import Flask, render_template, request, jsonify, make_response
import google.generativeai as genai
import json
from concurrent.futures import ThreadPoolExecutor
import concurrent.futures
from urllib.parse import quote
from xhtml2pdf import pisa
from io import BytesIO
import re
app = Flask(name )
executor = ThreadPoolExecutor(max_workers=10)
from google.generativeai.types import GenerationConfig, HarmCategory, HarmBlockThreshold
safety_settings = {
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
# ... add other harm categories as needed with BLOCK_NONE
}
Configure Google Gemini API
genai.configure(api_key="") # Replace with your actual API key
model = genai.GenerativeModel('gemini-1.5-flash',safety_settings=safety_settings)
RESPONSIVE_VOICE_KEY="dENc15J5"
--- Helper Functions ---
def generate_image(prompt, width=800, height=600):
"""Generate image using Pollinations AI"""
try:
encoded_prompt = quote(prompt)
image_url = f"https://image.pollinations.ai/prompt/{encoded_prompt}?width={width}&height={height}&nologo=true "
return image_url
except Exception as e:
print(f"Image generation error: {str(e)}")
return "https://image.pollinations.ai/prompt/scenic%20view?width=800&height=600&nologo=true "
def generate_all_images_concurrent(story_data):
"""Generate all images concurrently using ThreadPoolExecutor"""
try:
# Create tasks for cover and chapter images
cover_prompt = f"A professional book cover with a title on it, '{story_data['title']}', fantasy art"
cover_future = executor.submit(generate_image, cover_prompt, 400, 550)
chapter_futures = [executor.submit(generate_image, chapter['image_prompt']) for chapter in story_data['chapters']]
# Get results
cover_image = cover_future.result()
chapter_images = [future.result() for future in chapter_futures]
# Assign URLs to story data
for chapter, image_url in zip(story_data['chapters'], chapter_images):
chapter['image'] = image_url
return story_data, cover_image
except Exception as e:
print(f"Error in generate_all_images_concurrent: {str(e)}")
fallback_url = "https://image.pollinations.ai/prompt/scenic%20view?width=800&height=600&nologo=true"
cover_fallback = "https://image.pollinations.ai/prompt/book%20cover?width=400&height=550&nologo=true"
for chapter in story_data['chapters']:
chapter['image'] = fallback_url
return story_data, cover_fallback
Assistant2025-01-05 04:20 UTC Copy response
Thank you for sharing your app.py and index.html code. How can I assist you with this? Are you encountering any issues or do you need help with debugging or improving your application?
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language —
Conversation date Jan 5, 2025
Added to archive Nov 16, 2026
ID 01m7h42cpdfnts5p270v3j9r0ySource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 7846d2f35cbd5dd0b879f96e9c3318a4
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
def get_word_definitions(words):
"""Get definitions using Gemini API with improved prompting and error handling"""
prompt = f"""
Define the following words clearly and concisely, focusing on their most common meanings in everyday usage.
Words to define: {', '.join(words)}
Respond ONLY with a JSON object in this exact format (no other text):
{{
"word1": "simple definition here",
"word2": "simple definition here"
}}
Make sure each definition is:
- Clear and simple
- 10-15 words maximum
- Suitable for the general audience
- Focuses on the most common meaning
"""
try:
response = model.generate_content(prompt)
response_text = response.text.strip()
# Clean up the response to ensure it's valid JSON
# Remove any markdown formatting if present
if '```json' in response_text:
response_text = re.search(r'```json\s*(.*?)\s*```', response_text, re.DOTALL).group(1)
elif '```' in response_text:
response_text = re.search(r'```\s*(.*?)\s*```', response_text, re.DOTALL).group(1)
# Remove any remaining non-JSON text
response_text = re.search(r'\{.*\}', response_text, re.DOTALL).group(0)
definitions = json.loads(response_text)
# Ensure all requested words have definitions
final_definitions = {}
for word in words:
word_lower = word.lower()
# Try to find the word in the definitions (case-insensitive)
matching_key = next((k for k in definitions.keys() if k.lower() == word_lower), None)
if matching_key and definitions[matching_key].strip():
final_definitions[word] = definitions[matching_key]
else:
# If definition is missing, make another attempt for just this word
single_word_prompt = f"""
Define this word clearly and concisely in 10-15 words:
Word: {word}
Respond ONLY with the definition (no other text).
"""
try:
retry_response = model.generate_content(single_word_prompt)
definition = retry_response.text.strip()
if definition:
final_definitions[word] = definition
else:
final_definitions[word] = "No definition available"
except Exception:
final_definitions[word] = "No definition available"
return final_definitions
except Exception as e:
print(f"Error getting definitions: {str(e)}")
return {word: f"Definition not available due to error: {str(e)}" for word in words}
def extract_terminology(text):
"""Extract 4-5 significant terms and get their definitions using Gemini"""
# Find words that are potentially complex or important
words = re.findall(r'\b[A-Za-z]{5,}\b', text)
# Remove common words and duplicates
common_words = {
'there', 'their', 'would', 'could', 'should', 'about', 'which', 'these',
'those', 'were', 'have', 'that', 'what', 'when', 'where', 'while', 'from',
'been', 'being', 'other', 'another', 'every', 'everything', 'something',
'anything', 'nothing', 'through', 'although', 'though', 'without', 'within',
'around', 'before', 'after', 'under', 'over', 'because'
}
# Filter words
filtered_words = []
for word in words:
word_lower = word.lower()
if (
word_lower not in common_words and
not word.isupper() and # Skip acronyms
len(word) >= 6 and # Focus on longer words
not any(char.isdigit() for char in word) # Skip words with numbers
):
filtered_words.append(word)
# Remove duplicates while preserving case
unique_words = []
seen_words = set()
for word in filtered_words:
if word.lower() not in seen_words:
unique_words.append(word)
seen_words.add(word.lower())
# Select the most interesting words (prioritize longer, less common words)
selected_words = sorted(unique_words, key=lambda x: (len(x), x.lower()), reverse=True)[:5]
if selected_words:
# Get definitions using improved Gemini function
definitions = get_word_definitions(selected_words)
return {k: v for k, v in definitions.items() if v and v != "No definition available"}
return {}
--- Story Generation and Editing Functions (unchanged) --- def generate_story(keywords, genre, num_chapters, tone, style, age_group, include_magic, include_romance, include_conflict):
"""Generate story content using Gemini API with enhanced parameters"""
prompt = f"""
Create a captivating story based on the following:
Keywords: {keywords}
Genre: {genre}
Number of chapters: {num_chapters}
Tone: {tone}
Writing Style: {style}
Target Audience Age Group: {age_group}
Include Magical Elements: {'Yes' if include_magic else 'No'}
Include Romance: {'Yes' if include_romance else 'No'}
Include Major Conflicts: {'Yes' if include_conflict else 'No'}
Format the response exactly like this JSON structure (don't include any other text before or after the JSON):
{{
"title": "Story title",
"author": "AI Author",
"moral": "The moral of the story",
"chapters": [
{{
"chapter_number": 1,
"chapter_title": "Chapter title",
"content": "Chapter content (approximately 2-4 paragraphs, suitable for the target age group and writing style)",
"image_prompt": "Detailed visual description for a captivating chapter image, reflecting the chapter's mood and style",
"terminology": {{}}
}}
]
}}
"""
try:
response = model.generate_content(prompt)
response_text = response.text
# Parse JSON with multiple fallback attempts
try:
story_data = json.loads(response_text)
except json.JSONDecodeError:
# Try finding JSON in markdown code blocks
json_match = re.search(r'```json\s*(.*?)\s*```', response_text, re.DOTALL)
if json_match:
story_data = json.loads(json_match.group(1))
else:
# Try finding content between curly braces
json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
if json_match:
story_data = json.loads(json_match.group(0))
else:
story_data = {
"title": f"{genre.title()} Story",
"author": "AI Author",
"moral": "Could not generate a moral for the story",
"chapters": [{
"chapter_number": 1,
"chapter_title": "Chapter 1",
"content": "Story generation failed. Please try again.",
"image_prompt": "A blank page with some text",
"terminology": {}
}]
}
# Add terminology to each chapter
for chapter in story_data['chapters']:
chapter['terminology'] = extract_terminology(chapter['content'])
return story_data
except Exception as e:
print(f"Error generating story: {str(e)}")
return {
"title": f"{genre.title()} Story",
"author": "AI Author",
"moral": "Could not generate a moral for the story",
"chapters": [{
"chapter_number": 1,
"chapter_title": "Chapter 1",
"content": "Story generation failed. Please try again.",
"image_prompt": "A blank page with some text",
"terminology": {}
}]
}
def regenerate_chapter(story_data, chapter_number, tone, style, include_magic, include_romance, include_conflict):
"""Regenerate a specific chapter"""
chapter_index = chapter_number - 1
if not (0 <= chapter_index < len(story_data["chapters"])):
return "Invalid chapter number", 400
# Previous context for regeneration
previous_context = ""
if chapter_index > 0:
previous_context = story_data['chapters'][chapter_index - 1]['content']
prompt = f"""
Regenerate chapter {chapter_number} of the story titled '{story_data['title']}'.
Previous chapter context (if applicable): {previous_context}
Overall Tone: {tone}
Writing Style: {style}
Include Magical Elements: {'Yes' if include_magic else 'No'}
Include Romance: {'Yes' if include_romance else 'No'}
Include Major Conflicts: {'Yes' if include_conflict else 'No'}
Format the response exactly like this JSON structure (don't include any other text before or after the JSON):
{{
"chapter_number": {chapter_number},
"chapter_title": "New chapter title",
"content": "New chapter content (approximately 2-4 paragraphs, consistent with the story's style and tone)",
"image_prompt": "Detailed visual description for a captivating chapter image, furthering the narrative visually",
"terminology": {{}}
}}
"""
try:
response = model.generate_content(prompt)
try:
new_chapter = json.loads(response.text)
except json.JSONDecodeError:
json_match = re.search(r'```json\s*(.*?)\s*```', response.text, re.DOTALL)
if json_match:
new_chapter = json.loads(json_match.group(1))
else:
json_match = re.search(r'\{.*\}', response.text, re.DOTALL)
if json_match:
new_chapter = json.loads(json_match.group(0))
else:
new_chapter = {
"chapter_number": chapter_number,
"chapter_title": "Regenerated Chapter",
"content": "Failed to regenerate chapter. Please try again.",
"image_prompt": "A blank page with some text",
"terminology": {}
}
# Add terminology
new_chapter['terminology'] = extract_terminology(new_chapter['content'])
# Replace old chapter with new chapter
story_data['chapters'][chapter_index] = new_chapter
# Regenerate image for the chapter
new_chapter['image'] = generate_image(new_chapter['image_prompt'])
return new_chapter
except Exception as e:
print(f"Error regenerating chapter: {str(e)}")
return {
"chapter_number": chapter_number,
"chapter_title": "Regenerated Chapter",
"content": "Failed to regenerate chapter. Please try again.",
"image_prompt": "A blank page with some text",
"terminology": {}
}
--- Routes (unchanged) --- @app.route('/')
def index():
return render_template('index.html', responsive_voice_key=RESPONSIVE_VOICE_KEY)
@app.route('/generate', methods=['POST'])
def generate():
try:
data = request.get_json()
keywords = data.get('keywords')
genre = data.get('genre')
story_length = data.get('storyLength')
tone = data.get('tone')
style = data.get('style')
age_group = data.get('ageGroup')
include_magic = data.get('includeMagic')
include_romance = data.get('includeRomance')
include_conflict = data.get('includeConflict')
# Determine the number of chapters based on story length
num_chapters = {
'short': 3,
'medium': 5,
'long': 7,
'grand': 10
}.get(story_length, 3)
# Generate story content
story = generate_story(keywords, genre, num_chapters, tone, style, age_group, include_magic, include_romance, include_conflict)
# Generate all images concurrently
story, cover_image = generate_all_images_concurrent(story)
return jsonify({
'story': story,
'cover_image': cover_image
})
except Exception as e:
print(f"Error in generate route: {str(e)}")
return jsonify({
'error': 'Failed to generate story',
'details': str(e)
}), 500
@app.route('/regenerate', methods=['POST'])
def regenerate():
try:
data = request.get_json()
story_data = data.get('story')
chapter_number = int(data.get('chapter_number'))
tone = data.get('tone')
style = data.get('style')
include_magic = data.get('includeMagic')
include_romance = data.get('includeRomance')
include_conflict = data.get('includeConflict')
new_chapter = regenerate_chapter(story_data, chapter_number, tone, style, include_magic, include_romance, include_conflict)
return jsonify({'story': story_data, 'new_chapter': new_chapter})
except Exception as e:
print(f"Error in regenerate route: {str(e)}")
return jsonify({
'error': 'Failed to regenerate chapter',
'details': str(e)
}), 500
@app.route('/continue', methods=['POST'])
def continue_story_route():
try:
data = request.get_json()
previous_story = data.get('previous_story')
num_new_chapters = int(data.get('num_new_chapters', 3))
tone = data.get('tone')
style = data.get('style')
include_magic = data.get('includeMagic')
include_romance = data.get('includeRomance')
include_conflict = data.get('includeConflict')
# Generate new chapters
new_chapters = continue_story(previous_story, num_new_chapters, tone, style, include_magic, include_romance, include_conflict)
# Generate images for new chapters concurrently
futures = [executor.submit(generate_image, chapter['image_prompt'])
for chapter in new_chapters]
# Wait for all image generations to complete
for chapter, future in zip(new_chapters, futures):
chapter['image'] = future.result()
return jsonify({'new_chapters': new_chapters})
except Exception as e:
print(f"Error in continue route: {str(e)}")
return jsonify({
'error': 'Failed to continue story',
'details': str(e)
}), 500
@app.route('/get_moral', methods=['POST'])
def get_moral():
try:
data = request.get_json()
story_data = data.get('story')
return jsonify({'moral': story_data['moral']})
except Exception as e:
print(f"Error in get_moral route: {str(e)}")
return jsonify({
'error': 'Failed to retrieve moral',
'details': str(e)
}), 500
@app.route('/download', methods=['POST'])
def download_pdf():
try:
data = request.get_json()
story_data = data.get('story')
cover_image = data.get('cover_image')
# Configure PDF options
pdf_options = {
'page-size': 'A4',
'margin-top': '2.5cm',
'margin-right': '2cm',
'margin-bottom': '2.5cm',
'margin-left': '2cm',
'encoding': 'UTF-8',
}
# Generate HTML
pdf_html = render_template('pdf_template.html', story=story_data, cover_image=cover_image)
# Create PDF
pdf_buffer = BytesIO()
pisa.CreatePDF(
pdf_html,
dest=pdf_buffer,
encoding='utf-8',
)
pdf_buffer.seek(0)
# Create response
response = make_response(pdf_buffer.read())
response.headers['Content-Type'] = 'application/pdf'
response.headers['Content-Disposition'] = f'attachment; filename="{story_data["title"].replace(" ", "_")}.pdf"'
return response
except Exception as e:
print(f"Download PDF Error: {str(e)}")
return jsonify({
"error": "Error generating PDF",
"details": str(e)
}), 500
def continue_story(previous_story, num_new_chapters, tone, style, include_magic, include_romance, include_conflict):
"""Generate additional chapters for an existing story with enhanced parameters"""
prompt = f"""
Continue this story with {num_new_chapters} more chapters, maintaining the established themes and characters.
Previous story title: {previous_story['title']}
Last chapter content: {previous_story['chapters'][-1]['content']}
Overall Tone: {tone}
Writing Style: {style}
Include Magical Elements: {'Yes' if include_magic else 'No'}
Include Romance: {'Yes' if include_romance else 'No'}
Include Major Conflicts: {'Yes' if include_conflict else 'No'}
Format the response exactly like this JSON structure (don't include any other text before or after the JSON):
{{
"chapters": [
{{
"chapter_number": {len(previous_story['chapters']) + 1},
"chapter_title": "New chapter title",
"content": "New chapter content (approximately 2-4 paragraphs, consistent with the story's style and tone)",
"image_prompt": "Detailed visual description for a captivating chapter image, furthering the narrative visually",
"terminology": {{}}
}}
]
}}
"""
try:
response = model.generate_content(prompt)
try:
new_chapters = json.loads(response.text)
except json.JSONDecodeError:
json_match = re.search(r'```json\s*(.*?)\s*```', response.text, re.DOTALL)
if json_match:
new_chapters = json.loads(json_match.group(1))
else:
json_match = re.search(r'\{.*\}', response.text, re.DOTALL)
if json_match:
new_chapters = json.loads(json_match.group(0))
else:
new_chapters = {
"chapters": [{
"chapter_number": len(previous_story['chapters']) + 1,
"chapter_title": "New Chapter",
"content": "Failed to generate new content. Please try again.",
"image_prompt": "A blank page with some text",
"terminology": {}
}]
}
# Add terminology to each new chapter
for chapter in new_chapters['chapters']:
chapter['terminology'] = extract_terminology(chapter['content'])
return new_chapters['chapters']
except Exception as e:
print(f"Error continuing story: {str(e)}")
return [{
"chapter_number": len(previous_story['chapters']) + 1,
"chapter_title": "New Chapter",
"content": "Failed to generate new content. Please try again.",
"image_prompt": "A blank page with some text",
"terminology": {}
}]
if name == 'main ':
app.run(debug=True)
"
"
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Crimson Pro', serif;
background: transparent;
/* Important for Vanta.js */
color: var(--text);
min-height: 100vh;
position: relative;
/* For absolute positioning of elements */
overflow-x: hidden;
/* Prevent horizontal scroll */
}
/* Sparkle Effect */
.sparkle {
position: absolute;
pointer-events: none;
animation: sparkle 1.5s linear infinite;
opacity: 0;
}
@keyframes sparkle {
0%,
100% {
opacity: 0;
transform: scale(0);
}
50% {
opacity: 1;
transform: scale(1);
}
}
/* Enhanced Header Styles */
.header {
padding: 4rem 1rem;
text-align: center;
position: relative;
background: linear-gradient(180deg, rgba(42, 27, 61, 0.05), transparent);
}
.header::before,
.header::after {
content: '';
position: absolute;
width: 200px;
height: 3px;
background: linear-gradient(90deg, transparent, var(--gold), transparent);
left: 50%;
transform: translateX(-50%);
}
.header::before {
top: 20px;
}
.header::after {
bottom: 20px;
}
.header h1 {
font-family: 'Cinzel Decorative', cursive;
font-size: 4.5rem;
background: linear-gradient(45deg, var(--primary), var(--accent));
-webkit-background-clip: text;
color: transparent;
margin-bottom: 1rem;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
letter-spacing: 3px;
position: relative;
animation: titleFloat 6s ease-in-out infinite;
}
@keyframes titleFloat {
0%,
100% {
transform: translateY(0);
}
50% {
transform: translateY(-10px);
}
}
.header p {
font-family: 'Almendra', serif;
color: var(--secondary);
font-size: 1.8rem;
font-style: italic;
max-width: 800px;
margin: 0 auto;
}
/* Enhanced Input Container */
.creation-panel {
max-width: 1000px;
margin: 2rem auto;
padding: 3rem 1rem; /* Reduced padding for better mobile layout*/
background: rgba(255, 255, 255, 0.95);
border-radius: 20px;
box-shadow: var(--shadow);
transform: translateY(0);
transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
border: 1px solid rgba(68, 49, 141, 0.1);
position: relative;
overflow: hidden;
}
.creation-panel::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 5px;
background: linear-gradient(90deg, var(--accent), var(--secondary));
}
.creation-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 2rem;
margin-bottom: 2rem;
}
.input-group {
position: relative;
}
.input-label {
display: block;
margin-bottom: 0.8rem;
font-family: 'Cormorant Infant', serif;
font-weight: 600;
color: var(--primary);
font-size: 1.3rem;
position: relative;
padding-left: 1.5rem;
}
.input-label::before {
content: '✧';
position: absolute;
left: 0;
color: var(--accent);
}
.input-field {
width: 100%;
padding: 1rem 1.5rem;
border: 2px solid rgba(68, 49, 141, 0.2);
border-radius: 10px;
font-size: 1.1rem;
font-family: 'Crimson Pro', serif;
background: rgba(255, 255, 255, 0.9);
transition: all 0.3s ease;
}
.input-field:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(233, 128, 116, 0.1);
}
/* New Advanced Options Section */
.advanced-options {
background: rgba(42, 27, 61, 0.03);
padding: 2rem;
border-radius: 15px;
margin-top: 2rem;
}
.advanced-header {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 1.5rem;
cursor: pointer;
}
.advanced-header h3 {
font-family: 'Cormorant Infant', serif;
color: var(--secondary);
font-size: 1.4rem;
}
.options-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 0.8rem;
}
.custom-checkbox {
width: 20px;
height: 20px;
border: 2px solid var(--accent);
border-radius: 5px;
cursor: pointer;
position: relative;
}
.custom-checkbox:checked {
background: var(--accent);
}
.custom-checkbox:checked::after {
content: '✔';
color: white;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* Enhanced Generate Button */
.generate-btn {
width: 100%;
padding: 1.5rem;
background: linear-gradient(45deg, var(--primary), var(--secondary));
color: var(--white);
border: none;
border-radius: 15px;
font-size: 1.4rem;
font-family: 'Almendra', serif;
font-weight: 600;
cursor: pointer;
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
position: relative;
overflow: hidden;
margin-top: 2rem;
text-transform: uppercase;
letter-spacing: 2px;
}
.generate-btn::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
transition: 0.5s;
}
.generate-btn:hover::before {
left: 100%;
}
.generate-btn:hover {
transform: translateY(-3px);
box-shadow: 0 10px 20px rgba(42, 27, 61, 0.2);
}
/* Enhanced Book Display */
.book-display {
max-width: 1400px;
margin: 4rem auto;
padding: 2rem 1rem; /*Adjusted padding for mobile*/
display: none;
}
/* Enhanced Book Container and 3D Effects */
.book-container {
perspective: 3000px;
margin: 4rem auto;
max-width: 600px; /* Max width instead of specific width*/
width: 90%; /* Width as a percentage for responsiveness*/
height: auto; /*Allow the height to adjust to aspect ratio */
position: relative;
transform-style: preserve-3d;
padding: 0px 20px; /* Add some side padding */
}
.book {
position: relative;
width: 100%;
padding-bottom: 133%; /* Maintain a 3:4 aspect ratio (4/3 *100) to calculate the height based on the width */
transform-style: preserve-3d;
transform: rotateY(-30deg);
transition: all 1.5s cubic-bezier(0.645, 0.045, 0.355, 1);
box-shadow:
20px 20px 60px rgba(0, 0, 0, 0.4),
-20px 0 60px rgba(0, 0, 0, 0.2);
}
.book>div {
position: absolute;
width: 100%;
height: 100%;
}
/* Realistic Book Cover */
.book-cover {
transform-origin: left;
transform-style: preserve-3d;
transition: transform 1.5s cubic-bezier(0.645, 0.045, 0.355, 1);
background: linear-gradient(45deg, #2a1b3d, #44318d);
border-radius: 2px 15px 15px 2px;
box-shadow:
inset -5px 0 15px rgba(0, 0, 0, 0.4),
5px 0 15px rgba(0, 0, 0, 0.2);
}
.book-cover::before {
content: '';
position: absolute;
width: 50px;
height: 100%;
transform: translateX(-49px) rotateY(-90deg);
background: linear-gradient(90deg,
#1a0f28,
#2a1b3d 20%,
#44318d 60%,
#2a1b3d 80%,
#1a0f28
);
transform-origin: right;
border-left: 2px solid rgba(255, 255, 255, 0.1);
border-right: 2px solid rgba(0, 0, 0, 0.2);
}
.book-cover::after {
content: '';
position: absolute;
width: 100%;
height: 100%;
transform: translateZ(-50px);
background: linear-gradient(135deg, #f8f4e9, #fff9f0);
border-radius: 2px 15px 15px 2px;
box-shadow:
-10px 0 30px rgba(0, 0, 0, 0.2),
inset 0 0 40px rgba(0, 0, 0, 0.1);
}
/* Apply the cover image as a background */
.book-cover img#coverImage {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: fill;
border-radius: inherit; /* Match the book cover's border-radius */
}
/* Enhanced Page Spread Styles */
.page-spread {
display: flex;
gap: 0;
background: #fff9f0;
border-radius: 5px;
box-shadow:
0 30px 60px rgba(0, 0, 0, 0.3),
0 0 100px rgba(0, 0, 0, 0.2);
position: relative;
overflow: hidden;
max-width: 100%; /* Ensure it fits container's width*/
margin: 2rem auto;
transform-style: preserve-3d;
perspective: 2000px;
}
.page {
flex: 1;
padding: 3rem 2rem; /* Reduce side padding */
background: linear-gradient(to right,
#fff9f0,
#fff9f0 97%,
rgba(0, 0, 0, 0.05) 100%
);
position: relative;
min-height: 500px; /* Make sure pages always have a certain minimum*/
transition: transform 0.6s cubic-bezier(0.645, 0.045, 0.355, 1);
border-radius: 5px;
box-shadow:
inset 0 0 60px rgba(0, 0, 0, 0.03),
0 0 30px rgba(0, 0, 0, 0.1);
}
.page::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAMAAAAp4XiDAAAAUVBMVEWFhYWDg4N3d3dtbW17e3t1dXWBgYGHh4d5eXlzc3OLi4ubm5uVlZWPj4+NjY19fX2JiYl/f39ra2uRkZGZmZlpaWmXl5dvb29xcXGTk5NnZ2c8TV1mAAAAG3RSTlNAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAvEOwtAAAFVklEQVR4XpWWB67c2BUFb3g557T/hRo9/WUMZHlgr4Bg8Z4qQgQJlHI4A8SzFVrapvmTF9O7dmYRFZ60YiBhJRCgh1FYhiLAmdvX0CzTOpNE77ME0Zty/nWWzchDtiqrmQDeuv3powQ5ta2eN0FY0InkqDD73lT9c9lEzwUNqgFHs9VQce3TVClFCQrSTfOiYkVJQBmpbq2L6iZavPnAPcoU0dSw0SUTqz/GtrGuXfbyyBniKykOWQWGqwwMA7QiYAxi+IlPdqo+hYHnUt5ZPfnsHJyNiDtnpJzayNBkF6cWoYGAMY92U2hXHF/C1M8uP/ZtYdiuj26UdAdQQSXQErwSOMzt/XWRWAz5GuSBIkwG1H3FabJ2OsUOUhGC6tK4EMtJO0ttC6IBD3kM0ve0tJwMdSfjZo+EEISaeTr9P3wYrGjXqyC1krcKdhMpxEnt5JetoulscpyzhXN5FRpuPHvbeQaKxFAEB6EN+cYN6xD7RYGpXpNndMmZgM5Dcs3YSNFDHUo2LGfZuukSWyUYirJAdYbF3MfqEKmjM+I2EfhA94iG3L7uKrR+GdWD73ydlIB+6hgref1QTlmgmbM3/LeX5GI1Ux1RWpgxpLuZ2+I+IjzZ8wqE4nilvQdkUdfhzI5QDWy+kw5Wgg2pGpeEVeCCA7b85BO3F9DzxB3cdqvBzWcmzbyMiqhzuYqtHRVG2y4x+KOlnyqla8AoWWpuBoYRxzXrfKuILl6SfiWCbjxoZJUaCBj1CjH7GIaDbc9kqBY3W-Rgjda1iqQcOJu2WW+76pZC9QG7M00dffe9hNnseupFL53r8F7YHSwJWUKP2q+k7RdsxyOB11n0xtOvnW4irMMFNV4H0uqwS5ExsmP9AxbDTc9JwgneAT5vTiUSm1E7BSflSt3bfa1tv8Di3R8n3Af7MNWzs49hmauE2wP+ttrq+AsWpFG2awvsuOqbipWHgtuvuaAE+A1Z/7gC9hesnr+7wqCwG8c5yAg3AL1fm8T9AZtp/bbJGwl1pNrE7RuOX7PeMRUERVaPpEs+yqeoSmuOlokqw49pgomjLeh7icHNlG19yjs6XXOMedYm5xH2YxpV2tc0Ro2jJfxC50ApuxGob7lMsxfTbeUv07TyYxpeLucEH1gNd4IKH2LAg5TdVhlCafZvpskfncCfx8pOhJzd76bJWeYFnFciwcYfubRc12Ip/ppIhA1/mSZ/RxjFDrJC5xifFjJpY2Xl5zXdguFqYyTR1zSp1Y9p+tktDYYSNflcxI0iyO4TPBdlRcpeqjK/piF5bklq77VSEaA+z8qmJTFzIWiitbnzR794USKBUaT0NTEsVjZqLaFVqJoPN9ODG70IPbfBHKK+/q/AWR0tJzYHRULOa4MP+W/HfGadZUbfw177G7j/OGbIs8TahLyynl4X4RinF793Oz+BU0saXtUHrVBFT/DnA3ctNPoGbs4hRIjTok8i+algT1lTHi4SxFvONKNrgQFAq2/gFnWMXgwffgYMJpiKYkmW3tTg3ZQ9Jq+f8XN+A5eeUKHWvJWJ2sgJ1Sop+wwhqFVijqWaJhwtD8MNlSBeWNNWTa5Z5kPZw5+LbVT99wqTdx29lMUH4OIG/D86ruKEauBjvH5xy6um/Sfj7ei6UUVk4AIl3MyD4MSSTOFgSwsH/QJWaQ5as7ZcmgBZmzjjU1UrQ74ci1gWBCSGHtuV1H2mhSnO3Wp/3fEV5a+4wz//6qy8JxjZsmxxy5+4w9CDNJY09T072iKG0EnOS0arEYgXqYnXcYHwjTtUNAcMelOd4xpkoqiTYICWFq0JSiPfPDQdnt+4/wuqcXY47QILbgAAAABJRU5ErkJggg==');
opacity: 0.03;
pointer-events: none;
mix-blend-mode: multiply;
}
/* Page Turn Animation */
@keyframes pageTurn {
0% {
transform: rotateY(0deg);
box-shadow: -10px 0 30px rgba(0, 0, 0, 0.1);
}
100% {
transform: rotateY(-180deg);
box-shadow: 10px 0 30px rgba(0, 0, 0, 0.1);
}
}
.page-turn {
animation: pageTurn 1.2s cubic-bezier(0.645, 0.045, 0.355, 1) forwards;
}
/* Enhanced Chapter Content */
.chapter-content {
font-size: 1.3rem;
line-height: 1.8;
color: var(--text);
text-align: justify;
column-gap: 2rem;
position: relative;
text-indent: 2rem;
font-family: 'Crimson Pro', serif;
letter-spacing: 0.02em;
}
/* First Letter Drop Cap */
.chapter-content p:first-of-type::first-letter {
font-family: 'Cinzel Decorative', cursive;
font-size: 3.5em;
float: left;
line-height: 0.8;
padding: 0.1em 0.1em 0 0;
color: var(--primary);
}
/* Page Number Effect */
.page::after {
content: attr(data-page);
position: absolute;
bottom: 2rem;
font-family: 'Cormorant Infant', serif;
font-size: 1rem;
color: rgba(0, 0, 0, 0.5);
}
.page:first-child::after {
left: 3rem;
}
.page:last-child::after {
right: 3rem;
}
/* Book Opening Animation */
.book-cover.open {
transform: rotateY(-180deg);
transition: transform 1.5s cubic-bezier(0.645, 0.045, 0.355, 1);
}
/* Book Hover Effect */
.book:hover {
transform: rotateY(-35deg) translateY(-10px);
}
/* Story Pages */
.story-pages {
max-width: 1400px;
margin: 2rem auto;
padding: 2rem 1rem;
display: none;
}
.page-decoration {
position: absolute;
width: 100px;
height: 100px;
opacity: 0.1;
pointer-events: none;
}
.page-decoration.top-left {
top: 20px;
left: 20px;
transform: rotate(-45deg);
}
.page-decoration.bottom-right {
bottom: 20px;
right: 20px;
transform: rotate(135deg);
}
.chapter-image {
width: 100%;
height: 300px;
object-fit: cover;
border-radius: 15px;
margin-bottom: 2rem;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.chapter-image:hover {
transform: scale(1.02);
}
.chapter-title {
font-family: 'Cinzel Decorative', cursive;
font-size: 2.2rem;
color: var(--primary);
margin-bottom: 1.5rem;
text-align: center;
position: relative;
padding-bottom: 1rem;
}
.chapter-title::after {
content: '';
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 120px;
height: 3px;
background: linear-gradient(90deg, transparent, var(--accent), transparent);
}
/* Enhanced Navigation */
.story-navigation {
display: flex;
justify-content: center;
gap: 2rem;
margin-top: 3rem;
padding: 1rem;
background: rgba(255, 255, 255, 0.8);
border-radius: 15px;
backdrop-filter: blur(10px);
}
.nav-btn {
padding: 1rem 2rem;
border: none;
border-radius: 10px;
font-family: 'Almendra', serif;
font-weight: 600;
font-size: 1.2rem;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
display: flex;
align-items: center;
gap: 1rem;
}
.nav-btn.primary {
background: linear-gradient(45deg, var(--primary), var(--secondary));
color: var(--white);
}
.nav-btn.secondary {
background: transparent;
color: var(--primary);
border: 2px solid var(--primary);
}
.nav-btn:hover:not(:disabled) {
transform: translateY(-3px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}
.nav-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Enhanced Loading Animation */
.loading-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(244, 228, 188, 0.98);
display: none;
justify-content: center;
align-items: center;
z-index: 1000;
flex-direction: column;
backdrop-filter: blur(10px);
}
.loading-content {
text-align: center;
position: relative;
}
.magic-circle {
width: 120px;
height: 120px;
border: 4px solid transparent;
border-image: linear-gradient(45deg, var(--accent), var(--secondary)) 1;
animation: rotateAndPulse 3s infinite;
}
@keyframes rotateAndPulse {
0% {
transform: rotate(0deg) scale(1);
border-width: 4px;
}
50% {
transform: rotate(180deg) scale(1.1);
border-width: 2px;
}
100% {
transform: rotate(360deg) scale(1);
border-width: 4px;
}
}
.loading-text {
font-family: 'Cinzel Decorative', cursive;
font-size: 1.8rem;
color: var(--primary);
margin-top: 2rem;
position: relative;
}
.loading-text::after {
content: '...';
position: absolute;
animation: ellipsis 1.5s infinite;
}
@keyframes ellipsis {
0% {
content: '.';
}
33% {
content: '..';
}
66% {
content: '...';
}
100% {
content: '.';
}
}
.progress-container {
width: 300px;
height: 10px;
background: rgba(42, 27, 61, 0.1);
border-radius: 10px;
overflow: hidden;
margin-top: 2rem;
}
.progress-bar {
height: 100%;
background: linear-gradient(90deg, var(--accent), var(--secondary));
border-radius: 10px;
width: 0;
transition: width 0.3s ease;
}
/* Enhanced Toast Notification */
.toast {
position: fixed;
bottom: 2rem;
right: 2rem;
padding: 1.5rem 3rem;
background: rgba(255, 255, 255, 0.98);
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
display: none;
animation: slideIn 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
font-family: 'Cormorant Infant', serif;
color: var(--primary);
border-left: 4px solid var(--accent);
backdrop-filter: blur(10px);
font-size: 1.2rem;
}
@keyframes slideIn {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOut {
to {
transform: translateX(100%);
opacity: 0;
}
}
/* Responsive Design */
@media (max-width: 768px) {
.header h1 {
font-size: 3rem;
}
.header p {
font-size: 1.4rem;
}
.creation-panel {
padding: 2rem 1rem; /*Adjusted for smaller devices*/
}
.book-container{
width: 85%; /* Increased for smaller screens*/
height: auto;
padding: 0px; }
.book {
width: 80%;
height: auto;
}
.page-spread {
flex-direction: column;
}
.page {
padding: 1.5rem;
}
.chapter-title {
font-size: 1.8rem;
}
.chapter-content {
font-size: 1.1rem;
}
.story-navigation {
flex-wrap: wrap;
}
}
/* Enhanced book hover effect with depth */
.book {
cursor: pointer; /* Add pointer cursor for interaction */
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
/* Enhanced Background Container */
#vanta-background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
/* Modified body background */
/* Enhanced Loading Animation */
.loading-overlay {
backdrop-filter: blur(10px);
background: rgba(244, 228, 188, 0.85);
}
.loading-content {
position: relative;
}
.magic-book {
width: 100px;
height: 150px;
position: relative;
perspective: 1500px;
margin: 0 auto 30px;
}
.book-cover-animated {
position: absolute;
width: 100%;
height: 100%;
transform-style: preserve-3d;
animation: bookFloat 3s ease-in-out infinite;
background: linear-gradient(45deg, var(--primary), var(--secondary));
border-radius: 5px;
box-shadow: 0 0 30px rgba(0,0,0,0.2);
}
.book-page {
position: absolute;
width: 95%;
height: 95%;
background: var(--white);
top: 2.5%;
left: 2.5%;
transform-origin: left;
animation: pageFlip 4s ease-in-out infinite;
}
@keyframes bookFloat {
0%,
100% {
transform: translateY(0) rotateY(-30deg);
}
50% {
transform: translateY(-20px) rotateY(-35deg);
}
}
@keyframes pageFlip {
0%,
100% {
transform: rotateY(0deg);
}
50% {
transform: rotateY(-160deg);
}
}
/* Magical particles */
.particle {
position: absolute;
width: 6px;
height: 6px;
background: var(--accent);
border-radius: 50%;
pointer-events: none;
opacity: 0;
}
@keyframes particleFloat {
0% {
transform: translate(0, 0) rotate(0deg);
opacity: 1;
}
100% {
transform: translate(var(--x), var(--y)) rotate(360deg);
opacity: 0;
}
}
/* Enhanced Creation Panel */
.creation-panel {
background: rgba(255, 255, 255, 0.92);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.2);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.creation-panel:hover {
transform: translateY(-5px);
box-shadow: 0 15px 40px rgba(0, 0, 0, 0.2);
}
/* Glowing input fields */
.input-field:focus {
box-shadow: 0 0 15px rgba(233, 128, 116, 0.3);
border-color: var(--accent);
animation: glow 1.5s ease-in-out infinite alternate;
}
@keyframes glow {
from {
box-shadow: 0 0 5px rgba(233, 128, 116, 0.3);
}
to {
box-shadow: 0 0 20px rgba(233, 128, 116, 0.6);
}
}
.terminology-section {
margin-top: 2rem;
padding: 1.5rem;
background: rgba(255, 255, 255, 0.8);
border-radius: 10px;
}
.terminology-title {
font-family: 'Cinzel Decorative', cursive;
font-size: 1.5rem;
color: var(--primary);
margin-bottom: 1rem;
}
.terminology-list {
list-style: none;
padding: 0;
}
.terminology-item {
margin-bottom: 0.8rem;
font-family: 'Crimson Pro', serif;
font-size: 1.1rem;
}
.term {
font-weight: 600;
color: var(--secondary);
}
.definition {
color: var(--text);
}
.moral-of-story{
text-align: center;
margin-top: 1rem;
font-style: italic;
display: none;
}
<div class="creation-panel">
<div class="creation-grid">
<div class="input-group">
<label class="input-label">Story Keywords</label>
<input type="text" id="keywords" class="input-field"
placeholder="Dragons, ancient prophecy, hidden kingdom...">
</div>
<div class="input-group">
<label class="input-label">Choose Genre</label>
<select id="genre" class="input-field">
<option value="fantasy">Mystical Fantasy</option>
<option value="mystery">Dark Mystery</option>
<option value="romance">Epic Romance</option>
<option value="sci-fi">Cosmic Science Fiction</option>
<option value="horror">Gothic Horror</option>
<option value="adventure">Grand Adventure</option>
<option value="fairytale">Enchanted Fairytale</option>
<option value="steampunk">Steampunk Adventure</option>
<option value="mythology">Mythological Epic</option>
</select>
</div>
<div class="input-group">
<label class="input-label">Story Length</label>
<select id="storyLength" class="input-field">
<option value="short">Short Tale (3 Chapters)</option>
<option value="medium">Medium Saga (5 Chapters)</option>
<option value="long">Epic Journey (7 Chapters)</option>
<option value="grand">Grand Epic (10 Chapters)</option>
</select>
</div>
</div>
<div class="advanced-options">
<div class="advanced-header">
<h3>Advanced Story Options</h3>
<i class="fas fa-caret-down"></i>
</div>
<div class="options-grid">
<div class="input-group">
<label class="input-label">Story Tone</label>
<select id="tone" class="input-field">
<option value="lighthearted">Lighthearted & Whimsical</option>
<option value="dramatic">Dark & Dramatic</option>
<option value="mysterious">Mysterious & Ethereal</option>
<option value="epic">Epic & Grand</option>
</select>
</div>
<div class="input-group">
<label class="input-label">Writing Style</label>
<select id="style" class="input-field">
<option value="descriptive">Rich & Descriptive</option>
<option value="concise">Clear & Concise</option>
<option value="poetic">Poetic & Flowing</option>
<option value="dramatic">Dynamic & Intense</option>
</select>
</div>
<div class="input-group">
<label class="input-label">Target Age Group</label>
<select id="ageGroup" class="input-field">
<option value="children">Children (8-12)</option>
<option value="young-adult">Young Adult (13-17)</option>
<option value="adult">Adult (18+)</option>
<option value="all-ages">All Ages</option>
</select>
</div>
</div>
<div class="options-grid" style="margin-top: 1.5rem;">
<div class="checkbox-group">
<input type="checkbox" id="includeMagic" class="custom-checkbox">
<label for="includeMagic">Include Magical Elements</label>
</div>
<div class="checkbox-group">
<input type="checkbox" id="includeRomance" class="custom-checkbox">
<label for="includeRomance">Include Romance</label>
</div>
<div class="checkbox-group">
<input type="checkbox" id="includeConflict" class="custom-checkbox">
<label for="includeConflict">Include Major Conflicts</label>
</div>
</div>
</div>
<button onclick="generateStory()" class="generate-btn">
<i class="fas fa-magic"></i> Weave Your Tale
</button>
</div>
<div class="book-display">
<div class="book-container">
<div class="book">
<div class="book-cover">
<img id="coverImage" alt="Book Cover" style="width: 100%; height: 100%; object-fit: cover;">
</div>
</div>
</div>
</div>
<div class="story-pages">
<div class="page-spread">
<div class="page" data-page="1">
<div class="page-decoration top-left">✧</div>
<img class="chapter-image" src="" alt="Chapter Illustration">
<h2 class="chapter-title"></h2>
<h3 class="moral-of-story"></h3>
<div class="chapter-content"></div>
<div class="page-decoration bottom-right">✧</div>
<div class="terminology-section" style="display: none;">
<h4 class="terminology-title">Magical Words & Meanings</h4>
<ul class="terminology-list"></ul>
</div>
<button class="nav-btn secondary regenerate-btn" style="margin: 10px auto; display: block;">
<i class="fas fa-sync-alt"></i> Regenerate Chapter
</button>
</div>
<div class="page" data-page="2">
<div class="page-decoration top-left">✧</div>
<img class="chapter-image" src="" alt="Chapter Illustration">
<h2 class="chapter-title"></h2>
<h3 class="moral-of-story"></h3>
<div class="chapter-content"></div>
<div class="page-decoration bottom-right">✧</div>
<div class="terminology-section" style="display: none;">
<h4 class="terminology-title">Magical Words & Meanings</h4>
<ul class="terminology-list"></ul>
</div>
<button class="nav-btn secondary regenerate-btn" style="margin: 10px auto; display: block;">
<i class="fas fa-sync-alt"></i> Regenerate Chapter
</button>
</div>
</div>
<div class="story-navigation">
<button class="nav-btn primary" id="showMoralBtn" onclick="showMoral()" style="display: none;">
<i class="fas fa-book-open"></i> Show Moral
</button>
<button class="nav-btn secondary" id="prevBtn" onclick="previousPages()" disabled>
<i class="fas fa-backward"></i> Previous
</button>
<button class="nav-btn primary" id="nextBtn" onclick="nextPages()">
Next <i class="fas fa-forward"></i>
</button>
<button class="nav-btn primary" id="continueBtn" onclick="continueStory()" style="display: none;">
<i class="fas fa-scroll"></i> Continue the Journey
</button>
<button class="nav-btn primary" id="readAloudBtn" onclick="readAloud()" style="display: block;">
<i class="fas fa-volume-up"></i> Read Aloud
</button>
<button class="nav-btn primary" id="stopReadAloudBtn" onclick="stopReadAloud()" style="display: none;">
<i class="fas fa-stop"></i> Stop Reading
</button>
<button class="nav-btn primary" id="downloadBtn" onclick="downloadStory()" style="display: block;">
<i class="fas fa-download"></i> Download Book
</button>
</div>
</div>
<!-- Replace the existing loading animation HTML with this -->
<div class="loading-overlay">
<div class="loading-content">
<div class="magic-book">
<div class="book-cover-animated">
<div class="book-page"></div>
</div>
</div>
<div class="loading-text">Weaving your magical tale</div>
<div class="progress-container">
<div class="progress-bar" id="progress-bar"></div>
</div>
</div>
</div>
<div class="toast" id="toast"></div>
<script>
let currentStory = null;
let currentPage = 0;
let speechUtterance = null;
// To store the current speech
// Create sparkle effect
function createSparkle() {
const sparkle = document.createElement('div');
sparkle.className = 'sparkle';
sparkle.innerHTML = '✧';
sparkle.style.left = Math.random() * 100 + 'vw';
sparkle.style.top = Math.random() * 100 + 'vh';
sparkle.style.fontSize = (Math.random() * 20 + 10) + 'px';
sparkle.style.color = `hsl(${Math.random() * 360}, 50%, 50%)`;
document.body.appendChild(sparkle);
setTimeout(() => sparkle.remove(), 1500);
}
setInterval(createSparkle, 300);
function displayCurrentPages() {
const leftPage = document.querySelector('.page:first-child');
const rightPage = document.querySelector('.page:last-child');
const chapters = currentStory.chapters;
if (currentPage < chapters.length) {
leftPage.style.opacity = '0';
rightPage.style.opacity = '0';
setTimeout(() => {
// Left page
leftPage.querySelector('.chapter-image').src = chapters[currentPage].image;
leftPage.querySelector('.chapter-title').textContent =
`Chapter ${chapters[currentPage].chapter_number}: ${chapters[currentPage].chapter_title}`;
leftPage.querySelector('.chapter-content').innerHTML = formatChapterContent(chapters[currentPage].content);
// Terminology for left page
const terminologyListLeft = leftPage.querySelector('.terminology-list');
terminologyListLeft.innerHTML = '';
if (Object.keys(chapters[currentPage].terminology).length > 0) {
leftPage.querySelector('.terminology-section').style.display = 'block';
for (const term in chapters[currentPage].terminology) {
const listItem = document.createElement('li');
listItem.className = 'terminology-item';
listItem.innerHTML = `<span class="term">${term}:</span> <span class="definition">${chapters[currentPage].terminology[term]}</span>`;
terminologyListLeft.appendChild(listItem);
}
} else {
leftPage.querySelector('.terminology-section').style.display = 'none';
}
// Regenerate button for left page
leftPage.querySelector('.regenerate-btn').onclick = () => regenerateChapter(currentPage);
// Right page
if (currentPage + 1 < chapters.length) {
rightPage.style.display = 'block';
rightPage.querySelector('.chapter-image').src = chapters[currentPage + 1].image;
rightPage.querySelector('.chapter-title').textContent =
`Chapter ${chapters[currentPage + 1].chapter_number}: ${chapters[currentPage + 1].chapter_title}`;
rightPage.querySelector('.chapter-content').innerHTML = formatChapterContent(chapters[currentPage + 1].content);
// Terminology for right page
const terminologyListRight = rightPage.querySelector('.terminology-list');
terminologyListRight.innerHTML = '';
if (Object.keys(chapters[currentPage + 1].terminology).length > 0) {
rightPage.querySelector('.terminology-section').style.display = 'block';
for (const term in chapters[currentPage + 1].terminology) {
const listItem = document.createElement('li');
listItem.className = 'terminology-item';
listItem.innerHTML = `<span class="term">${term}:</span> <span class="definition">${chapters[currentPage + 1].terminology[term]}</span>`;
terminologyListRight.appendChild(listItem);
}
} else {
rightPage.querySelector('.terminology-section').style.display = 'none';
}
// Regenerate button for right page
rightPage.querySelector('.regenerate-btn').onclick = () => regenerateChapter(currentPage + 1);
document.getElementById('continueBtn').style.display = 'none';
} else {
rightPage.style.display = 'none';
document.getElementById('continueBtn').style.display = 'block';
}
leftPage.style.opacity = '1';
rightPage.style.opacity = '1';
// Hide moral display when loading new pages
const leftPageMoral = document.querySelector('.page:first-child .moral-of-story');
const rightPageMoral = document.querySelector('.page:last-child .moral-of-story');
leftPageMoral.style.display = 'none';
if (rightPageMoral)
{
rightPageMoral.style.display = 'none';
}
}, 300);
}
document.getElementById('prevBtn').disabled = currentPage === 0;
document.getElementById('nextBtn').disabled = currentPage >= chapters.length - 2;
}
function formatChapterContent(content) {
// Split the content into paragraphs
const paragraphs = content.split('\n').filter(p => p.trim() !== '');
// Wrap each paragraph in a <p> tag
const formattedContent = paragraphs.map(p => `<p>${p}</p>`).join('');
return formattedContent;
}
function showLoading(message = 'Weaving your magical tale...') {
const overlay = document.querySelector('.loading-overlay');
const loadingText = document.querySelector('.loading-text');
const progressBar = document.getElementById('progress-bar');
loadingText.textContent = message;
progressBar.style.width = '0%';
overlay.style.display = 'flex';
}
function hideLoading() {
document.querySelector('.loading-overlay').style.display = 'none';
}
function showToast(message, duration = 3000) {
const toast = document.getElementById('toast');
toast.textContent = message;
toast.style.display = 'block';
setTimeout(() => {
toast.style.animation = 'slideOut 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55)';
setTimeout(() => {
toast.style.display = 'none';
toast.style.animation = '';
}, 500);
}, duration);
}
function enhancedPageTurn(direction) {
const pages = document.querySelectorAll('.page');
pages.forEach(page => {
page.style.transition = 'all 0.6s cubic-bezier(0.645, 0.045, 0.355, 1)';
page.style.transform = direction === 'forward'
? 'rotateY(-180deg)'
: 'rotateY(0deg)';
});
setTimeout(() => {
pages.forEach(page => {
page.style.transition = 'none';
page.style.transform = 'none';
});
}, 600);
}
function previousPages() {
if (currentPage >= 2) {
showLoading('Turning back the pages...');
enhancedPageTurn('backward');
currentPage -= 2;
setTimeout(() => {
displayCurrentPages();
hideLoading();
}, 800);
}
}
function nextPages() {
if (currentPage < currentStory.chapters.length - 2) {
showLoading('Turning to the next chapter...');
enhancedPageTurn('forward');
currentPage += 2;
setTimeout(() => {
displayCurrentPages();
hideLoading();
}, 800);
}
}
async function regenerateChapter(chapterIndex) {
showLoading('Reweaving the chapter...');
try {
const chapterNumber = currentStory.chapters[chapterIndex].chapter_number;
const response = await fetch('/regenerate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
story: currentStory,
chapter_number: chapterNumber,
tone: document.getElementById('tone').value,
style: document.getElementById('style').value,
includeMagic: document.getElementById('includeMagic').checked,
includeRomance: document.getElementById('includeRomance').checked,
includeConflict: document.getElementById('includeConflict').checked
})
});
const data = await response.json();
if (data.error) {
showToast(data.error);
} else {
// Replace the old chapter with the new one
currentStory.chapters[chapterIndex] = data.new_chapter;
// Preload the new image
await preloadImages([data.new_chapter.image]);
displayCurrentPages();
showToast('Chapter rewoven!');
}
} catch (error) {
showToast('A magical mishap occurred while regenerating the chapter. Please try again.');
console.error('Error:', error);
} finally {
hideLoading();
}
}
async function generateStory() {
const keywords = document.getElementById('keywords').value;
if (!keywords) {
showToast('Please share some keywords to begin your tale');
return;
}
showLoading();
try {
const storyConfig = {
keywords: keywords,
genre: document.getElementById('genre').value,
storyLength: document.getElementById('storyLength').value,
tone: document.getElementById('tone').value,
style: document.getElementById('style').value,
ageGroup: document.getElementById('ageGroup').value,
includeMagic: document.getElementById('includeMagic').checked,
includeRomance: document.getElementById('includeRomance').checked,
includeConflict: document.getElementById('includeConflict').checked
};
const response = await fetch('/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(storyConfig)
});
const data = await response.json();
currentStory = data.story;
// Preload images
await preloadImages(currentStory.chapters.map(chapter => chapter.image).concat(data.cover_image));
// Display the book
document.getElementById('coverImage').src = data.cover_image;
document.querySelector('.book-display').style.display = 'block';
document.querySelector('.book-cover').onclick = showPages;
// Add some magical effects
createMagicalEffect();
hideLoading();
showToast('Your magical tale awaits! Click the book cover to begin reading.');
} catch (error) {
hideLoading();
showToast('A magical mishap occurred. Please try again.');
console.error('Error:', error);
}
}
function createMagicalEffect() {
// Create multiple sparkles around the book
for (let i = 0; i < 20; i++) {
setTimeout(() => createSparkle(), i * 100);
}
}
function showPages() {
document.querySelector('.book-cover').classList.add('open');
setTimeout(() => {
document.querySelector('.book-display').style.display = 'none';
document.querySelector('.story-pages').style.display = 'block';
currentPage = 0;
displayCurrentPages();
// Show the "Show Moral" button
document.getElementById('showMoralBtn').style.display = 'block';
}, 1000);
}
async function continueStory() {
showLoading('Extending your magical journey...');
try {
const response = await fetch('/continue', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
previous_story: currentStory,
num_new_chapters: 3, // Add a fixed value for more chapters
tone: document.getElementById('tone').value,
style: document.getElementById('style').value,
includeMagic: document.getElementById('includeMagic').checked,
includeRomance: document.getElementById('includeRomance').checked,
includeConflict: document.getElementById('includeConflict').checked
})
});
const data = await response.json();
const newChapters = data.new_chapters;
// Preload new chapter images
await preloadImages(newChapters.map(chapter => chapter.image));
currentStory.chapters.push(...newChapters);
document.getElementById('continueBtn').style.display = 'none';
document.getElementById('nextBtn').disabled = false;
// Add magical effect for new chapters
createMagicalEffect();
hideLoading();
showToast('New chapters have been woven into your tale!');
displayCurrentPages();
} catch (error) {
hideLoading();
showToast('A magical mishap occurred while extending your tale. Please try again.');
console.error('Error:', error);
}
}
async function downloadStory() {
showLoading("Preparing your magical book for download...");
try {
const response = await fetch('/download', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
story: currentStory,
cover_image: document.getElementById('coverImage').src
})
});
if (response.ok) {
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${currentStory.title}.pdf`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
showToast('Your book is ready for download!');
} else {
const errorData = await response.json();
showToast(`Download failed: ${errorData.error || 'Unknown error'}`);
console.error('Download failed', errorData);
}
} catch (error) {
showToast('A magical mishap occurred during the download process.');
console.error('Download error:', error);
} finally {
hideLoading();
}
}
async function preloadImages(imageUrls) {
let loadedCount = 0;
const progressBar = document.getElementById('progress-bar');
const updateProgress = (loaded) => {
const progress = (loaded / imageUrls.length) * 100;
progressBar.style.width = `${progress}%`;
};
return new Promise((resolve) => {
const promises = imageUrls.map((url) => {
return new Promise((resolveImage) => {
const img = new Image();
img.src = url;
img.onload = () => {
loadedCount++;
updateProgress(loadedCount);
resolveImage();
};
img.onerror = () => {
console.error('Error loading image:', url);
loadedCount++;
updateProgress(loadedCount);
resolveImage();
};
});
});
Promise.all(promises).then(() => resolve(true));
});
}
// Enhanced book hover effect with depth
const book = document.querySelector('.book');
book.addEventListener('mousemove', (e) => {
const { left, top, width, height } = book.getBoundingClientRect();
const x = (e.clientX - left) / width;
const y = (e.clientY - top) / height;
const rotateY = -30 + (x - 0.5) * 20;
const rotateX = (y - 0.5) * 10;
const translateZ = Math.abs((x - 0.5) * 30);
book.style.transform = `
rotateY(${rotateY}deg)
rotateX(${rotateX}deg)
translateZ(${translateZ}px)
`;
});
book.addEventListener('mouseleave', () => {
book.style.transform = 'rotateY(-30deg) rotateX(0) translateZ(0)';
});
// Initialize advanced options toggle
document.querySelector('.advanced-header').addEventListener('click', function () {
const optionsGrid = this.nextElementSibling;
const caret = this.querySelector('.fa-caret-down');
if (optionsGrid.style.display === 'none') {
optionsGrid.style.display = 'grid';
caret.style.transform = 'rotate(180deg)';
} else {
optionsGrid.style.display = 'none';
caret.style.transform = 'rotate(0deg)';
}
});
// Add keyboard navigation
document.addEventListener('keydown', function (e) {
if (document.querySelector('.story-pages').style.display === 'block') {
if (e.key === 'ArrowLeft' && !document.getElementById('prevBtn').disabled) {
previousPages();
} else if (e.key === 'ArrowRight' && !document.getElementById('nextBtn').disabled) {
nextPages();
}
}
});
// Text-to-Speech functionality
function readAloud() {
if (!currentStory || !currentStory.chapters.length) {
showToast("No story available to read.");
return;
}
if (responsiveVoice.isPlaying()) {
stopReadAloud(); //stop current speech if button clicked while reading
return;
}
const currentChapterContent = getCurrentPageContent();
if (currentChapterContent) {
const firstFemaleVoice = responsiveVoice.getVoices().find(voice => voice.gender === "female");
responsiveVoice.speak(currentChapterContent, firstFemaleVoice ? firstFemaleVoice.name : "UK English Female", {
onstart: () => {
document.getElementById('readAloudBtn').style.display = 'none';
document.getElementById('stopReadAloudBtn').style.display = 'block';
},
onend: () => {
document.getElementById('readAloudBtn').style.display = 'block';
document.getElementById('stopReadAloudBtn').style.display = 'none';
},
onerror: (e) => {
console.error('ResponsiveVoice error:', e);
showToast("Stopped Reading Aloud.");
document.getElementById('readAloudBtn').style.display = 'block';
document.getElementById('stopReadAloudBtn').style.display = 'none';
}
});
}
}
function stopReadAloud() {
if (responsiveVoice && responsiveVoice.isPlaying()) {
responsiveVoice.cancel();
document.getElementById('readAloudBtn').style.display = 'block';
document.getElementById('stopReadAloudBtn').style.display = 'none';
}
}
function getCurrentPageContent() {
const leftPage = document.querySelector('.page:first-child');
const rightPage = document.querySelector('.page:last-child');
let content = "";
if (leftPage.style.opacity === '1') {
content += leftPage.querySelector('.chapter-title').textContent + ". ";
content += leftPage.querySelector('.chapter-content').textContent;
}
if (rightPage.style.display === 'block' && rightPage.style.opacity === '1') {
content += rightPage.querySelector('.chapter-title').textContent + ". ";
content += rightPage.querySelector('.chapter-content').textContent;
}
return content;
}
// Initialize Vanta.js background
VANTA.BIRDS({
el: "#vanta-background",
mouseControls: true,
touchControls: true,
gyroControls: false,
minHeight: 200.00,
minWidth: 200.00,
scale: 1.00,
scaleMobile: 1.00,
backgroundColor: 0xf4e4bc,
color1: 0x2a1b3d,
color2: 0xe98074,
colorMode: "lerpGradient",
birdSize: 1.50,
wingSpan: 15.00,
separation: 50.00,
alignment: 30.00,
cohesion: 30.00,
quantity: 3.00
});
// Create magical particles
function createParticle(x, y) {
const particle = document.createElement('div');
particle.className = 'particle';
document.body.appendChild(particle);
const angle = Math.random() * Math.PI * 2;
const velocity = 50 + Math.random() * 100;
const moveX = Math.cos(angle) * velocity;
const moveY = Math.sin(angle) * velocity;
particle.style.left = `${x}px`;
particle.style.top = `${y}px`;
particle.style.setProperty('--x', `${moveX}px`);
particle.style.setProperty('--y', `${moveY}px`);
particle.style.animation = 'particleFloat 1.5s ease-out forwards';
setTimeout(() => particle.remove(), 1500);
}
// Add particle effects to interactive elements
document.querySelectorAll('.input-field, .generate-btn').forEach(element => {
element.addEventListener('mouseover', (e) => {
const rect = element.getBoundingClientRect();
for (let i = 0; i < 3; i++) {
createParticle(
rect.left + Math.random() * rect.width,
rect.top + Math.random() * rect.height
);
}
});
});
function showMoral() {
const leftPageMoral = document.querySelector('.page:first-child .moral-of-story');
const rightPageMoral = document.querySelector('.page:last-child .moral-of-story');
const isMoralVisible = leftPageMoral.style.display === 'block';
leftPageMoral.style.display = isMoralVisible ? 'none' : 'block';
if (rightPageMoral)
{
rightPageMoral.style.display = isMoralVisible ? 'none' : 'block';
}
if (!isMoralVisible)
{
const leftPage = document.querySelector('.page:first-child');
leftPageMoral.textContent = currentStory.moral;
const rightPage = document.querySelector('.page:last-child');
if (rightPage)
{
rightPageMoral.textContent = currentStory.moral;
}
}
}
</script>
</body>
</html>
Copy first response
Not yet included in a published release.