跳到主要內容

[Bot Framework] 應用微軟Cognitive Services實作LUIS Bot (III), 實作LUIS Bot



首先,

建立一個Score.cs來表達分數

    public class Score
    {
        public Score(string user, int point, DateTime dateTime)
        {
            User = user;
            Point = point;
            DateTime = dateTime;
        }
        public string User { get; set; }
        public int Point { get; set; }
        public DateTime DateTime { get; set; }
        public override string ToString()
        {
            StringBuilder sb =new StringBuilder();
            sb.Append($"User:{User}, Score:{Point}, Date: {DateTime}");
            return sb.ToString();
        }
    }

再來, 我們建立Repository 負責資料存取(為了簡化說明所以沒有特意去串DB,而是直接將分數的資料建出來)
   
    public interface IRepository<T> where T:class
    {
       IEnumerable<T> GetAll();
    }
    public class ScoreRepository:IRepository<Score>
    {
        public  IEnumerable<Score> GetAll()
        {
            var scores = new List<Score>();
            scores.Add(new Score("Andy", 7, DateTime.Now));
            scores.Add(new Score("Andy", 20, DateTime.Now.AddDays(-7)));
            scores.Add(new Score("Andy", 13, DateTime.Now));
            scores.Add(new Score("Bob", 6, DateTime.Now));
            scores.Add(new Score("Bob", 19, DateTime.Now));
            scores.Add(new Score("Calvin", 35, DateTime.Now.AddDays(-30)));
            return scores;
        }
    }


建立Service 負責處理較複雜的商業邏輯來獲得最的高分數(這邊_scoRepository 宣告為Interface的目的是想提高程式的可測試性,將來做Unit test的時候我們就可以去Mock Repository)
    public class ScoreService
    {
        private IRepository<Score> _scoRepository;
        public ScoreService(IRepository<Score> scoRepository)
        {
            this._scoRepository = scoRepository;
        }
        public string GetHighScore()
        {
            return _scoRepository.GetAll().OrderByDescending(x => x.Point).FirstOrDefault()?.ToString();
        }
        public string GetHighScore(DateTime periodOfTime)
        {
            return _scoRepository.GetAll().Where(t => t.DateTime >= periodOfTime).OrderByDescending(x => x.Point).FirstOrDefault()?.ToString();
        }
    }






建立LUIS Dialog 處理對話
    [LuisModel("Your APP ID", "Your secret key")]
    [Serializable]
    public class LUISDialog: LuisDialog<object>
    {
       // Implement None Intent
       // Implement HighScore Intent
    }


LUIS dialog中為None Intent 新增一個方法
        [LuisIntent("")]
        [LuisIntent("None")]
        public async Task None(IDialogContext context, LuisResult result)
        {
            // Not a match -- Start a new Game
            //context.Call(new NumberGuesserDialog(), null);
            var reply = context.MakeMessage();
            reply.Text = "Sorry, I didn't get it";
            //Make you cortana speak
            reply.Speak = "Sorry, I can't understand";
            await context.PostAsync(reply);
            context.Wait(this.MessageReceived);
        }







實作回復最得高分的程式碼
        private async Task ShowHighScores(IDialogContext context, int paramDays)
        {
            // Get Yesterday
            var ParamYesterday = DateTime.Now.AddDays(paramDays);
            ScoreService scoreService=new ScoreService(new ScoreRepository());
            var scoreRecord = scoreService.GetHighScore(ParamYesterday);
            // Create a reply message
            var resultMessage = context.MakeMessage();
            resultMessage.Type = "message";
            resultMessage.Text = scoreRecord;
            resultMessage.Speak = scoreRecord;
            // Send Message
            await context.PostAsync(resultMessage);
        }

