public static string GetResponseEnglish(string query)
        {
            var logger = NLog.LogManager.GetCurrentClassLogger();

            var cache = MemoryCache.Default;

            if (!(cache["bot"] is Bot bot))
            {
                var settingsPath = HttpContext.Current.Server.MapPath("~/bin/ConfigurationFiles/Settings.xml");
                var aimlPath     = HttpContext.Current.Server.MapPath("~/bin/AIMLFiles");
                var basePath     = HttpContext.Current.Server.MapPath("~/bin");

                bot = new Bot(basePath);
                bot.LoadSettings(settingsPath);
                var loader = new AIMLLoader(bot);
                loader.LoadAIML(aimlPath);
            }

            var userId = Guid.NewGuid().ToString();
            var output = bot.Chat(query, userId);

            logger.LogAimlResult(query, output.RawOutput);

            return(output.RawOutput);
        }
Example #2
0
        /// <summary>
        /// Given a request containing user input, produces a result from the bot
        /// </summary>
        /// <param name="request">the request from the user</param>
        /// <returns>the result to be output to the user</returns>
        public async Task <Result> Query(Request request)
        {
            return(await Task.Run(() =>
            {
                Result result = new Result(request.user, this, request);

                if (this.isAcceptingUserInput)
                {
                    // Normalize the input
                    AIMLLoader loader = new AIMLLoader(this);
                    LIAM.Normalize.SplitIntoSentences splitter = new LIAM.Normalize.SplitIntoSentences(this);
                    string[] rawSentences = splitter.Transform(request.rawInput);
                    foreach (string sentence in rawSentences)
                    {
                        result.InputSentences.Add(sentence);
                        string path = loader.generatePath(sentence, request.user.getLastBotOutput(), request.user.Topic, true);
                        result.NormalizedPaths.Add(path);
                    }

                    // grab the templates for the various sentences from the graphmaster
                    foreach (string path in result.NormalizedPaths)
                    {
                        Utils.SubQuery query = new SubQuery(path);
                        query.Template = this.Graphmaster.evaluate(path, query, request, MatchState.UserInput, new StringBuilder());
                        result.SubQueries.Add(query);
                    }

                    // process the templates into appropriate output
                    foreach (SubQuery query in result.SubQueries)
                    {
                        if (query.Template.Length > 0)
                        {
                            try
                            {
                                XmlNode templateNode = AIMLTagHandler.getNode(query.Template);
                                string outputSentence = this.processNode(templateNode, query, request, result, request.user);
                                if (outputSentence.Length > 0)
                                {
                                    result.OutputSentences.Add(outputSentence);
                                }
                            }
                            catch
                            {
                                this.writeToLog("WARNING! A problem was encountered when trying to process the input: " + request.rawInput + " with the template: \"" + query.Template + "\"");
                            }
                        }
                    }
                }
                else
                {
                    result.OutputSentences.Add(this.NotAcceptingUserInputMessage);
                }

                // populate the Result object
                result.Duration = DateTime.Now - request.StartedOn;
                request.user.addResult(result);

                return result;
            }));
        }
Example #3
0
        public static int FromInsideLoaderContext(XmlNode currentNode, Request request, SubQuery query, Func <int> doit)
        {
            int total = 0;

            query = query ?? request.CurrentQuery;
            //Result result = query.Result;
            AltBot     RProcessor = request.TargetBot;
            AIMLLoader prev       = RProcessor.Loader;

            try
            {
                // RProcessor.Loader = this;
                // Get a list of the nodes that are children of the <aiml> tag
                // these nodes should only be either <topic> or <category>
                // the <topic> nodes will contain more <category> nodes
                string currentNodeName = currentNode.Name.ToLower();

                var ts = EnterTag(request, currentNode, query);
                try
                {
                    total += doit();
                }
                finally
                {
                    ts();
                }
            }
            finally
            {
                RProcessor.Loader = prev;
            }
            return(total);
        }
