File size: 3,558 Bytes
5ac732d
65eb8e4
5ac732d
65eb8e4
 
 
 
 
bfd0106
2084430
a9f0287
bfd0106
2084430
65eb8e4
 
 
 
 
 
5ac732d
65eb8e4
 
 
 
bfd0106
65eb8e4
5ac732d
65eb8e4
 
2084430
 
 
65eb8e4
d984995
65eb8e4
 
 
 
bfd0106
a9f0287
2084430
65eb8e4
 
 
2084430
65eb8e4
 
 
 
 
 
 
 
d984995
a9f0287
2084430
65eb8e4
bfd0106
65eb8e4
 
 
 
 
 
 
 
 
 
 
 
a9f0287
65eb8e4
 
 
 
 
 
5ac732d
65eb8e4
 
2084430
65eb8e4
 
 
 
a9f0287
65eb8e4
 
a9f0287
65eb8e4
 
 
 
 
 
 
 
 
 
 
 
 
 
bfd0106
5ac732d
65eb8e4
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
import os
import streamlit as st
from dotenv import load_dotenv
from novita_client import NovitaClient
import ast
import subprocess
import tempfile
import time

# Load API key
load_dotenv()

# --- Code Converter ---
class StoryToCodeConverter:
    def __init__(self):
        api_key = os.getenv("NOVITA_API_KEY")
        if not api_key:
            raise ValueError("NOVITA_API_KEY not found in environment")
        self.client = NovitaClient(api_key)

    def generate_code(self, story):
        prompt = f"""
Convert this children's story into Python animation code using turtle graphics.
Add code comments that explain the basic concepts to kids, like loops, movement, and colors.

Story: {story}

Only return the Python code wrapped in triple backticks like ```python ... ```
"""
        # Using Novita's correct `generate` method
        response = self.client.generate(prompt=prompt, model="gpt-4")
        content = response.get("text", "")  # Adjust if response structure changes
        return self._extract_code(content)

    def _extract_code(self, content):
        if "```python" in content:
            return content.split("```python")[1].split("```")[0]
        return content


# --- Code Executor ---
class CodeExecutor:
    def execute_safely(self, code):
        try:
            ast.parse(code)  # Basic safety check
            with tempfile.NamedTemporaryFile(delete=False, suffix=".py") as tmp:
                tmp.write(code.encode("utf-8"))
                tmp_path = tmp.name
            subprocess.Popen(["python", tmp_path])
            return True
        except Exception as e:
            st.error(f"Robot Chef burned the cake: {e}")
            return False


# --- Streamlit Interface ---
st.set_page_config(page_title="CodeTales", page_icon="โœจ")

with st.sidebar:
    st.header("๐Ÿฐ How It Works")
    st.markdown("""
1. ๐Ÿ“ Kids write a story (like a recipe!)  
2. ๐Ÿ”ฎ AI turns it into **Python code**  
3. ๐ŸŽฎ Animation appears like magic!  
4. ๐Ÿค– Robot Teacher explains the code!

Made for ages 6โ€“12. Fun, visual, and interactive!
""")

st.title("โœจ CodeTales: Storytime + Coding Magic")

story = st.text_area("Write Your Story Recipe ๐Ÿ“", height=200,
                     placeholder="Once upon a time, a rocket zoomed past rainbow stars and met an alien...")

if st.button("โœจ Bake My Story Cake!"):
    if not story.strip():
        st.warning("Please write a story first!")
    else:
        with st.spinner("Baking your story cake... ๐Ÿฐ"):
            try:
                converter = StoryToCodeConverter()
                code = converter.generate_code(story)
            except Exception as e:
                st.error(f"AI oven broke down! {e}")
                st.stop()

            st.subheader("๐Ÿ“œ Your Code Recipe")
            st.code(code, language='python')

            executor = CodeExecutor()
            if executor.execute_safely(code):
                st.balloons()
                with st.expander("๐Ÿค– Robot Teacher Says:"):
                    st.markdown("""
- `turtle.forward(100)` โ€“ Moves the rocket forward ๐Ÿš€  
- `turtle.color("red")` โ€“ Paints with colors ๐ŸŽจ  
- `for loop` โ€“ Repeats an action like magic ๐Ÿ”  
                    """)
                st.success("๐ŸŽ‰ Your story came to life!")
            else:
                st.error("Oops! Couldn't bake the animation.")
else:
    st.caption("Turn your words into animated code with magic ๐Ÿช„")

st.markdown("---")
st.caption("Made with โค๏ธ for young coders | Powered by Novita + Python Turtle")