Pranav0111 commited on
Commit
5e1b314
1 Parent(s): 3fd18b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -118
app.py CHANGED
@@ -1,137 +1,26 @@
1
  import gradio as gr
2
  from transformers import pipeline
 
3
  import random
4
  from datetime import datetime
5
 
6
  # Initialize sentiment analysis pipeline
7
  sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
8
 
9
- class JournalPrompts:
10
- def __init__(self):
11
- self.prompts = {
12
- "POSITIVE": [
13
- "What moments brought you the most joy today, and why?",
14
- "How did you contribute to your own happiness today?",
15
- "What accomplishment, big or small, are you proud of right now?",
16
- "Who made a positive impact on your day? How can you pay it forward?",
17
- "What unexpected positive surprise occurred today?",
18
- "How did you show kindness to yourself or others today?",
19
- "What made you laugh or smile today?",
20
- "What personal strength helped you succeed today?",
21
- "How did you make progress toward your goals today?",
22
- "What are you feeling grateful for in this moment?"
23
- ],
24
- "NEGATIVE": [
25
- "What is weighing on your mind, and what's one small step you could take to address it?",
26
- "If you could tell someone exactly how you're feeling right now, what would you say?",
27
- "What would make you feel even 1% better right now?",
28
- "What lesson might be hidden in this challenging situation?",
29
- "How have you overcome similar challenges in the past?",
30
- "What support do you need right now, and who could provide it?",
31
- "If your future self could send you a message of comfort, what would they say?",
32
- "What aspects of this situation are within your control?",
33
- "How can you show yourself compassion during this difficult time?",
34
- "What would you tell a friend who was facing this same situation?"
35
- ],
36
- "NEUTRAL": [
37
- "What's occupying your thoughts right now?",
38
- "How would you describe your energy level today?",
39
- "What would make today feel more meaningful?",
40
- "What patterns have you noticed in your daily life lately?",
41
- "What would you like to explore or learn more about?",
42
- "How aligned are your actions with your values today?",
43
- "What change would you like to see in your life six months from now?",
44
- "What's something you've been putting off that you could tackle today?",
45
- "How have your priorities shifted recently?",
46
- "What boundaries do you need to set or maintain?"
47
- ],
48
- "GROWTH": [
49
- "What skill would you like to develop further and why?",
50
- "How have your beliefs or perspectives changed recently?",
51
- "What habit would you like to build or break?",
52
- "What's the most important lesson you've learned this week?",
53
- "How are you different now compared to a year ago?",
54
- "What feedback have you received recently that resonated with you?",
55
- "What's one area of your life where you feel stuck? What's keeping you there?",
56
- "What would you attempt if you knew you couldn't fail?",
57
- "How do you want to be remembered?",
58
- "What does success mean to you right now?"
59
- ],
60
- "WELLNESS": [
61
- "How are you taking care of your physical health today?",
62
- "What does your body need right now?",
63
- "How well did you sleep last night? What affected your sleep?",
64
- "What activities make you feel most energized?",
65
- "How do you deal with stress? What works best for you?",
66
- "What self-care practice would be most helpful today?",
67
- "How connected do you feel to your body right now?",
68
- "What healthy boundary do you need to set?",
69
- "What does balance look like in your life?",
70
- "How do you recharge when you're feeling depleted?"
71
- ],
72
- "REFLECTION": [
73
- "What patterns have you noticed in your behavior lately?",
74
- "How have your priorities shifted in the past year?",
75
- "What advice would you give your younger self?",
76
- "What are you ready to let go of?",
77
- "What beliefs about yourself are holding you back?",
78
- "How do you handle uncertainty?",
79
- "What role does gratitude play in your life?",
80
- "What legacy do you want to leave?",
81
- "How do your values guide your decisions?",
82
- "What questions are you sitting with right now?"
83
- ]
84
- }
85
-
86
- def get_prompt(self, category):
87
- if category not in self.prompts:
88
- return "Invalid category"
89
- return random.choice(self.prompts[category])
90
-
91
- def get_mixed_prompts(self, sentiment):
92
- prompts = []
93
- prompts.append(f"Emotional: {self.get_prompt(sentiment)}")
94
- prompts.append(f"Growth: {self.get_prompt('GROWTH')}")
95
- random_category = random.choice(['WELLNESS', 'REFLECTION'])
96
- prompts.append(f"{random_category}: {self.get_prompt(random_category)}")
97
- return prompts
98
-
99
  class JournalCompanion:
100
  def __init__(self):
101
  self.entries = []
