rubyren commited on
Commit
ca7a425
Β·
verified Β·
1 Parent(s): ef20f32

Upload 3 files

Browse files
Files changed (4) hide show
  1. .gitattributes +1 -0
  2. app.py +476 -0
  3. museo.png +3 -0
  4. requirements.txt +5 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ museo.png filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+ from openai import OpenAI
4
+ import os
5
+ import requests
6
+ from dotenv import load_dotenv
7
+ import asyncio
8
+ from openai import AsyncOpenAI
9
+ import tempfile
10
+
11
+ # Load environment variables from .env file
12
+ load_dotenv()
13
+ # Access the API key
14
+ openai_api_key = os.getenv("OPENAI_API_KEY")
15
+ YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
16
+
17
+
18
+ client = openai.OpenAI(api_key=openai_api_key)
19
+ async_client = AsyncOpenAI(api_key=openai_api_key)
20
+
21
+
22
+ async def tts_itinerary(text, instructions, voice="nova"):
23
+ from aiohttp import ClientSession
24
+
25
+ # Use Gradio-safe temp file
26
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmpfile:
27
+ output_path = tmpfile.name
28
+
29
+ url = "https://api.openai.com/v1/audio/speech"
30
+ headers = {
31
+ "Authorization": f"Bearer {openai_api_key}",
32
+ "Content-Type": "application/json"
33
+ }
34
+ payload = {
35
+ "model": "gpt-4o-mini-tts",
36
+ "input": text,
37
+ "voice": voice,
38
+ "instructions": instructions,
39
+ "response_format": "wav"
40
+ }
41
+
42
+ async with ClientSession() as session:
43
+ async with session.post(url, headers=headers, json=payload) as resp:
44
+ if resp.status != 200:
45
+ error_text = await resp.text()
46
+ raise Exception(f"TTS failed: {resp.status} - {error_text}")
47
+
48
+ with open(output_path, "wb") as f:
49
+ while True:
50
+ chunk = await resp.content.read(1024)
51
+ if not chunk:
52
+ break
53
+ f.write(chunk)
54
+
55
+ return output_path
56
+
57
+
58
+
59
+ def sync_tts_wrapper(text):
60
+ instructions = (
61
+ "Voice: Friendly and enthusiastic, like a museum guide talking to kids. "
62
+ "Tone: Excited, informative, curious. Delivery: Clear and fun."
63
+ )
64
+ return asyncio.run(tts_itinerary(text, instructions))
65
+
66
+ # ✨ Itinerary Generator Logic
67
+ def generate_itinerary(age, interests, language, expectations,
68
+ learning_goals, eta, estimated_staying_time):
69
+ print(f"language is {language}")
70
+
71
+ system_prompt = (
72
+ "You are an advanced AI working for MuseoGo, a platform dedicated to enhancing museum visits using AI. "
73
+ "You will speak in the language that the current user provides to you."
74
+ "Your main task is to create user-friendly itineraries specifically for The Franklin Institute, "
75
+ f"Ensure that the expected number of hours for the exhibits sums to {estimated_staying_time} and does not go over that. "
76
+ "factoring in user profiles (age, interests, learning goals, ETA, and estimated staying time). "
77
+ "Ensure your responses are accurate, thorough, and easy to understand."
78
+ "Be explicit about how your recommendation matches my child's interests, age, and learning goals."
79
+ "Provide complete, detailed recommendations for exhibits and scheduling, integrating daily show times."
80
+ "You are displaying this directly to the user, don't exclaim in response to the prompt."
81
+ "Don't use the word I and instead use second person. Directly address your users. Don't respond to me with \"Certainly\"."
82
+ )
83
+
84
+ user_prompt = (
85
+ f"I am planning a trip to The Franklin Institute with my child.\n\n"
86
+ f"Child's Age: {age}\n"
87
+ f"Interests: {interests}\n"
88
+ f"Learning Goals: {learning_goals}\n"
89
+ f"Arrival Time (ETA): {eta}\n"
90
+ f"Estimated Staying Time: {estimated_staying_time}\n\n"
91
+ f"Keep in mind my child's conditions: {expectations}\n\n"
92
+ "Generate a personalized museum itinerary tailored to this information. "
93
+ "Include:\n"
94
+ "- Recommended exhibits in order, including why you chose each exhibit.\n"
95
+ "- Time estimates for each exhibit.\n"
96
+ "- Integration of daily show schedules.\n"
97
+ "- Any additional tips to maximize their visit.\n\n"
98
+ f"Please respond to me in {language} for the rest of the conversation.\n"
99
+ "Always format your answer as:\n"
100
+ "\"Number. Title - explanation\"\n"
101
+ )
102
+
103
+ response = client.chat.completions.create(
104
+ model="gpt-3.5-turbo",
105
+ messages=[
106
+ {"role": "system", "content": system_prompt},
107
+ {"role": "user", "content": user_prompt}
108
+ ]
109
+ )
110
+
111
+ itinerary = response.choices[0].message.content
112
+ audio_path = sync_tts_wrapper(itinerary)
113
+
114
+ return itinerary, gr.update(value=audio_path, visible=True)
115
+
116
+
117
+ # ✨ Knowledge Companion Logic
118
+ def answer_question(age, question):
119
+ system_prompt = (
120
+ "You are an educational AI chatbot for MuseoGo, designed to answer questions from children visiting "
121
+ "The Franklin Institute. Your answers must be:\n"
122
+ "- Age-appropriate (based on the child's age)\n"
123
+ "- Friendly and engaging 😊\n"
124
+ "- Factually correct and easy to understand\n"
125
+ "- Focused on science, exhibits, or museum topics\n"
126
+ "- Designed to make learning fun and spark curiosity 🧠✨\n\n"
127
+ "SAFETY GUIDELINES:\n"
128
+ "- If the input includes hate speech, harmful content, or anything inappropriate, DO NOT answer the question.\n"
129
+ "- Instead, respond with a kind and firm message like: 'Let's keep things friendly and fun! 😊 I'm here to help with science questions and cool stuff about the museum. If you're curious about something science-y, I'm all ears!'\n"
130
+ "- Never repeat or acknowledge harmful content directly.\n\n"
131
+ "Use emojis where helpful to make your responses more fun and relatable.\n"
132
+ "Always end your answer with a simple multiple-choice question to check understanding."
133
+ )
134
+
135
+ user_prompt = (
136
+ f"My child, age {age}, is visiting The Franklin Institute and asks: '{question}'\n\n"
137
+ "Please give a clear, fun explanation that matches their age level, and connect it to any related exhibit or science concept in the museum when possible."
138
+ )
139
+
140
+ response = client.chat.completions.create(
141
+ model="gpt-3.5-turbo",
142
+ messages=[
143
+ {"role": "system", "content": system_prompt},
144
+ {"role": "user", "content": user_prompt}
145
+ ]
146
+ )
147
+
148
+ return response.choices[0].message.content
149
+
150
+
151
+
152
+
153
+
154
+ # ✨ Exit Ticket Generator Logic
155
+
156
+ def generate_exit_ticket(age, exhibits, favorite_part):
157
+ system_prompt = (
158
+ "You are an AI assistant creating personalized exit tickets for young visitors "
159
+ "at The Franklin Institute. Your goal is to reinforce learning by summarizing key takeaways "
160
+ "and providing engaging prompts for reflection. Keep the tone friendly, simple, and age-appropriate. "
161
+ "Use fun language to celebrate learning and encourage curiosity."
162
+ )
163
+
164
+ user_prompt = (
165
+ f"A {age}-year-old child visited The Franklin Institute and explored the following topics:\n"
166
+ f"{exhibits}\n\n"
167
+ f"Their favorite part of the visit was: {favorite_part}\n\n"
168
+ "Create a fun, engaging exit ticket that includes:\n"
169
+ "- A summary of what they learned (in simple language for their age).\n"
170
+ "- A playful reflection question.\n"
171
+ "- A suggested hands-on or creative activity they can try at home to keep learning."
172
+ )
173
+ response = client.chat.completions.create(
174
+ model="gpt-3.5-turbo",
175
+ messages=[
176
+ {"role": "system", "content": system_prompt},
177
+ {"role": "user", "content": user_prompt}
178
+ ]
179
+ )
180
+
181
+ return response.choices[0].message.content
182
+
183
+ # def generate_exit_ticket(age, exhibits, favorite_part):
184
+ # # Handle both string and list inputs for exhibits
185
+ # if isinstance(exhibits, str):
186
+ # exhibits_list = [ex.strip() for ex in exhibits.split(",")]
187
+ # exhibits_str = exhibits
188
+ # elif isinstance(exhibits, list):
189
+ # exhibits_list = [ex.strip() for ex in exhibits]
190
+ # exhibits_str = ", ".join(exhibits)
191
+ # else:
192
+ # exhibits_list = []
193
+ # exhibits_str = str(exhibits)
194
+
195
+ # # Generate the exit ticket content
196
+ # exit_ticket_content = f"""## What You Learned Today!
197
+
198
+ # Hey there, future scientist! Today at The Franklin Institute, you explored {exhibits_str}.
199
+ # Here's what you might have discovered:
200
+
201
+ # - {exhibits_list[0] if len(exhibits_list) > 0 else "Science"} is all about...
202
+ # {'- ' + exhibits_list[1] + ' which shows...' if len(exhibits_list) > 1 else ''}
203
+
204
+ # ## Reflection Question
205
+ # What was the most surprising thing you learned about {favorite_part}?
206
+
207
+ # ## Keep Exploring at Home
208
+ # Try this fun activity: [simple activity related to {exhibits_list[0] if exhibits_list else 'science'}]
209
+ # """
210
+ # return exit_ticket_content
211
+
212
+ def search_youtube_videos(query, CHANNEL_ID="UCpAQimPOzeu_VRWRs_S4cPw"):
213
+ """
214
+ Searches YouTube videos from The Franklin Institute channel based on a query
215
+ and returns relevant videos with their URLs.
216
+ """
217
+ base_url = "https://www.googleapis.com/youtube/v3/search"
218
+ params = {
219
+ "key": YOUTUBE_API_KEY,
220
+ "channelId": CHANNEL_ID,
221
+ "part": "snippet",
222
+ "q": query,
223
+ "maxResults": 3,
224
+ "order": "relevance",
225
+ "type": "video"
226
+ }
227
+
228
+ try:
229
+ response = requests.get(base_url, params=params)
230
+ response.raise_for_status()
231
+ data = response.json()
232
+
233
+ results = []
234
+ for item in data.get("items", []):
235
+ video_id = item["id"]["videoId"]
236
+ title = item["snippet"]["title"]
237
+ # url = f"https://www.youtube.com/watch?v={video_id}"
238
+ results.append((title, video_id))
239
+
240
+ return results
241
+ except Exception as e:
242
+ print(f"Error searching YouTube videos: {e}")
243
+ return []
244
+
245
+
246
+
247
+ def format_embedded_videos(video_data):
248
+ """
249
+ Accepts a list of (title, video_id) and returns HTML with videos
250
+ in a responsive grid layout that adapts to screen size.
251
+ """
252
+ if not video_data:
253
+ return ""
254
+
255
+ html = '''
256
+ <style>
257
+ .video-grid {
258
+ display: flex;
259
+ flex-wrap: wrap;
260
+ gap: 20px;
261
+ justify-content: space-between;
262
+ }
263
+ .video-item {
264
+ flex: 1 1 45%;
265
+ min-width: 300px;
266
+ }
267
+ .video-container {
268
+ position: relative;
269
+ padding-bottom: 56.25%; /* 16:9 ratio */
270
+ height: 0;
271
+ overflow: hidden;
272
+ }
273
+ .video-container iframe {
274
+ position: absolute;
275
+ top: 0;
276
+ left: 0;
277
+ width: 100%;
278
+ height: 100%;
279
+ border: 0;
280
+ }
281
+ @media (max-width: 600px) {
282
+ .video-item {
283
+ flex: 1 1 100%;
284
+ }
285
+ }
286
+ </style>
287
+ <div class="video-grid">
288
+ '''
289
+
290
+ for title, video_id in video_data:
291
+ html += f"""
292
+ <div class="video-item">
293
+ <h4>πŸŽ₯ {title}</h4>
294
+ <div class="video-container">
295
+ <iframe
296
+ src="https://www.youtube.com/embed/{video_id}"
297
+ title="{title}"
298
+ allow="accelerometer; autoplay; clipboard-write;
299
+ encrypted-media; gyroscope; picture-in-picture"
300
+ allowfullscreen>
301
+ </iframe>
302
+ </div>
303
+ </div>
304
+ """
305
+
306
+ html += '</div>'
307
+ return html
308
+
309
+
310
+ def create_exit_ticket(age, exhibits, favorite_part):
311
+ # Generate the exit ticket content - plain text
312
+ exit_ticket_text = generate_exit_ticket(age, exhibits, favorite_part)
313
+
314
+ # Format the text into HTML-friendly format (replace newlines with <br>)
315
+ formatted_text = exit_ticket_text.replace('\n', '<br>')
316
+
317
+ # Wrap the content in a styled HTML container
318
+ exit_ticket_html = f"""
319
+ <div style="font-family: Arial, sans-serif; line-height: 1.6;">
320
+ <h2>🧾 Your Personalized Exit Ticket</h2>
321
+ <p>{formatted_text}</p>
322
+ </div>
323
+ """
324
+
325
+ # Get exhibits as a list
326
+ exhibits_list = [
327
+ ex.strip() for ex in
328
+ (exhibits.split(",") if isinstance(exhibits, str) else exhibits)
329
+ ]
330
+
331
+ # Prepare embedded video section
332
+ video_section = """
333
+ <div style="margin-top: 40px;">
334
+ <h2>🎬 Recommended Videos from The Franklin Institute</h2>
335
+ """
336
+ video_urls = []
337
+
338
+ for i, exhibit in enumerate(exhibits_list[:3]): # Limit to 3 exhibits
339
+ videos = search_youtube_videos(exhibit)
340
+ if videos:
341
+ if i < 2: # Only embed for first 2 exhibits
342
+ video_section += f"<h3>About {exhibit}:</h3>"
343
+ video_section += format_embedded_videos(videos[:2])
344
+ video_urls.append(videos[0][1]) # Store first video ID
345
+
346
+ # Pad with None if fewer than 3
347
+ while len(video_urls) < 3:
348
+ video_urls.append(None)
349
+
350
+ video_section += "</div>"
351
+
352
+ # Combine all content
353
+ full_exit_ticket = exit_ticket_html + video_section
354
+
355
+ return full_exit_ticket, video_urls[0], video_urls[1], video_urls[2]
356
+
357
+
358
+ ## Gradio Interface
359
+ css = """
360
+ @import url('https://fonts.googleapis.com/css2?family=Helvetica+Neue:wght@400;700&display=swap');
361
+
362
+ body, .gradio-container {
363
+ font-family: 'Helvetica Neue', Arial, sans-serif !important;
364
+ }
365
+
366
+ }
367
+ """
368
+
369
+ with gr.Blocks(title="Museum Experience", css=css) as demo:
370
+ gr.Markdown("# πŸ›οΈ Museum Experience")
371
+
372
+ with gr.Tabs() as tabs:
373
+ with gr.Tab("Itinerary Generator", id=0):
374
+ # Kid Information Section
375
+ with gr.Group():
376
+ gr.Markdown("## πŸ‘Ά Kid Information")
377
+ age = gr.Number(label="Age", value=10, precision=0)
378
+ interests = gr.CheckboxGroup(
379
+ label="What are the interested topics of your kids? (Select at least one)",
380
+ choices=["Space exploration", "Human biology", "Technology and innovation",
381
+ "Physics and mechanics", "Environmental science", "History of science"]
382
+ )
383
+ learning_goals = gr.Textbox(
384
+ label="Learning Goals",
385
+ placeholder="What do you hope your child will learn from this visit?"
386
+ )
387
+
388
+ # Visit Information Section
389
+ with gr.Group():
390
+ gr.Markdown("## πŸ•’ Visit Information")
391
+ eta = gr.Textbox(
392
+ label="Estimated arrival time",
393
+ placeholder="Enter time between 9:00 and 17:00",
394
+ value="12:00",
395
+ )
396
+ estimated_staying_time = gr.Radio(
397
+ label="Duration",
398
+ choices=["1 hour", "2 hours", "3 hours (recommended)", "4 hours", "> 4 hours"],
399
+ value="3 hours (recommended)"
400
+ )
401
+ language = gr.Radio(
402
+ label="Language preference",
403
+ choices=["English", "Spanish", "French", "Chinese", "Arabic"],
404
+ value="English"
405
+ )
406
+ expectations = gr.Textbox(
407
+ label="Other expectations (Optional)",
408
+ placeholder="E.g., wheelchair accessibility, quiet areas...",
409
+ lines=3
410
+ )
411
+
412
+ itinerary_output = gr.Markdown()
413
+ tts_audio_output = gr.Audio(label="🎧 Listen to Itinerary", visible=False)
414
+
415
+ generate_btn = gr.Button("Generate Itinerary", variant="primary")
416
+ generate_btn.click(
417
+ fn=generate_itinerary,
418
+ inputs=[age, interests, language, expectations, learning_goals, eta, estimated_staying_time],
419
+ outputs=[itinerary_output, tts_audio_output]
420
+ )
421
+
422
+
423
+ with gr.Tab("Learning Companion", id=1):
424
+ chatbot = gr.Chatbot(
425
+ avatar_images=(None, "museo.png"),
426
+ show_copy_button=True,
427
+ height="75vh",
428
+ show_label=True,
429
+ container=True
430
+ )
431
+
432
+ # Create the chat interface with supported parameters
433
+ chat_interface = gr.ChatInterface(
434
+ fn=answer_question,
435
+ chatbot=chatbot,
436
+ examples=[
437
+ "Why is the sky blue?",
438
+ "What is a black hole?",
439
+ "What makes a rainbow?"
440
+ ],
441
+ additional_inputs=None,
442
+ submit_btn=True,
443
+ fill_height=True
444
+ )
445
+
446
+
447
+ with gr.Tab("Exit Ticket Generator", id=2):
448
+ gr.Markdown("# πŸ›οΈ Franklin Institute Exit Ticket Generator")
449
+ gr.Markdown("Create personalized exit tickets for young visitors with learning summaries and video recommendations!")
450
+
451
+ exhibits = gr.CheckboxGroup(
452
+ label="What exhibitions did you visit today? (Select at least one)",
453
+ choices=["The Giant Heart" , "Your Brain" , "Changing Earth" , "Space Command" , "The Train Factory" , "Sir Isaac's Loft" , "SportsZone"],
454
+ interactive=True
455
+ )
456
+ favorite_part = gr.Textbox(
457
+ label="What is your favorite exhibition?",
458
+ placeholder="E.g., Space Exploration",
459
+ lines=3
460
+ )
461
+
462
+ generate_btn = gr.Button("Generate Exit Ticket", variant="primary")
463
+
464
+ with gr.Row():
465
+ exit_ticket_output = gr.HTML(label="Your Personalized Exit Ticket")
466
+ video_outputs = []
467
+ for i in range(3):
468
+ video_outputs.append(gr.Video(label=f"Recommended Video {i+1}", visible=False))
469
+
470
+ generate_btn.click(
471
+ fn=create_exit_ticket,
472
+ inputs=[age, exhibits, favorite_part],
473
+ outputs=[exit_ticket_output, *video_outputs]
474
+ )
475
+
476
+ demo.launch()
museo.png ADDED

Git LFS Details

  • SHA256: e710f91d00e8dc7ef16f36b53ae5f59e52014044d5bacf471c500ad002c475a0
  • Pointer size: 131 Bytes
  • Size of remote file: 543 kB
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio
2
+ huggingface
3
+ openai
4
+ dotenv
5
+ aiohttp