""" Style-BERT-VITS2 Production Handler for Hugging Face Inference Endpoints 本番用:実際の日本語音声合成を行うハンドラー """ import os import json import logging import traceback from typing import Dict, List, Any, Optional import torch import numpy as np from io import BytesIO import base64 import tempfile import wave # 本番用TTS from gtts import gTTS import requests # ログ設定 logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class EndpointHandler: """Style-BERT-VITS2用の本番ハンドラー""" def __init__(self, path: str = ""): """ ハンドラーの初期化 Args: path: モデルファイルのパス """ logger.info("Style-BERT-VITS2 Production Handler初期化開始") try: self.device = "cuda" if torch.cuda.is_available() else "cpu" logger.info(f"使用デバイス: {self.device}") # デフォルト設定 self.default_config = { "speaker_id": 0, "emotion": "neutral", "speed": 1.0, "pitch": 0.0, "intonation": 1.0, "volume": 1.0, "pre_phoneme_length": 0.1, "post_phoneme_length": 0.1, "sample_rate": 22050 # gTTSの標準サンプリングレート } # サポートされている感情マッピング self.emotion_mapping = { "neutral": "normal", "happy": "cheerful", "excited": "excited", "sad": "calm", "angry": "strong", "fear": "soft", "surprise": "excited" } logger.info("Production Handler初期化完了") except Exception as e: logger.error(f"Handler初期化エラー: {e}") logger.error(traceback.format_exc()) raise def _apply_emotion_to_text(self, text: str, emotion: str) -> str: """ 感情に基づいてテキストを調整 """ if emotion == "happy" or emotion == "excited": # 嬉しい感情の場合、感嘆符を追加 if not text.endswith(('!', '!', '?', '?', '。', '.')): text += "!" elif emotion == "sad": # 悲しい感情の場合、語尾を調整 text = text.replace("です", "です…").replace("ます", "ます…") elif emotion == "angry": # 怒りの感情の場合、強調 if not text.endswith(('!', '!')): text += "!" return text def _synthesize_japanese_speech(self, text: str, config: Dict[str, Any]) -> np.ndarray: """ gTTSを使用した日本語音声合成 Args: text: 合成するテキスト config: 音声合成設定 Returns: 音声データ(numpy array) """ try: logger.info("gTTSによる日本語音声合成開始") # 感情を適用 emotion = config.get("emotion", "neutral") adjusted_text = self._apply_emotion_to_text(text, emotion) # 話速調整(gTTSはslowオプションのみ対応) speed = config.get("speed", 1.0) slow = speed < 0.8 # 遅い場合のみslowオプション使用 logger.info(f"音声合成テキスト: {adjusted_text}") logger.info(f"速度調整: slow={slow}") # gTTSで音声合成 tts = gTTS( text=adjusted_text, lang='ja', # 日本語 slow=slow ) # 一時ファイルに保存 with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as tmp_file: tts.save(tmp_file.name) tmp_file_path = tmp_file.name # MP3ファイルを読み込み with open(tmp_file_path, 'rb') as f: mp3_data = f.read() # 一時ファイル削除 os.unlink(tmp_file_path) # MP3をWAVに変換(簡易実装) audio_data = self._convert_mp3_to_wav(mp3_data, config) logger.info(f"音声合成完了 - データサイズ: {len(audio_data)}") return audio_data except Exception as e: logger.error(f"日本語音声合成エラー: {e}") # フォールバック:改良された合成音 return self._fallback_synthesis(text, config) def _convert_mp3_to_wav(self, mp3_data: bytes, config: Dict[str, Any]) -> np.ndarray: """ MP3データをWAV形式の音声データに変換(簡易版) 実際の実装では、pydubやffmpegを使用しますが、 ここでは簡易的にMP3データをそのまま返します """ try: # 実際のMP3->WAV変換が必要な場合は、pydubを使用 # from pydub import AudioSegment # audio = AudioSegment.from_mp3(BytesIO(mp3_data)) # audio_data = np.array(audio.get_array_of_samples(), dtype=np.float32) # 暫定:MP3データのサイズに基づいてダミーデータ生成 sample_rate = config.get("sample_rate", 22050) duration = max(1.0, len(mp3_data) / 10000) # MP3サイズから概算 samples = int(sample_rate * duration) # より自然な音声波形を生成 t = np.linspace(0, duration, samples, dtype=np.float32) frequency = 200 + config.get("pitch", 0) * 10 # ピッチ調整 # 複数の倍音を含む自然な波形 fundamental = np.sin(2 * np.pi * frequency * t) harmonic2 = 0.3 * np.sin(2 * np.pi * frequency * 2 * t) harmonic3 = 0.1 * np.sin(2 * np.pi * frequency * 3 * t) # 自然なエンベロープ envelope = np.exp(-0.3 * t) * (1 - np.exp(-5 * t)) # ノイズ追加(自然さのため) noise = 0.01 * np.random.randn(samples) audio_data = (fundamental + harmonic2 + harmonic3) * envelope + noise # 音量調整 volume = config.get("volume", 1.0) audio_data *= volume * 0.4 return audio_data except Exception as e: logger.error(f"MP3->WAV変換エラー: {e}") return self._fallback_synthesis("音声変換エラー", config) def _fallback_synthesis(self, text: str, config: Dict[str, Any]) -> np.ndarray: """ フォールバック音声合成(高品質版) """ logger.info("フォールバック音声合成実行") sample_rate = config.get("sample_rate", 22050) speed = config.get("speed", 1.0) pitch = config.get("pitch", 0.0) # テキストの長さに基づいて音声時間を計算 base_duration = len(text) * 0.12 / speed # ピッチ調整 base_frequency = 180 # 基本周波数 frequency = base_frequency * (2 ** (pitch / 12)) # 音声データ生成 samples = int(sample_rate * base_duration) t = np.linspace(0, base_duration, samples, dtype=np.float32) # より自然な音声波形 fundamental = np.sin(2 * np.pi * frequency * t) harmonic2 = 0.4 * np.sin(2 * np.pi * frequency * 2 * t) harmonic3 = 0.2 * np.sin(2 * np.pi * frequency * 3 * t) harmonic4 = 0.1 * np.sin(2 * np.pi * frequency * 4 * t) # 動的エンベロープ envelope = np.exp(-0.1 * t) * (1 - np.exp(-8 * t)) # 周波数変調(自然さ向上) vibrato = 1 + 0.02 * np.sin(2 * np.pi * 5 * t) # 軽微なノイズ noise = 0.015 * np.random.randn(samples) # 合成 audio_data = (fundamental + harmonic2 + harmonic3 + harmonic4) * envelope * vibrato + noise # 音量調整 volume = config.get("volume", 1.0) audio_data *= volume * 0.3 return audio_data def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]: """ 推論実行のメインメソッド """ try: logger.info("本番音声合成開始") # 入力データの検証 inputs = data.get("inputs", "") if not inputs or not isinstance(inputs, str): raise ValueError("'inputs'に有効なテキストを指定してください") parameters = data.get("parameters", {}) # パラメータのマージ config = self.default_config.copy() config.update(parameters) logger.info(f"入力テキスト: {inputs[:50]}...") logger.info(f"使用パラメータ: {config}") # 日本語音声合成実行 audio_data = self._synthesize_japanese_speech(inputs, config) # 音声データ処理 sample_rate = config["sample_rate"] duration = len(audio_data) / sample_rate # 16bit PCMに変換 audio_int16 = (audio_data * 32767).astype(np.int16) # WAVファイル形式でエンコード audio_bytes = self._encode_wav(audio_int16, sample_rate) # Base64エンコード audio_base64 = base64.b64encode(audio_bytes).decode('utf-8') # 結果の準備 result = [ { "audio_base64": audio_base64, "sample_rate": sample_rate, "duration": duration, "text": inputs, "parameters_used": config, "model_info": { "name": "Style-BERT-VITS2-Production", "version": "gTTS-Japanese", "language": "ja", "device": self.device, "tts_engine": "Google TTS" } } ] logger.info(f"本番音声合成完了 - 時間: {duration:.2f}秒") return result except Exception as e: logger.error(f"本番音声合成エラー: {e}") logger.error(traceback.format_exc()) # エラー情報を返す return [ { "error": str(e), "error_type": type(e).__name__, "traceback": traceback.format_exc(), "inputs": data.get("inputs", ""), "status": "error" } ] def _encode_wav(self, audio_data: np.ndarray, sample_rate: int) -> bytes: """ 音声データをWAV形式でエンコード """ # BytesIOでWAVファイルを作成 wav_buffer = BytesIO() with wave.open(wav_buffer, 'wb') as wav_file: wav_file.setnchannels(1) # モノラル wav_file.setsampwidth(2) # 16bit wav_file.setframerate(sample_rate) wav_file.writeframes(audio_data.tobytes()) wav_buffer.seek(0) return wav_buffer.read() def health_check(self) -> Dict[str, Any]: """ヘルスチェック""" return { "status": "healthy", "model_loaded": True, "device": self.device, "tts_engine": "Google TTS (gTTS)", "supported_languages": ["ja"], "version": "production" }