Upload
ayasehiro
View
579
Download
0
Embed Size (px)
Citation preview
Xamarin.FormsでもCognitive Servicesを使おう!
2016年10月15日
綾瀬 ヒロ
Twitter @ayasehiro
JXUGC #17 お前の Xamarin アプリを見せてみろ!
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
自己紹介
u綾瀬 ヒロ
Twitter:@ayasehiro
FlashAirエバンジェリスト(自称)
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
運輸サービス系インダストリーマネージャです(元鉄道系SE)趣味で庭園鉄道の建設をしていたりします。昔、Mac用フリーソフト「何かon林檎」を作っていました。
Arduino/FlashAir/Xamarin/鉄道模型
Qiita: http://qiita.com/ayasehiroMakersHub: https://makershub.jp/ayasehiro
目次
1. Cognitive Servicesについて
2. MS Translator APIについて
3. アプリケーション例
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
本発表内容は、個人の見解であり、所属する組織の公式見解ではありません。
これまでこんなアプリを作りましたが……
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
鉄道模型ミニレイアウトの運転⽤アプリ
(FlashAir対応版)
Gゲージ⼤型鉄道模型の庭園鉄道運転⽤アプリ
(FlashAir対応版)
Microsoft Cognitive ServicesComputer Vision API - Analyzeを
使った「しゃべるデジカメ スマフォ版」
今回は、こんなの作りました!
「しゃべる翻訳アプリ OCR/音声認識版」
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
JXUGC #17 お前のXamarinアプリを見せてみろ!
Microsoft Cognitive ServicesのComputer Vision API及びBing Speech APIを使った翻訳アプリ
1.Cognitive Servicesについて
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Cognitive Services
u さまざまなAPIが公開されています。 https://www.microsoft.com/cognitive-services/
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Cognitive Services
u Computer Vision API – 画像分析機能
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Cognitive Services
u Computer Vision API – 画像分析機能(タグ・キャプション等)
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Cognitive Services
u Computer Vision API – 画像分析機能(有名人検索)
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Cognitive Services
u Computer Vision API – 画像分析機能(文字認識 OCR)
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Cognitive Services
u Computer Vision API – 画像分析機能(サムネイル生成)
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Cognitive Services
u Computer Vision API – Analyze機能
u 画像データをもとに、タグ(属性)情報とキャプション(説明文)を自動生成する機能。
u JPEG, PNG, GIF, BMP形式に対応
u 4MBまで
u 50x50ピクセル以上が必要
u REST API
u Http MethodでPOSTするだけで、JSON形式でタグ・キャプション等の情報を取得できる
u 無料利用可能
u 1分間20リクエストまで
u 1ヵ月5,000リクエストまで
Http Method POST
Request URL https://api.projectoxford.ai/vision/v1.0/analyze?visualFeatures=Description,Tags[&maxCandidates]
Request parameters maxCandidates (optional) Maximum number of candidate descriptions to be returned. The default is 1.
Request headers Content-Type (optional) Media type of the body sent to the API.
Ocp-Apim-Subscription-Key Subscription key which provides access to this API. Found in your subscriptions.
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Cognitive Services
u Computer Vision API – OCR機能
u 画像データをもとに、文字情報を読み取る(OCR)機能。
u JPEG, PNG, GIF, BMP形式に対応
u 4MBまで
u 40x40~3200x3200ピクセルの間、100Mピクセル以内
u REST API
u Http MethodでPOSTするだけで、JSON形式でタグ・キャプション等の情報を取得できる
u 無料利用可能
u 1分間20リクエストまで
u 1ヵ月5,000リクエストまで
Http Method POST
Request URL https://api.projectoxford.ai/vision/v1.0/ocr[?language][&detectOrientation ]
Request parameters language (optional) The BCP-47 language code of the text to be detected in the image.The default value is "unk", then the service will auto detect the language of the text in the image.
detectOrientation(optional) Whether detect the text orientation in the image. With detectOrientation=true the OCR service tries to detect the image orientation and correct it before further processing (e.g. if it's upside-down).
Request headers Content-Type (optional) Media type of the body sent to the API.
Ocp-Apim-Subscription-Key Subscription key which provides access to this API. Found in your subscriptions.
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Cognitive Services
u Bing Speech API(音声認識) https://www.microsoft.com/cognitive-services/en-us/speech-api
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Cognitive Services
u Bing Speech API – Speech Recognition機能
u 音声データをもとに、文字情報を認識する機能。
uPCM single channel、Siren、SirenSR形式に対応
u REST API
uHttp MethodでPOSTするだけで、JSON形式で音声認識した
文字データを取得できる
u 無料利用可能
u1ヵ月5,000リクエストまで
u機能ごとに20リクエスト/分まで
u全機能で60リクエスト/分まで
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Cognitive Services
u Bing Speech API – Speech Recognition機能
u 対応言語
language-Country
English Name language-Country
English Name language-Country
English Name language-Country
English Name
ar-EG* Arabic (Egypt) en-IN English (India) fr-FR French(France) pt-BR Portuguese(Brazil)
ca-ES Catalan(Spain) en-NZ English (New Zealand) it-IT Italian(Italy) pt-PT Portuguese(Por
tugal)
da-DK Danish(Denmark) en-US English (United
States) ja-JP Japanese(Japan) ru-RU Russian(Russia)
de-DE German(Germany) es-ES Spanish(Spain) ko-KR Korean (Korea) sv-SE Swedish(Swede
n)
en-AU English(Australia) es-MX Spanish
(Mexico) nb-NO Norwegian-Bokmal (Norway) zh-CN Chinese
(China)
en-CA English(Canada) fi-FI Finnish(Finland) nl-NL Dutch(Netherlan
ds) zh-HK Chinese (Hong Kong SAR)
en-GB English(United Kingdom) fr-CA French(Canada) pl-PL Polish(Poland) zh-TW Chinese
(Taiwan) *ar-EG supports Modern Standard Arabic (MSA)
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
2.Translator APIについて
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Translator API
u 翻訳APIが公開されている https://www.microsoft.com/en-us/translator/default.aspx
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Translator API
u Microsoft Translator - Text Translation API
u 指定した文字列を、指定した言語Aから言語Bに翻訳する機能。
u REST API(HTTP Interfaceの例)
uHttp MethodでPOSTするだけで、翻訳結果を得られる。
u 無料利用可能
u1ヵ月2,000,000文字まで
Http Method GET / POST
Request URL http://api.microsofttranslator.com/v2/Http.svc/Translate?text=“翻訳したい文字列(エンコード要)"&from="言語A”&to="言語B"
Request headers Content-Type (optional) Media type of the body sent to the API.
Authorization Subscription key which provides access to this API. Found in your subscriptions.
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
Microsoft Translator API
u Microsoft Translator - Text Translation API
u 対応言語(2016年6月現在)
Language Code English Name Language Code English Name Language Code English Nameaf Afrikaans ht Haitian Creole fa Persianar Arabic he Hebrew pl Polishbs-Latn Bosnian (Latin) hi Hindi pt Portuguesebg Bulgarian mww Hmong Daw otq Querétaro Otomica Catalan hu Hungarian ro Romanianzh-CHS Chinese Simplified id Indonesian ru Russianzh-CHT Chinese Traditional it Italian sr-Cyrl Serbian (Cyrillic)hr Croatian ja Japanese sr-Latn Serbian (Latin)cs Czech sw Kiswahili sk Slovakda Danish tlh Klingon sl Sloveniannl Dutch tlh-Qaak Klingon (pIqaD) es Spanishen English ko Korean sv Swedishet Estonian lv Latvian th Thaifi Finnish lt Lithuanian tr Turkishfr French ms Malay uk Ukrainiande German mt Maltese ur Urduel Greek no Norwegian vi Vietnamese
cy Welsh yua Yucatec Maya2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
3.アプリケーション例(1)
Microsoft Cognitive Services
Computer Vision API - Analyzeを使った
「しゃべるデジカメ スマフォ版」
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
(1)しゃべるデジカメ スマフォ版
u Computer Vision API – Describe Image機能を使って
スマートフォン内蔵カメラで撮影した写真に、
自動キャプション付けを行い、キャプション(英語)を日本語に翻訳し、
合成音声で発生する。
画像ファイル 画像ファイルの送信
テキストファイル受信
写真撮影
XamarinApp
合成音声発生
Computer Vision APIDescribe Image機能
Microsoft Azure
”a cat is sitting in the grass”
a cat is sitting in the grass
MS Translator APIテキストファイル翻訳
テキストファイル生成
a cat is sitting in the grass草の上に座っている猫
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
合成音声で発声
”a cat is sitting in the grass”草の上に座っている猫
”a cat is sitting in the grass”草の上に座っている猫
(1)しゃべるデジカメ スマフォ版
u Vision API - AnalyzeをXamarin.Formsで使う
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
public async Task<String> getCaptionFromPhoto(String filename, byte[] image) {String urlString ="https://api.projectoxford.ai/vision/v1.0/analyze?visualFeatures=Description,Tags";
var httpClient = new HttpClient();httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", tokenVisionAPI); httpClient.DefaultRequestHeaders.Add("maxCandidates", "1");
String boundary = "1234567890";var content = new MultipartFormDataContent(boundary);content.Add(new StreamContent(new MemoryStream(image)), filename, filename);
HttpResponseMessage aResponse = await httpClient.PostAsync(urlString, content);
String result = aResponse.Content.ReadAsStringAsync().Result;return result;
}
(1)しゃべるデジカメ スマフォ版
u Vision API - AnalyzeをXamarin.Formsで使う
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
https://www.microsoft.com/cognitive-services/en-US/subscriptions
tokenVisionAPI
3.アプリケーション例(2)
Microsoft Cognitive Services
Computer Vision API - OCRを使った
「しゃべる翻訳アプリ OCR版」
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
(2)しゃべる翻訳アプリ OCR版
u Computer Vision API – OCR機能を使ってスマートフォン内蔵カメラで
撮影した写真をOCRして、読み取った文字列を翻訳し、合成音声で発生する。
(対応パターン:自動判別→日本語、日本語→英語)
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
画像ファイル 画像ファイルの送信
テキストファイル受信
写真撮影
XamarinApp
合成音声発生
Computer Vision APIOCR機能
Microsoft Azure
Inhaltsverzeichnis…
MS Translator APIテキストファイル翻訳
テキストファイル生成⽬次…
合成音声で発声
”a cat is sitting in the grass”草の上に座っている猫
Inhaltsverzeichnis…
(2)しゃべる翻訳アプリ OCR版
u Vision API - OCRをXamarin.Formsで使う
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
public async Task<String> getOCRFromPhoto(String filename, byte[] image) {String urlString = "https://api.projectoxford.ai/vision/v1.0/ocr?Ja";String boundary = "1234567890";var httpClient = new HttpClient();httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", tokenVisionAPI);var content = new MultipartFormDataContent(boundary);content.Add(new StreamContent(new MemoryStream(image)), filename, filename);HttpResponseMessage aResponse = await httpClient.PostAsync(urlString, content);String result = aResponse.Content.ReadAsStringAsync().Result;
String str = "";RootClass rc = JsonConvert.DeserializeObject<RootClass>(result);for (int idx = 0; idx < rc.regions.Length; idx++)
for (int idx2 = 0; idx2 < rc.regions[idx].lines.Length; idx2++)for (int idx3 = 0; idx3 < rc.regions[idx].lines[idx2].words.Length; idx3++)
str += rc.regions[idx].lines[idx2].words[idx3].text;return str;
}
(2)しゃべる翻訳アプリ OCR版
u Vision API - OCRをXamarin.Formsで使う
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
[Newtonsoft.Json.JsonObjectAttribute(MemberSerialization = Newtonsoft.Json.MemberSerialization.OptIn)]public partial class RootClass {
[Newtonsoft.Json.JsonPropertyAttribute()] public string language;[Newtonsoft.Json.JsonPropertyAttribute()] public double textAngle;[Newtonsoft.Json.JsonPropertyAttribute()] public string orientation;[Newtonsoft.Json.JsonPropertyAttribute()] public Regions[] regions;
}
[Newtonsoft.Json.JsonObjectAttribute(MemberSerialization = Newtonsoft.Json.MemberSerialization.OptIn)]public partial class Regions{
[Newtonsoft.Json.JsonPropertyAttribute()] public string boundingBox;[Newtonsoft.Json.JsonPropertyAttribute()] public Lines[] lines;
}
[Newtonsoft.Json.JsonObjectAttribute(MemberSerialization = Newtonsoft.Json.MemberSerialization.OptIn)]public partial class Lines{
[Newtonsoft.Json.JsonPropertyAttribute()] public string boundingBox;[Newtonsoft.Json.JsonPropertyAttribute()] public Words[] words;
}
[Newtonsoft.Json.JsonObjectAttribute(MemberSerialization = Newtonsoft.Json.MemberSerialization.OptIn)]public partial class Words {
[Newtonsoft.Json.JsonPropertyAttribute()] public string boundingBox;[Newtonsoft.Json.JsonPropertyAttribute()] public string text;
}
3.アプリケーション例(3)
Microsoft Cognitive Services
Bing Speech APIを使った
「しゃべる翻訳アプリ 音声認識版」
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
(3)しゃべる翻訳アプリ 音声認識版
u Vision API - OCRをXamarin.Formsで使う
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
https://www.microsoft.com/cognitive-services/en-US/subscriptions
tokenVisionAPI
(3)しゃべる翻訳アプリ 音声認識版
u Bing Speech API – Speech Recognition機能を使ってスマートフォンで
録音した音声を認識して、認識した文字列を翻訳し、合成音声でしゃべる。
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
音声ファイル 音声ファイルの送信
テキストファイル受信
音声録音
Xamarin
合成音声発生
Bing Speech APISpeech Recognition機能
Microsoft Azure
合成音声で発声
MS Translator APIテキストファイル翻訳
テキストファイル生成
♪「この電⾞は空港に⾏きますか?」
「この電⾞は空港に⾏きますか? 」
「この電⾞は空港に⾏きますか? 」
「Does this train go to the airport?」
♪「この電⾞は空港に⾏きますか? 」
音声を録音
♪ 「Does this train go to the airport?」
(3)しゃべる翻訳アプリ 音声認識版
u Bing Speech API – Speech Recognition機能を使ってスマートフォンで
録音した音声を認識して、認識した文字列を翻訳し、合成音声でしゃべる。
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
音声ファイル
Bing Speech APIの呼び出し
受信データのJSONパース
Xamarin.Forms
合成音声処理
AVSpeechSynthesizer
Bing Speech API Speech Recognition機能
Microsoft Azure
MS Translator APITranslator APIの呼び出し
Xamarin.iOS
録音ボタンのPushイベント
(録音開始)
録音ボタンのPushイベント
(録音終了)
録音処理AVAudioRecorder
録音データ読み込みMemoryStream形式で引き渡す
Bing Speech APIの認証トークン生成
Access Token API
Translator APIの認証トークン生成
Access Token API
受信データのJSONパース
(3)しゃべる翻訳アプリ 音声認識版
u Bing Speech APIをXamarin.Formsで使う
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
public async Task<String> getSpeechToString(String filename, byte[] data) {String urlString = "https://speech.platform.bing.com/recognize?version=3.0&appID=D4D52672-91D7-4C74-8AD8-42B1D98141A5&format=json&device.os=" + Uri.EscapeDataString("iPhone OS") + "&locale=" + FromLangCode + "&scenarios=ulm" + " &requestid=" + speechClientSecret+ "&instanceid=" + speechClientId;String token = await getSpeechToTextAccessToken();var httpClient = new HttpClient();httpClient.DefaultRequestHeaders.Add("Authorization", token);var content = new StreamContent(new MemoryStream(data));content.Headers.TryAddWithoutValidation("Content-Type", "audio/wav;
samplerate=16000");HttpResponseMessage aResponse = await httpClient.PostAsync(urlString, content);String result = aResponse.Content.ReadAsStringAsync().Result;var obj = JsonConvert.DeserializeObject<dynamic>(result);String str = obj["header"]["lexical"].Value;return str;
}
(3)しゃべる翻訳アプリ 音声認識版
u Bing Speech APIをXamarin.Formsで使う
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
public async Task<String> getSpeechToTextAccessToken() {String urlString = "https://oxford-speech.cloudapp.net/token/issueToken";var httpClient = new HttpClient();var content = new FormUrlEncodedContent(new Dictionary<String, String> {
{ "grant_type", "client_credentials" },{ "client_id", speechClientId },{ "client_secret", speechClientSecret }, { "scope", "https://speech.platform.bing.com" }
});HttpResponseMessage aResponse = await httpClient.PostAsync(urlString, content);String result = aResponse.Content.ReadAsStringAsync().Result;var obj= JsonConvert.DeserializeObject<AdmAccessToken>(result);return "Bearer " + obj.access_token;
}
public class AdmAccessToken {public string access_token { get; set; }
}
(3)しゃべる翻訳アプリ 音声認識版
u Bing Speech APIをXamarin.Formsで使う
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
https://www.microsoft.com/cognitive-services/en-US/subscriptions
speechClientId
speechClientSecret
(3)しゃべる翻訳アプリ 音声認識版
u MS Translator APIをXamarin.Formsで使う
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
public async Task<String> getTranslatedString(String str, String FromLang, String ToLang) {String token = await getTranslateAccessToken();
String encstr = Uri.EscapeDataString(str);
String urlString = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + encstr + "&from=" + FromLang + "&to=" + ToLang;
httpClient.DefaultRequestHeaders.Add("Authorization", token);HttpResponseMessage aResponse = await httpClient.GetAsync(urlString);result = aResponse.Content.ReadAsStringAsync().Result;
return rtnstr;}
(3)しゃべる翻訳アプリ 音声認識版
u MS Translator APIをXamarin.Formsで使う
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
public async Task<String> getTranslateAccessToken() {String urlString = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";var httpClient = new HttpClient();var content = new FormUrlEncodedContent(new Dictionary<String, String> {
{ "grant_type", "client_credentials" },{ "client_id", translatorClientId },{ "client_secret", translatorClientSecret },{ "scope", "http://api.microsofttranslator.com" }
});HttpResponseMessage aResponse = await httpClient.PostAsync(urlString, content);String result = aResponse.Content.ReadAsStringAsync().Result;var obj = JsonConvert.DeserializeObject<AdmAccessToken>(result);return "Bearer " + obj.access_token;
}
public class AdmAccessToken {public string access_token { get; set; }
}
(3)しゃべる翻訳アプリ 音声認識版
u MS Translator APIをXamarin.Formsで使う
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
https://datamarket.azure.com/developer/applications
translatorClientId
translatorClientSecret
2016/10/15All rights reserved. Copyright(C) 2016 AYASE Hiro
ご静聴ありがとうございました