sunbal7 commited on
Commit
d984995
·
verified ·
1 Parent(s): c01d41b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -40
app.py CHANGED
@@ -100,6 +100,63 @@ st.markdown("""
100
  </style>
101
  """, unsafe_allow_html=True)
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  # Header section
104
  st.markdown('<div class="header">CodeTales ✨</div>', unsafe_allow_html=True)
105
  st.markdown('<div class="subheader">Storytime + Coding Magic</div>', unsafe_allow_html=True)
@@ -121,6 +178,16 @@ with st.expander("✨ How It Works (Like Baking a Cake) 🎂"):
121
  Tavus shows: *"See? 'spaceship.move_right()' makes it fly! That's coding!"*
122
  """)
123
 
 
 
 
 
 
 
 
 
 
 
124
  # Main content
125
  col1, col2 = st.columns([1, 1])
126
 
@@ -131,73 +198,110 @@ with col1:
131
  "Tell your adventure story...",
132
  height=200,
133
  placeholder="Once upon a time, a brave spaceship zoomed through space, shooting lasers at alien spaceships...",
134
- label_visibility="collapsed"
 
135
  )
136
 
137
  # Generate button with animation
138
  if st.button("✨ Generate Animation!", use_container_width=True, key="generate", type="primary"):
139
- st.session_state.generate_clicked = True
 
 
 
 
 
 
 
140
  st.markdown('</div>', unsafe_allow_html=True)
141
 
142
  with col2:
143
  st.markdown('<div class="story-box">', unsafe_allow_html=True)
144
  st.markdown("### 🎮 Your Game Animation")
145
 
146
- if 'generate_clicked' in st.session_state and story_text:
147
  with st.spinner("🧙‍♂️ Cooking your story in the magic oven..."):
148
- # Simulate processing time
149
- time.sleep(3)
150
-
151
- # Generate animation (would use actual API call in production)
152
- st.session_state.animation_generated = True
153
- st.session_state.story_text = story_text
154
 
155
- # Display animation placeholder
156
- st.video("https://cdn.pixabay.com/video/2023/01/20/155564-810349295_large.mp4")
157
-
158
- st.success("🎉 Your animation is ready! Tavus will explain the magic now!")
159
- elif 'animation_generated' in st.session_state:
160
- st.video("https://cdn.pixabay.com/video/2023/01/20/155564-810349295_large.mp4")
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  else:
162
- st.image("https://img.freepik.com/free-vector/hand-drawn-colorful-space-background_23-2148821798.jpg", use_column_width=True)
 
163
  st.info("👆 Write your story and click Generate to see the magic!")
164
 
165
  st.markdown('</div>', unsafe_allow_html=True)
166
 
167
  # Tavus explanation section
168
- if 'animation_generated' in st.session_state and 'story_text' in st.session_state:
169
  st.markdown('<div class="robot-speech">', unsafe_allow_html=True)
170
  st.markdown("### 🤖 Tavus the Robot Teacher says:")
171
 
172
  # Extract action words from story
173
- action_words = ["zoom", "shoot", "fly", "move", "jump", "run", "attack"]
174
  found_actions = [word for word in action_words if word in st.session_state.story_text.lower()]
175
 
176
  if found_actions:
177
- action = found_actions[0]
178
- explanation = {
179
- "zoom": "makes your spaceship move super fast!",
180
- "shoot": "creates laser beams to defeat enemies!",
181
- "fly": "keeps your character moving through the air!",
182
- "move": "changes position on the screen!",
183
- "jump": "makes your character leap upwards!",
184
- "run": "makes your character move faster!",
185
- "attack": "lets your hero fight the bad guys!"
186
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
- code_snippet = {
189
- "zoom": "spaceship.accelerate(speed=10)",
190
- "shoot": "laser = spaceship.fire_weapon()",
191
- "fly": "character.apply_gravity(False)",
192
- "move": "player.move(direction='right')",
193
- "jump": "hero.jump(height=100)",
194
- "run": "player.speed = player.speed * 2",
195
- "attack": "sword.swing(damage=15)"
196
- }
197
 
198
- st.markdown(f"See how your story became real code? When you said **'{action}'**, we used:")
199
- st.markdown(f'<div class="code-block">{code_snippet[action]}</div>', unsafe_allow_html=True)
200
- st.markdown(f"This code {explanation[action]} That's the magic of coding - turning words into actions!")
201
  else:
202
  st.markdown("I see you created an awesome story! Every word you write can become game code. Try adding action words like 'jump', 'run', or 'shoot' next time!")
203
 
 
100
  </style>
101
  """, unsafe_allow_html=True)
