import os import sys os.system("git clone https://github.com/C0untFloyd/bark-gui.git") sys.path.append("./bark-gui/") from cProfile import label from distutils.command.check import check from doctest import Example import dataclasses import gradio as gr import numpy as np import logging import torch import pytorch_seed import time import torchaudio from speechbrain.pretrained import SpectralMaskEnhancement enhance_model = SpectralMaskEnhancement.from_hparams( source="speechbrain/metricgan-plus-voicebank", savedir="pretrained_models/metricgan-plus-voicebank", run_opts={"device":"cuda"}, ) from xml.sax import saxutils from bark.api import generate_with_settings from bark.api import save_as_prompt from settings import Settings #import nltk from bark import SAMPLE_RATE from bark.clonevoice import clone_voice from bark.generation import SAMPLE_RATE, preload_models, _load_history_prompt, codec_decode from scipy.io.wavfile import write as write_wav from parseinput import split_and_recombine_text, build_ssml, is_ssml, create_clips_from_ssml from datetime import datetime from tqdm.auto import tqdm from id3tagging import add_id3_tag import shutil import string import argparse import json import gc, copy from datetime import datetime from huggingface_hub import hf_hub_download from pynvml import * nvmlInit() gpu_h = nvmlDeviceGetHandleByIndex(0) ctx_limit = 1536 title = "RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192" os.environ["RWKV_JIT_ON"] = '1' os.environ["RWKV_CUDA_ON"] = '1' # if '1' then use CUDA kernel for seq mode (much faster) from rwkv.model import RWKV model_path1 = hf_hub_download(repo_id="BlinkDL/rwkv-4-raven", filename=f"{title}.pth") model1 = RWKV(model=model_path1, strategy='cuda fp16i8 *8 -> cuda fp16') from rwkv.utils import PIPELINE, PIPELINE_ARGS pipeline = PIPELINE(model1, "20B_tokenizer.json") def generate_prompt(instruction, input=None): instruction = instruction.strip().replace('\r\n','\n').replace('\n\n','\n') input = input.strip().replace('\r\n','\n').replace('\n\n','\n') if input: return f"""Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request. # Instruction: {instruction} # Input: {input} # Response: """ else: return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request. # Instruction: {instruction} # Response: """ def evaluate( instruction, input=None, token_count=200, temperature=1.0, top_p=0.7, presencePenalty = 0.1, countPenalty = 0.1, ): args = PIPELINE_ARGS(temperature = max(0.2, float(temperature)), top_p = float(top_p), alpha_frequency = countPenalty, alpha_presence = presencePenalty, token_ban = [], # ban the generation of some tokens token_stop = [0]) # stop generation whenever you see any token here instruction = instruction.strip().replace('\r\n','\n').replace('\n\n','\n') input = input.strip().replace('\r\n','\n').replace('\n\n','\n') ctx = generate_prompt(instruction, input) all_tokens = [] out_last = 0 out_str = '' occurrence = {} state = None for i in range(int(token_count)): out, state = model1.forward(pipeline.encode(ctx)[-ctx_limit:] if i == 0 else [token], state) for n in occurrence: out[n] -= (args.alpha_presence + occurrence[n] * args.alpha_frequency) token = pipeline.sample_logits(out, temperature=args.temperature, top_p=args.top_p) if token in args.token_stop: break all_tokens += [token] if token not in occurrence: occurrence[token] = 1 else: occurrence[token] += 1 tmp = pipeline.decode(all_tokens[out_last:]) if '\ufffd' not in tmp: out_str += tmp yield out_str.strip() out_last = i + 1 gpu_info = nvmlDeviceGetMemoryInfo(gpu_h) print(f'vram {gpu_info.total} used {gpu_info.used} free {gpu_info.free}') del out del state gc.collect() torch.cuda.empty_cache() yield out_str.strip() examples = [ ["Tell me about ravens.", "", 300, 1.2, 0.5, 0.4, 0.4], ["Write a python function to mine 1 BTC, with details and comments.", "", 300, 1.2, 0.5, 0.4, 0.4], ["Write a song about ravens.", "", 300, 1.2, 0.5, 0.4, 0.4], ["Explain the following metaphor: Life is like cats.", "", 300, 1.2, 0.5, 0.4, 0.4], ["Write a story using the following information", "A man named Alex chops a tree down", 300, 1.2, 0.5, 0.4, 0.4], ["Generate a list of adjectives that describe a person as brave.", "", 300, 1.2, 0.5, 0.4, 0.4], ["You have $100, and your goal is to turn that into as much money as possible with AI and Machine Learning. Please respond with detailed plan.", "", 300, 1.2, 0.5, 0.4, 0.4], ] ########################################################################## chat_intro = '''The following is a coherent verbose detailed conversation between <|user|> and an AI girl named <|bot|>. <|user|>: Hi <|bot|>, Would you like to chat with me for a while? <|bot|>: Hi <|user|>. Sure. What would you like to talk about? I'm listening. ''' def user(message, chatbot): chatbot = chatbot or [] # print(f"User: {message}") return "", chatbot + [[message, None]] def alternative(chatbot, history): if not chatbot or not history: return chatbot, history chatbot[-1][1] = None history[0] = copy.deepcopy(history[1]) return chatbot, history def chat( prompt, user, bot, chatbot, history, temperature=1.0, top_p=0.8, presence_penalty=0.1, count_penalty=0.1, ): args = PIPELINE_ARGS(temperature=max(0.2, float(temperature)), top_p=float(top_p), alpha_frequency=float(count_penalty), alpha_presence=float(presence_penalty), token_ban=[], # ban the generation of some tokens token_stop=[]) # stop generation whenever you see any token here if not chatbot: return chatbot, history message = chatbot[-1][0] message = message.strip().replace('\r\n','\n').replace('\n\n','\n') ctx = f"{user}: {message}\n\n{bot}:" if not history: prompt = prompt.replace("<|user|>", user.strip()) prompt = prompt.replace("<|bot|>", bot.strip()) prompt = prompt.strip() prompt = f"\n{prompt}\n\n" out, state = model1.forward(pipeline.encode(prompt), None) history = [state, None, []] # [state, state_pre, tokens] # print("History reloaded.") [state, _, all_tokens] = history state_pre_0 = copy.deepcopy(state) out, state = model1.forward(pipeline.encode(ctx)[-ctx_limit:], state) state_pre_1 = copy.deepcopy(state) # For recovery # print("Bot:", end='') begin = len(all_tokens) out_last = begin out_str: str = '' occurrence = {} for i in range(300): if i <= 0: nl_bias = -float('inf') elif i <= 30: nl_bias = (i - 30) * 0.1 elif i <= 130: nl_bias = 0 else: nl_bias = (i - 130) * 0.25 out[187] += nl_bias for n in occurrence: out[n] -= (args.alpha_presence + occurrence[n] * args.alpha_frequency) token = pipeline.sample_logits(out, temperature=args.temperature, top_p=args.top_p) next_tokens = [token] if token == 0: next_tokens = pipeline.encode('\n\n') all_tokens += next_tokens if token not in occurrence: occurrence[token] = 1 else: occurrence[token] += 1 out, state = model1.forward(next_tokens, state) tmp = pipeline.decode(all_tokens[out_last:]) if '\ufffd' not in tmp: # print(tmp, end='', flush=True) out_last = begin + i + 1 out_str += tmp chatbot[-1][1] = out_str.strip() history = [state, all_tokens] yield chatbot, history out_str = pipeline.decode(all_tokens[begin:]) out_str = out_str.replace("\r\n", '\n').replace('\\n', '\n') if '\n\n' in out_str: break # State recovery if f'{user}:' in out_str or f'{bot}:' in out_str: idx_user = out_str.find(f'{user}:') idx_user = len(out_str) if idx_user == -1 else idx_user idx_bot = out_str.find(f'{bot}:') idx_bot = len(out_str) if idx_bot == -1 else idx_bot idx = min(idx_user, idx_bot) if idx < len(out_str): out_str = f" {out_str[:idx].strip()}\n\n" tokens = pipeline.encode(out_str) all_tokens = all_tokens[:begin] + tokens out, state = model1.forward(tokens, state_pre_1) break gpu_info = nvmlDeviceGetMemoryInfo(gpu_h) print(f'vram {gpu_info.total} used {gpu_info.used} free {gpu_info.free}') gc.collect() torch.cuda.empty_cache() chatbot[-1][1] = out_str.strip() history = [state, state_pre_0, all_tokens] yield chatbot, history from TTS.tts.utils.synthesis import synthesis from TTS.tts.utils.text.symbols import make_symbols, phonemes, symbols try: from TTS.utils.audio import AudioProcessor except: from TTS.utils.audio import AudioProcessor from TTS.tts.models import setup_model from TTS.config import load_config from TTS.tts.models.vits import * from TTS.tts.utils.speakers import SpeakerManager from pydub import AudioSegment # from google.colab import files import librosa from scipy.io.wavfile import write, read import subprocess OUTPUTFOLDER = "Outputs" def speechbrain(aud): # Load and add fake batch dimension noisy = enhance_model.load_audio( aud ).unsqueeze(0) enhanced = enhance_model.enhance_batch(noisy, lengths=torch.tensor([1.])) torchaudio.save('enhanced.wav', enhanced.cpu(), 16000) return 'enhanced.wav' def generate_text_to_speech(text, selected_speaker, text_temp, waveform_temp, eos_prob, quick_generation, complete_settings, seed, batchcount, progress=gr.Progress(track_tqdm=True)): # Chunk the text into smaller pieces then combine the generated audio # generation settings if selected_speaker == 'None': selected_speaker = None voice_name = selected_speaker if text == None or len(text) < 1: if selected_speaker == None: raise gr.Error('No text entered!') # Extract audio data from speaker if no text and speaker selected voicedata = _load_history_prompt(voice_name) audio_arr = codec_decode(voicedata["fine_prompt"]) result = create_filename(OUTPUTFOLDER, "None", "extract",".wav") save_wav(audio_arr, result) return result if batchcount < 1: batchcount = 1 silenceshort = np.zeros(int((float(settings.silence_sentence) / 1000.0) * SAMPLE_RATE), dtype=np.int16) # quarter second of silence silencelong = np.zeros(int((float(settings.silence_speakers) / 1000.0) * SAMPLE_RATE), dtype=np.float32) # half a second of silence use_last_generation_as_history = "Use last generation as history" in complete_settings save_last_generation = "Save generation as Voice" in complete_settings for l in range(batchcount): currentseed = seed if seed != None and seed > 2**32 - 1: logger.warning(f"Seed {seed} > 2**32 - 1 (max), setting to random") currentseed = None if currentseed == None or currentseed <= 0: currentseed = np.random.default_rng().integers(1, 2**32 - 1) assert(0 < currentseed and currentseed < 2**32) progress(0, desc="Generating") full_generation = None all_parts = [] complete_text = "" text = text.lstrip() if is_ssml(text): list_speak = create_clips_from_ssml(text) prev_speaker = None for i, clip in tqdm(enumerate(list_speak), total=len(list_speak)): selected_speaker = clip[0] # Add pause break between speakers if i > 0 and selected_speaker != prev_speaker: all_parts += [silencelong.copy()] prev_speaker = selected_speaker text = clip[1] text = saxutils.unescape(text) if selected_speaker == "None": selected_speaker = None print(f"\nGenerating Text ({i+1}/{len(list_speak)}) -> {selected_speaker} (Seed {currentseed}):`{text}`") complete_text += text with pytorch_seed.SavedRNG(currentseed): audio_array = generate_with_settings(text_prompt=text, voice_name=selected_speaker, semantic_temp=text_temp, coarse_temp=waveform_temp, eos_p=eos_prob) currentseed = torch.random.initial_seed() if len(list_speak) > 1: filename = create_filename(OUTPUTFOLDER, currentseed, "audioclip",".wav") save_wav(audio_array, filename) add_id3_tag(filename, text, selected_speaker, currentseed) all_parts += [audio_array] else: texts = split_and_recombine_text(text, settings.input_text_desired_length, settings.input_text_max_length) for i, text in tqdm(enumerate(texts), total=len(texts)): print(f"\nGenerating Text ({i+1}/{len(texts)}) -> {selected_speaker} (Seed {currentseed}):`{text}`") complete_text += text if quick_generation == True: with pytorch_seed.SavedRNG(currentseed): audio_array = generate_with_settings(text_prompt=text, voice_name=selected_speaker, semantic_temp=text_temp, coarse_temp=waveform_temp, eos_p=eos_prob) currentseed = torch.random.initial_seed() else: full_output = use_last_generation_as_history or save_last_generation if full_output: full_generation, audio_array = generate_with_settings(text_prompt=text, voice_name=voice_name, semantic_temp=text_temp, coarse_temp=waveform_temp, eos_p=eos_prob, output_full=True) else: audio_array = generate_with_settings(text_prompt=text, voice_name=voice_name, semantic_temp=text_temp, coarse_temp=waveform_temp, eos_p=eos_prob) # Noticed this in the HF Demo - convert to 16bit int -32767/32767 - most used audio format # audio_array = (audio_array * 32767).astype(np.int16) if len(texts) > 1: filename = create_filename(OUTPUTFOLDER, currentseed, "audioclip",".wav") save_wav(audio_array, filename) add_id3_tag(filename, text, selected_speaker, currentseed) if quick_generation == False and (save_last_generation == True or use_last_generation_as_history == True): # save to npz voice_name = create_filename(OUTPUTFOLDER, seed, "audioclip", ".npz") save_as_prompt(voice_name, full_generation) if use_last_generation_as_history: selected_speaker = voice_name all_parts += [audio_array] # Add short pause between sentences if text[-1] in "!?.\n" and i > 1: all_parts += [silenceshort.copy()] # save & play audio result = create_filename(OUTPUTFOLDER, currentseed, "final",".wav") save_wav(np.concatenate(all_parts), result) # write id3 tag with text truncated to 60 chars, as a precaution... add_id3_tag(result, complete_text, selected_speaker, currentseed) return result def create_filename(path, seed, name, extension): now = datetime.now() date_str =now.strftime("%m-%d-%Y") outputs_folder = os.path.join(os.getcwd(), path) if not os.path.exists(outputs_folder): os.makedirs(outputs_folder) sub_folder = os.path.join(outputs_folder, date_str) if not os.path.exists(sub_folder): os.makedirs(sub_folder) time_str = now.strftime("%H-%M-%S") file_name = f"{name}_{time_str}_s{seed}{extension}" return os.path.join(sub_folder, file_name) def save_wav(audio_array, filename): write_wav(filename, SAMPLE_RATE, audio_array) def save_voice(filename, semantic_prompt, coarse_prompt, fine_prompt): np.savez_compressed( filename, semantic_prompt=semantic_prompt, coarse_prompt=coarse_prompt, fine_prompt=fine_prompt ) def on_quick_gen_changed(checkbox): if checkbox == False: return gr.CheckboxGroup.update(visible=True) return gr.CheckboxGroup.update(visible=False) def delete_output_files(checkbox_state): if checkbox_state: outputs_folder = os.path.join(os.getcwd(), OUTPUTFOLDER) if os.path.exists(outputs_folder): purgedir(outputs_folder) return False # https://stackoverflow.com/a/54494779 def purgedir(parent): for root, dirs, files in os.walk(parent): for item in files: # Delete subordinate files filespec = os.path.join(root, item) os.unlink(filespec) for item in dirs: # Recursively perform this operation for subordinate directories purgedir(os.path.join(root, item)) def convert_text_to_ssml(text, selected_speaker): return build_ssml(text, selected_speaker) def apply_settings(themes, input_server_name, input_server_port, input_server_public, input_desired_len, input_max_len, input_silence_break, input_silence_speaker): settings.selected_theme = themes settings.server_name = input_server_name settings.server_port = input_server_port settings.server_share = input_server_public settings.input_text_desired_length = input_desired_len settings.input_text_max_length = input_max_len settings.silence_sentence = input_silence_break settings.silence_speaker = input_silence_speaker settings.save() def restart(): global restart_server restart_server = True def create_version_html(): python_version = ".".join([str(x) for x in sys.version_info[0:3]]) versions_html = f""" python: {python_version} • torch: {getattr(torch, '__long_version__',torch.__version__)} • gradio: {gr.__version__} """ return versions_html logger = logging.getLogger(__name__) APPTITLE = "Bark UI Enhanced v0.4.8" autolaunch = False if len(sys.argv) > 1: autolaunch = "-autolaunch" in sys.argv if torch.cuda.is_available() == False: os.environ['BARK_FORCE_CPU'] = 'True' logger.warning("No CUDA detected, fallback to CPU!") print(f'smallmodels={os.environ.get("SUNO_USE_SMALL_MODELS", False)}') print(f'enablemps={os.environ.get("SUNO_ENABLE_MPS", False)}') print(f'offloadcpu={os.environ.get("SUNO_OFFLOAD_CPU", False)}') print(f'forcecpu={os.environ.get("BARK_FORCE_CPU", False)}') print(f'autolaunch={autolaunch}\n\n') #print("Updating nltk\n") #nltk.download('punkt') print("Preloading Models\n") preload_models() settings = Settings('config.yaml') # Collect all existing speakers/voices in dir speakers_list = [] for root, dirs, files in os.walk("./bark/assets/prompts"): for file in files: if(file.endswith(".npz")): pathpart = root.replace("./bark/assets/prompts", "") name = os.path.join(pathpart, file[:-4]) if name.startswith("/") or name.startswith("\\"): name = name[1:] speakers_list.append(name) speakers_list = sorted(speakers_list, key=lambda x: x.lower()) speakers_list.insert(0, 'None') available_themes = ["Default", "gradio/glass", "gradio/monochrome", "gradio/seafoam", "gradio/soft", "gstaff/xkcd", "freddyaboulton/dracula_revamped", "ysharma/steampunk"] seed = -1 server_name = settings.server_name if len(server_name) < 1: server_name = None server_port = settings.server_port if server_port <= 0: server_port = None global run_server global restart_server run_server = True ''' from google.colab import drive drive.mount('/content/drive') src_path = os.path.join(os.path.join(os.path.join(os.path.join(os.getcwd(), 'drive'), 'MyDrive'), 'Colab Notebooks'), 'best_model_latest.pth.tar') dst_path = os.path.join(os.getcwd(), 'best_model.pth.tar') shutil.copy(src_path, dst_path) ''' TTS_PATH = "TTS/" # add libraries into environment sys.path.append(TTS_PATH) # set this if TTS is not installed globally # Paths definition OUT_PATH = 'out/' # create output path os.makedirs(OUT_PATH, exist_ok=True) # model vars MODEL_PATH = 'best_model.pth.tar' CONFIG_PATH = 'config.json' TTS_LANGUAGES = "language_ids.json" TTS_SPEAKERS = "speakers.json" USE_CUDA = torch.cuda.is_available() # load the config C = load_config(CONFIG_PATH) # load the audio processor ap = AudioProcessor(**C.audio) speaker_embedding = None C.model_args['d_vector_file'] = TTS_SPEAKERS C.model_args['use_speaker_encoder_as_loss'] = False model = setup_model(C) model.language_manager.set_language_ids_from_file(TTS_LANGUAGES) # print(model.language_manager.num_languages, model.embedded_language_dim) # print(model.emb_l) cp = torch.load(MODEL_PATH, map_location=torch.device('cpu')) # remove speaker encoder model_weights = cp['model'].copy() for key in list(model_weights.keys()): if "speaker_encoder" in key: del model_weights[key] model.load_state_dict(model_weights) model.eval() if USE_CUDA: model = model.cuda() # synthesize voice use_griffin_lim = False # Paths definition CONFIG_SE_PATH = "config_se.json" CHECKPOINT_SE_PATH = "SE_checkpoint.pth.tar" # Load the Speaker encoder SE_speaker_manager = SpeakerManager(encoder_model_path=CHECKPOINT_SE_PATH, encoder_config_path=CONFIG_SE_PATH, use_cuda=USE_CUDA) # Define helper function def compute_spec(ref_file): y, sr = librosa.load(ref_file, sr=ap.sample_rate) spec = ap.spectrogram(y) spec = torch.FloatTensor(spec).unsqueeze(0) return spec def voice_conversion(ta, ra, da): target_audio = 'target.wav' reference_audio = 'reference.wav' driving_audio = 'driving.wav' write(target_audio, ta[0], ta[1]) write(reference_audio, ra[0], ra[1]) write(driving_audio, da[0], da[1]) # !ffmpeg-normalize $target_audio -nt rms -t=-27 -o $target_audio -ar 16000 -f # !ffmpeg-normalize $reference_audio -nt rms -t=-27 -o $reference_audio -ar 16000 -f # !ffmpeg-normalize $driving_audio -nt rms -t=-27 -o $driving_audio -ar 16000 -f files = [target_audio, reference_audio, driving_audio] for file in files: subprocess.run(["ffmpeg-normalize", file, "-nt", "rms", "-t=-27", "-o", file, "-ar", "16000", "-f"]) # ta_ = read(target_audio) target_emb = SE_speaker_manager.compute_d_vector_from_clip([target_audio]) target_emb = torch.FloatTensor(target_emb).unsqueeze(0) driving_emb = SE_speaker_manager.compute_d_vector_from_clip([reference_audio]) driving_emb = torch.FloatTensor(driving_emb).unsqueeze(0) # Convert the voice driving_spec = compute_spec(driving_audio) y_lengths = torch.tensor([driving_spec.size(-1)]) if USE_CUDA: ref_wav_voc, _, _ = model.voice_conversion(driving_spec.cuda(), y_lengths.cuda(), driving_emb.cuda(), target_emb.cuda()) ref_wav_voc = ref_wav_voc.squeeze().cpu().detach().numpy() else: ref_wav_voc, _, _ = model.voice_conversion(driving_spec, y_lengths, driving_emb, target_emb) ref_wav_voc = ref_wav_voc.squeeze().detach().numpy() # print("Reference Audio after decoder:") # IPython.display.display(Audio(ref_wav_voc, rate=ap.sample_rate)) return (ap.sample_rate, ref_wav_voc) while run_server: print(f'Launching {APPTITLE} Server') # Create Gradio Blocks with gr.Blocks(title=f"{APPTITLE}", mode=f"{APPTITLE}", theme=settings.selected_theme) as barkgui: gr.Markdown("#