오디오 출력으로 인텐트 인식

애플리케이션에 최종 사용자에게 응답하는 봇이 필요한 경우가 많습니다. Dialogflow는 DeepMind WaveNet으로 구동되는 Cloud Text-to-Speech를 사용하여 에이전트에서 음성 응답을 생성할 수 있습니다. 인텐트 텍스트 응답에서 오디오로의 이러한 변환을 오디오 출력, 음성 합성, 텍스트 음성 변환 또는 TTS라고 합니다.

이 가이드에서는 인텐트를 감지할 때 입력 및 출력에 오디오를 사용하는 예시를 제공합니다. 이 사용 사례는 전적으로 음성 인터페이스로만 사용자와 통신하는 앱을 개발할 때 일반적입니다.

지원되는 언어 목록은 언어 페이지에서 TTS 열을 참조하세요.

시작하기 전에

이 기능은 최종 사용자 상호작용에 API를 사용할 때만 적용됩니다. 통합을 사용 중인 경우 이 가이드를 건너뛸 수 있습니다.

이 가이드를 읽기 전에 다음을 수행해야 합니다.

  1. Dialogflow 기본사항 읽기
  2. 설정 단계 수행

에이전트 만들기

아직 에이전트를 만들지 않은 경우 지금 만듭니다.

  1. Dialogflow ES 콘솔로 이동합니다.
  2. 로그인 메시지가 표시되면 Dialogflow 콘솔에 로그인합니다. 자세한 내용은 Dialogflow 콘솔 개요를 참조하세요.
  3. 왼쪽 사이드바 메뉴에서 에이전트 만들기를 클릭합니다. 이미 다른 에이전트가 있는 경우 에이전트 이름을 클릭하고 아래로 스크롤하여 새 에이전트 만들기를 클릭합니다.
  4. 에이전트 이름, 기본 언어, 기본 시간대를 입력합니다.
  5. 프로젝트를 이미 만든 경우 해당 프로젝트를 입력합니다. Dialogflow 콘솔이 프로젝트를 만들 수 있게 하려면 새 Google 프로젝트 만들기를 선택하세요.
  6. 만들기 버튼을 클릭합니다.

에이전트로 예시 파일 가져오기

이 가이드의 단계에서는 에이전트가 있다고 가정하므로 이 가이드를 위해 준비된 에이전트를 가져와야 합니다. 이 단계에서는 가져올 때 모든 에이전트 설정, 인텐트, 항목을 덮어쓰는 restore 옵션을 사용합니다.

파일을 가져오려면 다음 단계를 따르세요.

  1. room-booking-agent.zip 파일을 다운로드합니다.
  2. Dialogflow ES 콘솔로 이동합니다.
  3. 에이전트를 선택합니다.
  4. 에이전트 이름 옆에 있는 설정 버튼을 클릭합니다.
  5. 내보내기 및 가져오기 탭을 선택합니다.
  6. Zip 파일에서 복원을 선택하고 안내에 따라 다운로드한 zip 파일을 복원합니다.

인텐트 감지

인텐트를 감지하려면 Sessions 유형에서 detectIntent 메서드를 호출합니다.

REST

1. 오디오 콘텐츠 준비

'book a room'이라고 말하는 book-a-room.wav 샘플 입력 오디오 파일을 다운로드합니다. 이 예시에서 오디오 파일은 base64로 인코딩되어야 하므로 아래의 JSON 요청으로 오디오 파일을 제공할 수 있습니다. 다음은 Linux 예입니다.

wget https://cloud.google.com/dialogflow/es/docs/data/book-a-room.wav
base64 -w 0 book-a-room.wav > book-a-room.b64

다른 플랫폼의 예는 Cloud Speech API 문서의 Base64 인코딩 오디오 삽입을 참조하세요.

2. 인텐트 감지 요청하기

Sessions 유형에서 detectIntent 메서드를 호출하고 base64 인코딩 오디오를 지정합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID
  • SESSION_ID: 세션 ID
  • BASE64_AUDIO: 위에서 생성된 출력 파일의 base64 콘텐츠

HTTP 메서드 및 URL:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/agent/sessions/SESSION_ID:detectIntent

JSON 요청 본문:

{
  "queryInput": {
    "audioConfig": {
      "languageCode": "en-US"
    }
  },
  "outputAudioConfig" : {
    "audioEncoding": "OUTPUT_AUDIO_ENCODING_LINEAR_16"
  },
  "inputAudio": "BASE64_AUDIO"
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "responseId": "b7405848-2a3a-4e26-b9c6-c4cf9c9a22ee",
  "queryResult": {
    "queryText": "book a room",
    "speechRecognitionConfidence": 0.8616504,
    "action": "room.reservation",
    "parameters": {
      "time": "",
      "date": "",
      "duration": "",
      "guests": "",
      "location": ""
    },
    "fulfillmentText": "I can help with that. Where would you like to reserve a room?",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "I can help with that. Where would you like to reserve a room?"
          ]
        }
      }
    ],
    "intent": {
      "name": "projects/PROJECT_ID/agent/intents/e8f6a63e-73da-4a1a-8bfc-857183f71228",
      "displayName": "room.reservation"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {},
    "languageCode": "en-us"
  },
  "outputAudio": "UklGRs6vAgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AA..."
}

queryResult.action 필드의 값은 room.reservation이고, outputAudio 필드에는 긴 base64 오디오 문자열이 있습니다.

3. 출력 오디오 재생

outputAudio 필드의 텍스트를 복사하여 이름이 output_audio.b64인 파일에 저장합니다. 이 파일을 오디오로 변환해야 합니다. 다음은 Linux 예입니다.

base64 -d output_audio.b64 > output_audio.wav

다른 플랫폼의 예는 TTS(텍스트 음성 변환) API 문서에서 Base64 인코딩 오디오 콘텐츠 디코딩을 참조하세요.

이제 output_audio.wav 오디오 파일을 재생하여 위의 queryResult.fulfillmentMessages[1].text.text[0] 필드와 일치하는지 들어볼 수 있습니다. 두 번째 fulfillmentMessages 요소가 기본 플랫폼의 텍스트 응답이기 때문에 선택됩니다.

Java

Dialogflow에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.v2.DetectIntentRequest;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
import com.google.cloud.dialogflow.v2.OutputAudioConfig;
import com.google.cloud.dialogflow.v2.OutputAudioEncoding;
import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.cloud.dialogflow.v2.SessionName;
import com.google.cloud.dialogflow.v2.SessionsClient;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class DetectIntentWithTextToSpeechResponse {

  public static Map<String, QueryResult> detectIntentWithTexttoSpeech(
      String projectId, List<String> texts, String sessionId, String languageCode)
      throws IOException, ApiException {
    Map<String, QueryResult> queryResults = Maps.newHashMap();
    // Instantiates a client
    try (SessionsClient sessionsClient = SessionsClient.create()) {
      // Set the session name using the sessionId (UUID) and projectID (my-project-id)
      SessionName session = SessionName.of(projectId, sessionId);
      System.out.println("Session Path: " + session.toString());

      // Detect intents for each text input
      for (String text : texts) {
        // Set the text (hello) and language code (en-US) for the query
        TextInput.Builder textInput =
            TextInput.newBuilder().setText(text).setLanguageCode(languageCode);

        // Build the query with the TextInput
        QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();

        //
        OutputAudioEncoding audioEncoding = OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_LINEAR_16;
        int sampleRateHertz = 16000;
        OutputAudioConfig outputAudioConfig =
            OutputAudioConfig.newBuilder()
                .setAudioEncoding(audioEncoding)
                .setSampleRateHertz(sampleRateHertz)
                .build();

        DetectIntentRequest dr =
            DetectIntentRequest.newBuilder()
                .setQueryInput(queryInput)
                .setOutputAudioConfig(outputAudioConfig)
                .setSession(session.toString())
                .build();

        // Performs the detect intent request
        DetectIntentResponse response = sessionsClient.detectIntent(dr);

        // Display the query result
        QueryResult queryResult = response.getQueryResult();

        System.out.println("====================");
        System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
        System.out.format(
            "Detected Intent: %s (confidence: %f)\n",
            queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
        System.out.format(
            "Fulfillment Text: '%s'\n",
            queryResult.getFulfillmentMessagesCount() > 0
                ? queryResult.getFulfillmentMessages(0).getText()
                : "Triggered Default Fallback Intent");

        queryResults.put(text, queryResult);
      }
    }
    return queryResults;
  }
}

Node.js

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Imports the Dialogflow client library
const dialogflow = require('@google-cloud/dialogflow').v2;

// Instantiate a DialogFlow client.
const sessionClient = new dialogflow.SessionsClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'ID of GCP project associated with your Dialogflow agent';
// const sessionId = `user specific ID of session, e.g. 12345`;
// const query = `phrase(s) to pass to detect, e.g. I'd like to reserve a room for six people`;
// const languageCode = 'BCP-47 language code, e.g. en-US';
// const outputFile = `path for audio output file, e.g. ./resources/myOutput.wav`;

// Define session path
const sessionPath = sessionClient.projectAgentSessionPath(
  projectId,
  sessionId
);
const fs = require('fs');
const util = require('util');

async function detectIntentwithTTSResponse() {
  // The audio query request
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
        languageCode: languageCode,
      },
    },
    outputAudioConfig: {
      audioEncoding: 'OUTPUT_AUDIO_ENCODING_LINEAR_16',
    },
  };
  sessionClient.detectIntent(request).then(responses => {
    console.log('Detected intent:');
    const audioFile = responses[0].outputAudio;
    util.promisify(fs.writeFile)(outputFile, audioFile, 'binary');
    console.log(`Audio content written to file: ${outputFile}`);
  });
}
detectIntentwithTTSResponse();

