syedmudassir16 commited on
Commit
1176c46
·
verified ·
1 Parent(s): 78cad84

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +165 -213
app.py CHANGED
@@ -1,236 +1,187 @@
1
- import argparse
2
- import torch
3
- from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, pipeline
4
  import gradio as gr
5
 
6
- class llmChatbot:
7
- def __init__(self, model_name, temperature=0.3, max_new_tokens=256, top_p=0.95, repetition_penalty=1.0):
8
- # Specify how to quantize the model
9
- quantization_config = BitsAndBytesConfig(
10
- load_in_4bit=True,
11
- bnb_4bit_quant_type="nf4",
12
- bnb_4bit_compute_dtype="float16", # Use the string "float16" instead of torch.float16
13
- )
14
-
15
- self.model = AutoModelForCausalLM.from_pretrained(model_name, quantization_config=quantization_config, device_map="auto")
16
- self.tokenizer = AutoTokenizer.from_pretrained(model_name)
17
-
18
- # Set pad_token to eos_token if not already set
19
- if (self.tokenizer.pad_token is None):
20
- self.tokenizer.pad_token = self.tokenizer.eos_token
21
-
22
- self.temperature = temperature
23
- self.max_new_tokens = max_new_tokens
24
- self.top_p = top_p
25
- self.repetition_penalty = repetition_penalty
26
 
