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 client = Groq(api_key="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") # 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("#