102
 
103
+ # Novita.ai API functions
104
+ def generate_animation(prompt):
105
+ """Generate animation using Novita.ai API"""
106
+ api_key = os.getenv("NOVITA_API_KEY")
107
+ if not api_key:
108
+ st.error("Novita.ai API key not found. Please add it to your .env file.")
109
+ return None
110
+
111
+ headers = {
112
+ "Authorization": f"Bearer {api_key}",
113
+ "Content-Type": "application/json"
114
+ }
115
+
116
+ payload = {
117
+ "prompt": prompt,
118
+ "model": "animov-0.1.1",
119
+ "width": 512,
120
+ "height": 512,
121
+ "fps": 8,
122
+ "seconds": 4
123
+ }
124
+
125
+ try:
126
+ response = requests.post(
127
+ "https://api.novita.ai/v1/video",
128
+ headers=headers,
129
+ json=payload
130
+ )
131
+
132
+ if response.status_code == 200:
133
+ task_id = response.json()["task_id"]
134
+ return task_id
135
+ else:
136
+ st.error(f"API Error: {response.status_code} - {response.text}")
137
+ return None
138
+ except Exception as e:
139
+ st.error(f"Connection Error: {str(e)}")
140
+ return None
141
+
142
+ def get_animation_status(task_id):
143
+ """Check status of animation generation"""
144
+ api_key = os.getenv("NOVITA_API_KEY")
145
+ headers = {"Authorization": f"Bearer {api_key}"}
146
+
147
+ try:
148
+ response = requests.get(
149
+ f"https://api.novita.ai/v1/video/{task_id}",
150
+ headers=headers
151
+ )
152
+
153
+ if response.status_code == 200:
154
+ return response.json()
155
+ else:
156
+ return None
157
+ except:
158
+ return None
159
+
160
  # Header section
161
  st.markdown('<div class="header">CodeTales ✨</div>', unsafe_allow_html=True)
162
  st.markdown('<div class="subheader">Storytime + Coding Magic</div>', unsafe_allow_html=True)
 
178
  Tavus shows: *"See? 'spaceship.move_right()' makes it fly! That's coding!"*