27
- def format_prompt(self, message, history):
28
- fixed_prompt = """
29
- You are a smart mood analyser, who determines user mood. Based on the user input, classify the mood of the user into one of the four moods {Happy, Sad, Instrumental, Party}. If you are finding it difficult to classify into one of these four moods, keep the conversation going on until we classify the user’s mood. Return a single-word reply from one of the options if you have classified. Suppose you classify a sentence as happy, then just respond with "happy".
30
 
31
- Note: Do not write anything else other than the classified mood if classified.
32
 
33
- Note: If any question or any user text cannot be classified, follow up with a question to know the user's mood until you classify the mood.
34
 
35
- Note: Mood should be classified only from any of these 4 classes {Happy, Sad, Instrumental, Party}, if not any of these 4 then continue with a follow-up question until you classify the mood.
36
 
37
- Note: if user asks something like i need a coffee then do not classify the mood directly and ask more follow-up questions as asked in examples.
38
 
39
- Examples
40
- User: What is C programming?
41
- LLM Response: C programming is a programming language. How are you feeling now after knowing the answer?
42
 
43
- User: Can I get a coffee?
44
- LLM Response: It sounds like you're in need of a little pick-me-up. How are you feeling right now? Are you looking for something upbeat, something to relax to, or maybe some instrumental music while you enjoy your coffee?
45
- User: I feel like rocking
46
- LLM Response: Party
47
 
48
- User: I'm feeling so energetic today!
49
- LLM Response: Happy
 
 
50
 
51
- User: I'm feeling down today.
52
- LLM Response: Sad
53
 
54
- User: I'm ready to have some fun tonight!
55
- LLM Response: Party
56
 
57
- User: I need some background music while I am stuck in traffic.
58
- LLM Response: Instrumental
59
 
60
- User: Hi
61
- LLM Response: Hi, how are you doing?
62
 
63
- User: Feeling okay only.
64
- LLM Response: Are you having a good day?
65
- User: I don't know
66
- LLM Response: Do you want to listen to some relaxing music?
67
- User: No
68
- LLM Response: How about listening to some rock and roll music?
69
- User: Yes
70
- LLM Response: Party
71
 
72
- User: Where do I find an encyclopedia?
73
- LLM Response: You can find it in any of the libraries or on the Internet. Does this answer make you happy?
 
 
 
 
 
 
74
 
75
- User: I need a coffee
76
- LLM Response: It sounds like you're in need of a little pick-me-up. How are you feeling right now? Are you looking for something upbeat, something to relax to, or maybe some instrumental music while you enjoy your coffee?
77
 
78
- User: I just got promoted at work!
79
- LLM Response: Happy
80
 
81
- User: Today is my birthday!
82
- LLM Response: Happy
83
 
84
- User: I won a prize in the lottery.
85
- LLM Response: Happy
86
 
87
- User: I am so excited about my vacation next week!
88
- LLM Response: Happy
89
 
90
- User: I aced my exams!
91
- LLM Response: Happy
92
 
93
- User: I had a wonderful time with my family today.
94
- LLM Response: Happy
95
 
96
- User: I just finished a great workout!
97
- LLM Response: Happy
98
 
99
- User: I am feeling really good about myself today.
100
- LLM Response: Happy
101
 
102
- User: I finally finished my project and it was a success!
103
- LLM Response: Happy
104
 
105
- User: I just heard my favorite song on the radio.
106
- LLM Response: Happy
107
 
108
- User: My pet passed away yesterday.
109
- LLM Response: Sad
110
 
111
- User: I lost my job today.
112
- LLM Response: Sad
113
 
114
- User: I'm feeling really lonely.
115
- LLM Response: Sad
116
 
117
- User: I didn't get the results I wanted.
118
- LLM Response: Sad
119
 
120
- User: I had a fight with my best friend.
121
- LLM Response: Sad
122
 
123
- User: I'm feeling really overwhelmed with everything.
124
- LLM Response: Sad
125
 
126
- User: I just got some bad news.
127
- LLM Response: Sad
128
 
129
- User: I'm missing my family.
130
- LLM Response: Sad
131
 
132
- User: I am feeling really down today.
133
- LLM Response: Sad
134
 
135
- User: Nothing seems to be going right.
136
- LLM Response: Sad
137
 
138
- User: I need some music while I study.
139
- LLM Response: Instrumental
140
 
141
- User: I want to listen to something soothing while I work.
142
- LLM Response: Instrumental
143
 
144
- User: Do you have any recommendations for background music?
145
- LLM Response: Instrumental
146
 
147
- User: I'm looking for some relaxing tunes.
148
- LLM Response: Instrumental
149
 
150
- User: I need some music to focus on my tasks.
151
- LLM Response: Instrumental
152
 
153
- User: Can you suggest some ambient music for meditation?
154
- LLM Response: Instrumental
155
 
156
- User: What's good for background music during reading?
157
- LLM Response: Instrumental
158
 
159
- User: I need some calm music to help me sleep.
160
- LLM Response: Instrumental
161
 
162
- User: I prefer instrumental music while cooking.
163
- LLM Response: Instrumental
164
 
165
- User: What's the best music to play while doing yoga?
166
- LLM Response: Instrumental
167
 
168
- User: Let's have a blast tonight!
169
- LLM Response: Party
170
 
171
- User: I'm in the mood to dance!
172
- LLM Response: Party
173
 
174
- User: I want to celebrate all night long!
175
- LLM Response: Party
176
 
177
- User: Time to hit the club!
178
- LLM Response: Party
179
 
180
- User: I feel like partying till dawn.
181
- LLM Response: Party
182
 
183
- User: Let's get this party started!
184
- LLM Response: Party
185
 
186
- User: I'm ready to party hard tonight.
187
- LLM Response: Party
188
 
189
- User: I'm in the mood for some loud music and dancing!
190
- LLM Response: Party
191
 
192
- User: Tonight's going to be epic!
193
- LLM Response: Party
194
 
195
- User: Lets turn up the music and have some fun!
196
- LLM Response: Party
197
- """
198
 
199
- # Start with the fixed prompt
200
- prompt = f"<s>{fixed_prompt}"
 
 
 
 
201
 
