Exemplo n.º 1
0
        public ChatbotManager()
        {
            /* 환경변수
             * GOOGLE_APPLICATION_CREDENTIALS
             * D:\Programs\Google\Small-Talk-ab19e1b0105f.json
             */
            var        client    = SessionsClient.Create();
            QueryInput tempInput = new QueryInput();
            TextInput  tempText  = new TextInput
            {
                Text         = "야나두",
                LanguageCode = "ko"
            };

            tempInput.Text = tempText;
            var response = client.DetectIntent(new SessionName("small-talk-7a50b", "sess-01"), tempInput);

            var queryResult = response.QueryResult;

            Console.WriteLine($"Query text: {queryResult.QueryText}");
            Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
            Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
            Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
            Console.WriteLine();
        }
Exemplo n.º 2
0
        public ActionResult DetectIntentFromTexts(string q, string sessionId)
        {
            try
            {
                var client = SessionsClient.Create();

                DetectIntentRequest request = new DetectIntentRequest();
                request.SessionAsSessionName = new SessionName(_projectAgentName.ProjectId, sessionId);
                request.QueryInput           = new QueryInput
                {
                    Text = new TextInput()
                    {
                        Text         = q,
                        LanguageCode = "pt-br"
                    }
                };

                DetectIntentResponse response = client.DetectIntent(request);

                var queryResult = response.QueryResult;

                return(Ok(queryResult));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ex.Message));
            }
        }
        // [START dialogflow_detect_intent_text]
        public static int DetectIntentFromTexts(string projectId,
                                                string sessionId,
                                                string[] texts,
                                                string languageCode = "en-US")
        {
            var client = SessionsClient.Create();

            foreach (var text in texts)
            {
                var response = client.DetectIntent(
                    session: new SessionName(projectId, sessionId),
                    queryInput: new QueryInput()
                {
                    Text = new TextInput()
                    {
                        Text         = text,
                        LanguageCode = languageCode
                    }
                }
                    );

                var queryResult = response.QueryResult;

                Console.WriteLine($"Query text: {queryResult.QueryText}");
                if (queryResult.Intent != null)
                {
                    Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
                }
                Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
                Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
                Console.WriteLine();
            }

            return(0);
        }
Exemplo n.º 4
0
        public IActionResult Index(string userSay)
        {
            //由 google api console 建立服務帳號, 並匯出存取token
            System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", @"D:\temp\worldmap-1357-c80b706e2fa6.json");

            var input = new TextInput
            {
                Text = userSay, LanguageCode = "zh-TW"
            };

            // Create client
            SessionsClient sessionsClient = SessionsClient.Create();

            // Initialize request argument(s)
            DetectIntentRequest request = new DetectIntentRequest
            {
                SessionAsSessionName = SessionName.FromProjectSession("worldmap-1357", "[SESSION]"),
                QueryParams          = new QueryParameters(),
                QueryInput           = new QueryInput()
                {
                    Text = input
                },
                OutputAudioConfig     = new OutputAudioConfig(),
                InputAudio            = ByteString.Empty,
                OutputAudioConfigMask = new FieldMask(),
            };

            // Make the request
            DetectIntentResponse response = sessionsClient.DetectIntent(request);

            //將訊息傳送給 View 做顯示
            ViewData["response"] = response.QueryResult.FulfillmentText;
            return(View());
        }
Exemplo n.º 5
0
        /// <summary>
        /// 呼叫 Dialogflow 識別出意圖
        /// </summary>
        /// <param name="userSay"></param>
        /// <returns></returns>
        public DetectIntentResponse CallDialogFlow(string userSay)
        {
            //由 google api console 建立服務帳號, 並匯出存取token
            System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", @"認證檔.json");

            var input = new TextInput
            {
                Text         = userSay,
                LanguageCode = "zh-TW"
            };

            // Create client
            SessionsClient sessionsClient = SessionsClient.Create();

            // Initialize request argument(s)
            DetectIntentRequest request = new DetectIntentRequest
            {
                SessionAsSessionName = SessionName.FromProjectSession("worldmap-1357", "[SESSION]"),
                QueryParams          = new QueryParameters(),
                QueryInput           = new QueryInput()
                {
                    Text = input
                },
                OutputAudioConfig     = new OutputAudioConfig(),
                InputAudio            = ByteString.Empty,
                OutputAudioConfigMask = new FieldMask(),
            };

            // Make the request
            DetectIntentResponse response = sessionsClient.DetectIntent(request);

            return(response);
        }
Exemplo n.º 6
0
        public async Task <IActionResult> sendtext(string text, string sessionId)
        {
            var result = new RequestResult();

            try
            {
                var query = new QueryInput {
                    Text = new TextInput {
                        Text = text, LanguageCode = "ru-ru"
                    }
                };

                var agent   = "small-talk-1-cdboby";
                var creds   = GoogleCredential.FromFile($"{_env.WebRootPath}\\DFCredits.json");
                var channel = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host, creds.ToChannelCredentials());

                var client     = SessionsClient.Create(channel);
                var dialogFlow = await client.DetectIntentAsync(new SessionName(agent, sessionId), query);

                await channel.ShutdownAsync();

                result.IsSuccess = true;
                result.Data      = string.IsNullOrEmpty(dialogFlow?.QueryResult?.FulfillmentText) ? GetRandomDontKnow() : dialogFlow.QueryResult.FulfillmentText;
            }
            catch (Exception err)
            {
                result.IsSuccess = false;
                result.Data      = "Упс... что-то пошло не так...";
                result.Error     = $"Ошбика: {err.Message}";
            }

            return(new JsonResult(result));
        }
Exemplo n.º 7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var query = new QueryInput
            {
                Text = new TextInput
                {
                    Text         = "cc",
                    LanguageCode = "en-us"
                }
            };

            var sessionId = "SomeUniqueId";
            var agent     = "test5";
            var creds     = GoogleCredential.FromJson(@"D:/test5.json");
            var channel   = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host,
                                                  creds.ToChannelCredentials());

            var client = SessionsClient.Create(channel);

            var dialogFlow = client.DetectIntent(
                new SessionName(agent, sessionId),
                query
                );

            channel.ShutdownAsync();
        }
Exemplo n.º 8
0
        public static string DetectIntent(string text)
        {
            var query = new QueryInput
            {
                Text = new TextInput
                {
                    Text         = text,
                    LanguageCode = "ru"
                }
            };

            var sessionId = Guid.NewGuid().ToString();
            var agent     = "smalltalkbot-atvxnh";
            var creds     = IntentDetector.Creds;
            var channel   = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host,
                                                  creds.ToChannelCredentials());

            var client = SessionsClient.Create(channel);

            var dialogFlow = client.DetectIntent(
                new SessionName(agent, sessionId),
                query
                );

            channel.ShutdownAsync();
            return(dialogFlow.QueryResult.FulfillmentText);
        }
Exemplo n.º 9
0
        public ActionResult GetEvent(string eventName, string sessionId)
        {
            try
            {
                var client = SessionsClient.Create();

                DetectIntentRequest request = new DetectIntentRequest();
                request.SessionAsSessionName = new SessionName(_projectAgentName.ProjectId, sessionId);
                request.QueryInput           = new QueryInput
                {
                    Event = new EventInput
                    {
                        Name         = eventName,
                        LanguageCode = "pt-br"
                    }
                };

                request.QueryParams = new QueryParameters();

                DetectIntentResponse response = client.DetectIntent(request);

                var queryResult = response.QueryResult;

                return(Ok(queryResult));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ex.Message));
            }
        }
        // [START dialogflow_detect_intent_texttospeech_response]
        public static int DetectIntentTexttospeechResponseFromTexts(string projectId,
                                                                    string sessionId,
                                                                    string[] texts,
                                                                    string languageCode = "en-US")
        {
            var client            = SessionsClient.Create();
            var outputAudioConfig = new OutputAudioConfig
            {
                AudioEncoding          = OutputAudioEncoding.Linear16,
                SynthesizeSpeechConfig = new SynthesizeSpeechConfig
                {
                    SpeakingRate = 1,
                    Pitch        = 1,
                    VolumeGainDb = 1
                },
                SampleRateHertz = 16000,
            };

            foreach (var text in texts)
            {
                var response = client.DetectIntent(new DetectIntentRequest
                {
                    SessionAsSessionName = SessionName.FromProjectSession(projectId, sessionId),
                    OutputAudioConfig    = outputAudioConfig,
                    QueryInput           = new QueryInput()
                    {
                        Text = new TextInput()
                        {
                            Text         = text,
                            LanguageCode = languageCode
                        }
                    }
                }
                                                   );

                var queryResult = response.QueryResult;

                Console.WriteLine($"Query text: {queryResult.QueryText}");
                if (queryResult.Intent != null)
                {
                    Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
                }
                Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
                Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
                Console.WriteLine();

                if (response.OutputAudio.Length > 0)
                {
                    using (var output = File.Create("output.wav"))
                    {
                        response.OutputAudio.WriteTo(output);
                    }
                    Console.WriteLine("Audio content written to file \"output.wav\"");
                }
            }

            return(0);
        }
Exemplo n.º 11
0
        private SessionsClient CreateDialogFlowClientSessions()
        {
            var dialogFlowConfigurationFilePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/hrone-wxhfau-221616b3f7be.json");
            GoogleCredential googleCredential   = GoogleCredential.FromFile(dialogFlowConfigurationFilePath);
            Channel          channel            = new Channel(SessionsClient.DefaultEndpoint.Host,
                                                              googleCredential.ToChannelCredentials());

            return(SessionsClient.Create(channel));
        }
Exemplo n.º 12
0
        private SessionsClient CreateDialogFlowClientSessions()
        {
            var dialogFlowConfigurationFilePath = _env.ContentRootPath + "/App_Data";
            GoogleCredential googleCredential   = GoogleCredential.FromFile(dialogFlowConfigurationFilePath + "/hr-joy-26ab70a34ae2.json");
            Channel          channel            = new Channel(SessionsClient.DefaultEndpoint.Host,
                                                              googleCredential.ToChannelCredentials());

            return(SessionsClient.Create(channel));
        }
Exemplo n.º 13
0
        public int DetectIntentFromTexts(
            string sessionId,
            string text,
            string languageCode = "en-US")
        {
            string    projectId = "INSERT_PROJECT_ID_HERE";
            var       creds     = GoogleCredential.FromJson("INSERT_KEY_HERE");
            var       channel   = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host, creds.ToChannelCredentials());
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            var client = SessionsClient.Create(channel);

            var response = client.DetectIntent(
                session: new SessionName(projectId, sessionId),
                queryInput: new QueryInput()
            {
                Text = new TextInput()
                {
                    Text         = text,
                    LanguageCode = languageCode
                }
            }
                );
            var queryResult    = response.QueryResult;
            var detectedIntent = queryResult.Intent.DisplayName;
            var state          = graph.GetStateAsync(sessionId);


            if (state == null)
            {
                graph.SendHelloAsync(sessionId).Wait();
            }
            else if (state.CurrentContext == Startup.BotContext.Quiz.ToString())
            {
                QuizContextProcessing(sessionId, detectedIntent, queryResult, state);
            }
            //else if (state.CurrentContext == Startup.BotContext.Feedback.ToString())
            //{
            //    FeedbackProcessing(sessionId, detectedIntent, queryResult);
            //}
            else if (state.CurrentContext == Startup.BotContext.Email.ToString())
            {
                EmailProcessing(sessionId, detectedIntent, queryResult);
            }
            else if (state.CurrentContext == Startup.BotContext.Ineligible.ToString())
            {
                IneligibleContextProcessing(sessionId, detectedIntent, queryResult);
            }
            else if (state.CurrentContext == Startup.BotContext.Welcome.ToString())
            {
                WelcomeContextProcessing(sessionId, detectedIntent, queryResult);
            }

            return(0);
        }
        /// <summary>Snippet for StreamingDetectIntent</summary>
        public async Task StreamingDetectIntent()
        {
            // Snippet: StreamingDetectIntent(CallSettings, BidirectionalStreamingSettings)
            // Create client
            SessionsClient sessionsClient = SessionsClient.Create();

            // Initialize streaming call, retrieving the stream object
            SessionsClient.StreamingDetectIntentStream response = sessionsClient.StreamingDetectIntent();

            // Sending requests and retrieving responses can be arbitrarily interleaved
            // Exact sequence will depend on client/server behavior

            // Create task to do something with responses from server
            Task responseHandlerTask = Task.Run(async() =>
            {
                // Note that C# 8 code can use await foreach
                AsyncResponseStream <StreamingDetectIntentResponse> responseStream = response.GetResponseStream();
                while (await responseStream.MoveNextAsync())
                {
                    StreamingDetectIntentResponse responseItem = responseStream.Current;
                    // Do something with streamed response
                }
                // The response stream has completed
            });

            // Send requests to the server
            bool done = false;

            while (!done)
            {
                // Initialize a request
                StreamingDetectIntentRequest request = new StreamingDetectIntentRequest
                {
                    Session               = "",
                    QueryParams           = new QueryParameters(),
                    QueryInput            = new QueryInput(),
                    OutputAudioConfig     = new OutputAudioConfig(),
                    InputAudio            = ByteString.Empty,
                    OutputAudioConfigMask = new FieldMask(),
                };
                // Stream a request to the server
                await response.WriteAsync(request);

                // Set "done" to true when sending requests is complete
            }

            // Complete writing requests to the stream
            await response.WriteCompleteAsync();

            // Await the response handler
            // This will complete once all server responses have been processed
            await responseHandlerTask;
            // End snippet
        }
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntent()
 {
     // Snippet: DetectIntent(string, QueryInput, CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     string     session    = "projects/[PROJECT]/locations/[LOCATION]/agent/sessions/[SESSION]";
     QueryInput queryInput = new QueryInput();
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(session, queryInput);
     // End snippet
 }
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntentResourceNames()
 {
     // Snippet: DetectIntent(SessionName, QueryInput, CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     SessionName session    = SessionName.FromProjectLocationSession("[PROJECT]", "[LOCATION]", "[SESSION]");
     QueryInput  queryInput = new QueryInput();
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(session, queryInput);
     // End snippet
 }