Example #4
0
        /// <summary>
        /// Given a request containing user input, produces a result from the bot
        /// </summary>
        /// <param name="request">the request from the user</param>
        /// <returns>the result to be output to the user</returns>
        public Result Chat(Request request)
        {
            Result result = new Result(request.User, this, request);

            // Normalize the input
            AIMLLoader loader = new AIMLLoader(this);

            AimlStandard.Normalize.SplitIntoSentences splitter = new AimlStandard.Normalize.SplitIntoSentences(this);
            string[] rawSentences = splitter.Transform(request.RawInput);
            foreach (string sentence in rawSentences)
            {
                result.InputSentences.Add(sentence);
                string path = loader.GeneratePath(sentence, request.User.GetLastBotOutput(), request.User.Topic, true);
                result.NormalizedPaths.Add(path);
            }

            // grab the templates for the various sentences from the graphmaster
            foreach (string path in result.NormalizedPaths)
            {
                string template = this.Graphmaster.Evaluate(path, request, MatchState.UserInput, new StringBuilder());
                result.Templates.Add(template);
            }

            // process the templates into appropriate output
            foreach (string template in result.Templates)
            {
                if (template.Length > 0)
                {
                    try
                    {
                        XmlNode templateNode   = AIMLTagHandler.GetNode(template);
                        string  outputSentence = this.ProcessNode(templateNode, request, result, request.User);
                        if (outputSentence.Length > 0)
                        {
                            result.OutputSentences.Add(outputSentence);
                        }
                    }
                    catch (Exception e)
                    {
                        if (this.WillCallHome)
                        {
                            this.PhoneHome(e.Message, request);
                        }
                        this.WriteToLog("WARNING! A mal-formed template was encountered when trying to process the input: " + request.RawInput);
                    }
                }
            }

            // populate the Result object
            result.Duration = DateTime.Now - request.StartedOn;
            request.User.AddResult(result);

            return(result);
        }
Example #5
0
        public void TestChat()
        {
            var serviceProvider = new ServiceCollection()
                                  .AddLogging()
                                  .BuildServiceProvider();

            var factory = serviceProvider.GetService <ILoggerFactory>();
            var logger  = factory.CreateLogger <Bot>();
            int userId  = 1;

            var mockUserService = new Mock <IBotUserService>();

            mockUserService.Setup(x => x.GetTopic(It.IsAny <int>())).Returns("");

            var mockResultService = new Mock <IUserResultService>();

            mockResultService.Setup(x => x.GetLastOutput(It.IsAny <int>())).Returns("");

            var mockPredicateService = new Mock <IUserPredicateService>();

            var mockRequestService = new Mock <IUserRequestService>();


            IBotConfigurationLoader configurationLoader = new ConfigurationLoader();
            IBotUserService         botUserService      = mockUserService.Object;
            IUserResultService      resultService       = mockResultService.Object;
            IUserPredicateService   predicateService    = mockPredicateService.Object;
            IUserRequestService     requestService      = mockRequestService.Object;
            IApplicationService     applicationService  = GetMockAppService();

            SettingsDictionary substitutions = new SettingsDictionary();
            string             inputString   = "";

            Normalize.ApplySubstitutions substitutor = new Normalize.ApplySubstitutions(substitutions, inputString);
            Regex strippers = new Regex("[^0-9a-zA-Z]");

            Normalize.StripIllegalCharacters stripper = new Normalize.StripIllegalCharacters(strippers);
            IAimlLoader loader = new AIMLLoader(logger, substitutor, stripper, true, 1000);
            Bot         bot    = new Bot(configurationLoader, logger, botUserService, resultService, loader, predicateService, requestService, applicationService);

            bot.Initialize();
            string expectedResult = "Because I am a piece of software.";
            var    result         = bot.Chat(new Request("Why do you live in a computer?", userId));

            Assert.NotNull(result);
            Assert.Equal(expectedResult, result.Output);
        }
Example #6
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            Conversation.UpdateContainer(builder =>
            {
                builder.RegisterModule(new AzureModule(Assembly.GetExecutingAssembly()));

                var store = new InMemoryDataStore();
                builder.Register(c => store)
                .Keyed <IBotDataStore <BotData> >(AzureModule.Key_DataStore)
                .AsSelf()
                .SingleInstance();

                builder.RegisterType <DebugActivityLogger>().AsImplementedInterfaces().InstancePerDependency();

                builder.RegisterModule(new PostUnhandledExceptionToUserModule());
            });

            var settingsPath = HttpContext.Current.Server.MapPath("~/bin/ConfigurationFiles/Settings.xml");
            var aimlPath     = HttpContext.Current.Server.MapPath("~/bin/AIMLFiles");
            var basePath     = HttpContext.Current.Server.MapPath("~/bin");

            var bot = new Bot(basePath);

            bot.LoadSettings(settingsPath);
            var loader = new AIMLLoader(bot);

            loader.LoadAIML(aimlPath);

            var cache = MemoryCache.Default;

            cache.Set("bot", bot, new CacheItemPolicy
            {
                AbsoluteExpiration = DateTimeOffset.Now.AddDays(1.0)
            });
        }
