joey1101 commited on
Commit
298c5bd
·
verified ·
1 Parent(s): 0e9a20e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -146
app.py CHANGED
@@ -19,41 +19,40 @@ st.write("automative reply")
19
  # Text input for user to enter the comment
20
  text = st.text_area("Enter your comment", "")
21
 
 
 
 
 
 
 
 
 
 
22
 
23
  ##########################################
24
  # Step 1:情感分析 - 分析用户评论的情感倾向
25
  ##########################################
26
- # Perform tasks when the user clicks the "Comment" button
27
- if st.button("Comment"):
28
 
29
- pipe = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base")
30
 
31
- # 使用 "j-hartmann/emotion-english-distilroberta-base" 模型进行多维度情感分类
32
- emotion_classifier = pipeline(
33
- "text-classification",
34
- model="j-hartmann/emotion-english-distilroberta-base",
35
- return_all_scores=True
36
- )
 
37
 
38
- # 示例用户评论(可替换为实际评论)
39
- user_review = "I love the fast delivery, but the product quality could be better."
40
 
41
- # 对评论进行情感分析
42
- emotion_results = emotion_classifier(user_review)[0] # 返回列表中的第一个结果(单条输入)
43
 
44
- # 打印所有情感维度及其分数
45
 
46
- print("情感分析结果(多维度):")
47
- for emotion in emotion_results:
48
- print(f"{emotion['label']}: {emotion['score']:.4f}")
49
-
50
- st.write("Text:", text)
51
- st.write("Label:", max_label)
52
- st.write("Score:", max_score)
53
-
54
  # 提取置信度最高的情感标签(可选)
55
- dominant_emotion = max(emotion_results, key=lambda x: x['score'])
56
- print("\n主导情感:", dominant_emotion['label'], f"(置信度: {dominant_emotion['score']:.2f})")
57
 
58
 
59
 
@@ -61,139 +60,146 @@ print("\n主导情感:", dominant_emotion['label'], f"(置信度: {dominant_em
61
  # Step 2:回复生成 - 根据情感生成自动回复
62
  ##########################################
63
 
64
- emotion_strategies = {
65
- "anger": {
66
- "prompt": (
67
- "Customer complaint: '{review}'\n\n"
68
- "As a customer service representative, craft a professional response that:\n"
69
- "- Begins with sincere apology and acknowledgment\n"
70
- "- Clearly explains solution process with concrete steps\n"
71
- "- Offers appropriate compensation/redemption\n"
72
- "- Keeps tone humble and solution-focused (3-4 sentences)\n\n"
73
- "Response:"
74
- )
75
- },
76
- "disgust": {
77
- "prompt": (
78
- "Customer quality concern: '{review}'\n\n"
79
- "As a customer service representative, craft a response that:\n"
80
- "- Immediately acknowledges the product issue\n"
81
- "- Explains quality control measures being taken\n"
82
- "- Provides clear return/replacement instructions\n"
83
- "- Offers goodwill gesture (3-4 sentences)\n\n"
84
- "Response:"
85
- )
86
- },
87
- "fear": {
88
- "prompt": (
89
- "Customer safety concern: '{review}'\n\n"
90
- "As a customer service representative, craft a reassuring response that:\n"
91
- "- Directly addresses the safety worries\n"
92
- "- References relevant certifications/standards\n"
93
- "- Offers dedicated support contact\n"
94
- "- Provides satisfaction guarantee (3-4 sentences)\n\n"
95
- "Response:"
96
- )
97
- },
98
- "joy": {
99
- "prompt": (
100
- "Customer review: '{review}'\n\n"
101
- "As a customer service representative, craft a concise response that:\n"
102
- "- Specifically acknowledges both positive and constructive feedback\n"
103
- "- Briefly mentions loyalty/referral programs\n"
104
- "- Ends with shopping invitation (3-4 sentences)\n\n"
105
- "Response:"
106
- )
107
- },
108
- "neutral": {
109
- "prompt": (
110
- "Customer feedback: '{review}'\n\n"
111
- "As a customer service representative, craft a balanced response that:\n"
112
- "- Provides additional relevant product information\n"
113
- "- Highlights key service features\n"
114
- "- Politely requests more detailed feedback\n"
115
- "- Maintains professional tone (3-4 sentences)\n\n"
116
- "Response:"
117
- )
118
- },
119
- "sadness": {
120
- "prompt": (
121
- "Customer disappointment: '{review}'\n\n"
122
- "As a customer service representative, craft an empathetic response that:\n"
123
- "- Shows genuine understanding of the issue\n"
124
- "- Proposes personalized recovery solution\n"
125
- "- Offers extended support options\n"
126
- "- Maintains positive outlook (3-4 sentences)\n\n"
127
- "Response:"
128
- )
129
- },
130
- "surprise": {
131
- "prompt": (
132
- "Customer enthusiastic feedback: '{review}'\n\n"
133
- "As a customer service representative, craft a response that:\n"
134
- "- Matches customer's positive energy appropriately\n"
135
- "- Highlights unexpected product benefits\n"
136
- "- Invites to user community/events\n"
137
- "- Maintains brand voice (3-4 sentences)\n\n"
138
- "Response:"
139
- )
140
- }
141
- }
142
-
143
-
144
-
145
- # 生成回复Prompt
146
- template = emotion_strategies[dominant_emotion['label'].lower()]["prompt"]
147
- prompt = template.format(review=user_review)
148
- print(prompt)
149
-
150
-
151
-
152
-
153
- # 加载Llama-3作为text generation模型
154
- tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
155
- model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
156
-
157
-
158
-
159
-
160
- inputs = tokenizer(prompt, return_tensors="pt")
161
- outputs = model.generate(**inputs, max_new_tokens=100)
162
-
163
- input_length = inputs.input_ids.shape[1]
164
- response = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True)
165
- print(response)
166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
 
