Pranav0111 commited on
Commit
7aec52d
1 Parent(s): 2c416c0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -3
app.py CHANGED
@@ -3,7 +3,7 @@ from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
3
  import random
4
  from datetime import datetime
5
 
6
- # Initialize models (same as before)
7
  sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
8
  model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
9
  tokenizer = AutoTokenizer.from_pretrained(model_name)
@@ -18,8 +18,88 @@ text_generator = pipeline(
18
  pad_token_id=tokenizer.eos_token_id
19
  )
20
 
21
- # JournalCompanion class remains the same as in previous example
22
- # ... (insert the entire JournalCompanion class here)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  def create_journal_interface():
25
  journal = JournalCompanion()
 
3
  import random
4
  from datetime import datetime
5
 
6
+ # Initialize models
7
  sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
8
  model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
9
  tokenizer = AutoTokenizer.from_pretrained(model_name)
 
18
  pad_token_id=tokenizer.eos_token_id
19
  )
20
 
21
+ class JournalCompanion:
22
+ def __init__(self):
23
+ self.entries = []
24
+
25
+ def generate_prompts(self, sentiment):
26
+ prompt_template = f"""Generate three reflective journal prompts for someone feeling {sentiment.lower()}.
27
+ Make them thoughtful and encouraging. Format them as a bullet point list."""
28
+
29
+ try:
30
+ response = text_generator(prompt_template)[0]['generated_text']
31
+ # Extract the generated prompts after the input prompt
32
+ prompts = response[len(prompt_template):]
33
+ return "\n\nReflective Prompts:" + prompts
34
+ except Exception as e:
35
+ print("Error generating prompts:", e)
36
+ return "\n\nReflective Prompts:\n- What thoughts and feelings are you experiencing right now?\n- How has this experience affected you?\n- What would be helpful for you at this moment?"
37
+
38
+ def generate_affirmation(self, sentiment):
39
+ affirmation_template = f"Generate a short, encouraging affirmation for someone feeling {sentiment.lower()}."
40
+
41
+ try:
42
+ response = text_generator(affirmation_template)[0]['generated_text']
43
+ # Extract the generated affirmation after the input prompt
44
+ affirmation = response[len(affirmation_template):].strip()
45
+ return affirmation
46
+ except Exception as e:
47
+ print("Error generating affirmation:", e)
48
+ return "I acknowledge my feelings and trust in my ability to handle this moment."
49
+
50
+ def analyze_entry(self, entry_text):
51
+ if not entry_text.strip():
52
+ return ("Please write something in your journal entry.", "", "", "")
53
+
54
+ try:
55
+ # Perform sentiment analysis
56
+ sentiment_result = sentiment_analyzer(entry_text)[0]
57
+ sentiment = sentiment_result["label"].upper()
58
+ sentiment_score = sentiment_result["score"]
59
+ except Exception as e:
60
+ print("Error during sentiment analysis:", e)
61
+ return (
62
+ "An error occurred during analysis. Please try again.",
63
+ "Error",
64
+ "Could not analyze sentiment due to an error.",
65
+ "Could not generate affirmation due to an error."
66
+ )
67
+
68
+ entry_data = {
69
+ "text": entry_text,
70
+ "timestamp": datetime.now().isoformat(),
71
+ "sentiment": sentiment,
72
+ "sentiment_score": sentiment_score
73
+ }
74
+ self.entries.append(entry_data)
75
+
76
+ # Generate responses using TinyLlama
77
+ prompts = self.generate_prompts(sentiment)
78
+ affirmation = self.generate_affirmation(sentiment)
79
+ sentiment_percentage = f"{sentiment_score * 100:.1f}%"
80
+ message = f"Entry analyzed! Sentiment: {sentiment} ({sentiment_percentage} confidence)"
81
+
82
+ return message, sentiment, prompts, affirmation
83
+
84
+ def get_monthly_insights(self):
85
+ if not self.entries:
86
+ return "No entries yet to analyze."
87
+
88
+ total_entries = len(self.entries)
89
+ positive_entries = sum(1 for entry in self.entries if entry["sentiment"] == "POSITIVE")
90
+
91
+ try:
92
+ percentage_positive = (positive_entries / total_entries * 100)
93
+ percentage_negative = ((total_entries - positive_entries) / total_entries * 100)
94
+
95
+ insights = f"""Monthly Insights:
96
+ Total Entries: {total_entries}
97
+ Positive Entries: {positive_entries} ({percentage_positive:.1f}%)
98
+ Negative Entries: {total_entries - positive_entries} ({percentage_negative:.1f}%)
99
+ """
100
+ return insights
101
+ except ZeroDivisionError:
102
+ return "No entries available for analysis."
103
 
104
  def create_journal_interface():
105
  journal = JournalCompanion()