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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
from transformers import (
|
4 |
+
AutoTokenizer, AutoModelForCausalLM,
|
5 |
+
SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan,
|
6 |
+
WhisperProcessor, WhisperForConditionalGeneration
|
7 |
+
)
|
8 |
+
from datasets import load_dataset
|
9 |
+
import os
|
10 |
+
import spaces
|
11 |
+
import tempfile
|
12 |
+
import soundfile as sf
|
13 |
+
import librosa
|
14 |
+
import yaml
|
15 |
+
|
16 |
+
# ================== Configuration ==================
|
17 |
+
HUGGINGFACE_MODEL_ID = "HuggingFaceH4/Qwen2.5-1.5B-Instruct-gkd"
|
18 |
+
TORCH_DTYPE = torch.bfloat16
|
19 |
+
MAX_NEW_TOKENS = 512
|
20 |
+
DO_SAMPLE = True
|
21 |
+
TEMPERATURE = 0.7
|
22 |
+
TOP_K = 50
|
23 |
+
TOP_P = 0.95
|
24 |
+
|
25 |
+
TTS_MODEL_ID = "microsoft/speecht5_tts"
|
26 |
+
TTS_VOCODER_ID = "microsoft/speecht5_hifigan"
|
27 |
+
STT_MODEL_ID = "openai/whisper-small"
|
28 |
+
|
29 |
+
# ================== Global Variables ==================
|
30 |
+
tokenizer = None
|
31 |
+
llm_model = None
|
32 |
+
tts_processor = None
|
33 |
+
tts_model = None
|
34 |
+
tts_vocoder = None
|
35 |
+
speaker_embeddings = None
|
36 |
+
whisper_processor = None
|
37 |
+
whisper_model = None
|
38 |
+
first_load = True
|
39 |
+
|
40 |
+
# ================== UI Helpers ==================
|
41 |
+
def generate_pretty_html(data):
|
42 |
+
html = """
|
43 |
+
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: auto;
|
44 |
+
background-color: #f9f9f9; border-radius: 10px; padding: 20px;
|
45 |
+
box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
|
46 |
+
<h2 style="color: #2c3e50; border-bottom: 2px solid #ddd; padding-bottom: 10px;">Model Info</h2>
|
47 |
+
"""
|
48 |
+
for key, value in data.items():
|
49 |
+
html += f"""
|
50 |
+
<div style="margin-bottom: 12px;">
|
51 |
+
<strong style="color: #34495e; display: inline-block; width: 160px;">{key}:</strong>
|
52 |
+
<span style="color: #2c3e50;">{value}</span>
|
53 |
+
</div>
|
54 |
+
"""
|
55 |
+
html += "</div>"
|
56 |
+
return html
|
57 |
+
|
58 |
+
|
59 |
+
def load_config():
|
60 |
+
with open("config.yaml", "r", encoding="utf-8") as f:
|
61 |
+
return yaml.safe_load(f)
|
62 |
+
|
63 |
+
|
64 |
+
def render_modern_info():
|
65 |
+
try:
|
66 |
+
config = load_config()
|
67 |
+
return generate_pretty_html(config)
|
68 |
+
except Exception as e:
|
69 |
+
return f"<div style='color: red;'>Error loading config: {str(e)}</div>"
|
70 |
+
|
71 |
+
|
72 |
+
def load_readme():
|
73 |
+
with open("README.md", "r", encoding="utf-8") as f:
|
74 |
+
return f.read()
|
75 |
+
|
76 |
+
|
77 |
+
# ================== Helper Functions ==================
|
78 |
+
def split_text_into_chunks(text, max_chars=400):
|
79 |
+
sentences = text.replace("...", ".").split(". ")
|
80 |
+
chunks = []
|
81 |
+
current_chunk = ""
|
82 |
+
for sentence in sentences:
|
83 |
+
if len(current_chunk) + len(sentence) + 2 < max_chars:
|
84 |
+
current_chunk += ". " + sentence if current_chunk else sentence
|
85 |
+
else:
|
86 |
+
chunks.append(current_chunk)
|
87 |
+
current_chunk = sentence
|
88 |
+
if current_chunk:
|
89 |
+
chunks.append(current_chunk)
|
90 |
+
return [f"{chunk}." for chunk in chunks if chunk.strip()]
|
91 |
+
|
92 |
+
|
93 |
+
# ================== Model Loading ==================
|
94 |
+
@spaces.GPU
|
95 |
+
def load_models():
|
96 |
+
global tokenizer, llm_model, tts_processor, tts_model, tts_vocoder, speaker_embeddings, whisper_processor, whisper_model
|
97 |
+
hf_token = os.environ.get("HF_TOKEN")
|
98 |
+
|
99 |
+
# LLM
|
100 |
+
if tokenizer is None or llm_model is None:
|
101 |
+
try:
|
102 |
+
tokenizer = AutoTokenizer.from_pretrained(HUGGINGFACE_MODEL_ID, token=hf_token)
|
103 |
+
if tokenizer.pad_token is None:
|
104 |
+
tokenizer.pad_token = tokenizer.eos_token
|
105 |
+
llm_model = AutoModelForCausalLM.from_pretrained(
|
106 |
+
HUGGINGFACE_MODEL_ID,
|
107 |
+
torch_dtype=TORCH_DTYPE,
|
108 |
+
device_map="auto",
|
109 |
+
token=hf_token
|
110 |
+
).eval()
|
111 |
+
print("LLM loaded successfully.")
|
112 |
+
except Exception as e:
|
113 |
+
print(f"Error loading LLM: {e}")
|
114 |
+
|
115 |
+
# TTS
|
116 |
+
if tts_processor is None or tts_model is None or tts_vocoder is None:
|
117 |
+
try:
|
118 |
+
tts_processor = SpeechT5Processor.from_pretrained(TTS_MODEL_ID, token=hf_token)
|
119 |
+
tts_model = SpeechT5ForTextToSpeech.from_pretrained(TTS_MODEL_ID, token=hf_token)
|
120 |
+
tts_vocoder = SpeechT5HifiGan.from_pretrained(TTS_VOCODER_ID, token=hf_token)
|
121 |
+
embeddings = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation", token=hf_token)
|
122 |
+
speaker_embeddings = torch.tensor(embeddings[7306]["xvector"]).unsqueeze(0)
|
123 |
+
device = llm_model.device if llm_model else 'cpu'
|
124 |
+
tts_model.to(device)
|
125 |
+
tts_vocoder.to(device)
|
126 |
+
speaker_embeddings = speaker_embeddings.to(device)
|
127 |
+
print("TTS models loaded.")
|
128 |
+
except Exception as e:
|
129 |
+
print(f"Error loading TTS: {e}")
|
130 |
+
|
131 |
+
# STT
|
132 |
+
if whisper_processor is None or whisper_model is None:
|
133 |
+
try:
|
134 |
+
whisper_processor = WhisperProcessor.from_pretrained(STT_MODEL_ID, token=hf_token)
|
135 |
+
whisper_model = WhisperForConditionalGeneration.from_pretrained(STT_MODEL_ID, token=hf_token)
|
136 |
+
device = llm_model.device if llm_model else 'cpu'
|
137 |
+
whisper_model.to(device)
|
138 |
+
print("Whisper loaded.")
|
139 |
+
except Exception as e:
|
140 |
+
print(f"Error loading Whisper: {e}")
|
141 |
+
|
142 |
+
|
143 |
+
# ================== Chat & Audio Functions ==================
|
144 |
+
@spaces.GPU
|
145 |
+
def generate_response_and_audio(message, history):
|
146 |
+
global first_load
|
147 |
+
if first_load:
|
148 |
+
load_models()
|
149 |
+
first_load = False
|
150 |
+
|
151 |
+
global tokenizer, llm_model, tts_processor, tts_model, tts_vocoder, speaker_embeddings
|
152 |
+
|
153 |
+
if tokenizer is None or llm_model is None:
|
154 |
+
return [{"role": "assistant", "content": "Error: LLM not loaded."}], None
|
155 |
+
|
156 |
+
messages = history.copy()
|
157 |
+
messages.append({"role": "user", "content": message})
|
158 |
+
|
159 |
+
try:
|
160 |
+
input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
161 |
+
except:
|
162 |
+
input_text = ""
|
163 |
+
for item in history:
|
164 |
+
input_text += f"{item['role'].capitalize()}: {item['content']}\n"
|
165 |
+
input_text += f"User: {message}\nAssistant:"
|
166 |
+
|
167 |
+
try:
|
168 |
+
inputs = tokenizer(input_text, return_tensors="pt", padding=True, truncation=True).to(llm_model.device)
|
169 |
+
output_ids = llm_model.generate(
|
170 |
+
inputs["input_ids"],
|
171 |
+
attention_mask=inputs["attention_mask"],
|
172 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
173 |
+
do_sample=DO_SAMPLE,
|
174 |
+
temperature=TEMPERATURE,
|
175 |
+
top_k=TOP_K,
|
176 |
+
top_p=TOP_P,
|
177 |
+
pad_token_id=tokenizer.eos_token_id
|
178 |
+
)
|
179 |
+
generated_text = tokenizer.decode(output_ids[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True).strip()
|
180 |
+
except Exception as e:
|
181 |
+
print(f"LLM error: {e}")
|
182 |
+
return history + [{"role": "assistant", "content": "I had an issue generating a response."}], None
|
183 |
+
|
184 |
+
audio_path = None
|
185 |
+
if None not in [tts_processor, tts_model, tts_vocoder, speaker_embeddings]:
|
186 |
+
try:
|
187 |
+
device = llm_model.device
|
188 |
+
text_chunks = split_text_into_chunks(generated_text)
|
189 |
+
|
190 |
+
full_speech = []
|
191 |
+
for chunk in text_chunks:
|
192 |
+
tts_inputs = tts_processor(text=chunk, return_tensors="pt", max_length=512, truncation=True).to(device)
|
193 |
+
speech = tts_model.generate_speech(tts_inputs["input_ids"], speaker_embeddings, vocoder=tts_vocoder)
|
194 |
+
full_speech.append(speech.cpu())
|
195 |
+
|
196 |
+
full_speech_tensor = torch.cat(full_speech, dim=0)
|
197 |
+
|
198 |
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:
|
199 |
+
audio_path = tmp_file.name
|
200 |
+
sf.write(audio_path, full_speech_tensor.numpy(), samplerate=16000)
|
201 |
+
|
202 |
+
except Exception as e:
|
203 |
+
print(f"TTS error: {e}")
|
204 |
+
|
205 |
+
return history + [{"role": "assistant", "content": generated_text}], audio_path
|
206 |
+
|
207 |
+
|
208 |
+
@spaces.GPU
|
209 |
+
def transcribe_audio(filepath):
|
210 |
+
global first_load
|
211 |
+
if first_load:
|
212 |
+
load_models()
|
213 |
+
first_load = False
|
214 |
+
|
215 |
+
global whisper_processor, whisper_model
|
216 |
+
if whisper_model is None:
|
217 |
+
return "Whisper model not loaded."
|
218 |
+
|
219 |
+
try:
|
220 |
+
audio, sr = librosa.load(filepath, sr=16000)
|
221 |
+
inputs = whisper_processor(audio, sampling_rate=sr, return_tensors="pt").input_features.to(whisper_model.device)
|
222 |
+
outputs = whisper_model.generate(inputs)
|
223 |
+
return whisper_processor.batch_decode(outputs, skip_special_tokens=True)[0]
|
224 |
+
except Exception as e:
|
225 |
+
return f"Transcription failed: {e}"
|
226 |
+
|
227 |
+
|
228 |
+
# ================== Gradio UI ==================
|
229 |
+
with gr.Blocks(head="""
|
230 |
+
<script src="https://cdn.tailwindcss.com "></script>
|
231 |
+
""") as demo:
|
232 |
+
gr.Markdown("""
|
233 |
+
<div class="bg-gray-900 text-white p-4 rounded-lg shadow-md mb-6">
|
234 |
+
<h1 class="text-2xl font-bold">Qwen2.5 Chatbot with Voice Input/Output</h1>
|
235 |
+
<p class="text-gray-300">Powered by Gradio + TailwindCSS</p>
|
236 |
+
</div>
|
237 |
+
""")
|
238 |
+
|
239 |
+
with gr.Tab("Chat"):
|
240 |
+
gr.HTML("""
|
241 |
+
<div class="bg-gray-800 p-4 rounded-lg mb-4">
|
242 |
+
<label class="block text-gray-300 font-medium mb-2">Chat Interface</label>
|
243 |
+
</div>
|
244 |
+
""")
|
245 |
+
chatbot = gr.Chatbot(type='messages', elem_classes=["bg-gray-800", "text-white"])
|
246 |
+
text_input = gr.Textbox(
|
247 |
+
placeholder="Type your message...",
|
248 |
+
label="User Input",
|
249 |
+
elem_classes=["bg-gray-700", "text-white", "border-gray-600"]
|
250 |
+
)
|
251 |
+
audio_output = gr.Audio(label="Response Audio", autoplay=True)
|
252 |
+
text_input.submit(generate_response_and_audio, [text_input, chatbot], [chatbot, audio_output])
|
253 |
+
|
254 |
+
with gr.Tab("Transcribe"):
|
255 |
+
gr.HTML("""
|
256 |
+
<div class="bg-gray-800 p-4 rounded-lg mb-4">
|
257 |
+
<label class="block text-gray-300 font-medium mb-2">Audio Transcription</label>
|
258 |
+
</div>
|
259 |
+
""")
|
260 |
+
audio_input = gr.Audio(type="filepath", label="Upload Audio")
|
261 |
+
transcribed = gr.Textbox(
|
262 |
+
label="Transcription",
|
263 |
+
elem_classes=["bg-gray-700", "text-white", "border-gray-600"]
|
264 |
+
)
|
265 |
+
audio_input.upload(transcribe_audio, audio_input, transcribed)
|
266 |
+
|
267 |
+
clear_btn = gr.Button("Clear All", elem_classes=["bg-gray-600", "hover:bg-gray-500", "text-white", "mt-4"])
|
268 |
+
clear_btn.click(lambda: ([], "", None), None, [chatbot, text_input, audio_output])
|
269 |
+
|
270 |
+
html_output = gr.HTML("""
|
271 |
+
<div class="bg-gray-800 text-white p-4 rounded-lg mt-6 text-center">
|
272 |
+
Loading model info...
|
273 |
+
</div>
|
274 |
+
""")
|
275 |
+
demo.load(fn=render_modern_info, outputs=html_output)
|
276 |
+
|
277 |
+
|
278 |
+
# ================== Launch App ==================
|
279 |
+
demo.queue().launch()
|