169
 
170
  ##########################################
171
  # Step 3:语音生成 - 根据回复合成语音
172
  ##########################################
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
 
174
- # 加载模型和处理器
175
- #processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
176
- #speech_model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
177
- #vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
178
 
179
- processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
180
- model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
181
- vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
182
 
183
- # 创建默认的说话人嵌入
184
- embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
185
- speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0) # 女性中性语音
186
 
187
- # 文本预处理和语音合成
188
- inputs = processor(text=response, return_tensors="pt")
189
- spectrogram = model.generate_speech(inputs["input_ids"], speaker_embeddings)
190
 
191
- # 使用声码器生成波形音频
192
- with torch.no_grad():
193
- speech = vocoder(spectrogram)
194
 
195
- # 保存为WAV文件(16kHz采样率)
196
- sf.write("customer_service_response.wav", speech.numpy(), samplerate=16000)
197
- st.text("I wanna tell you that")
198
- st.audio("customer_service_response.wav")
199
 
 
 
 
19
  # Text input for user to enter the comment
20
  text = st.text_area("Enter your comment", "")
21
 
22
+ def main():
23
+ user_review = "I love the fast delivery, but the product quality could be better."
24
+ response = response_gen(user_review)
25
+ print(response)
26
+ sound_gen(response)
27
+ return
28
+
29
+
30
+ if st.button("Comment"):
31
 
32
  ##########################################
33
  # Step 1:情感分析 - 分析用户评论的情感倾向
34
  ##########################################
 
 
35
 
 
36
 
37
+ def analyze_dominant_emotion(user_review):
38
+ # Initialize the emotion classifier pipeline
39
+ emotion_classifier = pipeline(
40
+ "text-classification",
41
+ model="Thea231/jhartmann_emotion_finetuning",
42
+ return_all_scores=True
43
+ )
44
 
45
+ # Get emotion predictions for the input review
46
+ emotion_results = emotion_classifier(user_review)[0] # Get first result (single input case)
47
 
48
+ # Extract the emotion with highest confidence score
49
+ dominant_emotion = max(emotion_results, key=lambda x: x['score'])
50
 
51
+ return dominant_emotion
52
 
 
 
 
 
 
 
 
 
53
  # 提取置信度最高的情感标签(可选)
54
+ # dominant_emotion = analyze_dominant_emotion(user_review)
55
+ # print("\n主导情感:", dominant_emotion['label'], f"(置信度: {dominant_emotion['score']:.2f})")
56
 
57
 
58
 
 
60
  # Step 2:回复生成 - 根据情感生成自动回复
