File size: 4,203 Bytes
a25aeae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
import os
import requests
import json
from concurrent.futures import ThreadPoolExecutor, as_completed
import argparse

def synthesize_and_save(batch, voicevox_engine_url):
    for task in batch:
        file_name, text, char_name, style_name, style_id = task
        try:
            # フォルダを作成する
            output_folder = f"{char_name}_{style_name}"
            os.makedirs(output_folder, exist_ok=True)

            # 出力ファイル名を作成する
            output_file_name = os.path.join(output_folder, f"{file_name}.wav")

            # 既にファイルが存在する場合はスキップ
            if os.path.exists(output_file_name):
                print(f"File {output_file_name} already exists, skipping.")
                continue

            # 音声合成クエリを作成する
            query_response = requests.post(
                f"{voicevox_engine_url}/audio_query",
                params={"text": text, "speaker": style_id},
                headers={"Content-Type": "application/json"}
            )

            if query_response.status_code != 200:
                print(f"Failed to create audio query for {file_name} with character {char_name} and style {style_name}")
                continue

            query = query_response.json()

            # 音声合成を実行する
            synthesis_response = requests.post(
                f"{voicevox_engine_url}/synthesis",
                params={"speaker": style_id},
                data=json.dumps(query),
                headers={"Content-Type": "application/json"}
            )

            if synthesis_response.status_code != 200:
                print(f"Failed to synthesize audio for {file_name} with character {char_name} and style {style_name}")
                continue

            # 音声ファイルを保存する
            with open(output_file_name, "wb") as out_f:
                out_f.write(synthesis_response.content)

            print(f"Saved {output_file_name}")
        except Exception as e:
            print(f"Exception occurred for {file_name} with character {char_name} and style {style_name}: {e}")

def main(max_workers, batch_size):
    # VOICEVOXエンジンのURL
    VOICEVOX_ENGINE_URL = "http://localhost:50021"

    # キャラクター情報をJSONファイルからロードする
    with open("character_config.json", "r", encoding="utf-8") as f:
        CHARACTERS = json.load(f)

    # テキストファイルを読み込む
    # with open("emotion_transcript_utf8.txt", "r", encoding="utf-8") as f:
    with open("recitation_transcript_utf8.txt", "r", encoding="utf-8") as f:
        lines = f.readlines()

    tasks = []
    for line in lines:
        parts = line.strip().split(":")
        file_name = parts[0].strip()
        text_parts = parts[1].split(",")
        text = text_parts[0].strip()  # 2列目(使用するテキスト)

        for character in CHARACTERS:
            char_name = character["name"]
            for style in character["styles"]:
                style_name = style["name"]
                style_id = style["id"]
                tasks.append((file_name, text, char_name, style_name, style_id))

    # タスクをバッチに分ける
    batches = [tasks[i:i + batch_size] for i in range(0, len(tasks), batch_size)]

    # 並列処理の実行
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = [executor.submit(synthesize_and_save, batch, VOICEVOX_ENGINE_URL) for batch in batches]

        for future in as_completed(futures):
            future.result()  # 各タスクの結果を取得する(例外が発生した場合に備えて)

    print("All tasks completed.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Parallel voice synthesis script")
    parser.add_argument("--max_workers", type=int, default=256, help="Number of parallel workers")
    parser.add_argument("--batch_size", type=int, default=30, help="Number of tasks per batch")
    args = parser.parse_args()
    main(args.max_workers, args.batch_size)