Ejemplo n.º 1
0
        private async void buttonApply_Click(object sender, EventArgs e)
        {
            if (neuralTree.SelectedNode != null)
            {
                var node = (NeuralLinkModel)neuralTree.SelectedNode.Tag;
                neuralTree.SelectedNode.Text = node.Name = tbName.Text;
                node.Title         = tbTitle.Text;
                node.QuestionTitle = tbQuestionTitle.Text;
                node.Description   = tbDescription.Text;
                bool showNeuralExpEditor = false;
                var  type    = (string)cbxExpressionTypes.SelectedItem;
                var  curType = node.NeuralExp?.GetType().Name ?? ExpressionNone;
                if (curType != type && supportedTypes.ContainsKey(type))
                {
                    if (type == ExpressionNone)
                    {
                        node.NeuralExp = null;
                    }
                    else
                    {
                        node.NeuralExp      = type == null ? null : (INeuralExpression)Activator.CreateInstance(supportedTypes[type]);
                        showNeuralExpEditor = true;
                    }
                }

                await DbLinkCollection.ReplaceOneById(node._id, node);

                if (showNeuralExpEditor)
                {
                    await ShowNeuralExpressionEditor();
                }

                ReloadTree();
            }
        }
Ejemplo n.º 2
0
        public static List <ILinkInfo> GetAllNeuralNodesLinks(LinkType[] ignore = null)
        {
            List <ILinkInfo> res = new List <ILinkInfo>();
            var ignoreLink       = (bool)ignore?.Contains(LinkType.NeuralLink);

            if (!ignoreLink)
            {
                res.AddRange(DbLinkCollection.Find(x => true).ToList()?.Select(x => x as ILinkInfo).ToList());
            }

            var ignoreAction = (bool)ignore?.Contains(LinkType.ActionLink);

            if (!ignoreAction)
            {
                res.AddRange(DbActionCollection.Find(x => true).ToList()?.Select(x => x as ILinkInfo).ToList());
            }

            var ignoreResources = (bool)ignore?.Contains(LinkType.NeuralResource);

            if (!ignoreResources)
            {
                res.AddRange(DbResourceCollection.Find(x => true).ToList()?.Select(x => x as ILinkInfo).ToList());
            }

            return(res);
        }
Ejemplo n.º 3
0
        private async Task ShowNeuralExpressionEditor()
        {
            var type = (string)cbxExpressionTypes.SelectedItem;
            var node = (NeuralLinkModel)neuralTree.SelectedNode.Tag;

            if (neuralTree.SelectedNode != null && type != ExpressionNone && supportedTypes.ContainsKey(type) && node.NeuralExp?.GetType() == supportedTypes[type])
            {
                if (supportedTypes[type] == typeof(LinkExpression))
                {
                    var exp    = node.NeuralExp as LinkExpression;
                    var picker = new LinkExpressionEditor(exp);
                    var res    = picker.ShowDialog();
                    if (res == DialogResult.OK)
                    {
                        await DbLinkCollection.ReplaceOneById(node._id, node);
                    }
                }
                else if (supportedTypes[type] == typeof(DecisionExpression))
                {
                    var exp    = node.NeuralExp as DecisionExpression;
                    var picker = new DecisionExpressionEditor(exp);
                    var res    = picker.ShowDialog();
                    if (res == DialogResult.OK)
                    {
                        await DbLinkCollection.ReplaceOneById(node._id, node);
                    }
                }
            }
        }
Ejemplo n.º 4
0
        private async void NodePicker_Load(object sender, EventArgs e)
        {
            linkList = await type.GetAllLinks();

            if (excludeChildId != null)
            {
                var node = await DbLinkCollection.FindOneById(excludeChildId);

                node?.CildrenRank.ForEach(child => linkList.Remove(linkList.FirstOrDefault(x => x._id == child.Key)));
            }
            InitializeData(linkList);
        }
Ejemplo n.º 5
0
        private async void lnkLabels_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (neuralTree.SelectedNode != null)
            {
                var node   = (NeuralLinkModel)neuralTree.SelectedNode.Tag;
                var editor = new ListEditor("Neural node labels editor", node.Labels);
                var res    = editor.ShowDialog();
                if (res == DialogResult.OK)
                {
                    node.Labels = editor.Result;
                    await DbLinkCollection.ReplaceOneById(node._id, node);

                    ReloadTree();
                }
            }
        }
Ejemplo n.º 6
0
        private static async Task LoadNodes(this TreeNode treeNode, TreeView treeView)
        {
            TreeNode curTreeNode = null;
            var      root        = await DbLinkCollection.FindOneById(treeNode.Name);

            if (root != null)
            {
                foreach (var child in root.CildrenRank)
                {
                    var node = await DbLinkCollection.FindOneById(child.Key);

                    if (node != null)
                    {
                        bool isLoopNode = false;

                        if (LoadedTreeNodes.Contains(node._id))
                        {
                            isLoopNode = true;
                        }
                        else
                        {
                            LoadedTreeNodes.Add(node._id);
                        }

                        treeView.Invoke((MethodInvoker) delegate
                        {
                            // Running on the UI thread
                            var nodeName         = isLoopNode ? $"{node.Name} ({child.Value})(L)" : $"{node.Name} ({child.Value})";
                            curTreeNode          = treeNode.Nodes.Add(node._id, nodeName);
                            curTreeNode.ImageKey = node.GetNodeImage();
                            curTreeNode.Tag      = node;
                        });

                        if (!isLoopNode)
                        {
                            await curTreeNode.LoadNodes(treeView);
                        }
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public static async Task LoadTree(this TreeView treeView, string id = null)
        {
            LoadedTreeNodes.Clear();

            treeView.Invoke((MethodInvoker) delegate
            {
                treeView.Nodes.Clear();
            });

            TreeNode treeNode = null;
            var      root     = await DbLinkCollection.FindOneById(rootNode);;

            if (root != null)
            {
                treeView.Invoke((MethodInvoker) delegate
                {
                    treeView.Enabled   = false;
                    treeView.ImageList = LoadNeuralLinkValidationImageList();
                    // Running on the UI thread
                    treeNode = treeView.Nodes.Add(root._id, root.Name);
                    LoadedTreeNodes.Add(root._id);
                    treeNode.Tag          = root;
                    treeNode.ImageKey     = root.GetNodeImage();
                    treeView.SelectedNode = treeNode;
                });

                await treeNode?.LoadNodes(treeView);

                treeView.Invoke((MethodInvoker) delegate
                {
                    treeView.ExpandAll();
                    treeView.Enabled = true;
                    if (id != null)
                    {
                        treeView.SelectedNode = treeView.SelectedNode.FindChildFromName(id);
                    }
                    treeView.Focus();
                });
            }
        }
        /// <summary>
        /// Get children nodes suggestion based on ranking.
        /// </summary>
        /// <param name="curLink"></param>
        /// <param name="appendCommonActions"></param>
        /// <returns></returns>
        public static SuggestedActions GetChildSuggestionActions(this NeuralLinkModel curLink, bool appendCommonActions = true)
        {
            curLink.CildrenRank.Sort((x, y) => y.Value.CompareTo(x.Value));

            var result = new SuggestedActions()
            {
                Actions = curLink.CildrenRank.Select(id =>
                {
                    var name = DbLinkCollection.GetFieldValue(id.Key, x => x.Name).Result;
                    return(new CardAction {
                        Title = name, Value = id.Key, Type = ActionTypes.PostBack
                    });
                }).ToList()
            };

            if (appendCommonActions)
            {
                result.AppendActions(ParseActionsFromColonFormatString(CommonActionOptions));
            }

            return(result);
        }
Ejemplo n.º 9
0
        public static async Task <List <ILinkInfo> > GetAllLinks(this LinkType type)
        {
            List <ILinkInfo> res = null;

            switch (type)
            {
            case LinkType.NeuralLink:
                res = (await DbLinkCollection.Find(x => true).ToListAsync()).Select(x => x as ILinkInfo).ToList();
                break;

            case LinkType.ActionLink:
                res = (await DbActionCollection.Find(x => true).ToListAsync()).Select(x => x as ILinkInfo).ToList();
                break;

            case LinkType.NeuralResource:
                res = (await DbResourceCollection.Find(x => true).ToListAsync()).Select(x => x as ILinkInfo).ToList();
                break;

            default:
                break;
            }
            return(res);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Call this to create and feed test database
        /// </summary>
        /// <param name="botId"></param>
        /// <param name="dropDatabase"></param>
        /// <param name="profileName"></param>
        /// <returns></returns>
        public async static Task Feed(string botId, bool dropDatabase, string profileName = BotChatProfile.DefaultProfile)
        {
            #region Load Db from Code
            if (dropDatabase)
            {
                await MongoDbProvider.DropDatabase();

                await DbBotCollection.InsertNewOrUpdate(new BotModel { _id = BotAlphaName, Configuration = new BotConfiguration {
                                                                           ActiveProfile = profileName, ChatProfiles = new List <BotChatProfile> {
                                                                           }
                                                                       } });
            }

            await DbBotCollection.AddOrUpdateChatProfileById(BotAlphaName, new BotChatProfile { Name = profileName });

            await DbBotCollection.SetActiveChatProfileById(BotAlphaName, profileName);

            await SyncChatProfile();


            var superRootNode = await DbLinkCollection.InsertNew(new NeuralLinkModel
            {
                Name  = "SuperRoot",
                Notes = new List <string> {
                    "Welcome to philips chatbot mobile device assistant beta version!"
                },
                NeuralExp = new DecisionExpression
                {
                    QuestionTitle  = "Choose the conversation mode:",
                    Hint           = $"Simple:simple,Advanced:{BotResourceKeyConstants.CommandAdvanceChat}",
                    ExpressionTree = ExpressionBuilder.Build().EQ("simple")
                }
            });


            //configure it as bot root node
            await DbBotCollection.SetRootNodeById(botId, superRootNode._id, profileName);



            var nodeSimpleChatMode = await DbLinkCollection.InsertChildById(superRootNode._id, new NeuralLinkModel
            {
                Name  = "SimpleChatNode",
                Title = $"[{BotResourceKeyConstants.WhatIssue}]"
            });

            //Link super root forward action to simple chat mode
            await DbLinkCollection.SetNeuralExpForwardLinkById(superRootNode._id, new ActionLink { Type = LinkType.NeuralLink, LinkId = nodeSimpleChatMode._id });



            var nodeSound = await DbLinkCollection.InsertChildById(nodeSimpleChatMode._id, new NeuralLinkModel
            {
                Name  = "Sound/Speaker",
                Title = $"[{BotResourceKeyConstants.SelectedIssue}]",
                Notes = new List <string> {
                    $"[{BotResourceKeyConstants.WeHelpYou}]", $"[{BotResourceKeyConstants.WhatIssue}]"
                }
            });

            #region sound


            var resourceMute = await DbResourceCollection.InsertNew(new NeuralResourceModel
            {
                Name     = "NoSound",
                IsLocal  = false,
                Type     = ResourceType.Video,
                Location = "https://www.youtube.com/watch?v=8Y8HzSBMujQ",
                Title    = "How to fix sound problem on any android"
            });

            var actionMute = await DbActionCollection.InsertNew(new NeuralActionModel
            {
                Name      = "NoSoundAction",
                Title     = $"[{BotResourceKeyConstants.FoundSolution}]",
                Resources = new List <string> {
                    $"{resourceMute._id}"
                }
            });

            var resourceUnpleasantSound = await DbResourceCollection.InsertNew(new NeuralResourceModel
            {
                Name     = "UnpleasantSound0",
                IsLocal  = false,
                Type     = ResourceType.Video,
                Location = "https://www.youtube.com/watch?v=Y_hEEEt-Rb0",
                Title    = "[Solution] Mobile speaker producing noisy (crackling) sound fixed without​ replacing speaker"
            });

            var resourceUnpleasantSound1 = await DbResourceCollection.InsertNew(new NeuralResourceModel
            {
                Name     = "UnpleasantSound1",
                IsLocal  = false,
                Type     = ResourceType.ImageJPG,
                Location = "https://1.bp.blogspot.com/-74qhJFnbScQ/Xme-O_OkPnI/AAAAAAAADmw/v3iLjmTSBVYoRWH6HVenl5WYrddv2rd2QCLcBGAsYHQ/s320/Samsung%2BGT-E1207T%2BEar%2BSpeaker%2BJumpur%2BSolution.jpg",
                Title    = "[Solution] Mobile speaker producing noisy (crackling) sound fixed without​ replacing speaker"
            });

            var actionUnpleasantSound = await DbActionCollection.InsertNew(new NeuralActionModel
            {
                Name      = "UnpleasantSoundAction",
                Title     = $"[{BotResourceKeyConstants.FoundSolution}]",
                Resources = new List <string> {
                    resourceUnpleasantSound._id, resourceUnpleasantSound1._id
                }
            });

            var resourceCustomerSupport = await DbResourceCollection.InsertNew(new NeuralResourceModel
            {
                Name     = "customersupport ",
                IsLocal  = false,
                Type     = ResourceType.WebsiteUrl,
                Location = "https://www.philips.co.in/c-w/support-home/support-contact-page.html",
                Title    = "Please reach us @support site"
            });

            var actionCustomerSupport = await DbActionCollection.InsertNew(new NeuralActionModel
            {
                Name      = "customersupportAction",
                Title     = $"[{BotResourceKeyConstants.FoundSolution}]",
                Resources = new List <string> {
                    resourceCustomerSupport._id
                }
            });

            var nodeNoSound = await DbLinkCollection.InsertChildById(nodeSound._id, new NeuralLinkModel
            {
                Name  = "No sound",
                Title = "You have selected {Name} category issues!",
                Notes = new List <string> {
                    $"This might help you fixing it!"
                },
                NeuralExp = new DecisionExpression
                {
                    SkipEvaluation = true,
                    ForwardAction  = new ActionLink
                    {
                        Type   = LinkType.ActionLink,
                        LinkId = actionMute._id
                    }
                }
            });

            var nodeUnpleasantSound = await DbLinkCollection.InsertChildById(nodeSound._id, new NeuralLinkModel
            {
                Name      = "Unpleasant sound",
                Title     = $"[{BotResourceKeyConstants.SelectedIssue}]",
                NeuralExp = new DecisionExpression
                {
                    Hint           = "Yes:yes,No:no",
                    QuestionTitle  = "Did your device fall?",
                    ExpressionTree = ExpressionBuilder.Build().EQ("yes"),
                    ForwardAction  = new ActionLink
                    {
                        Type   = LinkType.ActionLink,
                        LinkId = actionUnpleasantSound._id
                    },
                    FallbackAction = new ActionLink
                    {
                        Type   = LinkType.ActionLink,
                        LinkId = actionCustomerSupport._id
                    }
                }
            });;

            #endregion
            var nodeDisplay = await DbLinkCollection.InsertChildById(nodeSimpleChatMode._id, new NeuralLinkModel
            {
                Name  = "Display/Broken screen",
                Title = $"[{BotResourceKeyConstants.SelectedIssue}]",
                Notes = new List <string> {
                    $"[{BotResourceKeyConstants.WeHelpYou}]", $"[{BotResourceKeyConstants.WhatIssue}]"
                }
            });

            #region display

            #endregion
            var nodeBattery = await DbLinkCollection.InsertChildById(nodeSimpleChatMode._id, new NeuralLinkModel
            {
                Name  = "Battery/Charging",
                Title = $"[{BotResourceKeyConstants.SelectedIssue}]",
                Notes = new List <string> {
                    $"[{BotResourceKeyConstants.WeHelpYou}]", $"[{BotResourceKeyConstants.WhatIssue}]"
                }
            });

            //await DbLinkCollection.UnLinkParentChild(nodeSimpleChatMode._id, nodeBattery._id);

            #region battery

            #endregion

            #endregion

            #region resources
            var stringRes = new List <KeyValuePair <string, string> > {
                new KeyValuePair <string, string>(BotResourceKeyConstants.ThankYou, "Thank you, Have a great day!"),
                new KeyValuePair <string, string>(BotResourceKeyConstants.WhatIssue, "What in the following do you need help with?"),
                new KeyValuePair <string, string>(BotResourceKeyConstants.SelectedIssue, "You have selected '{Name}' as your issue."),
                new KeyValuePair <string, string>(BotResourceKeyConstants.WeHelpYou, "Don't worry, we are here to help you."),
                new KeyValuePair <string, string>(BotResourceKeyConstants.CannotMoveBack, "Cannot move back, No history recorded yet."),
                new KeyValuePair <string, string>(BotResourceKeyConstants.Error, "Encountered an error while processing request, please contact bot administrator."),
                new KeyValuePair <string, string>(BotResourceKeyConstants.FoundSolution, "Here, we found few matching solutions"),
                new KeyValuePair <string, string>(BotResourceKeyConstants.InvalidInput, "Invalid input, please try again."),
                new KeyValuePair <string, string>(BotResourceKeyConstants.ThankYouFeedback, "Thanks for your feedback."),
                new KeyValuePair <string, string>(BotResourceKeyConstants.StartAgain, "Facing another issue?:start"),
                new KeyValuePair <string, string>(BotResourceKeyConstants.AdvanceChatQuery, "Tell us about your issue:"),
                new KeyValuePair <string, string>(BotResourceKeyConstants.NoMatchFound, "No match found, try again in different words."),
                new KeyValuePair <string, string>(BotResourceKeyConstants.Feedback, "Please help us improve our service, Was the solution helpful?"),

                new KeyValuePair <string, string>(BotResourceKeyConstants.FeedBackOptions, "Yes:yes,No:no,Exit:exit"),
                new KeyValuePair <string, string>(BotResourceKeyConstants.CommonActionOptions, "Back:back,Exit:exit")
            };

            await DbBotCollection.AddStringResourceBatchById(botId, stringRes);

            #endregion

            #region ML model test data
            var speakerTrainModel = new NeuraTrainDataModel
            {
                _id     = nodeSound._id,
                Dataset = new List <string> {
                    "Speaker is not working",
                    "Mobile sound issue",
                    "No sound",
                    "Unpleasant sound from speaker",
                    "Cant hear sound",
                    "Noisy music"
                }
            };

            await DbTrainDataCollection.InsertNew(speakerTrainModel);

            var displayTrainModel = new NeuraTrainDataModel
            {
                _id     = nodeDisplay._id,
                Dataset = new List <string> {
                    "Display is not working",
                    "Mobile display issue",
                    "Broken screen",
                    "Screen cracked",
                    "Lines on display",
                    "Issue with mobile display"
                }
            };

            await DbTrainDataCollection.InsertNew(displayTrainModel);

            #endregion
        }
Ejemplo n.º 11
0
        private async void actionMenu_Clicked(object sender, ToolStripItemClickedEventArgs e)
        {
            var clicked = e.ClickedItem.AccessibilityObject.Name;
            {
                if (neuralTree.SelectedNode != null)
                {
                    switch (clicked)
                    {
                    case MenuActionNew:
                    {
                        var newNode = await DbLinkCollection.InsertChildById(neuralTree.SelectedNode.Name, new NeuralLinkModel { Name = "New node" });

                        var newTreeNode = neuralTree.SelectedNode.Nodes.Add(newNode._id, newNode.Name);
                        newTreeNode.Tag         = newNode;
                        neuralTree.SelectedNode = newTreeNode;
                        ReloadTree();
                    }
                    break;

                    case MenuActionDelete:
                    {
                        if (DataProviders.ConfirmDialog($"Do you want to permanently delete node '{neuralTree.SelectedNode.Text}'?\n\n" +
                                                        $"Warning: This will also deletes from all the references to this node in other parent nodes of this.\n\n" +
                                                        $"Note: Refresh tree to view the updated changes.", "MenuActionDelete confirmation", MessageBoxIcon.Warning))
                        {
                            var node = (NeuralLinkModel)neuralTree.SelectedNode.Tag;
                            await DbLinkCollection.RemoveAndUnlinkFromParents(node);

                            await DbTrainDataCollection.RemoveOneById(node._id);

                            neuralTree.SelectedNode.Remove();
                            ReloadTree();
                        }
                    }
                    break;

                    case MenuActionMapChild:
                    {
                        var selectedNode = (NeuralLinkModel)neuralTree.SelectedNode.Tag;
                        var picker       = new NodePicker(LinkType.NeuralLink, selectedNode._id, $"Map child to : {selectedNode.Name}");
                        var res          = picker.ShowDialog();
                        if (res == DialogResult.OK && picker.NodeId != selectedNode._id)
                        {
                            var node = await DbLinkCollection.FindOneById(picker.NodeId);

                            if (node != null)
                            {
                                await DbLinkCollection.LinkParentChild(selectedNode._id, picker.NodeId);

                                var newTreeNode = neuralTree.SelectedNode.Nodes.Add(node._id, node.Name);
                                newTreeNode.Tag = node;
                                ReloadTree();
                            }
                        }
                    }
                    break;

                    case MenuActionUnmapChild:
                    {
                        if (neuralTree.SelectedNode.Parent == null)
                        {
                            await DbBotCollection.SetRootNodeById(BotAlphaName, null, cbxChatProfiles.Text);
                        }
                        else
                        {
                            await DbLinkCollection.UnLinkParentChild(neuralTree.SelectedNode.Parent.Name, neuralTree.SelectedNode.Name);

                            neuralTree.SelectedNode.Remove();
                        }
                        ReloadTree();
                    }
                    break;

                    default:
                        break;
                    }
                }

                switch (clicked)
                {
                case MenuActionRenameProfile:
                    await RenameChatProfile();

                    break;

                case MenuActionDeleteProfile:
                    await DeleteCurrentChatProfile();

                    break;

                case MenuActionNewProfile:
                    await CreateNewChatProfile();

                    break;

                case MenuActionNew:
                {
                    if (neuralTree.Nodes.Count == 0)
                    {
                        var rootNode = await DbLinkCollection.InsertNew(new NeuralLinkModel { Name = "RootNode" });

                        await DbBotCollection.SetRootNodeById(BotAlphaName, rootNode._id, await DataProviders.GetActiveProfile());

                        neuralTree.ImageList = DataProviders.LoadNeuralLinkValidationImageList();
                        var treeNode = neuralTree.Nodes.Add(rootNode._id, rootNode.Name);
                        treeNode.Tag            = rootNode;
                        treeNode.ImageKey       = rootNode.GetNodeImage();
                        neuralTree.SelectedNode = treeNode;
                        ReloadTree();
                    }
                }
                break;

                default:
                    break;
                }

                neuralTree.ExpandAll();
            }
        }
Ejemplo n.º 12
0
        private async Task <ResponseType> TakeAction(ITurnContext turnContext, RequestState requestState)
        {
            var ret     = ResponseType.Continue;
            var text    = turnContext.Activity.Text;
            var curLink = requestState.CurrentLink;

            switch (requestState.CurrentState)
            {
            case ChatStateType.Start:
            {
                await SendResponseForCurrentNode(turnContext, requestState);
            }
            break;

            case ChatStateType.AdvanceChat:
            {
                if (string.IsNullOrWhiteSpace(text))
                {
                    await SendReply(turnContext, StringsProvider.TryGet(BotResourceKeyConstants.InvalidInput), SuggestionExtension.GetCommonSuggestionActions());
                }
                else
                {
                    string nextNodeId = null;
                    try
                    {
                        nextNodeId = requestState.PredictNode(text);
                        var nextLink = await DbLinkCollection.FindOneById(nextNodeId);

                        if (nextLink != null)
                        {
                            requestState.StepForward(nextLink);
                            await SendResponseForCurrentNode(turnContext, requestState);
                        }
                        else
                        {
                            await SendReply(turnContext, StringsProvider.TryGet(BotResourceKeyConstants.NoMatchFound), SuggestionExtension.GetCommonSuggestionActions());
                        }
                    }
                    catch (Exception e)
                    {
                        await SendReply(turnContext, $"ML prediction returned an error: '{e.Message}'. please report this issue to the bot administrator.", SuggestionExtension.GetCommonSuggestionActions("Exit:exit"));
                    }
                }
            }
            break;

            case ChatStateType.PickNode:
            {
                var nextLink = await DbLinkCollection.FindOneById(text);

                if (nextLink == null)
                {
                    await turnContext.SendActivityAsync(StringsProvider.TryGet(BotResourceKeyConstants.InvalidInput));
                    await SendResponseForCurrentNode(turnContext, requestState);
                }
                else
                {
                    curLink = nextLink;
                    requestState.StepForward(curLink);
                    await SendResponseForCurrentNode(turnContext, requestState);
                }
            }
            break;

            case ChatStateType.RecordFeedback:
            {
                switch (text.ToLower())
                {
                case "yes":
                {
                    var             childLink  = curLink;
                    NeuralLinkModel parentLink = null;
                    while (requestState.LinkHistory.TryPop(out parentLink))
                    {
                        await DbLinkCollection.UpdateNeuralRankById(parentLink._id, childLink._id);

                        childLink = parentLink;
                    }
                    ret = ResponseType.End;
                }
                break;

                case "no":
                    ret = ResponseType.End;
                    break;

                default:
                    await turnContext.SendActivityAsync(StringsProvider.TryGet(BotResourceKeyConstants.InvalidInput));
                    await SendReply(turnContext, StringsProvider.TryGet(BotResourceKeyConstants.Feedback), SuggestionExtension.GetFeedbackSuggestionActions());

                    break;
                }
                if (ret == ResponseType.End)
                {
                    await turnContext.SendActivityAsync(StringsProvider.TryGet(BotResourceKeyConstants.ThankYouFeedback));
                }
            }
            break;

            case ChatStateType.InvalidInput:
            case ChatStateType.ExpInput:
            {
                await EvaluateExpressionInput(turnContext, requestState);
            }
            break;

            default:
                break;
            }
            return(ret);
        }
Ejemplo n.º 13
0
        private async Task <bool> EvaluateExpressionInput(ITurnContext turnContext, RequestState requestState)
        {
            var               res     = false;
            var               text    = turnContext.Activity.Text;
            var               curLink = requestState.CurrentLink;
            ActionLink        actionResult;
            ExpEvalResultType op = curLink.NeuralExp.Next(text, out actionResult);

            switch (op)
            {
            case ExpEvalResultType.Skipped:
            case ExpEvalResultType.False:
            case ExpEvalResultType.True:
            {
                if (op == ExpEvalResultType.Skipped)
                {
                    await SendNotes(curLink, turnContext);
                }
                switch (actionResult.Type)
                {
                case LinkType.NeuralLink:
                {
                    var link = await DbLinkCollection.FindOneById(actionResult.LinkId);

                    if (link != null)
                    {
                        curLink = link;
                        requestState.StepForward(curLink);
                        await SendResponseForCurrentNode(turnContext, requestState);
                    }
                    else
                    {
                        //Invalid expression evaluation link id.
                        await SendReply(turnContext, $"Invalid node information : '{actionResult.LinkId}',please report this issue to the bot administrator.", SuggestionExtension.GetCommonSuggestionActions());
                    }
                }
                break;

                case LinkType.ActionLink:
                {
                    var action = await DbActionCollection.FindOneById(actionResult.LinkId);

                    await turnContext.SendActivityAsync(action.BuildActionRespose(turnContext));

                    requestState.CurrentState = ChatStateType.RecordFeedback;
                }
                break;

                case LinkType.NeuralResource:
                {
                    var resource = await DbResourceCollection.FindOneById(actionResult.LinkId);

                    await turnContext.SendActivityAsync(resource.BuildResourceResponse(turnContext));

                    requestState.CurrentState = ChatStateType.RecordFeedback;
                }
                break;

                default:
                    break;
                }
                if (requestState.CurrentState == ChatStateType.RecordFeedback)
                {
                    await Task.Delay(1000).ContinueWith(async ct =>
                        {
                            await SendReply(turnContext, StringsProvider.TryGet(BotResourceKeyConstants.Feedback), SuggestionExtension.GetFeedbackSuggestionActions());
                        });
                }
                res = true;
            }
            break;

            case ExpEvalResultType.Exception:
            case ExpEvalResultType.Invalid:
            {
                await SendReply(turnContext, "Invalid input, please try again!", SuggestionExtension.GetCommonSuggestionActions("Exit:exit"));

                requestState.CurrentState = ChatStateType.InvalidInput;
            }
            break;

            case ExpEvalResultType.Empty:    //TODO
            {
                await SendReply(turnContext, $"Evaluated empty expression of node : '{curLink._id}',please report this issue to the bot administrator.", SuggestionExtension.GetCommonSuggestionActions());
            }
            break;

            default:

                break;
            }
            return(res);
        }
        private async Task <bool> EvaluateExpressionInput(ITurnContext turnContext, RequestState requestState)
        {
            var               res     = false;
            var               text    = turnContext.Activity.Text;
            var               curLink = requestState.CurrentLink;
            ActionLink        actionResult;
            ExpEvalResultType op = curLink.NeuralExp.Next(text, out actionResult);

            switch (op)
            {
            case ExpEvalResultType.Skipped:
            case ExpEvalResultType.False:
            case ExpEvalResultType.True:
            {
                switch (actionResult.Type)
                {
                case LinkType.NeuralLink:
                {
                    var link = await DbLinkCollection.FindOneById(actionResult.LinkId);

                    if (link != null)
                    {
                        curLink = link;
                        requestState.StepForward(curLink);
                        await SendResponseForCurrentNode(turnContext, requestState);
                    }
                    else
                    {
                        //Invalid expression evaluation link id.
                    }
                }
                break;

                case LinkType.ActionLink:
                {
                    var action = await DbActionCollection.FindOneById(actionResult.LinkId);

                    await turnContext.SendActivityAsync(action.BuildActionRespose(turnContext));

                    await Task.Delay(1000).ContinueWith(async ct =>
                            {
                                await SendReply(turnContext, StringsProvider.TryGet(BotResourceKeyConstants.Feedback), SuggestionExtension.GetFeedbackSuggestionActions());
                            });

                    requestState.CurrentState = ChatStateType.RecordFeedback;
                }
                break;

                case LinkType.NeuralResource:
                    break;

                default:
                    break;
                }
            }
                res = true;
                break;

            case ExpEvalResultType.Exception:
            case ExpEvalResultType.Invalid:
            {
                await SendReply(turnContext, "Invalid input, Try again!", SuggestionExtension.GetCommonSuggestionActions());

                requestState.CurrentState = ChatStateType.InvalidInput;
            }
            break;

            case ExpEvalResultType.Empty:    //TODO
            default:

                break;
            }
            return(res);
        }