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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
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",
}