照片解析,文本查询

test
橙橙楊 5 years ago committed by 潘啟华
parent b3e02a497b
commit acf258b3b0
  1. 2
      Log.php
  2. 89
      api/BaiduImage.php
  3. 10
      api/JsonResponse.php
  4. 45
      api/QueryText.php
  5. 49
      baidu/BaiduAiRequest.php
  6. 9
      config.php
  7. 64
      database/DbUtil.php
  8. 103
      database/Query.php
  9. 38
      entity/ApiToken.php
  10. 68
      entity/Garbage.php
  11. 3
      index.php
  12. 4
      script/db.sql
  13. 6974
      script/main_Garbage.sql
  14. 24
      test.php

@ -1,6 +1,6 @@
<?php
require 'vendor/autoload.php';
require_once __ROOT__ . '/vendor/autoload.php';
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;

@ -1,14 +1,87 @@
<?php
header("Content-type:application/json");
require_once "../config.php";
require_once __ROOT__ . "/baidu/BaiduAiRequest.php";
require_once __ROOT__ . "/entity/Garbage.php";
require_once __ROOT__ . "/database/Query.php";
require_once __ROOT__ . "/api/JsonResponse.php";
if (isset($_POST["image"])) {
//查询垃圾分类
function query_waste_soring($image_res)
{
// 匹配结果大于0才进行处理
if (isset($image_res["result_num"]) && $image_res["result_num"] > 0) {
// 匹配关键字
$keyword = array();
$sql = "";
// 去除匹配结果数组
foreach ($image_res["result"] as $result) {
// 筛选置信值大于0.5的结果
if ($result["score"] >= 0.5) {
array_push($keyword, '%' . $result["keyword"] . '%');
// 拼接模糊查询语句
$sql = $sql . " or name like ?";
}
}
// 如果筛选结果大于0处理
if (count($keyword) > 0) {
$sql = "select * from garbage where" . substr($sql, 3);
info("查询sql" . $sql);
$garbage_result = getGarbageQuery($sql, $keyword);
json_res(json_encode(array("img_parse" => true, "query" => true, "img_res" => $image_res, "result" => $garbage_result->getGarbageObjArray()), JSON_UNESCAPED_UNICODE));
} else {
json_res(json_encode(array("img_parse" => true, "img_res" => $image_res)));
}
} else {
json_res(json_encode(array("img_parse" => false)));
}
}
// 查询token
$token_result = new class() extends AbstractTokenQuery
{
public function bind_param(mysqli_stmt $stmt, array $param)
{
echo <<<EOF
{"msg":"合法图片参数"}
EOF;
}
};
DbUtil::query("select * from api_token limit 0,1", $token_result);
// toekn如果失效,则更新token
if (strtotime(date(default_format)) >= strtotime($token_result->getToken()->getEndTime())) {
info("token失效了,更新token");
$updateToken = new BaiduAiRequest("https://aip.baidubce.com/oauth/2.0/token");
$updateToken->request_token();
DbUtil::query("select * from api_token limit 0,1", $token_result);
}
//获取图片参数
if (isset($_POST["image"])) {
// 请求通用物体和场景识别高级版接口
$image_req = new BaiduAiRequest("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general");
// 获取解析结果
$image_res = $image_req->request_with_param(array("access_token" => $token_result->getToken()->getAccessToken(), "image" => $_POST["image"]));
query_waste_soring($image_res);
} else if ($_FILES["file"]["error"] > 0) {
json_res(<<<EOF
{"msg":"文件上传失败"}
EOF
);
} else if ($_FILES["file"]["error"] == 0) {
// base64加密文件二进制数据
$image = base64_encode(file_get_contents($_FILES["file"]["tmp_name"]));
// 请求通用物体和场景识别高级版接口
$image_req = new BaiduAiRequest("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general");
// 获取解析结果
$image_res = $image_req->request_with_param(array("access_token" => $token_result->getToken()->getAccessToken(), "image" => $image));
query_waste_soring($image_res);
} else {
echo <<<EOF
json_res(<<<EOF
{"msg":"缺少图片参数"}
EOF;
}
EOF
);
}

@ -0,0 +1,10 @@
<?php
//返回json
function json_res($json_str)
{
// 设置json响应头
header("Content-type:application/json");
echo $json_str;
}

