import gradio as gr import json from gtts import gTTS import os import random # Load poem and explanations with open('poem.txt', 'r', encoding='utf-8') as f: poem_data = f.read() with open('explanations.json', 'r', encoding='utf-8') as f: explanations = json.load(f) # Stanza split stanzas = poem_data.strip().split("Stanza") stanza_map = {str(i): s.strip() for i, s in enumerate(stanzas[1:], start=1)} # Poem Generator def generate_poem(objects): starters = [ f"In the world of the {objects[0]}, stories unfold,", f"The {objects[0]} stands tall and bold.", f"A {objects[0]} whispers under the sky,", f"Where the {objects[0]} and {objects[1]} lie." ] middles = [ f"The {objects[1]} flows with tales unknown,", f"Near the {objects[1]}, seeds are sown.", f"And the {objects[1]} sings a gentle tune,", f"Under stars and a watching moon." ] endings = [ "In quiet places, poems are made,", "With every breeze, old memories fade.", "Such beauty lives in things so small,", "They write their poems after all." ] return f"{random.choice(starters)}\n{random.choice(middles)}\n{random.choice(endings)}" # Logic def handle_input(user_input, poem_topic): user_input = user_input.lower() response = "" if "read stanza" in user_input: for i in range(1, 4): if str(i) in user_input: response = f"Stanza {i}:\n{stanza_map[str(i)]}" break elif "explain" in user_input: for i in range(1, 4): if str(i) in user_input: response = f"Explanation:\n{explanations[str(i)]['explanation']}" break elif "poetic devices" in user_input or "devices" in user_input: for i in range(1, 4): if str(i) in user_input: devices = ", ".join(explanations[str(i)]["devices"]) response = f"Poetic Devices in stanza {i}: {devices}" break elif "poet" in user_input: response = explanations["poet"] elif poem_topic: objs = [x.strip() for x in poem_topic.split("and") if x.strip()] if len(objs) < 2: objs.append("dreams") poem = generate_poem(objs[:2]) response = f"Here's a poem about {', '.join(objs[:2])}:\n\n{poem}" else: response = "Please ask me to read or explain a stanza, or generate a poem." tts = gTTS(response) tts.save("poembot_response.mp3") return response, "poembot_response.mp3" iface = gr.Interface( fn=handle_input, inputs=[ gr.Textbox(label="🎤 Ask me something (e.g., 'Read stanza 1')"), gr.Textbox(label="🎨 Make a poem about (e.g., 'cloud and time')"), ], outputs=[ gr.Textbox(label="📖 Response"), gr.Audio(label="🔊 Voice Response", autoplay=True) ], title="PoemBot - Voice Poetry Assistant", description="Ask me to read stanzas, explain, find poetic devices or create poems from your words!" ) iface.launch()