joey1101 commited on
Commit
e4cf4e2
·
verified ·
1 Parent(s): c39c802

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -80
app.py CHANGED
@@ -1,7 +1,7 @@
1
  ##########################################
2
  # Step 0: Import required libraries
3
  ##########################################
4
- import streamlit as st # For building the web application interface
5
  from transformers import (
6
  pipeline,
7
  SpeechT5Processor,
@@ -9,70 +9,50 @@ from transformers import (
9
  SpeechT5HifiGan,
10
  AutoModelForCausalLM,
11
  AutoTokenizer
12
- ) # For sentiment analysis, text-to-speech, and response generation
13
  from datasets import load_dataset # For loading datasets (e.g., speaker embeddings)
14
  import torch # For tensor operations
15
  import soundfile as sf # For saving audio as .wav files
16
- import sentencepiece # Required by SpeechT5Processor for tokenization
17
-
18
 
19
  ##########################################
20
  # Streamlit application title and input
21
  ##########################################
22
- # Display a deep blue title in a large, visually appealing font
23
- st.markdown(
24
- "<h1 style='text-align: center; color: #00008B; font-size: 50px;'>🚀 Just Comment</h1>",
25
- unsafe_allow_html=True
26
- ) # Set deep blue title
27
-
28
- # Display a gentle, warm subtitle below the title
29
- st.markdown(
30
- "<h3 style='text-align: center; color: #5D6D7E; font-style: italic;'>I'm listening to you, my friend~</h3>",
31
- unsafe_allow_html=True
32
- ) # Set a friendly subtitle
33
-
34
- # Add a text area for user input with placeholder and tooltip
35
- text = st.text_area(
36
- "Enter your comment",
37
- placeholder="Type something here...",
38
- height=100,
39
- help="Write a comment you would like us to respond to!" # Provide tooltip
40
- ) # Create text input field
41
-
42
-
43
 
44
  ##########################################
45
  # Step 1: Sentiment Analysis Function
46
  ##########################################
47
  def analyze_dominant_emotion(user_review):
48
  """
49
- Analyze the dominant emotion in the user's review using our fine-tuned sentiment analysis model.
50
  """
51
  emotion_classifier = pipeline(
52
  "text-classification",
53
  model="Thea231/jhartmann_emotion_finetuning",
54
  return_all_scores=True
55
- ) # Load our fine-tuned sentiment analysis model from Hugging Face
56
-
57
- emotion_results = emotion_classifier(user_review)[0] # Perform sentiment analysis on the user input
58
- dominant_emotion = max(emotion_results, key=lambda x: x['score']) # Extract the emotion with the highest confidence score
59
- return dominant_emotion # Return the dominant emotion with its label and score
60
-
61
 
 
 
 
 
62
  ##########################################
63
  # Step 2: Response Generation Function
64
  ##########################################
65
  def response_gen(user_review):
66
  """
67
- Generate a logical and complete response based on the sentiment of the user's review.
68
  """
69
- dominant_emotion = analyze_dominant_emotion(user_review) # Identify the dominant emotion from the user's review
70
- emotion_label = dominant_emotion['label'].lower() # Extract the emotion label and convert it to lowercase
71
-
72
- # Define response templates tailored to each emotion
 
73
  emotion_prompts = {
74
  "anger": (
75
- f"Customer complaint: '{user_review}'\n\n"
76
  "As a customer service representative, write a response that:\n"
77
  "- Sincerely apologizes for the issue\n"
78
  "- Explains how the issue will be resolved\n"
@@ -80,69 +60,69 @@ def response_gen(user_review):
80
  "Response:"
81
  ),
82
  "joy": (
83
- f"Customer review: '{user_review}'\n\n"
84
  "As a customer service representative, write a positive response that:\n"
85
  "- Thanks the customer for their feedback\n"
86
  "- Acknowledges both positive and constructive comments\n"
87
  "- Invites them to explore loyalty programs\n\n"
88
  "Response:"
89
  ),
90
- # Add other emotions (e.g., sadness, fear) as needed
91
  }
92
-
93
- # Select the appropriate prompt template based on the detected emotion
94
- prompt = emotion_prompts.get(emotion_label, f"Neutral feedback: '{user_review}'\n\nProvide a professional response.")
95
-
96
- # Load a small text generation model for generating concise, logical responses
97
- tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-0.5B") # Load a tokenizer for processing the prompt
98
- model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen1.5-0.5B") # Load the language model for generating text
99
-
100
- inputs = tokenizer(prompt, return_tensors="pt") # Tokenize the input prompt
101
- outputs = model.generate(**inputs, max_new_tokens=100) # Generate a response with a limit on the number of tokens
102
- response = tokenizer.decode(outputs[0], skip_special_tokens=True) # Decode the generated response to text
103
-
104
- # Ensure the response length falls within the desired range (50-200 words)
105
- if len(response.split()) < 50 or len(response.split()) > 200:
106
- response = f"Dear customer, thank you for your feedback regarding '{user_review}'. We appreciate your patience and will ensure improvements based on your valuable input." # Fallback response
107
-
108
- return response # Return the generated response
109
 
110
  ##########################################
111
  # Step 3: Text-to-Speech Conversion Function
112
  ##########################################
113
  def sound_gen(response):
114
  """
115
- Convert the generated text response to a speech file and save it locally.
116
  """
117
- processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts") # Load the processor for the TTS model
118
- model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts") # Load the text-to-speech model
119
- vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan") # Load the vocoder model for audio synthesis
120
-
121
- # Load speaker embeddings for generating the audio (neutral female voice)
122
- embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation") # Load speaker embeddings dataset
123
- speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0) # Select a sample embedding
124
-
125
- inputs = processor(text=response, return_tensors="pt") # Convert the text response into processor-compatible format
126
- spectrogram = model.generate_speech(inputs["input_ids"], speaker_embeddings) # Generate speech as a spectrogram
127
-
128
- with torch.no_grad(): # Disable gradient computation for audio generation
129
- speech = vocoder(spectrogram) # Convert the spectrogram into an audio waveform
130
-
131
- sf.write("customer_service_response.wav", speech.numpy(), samplerate=16000) # Save the audio as a .wav file
132
- st.audio("customer_service_response.wav") # Allow users to play the generated audio in the app
 
 
 
 
133
 
