yaoyaoNo1 commited on
Commit
ef33d58
·
1 Parent(s): d9c6f99

mona's implementation

Browse files
Files changed (2) hide show
  1. app.py +116 -97
  2. requirements.txt +5 -4
app.py CHANGED
@@ -1,124 +1,143 @@
 
 
1
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForCausalLM
 
2
  import torch
3
  import gradio as gr
4
- import pandas as pd
5
- from datetime import datetime
6
-
7
- # Replace with your own pixabay API key
8
- # Intentionally hidden when deployed on HuggingFace Space
9
- API_Key = "censored-for-security-reason"
10
 
11
- # Load emotion model and tokenizer
12
  emotion_tokenizer = AutoTokenizer.from_pretrained("mrm8488/t5-base-finetuned-emotion")
13
  emotion_model = AutoModelForSeq2SeqLM.from_pretrained("mrm8488/t5-base-finetuned-emotion")
14
 
15
- # Load text generation model and tokenizer
16
- import os
17
- token=os.getenv('hftoken')
18
- text_tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it", token=token)
19
- text_model = AutoModelForCausalLM.from_pretrained("google/gemma-2-2b-it", token=token)
20
 
21
- # Set device to CUDA
22
  device = torch.device('cpu')
23
  emotion_model.to(device)
24
  text_model.to(device)
25
 
26
- # Initialize CSV file
27
- csv_file = 'diary_entries.csv'
28
- try:
29
- # Try to load the existing file
30
- df = pd.read_csv(csv_file)
31
- except FileNotFoundError:
32
- # If it doesn't exist, create an empty DataFrame
33
- df = pd.DataFrame(columns=["Date", "Diary Text", "Emotion", "Quote 1", "Quote 2"])
 
34
 
35
-
36
- # Function to predict emotion
37
  def get_emotion(text):
38
  input_ids = emotion_tokenizer.encode(text + '</s>', return_tensors='pt').to(device)
39
  output = emotion_model.generate(input_ids=input_ids, max_length=2)
40
- dec = [emotion_tokenizer.decode(ids, skip_special_tokens=True) for ids in output]
41
- label = dec[0].strip()
42
- return label
43
-
44
-
45
- # Function to generate two distinct inspirational quotes based on emotion and original text
46
- def generate_quotes(original_text, emotion):
47
- # First quote generation
48
- input_text_1 = f"Text: {original_text}\nEmotion: {emotion}\nInspirational Quote 1:"
49
- input_ids_1 = text_tokenizer(input_text_1, return_tensors="pt").to(device)
50
- outputs_1 = text_model.generate(**input_ids_1, max_new_tokens=70, do_sample=True, temperature=0.7)
51
- generated_text_1 = text_tokenizer.decode(outputs_1[0], skip_special_tokens=True)
52
-
53
- if "Inspirational Quote 1:" in generated_text_1:
54
- quote1 = generated_text_1.split("Inspirational Quote 1:")[1].strip().split("\n")[0]
55
- else:
56
- quote1 = generated_text_1.strip()
57
-
58
- # Second quote generation
59
- input_text_2 = f"Text: {original_text}\nEmotion: {emotion}\nInspirational Quote 2:"
60
- input_ids_2 = text_tokenizer(input_text_2, return_tensors="pt").to(device)
61
- outputs_2 = text_model.generate(**input_ids_2, max_new_tokens=70, do_sample=True, temperature=0.7)
62
- generated_text_2 = text_tokenizer.decode(outputs_2[0], skip_special_tokens=True)
63
-
64
- if "Inspirational Quote 2:" in generated_text_2:
65
- quote2 = generated_text_2.split("Inspirational Quote 2:")[1].strip().split("\n")[0]
 
 
 
 
 
 
 
 
66
  else:
