Spaces:
Sleeping
Sleeping
import gradio as gr | |
from transformers import pipeline | |
import random | |
from datetime import datetime | |
import json | |
import os | |
# Initialize sentiment analysis pipeline | |
sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english") | |
class JournalPrompts: | |
def __init__(self): | |
self.prompts = { | |
# Emotion-based prompts | |
"POSITIVE": [ | |
"What moments brought you the most joy today, and why?", | |
"How did you contribute to your own happiness today?", | |
"What accomplishment, big or small, are you proud of right now?", | |
"Who made a positive impact on your day? How can you pay it forward?", | |
"What unexpected positive surprise occurred today?", | |
"How did you show kindness to yourself or others today?", | |
"What made you laugh or smile today?", | |
"What personal strength helped you succeed today?", | |
"How did you make progress toward your goals today?", | |
"What are you feeling grateful for in this moment?" | |
], | |
"NEGATIVE": [ | |
"What is weighing on your mind, and what's one small step you could take to address it?", | |
"If you could tell someone exactly how you're feeling right now, what would you say?", | |
"What would make you feel even 1% better right now?", | |
"What lesson might be hidden in this challenging situation?", | |
"How have you overcome similar challenges in the past?", | |
"What support do you need right now, and who could provide it?", | |
"If your future self could send you a message of comfort, what would they say?", | |
"What aspects of this situation are within your control?", | |
"How can you show yourself compassion during this difficult time?", | |
"What would you tell a friend who was facing this same situation?" | |
], | |
"NEUTRAL": [ | |
"What's occupying your thoughts right now?", | |
"How would you describe your energy level today?", | |
"What would make today feel more meaningful?", | |
"What patterns have you noticed in your daily life lately?", | |
"What would you like to explore or learn more about?", | |
"How aligned are your actions with your values today?", | |
"What change would you like to see in your life six months from now?", | |
"What's something you've been putting off that you could tackle today?", | |
"How have your priorities shifted recently?", | |
"What boundaries do you need to set or maintain?" | |
], | |
# Growth prompts | |
"GROWTH": [ | |
"What skill would you like to develop further and why?", | |
"How have your beliefs or perspectives changed recently?", | |
"What habit would you like to build or break?", | |
"What's the most important lesson you've learned this week?", | |
"How are you different now compared to a year ago?", | |
"What feedback have you received recently that resonated with you?", | |
"What's one area of your life where you feel stuck? What's keeping you there?", | |
"What would you attempt if you knew you couldn't fail?", | |
"How do you want to be remembered?", | |
"What does success mean to you right now?" | |
], | |
# Additional categories as shown in previous prompt lists... | |
"WELLNESS": [ | |
"How are you taking care of your physical health today?", | |
"What does your body need right now?", | |
"How well did you sleep last night? What affected your sleep?", | |
"What activities make you feel most energized?", | |
"How do you deal with stress? What works best for you?", | |
"What self-care practice would be most helpful today?", | |
"How connected do you feel to your body right now?", | |
"What healthy boundary do you need to set?", | |
"What does balance look like in your life?", | |
"How do you recharge when you're feeling depleted?" | |
], | |
"REFLECTION": [ | |
"What patterns have you noticed in your behavior lately?", | |
"How have your priorities shifted in the past year?", | |
"What advice would you give your younger self?", | |
"What are you ready to let go of?", | |
"What beliefs about yourself are holding you back?", | |
"How do you handle uncertainty?", | |
"What role does gratitude play in your life?", | |
"What legacy do you want to leave?", | |
"How do your values guide your decisions?", | |
"What questions are you sitting with right now?" | |
] | |
} | |
def get_prompt(self, category): | |
"""Get a random prompt from the specified category""" | |
if category not in self.prompts: | |
return "Invalid category" | |
return random.choice(self.prompts[category]) | |
def get_mixed_prompts(self, sentiment): | |
"""Get a mix of prompts based on sentiment and other categories""" | |
prompts = [] | |
# Add sentiment-based prompt | |
prompts.append(f"Emotional: {self.get_prompt(sentiment)}") | |
# Add growth prompt | |
prompts.append(f"Growth: {self.get_prompt('GROWTH')}") | |
# Add wellness or reflection prompt | |
random_category = random.choice(['WELLNESS', 'REFLECTION']) | |
prompts.append(f"{random_category}: {self.get_prompt(random_category)}") | |
return prompts | |
class JournalCompanion: | |
def __init__(self): | |
# Initialize storage for entries (in-memory for demo) | |
self.entries = [] | |
self.journal_prompts = JournalPrompts() | |
# Affirmations based on sentiment | |
self.affirmations = { | |
"POSITIVE": [ | |
"You're radiating positive energy! Keep embracing joy.", | |
"Your optimism is inspiring. You're on the right path.", | |
"You have so much to be proud of. Keep shining!", | |
"Your positive mindset creates beautiful opportunities." | |
], | |
"NEGATIVE": [ | |
"It's okay to feel this way. You're stronger than you know.", | |
"Every challenge helps you grow. You've got this.", | |
"Tomorrow brings new opportunities. Be gentle with yourself.", | |
"Your feelings are valid, and this too shall pass." | |
], | |
"NEUTRAL": [ | |
"You're exactly where you need to be right now.", | |
"Your journey is unique and valuable.", | |
"Take a moment to appreciate your progress.", | |
"Every moment is a chance for a fresh perspective." | |
] | |
} | |
def analyze_entry(self, entry_text): | |
"""Analyze journal entry and provide feedback""" | |
if not entry_text.strip(): | |
return { | |
"message": "Please write something in your journal entry.", | |
"sentiment": "", | |
"prompts": [], | |
"affirmation": "" | |
} | |
# Perform sentiment analysis | |
sentiment_result = sentiment_analyzer(entry_text)[0] | |
sentiment = sentiment_result["label"] | |
# Store entry with metadata | |
entry_data = { | |
"text": entry_text, | |
"timestamp": datetime.now().isoformat(), | |
"sentiment": sentiment, | |
"sentiment_score": sentiment_result["score"] | |
} | |
self.entries.append(entry_data) | |
# Get mixed prompts based on sentiment and other categories | |
prompts = self.journal_prompts.get_mixed_prompts(sentiment) | |
# Get affirmation | |
affirmation = random.choice(self.affirmations[sentiment]) | |
# Calculate sentiment score percentage | |
sentiment_percentage = f"{sentiment_result['score']*100:.1f}%" | |
message = f"Entry analyzed! Sentiment: {sentiment} ({sentiment_percentage} confidence)" | |
return { | |
"message": message, | |
"sentiment": sentiment, | |
"prompts": "\n\n".join(prompts), | |
"affirmation": affirmation | |
} | |
def get_monthly_insights(self): | |
"""Generate monthly insights from stored entries""" | |
if not self.entries: | |
return "No entries yet to analyze." | |
total_entries = len(self.entries) | |
positive_entries = sum(1 for entry in self.entries if entry["sentiment"] == "POSITIVE") | |
insights = f"""Monthly Insights: | |
Total Entries: {total_entries} | |
Positive Entries: {positive_entries} ({(positive_entries/total_entries*100):.1f}%) | |
Negative Entries: {total_entries - positive_entries} ({((total_entries-positive_entries)/total_entries*100):.1f}%) | |
""" | |
return insights | |
def create_journal_interface(): | |
# Initialize the journal companion | |
journal = JournalCompanion() | |
# Define the interface | |
with gr.Blocks(title="AI Journal Companion") as interface: | |
gr.Markdown("# π AI Journal Companion") | |
gr.Markdown("Write your thoughts and receive AI-powered insights, prompts, and affirmations.") | |
with gr.Row(): | |
with gr.Column(): | |
# Input components | |
entry_input = gr.Textbox( | |
label="Journal Entry", | |
placeholder="Write your journal entry here...", | |
lines=5 | |
) | |
submit_btn = gr.Button("Submit Entry", variant="primary") | |
with gr.Column(): | |
# Output components | |
result_message = gr.Textbox(label="Analysis Result") | |
sentiment_output = gr.Textbox(label="Detected Sentiment") | |
prompt_output = gr.Textbox(label="Reflective Prompts", lines=3) | |
affirmation_output = gr.Textbox(label="Daily Affirmation") | |
with gr.Row(): | |
insights_btn = gr.Button("Show Monthly Insights") | |
insights_output = gr.Textbox(label="Monthly Insights") | |
# Set up event handlers | |
submit_btn.click( | |
fn=journal.analyze_entry, | |
inputs=[entry_input], | |
outputs=[ | |
result_message, | |
sentiment_output, | |
prompt_output, | |
affirmation_output | |
] | |
) | |
insights_btn.click( | |
fn=journal.get_monthly_insights, | |
inputs=[], | |
outputs=[insights_output] | |
) | |
return interface | |
# Create and launch the interface | |
if __name__ == "__main__": | |
interface = create_journal_interface() | |
interface.launch() |