179
  """)
180
 
181
+ # Initialize session state
182
+ if 'task_id' not in st.session_state:
183
+ st.session_state.task_id = None
184
+ if 'video_url' not in st.session_state:
185
+ st.session_state.video_url = None
186
+ if 'generating' not in st.session_state:
187
+ st.session_state.generating = False
188
+ if 'story_text' not in st.session_state:
189
+ st.session_state.story_text = ""
190
+
191
  # Main content
192
  col1, col2 = st.columns([1, 1])
193
 
 
198
  "Tell your adventure story...",
199
  height=200,
200
  placeholder="Once upon a time, a brave spaceship zoomed through space, shooting lasers at alien spaceships...",
201
+ label_visibility="collapsed",
202
+ value=st.session_state.story_text
203
  )
204
 
205
  # Generate button with animation
206
  if st.button("✨ Generate Animation!", use_container_width=True, key="generate", type="primary"):
207
+ if story_text.strip():
208
+ st.session_state.story_text = story_text
209
+ st.session_state.generating = True
210
+ st.session_state.task_id = generate_animation(story_text)
211
+ st.session_state.video_url = None
212
+ st.rerun()
213
+ else:
214
+ st.warning("Please enter a story first!")
215
  st.markdown('</div>', unsafe_allow_html=True)
216
 
217
  with col2:
218
  st.markdown('<div class="story-box">', unsafe_allow_html=True)
219
  st.markdown("### 🎮 Your Game Animation")
220
 
221
+ if st.session_state.generating and st.session_state.task_id:
222
  with st.spinner("🧙‍♂️ Cooking your story in the magic oven..."):
223
+ status = get_animation_status(st.session_state.task_id)
 
 
 
 
 
224
 
225
+ if status and status.get("status") == "SUCCESS":
226
+ st.session_state.video_url = status["video_url"]
227
+ st.session_state.generating = False
228
+ st.rerun()
229
+ elif status and status.get("status") in ["FAILED", "CANCELLED"]:
230
+ st.error("Oh no! The magic oven malfunctioned. Try again with a different story!")
231
+ st.session_state.generating = False
232
+ else:
233
+ # Still processing
234
+ time.sleep(3)
235
+ st.rerun()
236
+
237
+ if st.session_state.video_url:
238
+ st.video(st.session_state.video_url)
239
+ st.success("���� Your animation is ready! Tavus will explain the magic now!")
240
+ elif st.session_state.story_text:
241
+ st.image("https://img.freepik.com/free-vector/hand-drawn-colorful-space-background_23-2148821798.jpg",
242
+ use_column_width=True)
243
+ st.info("👆 Click Generate to see your story come to life!")
244
  else:
245
+ st.image("https://img.freepik.com/free-vector/hand-drawn-colorful-space-background_23-2148821798.jpg",
246
+ use_column_width=True)
247
  st.info("👆 Write your story and click Generate to see the magic!")
248
 
249
  st.markdown('</div>', unsafe_allow_html=True)
250
 
251
  # Tavus explanation section
252
+ if st.session_state.video_url and st.session_state.story_text:
253
  st.markdown('<div class="robot-speech">', unsafe_allow_html=True)
254
  st.markdown("### 🤖 Tavus the Robot Teacher says:")
255
 
256
  # Extract action words from story
257
+ action_words = ["zoom", "shoot", "fly", "move", "jump", "run", "attack", "laser", "alien", "spaceship"]
258
  found_actions = [word for word in action_words if word in st.session_state.story_text.lower()]
259
 
260
  if found_actions:
261
+ # Create explanation based on found words
262
+ explanations = []
263
+ code_snippets = []
264
+
265
+ for action in found_actions[:3]: # Limit to 3 explanations
266
+ if action == "zoom":
267
+ explanations.append("makes your spaceship move super fast!")
268
+ code_snippets.append("spaceship.accelerate(speed=10)")
269
+ elif action == "shoot":
270
+ explanations.append("creates laser beams to defeat enemies!")
271
+ code_snippets.append("laser = spaceship.fire_weapon()")
272
+ elif action == "fly":
273
+ explanations.append("keeps your character moving through the air!")
274
+ code_snippets.append("character.apply_gravity(False)")
275
+ elif action == "move":
276
+ explanations.append("changes position on the screen!")
277
+ code_snippets.append("player.move(direction='right')")
278
+ elif action == "jump":
279
+ explanations.append("makes your character leap upwards!")
280
+ code_snippets.append("hero.jump(height=100)")
281
+ elif action == "run":
282
+ explanations.append("makes your character move faster!")
283
+ code_snippets.append("player.speed = player.speed * 2")
284
+ elif action == "attack":
285
+ explanations.append("lets your hero fight the bad guys!")
286
+ code_snippets.append("sword.swing(damage=15)")
287
+ elif action == "laser":
288
+ explanations.append("creates powerful energy beams!")
289
+ code_snippets.append("weapon = Laser(color='red', damage=20)")
290
+ elif action == "alien":
291
+ explanations.append("adds enemies to your game!")
292
+ code_snippets.append("enemy = Alien(position=(100, 200))")
293
+ elif action == "spaceship":
294
+ explanations.append("creates your main character!")
295
+ code_snippets.append("player = Spaceship(image='spaceship.png')")
296
+
297
+ st.markdown("See how your story became real code? Here's what happened:")
298
 
299
+ for i, (action, explanation, snippet) in enumerate(zip(found_actions, explanations, code_snippets)):
300
+ st.markdown(f"**{i+1}. When you said '{action}'**:")
301
+ st.markdown(f'<div class="code-block">{snippet}</div>', unsafe_allow_html=True)
302
+ st.markdown(f"This code {explanation}")
 
 
 
 
 
303
 
304
+ st.markdown("That's the magic of coding - turning words into actions!")
 
 
305
  else:
306
  st.markdown("I see you created an awesome story! Every word you write can become game code. Try adding action words like 'jump', 'run', or 'shoot' next time!")
307