Quellcode durchsuchen

添加接团客户OCR识别

123456 vor 1 Jahr
Ursprung
Commit
a1259da20c

+ 185 - 0
OASystem/OASystem.Api/Controllers/BaiduOCRController.cs

@@ -0,0 +1,185 @@
+using Autofac.Core;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using OASystem.API.OAMethodLib.BaiduApi;
+using OASystem.API.OAMethodLib.TencentCloudAPI;
+using OASystem.Domain.Dtos.Baidu;
+using OASystem.Domain.Dtos.CRM;
+using OASystem.Domain.Entities.Customer;
+using OASystem.Domain.ViewModels.OCR;
+
+namespace OASystem.API.Controllers
+{
+    [Route("api/[controller]/[action]")]
+    [ApiController]
+    public class BaiduOCRController : ControllerBase
+    {
+        /// <summary>
+        /// 接团客户OCR识别
+        /// </summary>
+        /// <param name="dto"></param>
+        /// <returns></returns>
+        [HttpPost]
+        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
+        public IActionResult ClientOCR(ClientOCRDto dto)
+        {
+            try
+            {
+                string[] picBase64Array = dto.base64img.Split(';');
+                string picFormat = picBase64Array[0].Split('/')[1];
+                if (!TencentOCRTools.ImageType(picFormat))
+                {
+                    return Ok(JsonView("图片格式不正确!只支持 PNG、JPG、JPEG、BMP 格式!"));
+                }
+            }
+            catch (Exception ex)
+            {
+                return Ok(JsonView("请上传图片base64编码数据!"));
+            }
+         
+
+            JsonView jw = new JsonView();
+            string api_Response = BaiduApiHelper._apiTableV2(dto.base64img);
+            JObject json = JObject.Parse(api_Response);
+            if (json["tables_result"][0]["body"] != null)
+            {
+               
+                List<BaiduOCR_TableV2> sourceList = JsonConvert.DeserializeObject<List<BaiduOCR_TableV2>>(json["tables_result"][0]["body"].ToString());
+                List<BaiduOCR_TableV2> headerList = sourceList.Where(s => s.row_start == 0).OrderBy(s => s.col_start).ToList();
+                List<BaiduOCR_TableV2> dataList = sourceList.Where(s => s.row_start != 0).ToList();
+                int maxRowIndex = dataList.Max(s => s.row_start);
+                int maxColIndex = headerList.Max(s => s.col_start) + 1;
+                Dictionary<int, string> dicHeader = new Dictionary<int, string>();
+                List<string> listNameStr = new List<string>() { "姓名", "Name" };
+                List<string> listSexStr = new List<string>() { "性别", "Gender" };
+                List<string> listDOBStr = new List<string>() { "D.O.B", "出生年月" };
+                List<string> listIdCard = new List<string>() { "身份证号码", "身份证" };
+                List<string> listOrganizationStr = new List<string>() { "工作单位", "Organization", "单位" };
+                List<string> listJobStr = new List<string>() { "职务", "Title" };
+                List<string> listMobileStr = new List<string>() { "联系电话", "Mobile" };
+                List<string> listAgeStr = new List<string>() { "年龄", "Age" };
+                for (int i = 0; i < headerList.Count; i++)
+                {
+                    string words = headerList[i].words.Trim();
+                    if (listNameStr.Exists(s => s == words))
+                    {
+                        dicHeader.Add(i, "Name");
+                    }
+                    else if (listSexStr.Exists(s => s == words))
+                    {
+                        dicHeader.Add(i, "Sex");
+                    }
+                    else if (listDOBStr.Exists(s => s == words))
+                    {
+                        dicHeader.Add(i, "DOB");
+                    }
+                    else if (listIdCard.Exists(s => s == words))
+                    {
+                        dicHeader.Add(i, "IdCard");
+                    }
+                    else if (listOrganizationStr.Exists(s => s == words))
+                    {
+                        dicHeader.Add(i, "Organization");
+                    }
+                    else if (listJobStr.Exists(s => s == words))
+                    {
+                        dicHeader.Add(i, "Job");
+                    }
+                    else if (listMobileStr.Exists(s => s == words))
+                    {
+                        dicHeader.Add(i, "Mobile");
+                    }
+                    else if (listAgeStr.Exists(s => s == words))
+                    {
+                        dicHeader.Add(i, "Age");
+                    }
+
+                }
+
+                List<BaiduClientOCRView> ClientArr = new List<BaiduClientOCRView>();
+                for (int i = 1; i < maxRowIndex; i++)
+                {
+                    BaiduClientOCRView client = new BaiduClientOCRView();
+                    for (int j = 0; j < maxColIndex; j++)
+                    {
+                        var item = dataList.First(s => s.row_start == i && s.col_start == j);
+                        string words = item.words.Replace("\\n", "");
+                        string values = dicHeader[j];
+
+                        if (values.Equals("Name"))
+                        {
+                            if (Regex.Matches(words, "[a-zA-Z]").Count < 1)
+                            {
+                                string lastName = words.Substring(0, 1);
+                                string name = words.Substring(1);
+                                client.LastName = lastName;
+                                client.Name = name;
+                            }
+                            else
+                            {
+                                Regex regForeign = new Regex("[a-zA-Z]+[\\s][a-zA-Z]+");
+                                if (regForeign.IsMatch(words))
+                                {
+                                    string[] names = words.Split(' ');
+                                    client.LastName = names[1];
+                                    client.Name = names[0];
+                                }
+                                else
+                                {
+                                    client.Name = words;
+                                }
+                            }
+                        }
+                        else if (values.Equals("Sex"))
+                        {
+                            client.Sex = words;
+                        }
+                        else if (values.Equals("DOB"))
+                        {
+                            client.Birthday = words;
+                        }
+                        else if (values.Equals("IdCard"))
+                        {
+                            client.IDcard = words;
+                        }
+                        else if (values.Equals("Organization"))
+                        {
+                            client.Company = words;
+                        }
+                        else if (values.Equals("Job"))
+                        {
+                            client.Job = words;
+                        }
+                        else if (values.Equals("Mobile"))
+                        {
+                            client.Phone = words;
+                        }
+                    }
+
+                    ClientArr.Add(client);
+                }
+
+                jw.Code = 200;
+                jw.Msg = "获取成功!";
+                jw.Data = ClientArr;
+
+            }
+            else if (json["error_code"] != null)
+            {
+                jw.Data = new string[0];
+                jw.Msg = "百度接口异常!";
+            }
+            else
+            {
+                jw.Data = new string[0];
+                jw.Msg = "百度接口异常!";
+            }
+
+            return Ok(jw);
+        }
+
+
+
+
+    }
+}

