赞
踩
本文探索如何利用百度千帆大模型平台完成图片内容理解的api编写
目录
该请求用于图像内容理解,支持输入图片和提问信息,可对输入图片进行理解,输出对图片的一句话描述,同时可针对图片内的主体/文字等进行检测与识别,支持返回图片内多主体/文字的内容、位置等信息。图像内容理解服务涉及 2 个子接口,分别为:
图像内容理解-提交请求:支持传入图片、提问等参数,创建图像内容理解任务,该接口会返回任务ID。
图像内容理解-获取结果:在任务成功创建后,支持传入任务ID,查看任务处理的状态、获取处理完成后返回的结果。
鉴权认证:
鉴权的主要目的是获取Access_token。Access_token是用户的访问令牌,承载了用户的身份、权限等信息。鉴权主要分为以下两步:
1.获取AK/SK
2.获取Access_token
当成功创建应用后,在对应产品页签下选择“应用列表”,可查看已创建的应用。
百度平台将会分配给此应用的相关凭证,主要为AppID、API Key、Secret Key。以上三个信息是应用实际开发的重要凭证。
百度AI开放平台使用OAuth2.0授权调用开放API,调用API时必须在URL中带上Access_token参数,Access token默认有效期为30天,获取Access_token的流程如下:
向授权服务地址https://aip.baidubce.com/oauth/2.0/token
发送请求(推荐使用POST),并在URL中带上以下参数:
grant_type: 必须参数,固定为client_credentials
;
client_id: 必须参数,应用的API Key
;
client_secret: 必须参数,应用的Secret Key
;
我们在自己的后端代码中可以编写这个接口:
/** 获取access_token **/ @PostMapping("/get_token") public ResponseEntity<String> getBaiduToken() { String authUrl = "https://aip.baidubce.com/oauth/2.0/token"; // Set headers HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("grant_type", "client_credentials"); map.add("client_id", apiKey); map.add("client_secret", secretKey); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers); ResponseEntity<Map> response = restTemplate.postForEntity(authUrl, entity, Map.class); if (response.getStatusCode() == HttpStatus.OK) { Map<String, Object> responseBody = response.getBody(); if (responseBody != null && responseBody.containsKey("access_token")) { String accessToken = (String) responseBody.get("access_token"); return ResponseEntity.ok(accessToken); } else { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("找不到token"); } } else { return ResponseEntity.status(response.getStatusCode()).body(response.getBody().toString()); } }
这段代码用于获取百度AI平台的访问令牌(access token)。
public ResponseEntity<String> getBaiduToken() {
: 方法的声明,返回一个ResponseEntity
,其中包含一个String
类型的数据,表示获取到的访问令牌。
String authUrl = "https://aip.baidubce.com/oauth/2.0/token";
: 这是百度AI平台用于获取访问令牌的API地址。
HttpHeaders headers = new HttpHeaders();
: 创建HTTP请求头对象。
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
: 设置HTTP请求头的内容类型为application/x-www-form-urlencoded
,表示表单数据。
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
: 创建一个用于存储请求参数的Map对象,参数是键值对形式。
map.add("grant_type", "client_credentials");
: 将客户端凭证模式作为参数添加到请求中。
map.add("client_id", apiKey);
: 将API密钥作为参数添加到请求中。
map.add("client_secret", secretKey);
: 将密钥作为参数添加到请求中。
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
: 创建一个HTTP实体对象,包含请求参数和请求头信息。
ResponseEntity<Map> response = restTemplate.postForEntity(authUrl, entity, Map.class);
: 发送HTTP POST请求到指定的URL,使用之前构建的实体对象,返回一个ResponseEntity
,其中包含一个Map
对象,表示API的响应。
if (response.getStatusCode() == HttpStatus.OK) {
: 检查HTTP响应状态码是否为200(OK)。
Map<String, Object> responseBody = response.getBody();
: 获取API响应的主体内容。
if (responseBody != null && responseBody.containsKey("access_token")) {
: 检查API响应中是否包含名为"access_token"的字段。
String accessToken = (String) responseBody.get("access_token");
: 从API响应中获取访问令牌。
return ResponseEntity.ok(accessToken);
: 如果获取到了访问令牌,则以HTTP 200的状态返回访问令牌。
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("找不到token");
: 如果无法获取到访问令牌,则返回HTTP 500(Internal Server Error)状态码,并包含一条错误消息。
return ResponseEntity.status(response.getStatusCode()).body(response.getBody().toString());
: 如果HTTP响应状态码不是200,则返回与API响应体相同的状态码和内容。
我们可以通过ApiFox来测试接口编写的正确性:
可以看到他成功的返回了我们想要的token,以后请求我们带上他就好。
请求示例
HTTP 方法:POST
请求URL: https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/request
URL参数:
参数 | 值 |
---|---|
access_token | 通过API Key和Secret Key获取的access_token |
Header如下:
参数 | 值 |
---|---|
Content-Type | application/json |
Body中放置请求参数,要求使用json格式的结构体来描述一个请求的具体内容,参数详情如下:
请求参数
参数 | 是否必选 | 类型 | 可选值范围 | 说明 |
---|---|---|---|---|
image | 和 url 二选一 | string | - | 图片数据,base64 编码后进行 urlencode,要求 base64 编码和 urlencode 后大小不超过 4M,最短边至少 15px,最长边最大 4096px,支持 jpg/jpeg/png/bmp 格式优先级:image > url,当 image 字段存在时,url 字段失效 |
url | 和 image 二选一 | string | - | 图片完整 url,url 长度不超过 1024 字节,要求 base64 编码和 urlencode 后大小不超过 4M,最短边至少 15px,最长边最大 4096px,支持 jpg/jpeg/png/bmp 格式优先级:image > url,当 image 字段存在时,url 字段失效 |
question | 是 | string | - | 提问信息,如“这张图片里有什么?”、“这张图片里有几只鸟”限制 100 个字符之内 |
output_CHN | 否 | bool | true/false | 是否以中文输出描述 description 和拼接语句 description_to_llm ,可选值包括:- true:以中文输出- false:不以中文输出,默认为 false |
返回参数
字段 | 类型 | 说明 |
---|---|---|
log_id | uint64 | 唯一的log id,用于问题定位 |
result | object | 返回结果列表 |
+ task_id | string | 该请求生成的task_id,后续使用该task_id获取识别结果 |
返回示例
{ "log_id": 1749362025959261144, "result":{ "task_id":"1749357426042159725", }, }
我们可以根据这个请求格式编写提交请求的接口:
/** * 图像内容理解-提交请求接口 */ @PostMapping("/image-understanding/request") public ResponseEntity<String> submitImageUnderstandingRequest(@RequestBody Map<String, Object> request) { ResponseEntity<String> tokenResponse = getBaiduToken(); if (tokenResponse.getStatusCode() != HttpStatus.OK) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取token失败"); } String accessToken = tokenResponse.getBody(); String requestUrl = "https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/request"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); // 构建请求体,可能包含image或url,以及question Map<String, Object> requestBody = new HashMap<>(); requestBody.put("image", request.get("image")); // base64编码后的图片数据 requestBody.put("url", request.get("url")); // 或者是图片的URL requestBody.put("question", request.get("question")); // 提问信息 HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers); ResponseEntity<String> response = restTemplate.postForEntity(requestUrl + "?access_token=" + accessToken, entity, String.class); return response; }
这段代码用于提交图像内容理解的请求到百度AI平台。
@PostMapping("/image-understanding/request")
: POST请求的映射,指定了该方法处理的URL路径为"/image-understanding/request"。
public ResponseEntity<String> submitImageUnderstandingRequest(@RequestBody Map<String, Object> request) {
: 方法的声明,它接受一个Map<String, Object>
类型的请求体,并返回一个ResponseEntity
,其中包含一个String
类型的数据,表示处理结果。
ResponseEntity<String> tokenResponse = getBaiduToken();
: 调用之前定义的getBaiduToken()
方法,获取百度AI平台的访问令牌。
if (tokenResponse.getStatusCode() != HttpStatus.OK) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取token失败"); }
: 检查获取访问令牌的响应状态码是否为200(OK),如果不是,则返回HTTP 500(Internal Server Error)状态码,并包含一条错误消息。
String accessToken = tokenResponse.getBody();
: 从获取到的访问令牌响应中提取出访问令牌。
String requestUrl = "https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/request";
: 设置图像内容理解请求的URL。
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);
: 创建HTTP请求头对象,并设置内容类型为JSON。
Map<String, Object> requestBody = new HashMap<>();
: 创建一个用于存储请求体参数的Map对象。
requestBody.put("image", request.get("image"));
: 将请求中的图像数据放入请求体中。
requestBody.put("url", request.get("url"));
: 将请求中的图像URL放入请求体中。
requestBody.put("question", request.get("question"));
: 将请求中的提问信息放入请求体中。
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
: 创建一个HTTP实体对象,包含请求体和请求头信息。
ResponseEntity<String> response = restTemplate.postForEntity(requestUrl + "?access_token=" + accessToken, entity, String.class);
: 发送HTTP POST请求到指定的URL,包括访问令牌作为查询参数,返回一个ResponseEntity
,其中包含一个String
类型的数据,表示API的响应。
return response;
: 返回图像内容理解请求的API响应。
同样的,我们测试该接口:
我们可以看到他成功的获取到了task_id,有了task_id我们就可以用它来获取最终的结果。
请求示例
HTTP 方法:POST
请求URL:https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/get-result
URL参数:
参数 | 值 |
---|---|
access_token | 通过API Key和Secret Key获取的access_token |
Header如下:
参数 | 值 |
---|---|
Content-Type | application/json |
Body中放置请求参数,要求使用json格式的结构体来描述一个请求的具体内容,参数详情如下:
请求参数
参数 | 是否必选 | 类型 | 可选值范围 | 说明 |
---|---|---|---|---|
task_id | 是 | string | - | 调用提交请求接口时,返回的task_id |
返回参数
字段 | 类型 | 说明 |
---|---|---|
log_id | uint64 | 唯一的log id,用于问题定位 |
result | object | 返回结果列表 |
+ task_id | string | 该结果对应请求的task_id |
+ ret_code | int | 识别状态,0:处理成功;1:处理中;若发生错误,将返回其他错误码, |
+ ret_msg | string | 识别状态信息:sucess:处理成功;processing:处理中;若发生错误,将返回其他错误信息 |
+ description | string | 针对图片的一句话描述,当 output_CHN= true 时,该字段输出为中文 |
+ description_to_llm | string | 拼接一句话描述、OCR 及图像识别结果、提问信息后的语句,将该语句输入大模型后,大模型将基于图像内容与提问,给出相应答案当 output_CHN= true 时,该字段输出为中文;当 output_CHN= false 时,该字段输出为中英混合 |
+ subject_result | array | 图片内主体检测的信息 |
++ name | string | 图片主体标签 |
++ location | object | 图片内主体的检测框位置信息 |
+ classify_result | array | 图片内目标分类的信息 |
+ ocr_result | array | 当图片中存在文字时,该参数有返回 |
++ word | string | 文字识别结果字符串 |
++ rect | array | 文字识别结果位置信息 |
+++ left | uint32 | 位置的长方形左上顶点的水平坐标 |
+++ top | uint32 | 位置的长方形左上顶点的垂直坐标 |
+++ width | uint32 | 位置的长方形的宽度 |
+++ height | uint32 | 位置的长方形的高度 |
针对该接口,我们在后端中编写针对他的代码:
/** * 图像内容理解-获取结果接口 */ @PostMapping("/image-understanding/get-result") public ResponseEntity<String> getImageUnderstandingResult(@RequestBody Map<String, String> request) throws Exception { ResponseEntity<String> tokenResponse = getBaiduToken(); if (tokenResponse.getStatusCode() != HttpStatus.OK) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取token失败"); } String accessToken = tokenResponse.getBody(); String requestUrl = "https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/get-result"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map<String, String> requestBody = new HashMap<>(); requestBody.put("task_id", request.get("task_id")); HttpEntity<Map<String, String>> entity = new HttpEntity<>(requestBody, headers); ResponseEntity<String> response = restTemplate.postForEntity(requestUrl + "?access_token=" + accessToken, entity, String.class); return response; }
这段代码用于获取图像内容理解的结果。
@PostMapping("/image-understanding/get-result")
: POST请求的映射,指定了该方法处理的URL路径为"/image-understanding/get-result"。
public ResponseEntity<String> getImageUnderstandingResult(@RequestBody Map<String, String> request) throws Exception {
: 这是方法的声明,它接受一个Map<String, String>
类型的请求体,并返回一个ResponseEntity
,其中包含一个String
类型的数据,表示处理结果。在方法声明中抛出Exception
异常,表明该方法可能会抛出异常。
ResponseEntity<String> tokenResponse = getBaiduToken();
: 调用之前定义的getBaiduToken()
方法,获取百度AI平台的访问令牌。
if (tokenResponse.getStatusCode() != HttpStatus.OK) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取token失败"); }
: 检查获取访问令牌的响应状态码是否为200(OK),如果不是,则返回HTTP 500(Internal Server Error)状态码,并包含一条错误消息。
String accessToken = tokenResponse.getBody();
: 从获取到的访问令牌响应中提取出访问令牌。
String requestUrl = "https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/get-result";
: 设置获取图像内容理解结果的URL。
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);
: 创建HTTP请求头对象,并设置内容类型为JSON。
Map<String, String> requestBody = new HashMap<>();
: 创建一个用于存储请求体参数的Map对象。
requestBody.put("task_id", request.get("task_id"));
: 将请求中的任务ID放入请求体中。
HttpEntity<Map<String, String>> entity = new HttpEntity<>(requestBody, headers);
: 创建一个HTTP实体对象,包含请求体和请求头信息。
ResponseEntity<String> response = restTemplate.postForEntity(requestUrl + "?access_token=" + accessToken, entity, String.class);
: 发送HTTP POST请求到指定的URL,包括访问令牌作为查询参数,返回一个ResponseEntity
,其中包含一个String
类型的数据,表示API的响应。
return response;
: 返回获取图像内容理解结果的API响应。
我们利用上面成功拿到的task_id来进行最终结果的获取:
可以看到,我们成功的到达了图像内容理解的结果。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。