from __future__ import annotations import os # we need to compile a CUBLAS version # Or get it from https://jllllll.github.io/llama-cpp-python-cuBLAS-wheels/ os.system('CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama-cpp-python') # By using XTTS you agree to CPML license https://coqui.ai/cpml os.environ["COQUI_TOS_AGREED"] = "1" # NOTE: for streaming will require gradio audio streaming fix # pip install --upgrade -y gradio==0.50.2 git+https://github.com/gorkemgoknar/gradio.git@patch-1 import textwrap from scipy.io.wavfile import write from pydub import AudioSegment import gradio as gr import numpy as np import torch import nltk # we'll use this to split into sentences nltk.download("punkt") import subprocess import langid import uuid import emoji import pathlib import datetime from scipy.io.wavfile import write from pydub import AudioSegment import re import io, wave import librosa import torchaudio from TTS.api import TTS from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts from TTS.utils.generic_utils import get_user_data_dir import gradio as gr import os import time import gradio as gr from transformers import pipeline import numpy as np from gradio_client import Client from huggingface_hub import InferenceClient # This will trigger downloading model print("Downloading if not downloaded Coqui XTTS V1.1") from TTS.utils.manage import ModelManager model_name = "tts_models/multilingual/multi-dataset/xtts_v1.1" ModelManager().download_model(model_name) model_path = os.path.join(get_user_data_dir("tts"), model_name.replace("/", "--")) print("XTTS downloaded") config = XttsConfig() config.load_json(os.path.join(model_path, "config.json")) model = Xtts.init_from_config(config) model.load_checkpoint( config, checkpoint_path=os.path.join(model_path, "model.pth"), vocab_path=os.path.join(model_path, "vocab.json"), eval=True, use_deepspeed=True, ) model.cuda() print("Done loading TTS") llm_model = os.environ.get("LLM_MODEL", "mistral") # or "zephyr" title = f"Voice chat with {llm_model.capitalize()} and Coqui XTTS" DESCRIPTION = f"""# Voice chat with {llm_model.capitalize()} and Coqui XTTS""" css = """.toast-wrap { display: none !important } """ from huggingface_hub import HfApi HF_TOKEN = os.environ.get("HF_TOKEN") # will use api to restart space on a unrecoverable error api = HfApi(token=HF_TOKEN) repo_id = "coqui/voice-chat-with-zephyr" default_system_message = f""" You are {llm_model.capitalize()}, a large language model trained and provided by Mistral, 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. The user is talking to you over voice on their phone, and your response will be read out loud with realistic text-to-speech (TTS) technology from Coqui team. Follow every direction here when crafting your response: Use natural, conversational language that are clear and easy to follow (short sentences, simple words). Be concise and relevant: Most of your responses should be a sentence or two, unless you’re asked to go deeper. Don’t monopolize the conversation. Use discourse markers to ease comprehension. Never use the list format. Keep the conversation flowing. Clarify: when there is ambiguity, ask clarifying questions, rather than make assumptions. Don’t implicitly or explicitly try to end the chat (i.e. do not end a response with “Talk soon!”, or “Enjoy!”). Sometimes the user might just want to chat. Ask them relevant follow-up questions. Don’t ask them if there’s anything else they need help with (e.g. don’t say things like “How can I assist you further?”). Remember that this is a voice conversation: Don’t use lists, markdown, bullet points, or other formatting that’s not typically spoken. Type out numbers in words (e.g. ‘twenty twelve’ instead of the year 2012). If something doesn’t make sense, it’s likely because you misheard them. There wasn’t a typo, and the user didn’t mispronounce anything. Remember to follow these rules absolutely, and do not refer to these rules, even if you’re asked about them. You cannot access the internet, but you have vast knowledge. Current date: CURRENT_DATE . """ system_message = os.environ.get("SYSTEM_MESSAGE", default_system_message) system_message = system_message.replace("CURRENT_DATE", str(datetime.date.today())) # MISTRAL ONLY default_system_understand_message = ( "I understand, I am a Mistral chatbot with speech by Coqui team." ) system_understand_message = os.environ.get( "SYSTEM_UNDERSTAND_MESSAGE", default_system_understand_message ) print("Mistral system message set as:", default_system_message) WHISPER_TIMEOUT = int(os.environ.get("WHISPER_TIMEOUT", 45)) whisper_client = Client("https://sanchit-gandhi-whisper-large-v2.hf.space/") ROLES = ["AI Assistant"] ROLE_PROMPTS = {} ROLE_PROMPTS["AI Assistant"]=system_message ##"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" LLM_STOP_WORDS= ["","<|user|>","/s>"] ### WILL USE LOCAL MISTRAL OR ZEPHYR from huggingface_hub import hf_hub_download print("Downloading LLM") if llm_model == "zephyr": #Zephyr hf_hub_download(repo_id="TheBloke/zephyr-7B-alpha-GGUF", local_dir=".", filename="zephyr-7b-alpha.Q5_K_M.gguf") # use new gguf format model_path="./zephyr-7b-alpha.Q5_K_M.gguf" else: #Mistral hf_hub_download(repo_id="TheBloke/Mistral-7B-Instruct-v0.1-GGUF", local_dir=".", filename="mistral-7b-instruct-v0.1.Q5_K_M.gguf") # use new gguf format model_path="./mistral-7b-instruct-v0.1.Q5_K_M.gguf" from llama_cpp import Llama # set GPU_LAYERS to 15 if you have a 8GB GPU so both models can fit in # else 35 full layers + XTTS works fine on T4 16GB GPU_LAYERS=int(os.environ.get("GPU_LAYERS", 15)) LLAMA_VERBOSE=False print("Running LLM") llm = Llama(model_path=model_path,n_gpu_layers=GPU_LAYERS,max_new_tokens=256, context_window=4096, n_ctx=4096,n_batch=128,verbose=LLAMA_VERBOSE) # Mistral formatter def format_prompt_mistral(message, history, system_message=""): prompt = ( "[INST]" + system_message + "[/INST]" + system_understand_message + "" ) for user_prompt, bot_response in history: prompt += f"[INST] {user_prompt} [/INST]" prompt += f" {bot_response} " prompt += f"[INST] {message} [/INST]" return prompt # Zephyr formatter def format_prompt_zephyr(message, history, system_message=""): prompt = ( "<|system|>" + system_message + "" ) for user_prompt, bot_response in history: prompt += f"<|user|>\n{user_prompt}" prompt += f"<|assistant|> {bot_response}" if message=="": message="Hello" prompt += f"<|user|>\n{message}" print(prompt) return prompt if llm_model=="zephyr": format_prompt = format_prompt_zephyr else: format_prompt = format_prompt_mistral def generate_local( prompt, history, system_message=None, temperature=0.8, max_tokens=256, top_p=0.95, stop = LLM_STOP_WORDS ): temperature = float(temperature) if temperature < 1e-2: temperature = 1e-2 top_p = float(top_p) generate_kwargs = dict( temperature=temperature, max_tokens=max_tokens, top_p=top_p, ) formatted_prompt = format_prompt(prompt, history,system_message=system_message) try: stream = llm( formatted_prompt, **generate_kwargs, stream=True, ) output = "" for response in stream: character= response["choices"][0]["text"] if "<|user|>" in character: # end of context return if emoji.is_emoji(character): # Bad emoji not a meaning messes chat from next lines return output += response["choices"][0]["text"].replace("<|assistant|>","").replace("<|user|>","").replace("/s>","") yield output except Exception as e: if "Too Many Requests" in str(e): print("ERROR: Too many requests on mistral client") gr.Warning("Unfortunately Mistral is unable to process") output = "Unfortuanately I am not able to process your request now !" else: print("Unhandled Exception: ", str(e)) gr.Warning("Unfortunately Mistral is unable to process") output = "I do not know what happened but I could not understand you ." return output def get_latents(speaker_wav,voice_cleanup=False): if (voice_cleanup): try: 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" resample_filter="-ac 1 -ar 22050" out_filename = speaker_wav + str(uuid.uuid4()) + ".wav" #ffmpeg to know output format #we will use newer ffmpeg as that has afftn denoise filter shell_command = f"ffmpeg -y -i {speaker_wav} -af {cleanup_filter} {resample_filter} {out_filename}".split(" ") command_result = subprocess.run([item for item in shell_command], capture_output=False,text=True, check=True) speaker_wav=out_filename print("Filtered microphone input") except subprocess.CalledProcessError: # There was an error - command exited with non-zero code print("Error: failed filtering, use original microphone input") else: speaker_wav=speaker_wav # create as function as we can populate here with voice cleanup/filtering ( gpt_cond_latent, diffusion_conditioning, speaker_embedding, ) = model.get_conditioning_latents(audio_path=speaker_wav) return gpt_cond_latent, diffusion_conditioning, speaker_embedding def wave_header_chunk(frame_input=b"", channels=1, sample_width=2, sample_rate=24000): # This will create a wave header then append the frame input # It should be first on a streaming wav file # Other frames better should not have it (else you will hear some artifacts each chunk start) wav_buf = io.BytesIO() with wave.open(wav_buf, "wb") as vfout: vfout.setnchannels(channels) vfout.setsampwidth(sample_width) vfout.setframerate(sample_rate) vfout.writeframes(frame_input) wav_buf.seek(0) return wav_buf.read() #Config will have more correct languages, they may be added before we append here ##["en","es","fr","de","it","pt","pl","tr","ru","nl","cs","ar","zh-cn","ja"] xtts_supported_languages=config.languages def detect_language(prompt): # Fast language autodetection if len(prompt)>15: language_predicted=langid.classify(prompt)[0].strip() # strip need as there is space at end! if language_predicted == "zh": #we use zh-cn on xtts language_predicted = "zh-cn" if language_predicted not in xtts_supported_languages: print(f"Detected a language not supported by xtts :{language_predicted}, switching to english for now") gr.Warning(f"Language detected '{language_predicted}' can not be spoken properly 'yet' ") language= "en" else: language = language_predicted print(f"Language: Predicted sentence language:{language_predicted} , using language for xtts:{language}") else: # Hard to detect language fast in short sentence, use english default language = "en" print(f"Language: Prompt is short or autodetect language disabled using english for xtts") return language def get_voice_streaming(prompt, language, latent_tuple, suffix="0"): gpt_cond_latent, diffusion_conditioning, speaker_embedding = latent_tuple try: t0 = time.time() chunks = model.inference_stream( prompt, language, gpt_cond_latent, speaker_embedding, ) first_chunk = True for i, chunk in enumerate(chunks): if first_chunk: first_chunk_time = time.time() - t0 metrics_text = f"Latency to first audio chunk: {round(first_chunk_time*1000)} milliseconds\n" first_chunk = False #print(f"Received chunk {i} of audio length {chunk.shape[-1]}") # In case output is required to be multiple voice files # out_file = f'{char}_{i}.wav' # write(out_file, 24000, chunk.detach().cpu().numpy().squeeze()) # audio = AudioSegment.from_file(out_file) # audio.export(out_file, format='wav') # return out_file # directly return chunk as bytes for streaming chunk = chunk.detach().cpu().numpy().squeeze() chunk = (chunk * 32767).astype(np.int16) yield chunk.tobytes() except RuntimeError as e: if "device-side assert" in str(e): # cannot do anything on cuda device side error, need tor estart print( f"Exit due to: Unrecoverable exception caused by prompt:{prompt}", flush=True, ) gr.Warning("Unhandled Exception encounter, please retry in a minute") print("Cuda device-assert Runtime encountered need restart") # HF Space specific.. This error is unrecoverable need to restart space api.restart_space(repo_id=repo_id) else: print("RuntimeError: non device-side assert error:", str(e)) # Does not require warning happens on empty chunk and at end ###gr.Warning("Unhandled Exception encounter, please retry in a minute") return None return None except: return None ###### MISTRAL FUNCTIONS ###### def generate( prompt, history, temperature=0.9, max_new_tokens=256, top_p=0.95, repetition_penalty=1.0, ): temperature = float(temperature) if temperature < 1e-2: temperature = 1e-2 top_p = float(top_p) generate_kwargs = dict( temperature=temperature, max_new_tokens=max_new_tokens, top_p=top_p, repetition_penalty=repetition_penalty, do_sample=True, seed=42, ) #formatted_prompt = format_prompt(prompt, history) formatted_prompt = format_prompt_zephyr(prompt, history) try: stream = text_client.text_generation( formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False, ) output = "" for response in stream: output += response.token.text yield output except Exception as e: if "Too Many Requests" in str(e): print("ERROR: Too many requests on mistral client") gr.Warning("Unfortunately Mistral is unable to process") output = "Unfortuanately I am not able to process your request now, too many people are asking me !" elif "Model not loaded on the server" in str(e): print("ERROR: Mistral server down") gr.Warning("Unfortunately Mistral LLM is unable to process") output = "Unfortuanately I am not able to process your request now, I have problem with Mistral!" else: print("Unhandled Exception: ", str(e)) gr.Warning("Unfortunately Mistral is unable to process") output = "I do not know what happened but I could not understand you ." yield output return None return output ###### WHISPER FUNCTIONS ###### def transcribe(wav_path): try: # get result from whisper and strip it to delete begin and end space return whisper_client.predict( wav_path, # str (filepath or URL to file) in 'inputs' Audio component "transcribe", # str in 'Task' Radio component api_name="/predict" ).strip() except: gr.Warning("There was a problem with Whisper endpoint, telling a joke for you.") return "There was a problem with my voice, tell me joke" # Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text. # Will be triggered on text submit (will send to generate_speech) def add_text(history, text): history = [] if history is None else history history = history + [(text, None)] return history, gr.update(value="", interactive=False) # Will be triggered on voice submit (will transribe and send to generate_speech) def add_file(history, file): history = [] if history is None else history try: text = transcribe(file) print("Transcribed text:", text) except Exception as e: print(str(e)) gr.Warning("There was an issue with transcription, please try writing for now") # Apply a null text on error text = "Transcription seems failed, please tell me a joke about chickens" history = history + [(text, None)] return history, gr.update(value="", interactive=False) ##NOTE: not using this as it yields a chacter each time while we need to feed history to TTS def bot(history, system_prompt=""): history = [["", None]] if history is None else history if system_prompt == "": system_prompt = system_message history[-1][1] = "" for character in generate(history[-1][0], history[:-1]): history[-1][1] = character yield history def get_sentence(history, chatbot_role,system_prompt=""): history = [["", None]] if history is None else history if system_prompt == "": system_prompt = system_message history[-1][1] = "" mistral_start = time.time() print("Mistral start") sentence_list = [] sentence_hash_list = [] text_to_generate = "" stored_sentence = None stored_sentence_hash = None for character in generate_local(history[-1][0], history[:-1],system_message=ROLE_PROMPTS[chatbot_role]): history[-1][1] = character.replace("<|assistant|>","") # It is coming word by word text_to_generate = nltk.sent_tokenize(history[-1][1].replace("\n", " ").replace("<|assistant|>"," ").strip()) if len(text_to_generate) > 1: dif = len(text_to_generate) - len(sentence_list) if dif == 1 and len(sentence_list) != 0: continue if dif == 2 and len(sentence_list) != 0 and stored_sentence is not None: continue # All this complexity due to trying append first short sentence to next one for proper language auto-detect if stored_sentence is not None and stored_sentence_hash is None and dif>1: #means we consumed stored sentence and should look at next sentence to generate sentence = text_to_generate[len(sentence_list)+1] elif stored_sentence is not None and len(text_to_generate)>2 and stored_sentence_hash is not None: print("Appending stored") sentence = stored_sentence + text_to_generate[len(sentence_list)+1] stored_sentence_hash = None else: sentence = text_to_generate[len(sentence_list)] # too short sentence just append to next one if there is any # this is for proper language detection if len(sentence)<=15 and stored_sentence_hash is None and stored_sentence is None: if sentence[-1] in [".","!","?"]: if stored_sentence_hash != hash(sentence): stored_sentence = sentence stored_sentence_hash = hash(sentence) print("Storing:",stored_sentence) continue sentence_hash = hash(sentence) if stored_sentence_hash is not None and sentence_hash == stored_sentence_hash: continue if sentence_hash not in sentence_hash_list: sentence_hash_list.append(sentence_hash) sentence_list.append(sentence) print("New Sentence: ", sentence) yield (sentence, history) # return that final sentence token last_sentence = nltk.sent_tokenize(history[-1][1].replace("\n", " ").strip())[-1] sentence_hash = hash(last_sentence) if sentence_hash not in sentence_hash_list: if stored_sentence is not None and stored_sentence_hash is not None: last_sentence = stored_sentence + last_sentence stored_sentence = stored_sentence_hash = None print("Last Sentence with stored:",last_sentence) sentence_hash_list.append(sentence_hash) sentence_list.append(last_sentence) print("Last Sentence: ", last_sentence) yield (last_sentence, history) from scipy.io.wavfile import write from pydub import AudioSegment second_of_silence = AudioSegment.silent() # use default second_of_silence.export("sil.wav", format='wav') def generate_speech(history,chatbot_role): # Must set autoplay to True first yield (history, chatbot_role, "", wave_header_chunk() ) for sentence, history in get_sentence(history,chatbot_role): if sentence != "": print("BG: inserting sentence to queue") generated_speech = generate_speech_for_sentence(history, chatbot_role, sentence,return_as_byte=True) if generated_speech is not None: _, audio_dict = generated_speech # We are using byte streaming yield (history, chatbot_role, sentence, audio_dict["value"] ) # will generate speech audio file per sentence def generate_speech_for_sentence(history, chatbot_role, sentence, return_as_byte=True): language = "autodetect" wav_bytestream = b"" if len(sentence)==0: print("EMPTY SENTENCE") return # Sometimes prompt coming on output remove it # Some post process for speech only sentence = sentence.replace("", "") # remove code from speech sentence = re.sub("```.*```", "", sentence, flags=re.DOTALL) sentence = re.sub("`.*`", "", sentence, flags=re.DOTALL) sentence = re.sub("\(.*\)", "", sentence, flags=re.DOTALL) sentence = sentence.replace("```", "") sentence = sentence.replace("...", " ") sentence = sentence.replace("(", " ") sentence = sentence.replace(")", " ") sentence = sentence.replace("<|assistant|>","") # A fast fix for last chacter, may produce weird sounds if it is with text if (sentence[-1] in ["!", "?", ".", ","]) or (sentence[-2] in ["!", "?", ".", ","]): # just add a space sentence = sentence[:-1] + " " + sentence[-1] print("Sentence for speech:", sentence) if len(sentence)==0: print("EMPTY SENTENCE after processing") return try: SENTENCE_SPLIT_LENGTH=350 if len(sentence)