Spaces:
Running
Running
Pranav0111
commited on
Commit
•
a1ff824
1
Parent(s):
0703c2b
Update app.py
Browse files
app.py
CHANGED
@@ -1,21 +1,54 @@
|
|
1 |
import gradio as gr
|
2 |
-
from transformers import pipeline
|
3 |
-
import openai
|
4 |
import random
|
5 |
-
import os
|
6 |
from datetime import datetime
|
7 |
|
8 |
# Initialize sentiment analysis pipeline
|
9 |
sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
|
10 |
|
11 |
-
#
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
class JournalCompanion:
|
16 |
def __init__(self):
|
17 |
self.entries = []
|
18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
def analyze_entry(self, entry_text):
|
20 |
if not entry_text.strip():
|
21 |
return ("Please write something in your journal entry.", "", "", "")
|
@@ -30,7 +63,7 @@ class JournalCompanion:
|
|
30 |
return (
|
31 |
"An error occurred during analysis. Please try again.",
|
32 |
"Error",
|
33 |
-
"Could not
|
34 |
"Could not generate affirmation due to an error."
|
35 |
)
|
36 |
|
@@ -42,50 +75,14 @@ class JournalCompanion:
|
|
42 |
}
|
43 |
self.entries.append(entry_data)
|
44 |
|
45 |
-
# Generate
|
46 |
-
prompts = self.
|
47 |
-
affirmation = self.
|
48 |
sentiment_percentage = f"{sentiment_score * 100:.1f}%"
|
49 |
message = f"Entry analyzed! Sentiment: {sentiment} ({sentiment_percentage} confidence)"
|
50 |
|
51 |
return message, sentiment, prompts, affirmation
|
52 |
|
53 |
-
def generate_dynamic_prompts(self, sentiment):
|
54 |
-
prompt_request = f"Generate three reflective journal prompts for a person feeling {sentiment.lower()}."
|
55 |
-
try:
|
56 |
-
response = openai.ChatCompletion.create(
|
57 |
-
model="gpt-3.5-turbo",
|
58 |
-
messages=[
|
59 |
-
{"role": "system", "content": "You are a helpful assistant."},
|
60 |
-
{"role": "user", "content": prompt_request}
|
61 |
-
],
|
62 |
-
max_tokens=60,
|
63 |
-
n=1
|
64 |
-
)
|
65 |
-
prompts = response.choices[0].message["content"].strip()
|
66 |
-
except Exception as e:
|
67 |
-
print("Error generating prompts:", e)
|
68 |
-
prompts = "Could not generate prompts at this time."
|
69 |
-
return prompts
|
70 |
-
|
71 |
-
def generate_dynamic_affirmation(self, sentiment):
|
72 |
-
affirmation_request = f"Generate an affirmation for someone who is feeling {sentiment.lower()}."
|
73 |
-
try:
|
74 |
-
response = openai.ChatCompletion.create(
|
75 |
-
model="gpt-3.5-turbo",
|
76 |
-
messages=[
|
77 |
-
{"role": "system", "content": "You are a helpful assistant."},
|
78 |
-
{"role": "user", "content": affirmation_request}
|
79 |
-
],
|
80 |
-
max_tokens=20,
|
81 |
-
n=1
|
82 |
-
)
|
83 |
-
affirmation = response.choices[0].message["content"].strip()
|
84 |
-
except Exception as e:
|
85 |
-
print("Error generating affirmation:", e)
|
86 |
-
affirmation = "Could not generate an affirmation at this time."
|
87 |
-
return affirmation
|
88 |
-
|
89 |
def get_monthly_insights(self):
|
90 |
if not self.entries:
|
91 |
return "No entries yet to analyze."
|
@@ -93,12 +90,32 @@ class JournalCompanion:
|
|
93 |
total_entries = len(self.entries)
|
94 |
positive_entries = sum(1 for entry in self.entries if entry["sentiment"] == "POSITIVE")
|
95 |
|
96 |
-
insights
|
|
|
97 |
Total Entries: {total_entries}
|
98 |
Positive Entries: {positive_entries} ({(positive_entries / total_entries * 100):.1f}%)
|
99 |
Negative Entries: {total_entries - positive_entries} ({((total_entries - positive_entries) / total_entries * 100):.1f}%)
|
100 |
-
|
101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
def create_journal_interface():
|
104 |
journal = JournalCompanion()
|
@@ -147,4 +164,4 @@ def create_journal_interface():
|
|
147 |
|
148 |
if __name__ == "__main__":
|
149 |
interface = create_journal_interface()
|
150 |
-
interface.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
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)
|
13 |
+
text_generator = pipeline(
|
14 |
+
"text-generation",
|
15 |
+
model=model,
|
16 |
+
tokenizer=tokenizer,
|
17 |
+
max_new_tokens=50,
|
18 |
+
temperature=0.7,
|
19 |
+
top_p=0.9,
|
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.", "", "", "")
|
|
|
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 |
|
|
|
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."
|
|
|
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()
|
|
|
164 |
|
165 |
if __name__ == "__main__":
|
166 |
interface = create_journal_interface()
|
167 |
+
interface.launch()
|