Exemplo n.º 1
0
        /// <summary>
        /// Sends a <see cref="DF2QueryInput"/> object as a HTTP request to the remote
        /// chatbot.
        /// </summary>
        /// <param name="queryInput">The input request.</param>
        /// <param name="session">The session ID, i.e., the ID of the user who talks to the chatbot.</param>
        private IEnumerator DetectIntent(DF2QueryInput queryInput, string session)
        {
            // Gets the JWT access token.
            string accessToken = string.Empty;

            while (!JwtCache.TryGetToken(accessSettings.ServiceAccount, out accessToken))
            {
                yield return(JwtCache.GetToken(accessSettings.CredentialsFileName,
                                               accessSettings.ServiceAccount));
            }

            // Prepares the HTTP request.
            var settings = new JsonSerializerSettings();

            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.ContractResolver  = new CamelCasePropertyNamesContractResolver();
            DF2Request request = new DF2Request(session, queryInput);

            // Adds the input contexts and the entities.
            request.QueryParams          = new DF2QueryParams();
            request.QueryParams.Contexts = inputContexts.ToArray();
            inputContexts.Clear();
            request.QueryParams.SessionEntityTypes = inputEntities.ToArray();
            inputEntities.Clear();

            string jsonInput = JsonConvert.SerializeObject(request, settings);

            byte[] body = Encoding.UTF8.GetBytes(jsonInput);

            string          url        = string.Format(PARAMETRIC_DETECT_INTENT_URL, accessSettings.ProjectId, session);
            UnityWebRequest df2Request = new UnityWebRequest(url, "POST");

            df2Request.SetRequestHeader("Authorization", "Bearer " + accessToken);
            df2Request.SetRequestHeader("Content-Type", "application/json");
            df2Request.uploadHandler   = new UploadHandlerRaw(body);
            df2Request.downloadHandler = new DownloadHandlerBuffer();

            yield return(df2Request.SendWebRequest());

            // Processes response.
            if (df2Request.isNetworkError || df2Request.isHttpError)
            {
                DetectIntentError?.Invoke(JsonConvert.DeserializeObject <DF2ErrorResponse>(df2Request.downloadHandler.text));
            }
            else
            {
                string      response = Encoding.UTF8.GetString(df2Request.downloadHandler.data);
                DF2Response resp     = JsonConvert.DeserializeObject <DF2Response>(response);
                ChatbotResponded?.Invoke(resp);
                for (int i = 0; i < resp.queryResult.outputContexts.Length; i++)
                {
                    DF2Context context = resp.queryResult.outputContexts[i];
                    string[]   cName   = context.Name.ToLower().Split('/');
                    if (reactionContexts.ContainsKey(cName[cName.Length - 1]))
                    {
                        reactionContexts[cName[cName.Length - 1]](context);
                    }
                }
            }
        }
    /// <summary>
    /// Sends a <see cref="DF2QueryInput"/> object as a HTTP request to the remote
    /// chatbot.
    /// </summary>
    /// <param name="queryInput">The input request.</param>
    /// <param name="session">The session ID, i.e., the ID of the user who talks to the chatbot.</param>
    private IEnumerator DetectIntent(string audio = "")
    {
        // Gets the JWT access token.
        string accessToken = string.Empty;

        while (!JwtCache.TryGetToken(accessSettings.ServiceAccount, out accessToken))
        {
            yield return(JwtCache.GetToken(accessSettings.CredentialsFileName,
                                           accessSettings.ServiceAccount));
        }

        Debug.Log(accessToken);
        // Prepares the HTTP request.
        var settings = new JsonSerializerSettings();

        settings.NullValueHandling = NullValueHandling.Ignore;
        settings.ContractResolver  = new CamelCasePropertyNamesContractResolver();


        S2TRequest request = new S2TRequest();

        request.Audio         = new S2TAudio();
        request.Audio.Content = audio;

        request.Config = new S2TConfig();
        request.Config.LanguageCode = "en-US";

        string jsonInput = JsonConvert.SerializeObject(request, settings);

        Debug.Log("Json: " + jsonInput);

        byte[] body = Encoding.UTF8.GetBytes(jsonInput);


        UnityWebRequest df2Request = new UnityWebRequest(PARAMETRIC_DETECT_INTENT_URL, "POST");

        df2Request.SetRequestHeader("Authorization", "Bearer " + accessToken);
        df2Request.SetRequestHeader("Content-Type", "application/json");
        df2Request.uploadHandler   = new UploadHandlerRaw(body);
        df2Request.downloadHandler = new DownloadHandlerBuffer();

        yield return(df2Request.SendWebRequest());

        // Processes response.
        if (df2Request.isNetworkError || df2Request.isHttpError)
        {
            DetectIntentError?.Invoke(JsonConvert.DeserializeObject <S2TErrorResponse>(df2Request.downloadHandler.text));
        }
        else
        {
            string response = Encoding.UTF8.GetString(df2Request.downloadHandler.data);

            S2TResponse resp = JsonConvert.DeserializeObject <S2TResponse>(response);
            ChatbotResponded?.Invoke(resp);
            // if(resp.Results[0] !=null)
            // {
            //  Debug.Log("transcript: "+resp.Results[0].Alternatives[0].Transcript);
            // }
        }
    }