Example #7
0
        public void SetCategoryTag(Unifiable generatedPath, Unifiable patternInfo, CategoryInfo category,
                                   XmlNode outerNode, XmlNode templateNode, Unifiable guard, Unifiable thatInfo)
        {
#if false
            var node = this.RootNode;
            if (SilentTagsInPutParent && AIMLLoader.IsSilentTag(templateNode))
            {
                GraphMaster parent1 = makeParent();
                this.Parents.Add(parent1);
                parent1.Size++;
                node = parent1.RootNode;
                writeToLog("Adding to Parent " + category);
            }
            Node created = Node.addCategoryTag(node, generatedPath, patternInfo,
                                               category, outerNode, templateNode, guard, thatInfo, this);

            this.Size++;
#endif
            // keep count of the number of categories that have been processed
        }
        public static async Task <string> GetResponseNorwegian(string query)
        {
            var logger = NLog.LogManager.GetCurrentClassLogger();

            var cache = MemoryCache.Default;

            if (!(cache["bot"] is Bot bot))
            {
                var settingsPath = HttpContext.Current.Server.MapPath("~/bin/ConfigurationFiles/Settings.xml");
                var aimlPath     = HttpContext.Current.Server.MapPath("~/bin/AIMLFiles");
                var basePath     = HttpContext.Current.Server.MapPath("~/bin");

                bot = new Bot(basePath);
                bot.LoadSettings(settingsPath);
                var loader = new AIMLLoader(bot);
                loader.LoadAIML(aimlPath);
            }

            // Calls for AIML should be translated to English
            var translator = new Translator(ConfigurationManager.AppSettings["TranslatorKey"]);

            var utteranceInEnglish = await translator.TranslateFromNorwegianToEnglish(query);

            logger.LogTranslationResult(query, utteranceInEnglish, "Norwegian", "English");

            var userId = Guid.NewGuid().ToString();
            var output = bot.Chat(utteranceInEnglish, userId);

            logger.LogAimlResult(utteranceInEnglish, output.RawOutput);

            var resultInNorwegian = await translator.TranslateFromEnglishToNorwegian(output.RawOutput);

            resultInNorwegian = FirstLetterToUpper(resultInNorwegian);

            logger.LogTranslationResult(output.RawOutput, resultInNorwegian, "English", "Norwegian");

            return(resultInNorwegian);
        }
Example #9
0
        /// <summary>
        /// Allows the bot to load a new XML version of some AIML
        /// </summary>
        /// <param name="newAIML">The XML document containing the AIML</param>
        /// <param name="filename">The originator of the XML document</param>
        public void loadAIMLFromXML(XmlDocument newAIML, string filename)
        {
            AIMLLoader loader = new AIMLLoader(this);

            loader.loadAIMLFromXML(newAIML, filename);
        }
Example #10
0
        /// <summary>
        /// Loads AIML from .aiml files into the graphmaster "brain" of the bot
        /// </summary>
        public void loadAIMLFromFiles()
        {
            AIMLLoader loader = new AIMLLoader(this);

            loader.loadAIML();
        }
Example #11
0
        public void SaveDb()
        {
            AIMLLoader loader = new AIMLLoader(this);

            loader.SaveDB();
        }
Example #12
0
        public void BackupDb()
        {
            AIMLLoader loader = new AIMLLoader(this);

            loader.Backup();
        }
Example #13
0
        /// <summary>
        /// Given a request containing user input, produces a result from the bot
        /// </summary>
        /// <param name="request">the request from the user</param>
        /// <returns>the result to be output to the user</returns>
        public Result Chat(Request request)
        {
            Result result      = new Result(request.user, this, request);
            bool   IsAddResult = true;

            if (this.isAcceptingUserInput)
            {
                // Normalize the input
                AIMLLoader loader = new AIMLLoader(this);
                AIMLbot.Normalize.SplitIntoSentences splitter = new AIMLbot.Normalize.SplitIntoSentences(this);
                string[] rawSentences = splitter.Transform(request.rawInput);
                foreach (string sentence in rawSentences)
                {
                    result.InputSentences.Add(sentence);
                    string path = loader.generatePath(sentence, request.user.getLastBotOutput(), request.user.Topic, true);
                    result.NormalizedPaths.Add(path);
                }

                // grab the templates for the various sentences from the graphmaster
                foreach (string path in result.NormalizedPaths)
                {
                    Utils.SubQuery query = new SubQuery(path);
                    query.Template = this.Graphmaster.evaluate(path, query, request, MatchState.UserInput, new StringBuilder());
                    result.SubQueries.Add(query);
                }

                // process the templates into appropriate output
                foreach (SubQuery query in result.SubQueries)
                {
                    if (query.Template.Length > 0)
                    {
                        try
                        {
                            XmlNode templateNode   = AIMLTagHandler.getNode(query.Template);
                            string  outputSentence = this.processNode(templateNode, query, request, result, request.user);
                            if (outputSentence.Length > 0)
                            {
                                if (outputSentence.Contains("[notadd]"))
                                {
                                    outputSentence = outputSentence.Replace("[notadd]", "");
                                    IsAddResult    = false;
                                }
                                result.OutputSentences.Add(outputSentence);
                            }
                        }
                        catch (Exception e)
                        {
                            if (this.WillCallHome)
                            {
                                this.phoneHome(e.Message, request);
                            }
                            this.writeToLog("WARNING! A problem was encountered when trying to process the input: " + request.rawInput + " with the template: \"" + query.Template + "\"");
                        }
                    }
                }
            }
            else
            {
                result.OutputSentences.Add(this.NotAcceptingUserInputMessage);
            }

            // populate the Result object
            result.Duration = DateTime.Now - request.StartedOn;
            if (IsAddResult)
            {
                request.user.addResult(result);
            }
            return(result);
        }
Example #14
0
        /// <summary>
        /// Loads AIML from .aiml files into the graphmaster "brain" of the bot
        /// </summary>
        //public void loadAIMLFromFiles()
        //{
        //    AIMLLoader loader = new AIMLLoader(this);
        //    loader.loadAIML();
        //}
        /// <summary>
        /// Loads AIML from .aiml files into the graphmaster "brain" of the bot
        /// </summary>
        public void loadAIMLFromFiles(string aimldir)
        {
            AIMLLoader loader = new AIMLLoader(this);

            loader.loadAIML(aimldir);
        }
Example #15
0
        // Token: 0x0600008E RID: 142 RVA: 0x000058A4 File Offset: 0x000048A4
        public Result Chat(Request request)
        {
            Result result = new Result(request.user, this, request);

            if (this.isAcceptingUserInput)
            {
                AIMLLoader         aimlloader         = new AIMLLoader(this);
                SplitIntoSentences splitIntoSentences = new SplitIntoSentences(this);
                string[]           array = splitIntoSentences.Transform(request.rawInput);
                foreach (string text in array)
                {
                    result.InputSentences.Add(text);
                    string item = aimlloader.generatePath(text, request.user.getLastBotOutput(), request.user.Topic, true);
                    result.NormalizedPaths.Add(item);
                }
                foreach (string text2 in result.NormalizedPaths)
                {
                    SubQuery subQuery = new SubQuery(text2);
                    subQuery.Template = this.Graphmaster.evaluate(text2, subQuery, request, MatchState.UserInput, new StringBuilder());
                    result.SubQueries.Add(subQuery);
                }
                using (List <SubQuery> .Enumerator enumerator2 = result.SubQueries.GetEnumerator())
                {
                    while (enumerator2.MoveNext())
                    {
                        SubQuery subQuery2 = enumerator2.Current;
                        if (subQuery2.Template.Length > 0)
                        {
                            try
                            {
                                XmlNode node  = AIMLTagHandler.getNode(subQuery2.Template);
                                string  text3 = this.processNode(node, subQuery2, request, result, request.user);
                                if (text3.Length > 0)
                                {
                                    result.OutputSentences.Add(text3);
                                }
                            }
                            catch (Exception ex)
                            {
                                if (this.WillCallHome)
                                {
                                    this.phoneHome(ex.Message, request);
                                }
                                this.writeToLog(string.Concat(new string[]
                                {
                                    "WARNING! A problem was encountered when trying to process the input: ",
                                    request.rawInput,
                                    " with the template: \"",
                                    subQuery2.Template,
                                    "\""
                                }));
                            }
                        }
                    }
                    goto IL_1E4;
                }
            }
            result.OutputSentences.Add(this.NotAcceptingUserInputMessage);
IL_1E4:
            result.Duration = DateTime.Now - request.StartedOn;
            request.user.addResult(result);
            return(result);
        }