Skip to content

Commit 923be3f

Browse files
committed
add: 图片放qiniu OCR用百度
1 parent d01b00c commit 923be3f

File tree

3 files changed

+265
-0
lines changed

3 files changed

+265
-0
lines changed
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
<?php
2+
3+
namespace App\Http\Controllers\Bus;
4+
5+
use App\Http\Repository\AccessToken;
6+
use App\Http\Repository\ToolRepository;
7+
use Curl\Http;
8+
use Illuminate\Http\Request;
9+
use App\Http\Controllers\Controller;
10+
use Illuminate\Support\Facades\Log;
11+
use Qiniu\Auth;
12+
13+
class AutoController extends Controller
14+
{
15+
/**
16+
* 获取七牛 Token 的方法
17+
*
18+
* @return \Illuminate\Http\Response
19+
*/
20+
public function getToken()
21+
{
22+
$bucket = env('QINIU_BUCKET');
23+
$accessKey = env('QINIU_ACCESSKEY');
24+
$secretKey = env('QINIU_SECRETKEY');
25+
$url = env('APP_URL');
26+
27+
$auth = new Auth($accessKey, $secretKey);
28+
//$upToken = $auth->uploadToken($bucket);
29+
// 上传策略
30+
$policy = array(
31+
'deadline' => time() + 60, // 上传凭证有效截止时间。Unix时间戳,单位为秒
32+
'returnUrl' => $url.'/api/qiniuCallback',
33+
'returnBody' => '{"key": $(key)}',
34+
// 'callbackBody' => 'key=$(key)&hash=$(etag)&bucket=$(bucket)',
35+
);
36+
$upToken = $auth->uploadToken($bucket, null, 3600, $policy);
37+
38+
return $this->out(200, ['token' => $upToken]);
39+
}
40+
41+
/**
42+
* 七牛上传回调方法
43+
*
44+
* @param Request $request
45+
*
46+
* @return array
47+
*/
48+
public function qiniuCallback(Request $request)
49+
{
50+
$uploadRet = $request['upload_ret'];
51+
$ret = base64_decode($uploadRet);
52+
$cbody = json_decode($ret, true);
53+
if (empty($cbody['key'])) {
54+
return ['code' => 1, 'data' => [], 'msg' => 'error'];
55+
}
56+
// 七牛云访问的 url
57+
$dn = env('QINIU_URL');
58+
Log::info('qiniuCallback: ', $cbody); // error_log(print_r($cbody, true));
59+
$url = $dn.$cbody['key'];
60+
61+
$stat_ = file_get_contents($url.'?stat');
62+
$stat = json_decode($stat_, true);
63+
$mtype = $stat['mimeType'];
64+
if (substr($mtype, 0, 6) == 'image/') {
65+
// 3. 调用百度 OCR 识别信息
66+
$words = $this->baiduOCR('', $url);
67+
return ['code' => 0, 'data' => ['url' => $url, 'words' => $words], 'msg' => 'success'];
68+
}
69+
return ['code' => 1, 'data' => [], 'msg' => 'error'];
70+
}
71+
72+
/**
73+
* @param $img
74+
* @param $imgUrl
75+
*
76+
* @return string
77+
*/
78+
public function baiduOCR($img, $imgUrl)
79+
{
80+
// 1. 获取 Access Token
81+
$config = [
82+
'url' => 'https://aip.baidubce.com/oauth/2.0/token',
83+
// 'params' => [
84+
// 'grant_type' => 'client_credentials',
85+
// 'client_id' => 'Va5yQRHlA4Fq5eR3LT0vuXV4',
86+
// 'client_secret' => '0rDSjzQ20XUj5itV6WRtznPQSzr5pVw2'
87+
// ]
88+
];
89+
$accessToken = AccessToken::getInstance($config)->getToken();
90+
91+
if (empty($accessToken)) {
92+
Log::error('######### GET baiduOCR ERROR !!!'); //error_log($e->getMessage());
93+
return '';
94+
}
95+
96+
// 2. 识别图片
97+
$url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token='.$accessToken;
98+
// 2.1 两种传递方式:一、base64 文件, 二、网络图片地址
99+
if ($img) {
100+
$img = base64_encode($img);
101+
$bodys = ["image" => $img];
102+
} elseif ($imgUrl) {
103+
$bodys = ['url' => $imgUrl];
104+
} else {
105+
return '';
106+
}
107+
108+
$http = new Http();
109+
$res = $http->request($url, $bodys, 'POST');
110+
111+
$result = json_decode($res['content'], true);
112+
113+
$words = '';
114+
if ($result) {
115+
foreach ($result['words_result'] as $value) {
116+
$words .= $value['words'].PHP_EOL;
117+
}
118+
119+
// 3. 保存到数据库
120+
ToolRepository::getInstance()->saveUploadData($imgUrl, $words);
121+
}
122+
return $words;
123+
}
124+
}
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
<?php
2+
/**
3+
* Token 获取并缓存到文件
4+
* User: lisgroup
5+
* Date: 18-10-07
6+
* Time: 上午11:39
7+
*/
8+
9+
namespace App\Http\Repository;
10+
11+
12+
use Curl\Http;
13+
use Illuminate\Support\Facades\Storage;
14+
15+
class AccessToken
16+
{
17+
protected $expiresIn = 2592000;
18+
19+
/**
20+
* @var array 请求的 header 头信息
21+
* 如:
22+
* $header = [
23+
* 'Content-Type: application/json;charset=UTF-8',
24+
* 'Content-Length: 46', // 需定义长度 strlen($params),
25+
* 'user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1',
26+
* ]
27+
*
28+
*/
29+
protected $header = [];
30+
31+
/**
32+
* @var string|array 模拟表单提交的数据,发送 JSON 数据必须定义为 String
33+
* 如:{"username":"admin","password":"123456"}
34+
*/
35+
protected $params = 'api=11959004&grant_type=client_credentials&client_id=yxGSiFRIbfdl7WwGGXIGlmnR&client_secret=nE2rXH6ScEUg8MifDPbTzCrD5SHoC4vh';
36+
37+
private $fileName = '';
38+
39+
private $url;
40+
private static $instance;
41+
42+
/**
43+
* TokenUtil constructor.
44+
* @param array $config
45+
*
46+
* $config = [
47+
* 'url' => "https://api.yii2.wang/v1/authorize",
48+
* 'expiresIn' => '86400', // 24H
49+
* 'params' => ['username' => '13776036576', 'password' => '123456'],
50+
* ];
51+
*/
52+
private function __construct($config)
53+
{
54+
foreach ($config as $key => $value) {
55+
$this->$key = $value;
56+
}
57+
// empty($this->fileName) && $this->fileName = __DIR__.'/token.txt';
58+
}
59+
60+
public static function getInstance($config = [])
61+
{
62+
if (!(self::$instance instanceof AccessToken)) {
63+
self::$instance = new self($config);
64+
}
65+
return self::$instance;
66+
}
67+
68+
/**
69+
* 读取 token
70+
* @param bool $bool 是否强制刷新缓存 token
71+
* @return bool|string
72+
*/
73+
public function getToken($bool = false)
74+
{
75+
try {
76+
$data = Storage::get('token.txt');
77+
} catch (\Exception $e) {
78+
return $this->buildAccessToken();
79+
}
80+
$store = json_decode($data, true);
81+
// 1. 强制获取,文件不存在,文件过期 =》 刷新 Token
82+
if ($bool || empty($store['create_at']) || time() - $store['create_at'] > $this->expiresIn) {
83+
// HTTP 请求获取 token 并写入文件缓存
84+
return $this->buildAccessToken();
85+
}
86+
87+
// 2. 在有效期内,直接读取返回
88+
return $store['access_token'];
89+
}
90+
91+
/**
92+
* 设置定时器,每两小时执行一次 buildAccessToken() 函数获取一次 access_token
93+
*/
94+
public function setInterval()
95+
{
96+
ignore_user_abort();//关闭浏览器仍然执行
97+
set_time_limit(0);//让程序一直执行下去
98+
$interval = $this->expiresIn;//每隔一定时间运行
99+
do {
100+
try {
101+
$this->buildAccessToken();
102+
} catch (\Exception $e) {
103+
echo $e->getMessage();
104+
}
105+
sleep($interval); // 等待时间,进行下一次操作。
106+
} while (true);
107+
}
108+
109+
/**
110+
* 获取 access_token 并保存到 token.txt 文件中
111+
* @return string|bool 返回 access_token
112+
*/
113+
private function buildAccessToken()
114+
{
115+
if (empty($this->url)) {
116+
return false;
117+
}
118+
119+
$curl = new Http();
120+
$httpResult = $curl->request($this->url, $this->params, 'post', 6, $this->header);
121+
122+
// 2. 写入文件缓存
123+
if (!empty($httpResult['content'])) {
124+
$content = json_decode($httpResult['content'], true);
125+
$response = array_merge($content, ['create_at' => time()]);
126+
$json = json_encode($response, JSON_UNESCAPED_UNICODE);
127+
128+
// 2018-10-11 使用 Laravel Storage 存储数据
129+
return Storage::disk('local')->put('token.txt', $json) ? $content['access_token'] : false;
130+
} else {
131+
return false;
132+
}
133+
}
134+
}

laravel/routes/web.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,13 @@
4646
Route::any('new_line', 'NewApiController@newBusLine');
4747
Route::any('output', 'NewApiController@output');
4848
Route::any('test', 'NewApiController@Task');
49+
50+
// 1. 获取七牛上传操作的 token
51+
Route::get('getToken', 'AutoController@getToken');
52+
// 2. 七牛 303 状态码 回调上传完成文件信息
53+
Route::get('qiniuCallback', 'AutoController@qiniuCallback');
54+
// 3. 百度 OCR
55+
Route::get('baiduOCR', 'AutoController@baiduOCR');
4956
});
5057

5158
/******** 测试任务的接口地址 *********/

0 commit comments

Comments
 (0)