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 JournalCompanion: def __init__(self): # Initialize storage for entries (in-memory for demo) self.entries = [] # Reflective prompts based on sentiment self.prompts = { "POSITIVE": [ "What made this experience particularly meaningful?", "How can you carry this positive energy forward?", "Who would you like to share this joy with?", "What values of yours were honored in this moment?" ], "NEGATIVE": [ "What could help make this situation better?", "What have you learned from this challenge?", "Who could you reach out to for support?", "What would be a small step toward improvement?" ], "NEUTRAL": [ "What's on your mind right now?", "What would make today more meaningful?", "What are you looking forward to?", "What would you like to explore further?" ] } # 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": "", "prompt": "", "affirmation": "" } # Perform sentiment analysis sentiment_result = sentiment_analyzer(entry_text)[0] sentiment = "POSITIVE" if sentiment_result["label"] == "POSITIVE" else "NEGATIVE" # 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) # Generate response prompt = random.choice(self.prompts[sentiment]) 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, "prompt": prompt, "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 Prompt") 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()