moodanalyzer / app.py
razanalsulami's picture
Create app.py
3c3ff47 verified
raw
history blame
2.94 kB
# Import required libraries
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag
from transformers import pipeline
import gradio as gr
# Download NLTK data
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('stopwords')
# Load Hugging Face's sentiment analysis pipeline
sentiment_analyzer = pipeline('sentiment-analysis')
# Function to extract keywords (nouns and verbs)
def extract_keywords(text):
stop_words = set(stopwords.words('english'))
words = word_tokenize(text)
words_filtered = [word for word in words if word.isalnum() and word.lower() not in stop_words]
# Part-of-speech tagging
tagged = pos_tag(words_filtered)
# Keep only nouns and verbs
keywords = [word for word, tag in tagged if tag.startswith('NN') or tag.startswith('VB')]
return keywords
# Analyze mood and provide suggestions based on keywords
def analyze_journal(text):
keywords = extract_keywords(text)
sentiment_result = sentiment_analyzer(text)[0]
mood_label = sentiment_result['label']
# Generate suggestions based on keywords and mood
suggestions = []
if mood_label == "POSITIVE":
suggestions.append("It seems you're feeling good! Keep up the positive activities.")
elif mood_label == "NEGATIVE":
suggestions.append("It looks like you're feeling down. Consider trying mindfulness exercises or talking to a friend.")
else:
suggestions.append("You're feeling neutral. It's a good time to reflect and engage in self-care.")
# Personalized suggestions based on keywords
if 'work' in keywords or 'job' in keywords:
suggestions.append("You mentioned work. Remember to balance tasks with self-care to avoid burnout.")
if 'stress' in keywords or 'anxious' in keywords:
suggestions.append("It seems like you're feeling stressed. Deep breathing exercises or a short walk might help.")
if 'happy' in keywords or 'joy' in keywords:
suggestions.append("You're in a good mood! Keep doing activities that bring you joy.")
if 'tired' in keywords or 'sleep' in keywords:
suggestions.append("You're feeling tired. Getting enough rest is important for mental well-being.")
return f"Keywords: {', '.join(keywords)}\nMood: {mood_label}\n\nSuggestions:\n- " + "\n- ".join(suggestions)
# Gradio interface for the journal analyzer
iface = gr.Interface(
fn=analyze_journal, # Function to call for analyzing the journal
inputs=gr.components.Textbox(lines=5, label="Write your journal entry here"), # Input for journal text
outputs="text", # Output as text (keywords, mood, and suggestions)
title="Mental Health Mood Analyzer",
description="Write about your day, and the analyzer will suggest improvements based on your mood and keywords."
)
# Launch the Gradio interface
iface.launch()