由於LUIS傳回來的Entity不見得會是數字
(例如:show me the high score for the past two days, 其中two 就是Entity)
所以我們須將英文數字轉成int, 讓我們等一下在做日期加減時能夠正常運算
        static int ParseEnglish(string number)
        {
            string[] words = number.ToLower().Split(new char[] {' ', '-', ','}, StringSplitOptions.RemoveEmptyEntries);
            string[] ones = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
            string[] teens =
                {"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
            string[] tens = {"ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
            Dictionary<string, int> modifiers = new Dictionary<string, int>()
            {
                {"billion", 1000000000},
                {"million", 1000000},
                {"thousand", 1000},
                {"hundred", 100}
            };
            if (number == "eleventy billion")
                return int.MaxValue; // 110,000,000,000 is out of range for an int!
            int result = 0;
            int currentResult = 0;
            int lastModifier = 1;
            foreach (string word in words)
            {
                if (modifiers.ContainsKey(word))
                {
                    lastModifier *= modifiers[word];
                }
                else
                {
                    int n;
                    if (lastModifier > 1)
                    {
                        result += currentResult * lastModifier;
                        lastModifier = 1;
                        currentResult = 0;
                    }
                    if ((n = Array.IndexOf(ones, word) + 1) > 0)
                    {
                        currentResult += n;
                    }
                    else if ((n = Array.IndexOf(teens, word) + 1) > 0)
                    {
                        currentResult += n + 10;
                    }
                    else if ((n = Array.IndexOf(tens, word) + 1) > 0)
                    {
                        currentResult += n * 10;
                    }
                    else if (word != "and")
                    {
                        throw new ApplicationException("Unrecognized word: " + word);
                    }
                }
            }
            return result + currentResult * lastModifier;
        }


LUIS dialog中為HighScore Intent 新增一個方法
        [LuisIntent("HighScores")]
        public async Task GetHighScore(IDialogContext context, LuisResult result)
        {
            bool isIntentMatch = false;
            foreach (var objIntent in result.Intents)
            {
                if (objIntent.Intent == "HighScores" && objIntent.Score >= .98f)
                {
                    isIntentMatch = true;
                }
            }
            if (!isIntentMatch)
            {
                var reply = context.MakeMessage();
                reply.Type = "message";
                reply.Text = "I don't understand";
                reply.Speak = "I don't understand";
                await context.PostAsync(reply);
                context.Wait(this.MessageReceived);
                return;
            }
            // Determine the days in the past
            // to search for High Scores
            int intDays = -1;
            #region PeriodOfTime
            EntityRecommendation PeriodOfTime;
            if (result.TryFindEntity("PeriodOfTime", out PeriodOfTime))
            {
                switch (PeriodOfTime.Entity)
                {
                    case "month":
                        intDays = -30;
                        break;
                    case "day":
                        intDays = -1;
                        break;
                    case "week":
                        intDays = -7;
                        break;
                    default:
                        intDays = -1;
                        break;
                }
            }
            #endregion
            #region Days
            EntityRecommendation Days;
            if (result.TryFindEntity("Days", out Days))
            {
                // Set Days
                int intTempDays;
                if (int.TryParse(Days.Entity, out intTempDays))
                {
                    // A Number was passed
                    intDays = (Convert.ToInt32(intTempDays) * (-1));
                }
                else
                {
                    // A number was not passed
                    // Call ParseEnglish Method
                    // From: http://stackoverflow.com/questions/11278081/convert-words-string-to-int
                    intTempDays = ParseEnglish(Days.Entity);
                    intDays = (Convert.ToInt32(intTempDays) * (-1));
                }
                // 30 days maximum
                if (intDays > 30)
                {
                    intDays = 30;
                }
            }
            #endregion
            await ShowHighScores(context, intDays);
            context.Wait(this.MessageReceived);
        }


最後在MessagesController.cs中使用LUISDialog
        public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                Conversation.SendAsync(activity, ()=> new LUISDialog());
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;
        }

做到這裡差不多可以收工了><

以下是測試結果:



Source code:
https://github.com/andy51002000/MyLUISBot.git

留言

這個網誌中的熱門文章

[解決方法] docker: permission denied

前言 當我們執行docker 指令時若出現以下錯誤訊息 docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.26/containers/create: dial unix /var/run/docker.sock: connect: permission denied. See 'docker run --help'. 表示目前的使用者身分沒有權限去存取docker engine, 因為docker的服務基本上都是以root的身分在執行的, 所以在指令前加sudo就能成功執行指令 但每次實行docker指令(就連docker ps)都還要加sudo實在有點麻煩, 正確的解法是 我們可以把目前使用者加到docker群組裡面, 當docker service 起來時, 會以這個群組的成員來初始化相關服務 sudo groupadd docker sudo usermod -aG docker $USER 需要退出重新登錄後才會生效 Workaround 因為問題是出在權限不足, 如果以上方法都不管用的話, 可以手動修改權限來解決這個問題 sudo chmod 777 /var/run/docker.sock https://docs.docker.com/install/linux/linux-postinstall/

[C#] Visual Studio, 如何在10分鐘內快速更改命名專案名稱

前言: 由於工作需要, 而且懶得再重寫類似的專案, 所以常常將之前寫的專案複製一份加料後, 再重新命名編譯 假設今天我有一個專案HolyUWP, 我想把它重新命名成 BestUWP 時該怎麼做? 以下是幾個簡單的的步驟 使用Visual Studio 2017 備份原來專案 更改Solution名稱 更改Assembly name, Default namespce 更改每支程式碼的Namespace 更改專案資料夾名稱 備份原來專案 由於怕改壞掉, 所以在改之前先備份 更改Solution名稱 更改sln的名稱, 這邊我改成BestUWP.sln 使用Visual Studio打開你的.sln, 右鍵點擊Solution後選擇Rename, 這邊我把它重新命名成BestUWP(跟檔案名稱一致) 必要的話可以順便修改Porject名稱 更改Assembly name, Default namespce 進入 Project > OOXX Properties    修改Assembly Name, Default namesapce 更改每支程式碼的Namespace 基本上隨便挑一支有用到預設Namesapce(HolyUWP)的程式碼來改就好了 重新命名後點擊Apply,  這個動作做完後所有用到舊Namespace的程式碼都會被改成新的 更改專案資料夾名稱 以上動作做完後, 基本上就可以把專案編譯出來測看看了~

[解決方法] mac 作業系統上無法使用 docker

  錯誤訊息 Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? 原因 因為 docker 的設計是走 client-server 的架構,  如果少裝了 server 的部分就會出現以上的錯誤訊息 解決方法 因為 docker daemon 需要使用 linux kernel 上的某些功能, 所以若想要在 mac 的 OS X 上使用 docker 必須額外起一台 linux VM 給 docker daemon 用  Step 1. 安裝 virtual box $ brew install virtualbox --cask   Step 2. 安裝 docker machine $ brew install docker-machine --cask   Step 3. 設定 使用 docker-machine 建立 VM 跑容器 $docker-machine create --driver virtualbox default $docker-machine restart   輸出環境變數 $docker-machine env default 如果執行以上的指令出現錯誤訊息 Error checking TLS connection: ...  可以執行以下指令重新產生憑證 $docker-machine regenerate-certs 最後套用環境變數, 讓 docker 知道要怎麼去跟這台 VM 溝通  $eval $(docker-machine env default)   測試 若做完以上的步驟沒噴錯誤訊息的話, 可以跑個 hello-world 看看 docker daemon 有沒有起來 $docker run hello-world Unable to find image 'hello-world:latest' locally latest: Pulling from library/hello-world 0e03bdcc26d7: Pull complete Digest: sha256:95ddb6c31407e84e91a986b004aee40975cb0