202
- # Append the conversation history
203
- for user_prompt, bot_response in history:
204
- prompt += f"\nUser: {user_prompt}\nLLM Response: {bot_response}"
205
-
206
- # Add the current message
207
- prompt += f"\nUser: {message}\nLLM Response:"
208
-
209
- return prompt
210
-
211
- def generate(self, message, history, temperature=None, max_new_tokens=None, top_p=None, repetition_penalty=None):
212
- if temperature is None:
213
- temperature = self.temperature
214
- if max_new_tokens is None:
215
- max_new_tokens = self.max_new_tokens
216
- if top_p is None:
217
- top_p = self.top_p
218
- if repetition_penalty is None:
219
- repetition_penalty = self.repetition_penalty
220
-
221
- prompt = self.format_prompt(message, history)
222
- inputs = self.tokenizer(prompt, return_tensors="pt", padding=True).to("cuda")
223
- generate_kwargs = dict(
224
- temperature=temperature,
225
- max_new_tokens=max_new_tokens,
226
- top_p=top_p,
227
- repetition_penalty=repetition_penalty,
228
- do_sample=True,
229
- pad_token_id=self.tokenizer.pad_token_id, # Explicitly set the pad_token_id
230
- )
231
- output_ids = self.model.generate(**inputs, **generate_kwargs)
232
- output = self.tokenizer.decode(output_ids[0], skip_special_tokens=True)
233
- return output[len(prompt):].strip()
234
 
235
  def classify_mood(input_string):
236
  input_string = input_string.lower()
@@ -240,43 +191,44 @@ def classify_mood(input_string):
240
  return word, True
241
  return None, False
242
 
243
- def speech_to_text(speech):
244
- asr = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h")
245
- text = asr(speech)["text"]
246
- return text
247
-
248
- def text_to_speech(text):
249
- tts = pipeline("text-to-speech", model="facebook/fastspeech2-en-ljspeech")
250
- speech = tts(text)["audio"]
251
- return speech
252
-
253
- if __name__ == "__main__":
254
- parser = argparse.ArgumentParser(description="Start the Mistral chatbot application.")
255
- parser.add_argument("--model_name", type=str, default="mistralai/Mistral-7B-Instruct-v0.2", help="The name of the model to use.")
256
-
257
- args = parser.parse_args()
258
- model_name = args.model_name
259
-
260
- # Instantiate the chatbot with necessary parameters
261
- mistral_chatbot = llmChatbot(model_name=model_name)
262
- history = []
263
- print("How are you doing today?")
264
-
265
- def chatbot_response(audio_input):
266
- text_input = speech_to_text(audio_input)
267
- result = mistral_chatbot.generate(text_input, history)
268
- mood, is_classified = classify_mood(result)
269
  if is_classified:
270
- response_text = mood.capitalize()
271
- else:
272
- response_text = result
273
- audio_output = text_to_speech(response_text)
274
- history.append((text_input, response_text))
275
- return audio_output, response_text
276
-
277
- gr.Interface(
278
- fn=chatbot_response,
279
- inputs=gr.Audio(source="microphone", type="filepath"),
280
- outputs=[gr.Audio(type="numpy"), "text"],
281
- live=True
282
- ).launch()
 
 
1
+ from huggingface_hub import InferenceClient
 
 
2
  import gradio as gr
3
 
