Pranav0111 commited on
Commit
2c416c0
β€’
1 Parent(s): a1ff824

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -113
app.py CHANGED
@@ -3,10 +3,8 @@ from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
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
- # Initialize text generation model
10
  model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
11
  tokenizer = AutoTokenizer.from_pretrained(model_name)
12
  model = AutoModelForCausalLM.from_pretrained(model_name)
@@ -20,129 +18,159 @@ text_generator = pipeline(
20
  pad_token_id=tokenizer.eos_token_id
21
  )
22
 
23
- class JournalCompanion:
24
- def __init__(self):
25
- self.entries = []
 
 
26
 
27
- def generate_prompts(self, sentiment):
28
- prompt_template = f"""Generate three reflective journal prompts for someone feeling {sentiment.lower()}.
29
- Make them thoughtful and encouraging. Format them as a bullet point list."""
 
 
 
 
 
30
 
31
- try:
32
- response = text_generator(prompt_template)[0]['generated_text']
33
- # Extract the generated prompts after the input prompt
34
- prompts = response[len(prompt_template):]
35
- return "\n\nReflective Prompts:" + prompts
36
- except Exception as e:
37
- print("Error generating prompts:", e)
38
- 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?"
39
-
40
- def generate_affirmation(self, sentiment):
41
- affirmation_template = f"Generate a short, encouraging affirmation for someone feeling {sentiment.lower()}."
42
 
43
- try:
44
- response = text_generator(affirmation_template)[0]['generated_text']
45
- # Extract the generated affirmation after the input prompt
46
- affirmation = response[len(affirmation_template):].strip()
47
- return affirmation
48
- except Exception as e:
49
- print("Error generating affirmation:", e)
50
- return "I acknowledge my feelings and trust in my ability to handle this moment."
51
-
52
- def analyze_entry(self, entry_text):
53
- if not entry_text.strip():
54
- return ("Please write something in your journal entry.", "", "", "")
55
-
56
- try:
57
- # Perform sentiment analysis
58
- sentiment_result = sentiment_analyzer(entry_text)[0]
59
- sentiment = sentiment_result["label"].upper()
60
- sentiment_score = sentiment_result["score"]
61
- except Exception as e:
62
- print("Error during sentiment analysis:", e)
63
- return (
64
- "An error occurred during analysis. Please try again.",
65
- "Error",
66
- "Could not analyze sentiment due to an error.",
67
- "Could not generate affirmation due to an error."
68
- )
69
-
70
- entry_data = {
71
- "text": entry_text,
72
- "timestamp": datetime.now().isoformat(),
73
- "sentiment": sentiment,
74
- "sentiment_score": sentiment_score
75
  }
76
- self.entries.append(entry_data)
77
-
78
- # Generate responses using TinyLlama
79
- prompts = self.generate_prompts(sentiment)
80
- affirmation = self.generate_affirmation(sentiment)
81
- sentiment_percentage = f"{sentiment_score * 100:.1f}%"
82
- message = f"Entry analyzed! Sentiment: {sentiment} ({sentiment_percentage} confidence)"
83
 
84
- return message, sentiment, prompts, affirmation
85
-
86
- def get_monthly_insights(self):
87
- if not self.entries:
88
- return "No entries yet to analyze."
89
-
90
- total_entries = len(self.entries)
91
- positive_entries = sum(1 for entry in self.entries if entry["sentiment"] == "POSITIVE")
 
 
 
 
 
 
 
 
 
 
 
92
 
93
- # Generate insights using TinyLlama
94
- insight_template = f"""Based on journal entries:
95
- Total Entries: {total_entries}
96
- Positive Entries: {positive_entries} ({(positive_entries / total_entries * 100):.1f}%)
97
- Negative Entries: {total_entries - positive_entries} ({((total_entries - positive_entries) / total_entries * 100):.1f}%)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
- Generate a brief insight about this pattern."""
 
 
100
 
101
- try:
102
- response = text_generator(insight_template)[0]['generated_text']
103
- insights = response[len(insight_template):].strip()
104
- return f"""Monthly Insights:
105
- {insights}
106
 
107
- Statistics:
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
- except Exception as e:
113
- print("Error generating insights:", e)
114
- return f"""Monthly Insights:
115
- Total Entries: {total_entries}
116
- Positive Entries: {positive_entries} ({(positive_entries / total_entries * 100):.1f}%)
117
- Negative Entries: {total_entries - positive_entries} ({((total_entries - positive_entries) / total_entries * 100):.1f}%)
118
- """
119
-
120
- def create_journal_interface():
121
- journal = JournalCompanion()
122
 
123
- with gr.Blocks(title="AI Journal Companion") as interface:
124
- gr.Markdown("# πŸ“” AI Journal Companion")
125
- gr.Markdown("Write your thoughts and receive AI-powered insights, prompts, and affirmations.")
126
-
127
- with gr.Row():
128
- with gr.Column():
129
- entry_input = gr.Textbox(
130
- label="Journal Entry",
131
- placeholder="Write your journal entry here...",
132
- lines=5
133
  )
134
- submit_btn = gr.Button("Submit Entry", variant="primary")
135
-
136
- with gr.Column():
137
- result_message = gr.Markdown(label="Analysis Result")
138
- sentiment_output = gr.Textbox(label="Detected Sentiment")
139
- prompt_output = gr.Markdown(label="Reflective Prompts")
140
- affirmation_output = gr.Textbox(label="Daily Affirmation")
 
 
 
 
 
 
 
 
 
141
 
142
- with gr.Row():
143
- insights_btn = gr.Button("Show Monthly Insights")
144
- insights_output = gr.Markdown(label="Monthly Insights")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
 
146
  submit_btn.click(
147
  fn=journal.analyze_entry,
148
  inputs=[entry_input],
 
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)
10
  model = AutoModelForCausalLM.from_pretrained(model_name)
 
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()
26
 
27
+ # Custom CSS for better styling
28
+ custom_css = """
29
+ /* Global styles */
30
+ .container {
31
+ max-width: 1200px;
32
+ margin: 0 auto;
33
+ padding: 20px;
34
+ }
35
 