Python

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def detect_intent_with_texttospeech_response(
    project_id, session_id, texts, language_code
):
    """Returns the result of detect intent with texts as inputs and includes
    the response in an audio format.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient()

    session_path = session_client.session_path(project_id, session_id)
    print("Session path: {}\n".format(session_path))

    for text in texts:
        text_input = dialogflow.TextInput(text=text, language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        # Set the query parameters with sentiment analysis
        output_audio_config = dialogflow.OutputAudioConfig(
            audio_encoding=dialogflow.OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_LINEAR_16
        )

        request = dialogflow.DetectIntentRequest(
            session=session_path,
            query_input=query_input,
            output_audio_config=output_audio_config,
        )
        response = session_client.detect_intent(request=request)

        print("=" * 20)
        print("Query text: {}".format(response.query_result.query_text))
        print(
            "Detected intent: {} (confidence: {})\n".format(
                response.query_result.intent.display_name,
                response.query_result.intent_detection_confidence,
            )
        )
        print("Fulfillment text: {}\n".format(response.query_result.fulfillment_text))
        # The response's audio_content is binary.
        with open("output.wav", "wb") as out:
            out.write(response.output_audio)
            print('Audio content written to file "output.wav"')

관련 응답 필드의 설명은 인텐트 감지 응답 섹션을 참조하세요.

인텐트 감지 응답

인텐트 감지 요청에 대한 응답은 DetectIntentResponse 유형입니다.

일반적인 인텐트 감지 처리는 DetectIntentResponse.queryResult.fulfillmentMessages 필드의 콘텐츠를 제어합니다.

DetectIntentResponse.outputAudio 필드는 DetectIntentResponse.queryResult.fulfillmentMessages 필드에서 검색된 기본 플랫폼 텍스트 응답에 기반한 오디오로 채워집니다. 기본 텍스트 응답이 여러 개 존재하는 경우 오디오를 생성할 때 서로 연결됩니다. 기본 플랫폼 텍스트 응답이 존재하지 않으면 생성된 오디오 콘텐츠가 비게 됩니다.

DetectIntentResponse.outputAudioConfig 필드는 출력 오디오를 생성하는 데 사용되는 오디오 설정으로 채워집니다.

스트림의 인텐트 감지

스트림에서 인텐트를 감지할 때는 출력 오디오를 사용하지 않는 예시(스트림에서 인텐트 감지)와 유사한 요청을 보냅니다. 단 OutputAudioConfig 필드를 요청에 제공합니다. output_audiooutput_audio_config 필드는 Dialogflow API 서버에서 가져오는 마지막 스트리밍 응답에서 채워집니다. 자세한 내용은 StreamingDetectIntentRequestStreamingDetectIntentResponse를 참조하세요.

음성의 에이전트 설정

음성 합성의 여러 측면을 제어할 수 있습니다. 에이전트 음성 설정을 참조하세요.

Dialogflow 시뮬레이터 사용

Dialogflow 시뮬레이터를 통해 에이전트와 상호작용하고 오디오 응답을 받을 수 있습니다.

  1. 위의 단계에 따라 자동 TTS(텍스트 음성 변환)를 사용 설정합니다.
  2. 시뮬레이터에 'book a room'을 입력하거나 말합니다.
  3. 시뮬레이터 하단의 출력 오디오 섹션을 참조합니다.