C# 百度云IOCR通用版文字识别

百度智能云   文字识别

     自定义模板-iOCR通用版

   创建模板-框选参照字段-框选识别区

Nuget包引用  Baidu.AI

        /// <summary>
        /// 明细文字识别
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public VMPaymentInvoiceDetailOcr Ocr(VMPaymentInvoiceDetailOcrArgs args)
        {
            var caller = Caller.Current;
            using var db = new DataContext();
            byte[] image;
            if (args.Stream != null)
            {
                image = new byte[args.Stream.Length];
                args.Stream.Read(image, 0, image.Length);
            }
            else if (args.Base64String.IsNotNullAndEmptyEx())
            {
                image = System.Convert.FromBase64String(args.Base64String);
            }
            else if (args.Url.IsNotNullAndEmptyEx())
            {
                var wc = new System.Net.WebClient() { Encoding = System.Text.Encoding.UTF8 };
                image = wc.DownloadData(args.Url);
                args.Stream.Read(image, 0, image.Length);
            }
            else throw new BusinessException("要上传的内容为空!");

            var pmSettingList = DASetting.Instance.GetList(caller, db, CDSettingProject.Id.Baidu.Cloud.ApiKey, CDSettingProject.Id.Baidu.Cloud.SecretKey);
            var apiKey = pmSettingList.GetContentEx(CDSettingProject.Id.Baidu.Cloud.ApiKey);
            var secretKey = pmSettingList.GetContentEx(CDSettingProject.Id.Baidu.Cloud.SecretKey);

            var pmTemplateSign = DAPaymentInvoiceDetailTemplateSign.Instance.GetItem(caller, db, args.TemplateSignId);
            if (pmTemplateSign.IsNullEx()) throw new BusinessException("未找到对应项目收票明细模板!");

            var templateSign = pmTemplateSign.FValue;

            Dictionary<string, object> param = new Dictionary<string, object>();
            try
            {
                //IOCR通用版
                Baidu.Aip.Ocr.Ocr ocrclient = new Baidu.Aip.Ocr.Ocr(apiKey, secretKey);
                param.Add("templateSign", templateSign);
                var response = ocrclient.Custom(image, param);
                param.Add("image",image);
                LogHelper.Logger.Debug($"【{caller.PlatformCustomerId}】【{caller.PlatformCustomerName}】【{caller.PlatformCustomerDatabase}】【{Options.Name}】【文字识别】【百度云】【IOCR通用版】\r\n【请求】{param.ToJsonStringEx()}\r\n【响应】{response.ToJsonStringEx()}");
                
                IOcrCurrencyResponse ocrCurrencyResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<IOcrCurrencyResponse>(Newtonsoft.Json.JsonConvert.SerializeObject(response));
                if (ocrCurrencyResponse == null || ocrCurrencyResponse.ErrorCode != 0 || ocrCurrencyResponse.Data == null || ocrCurrencyResponse.Data.Ret == null) throw new BusinessException("识别失败,错误原由:"+ ocrCurrencyResponse.ErrorMsg + "!");

                var result = new VMPaymentInvoiceDetailOcr()
                {
                    Title = ocrCurrencyResponse.Data.Ret.FirstOrDefault(p => p.WordName == "title")?.Word.ToString(),
                    InvoiceCode = ocrCurrencyResponse.Data.Ret.FirstOrDefault(p => p.WordName == "invoice_code")?.Word.ToString(),
                    Code = ocrCurrencyResponse.Data.Ret.FirstOrDefault(p => p.WordName == "code")?.Word.ToString(),
                    DateIssued = ocrCurrencyResponse.Data.Ret.FirstOrDefault(p => p.WordName == "invoice_date")?.Word.ToNullableDateTimeEx(),
                    Page = ocrCurrencyResponse.Data.Ret.FirstOrDefault(p => p.WordName == "page")?.Word.ToNullableInt32Ex(),
                    Remark = ocrCurrencyResponse.Data.Ret.FirstOrDefault(p => p.WordName == "remark")?.Word.ToString(),
                    DetailCargoList = new List<VMPaymentInvoiceDetailOcrCargo>()
                };

                List<DistinguishSplitModel> distinguishSplits = ocrCurrencyResponse.Data.Ret.Where(a => a.WordName.IndexOf("invoice_detail") != -1).Select(a =>
                     new DistinguishSplitModel()
                     {
                         WordName = a.WordName.Split('#')[2],
                         Index = a.WordName.Split('#')[1].ToNullableInt32Ex(),
                         Word = a.Word
                     }).ToList();

                for (int i = 1; i <= distinguishSplits.Max(a => a.Index); i++)
                {
                    var pmCargoList = distinguishSplits.FindAll(a => a.Index == i);
                    var cargo = new VMPaymentInvoiceDetailOcrCargo()
                    {
                        Name = pmCargoList.FirstOrDefault(a=>a.WordName=="name")?.Word,
                        Spec = pmCargoList.FirstOrDefault(a => a.WordName == "spec")?.Word,
                        Unit = pmCargoList.FirstOrDefault(a => a.WordName == "unit")?.Word,
                        Quantity = pmCargoList.FirstOrDefault(a => a.WordName == "quantity")?.Word.ToNullableDecimalEx(),
                        Price = pmCargoList.FirstOrDefault(a => a.WordName == "price")?.Word.ToNullableDecimalEx(),
                        AmountExcludingTax = pmCargoList.FirstOrDefault(a => a.WordName == "amountexcludingtax")?.Word.ToNullableDecimalEx(),
                        TaxRate = pmCargoList.FirstOrDefault(a => a.WordName == "taxrate")?.Word.Replace("%", "").ToNullableDecimalEx(),
                        TaxAmount = pmCargoList.FirstOrDefault(a => a.WordName == "taxamount")?.Word.ToNullableDecimalEx(),
                    }.AppendToEx(result.DetailCargoList);
                    cargo.Amount = cargo.AmountExcludingTax + cargo.TaxAmount;
                }
                return result;
            }
            catch (AggregateException ex)
            {
                LogHelper.Logger.Error($"【{caller.PlatformCustomerId}】【{caller.PlatformCustomerName}】【{caller.PlatformCustomerDatabase}】【{Options.Name}】【文字识别】【百度云】【IOCR通用版】\r\n【请求】{param.ToJsonStringEx()}", ex);
                throw new BusinessException("识别失败!");
            }
        }  

  

    

posted @ 2022-09-06 16:28  冷鳯  阅读(256)  评论(0)    收藏  举报