@ -0,0 +1,45 @@
<?php
require_once "../config.php";
require_once __ROOT__ . "/api/JsonResponse.php";
require_once __ROOT__ . "/database/DbUtil.php";
require_once __ROOT__ . "/database/Query.php";
//关键字查询
class QueryText
{
public static function get($sql, $keyword): AbstractGarbageQuery
{
$garbage_result = new class() extends AbstractGarbageQuery
{
// 参数绑定
public function bind_param(mysqli_stmt $stmt, array $param)
{
if (count($param) > 1) {
$stmt->bind_param(str_repeat("s", count($param)), $param[0], ...array_slice($param, 1));
} else {
$stmt->bind_param(str_repeat("s", count($param)), $param[0]);
}
}
};
DbUtil::query($sql, $garbage_result, $keyword);
return $garbage_result;
}
}
if (empty($_GET)) {
json_res(json_encode(array("status" => false, "error" => "非法请求"), JSON_UNESCAPED_UNICODE));
} else if (isset($_GET["keyword"]) and !empty($_GET["keyword"])) {
$result = getGarbageQuery("select * from garbage where name like ?", array("%" . $_GET["keyword"] . "%"));
json_res(json_encode(array("status" => true, "result" => $result->getGarbageObjArray(), "keyword" => $_GET["keyword"]), JSON_UNESCAPED_UNICODE));
} else if (isset($_GET["category"]) and is_numeric($_GET["category"])) {
$result = getGarbageQuery("select * from garbage where category = ?", array((int)$_GET["category"]));
json_res(json_encode(array("status" => true, "result" => $result->getGarbageObjArray(), "category" => $_GET["category"]), JSON_UNESCAPED_UNICODE));
} else {
json_res(json_encode(array("status" => false, "error" => "非法查询参数"), JSON_UNESCAPED_UNICODE));
}