67
- quote2 = generated_text_2.strip()
68
-
69
- return quote1, quote2
70
-
71
- # Function to map emotions to weather search terms
72
- def map_emotion_to_weather(emotion):
73
- mapping = {
74
- "anger": "fire",
75
- "joy": "sunshine",
76
- "sadness": "lonely",
77
- "love": "rose",
78
- "fear": "ghost",
79
- "surprise":"gift",
80
- }
81
- return mapping.get(emotion, "nature") # Default to "nature" if not found
82
-
83
- # Function to handle emotion detection, quotes generation, and image display
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  def journal_interface(Diary):
85
- try:
86
- # Step 1: Detect Emotion
87
- emotion = get_emotion(Diary)
88
-
89
- # Step 2: Generate Inspirational Quotes
90
- quote1, quote2 = generate_quotes(Diary, emotion)
91
-
92
- # Step 3: Get image URL based on the emotion
93
- # image_url = get_image_url(emotion)
94
-
95
- # Step 4: Save to CSV
96
- date_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
97
- new_entry = pd.DataFrame([[date_time, Diary, emotion, quote1, quote2]], columns=["Date", "Diary Text", "Emotion", "Quote 1", "Quote 2"])
98
- global df
99
- df = pd.concat([df, new_entry], ignore_index=True)
100
- df.to_csv(csv_file, index=False)
101
-
102
- return emotion, quote1, quote2, #image_url
103
- except Exception as e:
104
- # Return the error message to the interface for debugging
105
- print(f"Error encountered: {str(e)}")
106
- return f"Error: {str(e)}", "", "" #None # Last output is for the image
107
-
108
- # Create the Gradio interface
109
  interface = gr.Interface(
110
  fn=journal_interface,
111
  inputs=gr.Textbox(lines=5, placeholder="Enter your thoughts here..."),
112
  outputs=[
113
  gr.Textbox(label="Detected Emotion"),
114
- gr.Textbox(label="Generated Quote 1"),
115
- gr.Textbox(label="Generated Quote 2"),
116
- #gr.Image(label="Emotion Image", visible=True, width="100%") # Show image based on emotion
117
  ],
118
  title="AI-Powered Personal Journal",
119
- description="Enter your thoughts, and the AI will detect the emotion and generate two inspirational quotes based on it.",
120
- theme=gr.themes.Soft() # Apply the Soft theme here
121
  )
 
 
 
 
122
 
123
- # Launch the Gradio app
124
- interface.launch(share=True)
 
1
+ #imorting libraries and utulities
2
+ import psutil
3
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForCausalLM
4
+ import pandas as pd
5
  import torch
6
  import gradio as gr
7
+ from joblib import Parallel, delayed
8
+ import matplotlib.pyplot as plt
9
+ import seaborn as sns
10
+ import random
 
 
11
 
12
+ # Load emotion detection
13
  emotion_tokenizer = AutoTokenizer.from_pretrained("mrm8488/t5-base-finetuned-emotion")
14
  emotion_model = AutoModelForSeq2SeqLM.from_pretrained("mrm8488/t5-base-finetuned-emotion")
15
 
16
+ #Load quote generation models
17
+ text_tokenizer = AutoTokenizer.from_pretrained("gpt2")
18
+ text_model = AutoModelForCausalLM.from_pretrained("gpt2")
 
 
19
 
 
20
  device = torch.device('cpu')
21
  emotion_model.to(device)
22
  text_model.to(device)
23
 
24
+ # Hardcoded fallback quotes for each emotion
25
+ fallback_quotes = {
26
+ "sadness": ["Keep going, tough times don't last.", "This too shall pass."],
27
+ "joy": ["Happiness is here to stay.", "Enjoy this moment."],
28
+ "love": ["Love is a beautiful journey.", "Cherish every moment of love."],
29
+ "anger": ["Take a deep breath, you'll get through this.", "Channel your anger into something positive."],
30
+ "fear": ["Courage is not the absence of fear.", "Face your fears, and they will disappear."],
31
+ "surprise": ["Embrace the unexpected.", "Life is full of pleasant surprises."]
32
+ }
33
 
34
+ # Function to detect emotion from the user's input text
 
35
  def get_emotion(text):
36
  input_ids = emotion_tokenizer.encode(text + '</s>', return_tensors='pt').to(device)
37
  output = emotion_model.generate(input_ids=input_ids, max_length=2)
