import os import uuid import streamlit as st from dotenv import load_dotenv from openai import OpenAI from elevenlabs import generate, play, set_api_key import json import requests # Load API keys load_dotenv() OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY") # Initialize OpenAI and ElevenLabs clients openai_client = OpenAI(api_key=OPENAI_API_KEY) set_api_key(ELEVENLABS_API_KEY) # Streamlit UI st.title("Explain Like I'm Five (with Voice!)") topic = st.text_input("What do you want me to explain like you're five?", "") def stream_openai_response(payload, headers): with requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload, stream=True) as r: for line in r.iter_lines(): if line and line.startswith(b"data: "): yield line[len(b"data: "):].decode() if st.button("Explain with Voice"): if topic: st.subheader("Here's how a five-year-old might understand it:") explanation_box = st.empty() full_explanation = "" with st.spinner(f"Asking my smart brain to explain '{topic}' simply..."): prompt = f"Explain {topic} to a five-year-old using very simple words, short sentences, and a fun example or analogy that a young child can easily understand." headers = {"Authorization": f"Bearer {OPENAI_API_KEY}"} payload = { "model": "gpt-4o", "messages": [{"role": "user", "content": prompt}], "temperature": 0.7, "stream": True } for chunk in stream_openai_response(payload, headers): if chunk.strip() == "[DONE]": break try: parsed = json.loads(chunk) delta = parsed['choices'][0]['delta'].get('content', '') full_explanation += delta explanation_box.markdown(full_explanation) except json.JSONDecodeError: st.warning(f"Non-JSON chunk received: {chunk}") continue with st.spinner("Generating the voice for the explanation..."): audio = generate(text=full_explanation, voice="Bella", model="eleven_multilingual_v2") st.subheader("Listen to the explanation:") st.audio(audio, format="audio/mpeg") else: st.warning("Please enter a topic to be explained.")