Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
5 |
from transformers import (
|
6 |
pipeline,
|
7 |
SpeechT5Processor,
|
@@ -9,70 +9,50 @@ from transformers import (
|
|
9 |
SpeechT5HifiGan,
|
10 |
AutoModelForCausalLM,
|
11 |
AutoTokenizer
|
12 |
-
) # For
|
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 |
-
|
23 |
-
st.
|
24 |
-
|
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
|
50 |
"""
|
51 |
emotion_classifier = pipeline(
|
52 |
"text-classification",
|
53 |
model="Thea231/jhartmann_emotion_finetuning",
|
54 |
return_all_scores=True
|
55 |
-
) # Load
|
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
|
68 |
"""
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
|
|
73 |
emotion_prompts = {
|
74 |
"anger": (
|
75 |
-
|
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 |
-
|
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
|
91 |
}
|
92 |
-
|
93 |
-
#
|
94 |
-
prompt = emotion_prompts.get(emotion_label,
|
95 |
-
|
96 |
-
# Load a
|
97 |
-
tokenizer = AutoTokenizer.from_pretrained("
|
98 |
-
model = AutoModelForCausalLM.from_pretrained("
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
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
|
116 |
"""
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
|
|
|
|
|
|
|
|
133 |
|
134 |
##########################################
|
135 |
# Main Function
|
136 |
##########################################
|
137 |
def main():
|
138 |
"""
|
139 |
-
Main function to
|
140 |
"""
|
141 |
-
if text: # Check if the user
|
142 |
-
response = response_gen(text) # Generate
|
143 |
-
st.write(f"Generated response: {response}") # Display the generated response
|
144 |
-
sound_gen(response) # Convert the
|
145 |
|
146 |
-
# Run the main function
|
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()
|