2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

.NetからAWS Textractを使う方法

Last updated at Posted at 2019-06-11

Amazon TextractをC#.Netから使ってみました。
Amazon TextractとはAWSのサービスのひとつで、文字と項目や表を自動で認識してくれるAI系のサービスです。
https://aws.amazon.com/jp/textract/

2019/6/12現在、TextractのSDKに関する日本語の記事は見当たらなかったのでAWSのリファレンスとにらめっこしながら書いてみました。

・Textract SDKの使い方はこちら(英語)
https://docs.aws.amazon.com/ja_jp/textract/latest/dg/getting-started.html

↑のSDKの使い方はJavaですが、こちらの.Net用のリファレンスにTextractの項目があるので、
これを見ていけば.NetからTextract SDKが使えます。

・.Net用のリファレンス
https://docs.aws.amazon.com/sdkfornet/v3/apidocs/Index.html

環境は、.Net Core(Razor page) + C#です。

で、こちらがPOSTしたファイルをそのままTextractに渡して解析するサンプルコードです。
(Razor pageでFormからのSubmitに対するOnPostイベントハンドラ部分です。)
簡単に説明すると、解析対象の画像ファイルをMemoryStreamに入れてリクエストを投げれば、Blocksというリストに結果が入って返ってくるので、あとは煮るなり焼くなり、という感じです。

public IActionResult OnPost(IFormFile Targetfile)
{
     using (var client = new AmazonTextractClient(awsCredentials, this.awsOptions.Region))
     {
            //Document処理用のバッファ用意
            Stream s = Targetfile.OpenReadStream();
            byte[] file = new byte[Targetfile.Length];
            MemoryStream ms = new MemoryStream(file);
            s.CopyTo(ms);


            //AWSに解析させるDocumentオブジェクトの準備
            Document doc = new Document();
            doc.Bytes = ms;


            //リクエストの作成
             DetectDocumentTextRequest req = new DetectDocumentTextRequest();
             req.Document = doc;

            //処理実行
             var response = client.DetectDocumentTextAsync(req);
             response.Wait();


            //結果を見る
            //ここまでくれば、結果はresponse.Result.Blocksに入っています。
            //BlocksというのはTextractが解析してくれた結果リストで、発見されたオブジェクトが入っています。
            //ここではテキストだけですが、表や項目を解析すればそれもBlocksに入ってきます。
            //詳しくはこちら。https://docs.aws.amazon.com/ja_jp/textract/latest/dg/how-it-works-detecting.html
    }
}

※もちろんエラー処理とかは書いてないので、必要に応じて書いてください。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?