134
  ##########################################
135
  # Main Function
136
  ##########################################
137
  def main():
138
  """
139
- Main function to combine sentiment analysis, response generation, and text-to-speech functionality.
140
  """
141
- if text: # Check if the user has entered a comment in the text area
142
- response = response_gen(text) # Generate an automated response based on the input comment
143
- st.write(f"Generated response: {response}") # Display the generated response in the app
144
- sound_gen(response) # Convert the text response to speech and make it available for playback
145
 
146
- # Run the main function when the script is executed
147
  if __name__ == "__main__":
148
  main()
 
1
  ##########################################
2
  # Step 0: Import required libraries
3
  ##########################################
4
+ import streamlit as st # For building the web application
5
  from transformers import (
6
  pipeline,
7
  SpeechT5Processor,
 
9
  SpeechT5HifiGan,
10
  AutoModelForCausalLM,
11
  AutoTokenizer
12
+ ) # For emotion analysis, text-to-speech, and text generation
13
  from datasets import load_dataset # For loading datasets (e.g., speaker embeddings)
14
  import torch # For tensor operations
15
  import soundfile as sf # For saving audio as .wav files
 
 
16
 
17
  ##########################################
18
  # Streamlit application title and input
19
  ##########################################
20
+ st.title("Comment Reply for You") # Application title
21
+ st.write("Generate automatic replies for user comments") # Application description
22
+ text = st.text_area("Enter your comment", "") # Text input for user to enter comments
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  ##########################################
25
  # Step 1: Sentiment Analysis Function
26
  ##########################################
27
  def analyze_dominant_emotion(user_review):
28
  """
29
+ Analyze the dominant emotion in the user's review using a text classification model.
30
  """
