Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,60 +1,53 @@
|
|
| 1 |
##########################################
|
| 2 |
-
# Step 0:
|
| 3 |
##########################################
|
| 4 |
-
import streamlit as st # Web interface
|
| 5 |
-
from transformers import (
|
| 6 |
pipeline,
|
| 7 |
SpeechT5Processor,
|
| 8 |
SpeechT5ForTextToSpeech,
|
| 9 |
SpeechT5HifiGan,
|
| 10 |
AutoModelForCausalLM,
|
| 11 |
AutoTokenizer
|
| 12 |
-
)
|
| 13 |
-
from datasets import load_dataset # Voice
|
| 14 |
-
import torch # Tensor
|
| 15 |
-
import soundfile as sf # Audio
|
| 16 |
-
import time # Execution timing
|
| 17 |
|
| 18 |
##########################################
|
| 19 |
-
# Initial configuration (MUST
|
| 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 |
-
# Optimized model
|
| 30 |
##########################################
|
| 31 |
@st.cache_resource(show_spinner=False)
|
| 32 |
-
def
|
| 33 |
-
"""Load and cache models with
|
| 34 |
-
# Initialize device-agnostic model loading
|
| 35 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 36 |
|
| 37 |
-
#
|
| 38 |
emotion_pipe = pipeline(
|
| 39 |
"text-classification",
|
| 40 |
model="Thea231/jhartmann_emotion_finetuning",
|
| 41 |
device=device,
|
| 42 |
-
truncation=True
|
| 43 |
-
padding=True
|
| 44 |
)
|
| 45 |
|
| 46 |
-
#
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
use_fast=True
|
| 50 |
-
)
|
| 51 |
-
textgen_model = AutoModelForCausalLM.from_pretrained(
|
| 52 |
"Qwen/Qwen1.5-0.5B",
|
| 53 |
torch_dtype=torch.float16,
|
| 54 |
device_map="auto"
|
| 55 |
)
|
| 56 |
|
| 57 |
-
#
|
| 58 |
tts_processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
|
| 59 |
tts_model = SpeechT5ForTextToSpeech.from_pretrained(
|
| 60 |
"microsoft/speecht5_tts",
|
|
@@ -65,169 +58,137 @@ def _load_models():
|
|
| 65 |
torch_dtype=torch.float16
|
| 66 |
).to(device)
|
| 67 |
|
| 68 |
-
#
|
| 69 |
-
|
| 70 |
load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")[7306]["xvector"]
|
| 71 |
).unsqueeze(0).to(device)
|
| 72 |
|
| 73 |
return {
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
}
|
| 83 |
|
| 84 |
##########################################
|
| 85 |
-
#
|
| 86 |
##########################################
|
| 87 |
-
def
|
| 88 |
-
"""Render
|
| 89 |
st.title("Just Comment")
|
| 90 |
-
st.markdown(f"### I'm listening to you, my friend~")
|
| 91 |
-
|
| 92 |
-
return st.text_area(
|
| 93 |
"📝 Enter your comment:",
|
| 94 |
-
placeholder="
|
| 95 |
height=150,
|
| 96 |
-
key="
|
| 97 |
)
|
| 98 |
|
| 99 |
##########################################
|
| 100 |
-
# Core
|
| 101 |
##########################################
|
| 102 |
-
def
|
| 103 |
-
"""
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
# Find dominant emotion
|
| 109 |
-
dominant = max(
|
| 110 |
-
(e for e in results if e['label'].lower() in valid_emotions),
|
| 111 |
key=lambda x: x['score'],
|
| 112 |
-
default={'label': 'neutral', 'score':
|
| 113 |
)
|
| 114 |
-
|
| 115 |
-
st.write(f"⏱️ Emotion analysis time: {time.time()-start_time:.2f}s")
|
| 116 |
-
return dominant
|
| 117 |
|
| 118 |
-
def
|
| 119 |
-
"""
|
| 120 |
-
|
| 121 |
-
"sadness": f"Sadness detected: {{
|
| 122 |
-
"joy": f"Joy detected: {{
|
| 123 |
-
"love": f"Love detected: {{
|
| 124 |
-
"anger": f"Anger detected: {{
|
| 125 |
-
"fear": f"Fear detected: {{
|
| 126 |
-
"surprise": f"Surprise detected: {{
|
| 127 |
-
"neutral": f"Feedback: {{
|
| 128 |
}
|
| 129 |
-
return
|
| 130 |
-
|
| 131 |
-
def _process_response(raw_text):
|
| 132 |
-
"""Fast response processing with validation"""
|
| 133 |
-
# Extract response after last marker
|
| 134 |
-
response = raw_text.split("Response:")[-1].strip()
|
| 135 |
-
|
| 136 |
-
# Ensure complete sentences
|
| 137 |
-
if '.' in response:
|
| 138 |
-
response = response.rsplit('.', 1)[0] + '.'
|
| 139 |
-
|
| 140 |
-
# Length control
|
| 141 |
-
return response[:200] if len(response) > 50 else "Thank you for your feedback. We'll respond shortly."
|
| 142 |
|
| 143 |
-
def
|
| 144 |
-
"""
|
| 145 |
-
|
|
|
|
| 146 |
|
| 147 |
-
#
|
| 148 |
-
|
| 149 |
|
| 150 |
-
# Generate
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
# Tokenize and generate
|
| 154 |
-
inputs = models['textgen_tokenizer'](
|
| 155 |
prompt,
|
| 156 |
return_tensors="pt",
|
| 157 |
-
max_length=
|
| 158 |
truncation=True
|
| 159 |
-
).to(models[
|
| 160 |
|
| 161 |
-
|
| 162 |
inputs.input_ids,
|
| 163 |
-
max_new_tokens=
|
| 164 |
temperature=0.7,
|
| 165 |
top_p=0.9,
|
| 166 |
do_sample=True,
|
| 167 |
-
pad_token_id=models[
|
| 168 |
)
|
| 169 |
|
| 170 |
-
#
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
skip_special_tokens=True
|
| 174 |
-
)
|
| 175 |
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
| 178 |
|
| 179 |
-
def
|
| 180 |
-
"""
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
# Process text
|
| 184 |
-
inputs = models['tts_processor'](
|
| 185 |
text=text[:150], # Limit text length
|
| 186 |
return_tensors="pt"
|
| 187 |
-
).to(models[
|
| 188 |
|
| 189 |
-
#
|
| 190 |
-
|
| 191 |
-
spectrogram = models['tts_model'].generate_speech(
|
| 192 |
inputs["input_ids"],
|
| 193 |
-
models[
|
| 194 |
)
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
# Save optimized audio file
|
| 198 |
-
sf.write("response.wav", waveform.cpu().numpy(), 16000)
|
| 199 |
|
| 200 |
-
|
| 201 |
-
return "
|
| 202 |
|
| 203 |
##########################################
|
| 204 |
-
# Main
|
| 205 |
##########################################
|
| 206 |
def main():
|
| 207 |
-
"""
|
| 208 |
-
# Load
|
| 209 |
-
|
| 210 |
|
| 211 |
-
#
|
| 212 |
-
user_input =
|
| 213 |
|
| 214 |
if user_input:
|
| 215 |
-
total_start = time.time()
|
| 216 |
-
|
| 217 |
# Text generation
|
| 218 |
-
with st.spinner("
|
| 219 |
-
|
| 220 |
|
| 221 |
-
# Display
|
| 222 |
-
st.subheader(f"📄
|
| 223 |
-
st.markdown(f"```\n{
|
| 224 |
|
| 225 |
# Audio generation
|
| 226 |
-
with st.spinner("🔊
|
| 227 |
-
|
| 228 |
-
st.audio(
|
| 229 |
-
|
| 230 |
-
st.write(f"⏱️ Total execution time: {time.time()-total_start:.2f}s")
|
| 231 |
|
| 232 |
if __name__ == "__main__":
|
| 233 |
main()
|
|
|
|
| 1 |
##########################################
|
| 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,
|
| 9 |
SpeechT5HifiGan,
|
| 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"
|
|
|
|
| 24 |
)
|
| 25 |
|
| 26 |
##########################################
|
| 27 |
+
# Optimized model loader with caching
|
| 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",
|
| 38 |
device=device,
|
| 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 |
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)
|
| 65 |
|
| 66 |
return {
|
| 67 |
+
"emotion": emotion_pipe,
|
| 68 |
+
"text_model": text_model,
|
| 69 |
+
"text_tokenizer": text_tokenizer,
|
| 70 |
+
"tts_processor": tts_processor,
|
| 71 |
+
"tts_model": tts_model,
|
| 72 |
+
"tts_vocoder": tts_vocoder,
|
| 73 |
+
"speaker_emb": speaker_emb,
|
| 74 |
+
"device": device
|
| 75 |
}
|
| 76 |
|
| 77 |
##########################################
|
| 78 |
+
# User interface components
|
| 79 |
##########################################
|
| 80 |
+
def _show_interface():
|
| 81 |
+
"""Render input interface"""
|
| 82 |
st.title("Just Comment")
|
| 83 |
+
st.markdown(f"### 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,
|
| 88 |
+
key="input"
|
| 89 |
)
|
| 90 |
|
| 91 |
##########################################
|
| 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"""
|
| 106 |
+
templates = {
|
| 107 |
+
"sadness": f"Sadness detected: {{text}}\nRespond with: 1. Empathy 2. Support 3. Solution\nResponse:",
|
| 108 |
+
"joy": f"Joy detected: {{text}}\nRespond with: 1. Thanks 2. Praise 3. Engagement\nResponse:",
|
| 109 |
+
"love": f"Love detected: {{text}}\nRespond with: 1. Appreciation 2. Connection 3. Offer\nResponse:",
|
| 110 |
+
"anger": f"Anger detected: {{text}}\nRespond with: 1. Apology 2. Action 3. Compensation\nResponse:",
|
| 111 |
+
"fear": f"Fear detected: {{text}}\nRespond with: 1. Reassurance 2. Safety 3. Support\nResponse:",
|
| 112 |
+
"surprise": f"Surprise detected: {{text}}\nRespond with: 1. Acknowledgement 2. Solution 3. Follow-up\nResponse:",
|
| 113 |
+
"neutral": f"Feedback: {{text}}\nProfessional response:\n1. Acknowledgement\n2. Assistance\n3. Next steps\nResponse:"
|
| 114 |
}
|
| 115 |
+
return templates[emotion.lower()].format(text=text[:200]) # Input truncation
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
+
def _generate_response(text, models):
|
| 118 |
+
"""Optimized text generation pipeline"""
|
| 119 |
+
# Emotion detection
|
| 120 |
+
emotion = _fast_emotion(text, models["emotion"])
|
| 121 |
|
| 122 |
+
# Prompt construction
|
| 123 |
+
prompt = _build_prompt(text, emotion["label"])
|
| 124 |
|
| 125 |
+
# Generate text
|
| 126 |
+
inputs = models["text_tokenizer"](
|
|
|
|
|
|
|
|
|
|
| 127 |
prompt,
|
| 128 |
return_tensors="pt",
|
| 129 |
+
max_length=100,
|
| 130 |
truncation=True
|
| 131 |
+
).to(models["device"])
|
| 132 |
|
| 133 |
+
output = models["text_model"].generate(
|
| 134 |
inputs.input_ids,
|
| 135 |
+
max_new_tokens=120, # Balanced length
|
| 136 |
temperature=0.7,
|
| 137 |
top_p=0.9,
|
| 138 |
do_sample=True,
|
| 139 |
+
pad_token_id=models["text_tokenizer"].eos_token_id
|
| 140 |
)
|
| 141 |
|
| 142 |
+
# Process output
|
| 143 |
+
full_text = models["text_tokenizer"].decode(output[0], skip_special_tokens=True)
|
| 144 |
+
response = full_text.split("Response:")[-1].strip()
|
|
|
|
|
|
|
| 145 |
|
| 146 |
+
# Ensure completeness
|
| 147 |
+
if "." in response:
|
| 148 |
+
response = response.rsplit(".", 1)[0] + "."
|
| 149 |
+
return response[:200] or "Thank you for your feedback. We'll respond shortly."
|
| 150 |
|
| 151 |
+
def _text_to_speech(text, models):
|
| 152 |
+
"""High-speed audio synthesis"""
|
| 153 |
+
inputs = models["tts_processor"](
|
|
|
|
|
|
|
|
|
|
| 154 |
text=text[:150], # Limit text length
|
| 155 |
return_tensors="pt"
|
| 156 |
+
).to(models["device"])
|
| 157 |
|
| 158 |
+
with torch.inference_mode(): # Accelerated inference
|
| 159 |
+
spectrogram = models["tts_model"].generate_speech(
|
|
|
|
| 160 |
inputs["input_ids"],
|
| 161 |
+
models["speaker_emb"]
|
| 162 |
)
|
| 163 |
+
audio = models["tts_vocoder"](spectrogram)
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
+
sf.write("output.wav", audio.cpu().numpy(), 16000)
|
| 166 |
+
return "output.wav"
|
| 167 |
|
| 168 |
##########################################
|
| 169 |
+
# Main application flow
|
| 170 |
##########################################
|
| 171 |
def main():
|
| 172 |
+
"""Primary execution controller"""
|
| 173 |
+
# Load components
|
| 174 |
+
components = _load_components()
|
| 175 |
|
| 176 |
+
# Show interface
|
| 177 |
+
user_input = _show_interface()
|
| 178 |
|
| 179 |
if user_input:
|
|
|
|
|
|
|
| 180 |
# Text generation
|
| 181 |
+
with st.spinner("🔍 Analyzing..."):
|
| 182 |
+
response = _generate_response(user_input, components)
|
| 183 |
|
| 184 |
+
# Display result
|
| 185 |
+
st.subheader(f"📄 Response")
|
| 186 |
+
st.markdown(f"```\n{response}\n```") # f-string formatted
|
| 187 |
|
| 188 |
# Audio generation
|
| 189 |
+
with st.spinner("🔊 Synthesizing..."):
|
| 190 |
+
audio_path = _text_to_speech(response, components)
|
| 191 |
+
st.audio(audio_path, format="audio/wav")
|
|
|
|
|
|
|
| 192 |
|
| 193 |
if __name__ == "__main__":
|
| 194 |
main()
|