tktts.py ダウンロード/コピー
tktts.py
tktts.py
1"""
2tkttsモジュール
3
4このモジュールは、複数のTTS(Text-to-Speech)エンジンを統合し、テキストからの音声合成機能を提供します。
5クリップボードまたはファイルからテキストを読み込み、指定された話者と音声設定で音声を生成し、
6ファイルとして保存または直接再生できます。
7
8対応TTSエンジン:
9 - pyttsx3: ローカルのOS提供音声エンジンを利用
10 - winrt (onecore): WindowsのOneCore音声エンジンを利用
11 - voicevox: Voicevoxエンジンを利用 (要Voicevox Engine稼働)
12 - qwen3 (qwen): Qwen TTSモデルを利用 (ローカル)
13 - qwen_api (qwen-api): Qwen TTS APIを利用
14 - irodori (irodori-tts): Irodori TTSモデルを利用 (ローカル)
15 - irodori_api (irodori-api): Irodori TTS APIを利用
16 - aquestalkplayer (atp): AquesTalk Playerを利用
17 - openai: OpenAI TTS APIを利用
18 - elevenlabs (eleven): ElevenLabs TTS APIを利用
19 - gemini: Google Gemini TTS APIを利用
20 - edge (edge_tts, edge-tts): Microsoft Edge TTSを利用
21
22必要なコアライブラリ:
23 - pydub: 音声ファイルの操作(結合、フォーマット変換など)
24 - pyperclip: クリップボードへのアクセス
25 - chardet: ファイルのエンコード検出
26 - FFmpeg: 音声ファイルのエンコード/デコードに必要(PATHに設定推奨)
27
28外部ドキュメントへのリンク:
29 :doc:`tktts_usage`
30
31"""
32import os
33import sys
34import re
35import time
36import subprocess
37import shutil
38import tempfile
39from pathlib import Path
40import traceback
41import inspect
42
43# --- コアライブラリとオプションTTSバックエンド ---
44# 各TTSエンジン固有の依存関係は必須にしない。
45# 使えるバックエンドだけを安全に登録する。
46import importlib
47import importlib.util
48from types import SimpleNamespace
49
50CORE_LIBS = ["pydub", "pyperclip", "chardet"]
51missing_core = [name for name in CORE_LIBS if importlib.util.find_spec(name) is None]
52if missing_core:
53 print(f"Error: Missing core libraries: {', '.join(missing_core)}")
54 print(" install: pip install pydub pyperclip chardet")
55 print(" MP3などを扱う場合は FFmpeg もPATHに設定してください。")
56 raise SystemExit(1)
57
58import pyperclip
59import chardet
60from pydub import AudioSegment
61
62
63def check_ffmpeg_available() -> bool:
64 """
65 FFmpeg と FFprobe がシステムPATHで利用可能かを確認します。
66
67 :returns: FFmpeg と FFprobe の両方が利用可能であればTrue、そうでなければFalse。
68 :rtype: bool
69 """
70 ffmpeg = shutil.which("ffmpeg")
71 ffprobe = shutil.which("ffprobe")
72
73 if ffmpeg is None:
74 print("❌ ffmpeg が見つかりません。")
75 return False
76
77 if ffprobe is None:
78 print("⚠️ ffprobe が見つかりません。読み込み時に問題が出る可能性があります。")
79 return False
80
81 print(f"✅ ffmpeg: {ffmpeg}")
82 print(f"✅ ffprobe: {ffprobe}")
83 return True
84
85ffmpeg_path = shutil.which("ffmpeg")
86
87if ffmpeg_path is None:
88 print("tktts.py: ffmpeg が見つかりません")
89 raise SystemExit(1)
90else:
91# print("tktts.py: ffmpeg が使えます:", ffmpeg_path)
92 pass
93
94
95def _safe_import(module_name: str, dependency: str = None):
96 """
97 オプションのTTSバックエンドモジュールを安全に読み込みます。
98
99 dependency が未導入の場合や、モジュールインポート時に例外が発生した場合は、
100 バックエンド側の ``input()`` や ``sys.exit()`` を実行させず、Noneを返して
101 利用不可として登録します。
102
103 :param module_name: 読み込むモジュールの名前。
104 :type module_name: str
105 :param dependency: モジュールが依存する外部ライブラリの名前。これがNoneでない場合、
106 この依存ライブラリがインストールされているかを確認します。
107 :type dependency: str, optional
108 :returns: 読み込みに成功した場合はモジュールオブジェクト、失敗した場合はNone。
109 :rtype: types.ModuleType or None
110 """
111 if dependency and importlib.util.find_spec(dependency) is None:
112 print(
113 f"Warning in tktts.py: {module_name} is disabled "
114 f"because optional dependency [{dependency}] is not installed."
115 )
116 return None
117
118 try:
119 return importlib.import_module(module_name)
120 except SystemExit as e:
121 print(f"Warning in tktts.py: {module_name} terminated during import: {e}")
122 return None
123 except Exception as e:
124 print(f"\nWarning in tktts.py: Import error for {module_name}")
125 print("------------------------------------------------------------------")
126 print(f"Error message: {e}")
127 traceback.print_exc()
128 print("------------------------------------------------------------------")
129 return None
130
131
132tktts_pyttsx3 = _safe_import("tktts_pyttsx3", "pyttsx3")
133tktts_winrt = _safe_import("tktts_winrt", "winrt")
134tktts_voicevox = _safe_import("tktts_voicevox")
135tktts_qwen3 = _safe_import("tktts_qwen3", "qwen_tts")
136tktts_qwen_api = _safe_import("tktts_qwen_api")
137tktts_irodori = _safe_import("tktts_irodori", "irodori_tts")
138tktts_irodori_api = _safe_import("tktts_irodori_api")
139tktts_aquestalkplayer = _safe_import("tktts_aquestalkplayer")
140tktts_openai = _safe_import("tktts_openai", "openai")
141tktts_elevenlabs = _safe_import("tktts_elevenlabs", "elevenlabs")
142tktts_gemini = _safe_import("tktts_gemini", "google.genai")
143tktts_edge = _safe_import("tktts_edge", "edge_tts")
144
145
146default_pyttsx3_voice = "Zira"
147default_winrt_voice = "Ayumi"
148default_voicevox_voice = "四国めたん"
149default_qwen3_voice = "Ono_Anna"
150default_qwen_api_voice = "Ono_Anna"
151default_irodori_voice = "default"
152default_irodori_api_voice = "none"
153default_aqt_preset = "れいむ"
154default_openai_voice = "alloy"
155# 旧コードとの互換性のため、綴り間違いの変数名も残す。
156default_optnai_voice = default_openai_voice
157default_elevenlabs_voice = "Rachel"
158default_gemini_voice = "Kore"
159default_edge_voice = "Nanami"
160
161TTS_ENGINES = {
162 "pyttsx3": {
163 "engine": tktts_pyttsx3,
164 "default_voice": default_pyttsx3_voice,
165 "ext": "wav",
166 "direct_playback": True,
167 },
168 "winrt": {
169 "engine": tktts_winrt,
170 "default_voice": default_winrt_voice,
171 "ext": "wav",
172 "direct_playback": True,
173 },
174 "onecore": {
175 "engine": tktts_winrt,
176 "default_voice": default_winrt_voice,
177 "ext": "wav",
178 "direct_playback": True,
179 },
180 "voicevox": {
181 "engine": tktts_voicevox,
182 "default_voice": default_voicevox_voice,
183 "ext": "wav",
184 "direct_playback": False,
185 },
186 "qwen3": {
187 "engine": tktts_qwen3,
188 "default_voice": default_qwen3_voice,
189 "ext": "wav",
190 "direct_playback": False,
191 },
192 "qwen": {
193 "engine": tktts_qwen3,
194 "default_voice": default_qwen3_voice,
195 "ext": "wav",
196 "direct_playback": False,
197 },
198 "qwen_api": {
199 "engine": tktts_qwen_api,
200 "default_voice": default_qwen_api_voice,
201 "ext": "wav",
202 "direct_playback": False,
203 },
204 "qwen-api": {
205 "engine": tktts_qwen_api,
206 "default_voice": default_qwen_api_voice,
207 "ext": "wav",
208 "direct_playback": False,
209 },
210 "irodori": {
211 "engine": tktts_irodori,
212 "default_voice": default_irodori_voice,
213 "ext": "wav",
214 "direct_playback": False,
215 },
216 "irodori-tts": {
217 "engine": tktts_irodori,
218 "default_voice": default_irodori_voice,
219 "ext": "wav",
220 "direct_playback": False,
221 },
222 "irodori_api": {
223 "engine": tktts_irodori_api,
224 "default_voice": default_irodori_api_voice,
225 "ext": "wav",
226 "direct_playback": False,
227 },
228 "irodori-api": {
229 "engine": tktts_irodori_api,
230 "default_voice": default_irodori_api_voice,
231 "ext": "wav",
232 "direct_playback": False,
233 },
234 "aquestalkplayer": {
235 "engine": tktts_aquestalkplayer,
236 "default_voice": default_aqt_preset,
237 "ext": "wav",
238 "direct_playback": False,
239 },
240 "atp": {
241 "engine": tktts_aquestalkplayer,
242 "default_voice": default_aqt_preset,
243 "ext": "wav",
244 "direct_playback": False,
245 },
246 "openai": {
247 "engine": tktts_openai,
248 "default_voice": default_openai_voice,
249 "ext": "mp3",
250 "direct_playback": False,
251 },
252 "elevenlabs": {
253 "engine": tktts_elevenlabs,
254 "default_voice": default_elevenlabs_voice,
255 "ext": "mp3",
256 "direct_playback": False,
257 },
258 "eleven": {
259 "engine": tktts_elevenlabs,
260 "default_voice": default_elevenlabs_voice,
261 "ext": "mp3",
262 "direct_playback": False,
263 },
264 "gemini": {
265 "engine": tktts_gemini,
266 "default_voice": default_gemini_voice,
267 "ext": "wav",
268 "direct_playback": False,
269 },
270 "edge": {
271 "engine": tktts_edge,
272 "default_voice": default_edge_voice,
273 "ext": "mp3",
274 "direct_playback": False,
275 },
276 "edge_tts": {
277 "engine": tktts_edge,
278 "default_voice": default_edge_voice,
279 "ext": "mp3",
280 "direct_playback": False,
281 },
282 "edge-tts": {
283 "engine": tktts_edge,
284 "default_voice": default_edge_voice,
285 "ext": "mp3",
286 "direct_playback": False,
287 },
288}
289
290
291def get_available_engines(available_only: bool = True):
292 """
293 登録されているTTSエンジン名を返します。
294
295 GUIのプルダウンメニュー生成などにも利用できます。
296
297 :param available_only: 利用可能なエンジンのみを返すかどうか。Trueの場合、
298 依存ライブラリがロードできたエンジンのみを返します。
299 Falseの場合、全ての登録済みエンジン名を返します。
300 :type available_only: bool
301 :returns: 利用可能な(または全ての)TTSエンジン名のリスト。
302 :rtype: list[str]
303 """
304 if not available_only:
305 return list(TTS_ENGINES.keys())
306 return [name for name, cfg in TTS_ENGINES.items() if cfg["engine"] is not None]
307
308
309def _supported_kwargs(func, kwargs: dict):
310 """
311 関数が受け取れるキーワード引数のみをフィルタリングして返します。
312
313 引数に ``**kwargs`` を持つ関数は、全てのキーワード引数を受け入れると見なされます。
314 引数の値が ``None`` の場合は除外されます。
315
316 :param func: キーワード引数を適用する対象の関数。
317 :type func: callable
318 :param kwargs: フィルタリング対象のキーワード引数辞書。
319 :type kwargs: dict
320 :returns: 関数が受け取れるキーワード引数のみを含む辞書。
321 :rtype: dict
322 """
323 try:
324 signature = inspect.signature(func)
325 except (TypeError, ValueError):
326 # シグネチャを取得できない場合 (例: built-in関数) は、None値を除いて全て返す
327 return {k: v for k, v in kwargs.items() if v is not None}
328
329 if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in signature.parameters.values()):
330 # **kwargs を持つ関数は全てを受け入れる
331 return {k: v for k, v in kwargs.items() if v is not None}
332
333 return {
334 k: v
335 for k, v in kwargs.items()
336 if v is not None and k in signature.parameters
337 }
338
339
340def _call_backend(func, **kwargs):
341 """
342 キーワード引数をフィルタリングし、TTSバックエンド関数を呼び出します。
343
344 :param func: 呼び出すTTSバックエンド関数。
345 :type func: callable
346 :param kwargs: 関数に渡すキーワード引数。
347 :type kwargs: dict
348 :returns: バックエンド関数の実行結果。
349 :rtype: Any
350 """
351 return func(**_supported_kwargs(func, kwargs))
352
353def apply_replacements(text: str, replacements: dict):
354 """
355 置換辞書を使ってテキストを置換(大文字小文字無視)します。
356
357 :param text: 置換処理を適用する元のテキスト。
358 :type text: str
359 :param replacements: キーを正規表現パターン、値を置換後の文字列とする辞書。
360 キーのマッチングは大文字小文字を無視します。
361 :type replacements: dict or None
362 :returns: 置換後のテキスト。
363 :rtype: str
364 """
365 for key, val in (replacements or {}).items():
366 text = re.sub(key, val, text, flags=re.IGNORECASE)
367 return text
368
369def load_text(input_path: str, monologue: bool = False, wait_for_clipboard: bool = True):
370 """
371 入力元 ('clip' またはファイルパス) からテキストを取得し、(speaker, text) リストを返します。
372
373 テキストファイルはchardetでエンコードを自動判別します。
374 ファイル内の空行、コメント行(#で始まる行)、および記号のみの行は無視されます。
375
376 :param input_path: テキストの入力元。'clip' の場合はクリップボードから、
377 それ以外の文字列はファイルパスとして扱います。
378 :type input_path: str
379 :param monologue: テキストが独話形式(話者指定なし)かどうか。Trueの場合、
380 全ての話者がNoneとして扱われます。
381 :type monologue: bool
382 :param wait_for_clipboard: input_pathが'clip'の場合、クリップボードにテキストが
383 コピーされるまで待機するかどうか。
384 :type wait_for_clipboard: bool
385 :returns: (話者名, テキスト) のタプルを要素とするリスト。
386 読み込みに失敗した場合はNoneを返します。
387 :rtype: list[tuple[str or None, str]] or None
388 """
389
390 print()
391 print(f"load_text from {input_path}")
392 if input_path.lower() == "clip" and wait_for_clipboard:
393 print()
394 input("読み上げるテキストをクリップボードにコピーしてください:\n")
395 print("📥 クリップボードからテキストを取得中...")
396 text = pyperclip.paste()
397 text_lines = text.splitlines()
398 else:
399 file_name = input_path
400 if not os.path.isfile(file_name):
401 print(f"Error: ファイル [{file_name}] が見つかりません。")
402 return None
403
404 print(f"📖 ファイル [{file_name}] を読み込み中...")
405 try:
406 with open(file_name, "rb") as f:
407 raw_data = f.read()
408
409 result = chardet.detect(raw_data)
410 encoding = result["encoding"]
411 if encoding is None: encoding = 'utf-8'
412
413 text = raw_data.decode(encoding, errors='ignore')
414 print(f" 検出されたエンコード: {encoding}")
415 text_lines = text.splitlines()
416 except Exception as e:
417 print(f"❌ ファイル読み込み/エンコード判別エラー: {e}")
418 return None
419
420 # dialogueリストへの変換 (既存ロジックを流用)
421 dialogue = []
422 for line in text_lines:
423 line = line.strip()
424 if not line: continue
425 if line.startswith("#"): continue
426 # 発音できる文字を含まない行(---、===、……、記号だけの行)は
427 # 区切り・無音用の文字列とみなし、読み上げない。PPTXノートを
428 # 処理する add_notes_voice_pptx2.py と同じ規則にする。
429 if not any(char.isalnum() for char in line): continue
430
431 if monologue:
432 dialogue.append((None, line.strip()))
433 else:
434 if "," in line:
435 try:
436 speaker, text = line.split(",", 1)
437 dialogue.append((speaker.strip(), text.strip()))
438 except ValueError:
439 continue
440 # 対話モードでカンマがない行は無視
441 # 修正前のコードではカンマがない行は無視されているため、ここでは continue
442 continue
443
444 return dialogue
445
446def create_temp_dir(temp_dir: str):
447 """
448 指定されたパスに一時ディレクトリを作成します。
449
450 既に存在する場合は何もしません。
451
452 :param temp_dir: 作成する一時ディレクトリのパス。
453 :type temp_dir: str
454 :returns: 作成または確認された一時ディレクトリのパス。
455 :rtype: str
456 """
457 if not os.path.exists(temp_dir):
458 os.makedirs(temp_dir, exist_ok=True)
459 print(f"一時ディレクトリを作成: {temp_dir}")
460 return temp_dir
461
462def get_speaker_dict(tts_engine: str, dialogue: list, voices: str,
463 default_voicevox_voice: str ="四国めたん", default_pyttsx3_voice: str ="Zira",
464 default_winrt_voice: str ="Ayumi", default_aqt_preset: str ="れいむ",
465 default_optnai_voice: str ="alloy", default_elevenlabs_voice: str ="Rachel",
466 default_gemini_voice: str ="Kore"):
467 """
468 話者名とそれに割り当てる音声名をマッピングした辞書を作成します。
469
470 `voices` 引数で明示的に指定された音声が優先され、指定がない場合はエンジンのデフォルト音声が使用されます。
471
472 :param tts_engine: 使用するTTSエンジンの名前(例: "voicevox", "pyttsx3")。
473 :type tts_engine: str
474 :param dialogue: (話者名, テキスト) のタプルからなるリスト。
475 :type dialogue: list[tuple[str or None, str]]
476 :param voices: 話者と音声の割り当てをセミコロン区切りで指定する文字列。
477 例: "話者A=Voice1;話者B=Voice2"
478 または、カンマ区切りで音声名を直接指定する文字列。
479 例: "Voice1,Voice2,Voice3"
480 :type voices: str or None
481 :param default_voicevox_voice: Voicevoxのデフォルト音声名。
482 :type default_voicevox_voice: str
483 :param default_pyttsx3_voice: pyttsx3のデフォルト音声名。
484 :type default_pyttsx3_voice: str
485 :param default_winrt_voice: WinRTのデフォルト音声名。
486 :type default_winrt_voice: str
487 :param default_aqt_preset: AquesTalk Playerのデフォルトプリセット名。
488 :type default_aqt_preset: str
489 :param default_optnai_voice: OpenAIのデフォルト音声名。
490 :type default_optnai_voice: str
491 :param default_elevenlabs_voice: ElevenLabsのデフォルト音声名。
492 :type default_elevenlabs_voice: str
493 :param default_gemini_voice: Geminiのデフォルト音声名。
494 :type default_gemini_voice: str
495 :returns: 話者名(またはNone)をキー、音声名を値とする辞書。
496 無効なTTSエンジンが指定された場合はNoneを返します。
497 :rtype: dict[str or None, str] or None
498 """
499
500 tts_engine = str(tts_engine).lower()
501 if tts_engine in TTS_ENGINES:
502 default_voice = TTS_ENGINES[tts_engine]["default_voice"]
503 else:
504 print(f"\nError in tktts.get_speaker_dict(): Invalid tts engine [{tts_engine}]\n")
505 return None
506
507 print("\n話者リスト作成...")
508 voices_specified = [v.strip() for v in str(voices or "").split(";") if v.strip()]
509 if voices_specified:
510 default_voice = voices_specified[0]
511
512 speaker_names = []
513 target_voices = {}
514 for speaker, _text in dialogue or []:
515 if speaker is None or speaker == "" or speaker in speaker_names:
516 continue
517 speaker_names.append(speaker)
518 index = len(speaker_names) - 1
519 target_voices[speaker] = (
520 voices_specified[index] if index < len(voices_specified) else default_voice
521 )
522
523 target_voices[""] = default_voice
524 target_voices[None] = default_voice
525
526 for i, (speaker, voice) in enumerate(target_voices.items()):
527 print(f" {i:02d}: {speaker} => {voice}")
528
529 return target_voices
530
531def get_tts(tts_engine: str):
532 """
533 指定されたTTSエンジン名に対応するモジュールオブジェクトを取得します。
534
535 :param tts_engine: 取得するTTSエンジンの名前。
536 :type tts_engine: str
537 :returns: TTSモジュールオブジェクト。利用できない場合はNone。
538 :rtype: types.ModuleType or None
539 """
540 tts_engine = str(tts_engine or "").lower()
541 config = TTS_ENGINES.get(tts_engine)
542 if config is None:
543 print(f"\nError in tktts.get_tts(): Invalid tts engine [{tts_engine}]\n")
544 return None
545
546 tts_module = config["engine"]
547 if tts_module is not None:
548 return tts_module
549
550 print(f"\nError in tktts.get_tts(): TTS engine [{tts_engine}] is unavailable.")
551 print("対応バックエンドファイルと、そのオプション依存ライブラリを確認してください。")
552 return None
553
554
555def get_available_voices_info(tts_engine: str, endpoint: str = None, api_key: str = None):
556 """
557 指定されたTTSエンジンで利用可能な音声の詳細情報を取得します。
558
559 各TTSバックエンドの `get_available_voices_info` 関数を呼び出します。
560
561 :param tts_engine: 音声情報を取得するTTSエンジンの名前。
562 :type tts_engine: str
563 :param endpoint: APIベースのTTSエンジンで使用するエンドポイントURL。
564 :type endpoint: str, optional
565 :param api_key: APIベースのTTSエンジンで使用するAPIキー。
566 :type api_key: str, optional
567 :returns: 利用可能な音声の詳細情報。エンジンが利用不可、または対応する関数がない場合はNone。
568 形式はエンジンによって異なりますが、通常は辞書のリストなど。
569 :rtype: Any or None
570 """
571 tts_engine = str(tts_engine or "").lower()
572 tts = get_tts(tts_engine)
573 if tts is None or not hasattr(tts, "get_available_voices_info"):
574 return None
575 return _call_backend(
576 tts.get_available_voices_info,
577 endpoint=endpoint,
578 api_key=api_key,
579 )
580
581
582def get_available_voices(tts_engine: str, endpoint: str = None, api_key: str = None):
583 """
584 指定されたTTSエンジンで利用可能な音声のリストを取得します。
585
586 各TTSバックエンドの `get_available_voices` 関数を呼び出します。
587
588 :param tts_engine: 音声リストを取得するTTSエンジンの名前。
589 :type tts_engine: str
590 :param endpoint: APIベースのTTSエンジンで使用するエンドポイントURL。
591 :type endpoint: str, optional
592 :param api_key: APIベースのTTSエンジンで使用するAPIキー。
593 :type api_key: str, optional
594 :returns: 利用可能な音声名のリスト。エンジンが利用不可、または対応する関数がない場合はNone。
595 :rtype: list[str] or None
596 """
597 tts_engine = str(tts_engine or "").lower()
598 tts = get_tts(tts_engine)
599 if tts is None or not hasattr(tts, "get_available_voices"):
600 return None
601 return _call_backend(
602 tts.get_available_voices,
603 endpoint=endpoint,
604 api_key=api_key,
605 )
606
607
608def list_available_voices(tts_engine: str, endpoint: str = None, api_key: str = None):
609 """
610 指定されたTTSエンジンで利用可能な音声のリストを標準出力に表示します。
611
612 各TTSバックエンドの `list_available_voices` 関数を呼び出します。
613
614 :param tts_engine: 音声リストを表示するTTSエンジンの名前。
615 :type tts_engine: str
616 :param endpoint: APIベースのTTSエンジンで使用するエンドポイントURL。
617 :type endpoint: str, optional
618 :param api_key: APIベースのTTSエンジンで使用するAPIキー。
619 :type api_key: str, optional
620 :returns: 処理が成功した場合はTrue、失敗した場合はFalse。
621 :rtype: bool
622 """
623 tts_engine = str(tts_engine or "").lower()
624 tts = get_tts(tts_engine)
625 if tts is None:
626 return False
627 if not hasattr(tts, "list_available_voices"):
628 print(f"Error: TTS module [{tts_engine}] has no list_available_voices function.")
629 return False
630
631 try:
632 ret = _call_backend(
633 tts.list_available_voices,
634 endpoint=endpoint,
635 api_key=api_key,
636 )
637 except Exception as e:
638 print(f"Error calling list_available_voices for {tts_engine}: {e}")
639 traceback.print_exc()
640 ret = False
641
642 print("===============================")
643 return ret
644
645def normalize_speaker(speaker, tts_engine: str = None):
646 """
647 話者ラベルを正規化します。
648
649 半角スペースでは分割しない。WinRTなどの音声表示名には
650 ``Microsoft Ayumi ...`` のように空白が含まれるためである。
651 明示的なスタイル表記 ``話者(style)`` / ``話者(style)`` のみ除去します。
652
653 :param speaker: 正規化する話者名または音声名。
654 :type speaker: str or None
655 :param tts_engine: 使用するTTSエンジンの名前(現在は未使用ですが、将来の拡張性のため)。
656 :type tts_engine: str, optional
657 :returns: 正規化された話者名。入力がNoneの場合はNone。
658 :rtype: str or None
659 """
660 if speaker is None:
661 return None
662
663 normalized = str(speaker).strip()
664 for opening in ("(", "("):
665 if opening in normalized:
666 normalized = normalized.split(opening, 1)[0].rstrip()
667 return normalized
668
669def parse_kv_string(kv_string: str, keys: list = [], allow_no_key_kv_string: bool = False):
670 """
671 "key=val;key=val" 形式の文字列を辞書に変換します。
672
673 `allow_no_key_kv_string` がTrueの場合、"=" が含まれないアイテムも、
674 `keys` 引数のインデックスに基づいて辞書に追加されます。
675
676 :param kv_string: "key=val;key=val" 形式の文字列、またはセミコロン区切りの値の文字列。
677 :type kv_string: str
678 :param keys: `kv_string` が "key=val" 形式でない場合に、値に割り当てるキーのリスト。
679 :type keys: list
680 :param allow_no_key_kv_string: "=" を含まないアイテムを許容し、`keys` に基づいて処理するかどうか。
681 :type allow_no_key_kv_string: bool
682 :returns: キーと値をマッピングした辞書。
683 :rtype: dict
684 """
685
686 if not kv_string: return {}
687 nkeys = len(keys)
688
689 d = {}
690 idx = 0
691 for item in kv_string.split(";"):
692 if "=" in item:
693 k, v = item.split("=", 1)
694 d[k.strip()] = v.strip()
695 elif allow_no_key_kv_string:
696 if "*" in item or item.strip() == "": continue
697
698 if idx < nkeys: d[keys[idx]] = item
699 d[idx] = item
700 idx += 1
701 for speaker in keys:
702 if speaker in d.keys(): continue
703 d[speaker] = speaker
704
705 return d
706
707def _get_attr(args: SimpleNamespace, name: str, default=None):
708 """
709 Namespaceオブジェクトから属性を安全に取得します。
710
711 属性が存在しない場合はデフォルト値を返します。
712
713 :param args: 属性を取得する対象のNamespaceオブジェクト。
714 :type args: SimpleNamespace or None
715 :param name: 取得する属性の名前。
716 :type name: str
717 :param default: 属性が存在しない場合に返すデフォルト値。
718 :type default: Any, optional
719 :returns: 取得された属性の値、またはデフォルト値。
720 :rtype: Any
721 """
722 return getattr(args, name, default) if args is not None else default
723
724
725def _effective_pyttsx3_rate(args: SimpleNamespace):
726 """
727 pyttsx3向けに最終的な話速を計算します。
728
729 基本話速 (`speak_rate`) に浮動小数点数倍率 (`fspeak_rate`) を適用します。
730
731 :param args: 設定値を含むNamespaceオブジェクト。
732 `speak_rate` (int) と `fspeak_rate` (float) を含む可能性があります。
733 :type args: SimpleNamespace
734 :returns: 最終的な話速(整数値)。最低値は1。
735 :rtype: int
736 """
737 base_rate = float(_get_attr(args, "speak_rate", 150) or 150)
738 multiplier = _get_attr(args, "fspeak_rate", None)
739 if multiplier is not None:
740 try:
741 base_rate *= float(multiplier)
742 except (TypeError, ValueError):
743 pass
744 return max(1, int(round(base_rate)))
745
746
747def _effective_winrt_rate(args: SimpleNamespace):
748 """
749 WinRT向けに最終的な話速を計算します。
750
751 GUIの `fspeak_rate` は相対倍率なので、WinRTにはそのまま渡せます。
752 `fspeak_rate` が優先され、なければ `speak_rate` が使用されます。
753
754 :param args: 設定値を含むNamespaceオブジェクト。
755 `fspeak_rate` (float) と `speak_rate` (int) を含む可能性があります。
756 :type args: SimpleNamespace
757 :returns: 最終的な話速(数値)。
758 :rtype: float or int
759 """
760 # GUIの fspeak_rate は相対倍率なので、WinRTにはそのまま渡せる。
761 relative_rate = _get_attr(args, "fspeak_rate", None)
762 if relative_rate is not None:
763 return relative_rate
764 return _get_attr(args, "speak_rate", 150)
765
766
767def _elevenlabs_voice_settings(args: SimpleNamespace):
768 """
769 ElevenLabsの音声設定をargsから抽出し、辞書形式で返します。
770
771 `elevenlabs_voice_settings` が辞書として直接提供される場合はそれを優先し、
772 そうでなければ個別の `elevenlabs_stability` などの設定値を集約します。
773
774 :param args: 設定値を含むNamespaceオブジェクト。
775 `elevenlabs_voice_settings` または個別のElevenLabs設定
776 (`elevenlabs_stability`, `elevenlabs_similarity_boost` など)
777 を含む可能性があります。
778 :type args: SimpleNamespace
779 :returns: ElevenLabsの音声設定を含む辞書、またはNone。
780 :rtype: dict or None
781 """
782 settings = _get_attr(args, "elevenlabs_voice_settings", None)
783 if settings is None:
784 settings = _get_attr(args, "voice_settings", None)
785 if isinstance(settings, dict):
786 return dict(settings)
787
788 values = {}
789 for key in ("stability", "similarity_boost", "style", "use_speaker_boost"):
790 value = _get_attr(args, f"elevenlabs_{key}", None)
791 if value is not None:
792 values[key] = value
793 return values or None
794
795
796def _infer_output_format(outfile: str, requested_format: str, default_format: str):
797 """
798 出力ファイル名と要求された形式から最終的な出力フォーマットを推測します。
799
800 `requested_format` があればそれを、なければ `outfile` の拡張子を、
801 どちらもなければ `default_format` を使用します。
802
803 :param outfile: 出力ファイルのパス。拡張子からフォーマットを推測するために使用されます。
804 :type outfile: str
805 :param requested_format: ユーザーが明示的に要求した出力フォーマット(例: "mp3", "wav")。
806 :type requested_format: str or None
807 :param default_format: 推測できなかった場合のデフォルトの出力フォーマット。
808 :type default_format: str
809 :returns: 推測された出力フォーマットの文字列(小文字、先頭の"."なし)。
810 :rtype: str
811 """
812 if requested_format:
813 return str(requested_format).lower().lstrip(".")
814 suffix = Path(str(outfile)).suffix.lower().lstrip(".")
815 if suffix:
816 return "wav" if suffix == "wave" else suffix
817 return default_format
818
819
820def speak_dialogue(args: SimpleNamespace, dialogue: list, voice_map: dict = None, speakers: dict = None, replacements: dict = None,
821 default_voicevox_voice: str ="四国めたん", default_pyttsx3_voice: str ="Zira",
822 default_winrt_voice: str ="Ayumi", default_aqt_preset: str ="れいむ",
823 default_optnai_voice: str ="alloy", default_elevenlabs_voice: str ="Rachel",
824 default_gemini_voice: str ="Kore",
825 endpoint: str =None, api_key: str =None, output_format: str =None):
826 """
827 選択されたTTSエンジンで音声生成を行い、結合して保存または直接再生します。
828
829 この関数は、指定されたダイアログデータと設定に基づいて、適切なTTSバックエンドを呼び出し、
830 生成された音声ファイルを一時ディレクトリに保存し、必要に応じてそれらを結合して最終的な
831 出力ファイルとして保存します。
832
833 :param args: TTSエンジンの設定値を含むNamespaceオブジェクト。
834 `tts` (str), `outfile` (str), `monologue` (bool), `speak_rate` (int),
835 `tinterval` (float), `voices` (str), `temp_dir` (str) など、
836 および各エンジン固有の設定(例: `qwen3_language`, `elevenlabs_api_key`)
837 を含みます。
838 :type args: SimpleNamespace
839 :param dialogue: (話者名, テキスト) のタプルを要素とするリスト。
840 :type dialogue: list[tuple[str or None, str]]
841 :param voice_map: 話者名と音声名のマッピング辞書。Noneの場合は `args.voices` から生成されます。
842 :type voice_map: dict[str or None, str], optional
843 :param speakers: (未使用) 話者リスト。
844 :type speakers: dict, optional
845 :param replacements: テキストの置換ルールを定義する辞書。
846 :type replacements: dict, optional
847 :param default_voicevox_voice: Voicevoxのデフォルト音声名。
848 :type default_voicevox_voice: str
849 :param default_pyttsx3_voice: pyttsx3のデフォルト音声名。
850 :type default_pyttsx3_voice: str
851 :param default_winrt_voice: WinRTのデフォルト音声名。
852 :type default_winrt_voice: str
853 :param default_aqt_preset: AquesTalk Playerのデフォルトプリセット名。
854 :type default_aqt_preset: str
855 :param default_optnai_voice: OpenAIのデフォルト音声名。
856 :type default_optnai_voice: str
857 :param default_elevenlabs_voice: ElevenLabsのデフォルト音声名。
858 :type default_elevenlabs_voice: str
859 :param default_gemini_voice: Geminiのデフォルト音声名。
860 :type default_gemini_voice: str
861 :param endpoint: APIベースのTTSエンジンで使用するエンドポイントURL。
862 `args` の設定よりも優先されます。
863 :type endpoint: str, optional
864 :param api_key: APIベースのTTSエンジンで使用するAPIキー。
865 `args` の設定よりも優先されます。
866 :type api_key: str, optional
867 :param output_format: 出力ファイルのフォーマット。`args` の設定よりも優先されます。
868 :type output_format: str, optional
869 :returns: 音声出力に成功した場合、ファイル保存モードでは出力ファイルのパス、
870 直接再生モードではTrue。失敗した場合はFalse。
871 :rtype: str or bool
872 """
873
874 print("tktts.speak_dialogue(): Generate audio files:")
875 tts_engine = str(_get_attr(args, "tts", "")).lower()
876 tts = get_tts(tts_engine)
877 if tts is None:
878 return False
879
880 config = TTS_ENGINES.get(tts_engine)
881 if config is None:
882 return False
883
884 outfile = _get_attr(args, "outfile", "") or ""
885 is_save_mode = bool(outfile)
886 monologue = bool(_get_attr(args, "monologue", False))
887 speak_rate = _get_attr(args, "speak_rate", 150)
888 tinterval = float(_get_attr(args, "tinterval", 0.5) or 0.0)
889 voices = _get_attr(args, "voices", "") or ""
890 speakers = speakers or {}
891 replacements = replacements or {}
892
893 print("\nspeak_dialogue:")
894 print(
895 f" tts_engine : {tts_engine} is monologue: {monologue} "
896 f"speak rate: {speak_rate} tinterval: {tinterval}"
897 )
898 print(f" voices : {voices}")
899 print(f" outfile : {outfile}" if is_save_mode else " is_save_mode: False")
900
901 if voice_map is None or isinstance(voice_map, str):
902 # GUIなどから単一の音声名が文字列で渡された場合も、話者マップへ
903 # 変換してバックエンドへ渡す。WinRTバックエンド側で音声名を
904 # speakerとして正規化すると、空白を含む表示名が切れる実装との
905 # 互換問題を避けられる。
906 selected_voices = voice_map if isinstance(voice_map, str) else voices
907 target_voices = get_speaker_dict(
908 tts_engine,
909 dialogue,
910 selected_voices,
911 default_voicevox_voice=default_voicevox_voice,
912 default_pyttsx3_voice=default_pyttsx3_voice,
913 default_winrt_voice=default_winrt_voice,
914 default_aqt_preset=default_aqt_preset,
915 default_optnai_voice=default_optnai_voice,
916 default_elevenlabs_voice=default_elevenlabs_voice,
917 default_gemini_voice=default_gemini_voice,
918 )
919 else:
920 target_voices = voice_map
921
922 if target_voices is None:
923 return False
924
925 if not is_save_mode and not config.get("direct_playback", False):
926 print("❌ このエンジンではファイル保存が必要です。--outfile を指定してください。")
927 return False
928
929 temp_dir_name = _get_attr(args, "temp_dir", None)
930 if not temp_dir_name:
931 print("❌ 一時ファイル保存先が必要です。--temp_dir を指定してください。")
932 return False
933 temp_dir = create_temp_dir(temp_dir_name)
934
935 call_kwargs = {
936 "dialogue": dialogue or [],
937 "replacements": replacements,
938 "target_voices": target_voices,
939 "speakers": speakers,
940 "temp_dir": temp_dir,
941 "outfile": outfile,
942 "ext": config["ext"],
943 "cfg": args,
944 }
945
946 if tts_engine == "pyttsx3":
947 call_kwargs["speak_rate"] = _effective_pyttsx3_rate(args)
948 elif tts_engine in ("winrt", "onecore"):
949 call_kwargs["speak_rate"] = _effective_winrt_rate(args)
950 elif tts_engine == "voicevox":
951 call_kwargs["endpoint"] = endpoint or _get_attr(args, "endpoint", None)
952 elif tts_engine in ("qwen3", "qwen"):
953 call_kwargs.update({
954 "language": _get_attr(args, "qwen3_language", None),
955 "model_id": _get_attr(args, "qwen3_model_id", None),
956 "device": _get_attr(args, "qwen3_device", None),
957 "dtype": _get_attr(args, "qwen3_dtype", None),
958 })
959 elif tts_engine in ("qwen_api", "qwen-api"):
960 call_kwargs.update({
961 "server": _get_attr(args, "qwen_api_server", None),
962 "language": _get_attr(args, "qwen3_language", None),
963 "model_id": _get_attr(args, "qwen3_model_id", None),
964 "instruct": _get_attr(args, "qwen3_instruct", None),
965 "timeout": _get_attr(args, "qwen_api_timeout", None),
966 })
967 elif tts_engine in ("irodori", "irodori-tts"):
968 call_kwargs.update({
969 "caption": _get_attr(args, "irodori_caption", None),
970 "ref_wav": _get_attr(args, "irodori_ref_wav", None),
971 "ref_wavs": _get_attr(args, "irodori_ref_wavs", None),
972 "model_id": _get_attr(args, "irodori_model_id", None),
973 "device": _get_attr(args, "irodori_device", None),
974 "precision": _get_attr(args, "irodori_precision", None),
975 })
976 elif tts_engine in ("irodori_api", "irodori-api"):
977 call_kwargs.update({
978 "server": _get_attr(args, "irodori_api_server", None),
979 "caption": _get_attr(args, "irodori_caption", None),
980 "num_steps": _get_attr(args, "irodori_num_steps", None),
981 "duration_scale": _get_attr(args, "irodori_duration_scale", None),
982 "timeout": _get_attr(args, "irodori_api_timeout", None),
983 "sway": _get_attr(args, "irodori_api_sway", None),
984 "sway_coeff": _get_attr(args, "irodori_api_sway_coeff", None),
985 })
986 elif tts_engine in ("aquestalkplayer", "atp"):
987 call_kwargs["aquestalk_path"] = _get_attr(args, "aquestalk_path", None)
988 elif tts_engine == "openai":
989 call_kwargs["instruction"] = _get_attr(args, "instruction", None)
990 elif tts_engine == "gemini":
991 call_kwargs.update({
992 "instruction": _get_attr(args, "instruction", None),
993 "tts_model": _get_attr(args, "gemini_model", None),
994 "api_key": (
995 api_key
996 or _get_attr(args, "gemini_api_key", None)
997 or _get_attr(args, "api_key", None)
998 ),
999 })
1000 elif tts_engine in ("edge", "edge_tts", "edge-tts"):
1001 call_kwargs.update({
1002 "rate": _get_attr(args, "edge_rate", None),
1003 "volume": _get_attr(args, "edge_volume", None),
1004 "pitch": _get_attr(args, "edge_pitch", None),
1005 })
1006 elif tts_engine in ("elevenlabs", "eleven"):
1007 call_kwargs.update({
1008 "api_key": (
1009 api_key
1010 or _get_attr(args, "elevenlabs_api_key", None)
1011 or _get_attr(args, "api_key", None)
1012 ),
1013 "model_id": (
1014 _get_attr(args, "elevenlabs_model_id", None)
1015 or _get_attr(args, "model_id", None)
1016 ),
1017 "voice_settings": _elevenlabs_voice_settings(args),
1018 "output_format": _get_attr(args, "elevenlabs_output_format", None),
1019 "optimize_streaming_latency": _get_attr(
1020 args, "elevenlabs_optimize_streaming_latency", None
1021 ),
1022 "language_code": _get_attr(args, "elevenlabs_language_code", None),
1023 })
1024
1025 print(f"\n⚙️ {tts_engine.upper()}で音声ファイルを生成中...")
1026 try:
1027 result = _call_backend(tts.speak_dialogue, **call_kwargs)
1028 success, tmpfiles = result
1029 except Exception as e:
1030 print(f"❌ {tts_engine} の speak_dialogue 呼び出しエラー: {e}")
1031 traceback.print_exc()
1032 return False
1033
1034 if not success:
1035 return False
1036
1037 # pyttsx3 / WinRT の直接再生はバックエンド側で完了する。
1038 if not is_save_mode:
1039 return True
1040
1041 tmpfiles = list(tmpfiles or [])
1042 if not tmpfiles:
1043 if os.path.isfile(outfile) and os.path.getsize(outfile) > 0:
1044 return outfile
1045 print("❌ 結合対象の一時音声ファイルが生成されませんでした。")
1046 return False
1047
1048 final_format = _infer_output_format(outfile, output_format, config["ext"])
1049 output_parent = os.path.dirname(os.path.abspath(outfile))
1050 if output_parent:
1051 os.makedirs(output_parent, exist_ok=True)
1052
1053 print(" ファイルを結合中...")
1054 combined_audio = AudioSegment.silent(duration=0)
1055 try:
1056 for tmpfile in tmpfiles:
1057 segment = AudioSegment.from_file(tmpfile, format=config["ext"])
1058 combined_audio += segment
1059 if tinterval > 0:
1060 print(f" insert {tinterval} sec interval")
1061 combined_audio += AudioSegment.silent(duration=int(tinterval * 1000))
1062
1063 combined_audio.export(outfile, format=final_format)
1064 print(f"✅ 出力音声を {outfile} に保存しました (形式: {final_format})。")
1065 except Exception as e:
1066 print(f"❌ 音声ファイルの結合または保存に失敗しました: {e}")
1067 traceback.print_exc()
1068 return False
1069 finally:
1070 time.sleep(0.1)
1071 print("🗑️ 一時ファイルを削除中...")
1072 for filename in tmpfiles:
1073 try:
1074 if os.path.isfile(filename):
1075 os.remove(filename)
1076 except OSError as e:
1077 print(f" [warn] 一時ファイルを削除できません: {filename}: {e}")
1078 try:
1079 if os.path.isdir(temp_dir) and not os.listdir(temp_dir):
1080 os.rmdir(temp_dir)
1081 except OSError:
1082 pass
1083
1084 return outfile
1085
1086
1087class tkTTS:
1088 """
1089 複数のTTSエンジンを扱うためのラッパークラス。
1090
1091 選択されたTTSエンジンを初期化し、音声合成関連の様々なユーティリティ機能を提供します。
1092 設定はSimpleNamespaceオブジェクトを通じて管理されます。
1093 """
1094 def __init__(self, tts_name: str = None, config: SimpleNamespace = None):
1095 """
1096 tkTTSクラスのコンストラクタ。
1097
1098 :param tts_name: 初期化するTTSエンジンの名前。
1099 :type tts_name: str, optional
1100 :param config: 設定値を含むSimpleNamespaceオブジェクト。
1101 `endpoint`, `aquestalk_path`, `elevenlabs_api_key`, `gemini_api_key`, `api_key`
1102 などの属性を持つことができます。
1103 :type config: types.SimpleNamespace, optional
1104 """
1105 self.tts_name = tts_name
1106 self.tts = None
1107 self.config = config if config is not None else SimpleNamespace()
1108 self.endpoint = getattr(self.config, "endpoint", None)
1109 self.aquestalk_path = getattr(self.config, "aquestalk_path", None)
1110 self.api_key = (
1111 getattr(self.config, "elevenlabs_api_key", None)
1112 or getattr(self.config, "gemini_api_key", None)
1113 or getattr(self.config, "api_key", None)
1114 )
1115
1116 if tts_name is not None:
1117 self.set_engine(tts_name)
1118
1119 def _default_endpoint(self):
1120 """
1121 現在のTTSエンジンに応じたデフォルトのエンドポイントURLを返します。
1122
1123 :returns: デフォルトのエンドポイントURL。
1124 :rtype: str or None
1125 """
1126 if self.tts_name in ("irodori_api", "irodori-api"):
1127 return getattr(self.config, "irodori_api_server", None)
1128 if self.tts_name in ("qwen_api", "qwen-api"):
1129 return getattr(self.config, "qwen_api_server", None)
1130 return getattr(self.config, "endpoint", None)
1131
1132 def set_engine(self, tts_name: str):
1133 """
1134 使用するTTSエンジンを設定します。
1135
1136 :param tts_name: 設定するTTSエンジンの名前。
1137 :type tts_name: str
1138 """
1139 self.tts_name = str(tts_name).lower()
1140 self.tts = get_tts(self.tts_name)
1141
1142 def set_endpoint(self, endpoint: str):
1143 """
1144 TTSエンジンのエンドポイントURLを設定します。
1145
1146 :param endpoint: 設定するエンドポイントURL。
1147 :type endpoint: str
1148 """
1149 self.endpoint = endpoint
1150 setattr(self.config, "endpoint", endpoint)
1151
1152 def set_aquestalk_path(self, aquestalk_path: str):
1153 """
1154 AquesTalk Playerの実行パスを設定します。
1155
1156 :param aquestalk_path: AquesTalk Playerの実行ファイルパス。
1157 :type aquestalk_path: str
1158 """
1159 self.aquestalk_path = aquestalk_path
1160 setattr(self.config, "aquestalk_path", aquestalk_path)
1161
1162 def set_api_key(self, api_key: str):
1163 """
1164 APIベースのTTSエンジンで使用するAPIキーを設定します。
1165
1166 このAPIキーはElevenLabsとGeminiの設定にも反映されます。
1167
1168 :param api_key: 設定するAPIキー。
1169 :type api_key: str
1170 """
1171 self.api_key = api_key
1172 setattr(self.config, "elevenlabs_api_key", api_key)
1173
1174 def get_tts_name(self, tts_name: str = None):
1175 """
1176 現在のTTSエンジン名、または引数で指定されたTTSエンジン名を返します。
1177
1178 :param tts_name: 返すTTSエンジン名。Noneの場合、インスタンスの現在のエンジン名を返します。
1179 :type tts_name: str, optional
1180 :returns: TTSエンジンの名前。
1181 :rtype: str
1182 """
1183 if tts_name is None: return self.tts_name
1184 return tts_name
1185
1186 def get_default_voice(self, tts_name: str = None):
1187 """
1188 指定されたTTSエンジンのデフォルトの音声名を返します。
1189
1190 :param tts_name: デフォルト音声名を取得するTTSエンジン。Noneの場合、インスタンスの現在のエンジン名を使用します。
1191 :type tts_name: str, optional
1192 :returns: デフォルトの音声名、またはNone(エンジンが見つからない場合)。
1193 :rtype: str or None
1194 """
1195 tts_def = TTS_ENGINES.get(self.get_tts_name(tts_name), None)
1196 if tts_def:return tts_def["default_voice"]
1197 return None
1198
1199 def normalize_speaker(self, speaker, tts_name: str = None):
1200 """
1201 話者ラベルを正規化します。
1202
1203 モジュールレベルの `normalize_speaker` 関数を呼び出します。
1204
1205 :param speaker: 正規化する話者名または音声名。
1206 :type speaker: str or None
1207 :param tts_name: 使用するTTSエンジンの名前(現在は未使用)。
1208 :type tts_name: str, optional
1209 :returns: 正規化された話者名。入力がNoneの場合はNone。
1210 :rtype: str or None
1211 """
1212 if tts_name is None: tts_name = self.tts_name
1213 return normalize_speaker(speaker, tts_name)
1214
1215 def get_available_voices_info(self, tts_name: str = None, endpoint: str = None, api_key: str = None):
1216 """
1217 指定されたTTSエンジンで利用可能な音声の詳細情報を取得します。
1218
1219 モジュールレベルの `get_available_voices_info` 関数を呼び出します。
1220 引数がNoneの場合、インスタンスの設定 (`self.tts_name`, `self.endpoint`, `self.api_key`) を使用します。
1221
1222 :param tts_name: 音声情報を取得するTTSエンジンの名前。
1223 :type tts_name: str, optional
1224 :param endpoint: APIベースのTTSエンジンで使用するエンドポイントURL。
1225 :type endpoint: str, optional
1226 :param api_key: APIベースのTTSエンジンで使用するAPIキー。
1227 :type api_key: str, optional
1228 :returns: 利用可能な音声の詳細情報。
1229 :rtype: Any or None
1230 """
1231 if tts_name is None:
1232 tts_name = self.tts_name
1233 if endpoint is None:
1234 endpoint = (
1235 (
1236 getattr(self.config, "irodori_api_server", None)
1237 if tts_name in ("irodori_api", "irodori-api")
1238 else getattr(self.config, "qwen_api_server", None)
1239 if tts_name in ("qwen_api", "qwen-api")
1240 else self.endpoint
1241 )
1242 )
1243 if api_key is None:
1244 api_key = self.api_key
1245 return get_available_voices_info(tts_name, endpoint=endpoint, api_key=api_key)
1246
1247 def get_available_voices(self, tts_name: str = None, endpoint: str = None, api_key: str = None):
1248 """
1249 指定されたTTSエンジンで利用可能な音声のリストを取得します。
1250
1251 モジュールレベルの `get_available_voices` 関数を呼び出します。
1252 引数がNoneの場合、インスタンスの設定 (`self.tts_name`, `self.endpoint`, `self.api_key`) を使用します。
1253
1254 :param tts_name: 音声リストを取得するTTSエンジンの名前。
1255 :type tts_name: str, optional
1256 :param endpoint: APIベースのTTSエンジンで使用するエンドポイントURL。
1257 :type endpoint: str, optional
1258 :param api_key: APIベースのTTSエンジンで使用するAPIキー。
1259 :type api_key: str, optional
1260 :returns: 利用可能な音声名のリスト。
1261 :rtype: list[str] or None
1262 """
1263 if tts_name is None:
1264 tts_name = self.tts_name
1265 if endpoint is None:
1266 endpoint = (
1267 (
1268 getattr(self.config, "irodori_api_server", None)
1269 if tts_name in ("irodori_api", "irodori-api")
1270 else getattr(self.config, "qwen_api_server", None)
1271 if tts_name in ("qwen_api", "qwen-api")
1272 else self.endpoint
1273 )
1274 )
1275 if api_key is None:
1276 api_key = self.api_key
1277 return get_available_voices(tts_name, endpoint=endpoint, api_key=api_key)
1278
1279 def list_available_voices(self, tts_name: str = None, endpoint: str = None, api_key: str = None):
1280 """
1281 指定されたTTSエンジンで利用可能な音声のリストを標準出力に表示します。
1282
1283 モジュールレベルの `list_available_voices` 関数を呼び出します。
1284 引数がNoneの場合、インスタンスの設定 (`self.tts_name`, `self.endpoint`, `self.api_key`) を使用します。
1285
1286 :param tts_name: 音声リストを表示するTTSエンジンの名前。
1287 :type tts_name: str, optional
1288 :param endpoint: APIベースのTTSエンジンで使用するエンドポイントURL。
1289 :type endpoint: str, optional
1290 :param api_key: APIベースのTTSエンジンで使用するAPIキー。
1291 :type api_key: str, optional
1292 :returns: 処理が成功した場合はTrue、失敗した場合はFalse。
1293 :rtype: bool
1294 """
1295 if tts_name is None:
1296 tts_name = self.tts_name
1297 if endpoint is None:
1298 endpoint = (
1299 (
1300 getattr(self.config, "irodori_api_server", None)
1301 if tts_name in ("irodori_api", "irodori-api")
1302 else getattr(self.config, "qwen_api_server", None)
1303 if tts_name in ("qwen_api", "qwen-api")
1304 else self.endpoint
1305 )
1306 )
1307 if api_key is None:
1308 api_key = self.api_key
1309 return list_available_voices(tts_name, endpoint=endpoint, api_key=api_key)
1310
1311 def show_voice_map(self, infile: str, voices: str, VOICE_MAPS: dict, is_monologue: bool, tts_name: str = None, endpoint: str = None):
1312 """
1313 入力ファイルから話者を解析し、現在の音声マップを表示します。
1314
1315 これは主にデバッグや設定確認のために使用されます。
1316
1317 :param infile: 解析対象の入力ファイルパス。'clip' も指定可能です。
1318 :type infile: str
1319 :param voices: 話者と音声の割り当てをセミコロン区切りで指定する文字列。
1320 例: "話者A=Voice1;話者B=Voice2"
1321 または、カンマ区切りで音声名を直接指定する文字列。
1322 例: "Voice1,Voice2,Voice3"
1323 :type voices: str
1324 :param VOICE_MAPS: TTSエンジンごとの音声マップを格納する辞書。
1325 例: `{"pyttsx3": {"speaker1": "Zira"}, "voicevox": {"speaker2": "四国めたん"}}`
1326 :type VOICE_MAPS: dict
1327 :param is_monologue: テキストが独話形式(話者指定なし)かどうか。
1328 :type is_monologue: bool
1329 :param tts_name: 使用するTTSエンジンの名前。Noneの場合、インスタンスの現在のエンジン名を使用します。
1330 :type tts_name: str, optional
1331 :param endpoint: APIベースのTTSエンジンで使用するエンドポイントURL。
1332 :type endpoint: str, optional
1333 :returns: 処理が成功した場合はTrue、失敗した場合はFalse。
1334 :rtype: bool
1335 """
1336 print()
1337 print(f"[{infile}]を解析します:")
1338 dialogue = self.load_text(infile, is_monologue, wait_for_clipboard = False)
1339 if not dialogue:
1340 print("エラー: 有効なテキストデータが取得できませんでした。")
1341 if not is_monologue:
1342 print(" 対話形式でない場合は --monologue=1 オプションをつけてください。")
1343 return False
1344
1345 speakers_in_file = self.get_speakers_from_dialogue(dialogue)
1346 print(f" Speakers in [{infile}]")
1347 for idx, sp in enumerate(speakers_in_file):
1348 print(f" {idx:02d}: {sp}")
1349
1350 current_voice_map = self.update_voice_map(voice_map = VOICE_MAPS,
1351 voices = voices, speakers = speakers_in_file)
1352
1353 print()
1354 print(f"Voice map:")
1355 print(f" {'Speaker':<20} => Voice")
1356 for key, val in current_voice_map.items():
1357 if type(key) is str:
1358 print(f" {key:<20} => {val}")
1359 for key, val in current_voice_map.items():
1360 if type(key) is not str and type(key) is not int:
1361 if key is None: key = 'None'
1362 print(f" {key:<20} => {val}")
1363 for key, val in current_voice_map.items():
1364 if type(key) is int:
1365 print(f" {key:<20} => {val}")
1366
1367 print()
1368 print(f"[{infile}] から検出された話者:")
1369 for s in sorted(speakers_in_file):
1370 if s is None or s == "":
1371 voice = current_voice_map.get(s, None)
1372 if voice is None: voice = current_voice_map.get(0, None)
1373 print(f" (独話): {voice}")
1374 else:
1375 ns = self.normalize_speaker(s)
1376 voice = current_voice_map.get(ns, '未設定')
1377 print(f" (speaker) {s}: {ns}: (voice) {voice}")
1378 return True
1379
1380
1381 def load_text(self, input_path: str, monologue: bool = False, wait_for_clipboard: bool = True):
1382 """
1383 入力元 ('clip' またはファイルパス) からテキストを取得し、(speaker, text) リストを返します。
1384
1385 モジュールレベルの `load_text` 関数を呼び出します。
1386
1387 :param input_path: テキストの入力元。'clip' の場合はクリップボードから、
1388 それ以外の文字列はファイルパスとして扱います。
1389 :type input_path: str
1390 :param monologue: テキストが独話形式(話者指定なし)かどうか。
1391 :type monologue: bool
1392 :param wait_for_clipboard: input_pathが'clip'の場合、クリップボードにテキストが
1393 コピーされるまで待機するかどうか。
1394 :type wait_for_clipboard: bool
1395 :returns: (話者名, テキスト) のタプルを要素とするリスト。
1396 読み込みに失敗した場合はNoneを返します。
1397 :rtype: list[tuple[str or None, str]] or None
1398 """
1399 return load_text(input_path, monologue = monologue, wait_for_clipboard = wait_for_clipboard)
1400
1401 def get_speakers_from_dialogue(self, dialogue: list):
1402 """
1403 ダイアログリストからユニークな話者名のリストを抽出します。
1404
1405 :param dialogue: (話者名, テキスト) のタプルを要素とするリスト。
1406 :type dialogue: list[tuple[str or None, str]]
1407 :returns: ダイアログに含まれるユニークな話者名のリスト。
1408 :rtype: list[str or None]
1409 """
1410 return list(set(s for s, _ in dialogue))
1411
1412 def parse_kv_string(self, kv_string: str, keys: list = [], allow_no_key_kv_string: bool = False):
1413 """
1414 "key=val;key=val" 形式の文字列を辞書に変換します。
1415
1416 モジュールレベルの `parse_kv_string` 関数とは異なり、話者名と音声名のマッピングに特化しています。
1417 "=" が含まれないアイテムも、`keys` 引数のインデックスに基づいて辞書に追加されます。
1418 また、正規化された話者名と、それに対応する音声名をマップします。
1419
1420 :param kv_string: "key=val;key=val" 形式の文字列、またはセミコロン区切りの音声名の文字列。
1421 :type kv_string: str
1422 :param keys: `kv_string` が "key=val" 形式でない場合に、値に割り当てるキーのリスト。
1423 (読み上げファイルから抽出された話者リストなど)
1424 :type keys: list
1425 :param allow_no_key_kv_string: "=" を含まないアイテムを許容し、`keys` に基づいて処理するかどうか。
1426 :type allow_no_key_kv_string: bool
1427 :returns: 話者名と音声名をマッピングした辞書。
1428 :rtype: dict[str or int, str]
1429 """
1430
1431 print()
1432 print("parse_kv_string:")
1433 print(" kv_string:", kv_string)
1434 print(" keys:", keys)
1435
1436 if not kv_string: return {}
1437 nkeys = len(keys)
1438
1439 speakers_kv = []
1440 d = {}
1441 idx = 0
1442# kv_stringのspeaker
1443 for item in kv_string.split(";"):
1444 if "=" in item:
1445 k, voice = item.split("=", 1)
1446 speaker = self.normalize_speaker(k.strip())
1447 d[speaker] = voice
1448 if voice not in d.keys(): d[voice] = voice
1449 if speaker not in speakers_kv:
1450 speakers_kv.append(speaker)
1451# print("478 add:", speaker)
1452 elif allow_no_key_kv_string:
1453# = が無い場合は整数idxの辞書をつくる
1454 if "*" in item or item.strip() == "": continue
1455
1456# ユーザ指定辞書keysで与えられたspeaker(読み上げファイルのspeaker)をkv_stringにマップ
1457 if idx < nkeys:
1458 voice = item
1459# speaker = self.normalize_speaker(voice)
1460# voice = self.normalize_speaker(keys[idx])
1461 speaker = self.normalize_speaker(keys[idx])
1462 d[speaker] = voice
1463 if voice not in d.keys(): d[voice] = voice
1464 if speaker not in speakers_kv:
1465 speakers_kv.append(speaker)
1466 d[idx] = item
1467 idx += 1
1468
1469# ユーザ指定辞書keysで与えられたspeaker(読み上げファイルのspeaker)をkv_stringにマップ
1470 for idx, speaker_keys in enumerate(keys):
1471 speaker_keys = self.normalize_speaker(speaker_keys)
1472 if speaker_keys in d.keys(): continue
1473
1474 d[speaker_keys] = speaker_keys
1475
1476 return d
1477
1478 def update_voice_map(self, voice_map: dict = {}, voices: str = "", speakers: list = {}):
1479 """
1480 現在のTTSエンジンの音声マップを更新します。
1481
1482 `voices` 文字列によって明示的に指定された割り当てが優先され、
1483 その後、`speakers` リストに基づいてデフォルトの割り当てが適用されます。
1484
1485 :param voice_map: 既存のTTSエンジンごとの音声マップ。
1486 :type voice_map: dict
1487 :param voices: 話者と音声の割り当てをセミコロン区切りで指定する文字列。
1488 例: "話者A=Voice1;話者B=Voice2"
1489 または、カンマ区切りで音声名を直接指定する文字列。
1490 例: "Voice1,Voice2,Voice3"
1491 :type voices: str
1492 :param speakers: ダイアログから検出された話者名のリスト。
1493 `voices` で指定されていない話者にデフォルトの音声名を割り当てるために使用されます。
1494 :type speakers: list[str or None]
1495 :returns: 更新された話者名と音声名のマッピング辞書。
1496 :rtype: dict[str or None or int, str]
1497 """
1498 current_voice_map = voice_map.get(self.tts_name, {}).copy()
1499 print(f" Voice maps for [{self.tts_name}] 環境からのDefault指定があれば: ", current_voice_map)
1500
1501 voices = voices.strip()
1502 if voices == "":
1503 print(f"voicesが空白です。speakersをそのまま利用します。")
1504 for idx, sp in enumerate(speakers):
1505 sp = self.normalize_speaker(sp)
1506 current_voice_map[sp] = sp
1507 current_voice_map[idx] = sp
1508 else:
1509 print(f"voicesから音声マップを読み込み中: ", voices)
1510# 読み上げファイルから抽出したspeakersは使わない
1511# voices_override = self.parse_kv_string(voices, {}, allow_no_key_kv_string = True)
1512 voices_override = self.parse_kv_string(voices, speakers, allow_no_key_kv_string = True)
1513 current_voice_map.update(voices_override)
1514
1515 current_voice_map[None] = current_voice_map.get(0, None)
1516 current_voice_map[""] = current_voice_map.get(0, None)
1517
1518 return current_voice_map
1519
1520 def speak_dialogue(self, dialogue: list = None, voice_map: dict = None, speakers: dict = None,
1521 replacements: dict = None, endpoint: str = None, api_key: str = None,
1522 output_format: str = None, config: SimpleNamespace = None):
1523 """
1524 現在のTTSエンジンで音声生成を行い、結合して保存または直接再生します。
1525
1526 モジュールレベルの `speak_dialogue` 関数を呼び出します。
1527 引数がNoneの場合、インスタンスの設定 (`self.config`, `self.endpoint`, `self.api_key`) を使用します。
1528
1529 :param dialogue: (話者名, テキスト) のタプルを要素とするリスト。
1530 :type dialogue: list[tuple[str or None, str]], optional
1531 :param voice_map: 話者名と音声名のマッピング辞書。
1532 :type voice_map: dict[str or None, str], optional
1533 :param speakers: (未使用) 話者リスト。
1534 :type speakers: dict, optional
1535 :param replacements: テキストの置換ルールを定義する辞書。
1536 :type replacements: dict, optional
1537 :param endpoint: APIベースのTTSエンジンで使用するエンドポイントURL。
1538 :type endpoint: str, optional
1539 :param api_key: APIベースのTTSエンジンで使用するAPIキー。
1540 :type api_key: str, optional
1541 :param output_format: 出力ファイルのフォーマット。
1542 :type output_format: str, optional
1543 :param config: TTSエンジンの設定値を含むNamespaceオブジェクト。
1544 :type config: types.SimpleNamespace, optional
1545 :returns: 音声出力に成功した場合、ファイル保存モードでは出力ファイルのパス、
1546 直接再生モードではTrue。失敗した場合はFalse。
1547 :rtype: str or bool
1548 """
1549 if endpoint is None:
1550 endpoint = self.endpoint
1551 if api_key is None:
1552 api_key = self.api_key
1553 if config is None:
1554 config = self.config
1555 return speak_dialogue(
1556 config,
1557 dialogue,
1558 voice_map,
1559 speakers=speakers,
1560 replacements=replacements,
1561 default_voicevox_voice=self.get_default_voice("voicevox"),
1562 default_pyttsx3_voice=self.get_default_voice("pyttsx3"),
1563 default_winrt_voice=self.get_default_voice("winrt"),
1564 default_aqt_preset=self.get_default_voice("aqt"),
1565 default_optnai_voice=self.get_default_voice("openai"),
1566 default_elevenlabs_voice=self.get_default_voice("elevenlabs"),
1567 default_gemini_voice=self.get_default_voice("gemini"),
1568 endpoint=endpoint,
1569 api_key=api_key,
1570 output_format=output_format,
1571 )