File size: 18,871 Bytes
c969520
65eb8e4
2d70a3f
688c6f3
 
2d70a3f
c969520
 
 
 
b59006d
 
688c6f3
b59006d
688c6f3
b59006d
 
688c6f3
 
 
 
b59006d
688c6f3
 
b59006d
 
 
 
 
 
 
 
 
688c6f3
b59006d
 
 
 
688c6f3
b59006d
 
 
688c6f3
b59006d
 
 
 
 
 
 
 
688c6f3
b59006d
 
 
 
688c6f3
b59006d
 
 
 
 
 
 
 
688c6f3
b59006d
 
 
 
 
 
 
 
 
 
688c6f3
b59006d
 
 
 
4541cc1
b59006d
 
 
 
 
4541cc1
b59006d
 
 
 
 
 
4541cc1
b59006d
 
 
 
 
 
 
 
4541cc1
b59006d
 
 
 
4541cc1
b59006d
 
 
 
4541cc1
2d70a3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c969520
 
 
 
 
 
 
2d70a3f
b59006d
 
4541cc1
b59006d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4541cc1
b59006d
4541cc1
2d70a3f
c969520
 
 
 
 
 
 
 
 
 
2d70a3f
b59006d
2d70a3f
b59006d
 
4541cc1
b59006d
 
 
4541cc1
b59006d
 
 
4541cc1
b59006d
 
 
4541cc1
b59006d
 
 
 
 
 
 
 
 
688c6f3
c969520
 
 
 
 
 
 
 
 
af8eab3
2d70a3f
c969520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34f7b23
c969520
 
 
 
34f7b23
c969520
 
 
 
34f7b23
c969520
 
34f7b23
c969520
 
 
 
 
34f7b23
c969520
 
 
 
 
 
 
 
 
4541cc1
c969520
 
 
 
34f7b23
b59006d
 
 
67aee2f
2d70a3f
 
 
 
b59006d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c969520
b59006d
 
 
 
 
 
 
 
 
c969520
b59006d
 
c969520
 
b59006d
 
 
 
 
 
 
 
 
 
 
 
 
 
c969520
 
34f7b23
 
b59006d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c969520
b59006d
 
 
 
 
 
 
4541cc1
b59006d
 
 
 
 
 
 
4541cc1
b59006d
 
 
 
 
 
 
 
c969520
 
b59006d
 
 
 
2d70a3f
4541cc1
b59006d
 
 
 
 
 
 
 
 
 
 
34f7b23
b59006d
 
 
 
 
c969520
b59006d
 
2d70a3f
b59006d
 
2d70a3f
 
 
 
 
 
c969520
 
 
 
 
 
 
b59006d
 
 
 
 
 
2d70a3f
b59006d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d70a3f
b59006d
 
 
 
 
 
34f7b23
c969520
 
 
 
 
34f7b23
c969520
 
34f7b23
 
c969520
 
 
 
 
34f7b23
c969520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34f7b23
 
 
 
 
 
 
 
 
 
 
 
 
4541cc1
b59006d
 
 
2d70a3f
4541cc1
b59006d
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
# app.py - Final Working Version
import streamlit as st
import os
import time
import random
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib import rc
import base64
from PIL import Image
import io