61
  ##########################################
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
+ def prompt_gen(user_review):
65
+ dominant_emotion = analyze_dominant_emotion(user_review)
66
+ emotion_strategies = {
67
+ "anger": {
68
+ "prompt": (
69
+ "Customer complaint: '{review}'\n\n"
70
+ "As a customer service representative, craft a professional response that:\n"
71
+ "- Begins with sincere apology and acknowledgment\n"
72
+ "- Clearly explains solution process with concrete steps\n"
73
+ "- Offers appropriate compensation/redemption\n"
74
+ "- Keeps tone humble and solution-focused (3-4 sentences)\n\n"
75
+ "Response:"
76
+ )
77
+ },
78
+ "disgust": {
79
+ "prompt": (
80
+ "Customer quality concern: '{review}'\n\n"
81
+ "As a customer service representative, craft a response that:\n"
82
+ "- Immediately acknowledges the product issue\n"
83
+ "- Explains quality control measures being taken\n"
84
+ "- Provides clear return/replacement instructions\n"
85
+ "- Offers goodwill gesture (3-4 sentences)\n\n"
86
+ "Response:"
87
+ )
88
+ },
89
+ "fear": {
90
+ "prompt": (
91
+ "Customer safety concern: '{review}'\n\n"
92
+ "As a customer service representative, craft a reassuring response that:\n"
93
+ "- Directly addresses the safety worries\n"
94
+ "- References relevant certifications/standards\n"
95
+ "- Offers dedicated support contact\n"
96
+ "- Provides satisfaction guarantee (3-4 sentences)\n\n"
97
+ "Response:"
98
+ )
99
+ },
100
+ "joy": {
101
+ "prompt": (
102
+ "Customer review: '{review}'\n\n"
103
+ "As a customer service representative, craft a concise response that:\n"
104
+ "- Specifically acknowledges both positive and constructive feedback\n"
105
+ "- Briefly mentions loyalty/referral programs\n"
106
+ "- Ends with shopping invitation (3-4 sentences)\n\n"
107
+ "Response:"
108
+ )
109
+ },
110
+ "neutral": {
111
+ "prompt": (
112
+ "Customer feedback: '{review}'\n\n"
113
+ "As a customer service representative, craft a balanced response that:\n"
114
+ "- Provides additional relevant product information\n"
115
+ "- Highlights key service features\n"
116
+ "- Politely requests more detailed feedback\n"
117
+ "- Maintains professional tone (3-4 sentences)\n\n"
118
+ "Response:"
119
+ )
120
+ },
121
+ "sadness": {
122
+ "prompt": (
123
+ "Customer disappointment: '{review}'\n\n"
124
+ "As a customer service representative, craft an empathetic response that:\n"
125
+ "- Shows genuine understanding of the issue\n"
126
+ "- Proposes personalized recovery solution\n"
127
+ "- Offers extended support options\n"
128
+ "- Maintains positive outlook (3-4 sentences)\n\n"
129
+ "Response:"
130
+ )
131
+ },
132
+ "surprise": {
133
+ "prompt": (
134
+ "Customer enthusiastic feedback: '{review}'\n\n"
135
+ "As a customer service representative, craft a response that:\n"
136
+ "- Matches customer's positive energy appropriately\n"
137
+ "- Highlights unexpected product benefits\n"
138
+ "- Invites to user community/events\n"
139
+ "- Maintains brand voice (3-4 sentences)\n\n"
140
+ "Response:"
141
+ )
142
+ }
143
+ }
144
+ # 生成回复Prompt
145
+ template = emotion_strategies[dominant_emotion['label'].lower()]["prompt"]
146
+ prompt = template.format(review=user_review)
147
+ print(prompt)
148
+ return prompt
149
+
150
+
151
+
152
+ def response_gen(user_review):
153
+ prompt = prompt_gen(user_review)
154
+ # 加载Llama-3作为text generation模型
155
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
156
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
157
+ inputs = tokenizer(prompt, return_tensors="pt")
158
+ outputs = model.generate(**inputs, max_new_tokens=100)
159
+
160
+ input_length = inputs.input_ids.shape[1]
161
+ response = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True)
162
+ # print(response)
163
+ return response
164
 
165
 
166
 
167
  ##########################################
168
  # Step 3:语音生成 - 根据回复合成语音
169
  ##########################################
170
+ def sound_gen(response):
171
+ # 加载模型和处理器
172
+ #processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
173
+ #speech_model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
174
+ #vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
175
+
176
+ processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
177
+ model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
178
+ vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
179
+
180
+ # 创建默认的说话人嵌入
181
+ embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
182
+ speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0) # 女性中性语音
183
+
184
+ # 文本预处理和语音合成
185
+ inputs = processor(text=response, return_tensors="pt")
186
+ spectrogram = model.generate_speech(inputs["input_ids"], speaker_embeddings)
187
 
188
+ # 使用声码器生成波形音频
189
+ with torch.no_grad():
190
+ speech = vocoder(spectrogram)
 
191
 
192
+ # 保存为WAV文件(16kHz采样率)
193
+ sf.write("customer_service_response.wav", speech.numpy(), samplerate=16000)
 
194
 
195
+ print("语音生成完成,已保存为 customer_service_response.wav")
196
+ return
 
197
 
 
 
 
198
 
199
+ sf.write("customer_service_response.wav", speech.numpy(), samplerate=16000)
200
+ st.text("I wanna tell you that")
201
+ st.audio("customer_service_response.wav")
202
 
 
 
 
 
203
 
204
+ if __name__ == "__main__":
205
+ main()