Spaces:
Sleeping
Sleeping
File size: 10,350 Bytes
074e8ce 4ee79f3 d26d845 4ee79f3 d26d845 4ee79f3 c1c3a76 4ee79f3 39ed2fb 074e8ce 4ee79f3 074e8ce 4ee79f3 074e8ce d4d880a 4ee79f3 074e8ce 0627d63 074e8ce d4d880a 4ee79f3 074e8ce 39ed2fb 074e8ce 39ed2fb 074e8ce d4d880a 074e8ce d26d845 074e8ce 39ed2fb 074e8ce 4ee79f3 074e8ce d871be8 074e8ce d26d845 074e8ce d26d845 c1c3a76 d871be8 074e8ce 0627d63 ef89b24 0627d63 074e8ce 9aed552 074e8ce 4ee79f3 d26d845 4ee79f3 074e8ce d26d845 d871be8 074e8ce d871be8 074e8ce ef89b24 074e8ce ef89b24 39ed2fb 074e8ce ef89b24 4ee79f3 074e8ce ef89b24 4ee79f3 074e8ce 1d0cd2a 074e8ce 1d0cd2a 196685d 074e8ce |
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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
"""Explainor - AI Agent that explains any topic in fun persona voices.
MCP's 1st Birthday Hackathon Submission
Track: MCP in Action (Creative)
Team: kaiser-data
"""
import os
import tempfile
import gradio as gr
from dotenv import load_dotenv
from src.personas import PERSONAS, get_persona_names, get_persona
from src.agent import run_agent
from src.tts import generate_speech
# Load environment variables
load_dotenv()
def format_sources(sources: list[dict]) -> str:
"""Format sources as markdown."""
if not sources:
return "*No external sources used*"
md = ""
for i, src in enumerate(sources, 1):
if src.get("url"):
md += f"{i}. [{src['title']}]({src['url']})\n"
else:
md += f"{i}. {src['title']} ({src.get('source', 'General')})\n"
return md
def format_mcp_tools(tools: list[dict]) -> str:
"""Format tools used as markdown."""
if not tools:
return "*No tools used*"
md = "**๐ Agent Tool Calls:**\n\n"
for tool in tools:
md += f"| {tool['icon']} | `{tool['name']}` | {tool['desc']} |\n"
return md
def explain_topic(topic: str, persona_name: str, audience: str = "", generate_audio: bool = False, progress=gr.Progress()):
"""Main function to explain a topic in a persona's voice.
Returns: (explanation_text, audio_path, sources_md, steps_md, mcp_md)
"""
if not topic.strip():
return (
"Please enter a topic to explain!",
None,
"",
"โ No topic provided",
"",
)
if not persona_name:
persona_name = "5-Year-Old"
steps_log = []
explanation = ""
sources = []
voice_id = None
voice_settings = None
mcp_tools = []
# Run the agent pipeline
progress(0, desc="Starting...")
for update in run_agent(topic, persona_name, audience):
if update["type"] == "step":
step_text = f"**{update['title']}**\n{update['content']}"
steps_log.append(step_text)
if update["step"] == "research":
progress(0.2, desc="Researching...")
elif update["step"] == "research_done":
progress(0.4, desc="Research complete")
if "sources" in update:
sources = update["sources"]
elif update["step"] == "generating":
progress(0.6, desc="Generating explanation...")
elif update["type"] == "result":
explanation = update["explanation"]
sources = update.get("sources", sources)
voice_id = update["voice_id"]
voice_settings = update.get("voice_settings")
mcp_tools = update.get("mcp_tools", [])
progress(0.8, desc="Explanation ready!")
# Format the steps log
steps_md = "\n\n---\n\n".join(steps_log)
# Generate audio only if checkbox is checked
audio_path = None
if generate_audio and explanation and voice_id:
progress(0.9, desc="Generating audio...")
try:
audio_bytes = generate_speech(explanation, voice_id, voice_settings)
# Save to temp file for Gradio
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as f:
f.write(audio_bytes)
audio_path = f.name
# Add text_to_speech tool
mcp_tools.append({"name": "text_to_speech", "icon": "๐", "desc": "Audio generation via ElevenLabs API"})
progress(1.0, desc="Done!")
except Exception as e:
steps_log.append(f"**โ ๏ธ Audio generation failed**\n{str(e)}")
steps_md = "\n\n---\n\n".join(steps_log)
progress(1.0, desc="Done (no audio)")
else:
progress(1.0, desc="Done!")
# Format sources
sources_md = format_sources(sources)
# Format MCP tools
mcp_md = format_mcp_tools(mcp_tools)
return explanation, audio_path, sources_md, steps_md, mcp_md
# Build the Gradio interface
def create_app():
"""Create and configure the Gradio app."""
with gr.Blocks(title="Explainor - AI Persona Explanations") as app:
# Header
gr.Markdown(
"""
# ๐ญ Explainor
### *AI Agent with Tool Orchestration*
**Learn anything through the voice of your favorite characters!**
This agent orchestrates multiple tools to: research your topic,
extract key facts, transform explanations into character voices, and generate audio.
"""
)
with gr.Row():
with gr.Column(scale=2):
topic_input = gr.Textbox(
label="๐ What do you want to learn about?",
placeholder="e.g., Blockchain, Photosynthesis, Black Holes...",
lines=1,
max_lines=1,
)
with gr.Column(scale=1):
# Build persona choices with emojis
persona_choices = [
f"{PERSONAS[name]['emoji']} {name}"
for name in get_persona_names()
]
persona_dropdown = gr.Dropdown(
choices=persona_choices,
value=persona_choices[0],
label="๐ญ Choose your explainer",
)
with gr.Row():
# Funny listener options (don't overlap with personas)
listener_choices = [
"๐ค Just me",
"๐ต My confused grandmother",
"๐ค A skeptical robot",
"๐ฝ An alien visiting Earth",
"๐ง A zombie (short attention span)",
"๐ฆ A very smart fox",
"๐ A stressed CEO",
"๐ฎ A distracted gamer",
]
audience_dropdown = gr.Dropdown(
choices=listener_choices,
value=listener_choices[0],
label="๐ค Who's listening?",
)
explain_btn = gr.Button(
"โจ Explain it to me!",
variant="primary",
size="lg",
)
# Output section
with gr.Row():
with gr.Column():
explanation_output = gr.Textbox(
label="๐ Explanation",
lines=8,
max_lines=15,
)
audio_checkbox = gr.Checkbox(
label="๐ Generate audio",
value=False,
)
audio_output = gr.Audio(
label="๐ Listen to the explanation",
type="filepath",
autoplay=False,
)
with gr.Row():
with gr.Column():
with gr.Accordion("๐ Agent Tool Calls", open=True):
mcp_output = gr.Markdown("")
with gr.Row():
with gr.Column():
with gr.Accordion("๐ Sources", open=False):
sources_output = gr.Markdown("")
with gr.Column():
with gr.Accordion("๐ง Execution Trace", open=False):
steps_output = gr.Markdown("")
# Example topics
gr.Examples(
examples=[
["Quantum Computing", f"{PERSONAS['5-Year-Old']['emoji']} 5-Year-Old"],
["Blockchain", f"{PERSONAS['Gordon Ramsay']['emoji']} Gordon Ramsay"],
["Black Holes", f"{PERSONAS['Pirate']['emoji']} Pirate"],
["Machine Learning", f"{PERSONAS['Shakespeare']['emoji']} Shakespeare"],
["Climate Change", f"{PERSONAS['Surfer Dude']['emoji']} Surfer Dude"],
["The Force", f"{PERSONAS['Yoda']['emoji']} Yoda"],
],
inputs=[topic_input, persona_dropdown],
label="Try these examples:",
)
# Footer
gr.Markdown(
"""
---
**Built for MCP's 1st Birthday Hackathon** | Track: MCP in Action (Creative)
Powered by: [Nebius AI](https://nebius.com) (LLM) + [ElevenLabs](https://elevenlabs.io) (TTS)
Made with โค๏ธ by **kaiser-data**
"""
)
# Event handler
def process_and_explain(topic, persona_with_emoji, gen_audio, audience_with_emoji):
# Extract persona name (remove emoji prefix)
persona_name = persona_with_emoji.split(" ", 1)[1] if " " in persona_with_emoji else persona_with_emoji
# Extract audience (remove emoji prefix), skip if "Just me"
audience = ""
if audience_with_emoji and "Just me" not in audience_with_emoji:
audience = audience_with_emoji.split(" ", 1)[1] if " " in audience_with_emoji else audience_with_emoji
return explain_topic(topic, persona_name, audience, gen_audio)
explain_btn.click(
fn=process_and_explain,
inputs=[topic_input, persona_dropdown, audio_checkbox, audience_dropdown],
outputs=[explanation_output, audio_output, sources_output, steps_output, mcp_output],
)
# Also trigger on Enter key in topic input
topic_input.submit(
fn=process_and_explain,
inputs=[topic_input, persona_dropdown, audio_checkbox, audience_dropdown],
outputs=[explanation_output, audio_output, sources_output, steps_output, mcp_output],
)
return app
# Create the app
app = create_app()
CUSTOM_CSS = """
/* Fix dark mode input visibility */
input, textarea, select {
color: var(--body-text-color) !important;
background-color: var(--input-background-fill) !important;
}
input:hover, textarea:hover, select:hover,
input:focus, textarea:focus, select:focus {
color: var(--body-text-color) !important;
background-color: var(--input-background-fill) !important;
}
/* Ensure placeholder is visible */
input::placeholder, textarea::placeholder {
color: var(--body-text-color-subdued) !important;
opacity: 0.7;
}
"""
if __name__ == "__main__":
app.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
css=CUSTOM_CSS,
mcp_server=True, # Enable MCP server - exposes this app as an MCP tool!
)
|