File size: 2,478 Bytes
977f070
 
 
 
 
 
f7081da
 
977f070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7081da
 
 
 
 
 
977f070
 
f7081da
 
 
 
977f070
 
f7081da
 
 
 
 
 
 
977f070
f7081da
 
 
 
 
 
 
 
 
 
 
977f070
 
f7081da
977f070
 
 
 
 
 
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
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.")