from flask import Flask, request, jsonify
import os
from google.cloud import texttospeech

app = Flask(__name__)

# 認証キーの設定
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/key/libertycall-main-7e4af202cdff.json"

# Google Cloud TTSクライアントの初期化
client = texttospeech.TextToSpeechClient()

@app.route('/tts', methods=['POST'])
def tts():
    data = request.get_json()
    text = data.get('text', '')

    if not text:
        return jsonify({'error': 'No text provided'}), 400

    synthesis_input = texttospeech.SynthesisInput(text=text)
    
    voice = texttospeech.VoiceSelectionParams(
        language_code="ja-JP",
        name="ja-JP-Wavenet-A",  # Wavenetモデルを指定
        ssml_gender=texttospeech.SsmlVoiceGender.FEMALE
    )

    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.MP3,
        speaking_rate=1.2  # 音声スピードを少し速く設定
    )

    try:
        # 音声生成
        response = client.synthesize_speech(
            request={"input": synthesis_input, "voice": voice, "audio_config": audio_config}
        )
        # 生成した音声データをaudio/mpegで返す
        return app.response_class(response.audio_content, mimetype='audio/mpeg')
    except Exception as e:
        return jsonify({'message': f'Error generating speech: {str(e)}'}), 500

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=5000)
