import gradio as gr from transformers import pipeline, set_seed from gtts import gTTS import tempfile, os, re # ---------- Configuration ---------- MODEL_NAME = "microsoft/DialoGPT-medium" set_seed(42) # ---------- Load model ---------- try: generator = pipeline("text-generation", model=MODEL_NAME) MODEL_READY = True print(f"✅ Model '{MODEL_NAME}' loaded.") except Exception as e: print("⚠️ Model load failed:", e) generator = None MODEL_READY = False # ---------- Memory ---------- CONVERSATION_MEMORY = [] # ---------- Creator detection ---------- CREATOR_PATTERNS = re.compile( r"(?i)\b(who|whom|whose|who's|who is)\b.*\b(create|created|made|built|developed|author|authored|program|sponsor|sponsored|owner|founder|behind)\b" r"|\b(create|created|made|built|developed)\b.*\b(you|this bot|this)\b" r"|\b(who (created|made|built) (you|this))\b" ) def detect_creator_intent(text): return bool(CREATOR_PATTERNS.search(text)) # ---------- Rule-based fallback ---------- def rule_based_reply(message): m = message.lower() if detect_creator_intent(m): return "I was created by AL-AMEEN, proudly sponsored by UNI ABUJA." if "your name" in m or "who are you" in m: return "I'm YAAYA, your smart assistant, created by AL-AMEEN and sponsored by UNI ABUJA." if any(g in m for g in ["hello", "hi", "hey"]): return "Hello there! I'm YAAYA. How can I help you today?" if "thank" in m: return "You're welcome! 😊" if "chemistry" in m: return "Chemistry is the science that studies matter — its structure, composition, and how it changes." return "I'm thinking... Could you rephrase that?" # ---------- AI generator ---------- def generate_with_model(prompt, max_new_tokens=60): if not MODEL_READY: return None out = generator( prompt, max_new_tokens=max_new_tokens, do_sample=True, temperature=0.8, top_k=50, top_p=0.9, repetition_penalty=1.3, num_return_sequences=1, eos_token_id=50256 ) text = out[0]["generated_text"] reply = text.split("YAAYA:")[-1].strip() if "YAAYA:" in text else text[len(prompt):].strip() reply = re.sub(r"(User:.*)+", "", reply) reply = re.sub(r"[^a-zA-Z0-9,.'!?\\s]", "", reply).strip() if len(reply.split()) < 3 or "god" in reply.lower(): return None return reply # ---------- Text-to-speech (male-style via gTTS pitch trick) ---------- def text_to_speech_mp3(text): try: tts = gTTS(text, lang='en', slow=False) tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") tts.save(tmp.name) return tmp.name except Exception as e: print("TTS failed:", e) return None # ---------- Chat logic ---------- def chat_with_yaaya(user_message, history): user_message = (user_message or "").strip() if not user_message: return history, "", None CONVERSATION_MEMORY.append(("user", user_message)) if detect_creator_intent(user_message): bot_reply = "I was created by AL-AMEEN, proudly sponsored by UNI ABUJA." else: if MODEL_READY: recent_turns = CONVERSATION_MEMORY[-10:] prompt = "" for role, txt in recent_turns: prompt += f"{role.capitalize()}: {txt}\n" prompt += f"User: {user_message}\nYAAYA:" gen = generate_with_model(prompt) bot_reply = gen if gen else rule_based_reply(user_message) else: bot_reply = rule_based_reply(user_message) CONVERSATION_MEMORY.append(("yaaya", bot_reply)) history = history + [(user_message, bot_reply)] audio_path = text_to_speech_mp3(bot_reply) return history, "", audio_path # clear textbox after send def reset_memory(): global CONVERSATION_MEMORY CONVERSATION_MEMORY = [] return [], "", None # ---------- CSS ---------- css = """ body { background: linear-gradient(180deg, #010316 0%, #08173c 100%); color: #e6eef8; font-family: 'Segoe UI', sans-serif; } .chatbot .message.user { background: linear-gradient(90deg, rgba(3,10,30,0.8), rgba(3,20,60,0.4)); color: #b9f2ff; } .chatbot .message.bot { background: linear-gradient(90deg, rgba(140,82,255,0.08), rgba(8,247,254,0.05)); color: #e9e0ff; } #title { color: #08f7fe; text-align:center; font-weight:700; font-size:24px; } #subtitle { color: #cbb7ff; text-align:center; margin-bottom:12px; font-size:15px; } """ # ---------- UI ---------- with gr.Blocks(css=css, theme=gr.themes.Soft(primary_hue="blue", secondary_hue="purple")) as demo: gr.HTML("

🧠 YAAYA

") gr.HTML("
Created by AL-AMEEN — Sponsored by UNI ABUJA
") chatbot = gr.Chatbot(elem_id="chatbot", label="Chat with YAAYA", height=450) with gr.Row(): txt = gr.Textbox(show_label=False, placeholder="Type your message and press Enter...") send = gr.Button("Send") clear = gr.Button("Clear Memory") audio = gr.Audio(label="YAAYA's Voice", interactive=False) send.click(chat_with_yaaya, inputs=[txt, chatbot], outputs=[chatbot, txt, audio]) txt.submit(chat_with_yaaya, inputs=[txt, chatbot], outputs=[chatbot, txt, audio]) clear.click(lambda: reset_memory(), outputs=[chatbot, txt, audio]) if __name__ == "__main__": demo.launch()