Pranav0111 commited on
Commit
e5113bc
·
verified ·
1 Parent(s): de5f825

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -0
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ import random
4
+ from datetime import datetime
5
+ import json
6
+ import os
7
+
8
+ # Initialize sentiment analysis pipeline
9
+ sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
10
+
11
+ class JournalCompanion:
12
+ def __init__(self):
13
+ # Initialize storage for entries (in-memory for demo)
14
+ self.entries = []
15
+
16
+ # Reflective prompts based on sentiment
17
+ self.prompts = {
18
+ "POSITIVE": [
19
+ "What made this experience particularly meaningful?",
20
+ "How can you carry this positive energy forward?",
21
+ "Who would you like to share this joy with?",
22
+ "What values of yours were honored in this moment?"
23
+ ],
24
+ "NEGATIVE": [
25
+ "What could help make this situation better?",
26
+ "What have you learned from this challenge?",
27
+ "Who could you reach out to for support?",
28
+ "What would be a small step toward improvement?"
29
+ ],
30
+ "NEUTRAL": [
31
+ "What's on your mind right now?",
32
+ "What would make today more meaningful?",
33
+ "What are you looking forward to?",
34
+ "What would you like to explore further?"
35
+ ]
36
+ }
37
+
38
+ # Affirmations based on sentiment
39
+ self.affirmations = {
40
+ "POSITIVE": [
41
+ "You're radiating positive energy! Keep embracing joy.",
42
+ "Your optimism is inspiring. You're on the right path.",
43
+ "You have so much to be proud of. Keep shining!",
44
+ "Your positive mindset creates beautiful opportunities."
45
+ ],
46
+ "NEGATIVE": [
47
+ "It's okay to feel this way. You're stronger than you know.",
48
+ "Every challenge helps you grow. You've got this.",
49
+ "Tomorrow brings new opportunities. Be gentle with yourself.",
50
+ "Your feelings are valid, and this too shall pass."
51
+ ],
52
+ "NEUTRAL": [
53
+ "You're exactly where you need to be right now.",
54
+ "Your journey is unique and valuable.",
55
+ "Take a moment to appreciate your progress.",
56
+ "Every moment is a chance for a fresh perspective."
57
+ ]
58
+ }
59
+
60
+ def analyze_entry(self, entry_text):
61
+ """Analyze journal entry and provide feedback"""
62
+ if not entry_text.strip():
63
+ return {
64
+ "message": "Please write something in your journal entry.",
65
+ "sentiment": "",
66
+ "prompt": "",
67
+ "affirmation": ""
68
+ }
69
+
70
+ # Perform sentiment analysis
71
+ sentiment_result = sentiment_analyzer(entry_text)[0]
72
+ sentiment = "POSITIVE" if sentiment_result["label"] == "POSITIVE" else "NEGATIVE"
73
+
74
+ # Store entry with metadata
75
+ entry_data = {
76
+ "text": entry_text,
77
+ "timestamp": datetime.now().isoformat(),
78
+ "sentiment": sentiment,
79
+ "sentiment_score": sentiment_result["score"]
80
+ }
81
+ self.entries.append(entry_data)
82
+
83
+ # Generate response
84
+ prompt = random.choice(self.prompts[sentiment])
85
+ affirmation = random.choice(self.affirmations[sentiment])
86
+
87
+ # Calculate sentiment score percentage
88
+ sentiment_percentage = f"{sentiment_result['score']*100:.1f}%"
89
+
90
+ message = f"Entry analyzed! Sentiment: {sentiment} ({sentiment_percentage} confidence)"
91
+
92
+ return {
93
+ "message": message,
94
+ "sentiment": sentiment,
95
+ "prompt": prompt,
96
+ "affirmation": affirmation
97
+ }
98
+
99
+ def get_monthly_insights(self):
100
+ """Generate monthly insights from stored entries"""
101
+ if not self.entries:
102
+ return "No entries yet to analyze."
103
+
104
+ total_entries = len(self.entries)
105
+ positive_entries = sum(1 for entry in self.entries if entry["sentiment"] == "POSITIVE")
106
+
107
+ insights = f"""Monthly Insights:
108
+ Total Entries: {total_entries}
109
+ Positive Entries: {positive_entries} ({(positive_entries/total_entries*100):.1f}%)
110
+ Negative Entries: {total_entries - positive_entries} ({((total_entries-positive_entries)/total_entries*100):.1f}%)
111
+ """
112
+ return insights
113
+
114
+ def create_journal_interface():
115
+ # Initialize the journal companion
116
+ journal = JournalCompanion()
117
+
118
+ # Define the interface
119
+ with gr.Blocks(title="AI Journal Companion") as interface:
120
+ gr.Markdown("# 📔 AI Journal Companion")
121
+ gr.Markdown("Write your thoughts and receive AI-powered insights, prompts, and affirmations.")
122
+
123
+ with gr.Row():
124
+ with gr.Column():
125
+ # Input components
126
+ entry_input = gr.Textbox(
127
+ label="Journal Entry",
128
+ placeholder="Write your journal entry here...",
129
+ lines=5
130
+ )
131
+ submit_btn = gr.Button("Submit Entry", variant="primary")
132
+
133
+ with gr.Column():
134
+ # Output components
135
+ result_message = gr.Textbox(label="Analysis Result")
136
+ sentiment_output = gr.Textbox(label="Detected Sentiment")
137
+ prompt_output = gr.Textbox(label="Reflective Prompt")
138
+ affirmation_output = gr.Textbox(label="Daily Affirmation")
139
+
140
+ with gr.Row():
141
+ insights_btn = gr.Button("Show Monthly Insights")
142
+ insights_output = gr.Textbox(label="Monthly Insights")
143
+
144
+ # Set up event handlers
145
+ submit_btn.click(
146
+ fn=journal.analyze_entry,
147
+ inputs=[entry_input],
148
+ outputs=[
149
+ result_message,
150
+ sentiment_output,
151
+ prompt_output,
152
+ affirmation_output
153
+ ]
154
+ )
155
+
156
+ insights_btn.click(
157
+ fn=journal.get_monthly_insights,
158
+ inputs=[],
159
+ outputs=[insights_output]
160
+ )
161
+
162
+ return interface
163
+
164
+ # Create and launch the interface
165
+ if __name__ == "__main__":
166
+ interface = create_journal_interface()
167
+ interface.launch()