36
+ /* Header styles */
37
+ .header {
38
+ text-align: center;
39
+ margin-bottom: 2rem;
40
+ background: linear-gradient(135deg, #6B73FF 0%, #000DFF 100%);
41
+ padding: 2rem;
42
+ border-radius: 15px;
43
+ color: white;
44
+ }
 
 
45
 
46
+ /* Input area styles */
47
+ .input-container {
48
+ background: white;
49
+ border-radius: 15px;
50
+ padding: 20px;
51
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
52
+ margin-bottom: 20px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  }
 
 
 
 
 
 
 
54
 
55
+ /* Output area styles */
56
+ .output-container {
57
+ background: #f8f9fa;
58
+ border-radius: 15px;
59
+ padding: 20px;
60
+ margin-top: 20px;
61
+ }
62
+
63
+ /* Button styles */
64
+ .custom-button {
65
+ background: linear-gradient(135deg, #6B73FF 0%, #000DFF 100%);
66
+ border: none;
67
+ padding: 10px 20px;
68
+ border-radius: 8px;
69
+ color: white;
70
+ font-weight: bold;
71
+ cursor: pointer;
72
+ transition: transform 0.2s;
73
+ }
74
 
75
+ .custom-button:hover {
76
+ transform: translateY(-2px);
77
+ }
78
+
79
+ /* Card styles */
80
+ .card {
81
+ background: white;
82
+ border-radius: 10px;
83
+ padding: 15px;
84
+ margin: 10px 0;
85
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
86
+ transition: transform 0.2s;
87
+ }
88
+
89
+ .card:hover {
90
+ transform: translateY(-2px);
91
+ }
92
+
93
+ /* Animation for results */
94
+ @keyframes fadeIn {
95
+ from { opacity: 0; transform: translateY(10px); }
96
+ to { opacity: 1; transform: translateY(0); }
97
+ }
98
 
99
+ .result-animation {
100
+ animation: fadeIn 0.5s ease-out;
101
+ }
102
 
103
+ /* Responsive design */
104
+ @media (max-width: 768px) {
105
+ .container {
106
+ padding: 10px;
107
+ }
108
 
109
+ .header {
110
+ padding: 1rem;
111
+ }
112
+ }
113
+ """
 
 
 
 
 
 
 
 
 
 
114
 
115
+ with gr.Blocks(css=custom_css, title="AI Journal Companion") as interface:
116
+ with gr.Column(elem_classes="container"):
117
+ # Header
118
+ with gr.Column(elem_classes="header"):
119
+ gr.Markdown("# πŸ“” AI Journal Companion")
120
+ gr.Markdown(
121
+ "Transform your thoughts into insights with AI-powered journaling",
122
+ elem_classes="subtitle"
 
 
123
  )
124
+
125
+ # Main content
126
+ with gr.Row():
127
+ # Input Column
128
+ with gr.Column(scale=1, elem_classes="input-container"):
129
+ entry_input = gr.Textbox(
130
+ label="Write Your Thoughts",
131
+ placeholder="Share what's on your mind...",
132
+ lines=8,
133
+ elem_classes="journal-input"
134
+ )
135
+ submit_btn = gr.Button(
136
+ "✨ Analyze Entry",
137
+ variant="primary",
138
+ elem_classes="custom-button"
139
+ )
140
 
141
+ # Output Column
142
+ with gr.Column(scale=1, elem_classes="output-container"):
143
+ with gr.Column(elem_classes="card result-animation"):
144
+ result_message = gr.Markdown(label="Analysis")
145
+ sentiment_output = gr.Textbox(
146
+ label="Emotional Tone",
147
+ elem_classes="sentiment-output"
148
+ )
149
+
150
+ with gr.Column(elem_classes="card result-animation"):
151
+ prompt_output = gr.Markdown(
152
+ label="Reflection Prompts",
153
+ elem_classes="prompts-output"
154
+ )
155
+
156
+ with gr.Column(elem_classes="card result-animation"):
157
+ affirmation_output = gr.Textbox(
158
+ label="Your Daily Affirmation",
159
+ elem_classes="affirmation-output"
160
+ )
161
+
162
+ # Insights Section
163
+ with gr.Row(elem_classes="insights-section"):
164
+ with gr.Column(scale=1):
165
+ insights_btn = gr.Button(
166
+ "πŸ“Š View Monthly Insights",
167
+ elem_classes="custom-button"
168
+ )
169
+ insights_output = gr.Markdown(
170
+ elem_classes="card insights-card"
171
+ )
172
 
173
+ # Event handlers
174
  submit_btn.click(
175
  fn=journal.analyze_entry,
176
  inputs=[entry_input],