import os import re import io import soundfile import requests import tempfile import winsound import time import subprocess class Play_Voice_SBV2: @classmethod def INPUT_TYPES(s): return { "required":{ "model_name": ("STRING", {"forceInput": True, "default": "jvnv-F1"}), "voice_text": ("STRING", {"forceInput": True}), "save_folder_path": ("STRING", {"forceInput": True}), "filename_suffix": ("STRING", {"forceInput": True}) }, "optional":{ "speaker_id": ("INT", {"default": 0, "min": 0, "max": 100}), "style": ("STRING", {"default": "Neutral"}), "style_weight": ("FLOAT", {"default": 1, "min": 0, "max": 10, "step": 0.1},), "length": ("FLOAT", {"default": 1, "min": 0.5, "max": 2, "step": 0.1}), "sdp_ratio": ("FLOAT", {"default": 0.2, "min": 0, "max": 1, "step": 0.1}), "noise": ("FLOAT", {"default": 0.6, "min": 0, "max": 1, "step": 0.1}), "noisew": ("FLOAT", {"default": 0.8, "min": 0, "max": 1, "step": 0.1}), "auto_split": ("BOOLEAN", {"default": True}), "split_interval": ("FLOAT", {"default": 1, "min": 0, "max": 1.5, "step": 0.1}), "language": (['JP', 'EN', 'ZH'],{"default":'JP'}) } } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("message",) OUTPUT_NODE = True FUNCTION = "run" CATEGORY = "Auto_Voice_Story" def run(self, model_name, voice_text, save_folder_path, filename_suffix, speaker_id, style, style_weight, length, sdp_ratio, noise, noisew, auto_split, split_interval, language): query_data = { "text": voice_text, "speaker_id": speaker_id, "model_name": model_name, "length": length, "sdp_ratio": sdp_ratio, "noise": noise, "noisew": noisew, "auto_split": auto_split, "split_interval": split_interval, "language": language, "style": style, "style_weight": style_weight, } saved = False message = "" response = requests.get("http://127.0.0.1:5000/voice", params=query_data, headers={"accept": "audio/wav"}) if response.status_code == 200: # WAVデータを一時ファイルに保存 with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file: tmp_file.write(response.content) tmp_file_name = tmp_file.name try: # 音声を非同期で再生 winsound.PlaySound(tmp_file_name, winsound.SND_FILENAME | winsound.SND_ASYNC) duration = len(voice_text) * 0.2 # 再生が完了するまで待機 time.sleep(duration) # 再生時間に合わせて待機 except Exception as e: print(f"Failed to play sound: {e}") finally: # 一時ファイルの削除をリトライ付きで実行 for _ in range(5): # 最大5回試行 try: os.remove(tmp_file_name) print(f"Temporary file deleted: {tmp_file_name}") break except PermissionError: print(f"File is in use, retrying: {tmp_file_name}") time.sleep(2) else: print(f"Failed to delete temporary file: {tmp_file_name}") if save_folder_path and os.path.exists(save_folder_path): invalid_chars = r'[\\/:*?"<>|]' filename_voice = voice_text.replace("\n", "").strip()[:15] filename_voice = f"{model_name}-{filename_voice}{filename_suffix}" filename_voice = re.sub(invalid_chars, "", filename_voice) + ".wav" wav_save_path = os.path.join(save_folder_path, filename_voice).replace("\\","/") try: with open(wav_save_path, 'wb') as save_file: save_file.write(response.content) message = f"セーブしました。:\n{save_folder_path}\n" except Exception: return ("セーブに失敗しました。", ) else: message = f"フォルダが見つかりません:\n{save_folder_path}\n" else: print(f"Failed to get audio data: {response.status_code}") print(f"Response content: {response.text}") # エラーメッセージを表示 return None message += f"Model: {model_name}\n{voice_text}" return (message, ) class Multiple_lines_to_SBV2: @classmethod def INPUT_TYPES(s): return { "required":{ "model_name": ("STRING", {"forceInput": True, "default": "jvnv-F1"}), "voice_texts": ("STRING", {"forceInput": True}), "save_folder_path": ("STRING", {"forceInput": True}) }, "optional":{ "speaker_id": ("INT", {"default": 0, "min": 0, "max": 100}), "style": ("STRING", {"default": "Neutral"}), "style_weight": ("FLOAT", {"default": 1, "min": 0, "max": 10, "step": 0.1},), "length": ("FLOAT", {"default": 1, "min": 0.5, "max": 2, "step": 0.1}), "sdp_ratio": ("FLOAT", {"default": 0.2, "min": 0, "max": 1, "step": 0.1}), "noise": ("FLOAT", {"default": 0.6, "min": 0, "max": 1, "step": 0.1}), "noisew": ("FLOAT", {"default": 0.8, "min": 0, "max": 1, "step": 0.1}), "auto_split": ("BOOLEAN", {"default": True}), "split_interval": ("FLOAT", {"default": 0.5, "min": 0, "max": 1.5, "step": 0.1}), "language": (['JP', 'EN', 'ZH'],{"default":'JP'}) } } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("save_list",) OUTPUT_NODE = True FUNCTION = "run" CATEGORY = "Auto_Voice_Story" def run(self, model_name, voice_texts, save_folder_path, speaker_id, style, style_weight, length, sdp_ratio, noise, noisew, auto_split, split_interval, language): query_data = { "text": "", "speaker_id": speaker_id, "model_name": model_name, "length": length, "sdp_ratio": sdp_ratio, "noise": noise, "noisew": noisew, "auto_split": auto_split, "split_interval": split_interval, "language": language, "style": style, "style_weight": style_weight, } save_list = "saved files:\n" invalid_chars = r'[\\/:*?"<>|]' voice_list = voice_texts.split("\n") if not os.path.exists(save_folder_path): os.mkdir(save_folder_path) for voice_text in voice_list: voice_text = voice_text.replace("\n", "") if not voice_text: continue query_data["text"] = voice_text filename_voice = voice_text.strip("\n")[:15] # テキストの先頭15文字 filename_voice = re.sub(invalid_chars, "", filename_voice) filename_voice = f"{model_name}-{filename_voice}" + ".wav" wav_save_path = os.path.join(save_folder_path, filename_voice).replace("\\","/") print("wav_save_path", wav_save_path) # サーバーにリクエストを送信して音声データを取得 response = requests.get("http://127.0.0.1:5000/voice", params=query_data, headers={"accept": "audio/wav"}) if response.status_code != 200: raise Exception(f"Error: {response.status_code} - {response.text}") # 音声データを保存 audio_stream = io.BytesIO(response.content) data, sample_rate = soundfile.read(audio_stream) soundfile.write(wav_save_path, data, sample_rate) save_list += f"{wav_save_path}\n" return (save_list, ) class Cut_Lines: @classmethod def INPUT_TYPES(s): return { "required": { "original_text": ("STRING", {"forceInput": True}), }, "optional": { "digits": ("INT", {"default": 4, "min": 3, "max": 7}), "num_every_10": ("BOOLEAN", {"default": True}), "delimiters": ("STRING", {"default": ":<:<((「"}), "remove_char": ("STRING", {"default": ":<>:<>()()「」"}), } } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("output_lines",) OUTPUT_NODE = True FUNCTION = "run" CATEGORY = "Auto_Voice_Story" def run(self, original_text, digits, num_every_10, delimiters, remove_char): output_lines = "" multiple = 9 * num_every_10 + 1 # 入力テキストを行ごとに分割し、空行を削除 lines_list = [ data.strip() for data in original_text.splitlines() if data.strip() ] # 各行を処理 for i, line in enumerate(lines_list): for j, char in enumerate(line): # 文字を左から順番に調べる name = "" if char in delimiters: name = line[:j].strip() # 区切り文字の左側 voice = line[j:].strip() # 区切り文字を含む右側 break # 最初の区切り文字を見つけたらループ終了 else: name = "" voice = line number = str(i * multiple).zfill(digits) output_lines += f"{number}_{name}_{voice}\n" output_lines = output_lines.translate(str.maketrans("", "", remove_char)) return (output_lines,) class Generate_and_Save_Character_Voice: @classmethod def INPUT_TYPES(s): return { "required": { "lines_text": ("STRING", {"forceInput": True}), "save_folder": ("STRING", {"forceInput": True}) }, "optional": { "character_name": ("STRING", {"default": ""}), "reverse": ("BOOLEAN", {"default": False}), "model_name": ("STRING", {"default": "jvnv-F1"}), "speaker_id": ("INT", {"default": 0, "min": 0, "max": 100}), "style": ("STRING", {"default": "Neutral"}), "style_weight": ("FLOAT", {"default": 1, "min": 0, "max": 10, "step": 0.1},), "length": ("FLOAT", {"default": 1, "min": 0.5, "max": 2, "step": 0.1}), "sdp_ratio": ("FLOAT", {"default": 0.2, "min": 0, "max": 1, "step": 0.1}), "noise": ("FLOAT", {"default": 0.6, "min": 0, "max": 1, "step": 0.1}), "noisew": ("FLOAT", {"default": 0.8, "min": 0, "max": 1, "step": 0.1}), "auto_split": ("BOOLEAN", {"default": True}), "split_interval": ("FLOAT", {"default": 1, "min": 0, "max": 1.5, "step": 0.1}), "language": (['JP', 'EN', 'ZH'],{"default":'JP'}), "filename_length": ("INT", {"default": 20, "min": 10, "max": 40, "step": 5}), "file_format": (['wav', 'mp3'], {"default": "wav"}), } } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("message",) OUTPUT_NODE = True FUNCTION = "run" CATEGORY = "Auto_Voice_Story" def generate_and_save_voice(self, query_data, voice_folder_path, filename, file_format="wav"): if file_format not in ["wav", "mp3"]: raise ValueError("file_formatは'wav'または'mp3'のいずれかを指定してください。") # サーバーにリクエストを送信してWAVデータを取得 response = requests.get( "http://127.0.0.1:5000/voice", params=query_data, headers={"accept": "audio/wav"} ) if response.status_code != 200: raise Exception(f"Error: {response.status_code} - {response.text}") # 保存先パスを作成 if file_format == "wav": # WAV形式で保存 wav_path = os.path.join(voice_folder_path, f"{filename}.wav").replace("\\", "/") with open(wav_path, "wb") as wav_file: wav_file.write(response.content) elif file_format == "mp3": # 一時WAVファイルの保存 temp_wav_path = os.path.join(voice_folder_path, "temp.wav").replace("\\", "/") with open(temp_wav_path, "wb") as temp_wav_file: temp_wav_file.write(response.content) # MP3形式で保存 mp3_path = os.path.join(voice_folder_path, f"{filename}.mp3").replace("\\", "/") command = [ "ffmpeg", "-y", "-i", temp_wav_path, # 入力ファイル "-vn", # ビデオを無効化 "-ar", "44100", # サンプリングレート(オプション) "-ac", "2", # チャンネル数(オプション) "-b:a", "192k", # ビットレート mp3_path # 出力ファイル ] subprocess.run(command, check=True) # 一時ファイルの削除 os.remove(temp_wav_path) def run(self, lines_text, save_folder, character_name, reverse, model_name, speaker_id, style, style_weight, length, sdp_ratio, noise, noisew, auto_split, split_interval, language, filename_length, file_format): query_data = { "text": "", "speaker_id": speaker_id, "model_name": model_name, "length": length, "sdp_ratio": sdp_ratio, "noise": noise, "noisew": noisew, "auto_split": auto_split, "split_interval": split_interval, "language": language, "style": style, "style_weight": style_weight, } invalid_chars = r'[\\/:*?"<>|]' lines = lines_text.splitlines() # 改行で分割してリスト化 voice_text = "" voice_counter = 0 os.makedirs(save_folder, exist_ok=True) character_name = character_name.replace(" ", "").replace(" ", "") name_list = [item for item in character_name.split(",") if item] if lines: message = "" for line in lines: name = "" parts = line.split("_") # 最初と2つ目のアンダースコアに挟まれた部分を取得 if len(parts) > 2: name = parts[1] # 最初と2つ目のアンダースコアに挟まれた部分 voice_text = "_".join(parts[2:]) else: continue condition1 = not reverse and name_list and any(char in name for char in name_list) condition2 = reverse and bool(name_list) and not any(char in name for char in name_list) condition3 = not name_list and not name # message += f"line:\n{line}\n" # message += f"name : {name} , name_list : {name_list}\n" # message += f"condition1 : {condition1} , condition2 : {condition2}, condition3 : {condition3}\n" if condition1 or condition2 or condition3: if voice_text: query_data["text"] = voice_text line = re.sub(r"[  ]+", "", line) filename_voice = line[:filename_length] # strip()は不要 filename = re.sub(invalid_chars, "", filename_voice) self.generate_and_save_voice(query_data, save_folder, filename, file_format) message += f"{voice_text}\n\n" voice_counter += 1 message += f"Read {len(lines)} lines\n" message += f"Saved {voice_counter} voices\n" else: message = "No Lines." return (message, ) class Single_Voice: @classmethod def INPUT_TYPES(s): return { "required":{ "voice_path": ("STRING", {"forceInput": True, "default": ""}), }, "optional":{ "split_interval": ("FLOAT", {"default": 0.5, "min": 0, "max": 2, "step": 0.5}), } } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("message",) OUTPUT_NODE = True FUNCTION = "run" CATEGORY = "Auto_Voice_Story" def run(self, voice_path, split_interval): if os.path.exists(voice_path) and voice_path.lower().endswith((".mp3", ".wav")): subprocess.run(["ffplay", "-nodisp", "-autoexit", voice_path]) time.sleep(split_interval) message = f"play:\n{voice_path}" return message class Load_Text: @classmethod def INPUT_TYPES(s): return { "required":{ "txt_filepath": ("STRING", {"forceInput": True}) } } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("text",) OUTPUT_NODE = True FUNCTION = "run" CATEGORY = "Auto_Voice_Story" def run(self, txt_filepath): if os.path.exists(txt_filepath): try: with open(txt_filepath, 'r', encoding='utf-8') as file: text = file.read().strip() print(f"Setting Loaded:\n{text}") except Exception as e: print(str(e)) return(text, ) NODE_CLASS_MAPPINGS = { "Multiple_lines_to_SBV2": Multiple_lines_to_SBV2, "Play_Voice_SBV2": Play_Voice_SBV2, "Cut_Lines": Cut_Lines, "Generate_and_Save_Character_Voice": Generate_and_Save_Character_Voice, "Single_Voice": Single_Voice, "Load_Text": Load_Text, } NODE_DISPLAY_NAME_MAPPINGS = { "Multiple_lines_to_SBV2": "Multiple_lines_to_SBV2", "Play_Voice_SBV2": "Play_Voice_SBV2", "Cut_Lines": "Cut_Lines", "Generate_and_Save_Character_Voice": "Generate_and_Save_Character_Voice", "Single_Voice": "Single_Voice", "Load_Text": "Load_Text", }