import gradio as gr from transformers import pipeline import random import requests from groq import Groq from datetime import datetime # Initialize the sentiment analysis pipeline pipe = pipeline("text-classification", model="bhadresh-savani/bert-base-uncased-emotion") # Initialize Groq client # Relaxing music files relaxing_music = { "Surah Ad-duha": "https://server11.mp3quran.net/yasser/093.mp3", "Surah Rehman": "https://server7.mp3quran.net/basit/Almusshaf-Al-Mojawwad/055.mp3", "Surah Insan": "https://server6.mp3quran.net/qtm/076.mp3", "Surah Takweer": "https://server10.mp3quran.net/jleel/081.mp3", "Surah Qasas": "https://server10.mp3quran.net/jleel/028.mp3" } # Static list of coping strategies coping_strategies = [ "Practice deep breathing exercises for 5 minutes.", "Take a short walk and focus on your surroundings.", "Write down three things you're grateful for today.", "Try a mindfulness meditation session for 10 minutes.", "Listen to calming music or nature sounds.", "Take a moment to celebrate! Reflect on what made you happy. ", "Trust in Allah’s plan: 'And whoever puts their trust in Allah, He will be enough for them", "Face your fears with courage. Remember: 'Fear not, for indeed, I am with you both; I hear and I see.", ] # Function to return a random coping strategy def coping_strategy(): return random.choice(coping_strategies) # Function to fetch motivational quotes from ZenQuotes API def daily_motivation(): url = "https://zenquotes.io/api/random" response = requests.get(url) if response.status_code == 200: data = response.json() quote = data[0]['q'] author = data[0]['a'] return f"{quote} - {author}" else: return "Could not fetch a motivational quote at the moment." # Track if a chat has started and detected mood chat_started = False detected_mood = None # Function to analyze mood using sentiment analysis def analyze_mood(text): global chat_started, detected_mood chat_started = True result = pipe(text)[0] detected_mood = result['label'].capitalize() return f"I sense you're feeling {detected_mood.lower()}." # Function to generate a response using Groq's LLaMA model def groq_chat(text): try: chat_completion = client.chat.completions.create( messages=[ { "role": "system", "content": "You’re a compassionate and knowledgeable medical health advisor..." }, {"role": "user", "content": text} ], model="llama3-8b-8192", ) return chat_completion.choices[0].message.content except Exception as e: return f"Error: {str(e)}" # Function to play relaxing music def play_music(music_choice): music_url = relaxing_music[music_choice] return music_url # Function to handle chat responses def handle_chat(text): bot_response = groq_chat(text) return [(text, bot_response)] # Function to interpret quiz results def interpret_results(answers): # Answer index: # 0-3: Non-distress related (0 points each) # 4-7: Distress related (points based on severity) # Distress question answers distress_answers = answers[4:8] # Calculate distress score distress_score = 0 for answer in distress_answers: if answer == "More than two weeks": distress_score += 3 elif answer == "More than a week": distress_score += 2 elif answer == "A few days but less than a week": distress_score += 1 # Percentage calculation percentage = min(distress_score / 12 * 100, 100) # Assuming max score is 12 # Interpret current situation if percentage > 70: situation = "High distress level. Symptoms are significantly impacting your daily life." elif percentage > 40: situation = "Moderate distress level. Some symptoms are affecting your daily activities." else: situation = "Low distress level. You seem to be managing well, but stay mindful." # Suggestions if percentage > 70: suggestions = "It may be beneficial to seek professional help. Consider talking to a mental health counselor or therapist." elif percentage > 40: suggestions = "Try incorporating stress management techniques into your routine. Reach out to support networks or consider self-help resources." else: suggestions = "Continue with your current coping strategies and maintain a healthy routine. Keep track of any changes in your mental state." return f"**Percentage Level:** {percentage:.2f}%\n\n**Current Situation:** {situation}\n\n**Suggestions:** {suggestions}" # Initialize a list to store journal entries journal_entries = [] # Function to save the journal entry with a timestamp def save_journal(entry): if entry.strip(): # Get the current date and time timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Append the entry to the list with the timestamp journal_entries.append(f"{timestamp} - {entry}") # Return all entries as a single string, each entry on a new line return "\n\n".join(journal_entries) else: return "Please write something to save." # Gradio UI components with gr.Blocks() as demo: gr.Markdown("#
🧘MindfulMate
\n\n**
Be present, be peaceful
**", elem_id="header") with gr.Tabs(): # Tab 1: Chat with MindfulMate with gr.Tab("Chat"): with gr.Row(): # Sidebar for music, coping strategies, and motivation with gr.Column(scale=1): music_choice = gr.Dropdown(choices=list(relaxing_music.keys()), label="Choose the Peace") play_music_btn = gr.Button("Play") audio_output = gr.Audio(label="Now Playing", autoplay=True, interactive=False) options = gr.Dropdown(["Get Coping Strategy", "Daily Motivation"], label="Choose an option") mood_output = gr.Textbox(label="Result", interactive=False) # Handle coping strategy and daily motivation options.change(fn=lambda opt: coping_strategy() if opt == "Get Coping Strategy" else daily_motivation(), inputs=options, outputs=mood_output) play_music_btn.click(fn=play_music, inputs=music_choice, outputs=audio_output) # Main Chat Area with gr.Column(scale=4): chatbot = gr.Chatbot(label="Chat with MindfulMate") with gr.Row(): text_input = gr.Textbox(label="Feel free to share what's in your mind...", scale=3) voice_input = gr.Audio(type="filepath", label="Speak", scale=1) submit_btn = gr.Button("Submit") # Corrected click function to return the correct format submit_btn.click(fn=lambda text: (handle_chat(text), analyze_mood(text)), inputs=text_input, outputs=[chatbot, mood_output]) # Tab 2: Journal with gr.Tab("Journal"): gr.Markdown("### Journaling Section") journal_input = gr.Textbox(label="Write about your day", placeholder="How was your day?", lines=6) save_journal_btn = gr.Button("Save Entry") journal_output = gr.Textbox(label="Your Journal Entries", interactive=False) # Connect the save button to the save_journal function save_journal_btn.click(fn=save_journal, inputs=journal_input, outputs=journal_output) # Tab 3: Take the Quiz with gr.Tab("Take the Quiz"): gr.Markdown("### Mental Health Quiz") question_1 = gr.Dropdown(["Sadness", "Anger", "Fear", "Guilt"], label="Which difficult emotion do you struggle with the most?") question_2 = gr.Dropdown(["0-1 hours", "2-3 hours", "4-5 hours", "More than 5 hours"], label="On an average weekday, how many hours do you spend alone?") question_3 = gr.Dropdown(["Very well", "Somewhat well", "Not very well", "Not at all"], label="How well do you feel you manage your stress?") question_4 = gr.Dropdown(["Introvert", "Extrovert"], label="Would you consider yourself an introvert or an extrovert?") question_5 = gr.Dropdown(["Not at all", "A few days but less than a week", "More than a week", "More than two weeks"], label="Over the last 2 weeks, how often have you been feeling nervous or anxious?") question_6 = gr.Dropdown(["Not at all", "A few days but less than a week", "More than a week", "More than two weeks"], label="Over the last 2 weeks, how often have you been bothered by not being able to control your thoughts or worries?") question_7 = gr.Dropdown(["Not at all", "A few days but less than a week", "More than a week", "More than two weeks"], label="Over the last 2 weeks, how often have you felt little interest or pleasure in doing things that you normally enjoyed doing?") question_8 = gr.Dropdown(["Not at all", "A few days but less than a week", "More than a week", "More than two weeks"], label="Over the last 2 weeks, how often have you felt down, depressed, or hopeless?") quiz_submit = gr.Button("Submit Quiz") quiz_results = gr.Textbox(label="Quiz Results", interactive=False) # Handle quiz results quiz_submit.click(fn=lambda *answers: interpret_results(list(answers)), inputs=[question_1, question_2, question_3, question_4, question_5, question_6, question_7, question_8], outputs=quiz_results) demo.launch()