102
- self.journal_prompts = JournalPrompts()
103
- self.affirmations = {
104
- "POSITIVE": [
105
- "You're radiating positive energy! Keep embracing joy.",
106
- "Your optimism is inspiring. You're on the right path.",
107
- "You have so much to be proud of. Keep shining!",
108
- "Your positive mindset creates beautiful opportunities."
109
- ],
110
- "NEGATIVE": [
111
- "It's okay to feel this way. You're stronger than you know.",
112
- "Every challenge helps you grow. You've got this.",
113
- "Tomorrow brings new opportunities. Be gentle with yourself.",
114
- "Your feelings are valid, and this too shall pass."
115
- ],
116
- "NEUTRAL": [
117
- "You're exactly where you need to be right now.",
118
- "Your journey is unique and valuable.",
119
- "Take a moment to appreciate your progress.",
120
- "Every moment is a chance for a fresh perspective."
121
- ]
122
- }
123
-
124
  def analyze_entry(self, entry_text):
125
  if not entry_text.strip():
126
  return ("Please write something in your journal entry.", "", "", "")
127
 
128
  try:
129
- # Attempt to perform sentiment analysis
130
  sentiment_result = sentiment_analyzer(entry_text)[0]
131
  sentiment = sentiment_result["label"].upper()
132
  sentiment_score = sentiment_result["score"]
133
  except Exception as e:
134
- # Print the error to the console for debugging
135
  print("Error during sentiment analysis:", e)
136
  return (
137
  "An error occurred during analysis. Please try again.",
@@ -147,13 +36,44 @@ class JournalCompanion:
147
  "sentiment_score": sentiment_score
148
  }
149
  self.entries.append(entry_data)
150
-
151
- prompts = self.journal_prompts.get_mixed_prompts(sentiment)
152
- affirmation = random.choice(self.affirmations.get(sentiment, ["You're doing great! Keep reflecting and growing."]))
 
153
  sentiment_percentage = f"{sentiment_score * 100:.1f}%"
154
  message = f"Entry analyzed! Sentiment: {sentiment} ({sentiment_percentage} confidence)"
155
 
156
- return message, sentiment, "\n\n".join(prompts), affirmation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  def get_monthly_insights(self):
159
  if not self.entries:
 
1
  import gradio as gr
2
  from transformers import pipeline
3
+ import openai # Import if you are using OpenAI's API
4
  import random
5
  from datetime import datetime
6
 
7
  # Initialize sentiment analysis pipeline
8
  sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  class JournalCompanion:
11
  def __init__(self):
12
  self.entries = []
13
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  def analyze_entry(self, entry_text):
15
  if not entry_text.strip():
16
  return ("Please write something in your journal entry.", "", "", "")
17
 
18
  try:
19
+ # Perform sentiment analysis
20
  sentiment_result = sentiment_analyzer(entry_text)[0]
21
  sentiment = sentiment_result["label"].upper()
22
  sentiment_score = sentiment_result["score"]
23
  except Exception as e:
 
24
  print("Error during sentiment analysis:", e)
25
  return (
26
  "An error occurred during analysis. Please try again.",
 
36
  "sentiment_score": sentiment_score
37
  }
38
  self.entries.append(entry_data)
39
+
40
+ # Generate dynamic responses using a language model
41
+ prompts = self.generate_dynamic_prompts(sentiment)
42
+ affirmation = self.generate_dynamic_affirmation(sentiment)
43
  sentiment_percentage = f"{sentiment_score * 100:.1f}%"
44
  message = f"Entry analyzed! Sentiment: {sentiment} ({sentiment_percentage} confidence)"
45
 
46
+ return message, sentiment, prompts, affirmation
47
+
48
+ def generate_dynamic_prompts(self, sentiment):
49
+ prompt_request = f"Generate three reflective journal prompts for a person feeling {sentiment.lower()}."
50
+ try:
51
+ response = openai.Completion.create(
52
+ engine="gpt-3.5-turbo",
53
+ prompt=prompt_request,
54
+ max_tokens=60,
55
+ n=1
56
+ )
57
+ prompts = response.choices[0].text.strip()
58
+ except Exception as e:
59
+ print("Error generating prompts:", e)
60
+ prompts = "Could not generate prompts at this time."
61
+ return prompts
62
+
63
+ def generate_dynamic_affirmation(self, sentiment):
64
+ affirmation_request = f"Generate an affirmation for someone who is feeling {sentiment.lower()}."
65
+ try:
66
+ response = openai.Completion.create(
67
+ engine="gpt-3.5-turbo",
68
+ prompt=affirmation_request,
69
+ max_tokens=20,
70
+ n=1
71
+ )
72
+ affirmation = response.choices[0].text.strip()
73
+ except Exception as e:
74
+ print("Error generating affirmation:", e)
75
+ affirmation = "Could not generate an affirmation at this time."
76
+ return affirmation
77
 
78
  def get_monthly_insights(self):
79
  if not self.entries: