import speech_recognition as sr
import requests
import json
import pandas as pd
import os
from google.cloud import texttospeech
import playsound
import datetime


kakao_speech_url = "https://kakaoi-newtone-openapi.kakao.com/v1/recognize"
kakao_synthsize_url = "https://kakaoi-newtone-openapi.kakao.com/v1/synthesize"
rest_api_key = '카카오 api 키'
recog_headers = {
    "Content-Type": "application/octet-stream",
    "X-DSS-Service": "DICTATION",
    "Authorization": "KakaoAK " + rest_api_key
}

def voice_recognition():
    r = sr.Recognizer()

    with sr.Microphone(sample_rate=16000) as source:
        r.adjust_for_ambient_noise(source)
        print("마이크가 활성화되었습니다.")
        audio = r.listen(source, timeout=4)

    return audio

def kakao_api(audio):
    res = requests.post(kakao_speech_url, headers=recog_headers, data=audio.get_raw_data())
    result_json_string = res.text[res.text.index('{"type":"finalResult"'):res.text.rindex('}')+1]
    result = json.loads(result_json_string)
    print("나 :"+ result['value'])
    return result['value']


def match_answer(question):
    answer = ""
    if "영실" in question:
        answer = "네 지평님 말씀하세요."
    return answer


def make_voice(answer):
    client = texttospeech.TextToSpeechClient()
    input_text = texttospeech.SynthesisInput(text=answer)
    # Note: the voice can also be specified by name.
    # Names of voices can be retrieved with client.list_voices().
    voice = texttospeech.VoiceSelectionParams(
        language_code="ko-KR",
        name="ko-KR-Wavenet-A",
        ssml_gender=texttospeech.SsmlVoiceGender.MALE,
    )

    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.MP3
    )

    response = client.synthesize_speech(
        request={"input": input_text, "voice": voice, "audio_config": audio_config}
    )

    with open("output.mp3", "wb") as out:
        out.write(response.audio_content)
    print("영실: "+answer)
    playsound.playsound("output.mp3")


if __name__ == "__main__":
    audio = voice_recognition()
    question = kakao_api(audio)
    answer = match_answer(question)
    make_voice(answer)
