Spaces:
Sleeping
Sleeping
# app.py - Final Version with Enhanced Performance & Light Purple Theme | |
import streamlit as st | |
import os | |
import time | |
import random | |
import numpy as np | |
import pandas as pd | |
import plotly.express as px | |
import plotly.graph_objects as go | |
from gtts import gTTS | |
import base64 | |
from PIL import Image | |
import io | |
import matplotlib.pyplot as plt | |
import requests | |
from io import BytesIO | |
import json | |
# Configure Streamlit page | |
st.set_page_config( | |
page_title="StoryCoder - Learn Python Through Stories", | |
page_icon="🧙♂️", | |
layout="wide", | |
initial_sidebar_state="expanded" | |
) | |
# Custom CSS with Light Purple Theme | |
st.markdown(""" | |
<style> | |
@import url('https://fonts.googleapis.com/css2?family=Comic+Neue:wght@700&family=Poppins:wght@400;600&display=swap'); | |
:root { | |
--primary: #8A2BE2; /* Violet */ | |
--secondary: #9370DB; /* Medium Purple */ | |
--accent: #FFD700; /* Gold */ | |
--dark: #4B0082; /* Indigo */ | |
--light: #E6E6FA; /* Lavender */ | |
--light2: #F5F0FF; /* Light Lavender */ | |
} | |
body { | |
background: linear-gradient(135deg, var(--light) 0%, var(--light2) 100%); | |
font-family: 'Poppins', sans-serif; | |
} | |
.stApp { | |
background: url('https://www.transparenttextures.com/patterns/soft-circle-scales.png'); | |
} | |
.story-box { | |
background-color: white; | |
border-radius: 20px; | |
padding: 25px; | |
box-shadow: 0 8px 16px rgba(74, 0, 128, 0.15); | |
border: 3px solid var(--accent); | |
margin-bottom: 25px; | |
} | |
.header { | |
color: var(--dark); | |
text-shadow: 1px 1px 2px rgba(0,0,0,0.1); | |
} | |
.concept-card { | |
background: linear-gradient(145deg, #ffffff, #f8f4ff); | |
border-radius: 15px; | |
padding: 15px; | |
margin: 10px 0; | |
border-left: 5px solid var(--secondary); | |
box-shadow: 0 4px 8px rgba(0,0,0,0.05); | |
} | |
.stButton>button { | |
background: linear-gradient(45deg, var(--primary), var(--secondary)); | |
color: white; | |
border-radius: 12px; | |
padding: 12px 28px; | |
font-weight: bold; | |
font-size: 18px; | |
border: none; | |
transition: all 0.3s; | |
font-family: 'Comic Neue', cursive; | |
} | |
.stButton>button:hover { | |
transform: translateY(-3px); | |
box-shadow: 0 6px 12px rgba(138, 43, 226, 0.3); | |
} | |
.stTextInput>div>div>input { | |
border-radius: 12px; | |
padding: 12px; | |
border: 2px solid var(--accent); | |
font-family: 'Poppins', sans-serif; | |
} | |
.tabs { | |
display: flex; | |
gap: 10px; | |
margin-bottom: 20px; | |
overflow-x: auto; | |
} | |
.tab { | |
padding: 12px 24px; | |
background-color: var(--secondary); | |
border-radius: 12px; | |
cursor: pointer; | |
font-weight: bold; | |
white-space: nowrap; | |
color: white; | |
transition: all 0.3s; | |
} | |
.tab:hover { | |
background-color: var(--primary); | |
} | |
.tab.active { | |
background-color: var(--primary); | |
box-shadow: 0 4px 8px rgba(0,0,0,0.1); | |
} | |
@media (max-width: 768px) { | |
.tabs { | |
flex-wrap: wrap; | |
} | |
} | |
.animation-container { | |
background: linear-gradient(135deg, #d8bfd8, #e6e6fa); | |
border-radius: 15px; | |
padding: 20px; | |
box-shadow: 0 8px 32px rgba(75, 0, 130, 0.2); | |
margin-bottom: 25px; | |
position: relative; | |
overflow: hidden; | |
} | |
.animation-canvas { | |
border-radius: 10px; | |
overflow: hidden; | |
margin: 0 auto; | |
display: block; | |
max-width: 100%; | |
} | |
.character { | |
font-size: 48px; | |
text-align: center; | |
margin: 10px 0; | |
} | |
.audio-player { | |
width: 100%; | |
margin: 20px 0; | |
border-radius: 20px; | |
background: #f0e6ff; | |
padding: 15px; | |
} | |
.animation-gif { | |
max-width: 100%; | |
border-radius: 10px; | |
box-shadow: 0 8px 16px rgba(0,0,0,0.15); | |
border: 2px solid white; | |
} | |
.ai-animation { | |
border: 3px solid var(--accent); | |
border-radius: 15px; | |
padding: 15px; | |
background: white; | |
margin: 20px 0; | |
} | |
.explanation-box { | |
background: linear-gradient(135deg, #f0e6ff, #e6d8ff); | |
border-radius: 15px; | |
padding: 20px; | |
margin: 20px 0; | |
border-left: 5px solid var(--primary); | |
box-shadow: 0 4px 12px rgba(0,0,0,0.1); | |
} | |
.explanation-header { | |
color: var(--dark); | |
display: flex; | |
align-items: center; | |
gap: 10px; | |
margin-bottom: 15px; | |
} | |
.magic-pulse { | |
animation: pulse 2s infinite; | |
} | |
@keyframes pulse { | |
0% { transform: scale(1); } | |
50% { transform: scale(1.05); } | |
100% { transform: scale(1); } | |
} | |
.concept-highlight { | |
background: linear-gradient(120deg, #e0d6ff, #d8c8ff); | |
padding: 3px 8px; | |
border-radius: 6px; | |
font-weight: bold; | |
} | |
</style> | |
""", unsafe_allow_html=True) | |
# Concept database | |
CONCEPTS = { | |
"loop": { | |
"name": "Loop", | |
"emoji": "🔄", | |
"description": "Loops repeat actions multiple times", | |
"example": "for i in range(5):\n print('Hello!')", | |
"color": "#8A2BE2", | |
"explanation": "A loop is like a magic spell that makes something happen again and again. In programming, we use loops when we want to repeat an action multiple times without writing the same code over and over." | |
}, | |
"conditional": { | |
"name": "Conditional", | |
"emoji": "❓", | |
"description": "Conditionals make decisions in code", | |
"example": "if sunny:\n go_outside()\nelse:\n stay_inside()", | |
"color": "#9370DB", | |
"explanation": "Conditionals are like crossroads in a story where you choose which path to take. In programming, we use 'if' statements to make decisions based on certain conditions, just like choosing what to wear based on the weather." | |
}, | |
"function": { | |
"name": "Function", | |
"emoji": "✨", | |
"description": "Functions are reusable blocks of code", | |
"example": "def greet(name):\n print(f'Hello {name}!')", | |
"color": "#DA70D6", | |
"explanation": "Functions are like magic spells you can create and reuse whenever you need them. They help us organize code into reusable blocks so we don't have to write the same thing multiple times." | |
}, | |
"variable": { | |
"name": "Variable", | |
"emoji": "📦", | |
"description": "Variables store information", | |
"example": "score = 10\nplayer = 'Alex'", | |
"color": "#BA55D3", | |
"explanation": "Variables are like labeled boxes where you can store information. They help us remember values and use them later in our code, just like remembering a character's name in a story." | |
}, | |
"list": { | |
"name": "List", | |
"emoji": "📝", | |
"description": "Lists store collections of items", | |
"example": "fruits = ['apple', 'banana', 'orange']", | |
"color": "#9932CC", | |
"explanation": "Lists are like magical scrolls that can hold multiple items. In programming, we use lists to store collections of related things, like a wizard's inventory of potions." | |
} | |
} | |
# Updated animation examples with reliable URLs | |
ANIMATION_EXAMPLES = { | |
"loop": "https://media.giphy.com/media/3o7abKhOpu0NwenH3O/giphy.gif", | |
"conditional": "https://media.giphy.com/media/l0HlG8vJXW0X5yX4s/giphy.gif", | |
"function": "https://media.giphy.com/media/3o7TKsQ8UQ4l4LhGz6/giphy.gif", | |
"variable": "https://media.giphy.com/media/3o7TKsQ8UQ4l4LhGz6/giphy.gif", | |
"list": "https://media.giphy.com/media/3o7abKhOpu0NwenH3O/giphy.gif" | |
} | |
# Fallback images if URLs fail | |
FALLBACK_IMAGES = { | |
"loop": "https://i.ibb.co/4sY7d0j/loop.gif", | |
"conditional": "https://i.ibb.co/8Xg7zY6/conditional.gif", | |
"function": "https://i.ibb.co/7yVnZ8C/function.gif", | |
"variable": "https://i.ibb.co/7yVnZ8C/function.gif", | |
"list": "https://i.ibb.co/4sY7d0j/loop.gif" | |
} | |
def check_url(url): | |
"""Check if a URL is valid and accessible""" | |
try: | |
response = requests.head(url, timeout=5) | |
return response.status_code == 200 | |
except: | |
return False | |
def create_animation_preview(concept): | |
"""Create an animation preview for the concept with fallback""" | |
try: | |
# Check if the URL is valid | |
url = ANIMATION_EXAMPLES.get(concept, "") | |
if url and check_url(url): | |
return url | |
# Use fallback if primary URL fails | |
return FALLBACK_IMAGES.get(concept, FALLBACK_IMAGES["loop"]) | |
except: | |
return FALLBACK_IMAGES["loop"] | |
def analyze_story(story): | |
"""Analyze story and identify programming concepts""" | |
story_lower = story.lower() | |
detected_concepts = [] | |
# Check for loops | |
if any(word in story_lower for word in ["times", "repeat", "again", "multiple", "each"]): | |
detected_concepts.append("loop") | |
# Check for conditionals | |
if any(word in story_lower for word in ["if", "when", "unless", "whether", "decide"]): | |
detected_concepts.append("conditional") | |
# Check for functions | |
if any(word in story_lower for word in ["make", "create", "do", "perform", "cast", "spell"]): | |
detected_concepts.append("function") | |
# Check for variables | |
if any(word in story_lower for word in ["is", "has", "set to", "value", "named", "called"]): | |
detected_concepts.append("variable") | |
# Check for lists | |
if any(word in story_lower for word in ["and", "many", "several", "collection", "items", "group"]): | |
detected_concepts.append("list") | |
return list(set(detected_concepts)) | |
def extract_count_from_story(story): | |
"""Extract a number from the story to use in animations""" | |
for word in story.split(): | |
if word.isdigit(): | |
return min(int(word), 10) | |
return 3 # Default value | |
def text_to_speech_custom(text, filename="story_audio.mp3"): | |
"""Convert text to speech using gTTS (faster and reliable)""" | |
try: | |
tts = gTTS(text=text, lang='en') | |
tts.save(filename) | |
return filename | |
except Exception as e: | |
st.error(f"Audio creation error: {str(e)}") | |
return None | |
def autoplay_audio(file_path): | |
"""Autoplay audio in Streamlit""" | |
with open(file_path, "rb") as f: | |
data = f.read() | |
b64 = base64.b64encode(data).decode() | |
md = f""" | |
<audio autoplay> | |
<source src="data:audio/mp3;base64,{b64}" type="audio/mp3"> | |
</audio> | |
""" | |
st.markdown(md, unsafe_allow_html=True) | |
def generate_animation_code(story, concept): | |
"""Generate Python animation code based on story""" | |
try: | |
count = extract_count_from_story(story) | |
short_story = story[:20] + '...' if len(story) > 20 else story | |
# Sample code based on concept | |
if concept == "loop": | |
code = f""" | |
# Loop Animation: Repeating Actions | |
import time | |
def animate_story(): | |
actions = {count} | |
print("Story: {short_story}") | |
print("Concept: Looping {count} times") | |
for i in range(actions): | |
print(f"Action {{i+1}}: Performing story action") | |
# Animation code would go here | |
time.sleep(0.5) | |
print("Story animation complete!") | |
animate_story() | |
""" | |
description = "Looping through actions multiple times" | |
visual_cue = "Repeating actions in a loop" | |
elif concept == "conditional": | |
code = f""" | |
# Conditional Animation: Making Decisions | |
import random | |
print("Story: {short_story}") | |
print("Concept: Making decisions based on conditions") | |
condition = random.choice([True, False]) | |
print(f"Condition is {{condition}}") | |
if condition: | |
print("Path 1: Following the true branch") | |
# True branch animation | |
else: | |
print("Path 2: Following the false branch") | |
# False branch animation | |
print("Story animation complete!") | |
""" | |
description = "Making decisions based on conditions" | |
visual_cue = "Branching paths based on conditions" | |
elif concept == "function": | |
code = f""" | |
# Function Animation: Reusable Actions | |
import time | |
print("Story: {short_story}") | |
print("Concept: Creating reusable functions") | |
def perform_action(): | |
print("Performing story action") | |
# Action animation code | |
# Call the function multiple times | |
for _ in range({count}): | |
perform_action() | |
time.sleep(0.3) | |
print("Story animation complete!") | |
""" | |
description = "Reusing code with functions" | |
visual_cue = "Calling a reusable function" | |
elif concept == "variable": | |
code = f""" | |
# Variable Animation: Storing Information | |
import time | |
print("Story: {short_story}") | |
print("Concept: Using variables to store information") | |
character = "Hero" | |
score = 10 | |
inventory = ["sword", "shield", "potion"] | |
print(f"Welcome {{character}}! You have {{score}} points.") | |
print(f"Your inventory: {{inventory}}") | |
for item in inventory: | |
print(f"Using {{item}}...") | |
time.sleep(0.5) | |
print("Story animation complete!") | |
""" | |
description = "Storing information in variables" | |
visual_cue = "Using stored values" | |
else: # list | |
code = f""" | |
# List Animation: Managing Collections | |
import time | |
print("Story: {short_story}") | |
print("Concept: Working with lists of items") | |
items = ["item1", "item2", "item3", "item4", "item5"][:{count}] | |
print(f"Collection has {{len(items)}} items") | |
for i, item in enumerate(items): | |
print(f"Processing item {{i+1}}: {{item}}") | |
time.sleep(0.4) | |
print("Story animation complete!") | |
""" | |
description = "Managing collections of items" | |
visual_cue = "Processing multiple items" | |
return code, description, visual_cue | |
except Exception as e: | |
return f"# Error generating code\nprint('Could not generate code: {str(e)}')", "", "" | |
def create_interactive_animation(story, concept): | |
"""Create an interactive animation using Plotly""" | |
try: | |
# Create animation data | |
frames = [] | |
count = extract_count_from_story(story) | |
for i in range(count): | |
frames.append({ | |
"frame": i, | |
"x": np.random.uniform(1, 9), | |
"y": np.random.uniform(1, 9), | |
"size": np.random.uniform(20, 40), | |
"label": f"Action {i+1}", | |
"color": f"hsl({i*40}, 100%, 50%)" | |
}) | |
df = pd.DataFrame(frames) | |
# Create animated scatter plot | |
fig = px.scatter( | |
df, | |
x="x", | |
y="y", | |
animation_frame="frame", | |
text="label", | |
size="size", | |
size_max=45, | |
color="color", | |
color_discrete_sequence=px.colors.qualitative.Pastel, | |
range_x=[0, 10], | |
range_y=[0, 10], | |
title=f"Interactive Animation: {story[:40]}{'...' if len(story) > 40 else ''}" | |
) | |
# Customize layout | |
fig.update_layout( | |
showlegend=False, | |
plot_bgcolor='rgba(245, 240, 255, 0.8)', | |
paper_bgcolor='rgba(245, 240, 255, 0.8)', | |
width=800, | |
height=600, | |
xaxis=dict(showgrid=False, zeroline=False, visible=False), | |
yaxis=dict(showgrid=False, zeroline=False, visible=False), | |
font_family="Poppins" | |
) | |
fig.update_traces( | |
textfont_size=18, | |
textposition='middle center', | |
marker=dict(sizemode='diameter') | |
) | |
return fig | |
except Exception as e: | |
st.error(f"Interactive animation error: {str(e)}") | |
return None | |
def generate_concept_explanation(story, concept, code_description, visual_cue): | |
"""Generate a detailed explanation of the programming concept with examples""" | |
concept_info = CONCEPTS.get(concept, {}) | |
explanation = f""" | |
Let me explain what's happening in your story and how it relates to programming! | |
<div class='concept-highlight'>Your story</div>: "{story[:100]}..." | |
<div class='concept-highlight'>Programming concept</div>: {concept_info.get('name', 'Programming')} | |
{concept_info.get('explanation', 'This is a fundamental programming concept.')} | |
<div class='concept-highlight'>In our animation</div>: | |
- {visual_cue} | |
- This represents: {code_description} | |
<div class='concept-highlight'>How it works in code</div>: | |
We use {concept_info.get('name', 'this concept')} like this: | |
``` | |
{concept_info.get('example', 'Example code will appear here')} | |
``` | |
<div class='concept-highlight'>Real-world use</div>: | |
You might use this concept when: | |
- Creating games with repeating actions (loops) | |
- Making decisions in apps (conditionals) | |
- Building reusable components (functions) | |
- Storing player information (variables) | |
- Managing collections of data (lists) | |
Try to spot this concept in other stories you create! | |
""" | |
return explanation | |
def main(): | |
"""Main application function""" | |
st.title("🧙♂️ StoryCoder - Learn Python Through Stories!") | |
st.subheader("Turn your story into an animation and discover coding secrets with voice explanations!") | |
# Initialize session state | |
if 'story' not in st.session_state: | |
st.session_state.story = "" | |
if 'concepts' not in st.session_state: | |
st.session_state.concepts = [] | |
if 'interactive_animation' not in st.session_state: | |
st.session_state.interactive_animation = None | |
if 'animation_code' not in st.session_state: | |
st.session_state.animation_code = "" | |
if 'code_description' not in st.session_state: | |
st.session_state.code_description = "" | |
if 'visual_cue' not in st.session_state: | |
st.session_state.visual_cue = "" | |
if 'audio_file' not in st.session_state: | |
st.session_state.audio_file = None | |
if 'active_tab' not in st.session_state: | |
st.session_state.active_tab = "story" | |
if 'explanation_audio' not in st.session_state: | |
st.session_state.explanation_audio = None | |
if 'concept_explanation' not in st.session_state: | |
st.session_state.concept_explanation = "" | |
# Create tabs | |
tabs = st.empty() | |
tab_cols = st.columns(5) | |
with tab_cols[0]: | |
if st.button("📖 Create Story", key="tab_story"): | |
st.session_state.active_tab = "story" | |
with tab_cols[1]: | |
if st.button("🎬 Animation", key="tab_animation"): | |
st.session_state.active_tab = "animation" | |
with tab_cols[2]: | |
if st.button("🔍 Concepts", key="tab_concepts"): | |
st.session_state.active_tab = "concepts" | |
with tab_cols[3]: | |
if st.button("💻 Code", key="tab_code"): | |
st.session_state.active_tab = "code" | |
with tab_cols[4]: | |
if st.button("🔄 Reset", key="tab_reset"): | |
st.session_state.story = "" | |
st.session_state.concepts = [] | |
st.session_state.interactive_animation = None | |
st.session_state.animation_code = "" | |
st.session_state.code_description = "" | |
st.session_state.visual_cue = "" | |
st.session_state.audio_file = None | |
st.session_state.explanation_audio = None | |
st.session_state.concept_explanation = "" | |
st.session_state.active_tab = "story" | |
# Story creation tab | |
if st.session_state.active_tab == "story": | |
with st.container(): | |
st.header("📖 Create Your Story") | |
st.write("Write a short story (2-5 sentences) and I'll turn it into an animation with voice explanations!") | |
story = st.text_area( | |
"Your story:", | |
height=200, | |
placeholder="Once upon a time, a rabbit hopped 3 times to reach a carrot...", | |
value=st.session_state.story, | |
key="story_input" | |
) | |
if st.button("✨ Create Animation!", use_container_width=True, key="create_animation"): | |
if len(story) < 10: | |
st.error("Your story needs to be at least 10 characters long!") | |
else: | |
st.session_state.story = story | |
with st.spinner("🧠 Analyzing your story for coding concepts..."): | |
st.session_state.concepts = analyze_story(story) | |
# Get the main concept | |
main_concept = st.session_state.concepts[0] if st.session_state.concepts else "variable" | |
with st.spinner("🚀 Creating interactive animation..."): | |
st.session_state.interactive_animation = create_interactive_animation( | |
story, main_concept | |
) | |
with st.spinner("💻 Generating animation code..."): | |
st.session_state.animation_code, st.session_state.code_description, st.session_state.visual_cue = generate_animation_code( | |
story, main_concept | |
) | |
with st.spinner("🔊 Creating audio narration..."): | |
audio_text = f"Your story: {story}. This demonstrates the programming concept: {st.session_state.code_description}" | |
st.session_state.audio_file = text_to_speech_custom( | |
audio_text | |
) | |
with st.spinner("🧠 Generating concept explanation..."): | |
st.session_state.concept_explanation = generate_concept_explanation( | |
story, | |
main_concept, | |
st.session_state.code_description, | |
st.session_state.visual_cue | |
) | |
with st.spinner("🔊 Creating explanation audio..."): | |
explanation_text = st.session_state.concept_explanation.replace('<div class="concept-highlight">', '').replace('</div>', '') | |
st.session_state.explanation_audio = text_to_speech_custom( | |
explanation_text, | |
"concept_explanation.mp3" | |
) | |
st.session_state.active_tab = "animation" | |
st.rerun() | |
# Show examples | |
st.subheader("✨ Story Examples") | |
col1, col2, col3 = st.columns(3) | |
with col1: | |
st.caption("Loop Example") | |
st.code('"A dragon breathes fire 5 times at the castle"', language="text") | |
st.image(create_animation_preview("loop"), | |
use_container_width=True, | |
caption="Loop Animation Preview") | |
with col2: | |
st.caption("Conditional Example") | |
st.code('"If it rains, the cat stays inside, else it goes out"', language="text") | |
st.image(create_animation_preview("conditional"), | |
use_container_width=True, | |
caption="Conditional Animation Preview") | |
with col3: | |
st.caption("Function Example") | |
st.code('"A wizard casts a spell to make flowers grow"', language="text") | |
st.image(create_animation_preview("function"), | |
use_container_width=True, | |
caption="Function Animation Preview") | |
# Animation tab | |
elif st.session_state.active_tab == "animation": | |
st.header("🎬 Your Story Animation") | |
if not st.session_state.story: | |
st.warning("Please create a story first!") | |
st.session_state.active_tab = "story" | |
st.rerun() | |
# Display interactive animation | |
st.subheader("🎮 Interactive Animation") | |
if st.session_state.interactive_animation: | |
st.plotly_chart(st.session_state.interactive_animation, use_container_width=True) | |
else: | |
st.info("Interactive animation preview. The real animation would run on your computer!") | |
concept = st.session_state.concepts[0] if st.session_state.concepts else "loop" | |
st.image(create_animation_preview(concept), | |
use_container_width=True) | |
# Animation concept preview | |
st.subheader("📽️ Animation Concept Preview") | |
if st.session_state.concepts: | |
concept = st.session_state.concepts[0] | |
st.image(create_animation_preview(concept), | |
caption=f"{CONCEPTS[concept]['name']} Animation Example", | |
use_container_width=True) | |
else: | |
st.info("Animation preview would appear here") | |
# Play audio narration | |
st.subheader("🔊 Story Narration") | |
if st.session_state.audio_file: | |
audio_bytes = open(st.session_state.audio_file, 'rb').read() | |
st.audio(audio_bytes, format='audio/mp3') | |
if st.button("▶️ Play Story Automatically", use_container_width=True): | |
autoplay_audio(st.session_state.audio_file) | |
else: | |
st.info("Audio narration would play automatically here") | |
# Concept explanation section | |
if st.session_state.concepts and st.session_state.concept_explanation: | |
st.subheader("🎓 Concept Explanation") | |
concept = st.session_state.concepts[0] | |
details = CONCEPTS.get(concept, {}) | |
st.markdown(f""" | |
<div class="explanation-box"> | |
<div class="explanation-header"> | |
<span style="font-size:36px;">{details.get('emoji', '✨')}</span> | |
<h3>Understanding {details.get('name', 'Programming')} Concept</h3> | |
</div> | |
{st.session_state.concept_explanation} | |
</div> | |
""", unsafe_allow_html=True) | |
if st.session_state.explanation_audio: | |
explanation_bytes = open(st.session_state.explanation_audio, 'rb').read() | |
st.audio(explanation_bytes, format='audio/mp3') | |
if st.button("▶️ Play Concept Explanation", use_container_width=True): | |
autoplay_audio(st.session_state.explanation_audio) | |
st.success("✨ Animation created successfully!") | |
st.caption("This animation was generated with Python code based on your story!") | |
if st.button("Reveal Coding Secrets!", use_container_width=True): | |
st.session_state.active_tab = "concepts" | |
st.rerun() | |
# Concepts tab | |
elif st.session_state.active_tab == "concepts": | |
st.header("🔍 Coding Concepts in Your Story") | |
st.subheader("We secretly used these programming concepts:") | |
if not st.session_state.concepts: | |
st.warning("No concepts detected in your story! Try adding words like '3 times', 'if', or 'make'.") | |
else: | |
for concept in st.session_state.concepts: | |
if concept in CONCEPTS: | |
details = CONCEPTS[concept] | |
st.markdown(f""" | |
<div class="concept-card" style="border-left: 5px solid {details['color']};"> | |
<div style="display:flex; align-items:center; gap:15px;"> | |
<span style="font-size:36px;">{details['emoji']}</span> | |
<h3 style="color:{details['color']};">{details['name']}</h3> | |
</div> | |
<p>{details['description']}</p> | |
<pre style="background:#f8f4ff; padding:10px; border-radius:8px;">{details['example']}</pre> | |
<p><strong>Explanation:</strong> {details.get('explanation', 'Learn how this concept works!')}</p> | |
</div> | |
""", unsafe_allow_html=True) | |
# Show animation preview for the concept | |
st.image(create_animation_preview(concept), | |
caption=f"{details['name']} Animation Example", | |
use_container_width=True) | |
# Play explanation if available | |
if st.session_state.explanation_audio: | |
st.subheader("🔊 Full Concept Explanation") | |
explanation_bytes = open(st.session_state.explanation_audio, 'rb').read() | |
st.audio(explanation_bytes, format='audio/mp3') | |
if st.button("▶️ Play Full Explanation", use_container_width=True): | |
autoplay_audio(st.session_state.explanation_audio) | |
if st.button("See the Magic Code!", use_container_width=True): | |
st.session_state.active_tab = "code" | |
st.rerun() | |
# Code tab | |
elif st.session_state.active_tab == "code": | |
st.header("💻 The Magic Code Behind Your Animation") | |
st.write("Here's the Python code that would create your animation:") | |
if st.session_state.animation_code: | |
st.subheader(st.session_state.code_description) | |
st.markdown(f"**Visual Cue:** {st.session_state.visual_cue}") | |
st.code(st.session_state.animation_code, language="python") | |
# Download button | |
st.download_button( | |
label="📥 Download Animation Code", | |
data=st.session_state.animation_code, | |
file_name="story_animation.py", | |
mime="text/python", | |
use_container_width=True | |
) | |
st.info("💡 To run this animation on your computer:") | |
st.markdown(""" | |
1. Install Python from [python.org](https://python.org) | |
2. Install required libraries: `pip install matplotlib numpy` | |
3. Copy the code above into a file named `animation.py` | |
4. Run it with: `python animation.py` | |
""") | |
st.success("🎉 When you run this code, you'll see your story come to life!") | |
# Show what the animation would look like | |
st.subheader("🎬 What Your Animation Would Look Like") | |
concept = st.session_state.concepts[0] if st.session_state.concepts else "loop" | |
st.image(create_animation_preview(concept), | |
caption="This is similar to what your animation would look like", | |
use_container_width=True) | |
# Code explanation section | |
if st.session_state.concept_explanation: | |
st.subheader("🎓 Code Concept Explanation") | |
concept = st.session_state.concepts[0] if st.session_state.concepts else "loop" | |
details = CONCEPTS.get(concept, {}) | |
st.markdown(f""" | |
<div class="explanation-box"> | |
<div class="explanation-header"> | |
<span style="font-size:36px;">{details.get('emoji', '✨')}</span> | |
<h3>Understanding the Code</h3> | |
</div> | |
{st.session_state.concept_explanation} | |
</div> | |
""", unsafe_allow_html=True) | |
# Play explanation audio | |
if st.session_state.explanation_audio: | |
explanation_bytes = open(st.session_state.explanation_audio, 'rb').read() | |
st.audio(explanation_bytes, format='audio/mp3') | |
if st.button("▶️ Play Code Explanation", use_container_width=True): | |
autoplay_audio(st.session_state.explanation_audio) | |
else: | |
st.warning("No code generated yet!") | |
if st.button("✨ Create Another Story!", use_container_width=True): | |
st.session_state.active_tab = "story" | |
st.session_state.story = "" | |
st.rerun() | |
if __name__ == "__main__": | |
main() |