File size: 6,311 Bytes
e5113bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
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()