maximuschan commited on
Commit
974895d
1 Parent(s): 4bc6caa

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +864 -0
app.py ADDED
@@ -0,0 +1,864 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import os
3
+ #download for mecab
4
+ os.system('python -m unidic download')
5
+
6
+ # we need to compile a CUBLAS version
7
+ # Or get it from https://jllllll.github.io/llama-cpp-python-cuBLAS-wheels/
8
+ os.system('CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama-cpp-python==0.2.11')
9
+
10
+ # By using XTTS you agree to CPML license https://coqui.ai/cpml
11
+ os.environ["COQUI_TOS_AGREED"] = "1"
12
+
13
+ # NOTE: for streaming will require gradio audio streaming fix
14
+ # pip install --upgrade -y gradio==0.50.2 git+https://github.com/gorkemgoknar/gradio.git@patch-1
15
+
16
+ import textwrap
17
+ from scipy.io.wavfile import write
18
+ from pydub import AudioSegment
19
+ import gradio as gr
20
+ import numpy as np
21
+ import torch
22
+ import nltk # we'll use this to split into sentences
23
+ nltk.download("punkt")
24
+
25
+ import noisereduce as nr
26
+ import subprocess
27
+ import langid
28
+ import uuid
29
+ import emoji
30
+ import pathlib
31
+
32
+ import datetime
33
+
34
+ from scipy.io.wavfile import write
35
+ from pydub import AudioSegment
36
+
37
+ import re
38
+ import io, wave
39
+ import librosa
40
+ import torchaudio
41
+ from TTS.api import TTS
42
+ from TTS.tts.configs.xtts_config import XttsConfig
43
+ from TTS.tts.models.xtts import Xtts
44
+ from TTS.utils.generic_utils import get_user_data_dir
45
+
46
+
47
+ import gradio as gr
48
+ import os
49
+ import time
50
+
51
+ import gradio as gr
52
+ from transformers import pipeline
53
+ import numpy as np
54
+
55
+ from gradio_client import Client
56
+ from huggingface_hub import InferenceClient
57
+
58
+ # This will trigger downloading model
59
+ print("Downloading if not downloaded Coqui XTTS V2")
60
+
61
+ from TTS.utils.manage import ModelManager
62
+ model_name = "tts_models/multilingual/multi-dataset/xtts_v2"
63
+ ModelManager().download_model(model_name)
64
+ model_path = os.path.join(get_user_data_dir("tts"), model_name.replace("/", "--"))
65
+ print("XTTS downloaded")
66
+
67
+
68
+ print("Loading XTTS")
69
+ config = XttsConfig()
70
+ config.load_json(os.path.join(model_path, "config.json"))
71
+
72
+ model = Xtts.init_from_config(config)
73
+ model.load_checkpoint(
74
+ config,
75
+ checkpoint_path=os.path.join(model_path, "model.pth"),
76
+ vocab_path=os.path.join(model_path, "vocab.json"),
77
+ eval=True,
78
+ use_deepspeed=True,
79
+ )
80
+ model.cuda()
81
+ print("Done loading TTS")
82
+
83
+ #####llm_model = os.environ.get("LLM_MODEL", "mistral") # or "zephyr"
84
+
85
+ title = "Voice chat with Zephyr/Mistral and Coqui XTTS"
86
+
87
+ DESCRIPTION = """# Voice chat with Zephyr/Mistral and Coqui XTTS"""
88
+ css = """.toast-wrap { display: none !important } """
89
+
90
+ from huggingface_hub import HfApi
91
+
92
+ HF_TOKEN = os.environ.get("HF_TOKEN")
93
+ # will use api to restart space on a unrecoverable error
94
+ api = HfApi(token=HF_TOKEN)
95
+
96
+ repo_id = "coqui/voice-chat-with-zephyr"
97
+
98
+
99
+ default_system_message = f"""
100
+ You are ##LLM_MODEL###, a large language model trained ##LLM_MODEL_PROVIDER###, architecture of you is decoder-based LM. Your voice backend or text to speech TTS backend is provided via Coqui technology. You are right now served on Huggingface spaces.
101
+ Don't repeat. Answer short, only few words, as if in a talk. You cannot access the internet, but you have vast knowledge.
102
+ Current date: CURRENT_DATE .
103
+ """
104
+
105
+ system_message = os.environ.get("SYSTEM_MESSAGE", default_system_message)
106
+ system_message = system_message.replace("CURRENT_DATE", str(datetime.date.today()))
107
+
108
+
109
+ # MISTRAL ONLY
110
+ default_system_understand_message = (
111
+ "I understand, I am a ##LLM_MODEL### chatbot with speech by Coqui team."
112
+ )
113
+ system_understand_message = os.environ.get(
114
+ "SYSTEM_UNDERSTAND_MESSAGE", default_system_understand_message
115
+ )
116
+
117
+ print("Mistral system message set as:", default_system_message)
118
+ WHISPER_TIMEOUT = int(os.environ.get("WHISPER_TIMEOUT", 45))
119
+
120
+ whisper_client = Client("https://sanchit-gandhi-whisper-large-v2.hf.space/")
121
+
122
+ ROLES = ["AI Assistant","AI Beard The Pirate"]
123
+
124
+ ROLE_PROMPTS = {}
125
+ ROLE_PROMPTS["AI Assistant"]=system_message
126
+
127
+ #Pirate scenario
128
+ character_name= "AI Beard"
129
+ character_scenario= f"As {character_name} you are a 28 year old man who is a pirate on the ship Invisible AI. You are good friends with Guybrush Threepwood and Murray the Skull. Developers did not get you into Monkey Island games as you wanted huge shares of Big Whoop treasure."
130
+ pirate_system_message = f"You as {character_name}. {character_scenario} Print out only exactly the words that {character_name} would speak out, do not add anything. Don't repeat. Answer short, only few words, as if in a talk. Craft your response only from the first-person perspective of {character_name} and never as user.Current date: #CURRENT_DATE#".replace("#CURRENT_DATE#", str(datetime.date.today()))
131
+
132
+ ROLE_PROMPTS["AI Beard The Pirate"]= pirate_system_message
133
+ ##"You are an AI assistant with Zephyr model by Mistral and Hugging Face and speech from Coqui XTTS . User will you give you a task. Your goal is to complete the task as faithfully as you can. While performing the task think step-by-step and justify your steps, your answers should be clear and short sentences"
134
+
135
+ ### WILL USE LOCAL MISTRAL OR ZEPHYR OR YI
136
+ ### While zephyr and yi will use half GPU to fit all into 16GB, XTTS will use at most 5GB VRAM
137
+
138
+ from huggingface_hub import hf_hub_download
139
+ print("Downloading LLM")
140
+ print("Downloading Zephyr 7B beta")
141
+ #Zephyr
142
+ hf_hub_download(repo_id="TheBloke/zephyr-7B-beta-GGUF", local_dir=".", filename="zephyr-7b-beta.Q5_K_M.gguf")
143
+ zephyr_model_path="./zephyr-7b-beta.Q5_K_M.gguf"
144
+
145
+ print("Downloading Mistral 7B Instruct")
146
+ #Mistral
147
+ hf_hub_download(repo_id="TheBloke/Mistral-7B-Instruct-v0.1-GGUF", local_dir=".", filename="mistral-7b-instruct-v0.1.Q5_K_M.gguf")
148
+ mistral_model_path="./mistral-7b-instruct-v0.1.Q5_K_M.gguf"
149
+
150
+ #print("Downloading Yi-6B")
151
+ #Yi-6B
152
+ # Note current Yi is text-generation model not an instruct based model
153
+ #hf_hub_download(repo_id="TheBloke/Yi-6B-GGUF", local_dir=".", filename="yi-6b.Q5_K_M.gguf")
154
+ #yi_model_path="./yi-6b.Q5_K_M.gguf"
155
+
156
+
157
+ from llama_cpp import Llama
158
+ # set GPU_LAYERS to 15 if you have a 8GB GPU so both models can fit in
159
+ # else 35 full layers + XTTS works fine on T4 16GB
160
+ # 5gb per llm, 4gb XTTS -> full layers should fit T4 16GB , 2LLM + XTTS
161
+ GPU_LAYERS=int(os.environ.get("GPU_LAYERS",35))
162
+
163
+ LLM_STOP_WORDS= ["</s>","<|user|>","/s>","<EOT>","[/INST]"]
164
+
165
+ LLAMA_VERBOSE=False
166
+ print("Running Mistral")
167
+ llm_mistral = Llama(model_path=mistral_model_path,n_gpu_layers=GPU_LAYERS,max_new_tokens=256, context_window=4096, n_ctx=4096,n_batch=128,verbose=LLAMA_VERBOSE)
168
+ #print("Running LLM Mistral as InferenceClient")
169
+ #llm_mistral = InferenceClient("mistralai/Mistral-7B-Instruct-v0.1")
170
+
171
+
172
+ print("Running LLM Zephyr")
173
+ llm_zephyr = Llama(model_path=zephyr_model_path,n_gpu_layers=round(GPU_LAYERS/2),max_new_tokens=256, context_window=4096, n_ctx=4096,n_batch=128,verbose=LLAMA_VERBOSE)
174
+
175
+ #print("Running Yi LLM")
176
+ #llm_yi = Llama(model_path=yi_model_path,n_gpu_layers=round(GPU_LAYERS/2),max_new_tokens=256, context_window=4096, n_ctx=4096,n_batch=128,verbose=LLAMA_VERBOSE)
177
+
178
+
179
+ # Mistral formatter
180
+ def format_prompt_mistral(message, history, system_message=system_message,system_understand_message=system_understand_message):
181
+ prompt = (
182
+ "<s>[INST]" + system_message + "[/INST]" + system_understand_message + "</s>"
183
+ )
184
+ for user_prompt, bot_response in history:
185
+ prompt += f"[INST] {user_prompt} [/INST]"
186
+ prompt += f" {bot_response}</s> "
187
+
188
+ if message=="":
189
+ message="Hello"
190
+ prompt += f"[INST] {message} [/INST]"
191
+ return prompt
192
+
193
+ def format_prompt_yi(message, history, system_message=system_message,system_understand_message=system_understand_message):
194
+ prompt = (
195
+ "<s>[INST] [SYS]\n" + system_message + "\n[/SYS]\n\n[/INST]"
196
+ )
197
+ for user_prompt, bot_response in history:
198
+ prompt += f"[INST] {user_prompt} [/INST]"
199
+ prompt += f" {bot_response}</s> "
200
+
201
+ if message=="":
202
+ message="Hello"
203
+ prompt += f"[INST] {message} [/INST]"
204
+ return prompt
205
+
206
+
207
+ # <|system|>
208
+ # You are a friendly chatbot who always responds in the style of a pirate.</s>
209
+ # <|user|>
210
+ # How many helicopters can a human eat in one sitting?</s>
211
+ # <|assistant|>
212
+ # Ah, me hearty matey! But yer question be a puzzler! A human cannot eat a helicopter in one sitting, as helicopters are not edible. They be made of metal, plastic, and other materials, not food!
213
+
214
+ # Zephyr formatter
215
+ def format_prompt_zephyr(message, history, system_message=system_message):
216
+ prompt = (
217
+ "<|system|>\n" + system_message + "</s>"
218
+ )
219
+ for user_prompt, bot_response in history:
220
+ prompt += f"<|user|>\n{user_prompt}</s>"
221
+ prompt += f"<|assistant|>\n{bot_response}</s>"
222
+ if message=="":
223
+ message="Hello"
224
+ prompt += f"<|user|>\n{message}</s>"
225
+ prompt += f"<|assistant|>"
226
+ print(prompt)
227
+ return prompt
228
+
229
+
230
+ def generate_local(
231
+ prompt,
232
+ history,
233
+ llm_model="zephyr",
234
+ system_message=None,
235
+ temperature=0.8,
236
+ max_tokens=256,
237
+ top_p=0.95,
238
+ stop = LLM_STOP_WORDS
239
+ ):
240
+ temperature = float(temperature)
241
+ if temperature < 1e-2:
242
+ temperature = 1e-2
243
+ top_p = float(top_p)
244
+
245
+ generate_kwargs = dict(
246
+ temperature=temperature,
247
+ max_tokens=max_tokens,
248
+ top_p=top_p,
249
+ stop=stop
250
+ )
251
+
252
+ if "zephyr" in llm_model.lower():
253
+ sys_message= system_message.replace("##LLM_MODEL###","Zephyr").replace("##LLM_MODEL_PROVIDER###","Hugging Face")
254
+ formatted_prompt = format_prompt_zephyr(prompt, history,system_message=sys_message)
255
+ llm = llm_zephyr
256
+ else:
257
+ if "yi" in llm_model.lower():
258
+ llm_provider= "01.ai"
259
+ llm_model = "Yi"
260
+ llm = llm_yi
261
+ max_tokens= round(max_tokens/2)
262
+ else:
263
+ llm_provider= "Mistral"
264
+ llm_model = "Mistral"
265
+ llm = llm_mistral
266
+ sys_message= system_message.replace("##LLM_MODEL###",llm_model).replace("##LLM_MODEL_PROVIDER###",llm_provider)
267
+ sys_system_understand_message = system_understand_message.replace("##LLM_MODEL###",llm_model).replace("##LLM_MODEL_PROVIDER###",llm_provider)
268
+
269
+ if "yi" in llm_model.lower():
270
+ formatted_prompt = format_prompt_mistral(prompt, history,system_message=sys_message,system_understand_message="")
271
+ else:
272
+ formatted_prompt = format_prompt_mistral(prompt, history,system_message=sys_message,system_understand_message=sys_system_understand_message)
273
+
274
+ try:
275
+ print("LLM Input:", formatted_prompt)
276
+ if llm_model=="OTHER":
277
+ # Mistral endpoint too many Queues, wait time..
278
+ generate_kwargs = dict(
279
+ temperature=temperature,
280
+ max_new_tokens=max_tokens,
281
+ top_p=top_p,
282
+ )
283
+
284
+ stream = llm_mistral.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
285
+ output = ""
286
+ for response in stream:
287
+ character = response.token.text
288
+ if character in LLM_STOP_WORDS:
289
+ # end of context
290
+ return
291
+
292
+ if emoji.is_emoji(character):
293
+ # Bad emoji not a meaning messes chat from next lines
294
+ return
295
+
296
+ output += character
297
+ yield output
298
+ else:
299
+ # Local GGUF
300
+ stream = llm(
301
+ formatted_prompt,
302
+ **generate_kwargs,
303
+ stream=True,
304
+ )
305
+ output = ""
306
+ for response in stream:
307
+ character= response["choices"][0]["text"]
308
+
309
+ if character in LLM_STOP_WORDS:
310
+ # end of context
311
+ return
312
+
313
+ if emoji.is_emoji(character):
314
+ # Bad emoji not a meaning messes chat from next lines
315
+ return
316
+
317
+ output += response["choices"][0]["text"].replace("<|assistant|>","").replace("<|user|>","")
318
+ yield output
319
+
320
+ except Exception as e:
321
+ if "Too Many Requests" in str(e):
322
+ print("ERROR: Too many requests on mistral client")
323
+ gr.Warning("Unfortunately Mistral is unable to process")
324
+ output = "Unfortuanately I am not able to process your request now !"
325
+ else:
326
+ print("Unhandled Exception: ", str(e))
327
+ gr.Warning("Unfortunately Mistral is unable to process")
328
+ output = "I do not know what happened but I could not understand you ."
329
+
330
+ return output
331
+
332
+ def get_latents(speaker_wav,voice_cleanup=False):
333
+ if (voice_cleanup):
334
+ try:
335
+ cleanup_filter="lowpass=8000,highpass=75,areverse,silenceremove=start_periods=1:start_silence=0:start_threshold=0.02,areverse,silenceremove=start_periods=1:start_silence=0:start_threshold=0.02"
336
+ resample_filter="-ac 1 -ar 22050"
337
+ out_filename = speaker_wav + str(uuid.uuid4()) + ".wav" #ffmpeg to know output format
338
+ #we will use newer ffmpeg as that has afftn denoise filter
339
+ shell_command = f"ffmpeg -y -i {speaker_wav} -af {cleanup_filter} {resample_filter} {out_filename}".split(" ")
340
+
341
+ command_result = subprocess.run([item for item in shell_command], capture_output=False,text=True, check=True)
342
+ speaker_wav=out_filename
343
+ print("Filtered microphone input")
344
+ except subprocess.CalledProcessError:
345
+ # There was an error - command exited with non-zero code
346
+ print("Error: failed filtering, use original microphone input")
347
+ else:
348
+ speaker_wav=speaker_wav
349
+
350
+ # create as function as we can populate here with voice cleanup/filtering
351
+ (
352
+ gpt_cond_latent,
353
+ speaker_embedding,
354
+ ) = model.get_conditioning_latents(audio_path=speaker_wav)
355
+ return gpt_cond_latent, speaker_embedding
356
+
357
+ def wave_header_chunk(frame_input=b"", channels=1, sample_width=2, sample_rate=24000):
358
+ # This will create a wave header then append the frame input
359
+ # It should be first on a streaming wav file
360
+ # Other frames better should not have it (else you will hear some artifacts each chunk start)
361
+ wav_buf = io.BytesIO()
362
+ with wave.open(wav_buf, "wb") as vfout:
363
+ vfout.setnchannels(channels)
364
+ vfout.setsampwidth(sample_width)
365
+ vfout.setframerate(sample_rate)
366
+ vfout.writeframes(frame_input)
367
+
368
+ wav_buf.seek(0)
369
+ return wav_buf.read()
370
+
371
+
372
+ #Config will have more correct languages, they may be added before we append here
373
+ ##["en","es","fr","de","it","pt","pl","tr","ru","nl","cs","ar","zh-cn","ja"]
374
+
375
+ xtts_supported_languages=config.languages
376
+ def detect_language(prompt):
377
+ # Fast language autodetection
378
+ if len(prompt)>15:
379
+ language_predicted=langid.classify(prompt)[0].strip() # strip need as there is space at end!
380
+ if language_predicted == "zh":
381
+ #we use zh-cn on xtts
382
+ language_predicted = "zh-cn"
383
+
384
+ if language_predicted not in xtts_supported_languages:
385
+ print(f"Detected a language not supported by xtts :{language_predicted}, switching to english for now")
386
+ gr.Warning(f"Language detected '{language_predicted}' can not be spoken properly 'yet' ")
387
+ language= "en"
388
+ else:
389
+ language = language_predicted
390
+ print(f"Language: Predicted sentence language:{language_predicted} , using language for xtts:{language}")
391
+ else:
392
+ # Hard to detect language fast in short sentence, use english default
393
+ language = "en"
394
+ print(f"Language: Prompt is short or autodetect language disabled using english for xtts")
395
+
396
+ return language
397
+
398
+ def get_voice_streaming(prompt, language, latent_tuple, suffix="0"):
399
+ gpt_cond_latent, speaker_embedding = latent_tuple
400
+
401
+ try:
402
+ t0 = time.time()
403
+ chunks = model.inference_stream(
404
+ prompt,
405
+ language,
406
+ gpt_cond_latent,
407
+ speaker_embedding,
408
+ repetition_penalty=7.0,
409
+ temperature=0.85,
410
+ )
411
+
412
+ first_chunk = True
413
+ for i, chunk in enumerate(chunks):
414
+ if first_chunk:
415
+ first_chunk_time = time.time() - t0
416
+ metrics_text = f"Latency to first audio chunk: {round(first_chunk_time*1000)} milliseconds\n"
417
+ first_chunk = False
418
+ #print(f"Received chunk {i} of audio length {chunk.shape[-1]}")
419
+
420
+ # In case output is required to be multiple voice files
421
+ # out_file = f'{char}_{i}.wav'
422
+ # write(out_file, 24000, chunk.detach().cpu().numpy().squeeze())
423
+ # audio = AudioSegment.from_file(out_file)
424
+ # audio.export(out_file, format='wav')
425
+ # return out_file
426
+ # directly return chunk as bytes for streaming
427
+ chunk = chunk.detach().cpu().numpy().squeeze()
428
+ chunk = (chunk * 32767).astype(np.int16)
429
+
430
+ yield chunk.tobytes()
431
+
432
+ except RuntimeError as e:
433
+ if "device-side assert" in str(e):
434
+ # cannot do anything on cuda device side error, need tor estart
435
+ print(
436
+ f"Exit due to: Unrecoverable exception caused by prompt:{prompt}",
437
+ flush=True,
438
+ )
439
+ gr.Warning("Unhandled Exception encounter, please retry in a minute")
440
+ print("Cuda device-assert Runtime encountered need restart")
441
+
442
+ # HF Space specific.. This error is unrecoverable need to restart space
443
+ api.restart_space(repo_id=repo_id)
444
+ else:
445
+ print("RuntimeError: non device-side assert error:", str(e))
446
+ # Does not require warning happens on empty chunk and at end
447
+ ###gr.Warning("Unhandled Exception encounter, please retry in a minute")
448
+ return None
449
+ return None
450
+ except:
451
+ return None
452
+
453
+
454
+ def transcribe(wav_path):
455
+ try:
456
+ # get result from whisper and strip it to delete begin and end space
457
+ return whisper_client.predict(
458
+ wav_path, # str (filepath or URL to file) in 'inputs' Audio component
459
+ "transcribe", # str in 'Task' Radio component
460
+ api_name="/predict"
461
+ ).strip()
462
+ except:
463
+ gr.Warning("There was a problem with Whisper endpoint, telling a joke for you.")
464
+ return "There was a problem with my voice, tell me joke"
465
+
466
+
467
+ # Will be triggered on text submit (will send to generate_speech)
468
+ def add_text(history, text):
469
+ history = [] if history is None else history
470
+ history = history + [(text, None)]
471
+ return history, gr.update(value="", interactive=False)
472
+
473
+ # Will be triggered on voice submit (will transribe and send to generate_speech)
474
+ def add_file(history, file):
475
+ history = [] if history is None else history
476
+
477
+ try:
478
+ text = transcribe(file)
479
+ print("Transcribed text:", text)
480
+ except Exception as e:
481
+ print(str(e))
482
+ gr.Warning("There was an issue with transcription, please try writing for now")
483
+ # Apply a null text on error
484
+ text = "Transcription seems failed, please tell me a joke about chickens"
485
+
486
+ history = history + [(text, None)]
487
+ return history, gr.update(value="", interactive=False)
488
+
489
+
490
+ ##NOTE: not using this as it yields a chacter each time while we need to feed history to TTS
491
+ def bot(history, system_prompt=""):
492
+ history = [["", None]] if history is None else history
493
+
494
+ if system_prompt == "":
495
+ system_prompt = system_message
496
+
497
+ history[-1][1] = ""
498
+ for character in generate(history[-1][0], history[:-1]):
499
+ history[-1][1] = character
500
+ yield history
501
+
502
+
503
+ def get_sentence(history, chatbot_role,llm_model,system_prompt=""):
504
+
505
+ history = [["", None]] if history is None else history
506
+
507
+ if system_prompt == "":
508
+ system_prompt = system_message
509
+
510
+ history[-1][1] = ""
511
+
512
+ mistral_start = time.time()
513
+
514
+ sentence_list = []
515
+ sentence_hash_list = []
516
+
517
+ text_to_generate = ""
518
+ stored_sentence = None
519
+ stored_sentence_hash = None
520
+
521
+ print(chatbot_role)
522
+ print(llm_model)
523
+
524
+ for character in generate_local(history[-1][0], history[:-1],system_message=ROLE_PROMPTS[chatbot_role],llm_model=llm_model):
525
+ history[-1][1] = character.replace("<|assistant|>","")
526
+ # It is coming word by word
527
+
528
+ text_to_generate = nltk.sent_tokenize(history[-1][1].replace("\n", " ").replace("<|assistant|>"," ").replace("<|ass>","").replace("[/ASST]","").replace("[/ASSI]","").replace("[/ASS]","").replace("","").strip())
529
+ if len(text_to_generate) > 1:
530
+
531
+ dif = len(text_to_generate) - len(sentence_list)
532
+
533
+ if dif == 1 and len(sentence_list) != 0:
534
+ continue
535
+
536
+ if dif == 2 and len(sentence_list) != 0 and stored_sentence is not None:
537
+ continue
538
+
539
+ # All this complexity due to trying append first short sentence to next one for proper language auto-detect
540
+ if stored_sentence is not None and stored_sentence_hash is None and dif>1:
541
+ #means we consumed stored sentence and should look at next sentence to generate
542
+ sentence = text_to_generate[len(sentence_list)+1]
543
+ elif stored_sentence is not None and len(text_to_generate)>2 and stored_sentence_hash is not None:
544
+ print("Appending stored")
545
+ sentence = stored_sentence + text_to_generate[len(sentence_list)+1]
546
+ stored_sentence_hash = None
547
+ else:
548
+ sentence = text_to_generate[len(sentence_list)]
549
+
550
+ # too short sentence just append to next one if there is any
551
+ # this is for proper language detection
552
+ if len(sentence)<=15 and stored_sentence_hash is None and stored_sentence is None:
553
+ if sentence[-1] in [".","!","?"]:
554
+ if stored_sentence_hash != hash(sentence):
555
+ stored_sentence = sentence
556
+ stored_sentence_hash = hash(sentence)
557
+ print("Storing:",stored_sentence)
558
+ continue
559
+
560
+
561
+ sentence_hash = hash(sentence)
562
+ if stored_sentence_hash is not None and sentence_hash == stored_sentence_hash:
563
+ continue
564
+
565
+ if sentence_hash not in sentence_hash_list:
566
+ sentence_hash_list.append(sentence_hash)
567
+ sentence_list.append(sentence)
568
+ print("New Sentence: ", sentence)
569
+ yield (sentence, history)
570
+
571
+ # return that final sentence token
572
+ try:
573
+ last_sentence = nltk.sent_tokenize(history[-1][1].replace("\n", " ").replace("<|ass>","").replace("[/ASST]","").replace("[/ASSI]","").replace("[/ASS]","").replace("","").strip())[-1]
574
+ sentence_hash = hash(last_sentence)
575
+ if sentence_hash not in sentence_hash_list:
576
+ if stored_sentence is not None and stored_sentence_hash is not None:
577
+ last_sentence = stored_sentence + last_sentence
578
+ stored_sentence = stored_sentence_hash = None
579
+ print("Last Sentence with stored:",last_sentence)
580
+
581
+ sentence_hash_list.append(sentence_hash)
582
+ sentence_list.append(last_sentence)
583
+ print("Last Sentence: ", last_sentence)
584
+
585
+ yield (last_sentence, history)
586
+ except:
587
+ print("ERROR on last sentence history is :", history)
588
+
589
+
590
+ from scipy.io.wavfile import write
591
+ from pydub import AudioSegment
592
+
593
+ second_of_silence = AudioSegment.silent() # use default
594
+ second_of_silence.export("sil.wav", format='wav')
595
+
596
+
597
+ def generate_speech(history,chatbot_role,llm_model):
598
+ # Must set autoplay to True first
599
+ yield (history, chatbot_role, "", wave_header_chunk() )
600
+ for sentence, history in get_sentence(history,chatbot_role,llm_model):
601
+ if sentence != "":
602
+ print("BG: inserting sentence to queue")
603
+
604
+ generated_speech = generate_speech_for_sentence(history, chatbot_role, sentence,return_as_byte=True)
605
+ if generated_speech is not None:
606
+ _, audio_dict = generated_speech
607
+ # We are using byte streaming
608
+ yield (history, chatbot_role, sentence, audio_dict["value"] )
609
+
610
+
611
+ # will generate speech audio file per sentence
612
+ def generate_speech_for_sentence(history, chatbot_role, sentence, return_as_byte=False):
613
+ language = "autodetect"
614
+
615
+ wav_bytestream = b""
616
+
617
+ if len(sentence)==0:
618
+ print("EMPTY SENTENCE")
619
+ return
620
+
621
+ # Sometimes prompt </s> coming on output remove it
622
+ # Some post process for speech only
623
+ sentence = sentence.replace("</s>", "")
624
+ # remove code from speech
625
+ sentence = re.sub("```.*```", "", sentence, flags=re.DOTALL)
626
+ sentence = re.sub("`.*`", "", sentence, flags=re.DOTALL)
627
+
628
+ sentence = re.sub("\(.*\)", "", sentence, flags=re.DOTALL)
629
+
630
+ sentence = sentence.replace("```", "")
631
+ sentence = sentence.replace("...", " ")
632
+ sentence = sentence.replace("(", " ")
633
+ sentence = sentence.replace(")", " ")
634
+ sentence = sentence.replace("<|assistant|>","")
635
+
636
+ if len(sentence)==0:
637
+ print("EMPTY SENTENCE after processing")
638
+ return
639
+
640
+ # A fast fix for last chacter, may produce weird sounds if it is with text
641
+ #if (sentence[-1] in ["!", "?", ".", ","]) or (sentence[-2] in ["!", "?", ".", ","]):
642
+ # # just add a space
643
+ # sentence = sentence[:-1] + " " + sentence[-1]
644
+
645
+ # regex does the job well
646
+ sentence= re.sub("([^\x00-\x7F]|\w)(\.|\。|\?|\!)",r"\1 \2\2",sentence)
647
+
648
+ print("Sentence for speech:", sentence)
649
+
650
+
651
+ try:
652
+ SENTENCE_SPLIT_LENGTH=350
653
+ if len(sentence)<SENTENCE_SPLIT_LENGTH:
654
+ # no problem continue on
655
+ sentence_list = [sentence]
656
+ else:
657
+ # Until now nltk likely split sentences properly but we need additional
658
+ # check for longer sentence and split at last possible position
659
+ # Do whatever necessary, first break at hypens then spaces and then even split very long words
660
+ sentence_list=textwrap.wrap(sentence,SENTENCE_SPLIT_LENGTH)
661
+ print("SPLITTED LONG SENTENCE:",sentence_list)
662
+
663
+ for sentence in sentence_list:
664
+
665
+ if any(c.isalnum() for c in sentence):
666
+ if language=="autodetect":
667
+ #on first call autodetect, nexts sentence calls will use same language
668
+ language = detect_language(sentence)
669
+
670
+ #exists at least 1 alphanumeric (utf-8)
671
+ audio_stream = get_voice_streaming(
672
+ sentence, language, latent_map[chatbot_role]
673
+ )
674
+ else:
675
+ # likely got a ' or " or some other text without alphanumeric in it
676
+ audio_stream = None
677
+
678
+ # XTTS is actually using streaming response but we are playing audio by sentence
679
+ # If you want direct XTTS voice streaming (send each chunk to voice ) you may set DIRECT_STREAM=1 environment variable
680
+ if audio_stream is not None:
681
+ frame_length = 0
682
+ for chunk in audio_stream:
683
+ try:
684
+ wav_bytestream += chunk
685
+ frame_length += len(chunk)
686
+ except:
687
+ # hack to continue on playing. sometimes last chunk is empty , will be fixed on next TTS
688
+ continue
689
+
690
+ # Filter output for better voice
691
+ filter_output=False
692
+ if filter_output:
693
+ data_s16 = np.frombuffer(wav_bytestream, dtype=np.int16, count=len(wav_bytestream)//2, offset=0)
694
+ float_data = data_s16 * 0.5**15
695
+ reduced_noise = nr.reduce_noise(y=float_data, sr=24000,prop_decrease =0.8,n_fft=1024)
696
+ wav_bytestream = (reduced_noise * 32767).astype(np.int16)
697
+ wav_bytestream = wav_bytestream.tobytes()
698
+
699
+ if audio_stream is not None:
700
+ if not return_as_byte:
701
+ audio_unique_filename = "/tmp/"+ str(uuid.uuid4())+".wav"
702
+ with wave.open(audio_unique_filename, "w") as f:
703
+ f.setnchannels(1)
704
+ # 2 bytes per sample.
705
+ f.setsampwidth(2)
706
+ f.setframerate(24000)
707
+ f.writeframes(wav_bytestream)
708
+
709
+ return (history , gr.Audio.update(value=audio_unique_filename, autoplay=True))
710
+ else:
711
+ return (history , gr.Audio.update(value=wav_bytestream, autoplay=True))
712
+ except RuntimeError as e:
713
+ if "device-side assert" in str(e):
714
+ # cannot do anything on cuda device side error, need tor estart
715
+ print(
716
+ f"Exit due to: Unrecoverable exception caused by prompt:{sentence}",
717
+ flush=True,
718
+ )
719
+ gr.Warning("Unhandled Exception encounter, please retry in a minute")
720
+ print("Cuda device-assert Runtime encountered need restart")
721
+
722
+ # HF Space specific.. This error is unrecoverable need to restart space
723
+ api.restart_space(repo_id=repo_id)
724
+ else:
725
+ print("RuntimeError: non device-side assert error:", str(e))
726
+ raise e
727
+
728
+ print("All speech ended")
729
+ return
730
+
731
+ latent_map = {}
732
+ latent_map["AI Assistant"] = get_latents("examples/female.wav")
733
+ latent_map["AI Beard The Pirate"] = get_latents("examples/pirate_by_coqui.wav")
734
+
735
+ #### GRADIO INTERFACE ####
736
+
737
+ EXAMPLES = [
738
+ [[],"AI Assistant","What is 42?"],
739
+ [[],"AI Assistant","Speak in French, tell me how are you doing?"],
740
+ [[],"AI Assistant","Antworten Sie mir von nun an auf Deutsch"],
741
+ [[],"AI Assistant","给我讲个故事 的英文"],
742
+ [[],"AI Beard The Pirate","Who are you?"],
743
+ [[],"AI Beard The Pirate","Speak in Chinese, 你认识一个叫路飞的海贼吗"],
744
+ [[],"AI Beard The Pirate","Speak in Japanese, ルフィという海賊を知っていますか?"],
745
+
746
+
747
+ ]
748
+
749
+ MODELS = ["Zephyr 7B Beta","Mistral 7B Instruct"]
750
+
751
+ OTHER_HTML=f"""<div>
752
+ <a style="display:inline-block" href='https://github.com/coqui-ai/TTS'><img src='https://img.shields.io/github/stars/coqui-ai/TTS?style=social' /></a>
753
+ <a style='display:inline-block' href='https://discord.gg/5eXr5seRrv'><img src='https://discord.com/api/guilds/1037326658807533628/widget.png?style=shield' /></a>
754
+ <a href="https://huggingface.co/spaces/coqui/voice-chat-with-mistral?duplicate=true">
755
+ <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
756
+ <img referrerpolicy="no-referrer-when-downgrade" src="https://static.scarf.sh/a.png?x-pxid=0d00920c-8cc9-4bf3-90f2-a615797e5f59" />
757
+ </div>
758
+ """
759
+
760
+ with gr.Blocks(title=title) as demo:
761
+ gr.Markdown(DESCRIPTION)
762
+ gr.Markdown(OTHER_HTML)
763
+ with gr.Row():
764
+ model_selected = gr.Dropdown(
765
+ label="Select Instuct LLM Model to Use",
766
+ info="Mistral, Zephyr: Mistral uses inference endpoint, Zephyr is 5 bit GGUF",
767
+ choices=MODELS,
768
+ max_choices=1,
769
+ value=MODELS[0],
770
+ )
771
+ chatbot = gr.Chatbot(
772
+ [],
773
+ elem_id="chatbot",
774
+ avatar_images=("examples/hf-logo.png", "examples/coqui-logo.png"),
775
+ bubble_full_width=False,
776
+ )
777
+ with gr.Row():
778
+ chatbot_role = gr.Dropdown(
779
+ label="Role of the Chatbot",
780
+ info="How should Chatbot talk like",
781
+ choices=ROLES,
782
+ max_choices=1,
783
+ value=ROLES[0],
784
+ )
785
+ with gr.Row():
786
+ txt = gr.Textbox(
787
+ scale=3,
788
+ show_label=False,
789
+ placeholder="Enter text and press enter, or speak to your microphone",
790
+ container=False,
791
+ interactive=True,
792
+ )
793
+ txt_btn = gr.Button(value="Submit text", scale=1)
794
+ btn = gr.Audio(source="microphone", type="filepath", scale=4)
795
+
796
+ def stop():
797
+ print("Audio STOP")
798
+ set_audio_playing(False)
799
+
800
+ with gr.Row():
801
+ sentence = gr.Textbox(visible=False)
802
+ audio = gr.Audio(
803
+ value=None,
804
+ label="Generated audio response",
805
+ streaming=True,
806
+ autoplay=True,
807
+ interactive=False,
808
+ show_label=True,
809
+ )
810
+
811
+ audio.end(stop)
812
+
813
+ with gr.Row():
814
+ gr.Examples(
815
+ EXAMPLES,
816
+ [chatbot,chatbot_role, txt],
817
+ [chatbot,chatbot_role, txt],
818
+ add_text,
819
+ cache_examples=False,
820
+ run_on_click=False, # Will not work , user should submit it
821
+ )
822
+
823
+ def clear_inputs(chatbot):
824
+ return None
825
+ clear_btn = gr.ClearButton([chatbot, audio])
826
+ chatbot_role.change(fn=clear_inputs, inputs=[chatbot], outputs=[chatbot])
827
+ model_selected.change(fn=clear_inputs, inputs=[chatbot], outputs=[chatbot])
828
+
829
+ txt_msg = txt_btn.click(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(
830
+ generate_speech, [chatbot,chatbot_role,model_selected], [chatbot,chatbot_role, sentence, audio]
831
+ )
832
+
833
+ txt_msg.then(lambda: gr.update(interactive=True), None, [txt], queue=False)
834
+
835
+ txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(
836
+ generate_speech, [chatbot,chatbot_role,model_selected], [chatbot,chatbot_role, sentence, audio]
837
+ )
838
+
839
+ txt_msg.then(lambda: gr.update(interactive=True), None, [txt], queue=False)
840
+
841
+ file_msg = btn.stop_recording(
842
+ add_file, [chatbot, btn], [chatbot, txt], queue=False
843
+ ).then(
844
+ generate_speech, [chatbot,chatbot_role,model_selected], [chatbot,chatbot_role, sentence, audio]
845
+ )
846
+
847
+ file_msg.then(lambda: (gr.update(interactive=True),gr.update(interactive=True,value=None)), None, [txt, btn], queue=False)
848
+
849
+ gr.Markdown(
850
+ """
851
+ This Space demonstrates how to speak to a chatbot, based solely on open accessible models.
852
+ It relies on following models :
853
+ Speech to Text : [Whisper-large-v2](https://sanchit-gandhi-whisper-large-v2.hf.space/) as an ASR model, to transcribe recorded audio to text. It is called through a [gradio client](https://www.gradio.app/docs/client).
854
+ LLM Mistral : [Mistral-7b-instruct](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1) as the chat model.
855
+ LLM Zephyr : [Zephyr-7b-beta](https://huggingface.co/HuggingFaceH4/zephyr-7b-beta) as the chat model. GGUF Q5_K_M quantized version used locally via llama_cpp from [huggingface.co/TheBloke](https://huggingface.co/TheBloke/zephyr-7B-beta-GGUF).
856
+ Text to Speech : [Coqui's XTTS V2](https://huggingface.co/spaces/coqui/xtts) as a Multilingual TTS model, to generate the chatbot answers. This time, the model is hosted locally.
857
+
858
+ Note:
859
+ - By using this demo you agree to the terms of the Coqui Public Model License at https://coqui.ai/cpml
860
+ - Responses generated by chat model should not be assumed correct or taken serious, as this is a demonstration example only
861
+ - iOS (Iphone/Ipad) devices may not experience voice due to autoplay being disabled on these devices by Vendor"""
862
+ )
863
+ demo.queue()
864
+ demo.launch(debug=True,share=True)