2017-12-05 4 views
1

私はdialogflowから直接テキスト応答を取得しようとしています。 githubのサンプルコードから回答が得られますが、ユーザーフレンドリーではありません。どのようにして「スピーチ専用」の回答を得ることができますか?Dialogflowでテキスト応答を直接取得するには?

import os.path 
import sys 

try: 
    import apiai 
except ImportError: 
    sys.path.append(
     os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir) 
    ) 
    import apiai 

CLIENT_ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN' 


def main(): 
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN) 

    request = ai.text_request() 

    request.lang = 'de' # optional, default value equal 'en' 

    request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>" 

    request.query = "Hello" 

    response = request.getresponse() 

    print (response.read()) 


if __name__ == '__main__': 
    main() 

私は単純な結果を期待しています。プレーンなハローテキスト。

私が代わりに何を得る= b'{\n "id": "306fd06a-d9e6-4c2e-8c05-98ff7fc0ecd5",\n "timestamp": "2017-12-05T22:18:15.563Z",\n "lang": "en",\n "result": {\n "source": "agent",\n "resolvedQuery": "hi",\n "action": "input.welcome",\n "actionIncomplete": false,\n "parameters": {},\n "contexts": [],\n "metadata": {\n "intentId": "8406ea3a-a0c9-4470-829f-aba0ce2da2e5",\n "webhookUsed": "false",\n "webhookForSlotFillingUsed": "false",\n "intentName": "Default Welcome Intent"\n },\n "fulfillment": {\n "speech": "Hi there!",\n "messages": [\n {\n "type": 0,\n "speech": "Hi there!"\n }\n ]\n },\n "score": 1.0\n },\n "alternateResult": {\n "source": "domains",\n "resolvedQuery": "hi",\n "action": "smalltalk.greetings.hello",\n "actionIncomplete": false,\n "parameters": {},\n "contexts": [],\n "metadata": {},\n "fulfillment": {\n "speech": "Hey!",\n "source": "agent"\n },\n "score": 1.0\n },\n "status": {\n "code": 200,\n "errorType": "success",\n "webhookTimedOut": false\n },\n "sessionId": "mr.9000"\n}'

答えて

1

ちょうどメッセージを取得するには、このようにしてみてください:

response = json.loads(request.getresponse().read().decode('utf-8')) 
message = response['result']['fulfillment']['speech'] 
print (message) 

は、冒頭で

import json 

を追加することを忘れないでください。まだインストールしていない場合は、インストールしてください。 Pythonでjsonに対処したいのであれば、あなたは必要です。 動作するかどうか教えてください

+0

TypeError: 'HTTPResponse'オブジェクトはサブスクリプトできません。私はそれが働くことを望む。 – Furky

+0

ちょっとコードを少し変えました。あなたは今それを試すことができますか? –

+0

名前 'json'は定義されていません。私は何とか近いと感じています。 – Furky

0

Dialogflow's query APIのようです。応答の形式はhereと記載されています。あなたはJSONを解析する必要があります。これを行うための最も一般的な方法は...

  1. あなたは(あなたのファイルの先頭に、すなわちimport json)をインポートする必要がありますjsonモジュールを使用してくださいだろう。
  2. 次はあなたがresponseを定義した後、すなわち行を追加します(あなたはloadメソッドで受信しているJSON文字列をロードする必要があります:response_dict = json.loads(response.read())
  3. を最後に、あなたがresponse_dictオブジェクトから正しい文字列を取得する必要があります: print(response_dict.['result']['resolvedQuery'])
+0

これも動作します!ありがとう! – Furky

0

私はあなたがテキストのみの回答を求めていると信じています。

そのままあなたは、次のコードを使用することができます。

Just don't forget to update your access token in the code.

<html> 
<head> 
    <title>API Example</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
    <script type="text/javascript"> 
     var accessToken = "update your access token here"; 
     var baseUrl = "https://api.api.ai/v1/"; 
     $(document).ready(function() { 
      $("#input").keypress(function(event) { 
       if (event.which == 13) { 
        event.preventDefault(); 
        send(); 
       } 
      }); 
      $("#rec").click(function(event) { 
       switchRecognition(); 
      }); 
     }); 
     var recognition; 
     function startRecognition() { 
      recognition = new webkitSpeechRecognition(); 
      recognition.onstart = function(event) { 
       updateRec(); 
      }; 
      recognition.onresult = function(event) { 
       var text = ""; 
       for (var i = event.resultIndex; i < event.results.length; ++i) { 
        text += event.results[i][0].transcript; 
       } 
       setInput(text); 
       stopRecognition(); 
      }; 
      recognition.onend = function() { 
       stopRecognition(); 
      }; 
      recognition.lang = "en-US"; 
      recognition.start(); 
     } 

     function stopRecognition() { 
      if (recognition) { 
       recognition.stop(); 
       recognition = null; 
      } 
      updateRec(); 
     } 
     function switchRecognition() { 
      if (recognition) { 
       stopRecognition(); 
      } else { 
       startRecognition(); 
      } 
     } 
     function setInput(text) { 
      $("#input").val(text); 
      send(); 
     } 
     function updateRec() { 
      $("#rec").text(recognition ? "Stop" : "Speak"); 
     } 
//  function send() { 
//   var text = $("#input").val(); 
//   $.ajax({ 
//    type: "POST", 
//    url: baseUrl + "query?v=20150910", 
//    contentType: "application/json; charset=utf-8", 
//    dataType: "json", 
//    headers: { 
//     "Authorization": "Bearer " + accessToken 
//    }, 
//    data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }), 
//    success: function(data) { 
//     setResponse(JSON.stringify(data, undefined, 2)); 
//    }, 
//    error: function() { 
//     setResponse("Internal Server Error"); 
//    } 
//   }); 
//   setResponse("Loading..."); 
//  } 
     function send() { 
      var text = $("#input").val(); 
      $.ajax({ 
       type: "POST", 
       url: baseUrl + "query?v=20150910", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       headers: { 
        "Authorization": "Bearer " + accessToken 
       }, 
       data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }), 
       success: function(data) { 
        var respText = data.result.fulfillment.speech; 
        console.log("Respuesta: " + respText); 
        setResponse(respText); 
       }, 
       error: function() { 
        setResponse("Internal Server Error"); 
       } 
      }); 
      setResponse("Thinking..."); 
     } 
     function setResponse(val) { 
      $("#response").text(val); 
     } 

    </script> 
    <style type="text/css"> 
     body { width: 500px; margin: 0 auto; text-align: center; margin-top: 20px; } 
     div { position: absolute; } 
     input { width: 400px; } 
     button { width: 50px; } 
     textarea { width: 100%; } 
    </style> 
</head> 
<body> 
<div> 
    <input id="input" type="text"> <button id="rec">Speak</button> 
    <br>Response<br> <textarea id="response" cols="40" rows="20"></textarea> 
</div> 
</body> 
</html> 
関連する問題