Pranav0111 commited on
Commit
bf1fafe
1 Parent(s): 1065445

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -40
app.py CHANGED
@@ -1,51 +1,53 @@
1
  import gradio as gr
2
- from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
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)
10
- model = AutoModelForCausalLM.from_pretrained(model_name)
11
- text_generator = pipeline(
12
- "text-generation",
13
- model=model,
14
- tokenizer=tokenizer,
15
- max_new_tokens=50,
16
- temperature=0.7,
17
- top_p=0.9,
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():
@@ -73,9 +75,9 @@ class JournalCompanion:
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
 
@@ -101,6 +103,8 @@ class JournalCompanion:
101
  except ZeroDivisionError:
102
  return "No entries available for analysis."
103
 
 
 
104
  def create_journal_interface():
105
  journal = JournalCompanion()
106
 
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
  import random
4
  from datetime import datetime
5
 
6
+ # Initialize models with smaller, faster alternatives
7
+ sentiment_analyzer = pipeline(
8
+ "sentiment-analysis",
9
+ model="distilbert-base-uncased-finetuned-sst-2-english",
10
+ device=-1 # Force CPU usage
 
 
 
 
 
 
 
 
11
  )
12
 
13
+ # Pre-defined prompts and affirmations for different sentiments
14
+ PROMPT_TEMPLATES = {
15
+ "POSITIVE": [
16
+ "- What made this positive experience particularly meaningful to you?",
17
+ "- How can you carry this positive energy forward?",
18
+ "- Who would you like to share this joy with and why?"
19
+ ],
20
+ "NEGATIVE": [
21
+ "- What can you learn from this challenging situation?",
22
+ "- What small step could you take to feel better?",
23
+ "- Who or what helps you feel supported during difficult times?"
24
+ ]
25
+ }
26
+
27
+ AFFIRMATIONS = {
28
+ "POSITIVE": [
29
+ "I deserve this joy and all good things coming my way.",
30
+ "My positive energy creates positive experiences.",
31
+ "I choose to embrace and celebrate this moment."
32
+ ],
33
+ "NEGATIVE": [
34
+ "This too shall pass, and I am growing stronger.",
35
+ "I trust in my ability to handle challenging situations.",
36
+ "Every experience is teaching me something valuable."
37
+ ]
38
+ }
39
+
40
  class JournalCompanion:
41
  def __init__(self):
42
  self.entries = []
43
 
44
+ def get_prompts(self, sentiment):
45
+ prompts = PROMPT_TEMPLATES.get(sentiment, PROMPT_TEMPLATES["POSITIVE"])
46
+ return "\n\nReflective Prompts:\n" + "\n".join(prompts)
 
 
 
 
 
 
 
 
 
47
 
48
+ def get_affirmation(self, sentiment):
49
+ affirmations = AFFIRMATIONS.get(sentiment, AFFIRMATIONS["POSITIVE"])
50
+ return random.choice(affirmations)
 
 
 
 
 
 
 
 
51
 
52
  def analyze_entry(self, entry_text):
53
  if not entry_text.strip():
 
75
  }
76
  self.entries.append(entry_data)
77
 
78
+ # Get pre-defined responses
79
+ prompts = self.get_prompts(sentiment)
80
+ affirmation = self.get_affirmation(sentiment)
81
  sentiment_percentage = f"{sentiment_score * 100:.1f}%"
82
  message = f"Entry analyzed! Sentiment: {sentiment} ({sentiment_percentage} confidence)"
83
 
 
103
  except ZeroDivisionError:
104
  return "No entries available for analysis."
105
 
106
+ # Rest of the code (create_journal_interface function and CSS) remains the samepad_token_id=tokenizer.eos_token_id
107
+ )
108
  def create_journal_interface():
109
  journal = JournalCompanion()
110