Exemplo n.º 17
0
        public void Configure(IApplicationBuilder app, ILogger <Startup> logger)
        {
            var client = SessionsClient.Create();

            var jsonSettings = new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                },
            };

            app.Map("/api/dialogflow/detectIntent", builder =>
            {
                builder.Run(async ctx =>
                {
                    try
                    {
                        var body       = await new StreamReader(ctx.Request.Body).ReadToEndAsync();
                        var request    = JsonConvert.DeserializeObject <DialogflowRequest>(body);
                        var queryInput =
                            string.IsNullOrEmpty(request.Text)
                                ? new QueryInput()
                        {
                            Event = new EventInput
                            {
                                LanguageCode = request.LanguageCode,
                                Name         = request.Event,
                            }
                        }
                                : new QueryInput()
                        {
                            Text = new TextInput()
                            {
                                Text         = request.Text,
                                LanguageCode = request.LanguageCode
                            }
                        };
                        var response = await client.DetectIntentAsync(
                            session: new SessionName(request.ProjectId, request.SessionId),
                            queryInput: queryInput
                            );
                        await ctx.Response.WriteAsync(JsonConvert.SerializeObject(response, jsonSettings));
                    }
                    catch (Exception e)
                    {
                        logger.LogError(e, "error occured");
                        ctx.Response.StatusCode = StatusCodes.Status500InternalServerError;
                        await ctx.Response.WriteAsync(e.Message);
                    }
                });
            });
        }
Exemplo n.º 18
0
        public void DeleteSessionToken()
        {
            OktaSettings oktaSettings = new OktaSettings();
            oktaSettings.BaseUri = new Uri(Environment.GetEnvironmentVariable("OKTA_TEST_URL"));
            oktaSettings.ApiToken = Environment.GetEnvironmentVariable("OKTA_TEST_KEY");

            String username = Environment.GetEnvironmentVariable("OKTA_TEST_ADMIN_NAME");
            String password = Environment.GetEnvironmentVariable("OKTA_TEST_ADMIN_PASSWORD");

            SessionsClient sessionsClient = new SessionsClient(oktaSettings);

            var session = sessionsClient.Create(username, password);
            sessionsClient.Close(session.Id);
        }
        private void Init()
        {
            if(channel == null)
            {
                sessionId = Guid.NewGuid().ToString();

                var creds = GoogleCredential.FromFile(HttpContext.Current.Server.MapPath("Content/Account/" + GoogleCredentialJsonFile));

                channel = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host,
                              creds.ToChannelCredentials());

                client = SessionsClient.Create(channel);
            }          
        }
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntent_RequestObject()
 {
     // Snippet: DetectIntent(DetectIntentRequest,CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     DetectIntentRequest request = new DetectIntentRequest
     {
         SessionAsSessionName = new SessionName("[PROJECT]", "[SESSION]"),
         QueryInput           = new QueryInput(),
     };
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(request);
     // End snippet
 }