+ 44 - 0
OASystem/OASystem.Api/OAMethodLib/BaiduApi/BaiduApiHelper.cs

@@ -0,0 +1,44 @@
+using MySql.Data.MySqlClient.Memcached;
+using Org.BouncyCastle.Asn1.Crmf;
+using RestSharp;
+using System.IO;
+
+namespace OASystem.API.OAMethodLib.BaiduApi
+{
+    public class BaiduApiHelper
+    {
+        const string API_KEY = "0OuunXiLEX3OL6hB4bhXvKyS";
+        const string SECRET_KEY = "GZ6HwIGxQlGH1O4MADm0DpO5BcLyhpx2";
+
+        public static string _apiTableV2(string Base64)
+        {
+            var client = new RestClient($"https://aip.baidubce.com/rest/2.0/ocr/v1/table?access_token={GetAccessToken()}");
+            client.Timeout = -1;
+            var request = new RestRequest(Method.POST);
+            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
+            request.AddHeader("Accept", "application/json");
+            // image 可以通过 GetFileBase64Content('C:\fakepath\tb.jpg') 方法获取
+            request.AddParameter("image", Base64);
+            IRestResponse response = client.Execute(request);
+            return response.Content;
+        }
+
+        /**
+        * 使用 AK,SK 生成鉴权签名(Access Token)
+        * @return 鉴权签名信息(Access Token)
+        */
+        static string GetAccessToken()
+        {
+            var client = new RestClient($"https://aip.baidubce.com/oauth/2.0/token");
+            //client.Timeout = -1;
+            var request = new RestRequest("",Method.POST);
+            request.AddParameter("grant_type", "client_credentials");
+            request.AddParameter("client_id", API_KEY);
+            request.AddParameter("client_secret", SECRET_KEY);
+            IRestResponse response = client.Execute(request);
+            Console.WriteLine(response.Content);
+            var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
+            return result.access_token.ToString();
+        }
+    }
+}

+ 1 - 0
OASystem/OASystem.Api/OASystem.API.csproj

@@ -33,6 +33,7 @@
     <PackageReference Include="QRCoder" Version="1.4.1" />
     <PackageReference Include="Quartz" Version="3.6.2" />
     <PackageReference Include="QuartzUI.Extension.AspNetCore" Version="1.1.8" />
+    <PackageReference Include="RestSharp" Version="106.15.0" />
     <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
     <PackageReference Include="SqlSugarCore" Version="5.1.3.35" />
     <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />

+ 23 - 0
OASystem/OASystem.Domain/Dtos/Baidu/ClientOCRDto.cs

@@ -0,0 +1,23 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace OASystem.Domain.Dtos.Baidu
+{
+    public class ClientOCRDto
+    {
+        public string base64img { get; set; }
+    }
+
+
+    public class BaiduOCR_TableV2
+    {
+        public int row_start { get; set; }
+        public int row_end { get; set; }
+        public int col_start { get; set; }
+        public int col_end { get; set; }
+        public string words { get; set; }
+    }
+}

+ 21 - 0
OASystem/OASystem.Domain/ViewModels/OCR/BaiduClientOCRView.cs

@@ -0,0 +1,21 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace OASystem.Domain.ViewModels.OCR
+{
+    public class BaiduClientOCRView
+    {
+        public string Sex { get; set; }
+        public string Birthday { get; set; }
+        public string IDcard { get; set; }
+        public string Company { get; set; }
+        public string Job { get; set; }
+        public string Phone { get; set; }
+        public string LastName { get; set; }
+        public string Name { get; set; }
+
+    }
+}