File size: 5,264 Bytes
e5113bc
 
5e1b314
e5113bc
 
 
 
 
 
f13b0ef
 
 
5e1b314
2573724
e5113bc
3fd18b2
e5113bc
9f919fb
5e1b314
9f919fb
 
 
0da85b2
 
3fd18b2
 
 
 
 
 
9f919fb
e5113bc
 
 
 
9f919fb
e5113bc
 
5e1b314
 
 
 
9f919fb
e5113bc
 
5e1b314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5113bc
 
 
 
 
 
 
 
 
 
9f919fb
 
e5113bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f919fb
e5113bc
9f919fb
e5113bc
 
 
 
9f919fb
e5113bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f919fb
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
import gradio as gr
from transformers import pipeline
import openai  # Import if you are using OpenAI's API
import random
from datetime import datetime

# Initialize sentiment analysis pipeline
sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")

class JournalCompanion:
    def __init__(self):
        self.entries = []
    
    def analyze_entry(self, entry_text):
        if not entry_text.strip():
            return ("Please write something in your journal entry.", "", "", "")

        try:
            # Perform sentiment analysis
            sentiment_result = sentiment_analyzer(entry_text)[0]
            sentiment = sentiment_result["label"].upper()
            sentiment_score = sentiment_result["score"]
        except Exception as e:
            print("Error during sentiment analysis:", e)
            return (
                "An error occurred during analysis. Please try again.",
                "Error",
                "Could not generate prompts due to an error.",
                "Could not generate affirmation due to an error."
            )

        entry_data = {
            "text": entry_text,
            "timestamp": datetime.now().isoformat(),
            "sentiment": sentiment,
            "sentiment_score": sentiment_score
        }
        self.entries.append(entry_data)

        # Generate dynamic responses using a language model
        prompts = self.generate_dynamic_prompts(sentiment)
        affirmation = self.generate_dynamic_affirmation(sentiment)
        sentiment_percentage = f"{sentiment_score * 100:.1f}%"
        message = f"Entry analyzed! Sentiment: {sentiment} ({sentiment_percentage} confidence)"
        
        return message, sentiment, prompts, affirmation

    def generate_dynamic_prompts(self, sentiment):
        prompt_request = f"Generate three reflective journal prompts for a person feeling {sentiment.lower()}."
        try:
            response = openai.Completion.create(
                engine="gpt-3.5-turbo",
                prompt=prompt_request,
                max_tokens=60,
                n=1
            )
            prompts = response.choices[0].text.strip()
        except Exception as e:
            print("Error generating prompts:", e)
            prompts = "Could not generate prompts at this time."
        return prompts

    def generate_dynamic_affirmation(self, sentiment):
        affirmation_request = f"Generate an affirmation for someone who is feeling {sentiment.lower()}."
        try:
            response = openai.Completion.create(
                engine="gpt-3.5-turbo",
                prompt=affirmation_request,
                max_tokens=20,
                n=1
            )
            affirmation = response.choices[0].text.strip()
        except Exception as e:
            print("Error generating affirmation:", e)
            affirmation = "Could not generate an affirmation at this time."
        return affirmation

    def get_monthly_insights(self):
        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():
    journal = JournalCompanion()
    
    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():
                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():
                result_message = gr.Markdown(label="Analysis Result")
                sentiment_output = gr.Textbox(label="Detected Sentiment")
                prompt_output = gr.Markdown(label="Reflective Prompts")
                affirmation_output = gr.Textbox(label="Daily Affirmation")
                
        with gr.Row():
            insights_btn = gr.Button("Show Monthly Insights")
            insights_output = gr.Markdown(label="Monthly Insights")

        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

if __name__ == "__main__":
    interface = create_journal_interface()
    interface.launch()