Spaces:
Sleeping
Sleeping
File size: 2,936 Bytes
3c3ff47 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# 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()
|