Exemplo n.º 21
0
    //Don't quite understand whether this is called before or after Start
    private void Awake()
    {
        //Need to set the environment variable to create a the client
        Environment.SetEnvironmentVariable(
            "GOOGLE_APPLICATION_CREDENTIALS",
            @"INSERT JSON FILE LOCATION HERE");
        client = SessionsClient.Create();//creating the client

        //Creating two AudioSource objects through code
        audioIn  = gameObject.AddComponent <AudioSource>();
        audioOut = gameObject.AddComponent <AudioSource>();

        //The mic name is required to record audio
        MicName = Microphone.devices[0].ToString();
    }
        /// <summary>Snippet for StreamingDetectIntent</summary>
        public async Task StreamingDetectIntent()
        {
            // Snippet: StreamingDetectIntent(CallSettings,BidirectionalStreamingSettings)
            // Create client
            SessionsClient sessionsClient = SessionsClient.Create();

            // Initialize streaming call, retrieving the stream object
            SessionsClient.StreamingDetectIntentStream duplexStream = sessionsClient.StreamingDetectIntent();

            // Sending requests and retrieving responses can be arbitrarily interleaved.
            // Exact sequence will depend on client/server behavior.

            // Create task to do something with responses from server
            Task responseHandlerTask = Task.Run(async() =>
            {
                IAsyncEnumerator <StreamingDetectIntentResponse> responseStream = duplexStream.ResponseStream;
                while (await responseStream.MoveNext())
                {
                    StreamingDetectIntentResponse response = responseStream.Current;
                    // Do something with streamed response
                }
                // The response stream has completed
            });

            // Send requests to the server
            bool done = false;

            while (!done)
            {
                // Initialize a request
                StreamingDetectIntentRequest request = new StreamingDetectIntentRequest
                {
                    Session    = "",
                    QueryInput = new QueryInput(),
                };
                // Stream a request to the server
                await duplexStream.WriteAsync(request);

                // Set "done" to true when sending requests is complete
            }
            // Complete writing requests to the stream
            await duplexStream.WriteCompleteAsync();

            // Await the response handler.
            // This will complete once all server responses have been processed.
            await responseHandlerTask;
            // End snippet
        }
Exemplo n.º 23
0
        public void DeleteSessionToken()
        {
            OktaSettings oktaSettings = new OktaSettings();

            oktaSettings.BaseUri  = new Uri(Environment.GetEnvironmentVariable("OKTA_TEST_URL"));
            oktaSettings.ApiToken = Environment.GetEnvironmentVariable("OKTA_TEST_KEY");

            String username = Environment.GetEnvironmentVariable("OKTA_TEST_ADMIN_NAME");
            String password = Environment.GetEnvironmentVariable("OKTA_TEST_ADMIN_PASSWORD");

            SessionsClient sessionsClient = new SessionsClient(oktaSettings);

            var session = sessionsClient.Create(username, password);

            sessionsClient.Close(session.Id);
        }
 /// <summary>Snippet for FulfillIntent</summary>
 public void FulfillIntentRequestObject()
 {
     // Snippet: FulfillIntent(FulfillIntentRequest, CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     FulfillIntentRequest request = new FulfillIntentRequest
     {
         MatchIntentRequest = new MatchIntentRequest(),
         Match             = new Match(),
         OutputAudioConfig = new OutputAudioConfig(),
     };
     // Make the request
     FulfillIntentResponse response = sessionsClient.FulfillIntent(request);
     // End snippet
 }
 /// <summary>Snippet for MatchIntent</summary>
 public void MatchIntentRequestObject()
 {
     // Snippet: MatchIntent(MatchIntentRequest, CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     MatchIntentRequest request = new MatchIntentRequest
     {
         SessionAsSessionName = SessionName.FromProjectLocationAgentSession("[PROJECT]", "[LOCATION]", "[AGENT]", "[SESSION]"),
         QueryParams          = new QueryParameters(),
         QueryInput           = new QueryInput(),
     };
     // Make the request
     MatchIntentResponse response = sessionsClient.MatchIntent(request);
     // End snippet
 }