4
+ client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.1")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ def format_prompt(message, history):
7
+ fixed_prompt = """
 
8
 
9
+ You are a smart mood analyser, who determines user mood. Based on the user input, classify the mood of the user into one of the four moods {Happy, Sad, Instrumental, Party}. If you are finding it difficult to classify into one of these four moods, keep the conversation going on until we classify the user’s mood. Return a single response in the format "Playing [mood] playlist" where [mood] is one of the options if you have classified. Suppose you classify a sentence as happy, then respond with "Playing happy playlist".
10
 
11
+ Note: Do not write anything else other than the classified playlist message if classified.
12
 
13
+ Note: If any question or any user text cannot be classified, follow up with a question to know the user's mood until you classify the mood.
14
 
15
+ Note: Mood should be classified only from any of these 4 classes {Happy, Sad, Instrumental, Party}, if not any of these 4 then continue with a follow-up question until you classify the mood.
16
 
17
+ Note: if user asks something like I need a coffee then do not classify the mood directly and ask more follow-up questions as asked in examples.
 
 
18
 
19
+ Examples:
20
+ User: What is C programming?
21
+ LLM Response: C programming is a programming language. How are you feeling now after knowing the answer?
 
22
 
23
+ User: Can I get a coffee?
24
+ LLM Response: It sounds like you're in need of a little pick-me-up. How are you feeling right now? Are you looking for something upbeat, something to relax to, or maybe some instrumental music while you enjoy your coffee?
25
+ User: I feel like rocking
26
+ LLM Response: Playing party playlist
27
 
28
+ User: I'm feeling so energetic today!
29
+ LLM Response: Playing happy playlist
30
 
31
+ User: I'm feeling down today.
32
+ LLM Response: Playing sad playlist
33
 
34
+ User: I'm ready to have some fun tonight!
35
+ LLM Response: Playing party playlist
36
 
37
+ User: I need some background music while I am stuck in traffic.
38
+ LLM Response: Playing instrumental playlist
39
 
40
+ User: Hi
41
+ LLM Response: Hi, how are you doing?
 
 
 
 
 
 
42
 
43
+ User: Feeling okay only.
44
+ LLM Response: Are you having a good day?
45
+ User: I don't know
46
+ LLM Response: Do you want to listen to some relaxing music?
47
+ User: No
48
+ LLM Response: How about listening to some rock and roll music?
49
+ User: Yes
50
+ LLM Response: Playing party playlist
51
 
52
+ User: Where do I find an encyclopedia?
53
+ LLM Response: You can find it in any of the libraries or on the Internet. Does this answer make you happy?
54
 
55
+ User: I need a coffee
56
+ LLM Response: It sounds like you're in need of a little pick-me-up. How are you feeling right now? Are you looking for something upbeat, something to relax to, or maybe some instrumental music while you enjoy your coffee?
57
 
58
+ User: I just got promoted at work!
59
+ LLM Response: Playing happy playlist
60
 
61
+ User: Today is my birthday!
62
+ LLM Response: Playing happy playlist
63
 
64
+ User: I won a prize in the lottery.
65
+ LLM Response: Playing happy playlist
66
 
67
+ User: I am so excited about my vacation next week!
68
+ LLM Response: Playing happy playlist
69
 
70
+ User: I aced my exams!
71
+ LLM Response: Playing happy playlist
72
 
73
+ User: I had a wonderful time with my family today.
74
+ LLM Response: Playing happy playlist
75
 
76
+ User: I just finished a great workout!
77
+ LLM Response: Playing happy playlist
78
 
79
+ User: I am feeling really good about myself today.
80
+ LLM Response: Playing happy playlist
81
 
82
+ User: I finally finished my project and it was a success!
83
+ LLM Response: Playing happy playlist
84
 
85
+ User: I just heard my favorite song on the radio.
86
+ LLM Response: Playing happy playlist
87
 
88
+ User: My pet passed away yesterday.
89
+ LLM Response: Playing sad playlist
90
 
91
+ User: I lost my job today.
92
+ LLM Response: Playing sad playlist
93
 
94
+ User: I'm feeling really lonely.
95
+ LLM Response: Playing sad playlist
96
 
97
+ User: I didn't get the results I wanted.
98
+ LLM Response: Playing sad playlist
99
 
100
+ User: I had a fight with my best friend.
101
+ LLM Response: Playing sad playlist
102
 
103
+ User: I'm feeling really overwhelmed with everything.
104
+ LLM Response: Playing sad playlist
105
 
106
+ User: I just got some bad news.
107
+ LLM Response: Playing sad playlist
108
 
109
+ User: I'm missing my family.
110
+ LLM Response: Playing sad playlist
111
 
112
+ User: I am feeling really down today.
113
+ LLM Response: Playing sad playlist
114
 
115
+ User: Nothing seems to be going right.
116
+ LLM Response: Playing sad playlist
117
 
118
+ User: I need some music while I study.
119
+ LLM Response: Playing instrumental playlist
120
 
121
+ User: I want to listen to something soothing while I work.
122
+ LLM Response: Playing instrumental playlist
123
 
124
+ User: Do you have any recommendations for background music?
125
+ LLM Response: Playing instrumental playlist
126
 
127
+ User: I'm looking for some relaxing tunes.
128
+ LLM Response: Playing instrumental playlist
129
 
130
+ User: I need some music to focus on my tasks.
131
+ LLM Response: Playing instrumental playlist
132
 
133
+ User: Can you suggest some ambient music for meditation?
134
+ LLM Response: Playing instrumental playlist
135
 
136
+ User: What's good for background music during reading?
137
+ LLM Response: Playing instrumental playlist
138
 
139
+ User: I need some calm music to help me sleep.
140
+ LLM Response: Playing instrumental playlist
141
 
142
+ User: I prefer instrumental music while cooking.
143
+ LLM Response: Playing instrumental playlist
144
 
145
+ User: What's the best music to play while doing yoga?
146
+ LLM Response: Playing instrumental playlist
147
 
148
+ User: Let's have a blast tonight!
149
+ LLM Response: Playing party playlist
150
 
151
+ User: I'm in the mood to dance!
152
+ LLM Response: Playing party playlist
153
 
154
+ User: I want to celebrate all night long!
155
+ LLM Response: Playing party playlist
156
 
157
+ User: Time to hit the club!
158
+ LLM Response: Playing party playlist
159
 
160
+ User: I feel like partying till dawn.
161
+ LLM Response: Playing party playlist
162
 
163
+ User: Let's get this party started!
164
+ LLM Response: Playing party playlist
165
 
166
+ User: I'm ready to party hard tonight.
167
+ LLM Response: Playing party playlist
168
 
169
+ User: I'm in the mood for some loud music and dancing!
170
+ LLM Response: Playing party playlist
171
 
172
+ User: Tonight's going to be epic!
173
+ LLM Response: Playing party playlist
 
174
 
175
+ User: Lets turn up the music and have some fun!
176
+ LLM Response: Playing party playlist
177
+ """
178
+ prompt = f"<s>{fixed_prompt}"
179
+ for user_prompt, bot_response in history:
180
+ prompt += f"\nUser: {user_prompt}\nLLM Response: {bot_response}"
181
 
