import os
from groq import Groq
import gradio as gr
from gtts import gTTS
import re
groq_key = os.environ.get("GROQ_API_KEY")
client = Groq(api_key=groq_key)
def generate_story(age, theme, language):
system_msg = {"role": "system", "content": "You write age-appropriate stories with complete endings and a moral."}
age_i = int(age)
length = "300 words" if age_i <= 6 else "600 words" if age_i <= 9 else "1000 words"
user_msg = {
"role": "user",
"content": f"Write a complete story for a {age}-year-old child. Theme: {theme}. Language: {language}. Length about {length}. End with a clear moral of the story."
}
response = client.chat.completions.create(
messages=[system_msg, user_msg],
model="openai/gpt-oss-20b",
max_tokens=2000,
temperature=0.8
)
return response.choices[0].message.content.strip()
def story_to_speech(story, language_code='en'):
tts = gTTS(text=story, lang=language_code)
filename = "/tmp/story.mp3"
tts.save(filename)
return filename
def create_story_interface(age, theme, language, tts_option):
story = generate_story(age, theme, language)
story = re.sub(r'[*_#`~]', '', story)
lines = story.split("\n", 1)
title, rest_of_story = (lines[0], lines[1]) if len(lines) > 1 else (lines[0], "")
if language.lower().startswith("u"):
story_html = f'
{title}
{rest_of_story}
'
lang_code = "ur"
else:
story_html = f'{title}
{rest_of_story}
'
lang_code = "en"
audio_file = story_to_speech(story, lang_code) if tts_option else None
return story_html, audio_file
age_options = [str(i) for i in range(3, 13)]
theme_options = ["Adventure","Animals","Fantasy","Educational","Friendship","Magic","Science","Mystery","Space","Nature","Kindness","Courage"]
language_options = ["English", "Urdu"]
# -----------------------------------------------
# GRADIO APP
# -----------------------------------------------
with gr.Blocks() as iface:
gr.HTML("""
""")
gr.HTML("""🌈 StoryTime AI🎪
""")
gr.HTML("""🎯 Create amazing stories that spark imagination and teach valuable lessons!
""")
with gr.Row():
with gr.Column(scale=1, min_width=300):
with gr.Group(elem_classes="control-panel"):
age_input = gr.Dropdown(age_options, label="👶 Child's Age", value="5")
theme_input = gr.Dropdown(theme_options, label="🎭 Story Theme", value="Adventure")
language_input = gr.Dropdown(language_options, label="🌍 Language", value="English")
tts_input = gr.Checkbox(label="🎵 Include Audio Story", value=True)
generate_btn = gr.Button("✨ Create Magical Story! ✨", elem_classes="generate-btn")
with gr.Column(scale=2):
with gr.Group(elem_classes="story-container"):
story_output = gr.Markdown("Your story will appear here!", show_label=False)
audio_output = gr.Audio(label="Audio Story", elem_classes="audio-player")
gr.HTML("""""")
generate_btn.click(
create_story_interface,
[age_input, theme_input, language_input, tts_input],
[story_output, audio_output]
)
iface.launch(ssr_mode=False)