BaiduOCRController.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. using OASystem.API.OAMethodLib;
  2. using OASystem.API.OAMethodLib.BaiduApi;
  3. using OASystem.API.OAMethodLib.TencentCloudAPI;
  4. using OASystem.Domain.Dtos.Baidu;
  5. using OASystem.Domain.ViewModels.OCR;
  6. using Quartz.Util;
  7. namespace OASystem.API.Controllers
  8. {
  9. /// <summary>
  10. /// 百度OCR识别
  11. /// </summary>
  12. [Route("api/[controller]/[action]")]
  13. [ApiController]
  14. public class BaiduOCRController : ControllerBase
  15. {
  16. /// <summary>
  17. /// 接团客户OCR识别
  18. /// </summary>
  19. /// <param name="dto"></param>
  20. /// <returns></returns>
  21. [HttpPost]
  22. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  23. public IActionResult ClientOCR(ClientOCRDto dto)
  24. {
  25. try
  26. {
  27. string[] picBase64Array = dto.base64img.Split(';');
  28. string picFormat = picBase64Array[0].Split('/')[1];
  29. if (!TencentOCRTools.ImageType(picFormat))
  30. {
  31. return Ok(JsonView("图片格式不正确!只支持 PNG、JPG、JPEG、BMP 格式!"));
  32. }
  33. }
  34. catch (Exception ex)
  35. {
  36. return Ok(JsonView("请上传图片base64编码数据!"));
  37. }
  38. JsonView jw = new JsonView();
  39. try
  40. {
  41. string api_Response = BaiduApiHelper._apiTableV2(dto.base64img);
  42. JObject json = JObject.Parse(api_Response);
  43. if (json["tables_result"][0]["body"] != null)
  44. {
  45. List<BaiduOCR_TableV2> sourceList = JsonConvert.DeserializeObject<List<BaiduOCR_TableV2>>(json["tables_result"][0]["body"].ToString());
  46. List<BaiduOCR_TableV2> headerList = sourceList.Where(s => s.row_start == 0).OrderBy(s => s.col_start).Select(x => new BaiduOCR_TableV2
  47. {
  48. col_end = x.col_end,
  49. col_start = x.col_start,
  50. row_end = x.row_end,
  51. row_start = x.row_start,
  52. words = Regex.Replace(x.words, "[`~!@#$%^&*()_\\-+=<>?:\"{}|,.\\/;'\\\\[\\]·!#¥(——):;“”‘、,|《。》?、【】[\\]]", string.Empty)
  53. }).ToList();
  54. List<BaiduOCR_TableV2> dataList = sourceList.Where(s => s.row_start != 0).ToList();
  55. int maxRowIndex = dataList.Max(s => s.row_start);
  56. int maxColIndex = headerList.Max(s => s.col_start) + 1;
  57. Dictionary<int, string> dicHeader = new Dictionary<int, string>();
  58. List<string> listNameStr = new List<string>() { "姓名", "name", "姓 名" };
  59. List<string> listSexStr = new List<string>() { "性别", "gender", "sex" };
  60. List<string> listDOBStr = new List<string>() { "D.O.B", "出生年月", "生日", "出生日期", "出生年月日" };
  61. List<string> listIdCard = new List<string>() { "身份证号码", "身份证", "身份证号" };
  62. List<string> listOrganizationStr = new List<string>() { "工作单位", "organization", "单位", "所在单位" };
  63. List<string> listJobStr = new List<string>() { "职务", "title", "职位", "所在单位及职务", "单位及职务" };
  64. List<string> listMobileStr = new List<string>() { "联系电话", "mobile" };
  65. List<string> listAgeStr = new List<string>() { "年龄", "age" };
  66. List<string> listBeiZhu = new List<string>() { "备注", "本团职务" };
  67. for (int i = 0; i < headerList.Count; i++)
  68. {
  69. string words = headerList[i].words.Trim().ToLower();
  70. if (listNameStr.Exists(s => s == words))
  71. {
  72. dicHeader.Add(i, "Name");
  73. }
  74. else if (listSexStr.Exists(s => s == words))
  75. {
  76. dicHeader.Add(i, "Sex");
  77. }
  78. else if (listDOBStr.Exists(s => s == words))
  79. {
  80. dicHeader.Add(i, "DOB");
  81. }
  82. else if (listIdCard.Exists(s => s == words))
  83. {
  84. dicHeader.Add(i, "IdCard");
  85. }
  86. else if (listOrganizationStr.Exists(s => s == words))
  87. {
  88. dicHeader.Add(i, "Organization");
  89. }
  90. else if (listJobStr.Exists(s => s == words))
  91. {
  92. dicHeader.Add(i, "Job");
  93. }
  94. else if (listMobileStr.Exists(s => s == words))
  95. {
  96. dicHeader.Add(i, "Mobile");
  97. }
  98. else if (listAgeStr.Exists(s => s == words))
  99. {
  100. dicHeader.Add(i, "Age");
  101. }
  102. else if (listBeiZhu.Exists(s => s == words))
  103. {
  104. dicHeader.Add(i, "BeiZhu");
  105. }
  106. }
  107. List<BaiduClientOCRView> ClientArr = new List<BaiduClientOCRView>();
  108. for (int i = 1; i <= maxRowIndex; i++)
  109. {
  110. BaiduClientOCRView client = new BaiduClientOCRView();
  111. for (int j = 0; j < maxColIndex; j++)
  112. {
  113. var item = dataList.First(s => s.row_start == i && s.col_start == j);
  114. string words = item.words.Replace("\\n", "");
  115. string values = string.Empty;
  116. try
  117. {
  118. values = dicHeader[j];
  119. }
  120. catch (Exception)
  121. {
  122. throw new Exception("有未能识别的列名请检查 : " + JsonConvert.SerializeObject(headerList.Select(x => x.words)));
  123. }
  124. if (words.IsNullOrWhiteSpace())
  125. {
  126. continue;
  127. }
  128. if (values.Equals("Name"))
  129. {
  130. if (Regex.Matches(words, "[a-zA-Z]").Count < 1)
  131. {
  132. string lastName = words.Substring(0, 1);
  133. string name = words.Substring(1);
  134. client.LastName = lastName;
  135. client.FirstName = name;
  136. string lastNamePinYin = lastName.GetTotalPingYin().Count > 0 ? lastName.GetTotalPingYin()[0].ToUpper() : "";
  137. string firstNamePinYin = "";
  138. for (int n = 0; n < name.Length; n++)
  139. {
  140. firstNamePinYin += name[n].ToString().GetTotalPingYin().Count > 0 ? name[n].ToString().GetTotalPingYin()[0].ToUpper() + " " : "";
  141. }
  142. client.Pinyin = lastNamePinYin + "/" + firstNamePinYin;
  143. }
  144. else
  145. {
  146. Regex regForeign = new Regex("[a-zA-Z]+[\\s][a-zA-Z]+");
  147. if (regForeign.IsMatch(words))
  148. {
  149. string[] names = words.Split(' ');
  150. client.LastName = names[1];
  151. client.FirstName = names[0];
  152. }
  153. else
  154. {
  155. client.FirstName = words;
  156. }
  157. }
  158. }
  159. else if (values.Equals("Sex"))
  160. {
  161. client.Sex = words == "男" ? 0 : 1;
  162. }
  163. else if (values.Equals("DOB"))
  164. {
  165. client.Birthday = words.Replace(".", "-");
  166. DateTime time = new DateTime();
  167. if (DateTime.TryParse(client.Birthday, out time))
  168. {
  169. client.Birthday = time.ToString("yyyy-MM-dd");
  170. }
  171. else
  172. {
  173. client.Birthday = "";
  174. }
  175. }
  176. else if (values.Equals("IdCard"))
  177. {
  178. client.IDcard = words;
  179. }
  180. else if (values.Equals("Organization"))
  181. {
  182. client.CompanyFullName = words;
  183. }
  184. else if (values.Equals("Job"))
  185. {
  186. client.Job = words;
  187. }
  188. else if (values.Equals("Mobile"))
  189. {
  190. client.Phone = words;
  191. }
  192. }
  193. if (!(client.FirstName + client.LastName + client.Pinyin + client.CompanyFullName + client.Job + client.Phone + client.Birthday).IsNullOrWhiteSpace())
  194. {
  195. if (string.IsNullOrWhiteSpace(client.CompanyFullName))
  196. {
  197. client.CompanyFullName = "暂无";
  198. }
  199. if (!string.IsNullOrWhiteSpace(client.LastName + client.FirstName))
  200. {
  201. var pinyin = client.LastName.GetTotalPingYinFirst() + "/";
  202. foreach (var cn in client.FirstName)
  203. {
  204. pinyin += cn.ToString().GetTotalPingYinFirst() + " ";
  205. }
  206. client.Pinyin = pinyin.TrimEnd();
  207. }
  208. ClientArr.Add(client);
  209. }
  210. }
  211. jw.Code = 200;
  212. jw.Msg = "获取成功!";
  213. jw.Data = ClientArr;
  214. }
  215. else if (json["error_code"] != null)
  216. {
  217. jw.Data = new string[0];
  218. jw.Msg = "百度接口异常!";
  219. }
  220. else
  221. {
  222. jw.Data = new string[0];
  223. jw.Msg = "百度接口异常!";
  224. }
  225. }
  226. catch (Exception ex)
  227. {
  228. jw.Code = 400;
  229. jw.Msg = "程序异常!" + ex.Message;
  230. jw.Data = new string[0];
  231. }
  232. return Ok(jw);
  233. }
  234. }
  235. }