Azure認知服務學習:徒然學會了抗拒熱鬧,卻還來不及透悟真正的冷清;寫個聊天機器人治愈自己吧

      網友投稿 679 2022-05-30

      寫在前面

      之前上學使用華為的ModelArts平臺做了類似的圖像識別之類的小項目,零編碼,但是需要自己搞數據集,標注、選擇算法、訓練模型等,用的話直接調API。

      NLP方面之前的一個實習公司有用,對一些類似招股書文件數據進行核查的。那會我作為Java開發做些數據清洗的工作,調NLP的接口去識別一些表格,然后用java寫一些邏輯,把數據的按要求分類整理上傳。

      在之后工作中沒有接觸過,也沒有學習過,但是對這方面蠻感興趣的?;舅闶切“?,對NLP之類的算法也不懂,買了一本相關的書籍,也落灰了。看到一個Azure認知服務的活動,學習學習。

      博文內容主要是:使用Azure認知服務學習,涉及語言理解、文本翻譯、語音轉文本

      我徒然學會了抗拒熱鬧,卻還來不及透悟真正的冷清。--------張大春

      在使用之前我們需要先了解下相關概念

      一、關于認知服務的一些基本概念和術語

      什么是 Azure 認知服務?:

      認知服務

      : 提供認知理解(看、聽、說、理解,甚至可以決策的認知)功能的服務。

      認知服務主要分為四大類:

      影像

      語音

      語言

      決策

      Azure 認知服務是具有 REST API和客戶端庫 SDK的基于云的服務,可用于幫助你將認知智能構建到應用程序中。 即使你沒有人工智能 (AI) 或數據科學技能,也可向應用程序添加認知功能。Azure 認知服務包含各種 AI 服務,讓你能夠構建可以看、聽、說、理解,甚至可以決策的認知解決方案。

      我們要做一個可以和自己聊天的機器人,需要語言理解,即告訴機器人想說什么話,表達什么意思,我們先看看這部分

      二、什么是語言理解 (LUIS)?

      語言理解 (LUIS) 是一種基于云的對話式 AI 服務,可在用戶對話的自然語言文本中應用自定義機器學習智能,以便預測整體含義并提煉出相關的詳細信息。 LUIS 通過其自定義門戶、API 和 SDK 客戶端庫提供訪問權限。找重點,會提煉出相關信息,換句話講,就是把要表達的信息轉化成機器或者說AI能夠識別的信息。

      1)、服務構建步驟

      ########### Python 3.6 ############# # # This quickstart shows how to predict the intent of an utterance by using the LUIS REST APIs. # 導入模塊 import requests try: ########## # Values to modify. # YOUR-APP-ID: The App ID GUID found on the www.luis.ai Application Settings page. # 替換為自己的APP-ID appId = '949d3538-07df-4149-bee8-83dc7f4e11bd' # YOUR-PREDICTION-KEY: Your LUIS prediction key, 32 character value. prediction_key = '24440ef2829c45f0**61599ee00b496a' # YOUR-PREDICTION-ENDPOINT: Replace with your prediction endpoint. # For example, "https://westus.api.cognitive.microsoft.com/" prediction_endpoint = 'https://chatbot0.cognitiveservices.azure.cn/' # The utterance you want to use. # 你想和他說的話.. utterance = '一個人怎么生活?' ########## # The headers to use in this REST call. headers = { } # The URL parameters to use in this REST call. params ={ 'query': utterance, 'timezoneOffset': '0', 'verbose': 'true', 'show-all-intents': 'true', 'spellCheck': 'false', 'staging': 'false', 'subscription-key': prediction_key } # Make the REST call. response = requests.get(f'{prediction_endpoint}luis/prediction/v3.0/apps/{appId}/slots/production/predict', headers=headers, params=params) # Display the results on the console. print(response.json()) except Exception as e: # Display the error string. print(f'{e}')

      這里我們用docker搞一個python環境,然后執行一下腳本,測試一下

      ┌──[root@liruilongs.github.io]-[/liruilong] └─$ docker pull centos/python-36-centos7 ┌──[root@liruilongs.github.io]-[/liruilong] └─$ ls input luis_run.sh output predict.py ┌──[root@liruilongs.github.io]-[/liruilong] └─$ docker run --rm -it --name=chatbot -v $PWD/predict.py:/predict.py centos/python-36-centos7 /bin/bash (app-root) cd / (app-root) ls anaconda-post.log bin boot dev etc help.1 home lib lib64 media mnt opt predict.py proc root run sbin srv sys tmp usr var (app-root) python predict.py Traceback (most recent call last): File "predict.py", line 6, in import requests ModuleNotFoundError: No module named 'requests' (app-root) pip install requests ......................... Collecting requests Downloading https:/ ..... (app-root) python predict.py {'query': '一個人怎么生活?', 'prediction': {'topIntent': '生活加油', 'intents': {'生活加油': {'score': 0.8969882}, 'Calendar.ShowNext': {'score': 0.58274937}, 'Calendar.FindCalendarWhen': {'score': 0.25383785}, 'Places.GetReviews': {'score': 0.24764298}, 'Utilities.ReadAloud': {'score': 0.20971665}, 'HomeAutomation.QueryState': {'score': 0.15509635}, 'Calendar.CheckAvailability': {'score': 0.12212229}, 'Places.GetPriceRange': {'score': 0.122063436},........

      測試成功 :predict.py腳本

      2)、本地部署服務,啟動和運行

      運行 LUIS 的 Docker 容器

      ┌──[root@liruilongs.github.io]-[/liruilong] └─$ mkdir input output ┌──[root@liruilongs.github.io]-[/liruilong] └─$ ls input luis_run.sh output ┌──[root@liruilongs.github.io]-[/liruilong] └─$ cat luis_run.sh docker run --rm -it -p 5000:5000 --memory 4g --cpus 2 -v $PWD/input:/input -v $PWD/output:/output mcr.microsoft.com/azure-cognitive-services/language/luis Eula=accept Billing=https://chatbot0.cognitiveservices.azure.cn/ ApiKey=24440ef2829c45f0**61599ee00b496a ##這里參數填自己的 ┌──[root@liruilongs.github.io]-[/liruilong] └─$ docker run --rm -it -p 5000:5000 --memory 4g --cpus 2 -v $PWD/input:/input -v $PWD/output:/output mcr.microsoft.com/azure-cognitive-services/language/luis Eula=accept Billing=https://chatbot0.cognitiveservices.azure.cn/ ApiKey=24440ef2829c45f0a**1599ee00b496a ## 啟動容器 EULA Notice: Copyright ? Microsoft Corporation 2020. This Cognitive Services Container image is made available to you under the terms [https://go.microsoft.com/fwlink/?linkid=2018657] governing your subscription to Microsoft Azure Services (including the Online Services Terms [https://go.microsoft.com/fwlink/?linkid=2018760]). If you do not have a valid Azure subscription, then you may not use this container. Using '/input' for reading models and other read-only data. Using '/output/luis/ff2a18ee78a1' for writing logs and other output data. Logging to console. Submitting metering to 'https://chatbot0.cognitiveservices.azure.cn/'. warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35] No XML encryptor configured. Key {d826e89b-febe-4b93-bad8-db07cb994012} may be persisted to storage in unencrypted form. warn: Microsoft.AspNetCore.Server.Kestrel[0] Overriding address(es) 'http://+:80'. Binding to endpoints defined in UseKestrel() instead. Hosting environment: Production Content root path: /app Now listening on: http://0.0.0.0:5000 Application started. Press Ctrl+C to shut down.

      應用包上傳,放到input文件夾下

      ┌──(liruilong?Liruilong)-[/mnt/c/Users/lenovo/Downloads] └─$ scp ./949d3538-07df-4149-bee8-83dc7f4e11bd_production.gz root@192.168.26.55:/ 949d3538-07df-4149-bee8-83dc7f4e11bd_production.gz 100% 6434KB 19.0MB/s 00:00

      放到input文件夾下,啟動容器

      ┌──[root@liruilongs.github.io]-[/] └─$ cp 949d3538-07df-4149-bee8-83dc7f4e11bd_production.gz /liruilong/input/ ┌──[root@liruilongs.github.io]-[/] └─$ cd /liruilong/input/ ┌──[root@liruilongs.github.io]-[/liruilong/input] └─$ ls 949d3538-07df-4149-bee8-83dc7f4e11bd_production.gz ┌──[root@liruilongs.github.io]-[/liruilong/input] └─$ cd .. ┌──[root@liruilongs.github.io]-[/liruilong] └─$ pwd /liruilong ┌──[root@liruilongs.github.io]-[/liruilong] └─$ # 啟動容器服務 ┌──[root@liruilongs.github.io]-[/liruilong] └─$ docker run --rm --name=demo -it -p 5000:5000 --memory 4g --cpus 2 -v $PWD/input:/input -v $PWD/output:/output mcr.microsoft.com/azure-cognitive-services/language/luis Eula=accept Billing=https://chatbot0.cognitiveservices.azure.cn/ ApiKey=24440ef2829c45f0a**1599ee00b496a EULA Notice: Copyright ? Microsoft Corporation 2020. This Cognitive Services Container image is made available to you under the terms [https://go.microsoft.com/fwlink/?linkid=2018657] governing your subscription to Microsoft Azure Services (including the Online Services Terms [https://go.microsoft.com/fwlink/?linkid=2018760]). If you do not have a valid Azure subscription, then you may not use this container. Using '/input' for reading models and other read-only data. Using '/output/luis/da43b9631f9d' for writing logs and other output data. Logging to console. Submitting metering to 'https://chatbot0.cognitiveservices.azure.cn/'. warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35] No XML encryptor configured. Key {886021ff-6bf5-423d-be12-ba9b52383b9e} may be persisted to storage in unencrypted form. warn: Microsoft.AspNetCore.Server.Kestrel[0] Overriding address(es) 'http://+:80'. Binding to endpoints defined in UseKestrel() instead. Hosting environment: Production Content root path: /app Now listening on: http://0.0.0.0:5000 Application started. Press Ctrl+C to shut down.

      隨便找一句測試一下:

      據悉,該活動由世界休閑組織,杭州市政府主辦,中國國際科技促進會三農發展工作委員會等聯合會承辦。

      { "query": "據悉,該活動由世界休閑組織,杭州市政府主辦,中國國際科技促進會三農發展工作委員會等聯合會承辦。", "topScoringIntent": { "intent": "Places.GetPhoneNumber", "score": 0.9103095 }, "entities": [ { "entity": "工作", "type": "Calendar.Subject", "startIndex": 35, "endIndex": 36, "score": 0.63087225 }, { "entity": "際科技促進會三農發展工作委員會等聯合會承辦 。", "type": "Note.Text", "startIndex": 25, "endIndex": 46, "score": 0.6798551 }, { "entity": "杭州市", "type": "Places.AbsoluteLocation", "startIndex": 14, "endIndex": 16, "score": 0.966151536 }, { "entity": "國際科", "type": "Places.PlaceName", "startIndex": 24, "endIndex": 26, "score": 0.3605822 }, { "entity": "工作", "type": "Calendar.DestinationCalendar", "startIndex": 35, "endIndex": 36, "resolution": { "values": [ "工作" ] } }, { "entity": "工作", "type": "Places.OpenStatus", "startIndex": 35, "endIndex": 36, "resolution": { "values": [ "工作" ] } }, { "entity": "休閑", "type": "RestaurantReservation.Atmosphere", "startIndex": 9, "endIndex": 10, "resolution": { "values": [ "休閑" ] } } ] }

      回過頭看看語言理解的定義:

      語言理解 (LUIS) 是一種基于云的對話式 AI 服務,可在用戶對話的自然語言文本中應用自定義機器學習智能,以便預測整體含義并提煉出相關的詳細信息。 LUIS 通過其自定義門戶、API 和 SDK 客戶端庫提供訪問權限。找重點,會提煉出相關信息,換句話講,就是把要表達的信息轉化成機器或者說AI能夠識別的信息。

      簡單嘗試一下,可以把生成的實體組合,作為關鍵字給類似圖靈機器人用,進行簡單對話,簡單測試了下,發現效果很一般,可能方法不太對,或者我找的機器人太差了,Azure的機器人需要注冊綁卡…所以這個以后有時間研究研究

      下面看看其他的認知服務,語音合成產品系列,我們現在聊天大都是語音,對于聊天機器人來說,需要把語音轉化為文本。然后才是語言理解。

      Azure認知服務學習:徒然學會了抗拒熱鬧,卻還來不及透悟真正的冷清;寫個聊天機器人治愈自己吧

      三、什么是語音轉文本?

      使用語音轉文本(也稱為語音識別)功能,可將音頻流實時聽錄為文本。 應用程序、工具或設備可以使用、顯示和處理此文本即命令輸入。

      1)、服務構建:

      2) JAVA開發環境準備,拉去github的Demo

      這里我們使用過java的方式

      Git :https://github.com/Azure-Samples/cognitive-services-speech-sdk/tree/master/quickstart/java/jre/from-microphone

      3)調用API測試

      package speechsdk.quickstart; import com.microsoft.cognitiveservices.speech.*; import com.microsoft.cognitiveservices.speech.audio.AudioConfig; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import static com.microsoft.cognitiveservices.speech.ResultReason.*; /** * @Classname Program * @Description TODO * @Date 2021/10/30 13:58 * @Created LiRuilong */ public class Program { private static Semaphore stopTranslationWithFileSemaphore; public static void main(String[] args) throws InterruptedException, ExecutionException { SpeechConfig speechConfig = SpeechConfig.fromSubscription("eb48f918a90448fe***53633d6301ebb", "chinanorth2"); speechConfig.setSpeechRecognitionLanguage("zh-cn"); // 從文件中識別 // SpeechRecognitionResult result = fromFile(speechConfig); // 從麥克風識別 SpeechRecognitionResult result = fromMic(speechConfig); switch (result.getReason()) { case RecognizedSpeech: System.out.println("We recognized: " + result.getText()); break; case NoMatch: System.out.println("NOMATCH: 無法識別語音."); break; case Canceled: { CancellationDetails cancellation = CancellationDetails.fromResult(result); System.out.println("CANCELED: Reason=" + cancellation.getReason()); if (cancellation.getReason() == CancellationReason.Error) { System.out.println("CANCELED: ErrorCode=" + cancellation.getErrorCode()); System.out.println("CANCELED: ErrorDetails=" + cancellation.getErrorDetails()); System.out.println("CANCELED: Did you update the subscription info?"); } } default:{}; break; } } /** * @param speechConfig: * @return: void * @Description 從麥克風識別 * @author LiRui long * @date 2021/11/1 18:30 **/ public static SpeechRecognitionResult fromMic(SpeechConfig speechConfig) throws InterruptedException, ExecutionException { AudioConfig audioConfig = AudioConfig.fromDefaultMicrophoneInput(); SpeechRecognizer recognizer = new SpeechRecognizer(speechConfig, audioConfig); System.out.println("對這麥克風說話."); Future task = recognizer.recognizeOnceAsync(); SpeechRecognitionResult result = task.get(); return result; } /** * @param speechConfig: * @return: com.microsoft.cognitiveservices.speech.SpeechRecognitionResult * @Description 從文件中識別 * @author LiRui long * @date 2021/11/1 18:29 **/ public static SpeechRecognitionResult fromFile(SpeechConfig speechConfig) throws InterruptedException, ExecutionException { AudioConfig audioConfig = AudioConfig.fromWavFileInput("E:\\docker\\cognitive-services-speech-sdk\\quickstart\\java\\jre\\translate-speech-to-text\\src\\speechsdk\\quickstart\\梁靜茹-我還記得.wav"); SpeechRecognizer recognizer = new SpeechRecognizer(speechConfig, audioConfig); // First initialize the semaphore. stopTranslationWithFileSemaphore = new Semaphore(0); recognizer.recognizing.addEventListener((s, e) -> { System.out.println("RECOGNIZING: Text=" + e.getResult().getText()); }); recognizer.recognized.addEventListener((s, e) -> { if (e.getResult().getReason() == RecognizedSpeech) { System.out.println("RECOGNIZED: Text=" + e.getResult().getText()); } else if (e.getResult().getReason() == NoMatch) { System.out.println("NOMATCH: Speech could not be recognized."); } }); recognizer.canceled.addEventListener((s, e) -> { System.out.println("CANCELED: Reason=" + e.getReason()); if (e.getReason() == CancellationReason.Error) { System.out.println("CANCELED: ErrorCode=" + e.getErrorCode()); System.out.println("CANCELED: ErrorDetails=" + e.getErrorDetails()); System.out.println("CANCELED: Did you update the subscription info?"); } stopTranslationWithFileSemaphore.release(); }); recognizer.sessionStopped.addEventListener((s, e) -> { System.out.println("\n Session stopped event."); stopTranslationWithFileSemaphore.release(); }); Future task = recognizer.recognizeOnceAsync(); SpeechRecognitionResult result = task.get(); return result; //System.out.println("RECOGNIZED: Text=" + result.getText()); } }

      四、什么是文本翻譯

      文本翻譯是一種基于云的機器翻譯服務,是 Azure 認知服務系列 REST API 的一部分。 翻譯器可用于任何操作系統

      1)、服務構建:

      2)Node環境調用API測試

      這里我們用node環境來測試一下;

      $ docker pull node $ mkdir translateDemo;cd translateDemo $ vim translateDemo.js

      測試js準備

      const axios = require('axios').default; const { v4: uuidv4 } = require('uuid'); let subscriptionKey = "3c6588c7026b41a4**7f81551cb4a737"; let endpoint = "https://api.translator.azure.cn/"; let location = "chinanorth"; axios({ baseURL: endpoint, url: '/translate', method: 'post', headers: { 'Ocp-Apim-Subscription-Key': subscriptionKey, 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': uuidv4().toString() }, params: { 'api-version': '3.0', 'from': 'zh-Hans', 'to': ['zh-Hant', 'en'] }, data: [{ 'text': '我徒然學會了抗拒熱鬧,卻還來不及透悟真正的冷清。--------張大春' }], responseType: 'json' }).then(function(response){ console.log(JSON.stringify(response.data, null, 4)); })

      這里測試將 【我徒然學會了抗拒熱鬧,卻還來不及透悟真正的冷清。--------張大春】中文簡體翻譯為中文繁體,英語。

      ┌──[root@liruilongs.github.io]-[~/translateDemo] └─$ vim translateDemo.js ┌──[root@liruilongs.github.io]-[~/translateDemo] └─$ docker run -it --rm --name=translateDemo -v $PWD/translateDemo.js:/root/translateDemo.js node:latest /bin/bash root@35376c1c05d8:/# pwd / root@35376c1c05d8:/# cd root/;npm install axios uuid added 3 packages, and audited 4 packages in 7s 1 package is looking for funding run `npm fund` for details found 0 vulnerabilities root@35376c1c05d8:~# node translateDemo.js [ { "translations": [ { "text": "我徒然學會了抗拒熱鬧,卻還來不及透悟真正的冷清。 --------張大春", "to": "zh-Hant" }, { "text": "I learned in vain to resist the excitement, but it is too late to understand the real cold. -------- Zhang Dachun", "to": "en" } ] } ] root@35376c1c05d8:~#

      時間原因,關于Azure認知服務免費提供的AI服務就嘗試到這里,聊天機器人沒有寫出來哈,但是對Azure認知服務有一些了解,嘻,生活加油 ^ _ ^

      AI平臺 API

      版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。

      上一篇:軟件測試人員必讀的經典書籍(附電子書),前阿里大佬給我推薦...
      下一篇:按照文件名最后數字進行排序(文件按文件名最后的數字排序)
      相關文章
      国产亚洲自拍一区| 区久久AAA片69亚洲| 亚洲动漫精品无码av天堂| 亚洲一区无码精品色| 亚洲国产成人精品久久久国产成人一区二区三区综 | 亚洲成人黄色网址| 亚洲国产精品国自产电影| 亚洲AV无码专区在线播放中文| 亚洲一区精品无码| 亚洲色大成网站WWW久久九九| 久久亚洲av无码精品浪潮| 亚洲综合亚洲综合网成人| 国产亚洲老熟女视频| 亚洲三区在线观看无套内射| 伊人久久大香线蕉亚洲五月天| 亚洲中文字幕无码不卡电影 | 亚洲va在线va天堂va手机| 久久久久精品国产亚洲AV无码| 国产精品亚洲片在线va| 2020久久精品亚洲热综合一本| 亚洲最大福利视频| 亚洲国产av玩弄放荡人妇| 国产偷国产偷亚洲高清人| 国产成人毛片亚洲精品| 中文国产成人精品久久亚洲精品AⅤ无码精品| 亚洲一区二区三区免费| 国产亚洲色婷婷久久99精品| 亚洲VA中文字幕无码一二三区| 亚洲国产精品久久久久婷婷软件| 18gay台湾男同亚洲男同| 亚洲国产精品久久网午夜 | 亚洲午夜国产精品无码| 亚洲AV无码精品色午夜果冻不卡| 亚洲一区免费观看| 亚洲乱码卡三乱码新区| 亚洲精品乱码久久久久久蜜桃图片 | 亚洲黄片手机免费观看| 亚洲免费人成在线视频观看| 无码乱人伦一区二区亚洲| 亚洲人成在久久综合网站| 亚洲人成网站在线播放2019|