Exemplo n.º 26
0
        public void SetAgent()
        {
            var config = Database.Load <ConversationConfig>(ConversationConfig.DocumentName());

            if (config == null)
            {
                Agent  = null;
                Config = null;
                return;
            }

            Config = config;
            var credentials = GoogleCredential.FromJson(config.ApiJson);
            var channel     = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host, credentials.ToChannelCredentials());

            Agent = SessionsClient.Create(channel);
        }
Exemplo n.º 27
0
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntentRequestObject()
 {
     // Snippet: DetectIntent(DetectIntentRequest, CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     DetectIntentRequest request = new DetectIntentRequest
     {
         SessionAsSessionName = SessionName.FromProjectLocationSession("[PROJECT]", "[LOCATION]", "[SESSION]"),
         QueryParams          = new QueryParameters(),
         QueryInput           = new QueryInput(),
         OutputAudioConfig    = new OutputAudioConfig(),
         InputAudio           = ByteString.Empty,
     };
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(request);
     // End snippet
 }
Exemplo n.º 28
0
        // [START dialogflow_detect_intent_audio_file]
        public static int DetectIntentFromAudioFile(string projectId,
                                                    string sessionId,
                                                    string filePath,
                                                    string languageCode = "en-US")
        {
            var client = SessionsClient.Create();

            var buffer = new byte[32 * 1024];
            int bytesRead;

            using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
            {
                bytesRead = fileStream.Read(buffer);
            }

            var response = client.DetectIntent(new DetectIntentRequest
            {
                SessionAsSessionName = SessionName.FromProjectSession(projectId, sessionId),
                InputAudio           = Google.Protobuf.ByteString.CopyFrom(buffer),
                QueryInput           = new QueryInput()
                {
                    AudioConfig = new InputAudioConfig()
                    {
                        AudioEncoding   = AudioEncoding.Linear16,
                        LanguageCode    = languageCode,
                        SampleRateHertz = 16000
                    }
                }
            });

            var queryResult = response.QueryResult;

            Console.WriteLine($"Query text: {queryResult.QueryText}");
            if (queryResult.Intent != null)
            {
                Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
            }
            Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
            Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
            Console.WriteLine();

            return(0);
        }
Exemplo n.º 29
0
        public IActionResult Index()
        {
            var cred = GoogleCredential.GetApplicationDefault();

            var channel = new Channel(
                SessionsClient.DefaultEndpoint.ToString(), cred.ToChannelCredentials());
            var Session = SessionsClient.Create(channel);

            var InputQueryInput = new QueryInput
            {
                Text = new TextInput
                {
                    Text         = "Hello",
                    LanguageCode = "en_US",
                }
            };

            var request = Session.DetectIntent(new SessionName("ProjectId", "Test"), InputQueryInput);

            return(Ok(request));
        }
Exemplo n.º 30
0
        public static int DetectIntentFromTexts(string projectId,
                                                string sessionId,
                                                string[] texts,
                                                string languageCode = "en-US")
        {
            string workingDirectory = Environment.CurrentDirectory;

            System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Directory.GetParent(workingDirectory).Parent.Parent.FullName + @"\json\GoogleCred.json");
            var client = SessionsClient.Create();


            foreach (var text in texts)
            {
                var response = client.DetectIntent(
                    session: new SessionName(projectId, sessionId),
                    queryInput: new QueryInput()
                {
                    Text = new TextInput()
                    {
                        Text         = text,
                        LanguageCode = languageCode
                    }
                }
                    );

                var queryResult = response.QueryResult;

                Console.WriteLine($"Query text: {queryResult.QueryText}");
                if (queryResult.Intent != null)
                {
                    Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
                }
                Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
                Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
                Console.WriteLine();
                Console.ReadLine();
            }

            return(0);
        }
Exemplo n.º 31
0
        public static async void GetDialogFlowAnswer(TelegramBotClient Bot, Message message)
        {
            SessionsClient client    = SessionsClient.Create();
            long           id        = message.From.Id;
            string         text      = message.Text;
            string         sessionId = id.ToString();

            DetectIntentResponse response = client.DetectIntent(
                session: SessionName.FromProjectSession(projectId, sessionId),
                queryInput: new QueryInput()
            {
                Text = new TextInput()
                {
                    Text         = text,
                    LanguageCode = languageCode
                }
            }
                );
            QueryResult queryResult = response.QueryResult;

            MongoDB.WriteUserBotMessages(queryResult, message);
            await Bot.SendTextMessageAsync(id, queryResult.FulfillmentText);
        }