百度内容审核(Baidu Content Security)提供 ​​文本、图片、视频、音频​​ 等内容的 ​​违规检测​​ 服务,适用于 ​​UGC 内容安全、社交平台审核、社区论坛过滤​​ 等场景。本指南将详细介绍如何在 ​​Spring Boot​​ 项目中集成 ​​百度内容审核 API​​,实现 ​​文本、图片​​ 的自动审核功能。


1. 百度内容审核简介​

百度内容审核(原 ​​百度 AI 开放平台 - 内容审核​​)提供:

  • ​文本审核​​:检测涉黄、涉政、广告、暴恐、违禁等违规内容。
  • ​图片审核​​:检测图片中的文字、物体、场景是否违规。
  • ​视频审核​​:基于截图+OCR 检测视频内容。
  • ​音频审核​​:检测语音中的违规内容。

​适用场景​

  • 社区论坛、评论系统内容过滤
  • 社交 App 的图片/视频审核
  • 电商平台的商品描述审核
  • 直播/短视频平台的实时审核

2. 环境准备​

​2.1 注册百度 AI 开放平台账号​

  1. 访问 百度 AI 开放平台,注册账号。
  2. 进入 ​​控制台​​ → ​​内容审核​​,创建应用:
    • ​应用名称​​:自定义(如 springboot-content-audit
    • ​选择服务​​:勾选 ​​文本审核​​、​​图片审核​​(按需选择)
    • ​获取 API Key 和 Secret Key​​(后续需要)

​2.2 创建 Spring Boot 项目​

使用 ​​Spring Initializr​​ 创建项目,添加依赖:

  • ​Spring Web​​(用于 HTTP 请求)
  • ​Lombok​​(简化代码)

https://i.imgur.com/xyz1234.png


3. Spring Boot 集成百度内容审核​

​3.1 添加依赖​

在 pom.xml 中添加 ​​HTTP 客户端​​(如 RestTemplate 或 WebClient):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

3.2 配置百度审核 API 信息​

在 application.yml 中配置:

baidu:
  content:
    audit:
      api-key: your-api-key  # 替换为你的 API Key
      secret-key: your-secret-key  # 替换为你的 Secret Key
      text-endpoint: https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined  # 文本审核接口
      image-endpoint: https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined  # 图片审核接口

3.3 获取百度 Access Token​

百度 API 需要 ​​Access Token​​ 进行鉴权,有效期 ​​30 天​​,需缓存避免频繁请求。

​(1) 创建 BaiduTokenService 获取 Token​
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Data
@Service
public class BaiduTokenService {

    @Value("${baidu.content.audit.api-key}")
    private String apiKey;

    @Value("${baidu.content.audit.secret-key}")
    private String secretKey;

    @Value("${baidu.content.audit.text-endpoint}")
    private String textEndpoint;

    @Value("${baidu.content.audit.image-endpoint}")
    private String imageEndpoint;

    private String accessToken;  // 缓存 Token
    private long tokenExpireTime;  // Token 过期时间

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 获取 Access Token(如果过期则重新获取)
     */
    public synchronized String getAccessToken() {
        if (accessToken == null || System.currentTimeMillis() > tokenExpireTime) {
            // 请求百度获取 Token
            String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + secretKey;
            Map<String, Object> response = restTemplate.getForObject(url, Map.class);
            this.accessToken = (String) response.get("access_token");
            this.tokenExpireTime = System.currentTimeMillis() + ((Integer) response.get("expires_in") - 60) * 1000;  // 提前 60 秒过期
        }
        return accessToken;
    }
}

3.4 实现文本审核功能​

​(1) 创建 TextAuditRequest 和 TextAuditResponse
@Data
public class TextAuditRequest {
    private String text;  // 待审核文本
}

@Data
public class TextAuditResponse {
    private Integer code;  // 状态码(0 表示成功)
    private String msg;    // 消息
    private TextData data; // 审核结果

    @Data
    public static class TextData {
        private Integer conclusionType;  // 结论类型(1: 合规, 2: 不合规, 3: 疑似)
        private List<TextResult> result; // 详细结果
    }

    @Data
    public static class TextResult {
        private Integer hit;      // 是否命中(1: 命中, 0: 未命中)
        private String label;     // 违规类型(如 "porn", "politics")
        private String keyword;   // 关键词
        private String phrase;    // 违规片段
    }
}
(2) 创建 TextAuditService
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class TextAuditService {

    @Autowired
    private BaiduTokenService tokenService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${baidu.content.audit.text-endpoint}")
    private String textEndpoint;

    /**
     * 文本审核
     */
    public TextAuditResponse auditText(String text) {
        // 1. 获取 Access Token
        String accessToken = tokenService.getAccessToken();

        // 2. 构造请求 URL
        String url = textEndpoint + "?access_token=" + accessToken;

        // 3. 构造请求体
        TextAuditRequest request = new TextAuditRequest();
        request.setText(text);

        // 4. 发送 POST 请求
        return restTemplate.postForObject(url, request, TextAuditResponse.class);
    }
}

3.5 实现图片审核功能​

​(1) 创建 ImageAuditRequest 和 ImageAuditResponse
@Data
public class ImageAuditRequest {
    private String image;  // Base64 编码的图片(或图片 URL)
    private Integer scene; // 审核场景(1: 色情, 2: 暴恐, 3: 政治, 4: 广告, 5: 违禁)
}

@Data
public class ImageAuditResponse {
    private Integer code;  // 状态码(0 表示成功)
    private String msg;    // 消息
    private ImageData data; // 审核结果

    @Data
    public static class ImageData {
        private Integer conclusionType;  // 结论类型(1: 合规, 2: 不合规, 3: 疑似)
        private List<ImageResult> result; // 详细结果
    }

    @Data
    public static class ImageResult {
        private Integer hit;      // 是否命中(1: 命中, 0: 未命中)
        private String label;     // 违规类型(如 "porn", "terrorism")
        private String keyword;   // 关键词
        private String phrase;    // 违规片段
    }
}
(2) 创建 ImageAuditService
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ImageAuditService {

    @Autowired
    private BaiduTokenService tokenService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${baidu.content.audit.image-endpoint}")
    private String imageEndpoint;

    /**
     * 图片审核(Base64 方式)
     */
    public ImageAuditResponse auditImageByBase64(String base64Image) {
        // 1. 获取 Access Token
        String accessToken = tokenService.getAccessToken();

        // 2. 构造请求 URL
        String url = imageEndpoint + "?access_token=" + accessToken;

        // 3. 构造请求体
        ImageAuditRequest request = new ImageAuditRequest();
        request.setImage(base64Image);
        request.setScene(1);  // 默认检测色情

        // 4. 发送 POST 请求
        return restTemplate.postForObject(url, request, ImageAuditResponse.class);
    }

    /**
     * 图片审核(URL 方式)
     */
    public ImageAuditResponse auditImageByUrl(String imageUrl) {
        // 1. 获取 Access Token
        String accessToken = tokenService.getAccessToken();

        // 2. 构造请求 URL
        String url = imageEndpoint + "?access_token=" + accessToken;

        // 3. 构造请求体
        ImageAuditRequest request = new ImageAuditRequest();
        request.setImage(imageUrl);  // 直接传 URL
        request.setScene(1);         // 默认检测色情

        // 4. 发送 POST 请求
        return restTemplate.postForObject(url, request, ImageAuditResponse.class);
    }
}

3.6 创建 Controller 接口​

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/audit")
public class AuditController {

    @Autowired
    private TextAuditService textAuditService;

    @Autowired
    private ImageAuditService imageAuditService;

    /**
     * 文本审核
     */
    @PostMapping("/text")
    public TextAuditResponse auditText(@RequestBody String text) {
        return textAuditService.auditText(text);
    }

    /**
     * 图片审核(Base64)
     */
    @PostMapping("/image/base64")
    public ImageAuditResponse auditImageByBase64(@RequestBody String base64Image) {
        return imageAuditService.auditImageByBase64(base64Image);
    }

    /**
     * 图片审核(URL)
     */
    @PostMapping("/image/url")
    public ImageAuditResponse auditImageByUrl(@RequestBody String imageUrl) {
        return imageAuditService.auditImageByUrl(imageUrl);
    }
}

4. 测试百度内容审核​

​4.1 测试文本审核​

​请求​​:

POST http://localhost:8080/api/audit/text
Content-Type: text/plain

"这是一段包含色情关键词的文本"

响应​​:

{
  "code": 0,
  "msg": "success",
  "data": {
    "conclusionType": 2,
    "result": [
      {
        "hit": 1,
        "label": "porn",
        "keyword": "色情关键词",
        "phrase": "这是一段包含色情关键词的文本"
      }
    ]
  }
}

4.2 测试图片审核(Base64)​

​请求​​:

POST http://localhost:8080/api/audit/image/base64
Content-Type: text/plain

"base64编码的图片数据"

响应​​:

{
  "code": 0,
  "msg": "success",
  "data": {
    "conclusionType": 1,
    "result": []
  }
}

​5. 总结​

步骤 说明
​1. 注册百度 AI 开放平台​ 创建应用,获取 API Key 和 Secret Key
​2. Spring Boot 集成​ 添加依赖,配置 API 信息
​3. 获取 Access Token​ 使用 BaiduTokenService 缓存 Token
​4. 实现文本审核​ TextAuditService 调用百度文本审核 API
​5. 实现图片审核​ ImageAuditService 支持 Base64 和 URL 方式
​6. 提供 REST API​ AuditController 对外提供审核接口

Logo

全面兼容主流 AI 模型,支持本地及云端双模式

更多推荐