joey1101 commited on
Commit
b1dada0
Β·
verified Β·
1 Parent(s): befe307

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -68
app.py CHANGED
@@ -2,7 +2,7 @@
2
  # Step 0: Essential imports
3
  ##########################################
4
  import streamlit as st # Web interface
5
- from transformers import ( # AI components
6
  pipeline,
7
  SpeechT5Processor,
8
  SpeechT5ForTextToSpeech,
@@ -10,14 +10,15 @@ from transformers import ( # AI components
10
  AutoModelForCausalLM,
11
  AutoTokenizer
12
  )
13
- from datasets import load_dataset # Voice data
14
- import torch # Tensor operations
15
- import soundfile as sf # Audio processing
 
16
 
17
  ##########################################
18
  # Initial configuration (MUST BE FIRST)
19
  ##########################################
20
- st.set_page_config( # Set page config first
21
  page_title="Just Comment",
22
  page_icon="πŸ’¬",
23
  layout="centered"
@@ -28,10 +29,10 @@ st.set_page_config( # Set page config first
28
  ##########################################
29
  @st.cache_resource(show_spinner=False)
30
  def _load_components():
31
- """Load and cache all models with hardware optimization"""
32
- device = "cuda" if torch.cuda.is_available() else "cpu"
33
 
34
- # Emotion classifier (fast)
35
  emotion_pipe = pipeline(
36
  "text-classification",
37
  model="Thea231/jhartmann_emotion_finetuning",
@@ -39,15 +40,21 @@ def _load_components():
39
  truncation=True
40
  )
41
 
42
- # Text generator (optimized)
43
  text_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-0.5B")
44
- text_model = AutoModelForCausalLM.from_pretrained(
45
- "Qwen/Qwen1.5-0.5B",
46
- torch_dtype=torch.float16,
47
- device_map="auto"
48
- )
 
 
 
 
 
 
49
 
50
- # TTS system (accelerated)
51
  tts_processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
52
  tts_model = SpeechT5ForTextToSpeech.from_pretrained(
53
  "microsoft/speecht5_tts",
@@ -58,7 +65,7 @@ def _load_components():
58
  torch_dtype=torch.float16
59
  ).to(device)
60
 
61
- # Preloaded voice profile
62
  speaker_emb = torch.tensor(
63
  load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")[7306]["xvector"]
64
  ).unsqueeze(0).to(device)
@@ -78,10 +85,10 @@ def _load_components():
78
  # User interface components
79
  ##########################################
80
  def _show_interface():
81
- """Render input interface"""
82
- st.title("Just Comment")
83
- st.markdown("### I'm listening to you, my friend~")
84
- return st.text_area( # Input field
85
  "πŸ“ Enter your comment:",
86
  placeholder="Share your thoughts...",
87
  height=150,
@@ -92,83 +99,93 @@ def _show_interface():
92
  # Core processing functions
93
  ##########################################
94
  def _fast_emotion(text, analyzer):
95
- """Rapid emotion detection with input limits"""
96
- result = analyzer(text[:256], return_all_scores=True)[0] # Limit input length
97
- emotions = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']
98
  return max(
99
- (e for e in result if e['label'].lower() in emotions),
100
  key=lambda x: x['score'],
101
  default={'label': 'neutral', 'score': 0}
102
  )
103
 
104
  def _build_prompt(text, emotion):
105
- """Template-based prompt engineering for response generation"""
106
- return f"{emotion.capitalize()} detected: {text}\nRespond with a coherent and supportive response."
 
 
 
 
 
 
 
 
 
 
107
 
108
  def _generate_response(text, models):
109
- """Optimized text generation pipeline"""
110
- # Emotion detection
111
- emotion = _fast_emotion(text, models["emotion"])
112
-
113
- # Prompt construction
114
- prompt = _build_prompt(text, emotion["label"])
115
-
116
- # Generate text
117
  inputs = models["text_tokenizer"](
118
  prompt,
119
  return_tensors="pt",
120
  max_length=100,
121
  truncation=True
122
  ).to(models["device"])
123
-
124
  output = models["text_model"].generate(
125
  inputs.input_ids,
126
- max_new_tokens=100, # Balanced length for response
 
127
  temperature=0.7,
128
  top_p=0.9,
129
  do_sample=True,
130
  pad_token_id=models["text_tokenizer"].eos_token_id
131
  )
132
-
133
- # Process output
134
- response = models["text_tokenizer"].decode(output[0], skip_special_tokens=True)
135
- return response.strip()[:200] or "Thank you for your feedback."
 
 
136
 
137
  def _text_to_speech(text, models):
138
- """High-speed audio synthesis"""
139
- inputs = models["tts_processor"](text=text[:150], return_tensors="pt").to(models["device"])
140
-
141
- with torch.inference_mode(): # Accelerated inference
142
- spectrogram = models["tts_model"].generate_speech(inputs["input_ids"], models["speaker_emb"])
 
 
 
 
 
143
  audio = models["tts_vocoder"](spectrogram)
144
-
145
- sf.write("output.wav", audio.cpu().numpy(), 16000)
146
- return "output.wav"
147
 
148
  ##########################################
149
  # Main application flow
150
  ##########################################
151
  def main():
152
- """Primary execution controller"""
153
- # Load components
154
- components = _load_components()
155
-
156
- # Show interface
157
- user_input = _show_interface()
158
-
159
- if user_input:
160
- # Text generation
161
- with st.spinner("πŸ” Analyzing..."):
162
- response = _generate_response(user_input, components)
163
-
164
- # Display result
165
  st.subheader("πŸ“„ Response")
166
- st.markdown(f"```\n{response}\n```") # f-string formatted
167
-
168
- # Audio generation
169
- with st.spinner("πŸ”Š Synthesizing..."):
170
- audio_path = _text_to_speech(response, components)
171
- st.audio(audio_path, format="audio/wav")
 
 
172
 
173
  if __name__ == "__main__":
174
- main() # Execute the main function
 
2
  # Step 0: Essential imports
3
  ##########################################
4
  import streamlit as st # Web interface
5
+ from transformers import ( # AI components: emotion analysis, text-to-speech, text generation
6
  pipeline,
7
  SpeechT5Processor,
8
  SpeechT5ForTextToSpeech,
 
10
  AutoModelForCausalLM,
11
  AutoTokenizer
12
  )
13
+ from datasets import load_dataset # To load speaker embeddings dataset
14
+ import torch # For tensor operations
15
+ import soundfile as sf # For audio file writing
16
+ import sentencepiece # Required for SpeechT5Processor tokenization
17
 
18
  ##########################################
19
  # Initial configuration (MUST BE FIRST)
20
  ##########################################
21
+ st.set_page_config( # Set page configuration
22
  page_title="Just Comment",
23
  page_icon="πŸ’¬",
24
  layout="centered"
 
29
  ##########################################
30
  @st.cache_resource(show_spinner=False)
31
  def _load_components():
32
+ """Load and cache all models with hardware optimization."""
33
+ device = "cuda" if torch.cuda.is_available() else "cpu" # Detect available device
34
 
35
+ # Load emotion classifier (fast; input truncated)
36
  emotion_pipe = pipeline(
37
  "text-classification",
38
  model="Thea231/jhartmann_emotion_finetuning",
 
40
  truncation=True
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
+ torch_dtype=torch.float16,
49
+ device_map="auto"
50
+ )
51
+ else:
52
+ text_model = AutoModelForCausalLM.from_pretrained(
53
+ "Qwen/Qwen1.5-0.5B",
54
+ torch_dtype=torch.float16
55
+ ).to(device)
56
 
57
+ # Load TTS components
58
  tts_processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
59
  tts_model = SpeechT5ForTextToSpeech.from_pretrained(
60
  "microsoft/speecht5_tts",
 
65
  torch_dtype=torch.float16
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)
 
85
  # User interface components
86
  ##########################################
87
  def _show_interface():
88
+ """Render input interface."""
89
+ st.title("πŸš€ Just Comment") # Display title with rocket emoji
90
+ st.markdown("### I'm listening to you, my friend~") # Display friendly subtitle
91
+ return st.text_area( # Return user comment input
92
  "πŸ“ Enter your comment:",
93
  placeholder="Share your thoughts...",
94
  height=150,
 
99
  # Core processing functions
100
  ##########################################
101
  def _fast_emotion(text, analyzer):
102
+ """Rapidly detect dominant emotion using a truncated input."""
103
+ result = analyzer(text[:256], return_all_scores=True)[0] # Analyze first 256 characters
104
+ valid_emotions = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']
105
  return max(
106
+ (e for e in result if e['label'].lower() in valid_emotions),
107
  key=lambda x: x['score'],
108
  default={'label': 'neutral', 'score': 0}
109
  )
110
 
111
  def _build_prompt(text, emotion):
112
+ """Build a continuous prompt (1–3 sentences) based on detected emotion."""
113
+ templates = {
114
+ "sadness": "I sensed sadness in your comment: {text}. We are sorry and ready to support you.",
115
+ "joy": "Your comment shows joy: {text}. Thank you for your positive feedback; we are excited to serve you better.",
116
+ "love": "Your comment expresses love: {text}. We appreciate your heartfelt words and value our connection.",
117
+ "anger": "I understand your comment reflects anger: {text}. Please accept our sincere apologies as we address your concerns.",
118
+ "fear": "It seems you feel fear: {text}. Rest assured, your safety and satisfaction are our top priorities.",
119
+ "surprise": "Your comment exudes surprise: {text}. We are pleased by your experience and will strive to exceed your expectations.",
120
+ "neutral": "Thank you for your comment: {text}. We are committed to providing you with excellent service."
121
+ }
122
+ # Use the template corresponding to the detected emotion (default to neutral)
123
+ return templates.get(emotion.lower(), templates["neutral"]).format(text=text[:200])
124
 
125
  def _generate_response(text, models):
126
+ """Generate a response by combining emotion detection and text generation."""
127
+ # Detect emotion quickly
128
+ detected_emotion = _fast_emotion(text, models["emotion"])
129
+ # Build prompt based on the detected emotion in a continuous format
130
+ prompt = _build_prompt(text, detected_emotion["label"])
131
+ print(f"Generated prompt: {prompt}") # Debug print with f-string
132
+ # Tokenize and generate response using the Qwen model
 
133
  inputs = models["text_tokenizer"](
134
  prompt,
135
  return_tensors="pt",
136
  max_length=100,
137
  truncation=True
138
  ).to(models["device"])
 
139
  output = models["text_model"].generate(
140
  inputs.input_ids,
141
+ max_new_tokens=120, # Constrain length for 50-200 tokens response
142
+ min_length=50,
143
  temperature=0.7,
144
  top_p=0.9,
145
  do_sample=True,
146
  pad_token_id=models["text_tokenizer"].eos_token_id
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 _text_to_speech(text, models):
156
+ """Convert the generated response text to speech and return the audio file path."""
157
+ inputs = models["tts_processor"](
158
+ text=text[:150], # Limit TTS input to 150 characters for speed
159
+ return_tensors="pt"
160
+ ).to(models["device"])
161
+ with torch.inference_mode(): # Accelerate inference
162
+ spectrogram = models["tts_model"].generate_speech(
163
+ inputs["input_ids"],
164
+ models["speaker_emb"]
165
+ )
166
  audio = models["tts_vocoder"](spectrogram)
167
+ sf.write("output.wav", audio.cpu().numpy(), 16000) # Save the audio file with 16kHz sample rate
168
+ return "output.wav" # Return the path to the audio file
 
169
 
170
  ##########################################
171
  # Main application flow
172
  ##########################################
173
  def main():
174
+ """Primary execution controller."""
175
+ models = _load_components() # Load all necessary models and components
176
+ user_input = _show_interface() # Render the input interface and get user comment
177
+ if user_input: # Proceed only if a comment is provided
178
+ with st.spinner("πŸ” Generating response..."):
179
+ generated_response = _generate_response(user_input, models)
 
 
 
 
 
 
 
180
  st.subheader("πŸ“„ Response")
181
+ st.markdown(
182
+ f"<p style='color:#3498DB; font-size:20px;'>{generated_response}</p>",
183
+ unsafe_allow_html=True
184
+ ) # Display the generated response in styled format
185
+ with st.spinner("πŸ”Š Synthesizing audio..."):
186
+ audio_file = _text_to_speech(generated_response, models)
187
+ st.audio(audio_file, format="audio/wav", start_time=0) # Embed auto-playing audio player
188
+ print(f"Final generated response: {generated_response}") # Debug print with f-string
189
 
190
  if __name__ == "__main__":
191
+ main() # Call the main function