# Configure Streamlit page
st.set_page_config(
    page_title="StoryCoder - Learn Python Through Stories",
    page_icon="πŸ§™β€β™‚οΈ",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Custom CSS for colorful UI
st.markdown("""
<style>
    @import url('https://fonts.googleapis.com/css2?family=Comic+Neue:wght@700&display=swap');
    
    :root {
        --primary: #FF6B6B;
        --secondary: #4ECDC4;
        --accent: #FFD166;
        --dark: #1A535C;
        --light: #F7FFF7;
    }
    
    body {
        background: linear-gradient(135deg, var(--light) 0%, #E8F4F8 100%);
        font-family: 'Comic Neue', cursive;
    }
    
    .stApp {
        background: url('https://www.transparenttextures.com/patterns/cartographer.png');
    }
    
    .story-box {
        background-color: white;
        border-radius: 20px;
        padding: 25px;
        box-shadow: 0 8px 16px rgba(26, 83, 92, 0.15);
        border: 3px solid var(--accent);
        margin-bottom: 25px;
    }
    
    .header {
        color: var(--dark);
        text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
    }
    
    .concept-card {
        background: linear-gradient(145deg, #ffffff, #f0f0f0);
        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: 10px 24px;
        font-weight: bold;
        font-size: 18px;
        border: none;
        transition: all 0.3s;
    }
    
    .stButton>button:hover {
        transform: scale(1.05);
        box-shadow: 0 6px 12px rgba(0,0,0,0.15);
    }
    
    .stTextInput>div>div>input {
        border-radius: 12px;
        padding: 12px;
        border: 2px solid var(--accent);
    }
    
    .tabs {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
        overflow-x: auto;
    }
    
    .tab {
        padding: 10px 20px;
        background-color: var(--accent);
        border-radius: 10px;
        cursor: pointer;
        font-weight: bold;
        white-space: nowrap;
    }
    
    .tab.active {
        background-color: var(--secondary);
        color: white;
    }
    
    @media (max-width: 768px) {
        .tabs {
            flex-wrap: wrap;
        }
    }
    
    .animation-container {
        background-color: #1a1a2e;
        border-radius: 15px;
        padding: 20px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
        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;
    }
</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": "#FF9E6D"
    },
    "conditional": {
        "name": "Conditional",
        "emoji": "❓",
        "description": "Conditionals make decisions in code",
        "example": "if sunny:\n    go_outside()\nelse:\n    stay_inside()",
        "color": "#4ECDC4"
    },
    "function": {
        "name": "Function",
        "emoji": "✨",
        "description": "Functions are reusable blocks of code",
        "example": "def greet(name):\n    print(f'Hello {name}!')",
        "color": "#FFD166"
    },
    "variable": {
        "name": "Variable",
        "emoji": "πŸ“¦",
        "description": "Variables store information",
        "example": "score = 10\nplayer = 'Alex'",
        "color": "#FF6B6B"
    },
    "list": {
        "name": "List",
        "emoji": "πŸ“",
        "description": "Lists store collections of items",
        "example": "fruits = ['apple', 'banana', 'orange']",
        "color": "#1A535C"
    }
}

# Character database
CHARACTERS = [
    {"name": "rabbit", "emoji": "🐰", "color": "#FFB6C1"},
    {"name": "dragon", "emoji": "πŸ‰", "color": "#FF6347"},
    {"name": "cat", "emoji": "🐱", "color": "#DDA0DD"},
    {"name": "dog", "emoji": "🐢", "color": "#FFD700"},
    {"name": "knight", "emoji": "🀺", "color": "#87CEEB"},
    {"name": "wizard", "emoji": "πŸ§™", "color": "#98FB98"},
    {"name": "scientist", "emoji": "πŸ”¬", "color": "#20B2AA"},
    {"name": "pirate", "emoji": "πŸ΄β€β˜ οΈ", "color": "#FFA500"}
]

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"]):
        detected_concepts.append("loop")
    
    # Check for conditionals
    if any(word in story_lower for word in ["if", "when", "unless", "whether"]):
        detected_concepts.append("conditional")
    
    # Check for functions
    if any(word in story_lower for word in ["make", "create", "do", "perform", "cast"]):
        detected_concepts.append("function")
    
    # Check for variables
    if any(word in story_lower for word in ["is", "has", "set to", "value"]):
        detected_concepts.append("variable")
    
    # Check for lists
    if any(word in story_lower for word in ["and", "many", "several", "collection", "items"]):
        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 create_animation(story, concepts):
    """Create a matplotlib animation based on the story and concepts"""
    try:
        # Choose a random character
        character = random.choice(CHARACTERS)
        count = extract_count_from_story(story)
        
        # Create figure and axis
        fig, ax = plt.subplots(figsize=(10, 6), facecolor='#f0f8ff')
        ax.set_xlim(0, 10)
        ax.set_ylim(0, 10)
        ax.axis('off')
        
        # Add title
        fig.suptitle('Your Story Animation', fontsize=20, color='purple', fontweight='bold')
        
        # Add story text
        ax.text(5, 9, f'"{story[:50]}{"..." if len(story) > 50 else ""}"', 
                fontsize=14, ha='center', wrap=True, color='#333')
        
        # Character position
        x_pos = 5
        y_pos = 6
        
        # Create character element
        char_text = ax.text(x_pos, y_pos, character["emoji"], 
                          fontsize=48, ha='center', color=character["color"])
        
        # Target position
        target_x = 8
        target_y = 6
        ax.plot(target_x, target_y, 'ro', markersize=15, alpha=0.5)
        ax.text(target_x, target_y - 0.8, 'Target', ha='center', fontsize=12)
        
        # Add hop counter
        counter_text = ax.text(2, 8, f'Hops: 0/{count}', fontsize=16, color='#333')
        
        # Animation function
        def animate(frame):
            nonlocal x_pos, y_pos
            
            # Move character toward target
            if frame < count:
                x_pos += 0.3
                
                # Hop animation
                if frame % 2 == 0:
                    y_pos = 6.5
                else:
                    y_pos = 6
                
                char_text.set_position((x_pos, y_pos))
                counter_text.set_text(f'Hops: {frame+1}/{count}')
            
            # Return to start after reaching target
            elif frame == count:
                x_pos = 5
                y_pos = 6
                char_text.set_position((x_pos, y_pos))
            
            return char_text, counter_text
        
        # Create animation
        ani = FuncAnimation(fig, animate, frames=count*2, interval=500, blit=True)
        
        # Save animation as GIF in memory
        buf = io.BytesIO()
        ani.save(buf, format='gif', writer='pillow', fps=2)
        buf.seek(0)
        
        # Close the figure to free memory
        plt.close(fig)
        
        return buf
    
    except Exception as e:
        st.error(f"Animation error: {str(e)}")
        return None

def create_story_image(story):
    """Create a story image with Matplotlib"""
    try:
        # Create figure
        fig, ax = plt.subplots(figsize=(10, 6))
        ax.set_facecolor('#f0f8ff')
        ax.set_xlim(0, 10)
        ax.set_ylim(0, 10)
        ax.axis('off')
        
        # Add title
        ax.text(5, 8, '✨ Your Story ✨', fontsize=24, 
                ha='center', color='purple', fontweight='bold')
        
        # Add story text (wrapped)
        words = story.split()
        lines = []
        current_line = []
        
        for word in words:
            if len(' '.join(current_line + [word])) < 60:
                current_line.append(word)
            else:
                lines.append(' '.join(current_line))
                current_line = [word]
        
        if current_line:
            lines.append(' '.join(current_line))
        
        for i, line in enumerate(lines):
            ax.text(5, 6.5 - i*0.7, line, fontsize=14, ha='center', color='#333')
        
        # Add decoration
        ax.text(2, 2, '🐰', fontsize=40, ha='center')
        ax.text(8, 2, 'πŸ‰', fontsize=40, ha='center')
        ax.text(5, 1, 'Created with StoryCoder', fontsize=12, 
                ha='center', style='italic', color='gray')
        
        # Save to buffer
        buf = io.BytesIO()
        plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0.5, dpi=100)
        buf.seek(0)
        plt.close()
        return buf
    
    except Exception as e:
        st.error(f"Image generation error: {str(e)}")
        return None

def main():
    """Main application function"""
    st.title("πŸ§™β€β™‚οΈ StoryCoder - Learn Python Through Stories!")
    st.subheader("Turn your story into an animation and discover coding secrets!")
    
    # 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 'animation' not in st.session_state:
        st.session_state.animation = None
    if 'active_tab' not in st.session_state:
        st.session_state.active_tab = "story"
    
    # Create tabs
    tabs = st.empty()
    tab_cols = st.columns(5)
    with tab_cols[0]:
        if st.button("πŸ“– Create Story"):
            st.session_state.active_tab = "story"
    with tab_cols[1]:
        if st.button("🎬 Animation"):
            st.session_state.active_tab = "animation"
    with tab_cols[2]:
        if st.button("πŸ” Concepts"):
            st.session_state.active_tab = "concepts"
    with tab_cols[3]:
        if st.button("πŸ’» Code"):
            st.session_state.active_tab = "code"
    with tab_cols[4]:
        if st.button("πŸ”„ Reset"):
            st.session_state.story = ""
            st.session_state.concepts = []
            st.session_state.animation = None
            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!")
            
            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):
                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)
                    
                    with st.spinner("🎬 Creating your animation..."):
                        st.session_state.animation = create_animation(
                            story, st.session_state.concepts
                        )
                    
                    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")
            with col2:
                st.caption("Conditional Example")
                st.code('"If it rains, the cat stays inside, else it goes out"', language="text")
            with col3:
                st.caption("Function Example")
                st.code('"A wizard casts a spell to make flowers grow"', language="text")
    
    # 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 animation
        st.markdown(f"""
        <div class="animation-container">
            <h3 style="color: white; text-align: center;">"{st.session_state.story[:60]}{'...' if len(st.session_state.story) > 60 else ''}"</h3>
        </div>
        """, unsafe_allow_html=True)
        
        if st.session_state.animation:
            st.image(st.session_state.animation, use_container_width=True)
        else:
            st.warning("Animation couldn't be generated. Showing story image instead.")
            story_img = create_story_image(st.session_state.story)
            if story_img:
                st.image(story_img, use_container_width=True)
        
        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:#f0f0f0; padding:10px; border-radius:8px;">{details['example']}</pre>
                    </div>
                    """, unsafe_allow_html=True)
        
        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 created your animation:")
        
        # Sample code (in a real app, you would generate this based on the story)
        count = extract_count_from_story(st.session_state.story)
        character = random.choice(CHARACTERS)
        
        sample_code = f"""
# Story: {st.session_state.story[:50]}{'...' if len(st.session_state.story) > 50 else ''}

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

# Setup the figure
fig, ax = plt.subplots(figsize=(10, 6))
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.axis('off')

# Add story text
ax.text(5, 9, "{st.session_state.story[:50]}{'...' if len(st.session_state.story) > 50 else ''}", 
        fontsize=14, ha='center', wrap=True)

# Add character
char = ax.text(5, 6, "{character['emoji']}", fontsize=48, ha='center', color='{character['color']}')

# Add target
ax.plot(8, 6, 'ro', markersize=15, alpha=0.5)
ax.text(8, 5.2, 'Target', ha='center', fontsize=12)

# Add counter
counter = ax.text(2, 8, 'Hops: 0/{count}', fontsize=16)

# Animation function
def animate(frame):
    x = char.get_position()[0]
    
    # Move character toward target
    if frame < {count}:
        new_x = x + 0.3
        
        # Hop animation
        if frame % 2 == 0:
            new_y = 6.5
        else:
            new_y = 6
            
        char.set_position((new_x, new_y))
        counter.set_text(f'Hops: {{frame+1}}/{count}')
    
    # Return to start after reaching target
    elif frame == {count}:
        char.set_position((5, 6))
    
    return char, counter

# Create and save animation
ani = FuncAnimation(fig, animate, frames={count*2}, interval=500, blit=True)
ani.save('animation.gif', writer='pillow', fps=2)

plt.close()
        """
        
        st.code(sample_code, language="python")
        
        # Download button
        st.download_button(
            label="Download Animation Code",
            data=sample_code,
            file_name="story_animation.py",
            mime="text/python",
            use_container_width=True
        )
        
        st.write("You can run this code on your computer to create similar animations!")
        
        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()