182
+ # Add the current message
183
+ prompt += f"\nUser: {message}\nLLM Response:"
184
+ return prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
  def classify_mood(input_string):
187
  input_string = input_string.lower()
 
191
  return word, True
192
  return None, False
193
 
194
+ def generate(
195
+ prompt, history, temperature=0.1, max_new_tokens=2048, top_p=0.8, repetition_penalty=1.0,
196
+ ):
197
+ temperature = float(temperature)
198
+ if temperature < 1e-2:
199
+ temperature = 1e-2
200
+ top_p = float(top_p)
201
+
202
+ generate_kwargs = dict(
203
+ temperature=temperature,
204
+ max_new_tokens=max_new_tokens,
205
+ top_p=top_p,
206
+ repetition_penalty=repetition_penalty,
207
+ do_sample=True,
208
+ seed=42,
209
+ )
210
+
211
+ formatted_prompt = format_prompt(prompt, history)
212
+
213
+ stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
214
+ output = ""
215
+
216
+ for response in stream:
217
+ output += response.token.text
218
+ mood, is_classified = classify_mood(output)
219
+ # Print the chatbot's response
220
  if is_classified:
221
+ output = f"Playing {mood} playlist"
222
+ return output
223
+ return output
224
+
225
+ demo = gr.ChatInterface(
226
+ fn=generate,
227
+ title="Mood-Based Music Recommender",
228
+ retry_btn=None,
229
+ undo_btn=None,
230
+ clear_btn=None,
231
+ description="<span style='font-size: larger; font-weight: bold;'>Hi! I'm a music recommender app. What kind of music do you want to listen to, or how are you feeling today?</span>",
232
+ )
233
+
234
+ demo.queue().launch()