Ocrimg.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. namespace addons\qingdongams\controller;
  3. use addons\qingdongams\model\File;
  4. use addons\qingdongams\model\Ocr;
  5. use addons\qingdongams\model\OcrType;
  6. use addons\qingdongams\model\AdminConfig;
  7. use fast\Http;
  8. use think\Cache;
  9. use think\Db;
  10. use think\Exception;
  11. use think\Log;
  12. /**
  13. * 文字识别
  14. */
  15. class Ocrimg extends StaffApi
  16. {
  17. protected $noNeedLogin = [];
  18. protected $noNeedRight = [];
  19. protected $curl = 'https://aip.baidubce.com/rest/2.0/ocr/v1/';
  20. // 你的百度 APPID AK SK
  21. public function _initialize()
  22. {
  23. $this->apiKey =AdminConfig::getConfigValue('baidu_api','baidu');
  24. $this->secretKey =AdminConfig::getConfigValue('baidu_secret','baidu');
  25. $this->textinappid =AdminConfig::getConfigValue('textin_api','textin');
  26. $this->textinsecret =AdminConfig::getConfigValue('textin_secret','textin');
  27. parent::_initialize();
  28. }
  29. // 获取识别类型
  30. public function getTypes()
  31. {
  32. $this->success('', OcrType::field('id,name')->select());
  33. }
  34. //上传识别
  35. public function getOcr()
  36. {
  37. $params = $this->request->post();
  38. if (!$params['type_id'] || !$params['file_id']) {
  39. $this->error('参数缺失');
  40. }
  41. $img = cdnurl(File::getUrl($params['file_id']), true);
  42. $img_type = substr(strrchr($img, '.'), 1);
  43. if (!in_array($img_type, ['jpg', 'jpeg', 'png', 'bmp'])) {
  44. $this->error('图片类型不对,请上传jpg/jpeg/png/bmp等格式图片');
  45. }
  46. $action = OcrType::where('id', $params['type_id'])->value('action');
  47. $url = $this->curl . $action . '?access_token=' . $this->getAccessToken();
  48. $imgcontent = file_get_contents($img);
  49. $imgcontent = base64_encode($imgcontent);
  50. $bodys = array(
  51. 'image' => $imgcontent
  52. );
  53. $res = Http::post($url, $bodys);
  54. Log::write('ocr返回结果 ' . $this->auth->id . '----请求:' . $url . '=====:' . $res);
  55. $result = json_decode($res, true);
  56. if (isset($result['error_code'])) {
  57. $this->error($result['error_msg'], null, $result['error_code']);
  58. }
  59. $params['ocr_result'] = is_array($res) ? json_encode($res) : $res;
  60. $data = $this->resultReturn($params['type_id'], $result['words_result']);
  61. $saveRes = true;
  62. Db::startTrans();
  63. try {
  64. $params['log_id'] = $result['log_id'];
  65. $params['staff_id'] = $this->auth->id;
  66. $params['file_url'] = $img;
  67. $params['money'] = $data['money'] ?? 0;
  68. $model = new Ocr();
  69. $saveRes = $model->allowField(true)->save($params);
  70. Db::commit();
  71. } catch (Exception $e) {
  72. Db::rollback();
  73. $this->error($e->getMessage());
  74. }
  75. if ($saveRes) {
  76. $this->success('识别成功', array_merge($data, ['log_id' => $result['log_id']]));
  77. }
  78. }
  79. // 获取accesstoken
  80. public function getAccessToken()
  81. {
  82. $key = 'ocr_token_';
  83. if ($token = Cache::get($key)) {
  84. return $token;
  85. }
  86. $url = 'https://aip.baidubce.com/oauth/2.0/token';
  87. $post_data['grant_type'] = 'client_credentials';
  88. $post_data['client_id'] = $this->apiKey;
  89. $post_data['client_secret'] = $this->secretKey;
  90. $o = "";
  91. foreach ($post_data as $k => $v) {
  92. $o .= "$k=" . urlencode($v) . "&";
  93. }
  94. $post_data = substr($o, 0, -1);
  95. $res = Http::post($url, $post_data);
  96. Log::write('ocr获取accestoken: ' . $this->auth->id . '----' . json_encode($post_data) . '===结果:' . $res);
  97. if (!$res) {
  98. $this->error('请联系管理员,识别失败!');
  99. }
  100. $result = json_decode($res, true);
  101. if (isset($result['error'])) {
  102. $this->error('请联系管理员,识别失败!');
  103. }
  104. Cache::set($key, $result['access_token'], 2592000);
  105. return $result['access_token'];
  106. }
  107. public function resultReturn($type, $result)
  108. {
  109. $data = [];
  110. switch ($type) {
  111. case 1:
  112. //1 增值税发票识别
  113. $data = [
  114. 'InvoiceType' => $result['InvoiceType'],// 发票种类
  115. 'InvoiceTypeOrg' => $result['InvoiceTypeOrg'],// 发票名称
  116. 'InvoiceCode' => $result['InvoiceCode'],// 发票代码
  117. 'InvoiceNum' => $result['InvoiceNum'],// 发票号码
  118. 'InvoiceDate' => $result['InvoiceDate'],// 开票日期
  119. 'PurchaserName' => $result['PurchaserName'],// 购方名称
  120. 'PurchaserRegisterNum' => $result['PurchaserRegisterNum'],// 购方纳税人识别号
  121. 'PurchaserAddress' => $result['PurchaserAddress'],// 购方地址及电话
  122. 'PurchaserBank' => $result['PurchaserBank'],// 购方开户行及账号
  123. 'Password' => $result['Password'],// 密码区
  124. 'Province' => $result['Province'],// 省
  125. 'City' => $result['City'],// 市
  126. 'Agent' => $result['Agent'],// 是否代开
  127. 'CommodityName' => $result['CommodityName'],// 货物名称 ['row':行号,'word':内容']
  128. 'CommodityType' => $result['CommodityType'],// 规格型号 ['row':行号,'word':内容']
  129. 'CommodityUnit' => $result['CommodityUnit'],// 单位 ['row':行号,'word':内容']
  130. 'CommodityNum' => $result['CommodityNum'],// 数量 ['row':行号,'word':内容']
  131. 'CommodityPrice' => $result['CommodityPrice'],// 单价 ['row':行号,'word':内容']
  132. 'CommodityAmount' => $result['CommodityAmount'],// 金额 ['row':行号,'word':内容']
  133. 'CommodityTaxRate' => $result['CommodityTaxRate'],// 税率 ['row':行号,'word':内容']
  134. 'CommodityTax' => $result['CommodityTax'],// 税额 ['row':行号,'word':内容']
  135. 'CommodityPlateNum' => $result['CommodityPlateNum'] ?? [],// 车牌号 ['row':行号,'word':内容']
  136. 'CommodityVehicleType' => $result['CommodityVehicleType'] ?? [],// 类型 ['row':行号,'word':内容']
  137. 'CommodityStartDate' => $result['CommodityStartDate'] ?? [],// 通行日期起 ['row':行号,'word':内容']
  138. 'CommodityEndDate' => $result['CommodityEndDate'] ?? [],// 通行日期止 ['row':行号,'word':内容']
  139. 'OnlinePay' => $result['OnlinePay'] ?? '',// 电子支付标识
  140. 'SellerName' => $result['SellerName'],// 销售方名称
  141. 'SellerRegisterNum' => $result['SellerRegisterNum'],// 销售方纳税人识别号
  142. 'SellerAddress' => $result['SellerAddress'],// 销售方地址及电话
  143. 'SellerBank' => $result['销售方开户行及账号'],// 销售方地址及电话
  144. 'TotalAmount' => $result['TotalAmount'],// 合计金额
  145. 'money' => $result['TotalAmount'],// 合计金额
  146. 'TotalTax' => $result['TotalTax'],// 合计税额
  147. 'AmountInWords' => $result['AmountInWords'],// 价税合计(大写)
  148. 'AmountInFiguers' => $result['AmountInFiguers'],// 价税合计(小写)
  149. 'NoteDrawer' => $result['NoteDrawer'],// 开票人
  150. 'Remarks' => $result['Remarks'],// 备注
  151. ];
  152. break;
  153. case 2:
  154. //2 增值税发票验真
  155. $data = [
  156. 'InvoiceType' => $result['InvoiceType'], // 发票类型
  157. 'InvoiceCode' => $result['InvoiceCode'], // 发票代码
  158. 'InvoiceNum' => $result['InvoiceNum'], // 发票号码
  159. 'InvoiceDate' => $result['InvoiceDate'], // 开票日期
  160. 'AmountInFiguers' => $result['AmountInFiguers'], // 合计金额小写
  161. 'money' => $result['AmountInFiguers'],// 合计金额
  162. 'AmountInWords' => $result['AmountInWords'], // 合计金额大写
  163. 'CommodityName' => $result['CommodityName'], // 商品名称 [['word':'餐费','row':1]]
  164. 'CommodityUnit' => $result['CommodityUnit'], // 商品单位 [['word':'餐费','row':1]]
  165. ];
  166. break;
  167. case 3:
  168. //3 定额发票识别
  169. $data = [
  170. 'invoice_code' => $result['invoice_code'], // 发票代码
  171. 'invoice_number' => $result['invoice_number'], // 发票号码
  172. 'invoice_rate' => $result['invoice_code'], // 金额
  173. 'location' => $result['location'], // 发票所在地
  174. 'invoice_rate_lowercase' => $result['invoice_rate_lowercase'], // 发票金额小写
  175. 'money' => $result['invoice_rate_lowercase'],// 合计金额
  176. 'province' => $result['province'], // 省
  177. 'city' => $result['city'] ?? '', // 市
  178. ];
  179. break;
  180. case 4:
  181. //4 通用机打发票识别
  182. $data = [
  183. 'InvoiceType' => $result['InvoiceType'],// 发票种类
  184. 'InvoiceCode' => $result['InvoiceCode'],// 发票代码
  185. 'InvoiceNum' => $result['InvoiceNum'],// 发票号码
  186. 'InvoiceDate' => $result['InvoiceDate'],// 开票日期
  187. 'AmountInWords' => $result['AmountInWords'],// 合计金额大写
  188. 'AmountInFiguers' => $result['AmountInFiguers'],// 合计金额小写
  189. 'money' => $result['AmountInFiguers'],// 合计金额
  190. 'CommodityName' => $result['CommodityName'],// 货物名称 ['row':行号,'word':内容']
  191. 'CommodityUnit' => $result['CommodityUnit'],// 商品单位 ['row':行号,'word':内容']
  192. 'CommodityPrice' => $result['CommodityPrice'],// 商品单价 ['row':行号,'word':内容']
  193. 'CommodityNum' => $result['CommodityNum'],// 商品数量 ['row':行号,'word':内容']
  194. 'CommodityAmount' => $result['CommodityAmount'],// 商品金额 ['row':行号,'word':内容']
  195. 'IndustrySort' => $result['IndustrySort'],// 行业分类
  196. 'MachineNum' => $result['MachineNum'],// 机打号码
  197. 'CheckCode' => $result['CheckCode'],// 校验码
  198. 'SellerName' => $result['SellerName'],// 销售方名称
  199. 'SellerRegisterNum' => $result['SellerRegisterNum'],// 销售方纳税人识别号
  200. 'PurchaserName' => $result['PurchaserName'],// 购买方名称
  201. 'PurchaserRegisterNum' => $result['PurchaserRegisterNum'],// 购买方纳税人识别
  202. 'TotalTax' => $result['TotalTax'],// 合计税额
  203. 'Province' => $result['Province'], // 省
  204. 'City' => $result['City'], // 市
  205. ];
  206. break;
  207. case 5:
  208. //5 火车票识别
  209. $data = [
  210. 'ticket_num' => $result['ticket_num'], // 车票号
  211. 'starting_station' => $result['starting_station'], // 始发站
  212. 'train_num' => $result['train_num'], // 车次号
  213. 'destination_station' => $result['destination_station'], // 到达站
  214. 'date' => $result['date'], // 出发日期
  215. 'ticket_rates' => $result['ticket_rates'], // 车票金额
  216. 'money' => $result['ticket_rates'],// 合计金额
  217. 'seat_category' => $result['ticket_rates'], // 席别
  218. 'name' => $result['name'], // 乘客姓名
  219. 'id_num' => $result['id_num'], // 身份证号
  220. 'serial_number' => $result['serial_number'], // 序列号
  221. 'sales_station' => $result['sales_station'], // 售站
  222. 'time' => $result['time'], // 时间
  223. 'seat_num' => $result['seat_num'], // 座位号
  224. ];
  225. break;
  226. case 6:
  227. //6 出租车票识别
  228. $data = [
  229. 'InvoiceCode' => $result['InvoiceCode'], // 发票代号
  230. 'InvoiceNum' => $result['InvoiceNum'], // 发票号码
  231. 'TaxiNum' => $result['TaxiNum'], // 车牌号
  232. 'Date' => $result['Date'], // 日期
  233. 'Time' => $result['Time'], // 上下车时间
  234. 'PickupTime' => $result['PickupTime'], // 上车时间
  235. 'DropoffTime' => $result['DropoffTime'], // 下车时间
  236. 'Fare' => $result['Fare'], // 金额
  237. 'money' => $result['Fare'],// 合计金额
  238. 'FuelOilSurcharge' => $result['FuelOilSurcharge'], // 燃油附加费
  239. 'CallServiceSurcharge' => $result['CallServiceSurcharge'], // 叫车服务费
  240. 'TotalFare' => $result['TotalFare'], // 总金额
  241. 'Location' => $result['Location'], // 开票城市
  242. 'PricePerkm' => $result['PricePerkm'], // 单价
  243. 'Distance' => $result['Distance'], // 里程
  244. 'province' => $result['province'] ?? '', // 省
  245. 'city' => $result['city'] ?? '', // 市
  246. ];
  247. break;
  248. case 7:
  249. //7 飞机行程单识别
  250. $data = [
  251. 'name' => $result['name'], // 里程
  252. 'starting_station' => $result['starting_station'], // 始发站
  253. 'destination_station' => $result['destination_station'], // 目的站
  254. 'flight' => $result['flight'], // 航班号
  255. 'date' => $result['date'], // 日期
  256. 'ticket_number' => $result['ticket_number'], // 电子客票号码
  257. 'fare' => $result['fare'], // 票价
  258. 'money' => $result['fare'],//
  259. 'dev_fund' => $result['dev_fund'], // 民航发展基金/基建费
  260. 'fuel_surcharge' => $result['fuel_surcharge'], // 燃油附加费
  261. 'other_tax' => $result['其他税费'], // 民航发展基金/基建费
  262. 'ticket_rates' => $result['ticket_rates'], // 合计金额
  263. 'issued_date' => $result['issued_date'], // 填开日期
  264. 'id_num' => $result['id_num'], // 身份证号
  265. 'carrier' => $result['carrier'], // 承运人
  266. 'time' => $result['time'], // 时间
  267. 'issued_by' => $result['issued_by'], // 订票渠道
  268. 'serial_number' => $result['serial_number'], // 印刷序号
  269. 'insurance' => $result['insurance'], // 保险费
  270. 'fare_basis' => $result['fare_basis'], // 客票级别
  271. 'class' => $result['class'], // 座位等级
  272. 'agent_code' => $result['agent_code'], // 销售单位号
  273. 'endorsement' => $result['endorsement'], // 签注
  274. 'allow' => $result['allow'], // 免费行李
  275. ];
  276. break;
  277. case 8:
  278. //8 汽车票识别
  279. $data = [
  280. 'InvoiceCode' => $result['InvoiceCode'], // 发票代码
  281. 'InvoiceNum' => $result['InvoiceNum'], // 发票号码
  282. 'Date' => $result['Date'], // 日期
  283. 'Time' => $result['Time'], // 时间
  284. 'StartingStation' => $result['StartingStation'], // 出发站
  285. 'Fare' => $result['Fare'], // 金额
  286. 'money' => $result['fare'],//
  287. 'IdNum' => $result['IdNum'], // 身份证号
  288. 'DestinationStation' => $result['DestinationStation'], // 到达站
  289. 'Name' => $result['Name'], // 姓名
  290. 'InvoiceTime' => $result['InvoiceTime'], // 开票日期
  291. ];
  292. break;
  293. case 9:
  294. //9 过路过桥费发票识别
  295. $data = [
  296. 'InvoiceCode' => $result['InvoiceCode'], // 发票代码
  297. 'InvoiceNum' => $result['InvoiceNum'], // 发票号码
  298. 'Entrance' => $result['Entrance'], // 入口
  299. 'Exit' => $result['Exit'], // 出口
  300. 'Date' => $result['Date'], // 日期
  301. 'Time' => $result['Time'], // 时间
  302. 'Fare' => $result['Fare'], // 金额
  303. 'money' => $result['fare'],//
  304. 'province' => $result['province'] ?? '', // 省
  305. 'city' => $result['city'] ?? '', // 市
  306. ];
  307. break;
  308. case 10:
  309. //10 船票识别
  310. $data = [
  311. 'InvoiceType' => $result['InvoiceType'], // 发票类型
  312. 'InvoiceCode' => $result['InvoiceCode'], // 发票代码
  313. 'InvoiceNum' => $result['InvoiceNum'], // 发票号码
  314. 'StartingStation' => $result['StartingStation'], // 出发地点
  315. 'DestinationStation' => $result['DestinationStation'], // 到达地点
  316. 'Fare' => $result['Fare'], // 金额
  317. 'money' => $result['fare'],//
  318. 'InvoiceDate' => $result['InvoiceDate'], // 开票日期
  319. ];
  320. break;
  321. case 11:
  322. //11 网约车行程单识别
  323. $data = [
  324. 'ServiceProvider' => $result['ServiceProvider'], // 服务商
  325. 'StartTime' => $result['StartTime'], // 行程开始时间
  326. 'EndTime' => $result['EndTime'], // 行程结束时间
  327. 'Phone' => $result['Phone'], // 行程人手机号
  328. 'ApplicationDate' => $result['ApplicationDate'], // 申请日期
  329. 'TotalFare' => $result['TotalFare'], // 总金额
  330. 'City' => $result['City'], // 城市
  331. 'Fare' => $result['Fare'], // 金额
  332. 'money' => $result['fare'],//
  333. 'Items' => $result['Items'], // [['PickupTime'=>上车时间,'PickupDate'=>上车日期,'CarType'=>车型,'Distance'=>里程,'StartPlace'=>起点,'DestinationPlace'=>终点]]
  334. ];
  335. break;
  336. case 12:
  337. //12 通用票据识别
  338. $data = [
  339. ['location' => $result['location'],// [['left'=>'','top'=>'','width'=>'','height'=>'']]
  340. 'words' => $result['words']],// 识别结果字符串
  341. ];
  342. break;
  343. case 13:
  344. // 车牌
  345. $data = ['number' => $result['number'],// 识别结果字符串
  346. ];
  347. break;
  348. case 14:
  349. // 名片
  350. $data = [
  351. 'name' => $result['NAME'][0],
  352. 'mobile' => $result['MOBILE'][0],
  353. 'company' => $result['COMPANY'][0],
  354. 'addr' => $result['ADDR'][0],
  355. 'email' => $result['EMAIL'][0],
  356. 'tel' => $result['TEL'][0],
  357. ];
  358. break;
  359. default:
  360. break;
  361. }
  362. return $data;
  363. }
  364. //名片识别 https://www.textin.com/market/detail/business_card
  365. public function business_card(){
  366. $file_id=input('file_id');
  367. if(empty($file_id)){
  368. $this->error('图片不能为空');
  369. }
  370. // 请登录后前往 “工作台-账号设置-开发者信息” 查看 x-ti-app-id
  371. $app_id = $this->textinappid;
  372. if(empty($app_id)){
  373. $this->error('后台未设置textinappid,请联系管理员');
  374. }
  375. // 请登录后前往 “工作台-账号设置-开发者信息” 查看 x-ti-secret-code
  376. $secret_code = $this->textinsecret;
  377. if(empty($app_id)){
  378. $this->error('后台未设置textinsecret,请联系管理员');
  379. }
  380. // 名片识别
  381. $url = 'https://api.textin.com/robot/v1.0/api/business_card';
  382. $img=File::getUrl($file_id);
  383. $headers = [
  384. 'x-ti-app-id:' . $app_id,
  385. 'x-ti-secret-code:' . $secret_code
  386. ];
  387. $fileData = file_get_contents('.'.$img); // 读取文件
  388. $response = $this->post($url, $headers, $fileData);
  389. $ocrResult = json_decode($response, true);
  390. Log::info($ocrResult);
  391. // 获取 身份证号 和 姓名
  392. $result =isset( $ocrResult['result'] )? $ocrResult['result'] : '';
  393. if ($result)
  394. {
  395. $list = $result['item_list'];
  396. $data=[];
  397. foreach ($list as $v){
  398. $data[$v['key']]=['name'=>$v['description'],'value'=>$v['value']];
  399. }
  400. $textin_field =AdminConfig::getConfigValue('textin_field','textin');
  401. if($textin_field){
  402. $textin_field=json_decode($textin_field,true);
  403. }else{
  404. $textin_field=[];
  405. }
  406. $result=[];
  407. foreach ($textin_field as $field => $val) {
  408. if (isset($data[$field]) && $val) {
  409. $result[$val] = $data[$field];
  410. }
  411. }
  412. $this->success('请求成功',$result);
  413. }
  414. $this->error('识别失败');
  415. }
  416. /**
  417. * Post请求
  418. *
  419. * @param string $url 地址
  420. * @param array $headers Http Header
  421. * @param string $body 内容
  422. * @return string
  423. */
  424. function post($url, $headers, $body) {
  425. $ch = curl_init();
  426. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  427. curl_setopt($ch, CURLOPT_URL, $url);
  428. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  429. curl_setopt($ch, CURLOPT_HEADER, false);
  430. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  431. curl_setopt($ch, CURLOPT_POST, true);
  432. curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  433. $response = curl_exec($ch);
  434. curl_close($ch);
  435. return $response;
  436. }
  437. }