38
+ emotion = emotion_tokenizer.decode(output[0], skip_special_tokens=True).strip()
39
+ return emotion
40
+
41
+
42
+ # Function to generate a motivational quote based on the detected emotion
43
+ def generate_quote(original_text, emotion):
44
+ input_text = f"Generate an inspiring quote based on the following emotion:\nEmotion: {emotion}\nText: {original_text}\nQuote:"
45
+ input_ids = text_tokenizer(input_text, return_tensors="pt").to(device)
46
+
47
+ try:
48
+ outputs = text_model.generate(
49
+ **input_ids,
50
+ max_length=100,
51
+ do_sample=True,
52
+ top_k=50, # Randomness control
53
+ top_p=0.95, # Probability control for better diversity
54
+ temperature=0.7
55
+ )
56
+ generated_text = text_tokenizer.decode(outputs[0], skip_special_tokens=True)
57
+ if "Quote:" in generated_text:
58
+ quote = generated_text.split("Quote:")[1].strip().split("\n")[0]
59
+ else:
60
+ quote = generated_text.strip()
61
+ return quote
62
+ except:
63
+ return random.choice(fallback_quotes.get(emotion, ["Stay positive.", "Keep pushing forward."]))
64
+
65
+
66
+ #For file input
67
+ def load_and_process_data(file_path):
68
+ df = pd.read_csv(file_path)
69
+ if 'Answer' in df.columns:
70
+ df = df[['Answer']]
71
+ df['Emotion'] = df['Answer'].apply(get_emotion)
72
  else:
73
+ raise ValueError("The expected column 'Answer' is not present in the dataset.")
74
+ return df
75
+
76
+ # Function to generate synthetic journal data for testing
77
+ def generate_synthetic_data(num_entries=100):
78
+ emotions = ["sadness", "joy", "love", "anger", "fear", "surprise"]
79
+ entries = []
80
+ for _ in range(num_entries):
81
+ emotion = random.choice(emotions)
82
+ text = f"This is a synthetic entry expressing {emotion}."
83
+ entries.append({"Answer": text, "Emotion": emotion})
84
+ return pd.DataFrame(entries)
85
+
86
+ # Function to process data in chunks (for parallel processing)
87
+ def process_chunk(chunk):
88
+ chunk['Inspirational Quote'] = chunk.apply(lambda row: generate_quote(row['Answer'], row['Emotion']), axis=1)
89
+ return chunk
90
+
91
+ def process_in_chunks(df, chunk_size=10):
92
+ results = Parallel(n_jobs=-1, backend="multiprocessing")(
93
+ delayed(process_chunk)(df[start:start + chunk_size]) for start in range(0, len(df), chunk_size)
94
+ )
95
+ return pd.concat(results, ignore_index=True)
96
+
97
+ # Function to plot the emotion distribution graph
98
+ def plot_emotion_distribution(df):
99
+ emotion_count = df['Emotion'].value_counts()
100
+ plt.figure(figsize=(10,6))
101
+ sns.barplot(x=emotion_count.index, y=emotion_count.values, palette='viridis')
102
+ plt.title('Sum of Each Emotion')
103
+ plt.xlabel('Emotion')
104
+ plt.ylabel('Count')
105
+ plt.show()
106
+
107
+ # Function to detect emotion and generate a quote for a journal entry
108
  def journal_interface(Diary):
109
+ emotion = get_emotion(Diary)
110
+ quote = generate_quote(Diary, emotion)
111
+ return emotion, quote
112
+
113
+ # Function to track CPU utilization during processing
114
+ def get_cpu_utilization():
115
+ return f"Current CPU Usage: {psutil.cpu_percent()}%"
116
+
117
+ # Main function to load the data, process it in chunks, and generate a graph
118
+ def main(file_path):
119
+ df = load_and_process_data(file_path)
120
+ print(file_path)
121
+ processed_df = process_in_chunks(df)
122
+ plot_emotion_distribution(processed_df)
123
+ print(get_cpu_utilization())
124
+ return processed_df
125
+
126
+ # Gradio interface for inputting thoughts and generating emotion/quote
 
 
 
 
 
 
127
  interface = gr.Interface(
128
  fn=journal_interface,
129
  inputs=gr.Textbox(lines=5, placeholder="Enter your thoughts here..."),
130
  outputs=[
131
  gr.Textbox(label="Detected Emotion"),
132
+ gr.Textbox(label="Generated Quote")
 
 
133
  ],
134
  title="AI-Powered Personal Journal",
135
+ description="Enter your thoughts, and the AI will detect the emotion and generate an inspirational quote based on it.",
136
+ theme=gr.themes.Soft()
137
  )
138
+ # Button to generate the graph and display CPU usage
139
+ def graph_button(file_path):
140
+ processed_df = main(file_path)
141
+ return get_cpu_utilization()
142
 
143
+ interface.launch(share=True)
 
requirements.txt CHANGED
@@ -1,6 +1,7 @@
1
- transformers
 
2
  torch
3
  gradio
4
- pandas
5
- datetime
6
- python-multipart
 
1
+ psutil
2
+ pandas
3
  torch
4
  gradio
5
+ joblib
6
+ matplotlib
7
+ seaborn