@ -1,7 +1,7 @@
<?php
require "ApiToken.php";
require "../database/DbUtil.php";
require_once __ROOT__ . "/entity/ApiToken.php";
require_once __ROOT__ . "/database/DbUtil.php";
//api请求
@ -20,7 +20,7 @@ class BaiduAiRequest
$this->url = $url;
}
function request()
function request_token()
{
try {
if (empty(self::$client_id) or empty(self::$client_secret)) {
@ -29,15 +29,18 @@ class BaiduAiRequest
$post_data['grant_type'] = 'client_credentials';
$post_data['client_id'] = self::$client_id;
$post_data['client_secret'] = self::$client_secret;
$o = "";
foreach ($post_data as $k => $v) {
$o .= "$k=" . urlencode($v) . "&";
}
$param = substr($o, 0, -1);
if (empty($this->url) || empty($param)) {
return false;
$json_res = $this->request_with_param($post_data);
if (array_key_exists("error", $json_res)) {
throw new Exception("请求异常");
} else {
DbUtil::delete("delete from api_token");
$token = new ApiToken(null, $json_res["refresh_token"], $json_res["expires_in"], null, $json_res["scope"], $json_res["session_key"], $json_res["access_token"], $json_res["session_secret"]);
DbUtil::insert("insert into api_token (refresh_token, expires_in, end_time, scope, session_key, access_token, session_secret) values (?,?,?,?,?,?,?)",
"sisssss", $token->getRefreshToken(), $token->getExpiresIn(), date_format(date_create(date(default_format))->add(date_interval_create_from_date_string($token->getExpiresIn() . " seconds")), default_format), $token->getScope(), $token->getSessionKey(), $token->getAccessToken(), $token->getSessionSecret());
info("token保存成功");
return $token;
}
return $this->request_with_param($param);
} catch (Exception $e) {
$GLOBALS["default_log"]->error($e);
return <<<EOF
@ -46,11 +49,20 @@ class BaiduAiRequest
}
}
// 发送请求
function request_with_param($param)
{
try {
$o = "";
foreach ($param as $k => $v) {
$o .= "$k=" . urlencode($v) . "&";
}
$param = substr($o, 0, -1);
if (empty($this->url) || empty($param)) {
return false;
}
$curlPost = $param;
$curl = curl_init($this->url);//初始化curl
curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
@ -61,17 +73,9 @@ class BaiduAiRequest
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($curl);//运行curl
curl_close($curl);
$json_res = json_decode($data, true);
$json_res = json_decode($data, true, 512, JSON_UNESCAPED_UNICODE);
info("接口响应结果:" . $data);
if (array_key_exists("error", $json_res)) {
throw new Exception("请求异常");
} else {
$token = new ApiToken($json_res["refresh_token"], $json_res["expires_in"], $json_res["session_key"], $json_res["access_token"], $json_res["scope"], $json_res["session_secret"]);
DbUtil::insert("insert into api_token (refresh_token, expires_in, end_time, scope, session_key, access_token, session_secret) values (?,?,?,?,?,?,?)",
"sisssss", $token->getRefreshToken(), $token->getExpiresIn(), $token->getEndTime(), $token->getScope(), $token->getSessionKey(), $token->getAccessToken(), $token->getSessionSecret());
info("token保存成功");
return $token;
}
return $json_res;
} catch (Exception $e) {
error($e);
return <<<EOF
@ -82,7 +86,4 @@ class BaiduAiRequest
}
$obj = new BaiduAiRequest("https://aip.baidubce.com/oauth/2.0/token");
$obj->request();

@ -1,13 +1,14 @@
<?php
//数据库配置
define("db_config", array(
"servername" => "mylinux",
"username" => "sukura",
"password" => "123456",
"dbname" => "waste_sorting"
));
//默认日期格式
define("default_format", "Y-m-d H:i:s");
//根目录
//define("__ROOT__", dirname(__FILE__));
define("__ROOT__", dirname(__FILE__));
define("__ROOT__", "D:/JetBrains/PhpstormProjects/WasteSorting");

@ -1,7 +1,16 @@
<?php
require "../config.php";
require "../Log.php";
require_once __ROOT__ . "/config.php";
require_once __ROOT__ . "/Log.php";
interface DoExcute
{
// 参数处理
function bind_param(mysqli_stmt $stmt, array $param);
// 执行结果处理
function doResult(mysqli_stmt $stmt);
}
class DbUtil
{
@ -36,18 +45,59 @@ class DbUtil
}
// 插入数据
public static function insert($sql, $types, ...$_)
public static function modify($action, $sql, $types = "", ...$_)
{
try {// 创建连接
$conn = self::getConn();
$stmt = $conn->prepare("$sql");// 参数绑定
$stmt->bind_param($types, ...$_);// 执行sql
$stmt->execute();// 关闭连接
$stmt = $conn->prepare("$sql");//创建一个预定义的对象 ?占位
if (!empty($types)) {
$stmt->bind_param($types, ...$_);// 参数绑定
}
$stmt->execute();// 执行sql
info($action . $stmt->affected_rows . "条数据");
$stmt->close();
info("执行sql.$sql.成功");
self::closeConn($conn);// 关闭连接
} catch (Exception $e) {
error($action . "数据异常" . $e);
}
}
// 插入数据
public static function insert($sql, $types = "", ...$_)
{
self::modify("插入", $sql, $types, ...$_);
}
// 更新数据
public static function update($sql, $types = "", ...$_)
{
self::modify("更新", $sql, $types, ...$_);
}
// 删除数据
public static function delete($sql, $types = "", ...$_)
{
self::modify("删除", $sql, $types, ...$_);
}
//查询数据
public static function query($sql, DoExcute $doExcute, array $param = array())
{
try {// 创建连接
$conn = self::getConn();
$stmt = $conn->prepare($sql);//创建一个预定义的对象 ?占位
$doExcute->bind_param($stmt, $param);
$stmt->execute();// 执行sql
$doExcute->doResult($stmt);
info("执行sql.$sql.成功");
$stmt->close();
// 关闭连接
self::closeConn($conn);
} catch (Exception $e) {
error("插入数据异常" . $e);
error("查询数据异常" . $e);
}
}
}

@ -0,0 +1,103 @@
<?php
require_once __ROOT__ . "/entity/ApiToken.php";
require_once __ROOT__ . "/entity/Garbage.php";
//Token查询
abstract class AbstractTokenQuery implements DoExcute
{
// token查询结果
private $token_array = array();
/**
* TokenQuery constructor.
*/
public function __construct()
{
}
// 绑定toekn信息
public function doResult(mysqli_stmt $stmt)
{
/**
*
* $col1 $id
* $col2 $refresh_token
* $col3 $expires_in
* $col4 $end_time
* $col5 $scope
* $col6 $session_key
* $col7 $access_token
* $col8 $session_secret
*/
$stmt->bind_result($col1, $col2, $col3, $col4, $col5, $col6, $col7, $col8);
while ($stmt->fetch()) {
array_push($this->token_array, new ApiToken($col1, $col2, $col3, $col4, $col5, $col6, $col7, $col8));
}
}
/**
* @return array
*/
public function getTokenArray(): array
{
return $this->token_array;
}
function getToken(): ApiToken
{
return $this->token_array[0];
}
}
//垃圾分类查询
abstract class AbstractGarbageQuery implements DoExcute
{
// 垃圾分类查询结果
private $garbage_obj_array = array();
public function doResult(mysqli_stmt $stmt)
{
$stmt->bind_result($col1, $col2, $col3, $col4);
while ($stmt->fetch()) {
$g = new Garbage($col1, $col2, $col3, $col4);
array_push($this->garbage_obj_array, $g);
}
}
/**
* @return array
*/
public function getGarbageObjArray(): array
{
return $this->garbage_obj_array;
}
}
function getGarbageQuery($sql, $keyword): AbstractGarbageQuery
{
$garbage_result = new class() extends AbstractGarbageQuery
{
public function bind_param(mysqli_stmt $stmt, array $param)
{
if (count($param) > 1) {
$stmt->bind_param(str_repeat("s", count($param)), $param[0], ...array_slice($param, 1));
} else {
$stmt->bind_param(str_repeat("s", count($param)), $param[0]);
}
}
};
DbUtil::query($sql, $garbage_result, $keyword);
return $garbage_result;
}

@ -1,21 +1,13 @@
<?php
//require "../database/config.php";
//百度token管理
class ApiToken
{
private $id;
private $refresh_token;
private $expires_in;
private $end_time;
/**
* @return false|string
*/
public function getEndTime()
{
return $this->end_time;
}
private $scope;
private $session_key;
private $access_token;
@ -23,24 +15,38 @@ class ApiToken
/**
* ApiToken constructor.
* @param $id
* @param $refresh_token
* @param $expires_in
* @param $end_time
* @param $scope
* @param $session_key
* @param $access_token
* @param $session_secret
*/
public function __construct($refresh_token, $expires_in, $scope, $session_key, $access_token, $session_secret)
public function __construct($id, $refresh_token, $expires_in, $end_time, $scope, $session_key, $access_token, $session_secret)
{
$this->id = $id;
$this->refresh_token = $refresh_token;
$this->expires_in = $expires_in;
$this->end_time = date_format(date_create(date(default_format))->add(date_interval_create_from_date_string($expires_in . " seconds")), default_format);
$this->end_time = $end_time;
$this->scope = $scope;
$this->session_key = $session_key;
$this->access_token = $access_token;
$this->session_secret = $session_secret;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @return mixed
*/
@ -57,6 +63,14 @@ class ApiToken
return $this->expires_in;
}
/**
* @return false|string
*/
public function getEndTime()
{
return $this->end_time;
}
/**
* @return mixed
*/

@ -0,0 +1,68 @@
<?php
//垃圾分类
class Garbage implements JsonSerializable
{
private $name;
private $category;
private $create_at;
private $update_at;
/**
* Garbage constructor.
* @param $name
* @param $category
* @param $create_at
* @param $update_at
*/
public function __construct($name, $category, $create_at, $update_at)
{
$this->name = $name;
$this->category = $category;
$this->create_at = $create_at;
$this->update_at = $update_at;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @return mixed
*/
public function getCategory()
{
return $this->category;
}
/**
* @return mixed
*/
public function getCreateAt()
{
return $this->create_at;
}
/**
* @return mixed
*/
public function getUpdateAt()
{
return $this->update_at;
}
public function jsonSerialize()
{
$data = [];
foreach ($this as $key => $val) {
if ($val !== null) $data[$key] = $val;
}
return $data;
}
}

@ -1,6 +1,7 @@
<?php
$menus = array("API" => "百度API配置", "WasteSorting" => "垃圾分类管理", "Question" => "题目管理");
require "head.php";
require_once "config.php";
require_once __ROOT__ . "/head.php";
getMenu("后台管理");

@ -7,10 +7,10 @@ create table api_token
expires_in int,
# 有效时间
end_time datetime,
scope varchar(256),
scope varchar(1024),
session_key varchar(256),
# 要获取的Access Token;
access_token varchar(1024),
access_token varchar(256),
session_secret varchar(32)
);

File diff suppressed because it is too large Load Diff

@ -1,3 +1,23 @@
<?php
require "config.php";
echo __ROOT__;
include "config.php";
include __ROOT__ . "/database/DbUtil.php";
echo <<<EOF
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form action="/api/BaiduImage.php" method="post" enctype="multipart/form-data">
<label for="file">文件名:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="提交">
</form>
</body>
</html>
EOF;

Loading…
Cancel
Save