New discussion

yarab

#16 opened 3 months ago by
Mariam-33333

shit

#12 opened 3 months ago by
Mariam-33333

Delete app.py

#3 opened 3 months ago by
Mariam-33333

Delete app.py

#2 opened 3 months ago by
Mariam-33333

import gradio as gr from huggingface_hub import InferenceClient import random import re from transformers import MarianMTModel, MarianTokenizer from gtts import gTTS import tempfile import whisper import torch # ✅ Allowed mental health keywords (EN + AR + transliterated Arabic) MENTAL_KEYWORDS = [ # English "depression", "depressed", "anxiety", "anxious", "panic", "stress", "sad", "lonely", "trauma", "mental", "therapy", "therapist", "counselor", "mood", "overwhelmed", "anger", "fear", "worry", "self-esteem", "confidence", "motivation", "relationship", "cope", "coping", "relax", "calm", "sleep", "emotion", "feeling", "feel", "thoughts", "help", "life", "advice", "unmotivated", "lost", "hopeless", "tired", "burnout", "cry", "hurt", "love", "breakup", "friend", "family", "alone", "heartbroken", "scared", "fearful", # Transliterated Arabic "ana", "zahqan", "daye2", "ha2t", "mota3ab", "mota3eb", "za3lan", "malo", "khalni", "mash3or", "bakhaf", "w7ed", "msh 3aref", "mash fahem", "malish", "3ayez", "ayez", "7azeen", "mdaye2", # Arabic "حزين", "تعبان", "قلق", "خايف", "وحدة", "ضيق", "توتر", "زعلان", "اكتئاب", "علاج", "مشاعر", "مضغوط", "قلقان", "وحدي", "مش مبسوط", "زهقان", "ضايق", "تعب", "مش مرتاح", ] # ✅ Off-topic keywords (EN + AR) OFF_TOPIC = [ "recipe", "song", "music", "lyrics", "joke", "funny", "laugh", "code", "python", "program", "game", "food", "cook", "movie", "film", "series", "sport", "football", "instagram", "tiktok", "money", "business", "crypto", "ai", "computer", "نكتة", "ضحك", "اغنية", "اغاني", "طبخ", "اكل", "فيلم", "مسلسل", "كورة", "رياضة", "بيزنس", "فلوس", "العاب", "لعبة", "كود", "برمجة", "ذكاء اصطناعي" ] # ✅ Random off-topic replies OFF_TOPIC_RESPONSES = [ "I'm here to help with emotional and mental well-being. Let's focus on how you're feeling, coping, or managing your emotions today.", "I specialize in mental and emotional health conversations. Tell me what’s been on your mind lately.", "Let’s bring it back to how you’ve been feeling — I’m here to help you talk through emotions, stress, or challenges.", "My goal is to support your mental health. How have things been emotionally for you lately?", "I’m here for emotional and mental support only. What’s been bothering you recently?", "Let's focus on your thoughts and feelings — I can help you process or manage them better.", "It sounds like you might be going off-topic. Can we talk about how you’ve been feeling instead?", "Let’s keep this space focused on your emotions and well-being. What’s been heavy on your mind lately?", ] # ✅ Detect Arabic def contains_arabic(text: str) -> bool: return bool(re.search(r"[\u0600-\u06FF]", text)) # ✅ Check if user message is mental health–related def is_mental_health_related(text: str) -> bool: text_lower = text.lower() has_arabic = contains_arabic(text_lower) if any(word in text_lower for word in OFF_TOPIC): return False if any(word in text_lower for word in MENTAL_KEYWORDS): return True if has_arabic: return True return False # ✅ Main text-based response function def respond(message, history, system_message, max_tokens, temperature, top_p, hf_token: gr.OAuthToken): if not is_mental_health_related(message): yield random.choice(OFF_TOPIC_RESPONSES) return locked_system_message = ( "You are a licensed mental health therapy assistant. " "You respond with empathy, emotional intelligence, and a therapeutic tone. " "Never answer questions unrelated to emotional or mental wellness, even if they are in another language." ) client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b") messages = [{"role": "system", "content": locked_system_message}] messages.extend(history) messages.append({"role": "user", "content": message}) response = "" for msg in client.chat_completion( messages, max_tokens=max_tokens, stream=True, temperature=temperature, top_p=top_p, ): choices = msg.choices token = "" if len(choices) and choices[0].delta.content: token = choices[0].delta.content response += token yield response # --------------------------- # 🧠 Voice Chat + Translation System # --------------------------- whisper_model = whisper.load_model("base") # Load translation models en_to_ar_model = MarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-ar") en_to_ar_tokenizer = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-ar") ar_to_en_model = MarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-ar-en") ar_to_en_tokenizer = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-ar-en") def translate_en_to_ar(text): tokens = en_to_ar_tokenizer(text, return_tensors="pt", padding=True) translated = en_to_ar_model.generate(**tokens) return en_to_ar_tokenizer.decode(translated[0], skip_special_tokens=True) def translate_ar_to_en(text): tokens = ar_to_en_tokenizer(text, return_tensors="pt", padding=True) translated = ar_to_en_model.generate(**tokens) return ar_to_en_tokenizer.decode(translated[0], skip_special_tokens=True) def voice_chat(audio, language, hf_token: gr.OAuthToken): # 1️⃣ Voice → Text result = whisper_model.transcribe(audio) user_text = result["text"] # 2️⃣ Translate to English if Arabic if language == "Arabic": user_text = translate_ar_to_en(user_text) # 3️⃣ Get chatbot response client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b") messages = [ {"role": "system", "content": "You are a kind, empathetic therapy assistant."}, {"role": "user", "content": user_text}, ] response_text = client.chat_completion(messages, max_tokens=200).choices[0].message["content"] # 4️⃣ Translate back to Arabic if needed final_text = translate_en_to_ar(response_text) if language == "Arabic" else response_text # 5️⃣ Text → Voice tts_lang = 'ar' if language == "Arabic" else 'en' tts = gTTS(final_text, lang=tts_lang) tts_path = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) tts.save(tts_path.name) return final_text, tts_path.name # --------------------------- # 🧩 Gradio Interface (Text + Voice Tabs) # --------------------------- with gr.Blocks(title="🧠 Mental Health Therapy Chatbot") as demo: with gr.Tabs(): with gr.Tab("💬 Text Chat"): with gr.Sidebar(): gr.LoginButton() chatbot = gr.ChatInterface( respond, type="messages", additional_inputs=[ gr.Textbox(value="You are a friendly Chatbot.", label="System message"), gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"), ], ) chatbot.render() with gr.Tab("🎙️ Voice Chat"): with gr.Row(): audio_input = gr.Audio(source="microphone", type="filepath", label="🎤 Speak Here") language_input = gr.Radio(["English", "Arabic"], value="English", label="Language") voice_output_text = gr.Textbox(label="💬 Chatbot Response") voice_output_audio = gr.Audio(label="🔊 Voice Output") gr.LoginButton() gr.Button("Start Voice Chat").click( voice_chat, inputs=[audio_input, language_input, gr.OAuthToken()], outputs=[voice_output_text, voice_output_audio], ) if __name__ == "__main__": demo.launch()

1
#1 opened 3 months ago by
Mariam-33333