31
  emotion_classifier = pipeline(
32
  "text-classification",
33
  model="Thea231/jhartmann_emotion_finetuning",
34
  return_all_scores=True
35
+ ) # Load pre-trained emotion classification model
 
 
 
 
 
36
 
37
+ emotion_results = emotion_classifier(user_review)[0] # Get emotion scores for the review
38
+ dominant_emotion = max(emotion_results, key=lambda x: x['score']) # Find the emotion with the highest confidence
39
+ return dominant_emotion
40
+
41
  ##########################################
42
  # Step 2: Response Generation Function
43
  ##########################################
44
  def response_gen(user_review):
45
  """
46
+ Generate a response based on the sentiment of the user's review.
47
  """
48
+ # Use Llama-based model to create a response based on a generated prompt
49
+ dominant_emotion = analyze_dominant_emotion(user_review) # Get the dominant emotion
50
+ emotion_label = dominant_emotion['label'].lower() # Extract emotion label
51
+
52
+ # Define response templates for each emotion
53
  emotion_prompts = {
54
  "anger": (
55
+ "Customer complaint: '{review}'\n\n"
56
  "As a customer service representative, write a response that:\n"
57
  "- Sincerely apologizes for the issue\n"
58
  "- Explains how the issue will be resolved\n"
 
60
  "Response:"
61
  ),
62
  "joy": (
63
+ "Customer review: '{review}'\n\n"
64
  "As a customer service representative, write a positive response that:\n"
65
  "- Thanks the customer for their feedback\n"
66
  "- Acknowledges both positive and constructive comments\n"
67
  "- Invites them to explore loyalty programs\n\n"
68
  "Response:"
69
  ),
70
+ # Add other emotions as needed...
71
  }
72
+
73
+ # Format the prompt with the user's review
74
+ prompt = emotion_prompts.get(emotion_label, "Neutral").format(review=user_review)
75
+
76
+ # Load a pre-trained text generation model (replace 'meta-llama/Llama-3.2-1B' with an available model)
77
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
78
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
79
+ inputs = tokenizer(prompt, return_tensors="pt") # Tokenize the prompt
80
+ outputs = model.generate(**inputs, max_new_tokens=100) # Generate a response
81
+
82
+ input_length = inputs.input_ids.shape[1] # Length of the input text
83
+ response = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True) # Decode the generated text
84
+ return response
 
 
 
 
85
 
86
  ##########################################
87
  # Step 3: Text-to-Speech Conversion Function
88
  ##########################################
89
  def sound_gen(response):
90
  """
91
+ Convert the generated response to speech and save as a .wav file.
92
  """
93
+ # Load the pre-trained TTS models
94
+ processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
95
+ model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
96
+ vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
97
+
98
+ # Load speaker embeddings (e.g., neutral female voice)
99
+ embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
100
+ speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)
101
+
102
+ # Process the input text and generate a spectrogram
103
+ inputs = processor(text=response, return_tensors="pt")
104
+ spectrogram = model.generate_speech(inputs["input_ids"], speaker_embeddings)
105
+
106
+ # Use the vocoder to generate a waveform
107
+ with torch.no_grad():
108
+ speech = vocoder(spectrogram)
109
+
110
+ # Save the generated speech as a .wav file
111
+ sf.write("customer_service_response.wav", speech.numpy(), samplerate=16000)
112
+ st.audio("customer_service_response.wav") # Play the audio in Streamlit
113
 
114
  ##########################################
115
  # Main Function
116
  ##########################################
117
  def main():
118
  """
119
+ Main function to orchestrate the workflow of sentiment analysis, response generation, and text-to-speech.
120
  """
121
+ if text: # Check if the user entered a comment
122
+ response = response_gen(text) # Generate a response
123
+ st.write(f"Generated response: {response}") # Display the generated response
124
+ sound_gen(response) # Convert the response to speech and play it
125
 
126
+ # Run the main function
127
  if __name__ == "__main__":
128
  main()