Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,191 +1,210 @@
|
|
1 |
##########################################
|
2 |
-
# Step 0:
|
3 |
##########################################
|
4 |
-
import streamlit as st #
|
5 |
-
from transformers import (
|
6 |
pipeline,
|
7 |
SpeechT5Processor,
|
8 |
SpeechT5ForTextToSpeech,
|
9 |
SpeechT5HifiGan,
|
10 |
AutoModelForCausalLM,
|
11 |
AutoTokenizer
|
12 |
-
)
|
13 |
-
from datasets import load_dataset #
|
14 |
-
import torch #
|
15 |
-
import soundfile as sf #
|
16 |
-
import
|
17 |
|
18 |
##########################################
|
19 |
-
# Initial configuration (MUST
|
20 |
##########################################
|
21 |
-
st.set_page_config(
|
22 |
page_title="Just Comment",
|
23 |
page_icon="💬",
|
24 |
-
layout="centered"
|
|
|
25 |
)
|
26 |
|
27 |
##########################################
|
28 |
-
#
|
29 |
##########################################
|
30 |
@st.cache_resource(show_spinner=False)
|
31 |
-
def
|
32 |
-
"""Load and cache all models with
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
# Load text generation components with conditional device mapping
|
44 |
-
text_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-0.5B")
|
45 |
-
if device == "cuda":
|
46 |
-
text_model = AutoModelForCausalLM.from_pretrained(
|
47 |
"Qwen/Qwen1.5-0.5B",
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
else:
|
52 |
-
text_model = AutoModelForCausalLM.from_pretrained(
|
53 |
"Qwen/Qwen1.5-0.5B",
|
54 |
-
torch_dtype=torch.float16
|
55 |
-
)
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
"microsoft/
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
).to(device)
|
67 |
-
|
68 |
-
# Load a pre-trained speaker embedding (neutral voice)
|
69 |
-
speaker_emb = torch.tensor(
|
70 |
-
load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")[7306]["xvector"]
|
71 |
-
).unsqueeze(0).to(device)
|
72 |
-
|
73 |
-
return {
|
74 |
-
"emotion": emotion_pipe,
|
75 |
-
"text_model": text_model,
|
76 |
-
"text_tokenizer": text_tokenizer,
|
77 |
-
"tts_processor": tts_processor,
|
78 |
-
"tts_model": tts_model,
|
79 |
-
"tts_vocoder": tts_vocoder,
|
80 |
-
"speaker_emb": speaker_emb,
|
81 |
-
"device": device
|
82 |
}
|
83 |
|
84 |
##########################################
|
85 |
-
#
|
86 |
##########################################
|
87 |
-
def
|
88 |
-
"""Render
|
89 |
-
st.title("
|
90 |
-
st.markdown("### I'm listening to you, my friend~")
|
91 |
-
|
|
|
92 |
"📝 Enter your comment:",
|
93 |
-
placeholder="
|
94 |
height=150,
|
95 |
-
key="
|
96 |
)
|
97 |
|
98 |
##########################################
|
99 |
-
# Core
|
100 |
##########################################
|
101 |
-
def
|
102 |
-
"""
|
103 |
-
|
104 |
-
valid_emotions =
|
105 |
-
|
106 |
-
|
107 |
-
key=lambda x: x['score'],
|
108 |
-
default={'label': 'neutral', 'score': 0}
|
109 |
-
)
|
110 |
|
111 |
-
def
|
112 |
-
"""
|
113 |
-
|
114 |
-
"sadness":
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
121 |
}
|
122 |
-
|
123 |
-
return templates.get(emotion.lower(), templates["neutral"]).format(text=text[:200])
|
124 |
|
125 |
-
def
|
126 |
-
"""
|
127 |
-
#
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
inputs.input_ids,
|
141 |
-
max_new_tokens=
|
142 |
-
min_length=50,
|
143 |
temperature=0.7,
|
144 |
top_p=0.9,
|
145 |
do_sample=True,
|
146 |
-
pad_token_id=models[
|
|
|
|
|
|
|
|
|
147 |
)
|
148 |
-
input_len = inputs.input_ids.shape[1] # Length of prompt tokens
|
149 |
-
full_text = models["text_tokenizer"].decode(output[0], skip_special_tokens=True)
|
150 |
-
# Extract only the generated response portion (after any "Response:" marker if present)
|
151 |
-
response = full_text.split("Response:")[-1].strip()
|
152 |
-
print(f"Generated response: {response}") # Debug print with f-string
|
153 |
-
return response[:200] # Return response truncated to around 200 characters as an approximation
|
154 |
|
155 |
-
def
|
156 |
-
"""Convert
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
|
|
|
|
|
|
|
|
169 |
|
170 |
##########################################
|
171 |
-
# Main
|
172 |
##########################################
|
173 |
def main():
|
174 |
-
"""Primary execution
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
|
|
|
|
|
|
|
|
|
|
189 |
|
190 |
if __name__ == "__main__":
|
191 |
-
main()
|
|
|
1 |
##########################################
|
2 |
+
# Step 0: Import required libraries
|
3 |
##########################################
|
4 |
+
import streamlit as st # For web interface
|
5 |
+
from transformers import (
|
6 |
pipeline,
|
7 |
SpeechT5Processor,
|
8 |
SpeechT5ForTextToSpeech,
|
9 |
SpeechT5HifiGan,
|
10 |
AutoModelForCausalLM,
|
11 |
AutoTokenizer
|
12 |
+
) # AI model components
|
13 |
+
from datasets import load_dataset # For voice embeddings
|
14 |
+
import torch # Tensor computations
|
15 |
+
import soundfile as sf # Audio file handling
|
16 |
+
import re # Regular expressions for text processing
|
17 |
|
18 |
##########################################
|
19 |
+
# Initial configuration (MUST be first)
|
20 |
##########################################
|
21 |
+
st.set_page_config(
|
22 |
page_title="Just Comment",
|
23 |
page_icon="💬",
|
24 |
+
layout="centered",
|
25 |
+
initial_sidebar_state="collapsed"
|
26 |
)
|
27 |
|
28 |
##########################################
|
29 |
+
# Global model loading with caching
|
30 |
##########################################
|
31 |
@st.cache_resource(show_spinner=False)
|
32 |
+
def _load_models():
|
33 |
+
"""Load and cache all ML models with optimized settings"""
|
34 |
+
return {
|
35 |
+
# Emotion classification pipeline
|
36 |
+
'emotion': pipeline(
|
37 |
+
"text-classification",
|
38 |
+
model="Thea231/jhartmann_emotion_finetuning",
|
39 |
+
truncation=True # Enable text truncation for long inputs
|
40 |
+
),
|
41 |
+
|
42 |
+
# Text generation components
|
43 |
+
'textgen_tokenizer': AutoTokenizer.from_pretrained(
|
|
|
|
|
|
|
|
|
44 |
"Qwen/Qwen1.5-0.5B",
|
45 |
+
use_fast=True # Enable fast tokenization
|
46 |
+
),
|
47 |
+
'textgen_model': AutoModelForCausalLM.from_pretrained(
|
|
|
|
|
48 |
"Qwen/Qwen1.5-0.5B",
|
49 |
+
torch_dtype=torch.float16 # Use half-precision for faster inference
|
50 |
+
),
|
51 |
+
|
52 |
+
# Text-to-speech components
|
53 |
+
'tts_processor': SpeechT5Processor.from_pretrained("microsoft/speecht5_tts"),
|
54 |
+
'tts_model': SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts"),
|
55 |
+
'tts_vocoder': SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan"),
|
56 |
+
|
57 |
+
# Preloaded speaker embeddings
|
58 |
+
'speaker_embeddings': torch.tensor(
|
59 |
+
load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")[7306]["xvector"]
|
60 |
+
).unsqueeze(0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
}
|
62 |
|
63 |
##########################################
|
64 |
+
# UI Components
|
65 |
##########################################
|
66 |
+
def _display_interface():
|
67 |
+
"""Render user interface elements"""
|
68 |
+
st.title("Just Comment")
|
69 |
+
st.markdown("### I'm listening to you, my friend~")
|
70 |
+
|
71 |
+
return st.text_area(
|
72 |
"📝 Enter your comment:",
|
73 |
+
placeholder="Type your message here...",
|
74 |
height=150,
|
75 |
+
key="user_input"
|
76 |
)
|
77 |
|
78 |
##########################################
|
79 |
+
# Core Processing Functions
|
80 |
##########################################
|
81 |
+
def _analyze_emotion(text, classifier):
|
82 |
+
"""Identify dominant emotion with confidence threshold"""
|
83 |
+
results = classifier(text, return_all_scores=True)[0]
|
84 |
+
valid_emotions = {'sadness', 'joy', 'love', 'anger', 'fear', 'surprise'}
|
85 |
+
filtered = [e for e in results if e['label'].lower() in valid_emotions]
|
86 |
+
return max(filtered, key=lambda x: x['score'])
|
|
|
|
|
|
|
87 |
|
88 |
+
def _generate_prompt(text, emotion):
|
89 |
+
"""Create structured prompts for all emotion types"""
|
90 |
+
prompt_templates = {
|
91 |
+
"sadness": (
|
92 |
+
"Sadness detected: {input}\n"
|
93 |
+
"Required response structure:\n"
|
94 |
+
"1. Empathetic acknowledgment\n2. Support offer\n3. Solution proposal\n"
|
95 |
+
"Response:"
|
96 |
+
),
|
97 |
+
"joy": (
|
98 |
+
"Joy detected: {input}\n"
|
99 |
+
"Required response structure:\n"
|
100 |
+
"1. Enthusiastic thanks\n2. Positive reinforcement\n3. Future engagement\n"
|
101 |
+
"Response:"
|
102 |
+
),
|
103 |
+
"love": (
|
104 |
+
"Affection detected: {input}\n"
|
105 |
+
"Required response structure:\n"
|
106 |
+
"1. Warm appreciation\n2. Community focus\n3. Exclusive benefit\n"
|
107 |
+
"Response:"
|
108 |
+
),
|
109 |
+
"anger": (
|
110 |
+
"Anger detected: {input}\n"
|
111 |
+
"Required response structure:\n"
|
112 |
+
"1. Sincere apology\n2. Action steps\n3. Compensation\n"
|
113 |
+
"Response:"
|
114 |
+
),
|
115 |
+
"fear": (
|
116 |
+
"Concern detected: {input}\n"
|
117 |
+
"Required response structure:\n"
|
118 |
+
"1. Reassurance\n2. Safety measures\n3. Support options\n"
|
119 |
+
"Response:"
|
120 |
+
),
|
121 |
+
"surprise": (
|
122 |
+
"Surprise detected: {input}\n"
|
123 |
+
"Required response structure:\n"
|
124 |
+
"1. Acknowledge uniqueness\n2. Creative solution\n3. Follow-up\n"
|
125 |
+
"Response:"
|
126 |
+
)
|
127 |
}
|
128 |
+
return prompt_templates.get(emotion.lower(), "").format(input=text)
|
|
|
129 |
|
130 |
+
def _process_response(raw_text):
|
131 |
+
"""Clean and format generated response"""
|
132 |
+
# Extract text after last "Response:" marker
|
133 |
+
processed = raw_text.split("Response:")[-1].strip()
|
134 |
+
|
135 |
+
# Remove incomplete sentences
|
136 |
+
if '.' in processed:
|
137 |
+
processed = processed.rsplit('.', 1)[0] + '.'
|
138 |
+
|
139 |
+
# Ensure length between 50-200 characters
|
140 |
+
return processed[:200].strip() if len(processed) > 50 else "Thank you for your feedback. We value your input and will respond shortly."
|
141 |
+
|
142 |
+
def _generate_text_response(input_text, models):
|
143 |
+
"""Generate optimized text response with timing controls"""
|
144 |
+
# Emotion analysis
|
145 |
+
emotion = _analyze_emotion(input_text, models['emotion'])
|
146 |
+
|
147 |
+
# Prompt engineering
|
148 |
+
prompt = _generate_prompt(input_text, emotion['label'])
|
149 |
+
|
150 |
+
# Text generation with optimized parameters
|
151 |
+
inputs = models['textgen_tokenizer'](prompt, return_tensors="pt").to('cpu')
|
152 |
+
outputs = models['textgen_model'].generate(
|
153 |
inputs.input_ids,
|
154 |
+
max_new_tokens=100, # Strict token limit
|
|
|
155 |
temperature=0.7,
|
156 |
top_p=0.9,
|
157 |
do_sample=True,
|
158 |
+
pad_token_id=models['textgen_tokenizer'].eos_token_id
|
159 |
+
)
|
160 |
+
|
161 |
+
return _process_response(
|
162 |
+
models['textgen_tokenizer'].decode(outputs[0], skip_special_tokens=True)
|
163 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
164 |
|
165 |
+
def _generate_audio_response(text, models):
|
166 |
+
"""Convert text to speech with performance optimizations"""
|
167 |
+
# Process text input
|
168 |
+
inputs = models['tts_processor'](text=text, return_tensors="pt")
|
169 |
+
|
170 |
+
# Generate spectrogram
|
171 |
+
spectrogram = models['tts_model'].generate_speech(
|
172 |
+
inputs["input_ids"],
|
173 |
+
models['speaker_embeddings']
|
174 |
+
)
|
175 |
+
|
176 |
+
# Generate waveform with optimizations
|
177 |
+
with torch.no_grad(): # Disable gradient calculation
|
178 |
+
waveform = models['tts_vocoder'](spectrogram)
|
179 |
+
|
180 |
+
# Save audio file
|
181 |
+
sf.write("response.wav", waveform.numpy(), samplerate=16000)
|
182 |
+
return "response.wav"
|
183 |
|
184 |
##########################################
|
185 |
+
# Main Application Flow
|
186 |
##########################################
|
187 |
def main():
|
188 |
+
"""Primary execution flow"""
|
189 |
+
# Load models once
|
190 |
+
ml_models = _load_models()
|
191 |
+
|
192 |
+
# Display interface
|
193 |
+
user_input = _display_interface()
|
194 |
+
|
195 |
+
if user_input:
|
196 |
+
# Text generation stage
|
197 |
+
with st.spinner("🔍 Analyzing emotions and generating response..."):
|
198 |
+
text_response = _generate_text_response(user_input, ml_models)
|
199 |
+
|
200 |
+
# Display results
|
201 |
+
st.subheader("📄 Generated Response")
|
202 |
+
st.markdown(f"```\n{text_response}\n```") # f-string formatted output
|
203 |
+
|
204 |
+
# Audio generation stage
|
205 |
+
with st.spinner("🔊 Converting to speech..."):
|
206 |
+
audio_file = _generate_audio_response(text_response, ml_models)
|
207 |
+
st.audio(audio_file, format="audio/wav")
|
208 |
|
209 |
if __name__ == "__main__":
|
210 |
+
main()
|