头像检测。否符合要求
This commit is contained in:
@@ -129,5 +129,6 @@ public class PasswordUtil {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -113,5 +113,6 @@ public class ServiceManager {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -91,5 +91,6 @@ public class AliyunConfig {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
169
src/main/java/com/rj/controller/FaceDetectController.java
Normal file
169
src/main/java/com/rj/controller/FaceDetectController.java
Normal file
@@ -0,0 +1,169 @@
|
||||
package com.rj.controller;
|
||||
|
||||
import com.rj.service.IFaceDetectLogService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 人脸检测控制器
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/face-detect")
|
||||
@Tag(name = "人脸检测", description = "人脸检测相关接口")
|
||||
public class FaceDetectController {
|
||||
|
||||
@Autowired
|
||||
private IFaceDetectLogService faceDetectLogService;
|
||||
|
||||
/**
|
||||
* 人脸检测接口
|
||||
*/
|
||||
@PostMapping("/detect")
|
||||
@Operation(summary = "人脸检测", description = "检测图片中的人脸信息")
|
||||
public ResponseEntity<Map<String, Object>> detectFace(
|
||||
@Parameter(description = "图片URL", required = true)
|
||||
@RequestParam String imageUrl) {
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
log.info("开始人脸检测,图片URL: {}", imageUrl);
|
||||
|
||||
// 执行人脸检测
|
||||
com.rj.entity.FaceDetectLog detectLog = faceDetectLogService.detectFaceAndSave(imageUrl);
|
||||
|
||||
result.put("success", detectLog.getSuccess());
|
||||
result.put("message", detectLog.getSuccess() ? "人脸检测成功" : "人脸检测失败");
|
||||
result.put("imageUrl", imageUrl);
|
||||
result.put("requestId", detectLog.getRequestId());
|
||||
result.put("faceCount", detectLog.getFaceCount());
|
||||
result.put("processingTimeMs", detectLog.getProcessingTimeMs());
|
||||
|
||||
if (!detectLog.getSuccess()) {
|
||||
result.put("errorMessage", detectLog.getErrorMessage());
|
||||
return ResponseEntity.badRequest().body(result);
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(result);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("人脸检测失败: {}", e.getMessage(), e);
|
||||
result.put("success", false);
|
||||
result.put("message", "人脸检测失败: " + e.getMessage());
|
||||
return ResponseEntity.internalServerError().body(result);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询人脸检测日志
|
||||
*/
|
||||
@GetMapping("/logs")
|
||||
@Operation(summary = "分页查询人脸检测日志", description = "分页查询人脸检测日志列表")
|
||||
public ResponseEntity<Map<String, Object>> getLogs(
|
||||
@Parameter(description = "页码", example = "1")
|
||||
@RequestParam(defaultValue = "1") Integer current,
|
||||
@Parameter(description = "每页大小", example = "10")
|
||||
@RequestParam(defaultValue = "10") Integer size,
|
||||
@Parameter(description = "是否成功")
|
||||
@RequestParam(required = false) Boolean success,
|
||||
@Parameter(description = "开始时间")
|
||||
@RequestParam(required = false) String startTime,
|
||||
@Parameter(description = "结束时间")
|
||||
@RequestParam(required = false) String endTime) {
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.rj.entity.FaceDetectLog> page =
|
||||
faceDetectLogService.getPageList(current, size, success, startTime, endTime);
|
||||
|
||||
result.put("success", true);
|
||||
result.put("message", "查询成功");
|
||||
result.put("data", page.getRecords());
|
||||
result.put("total", page.getTotal());
|
||||
result.put("current", page.getCurrent());
|
||||
result.put("size", page.getSize());
|
||||
result.put("pages", page.getPages());
|
||||
|
||||
return ResponseEntity.ok(result);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("查询人脸检测日志失败: {}", e.getMessage(), e);
|
||||
result.put("success", false);
|
||||
result.put("message", "查询失败: " + e.getMessage());
|
||||
return ResponseEntity.internalServerError().body(result);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID查询人脸检测日志详情
|
||||
*/
|
||||
@GetMapping("/logs/{id}")
|
||||
@Operation(summary = "查询日志详情", description = "根据ID查询人脸检测日志详情")
|
||||
public ResponseEntity<Map<String, Object>> getLogById(
|
||||
@Parameter(description = "日志ID", required = true)
|
||||
@PathVariable Long id) {
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
log.info("查询人脸检测日志详情,ID: {}", id);
|
||||
|
||||
com.rj.entity.FaceDetectLog log = faceDetectLogService.getById(id);
|
||||
|
||||
if (log != null) {
|
||||
result.put("success", true);
|
||||
result.put("message", "查询成功");
|
||||
result.put("data", log);
|
||||
} else {
|
||||
result.put("success", false);
|
||||
result.put("message", "日志不存在");
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(result);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("查询日志详情失败: {}", e.getMessage(), e);
|
||||
result.put("success", false);
|
||||
result.put("message", "查询失败: " + e.getMessage());
|
||||
return ResponseEntity.internalServerError().body(result);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询人脸检测统计信息
|
||||
*/
|
||||
@GetMapping("/statistics")
|
||||
@Operation(summary = "查询统计信息", description = "查询人脸检测统计信息")
|
||||
public ResponseEntity<Map<String, Object>> getStatistics(
|
||||
@Parameter(description = "开始时间")
|
||||
@RequestParam(required = false) String startTime,
|
||||
@Parameter(description = "结束时间")
|
||||
@RequestParam(required = false) String endTime) {
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
Map<String, Object> statistics = faceDetectLogService.getStatistics(startTime, endTime);
|
||||
|
||||
result.put("success", true);
|
||||
result.put("message", "查询成功");
|
||||
result.put("data", statistics);
|
||||
|
||||
return ResponseEntity.ok(result);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("查询统计信息失败: {}", e.getMessage(), e);
|
||||
result.put("success", false);
|
||||
result.put("message", "查询失败: " + e.getMessage());
|
||||
return ResponseEntity.internalServerError().body(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -212,5 +212,6 @@ public class AuthController {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -351,5 +351,6 @@ public class MenuController {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -321,5 +321,6 @@ public class RoleController {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -327,5 +327,6 @@ public class UserRoleController {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -94,5 +94,6 @@ public class DifyWorkflowResponseDto {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
108
src/main/java/com/rj/entity/FaceDetectLog.java
Normal file
108
src/main/java/com/rj/entity/FaceDetectLog.java
Normal file
@@ -0,0 +1,108 @@
|
||||
package com.rj.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 人脸检测日志实体
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Accessors(chain = true)
|
||||
@TableName("face_detect_log")
|
||||
public class FaceDetectLog implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 请求ID
|
||||
*/
|
||||
@TableField("request_id")
|
||||
private String requestId;
|
||||
|
||||
/**
|
||||
* 使用的模型
|
||||
*/
|
||||
@TableField("model")
|
||||
private String model;
|
||||
|
||||
/**
|
||||
* 图片URL
|
||||
*/
|
||||
@TableField("image_url")
|
||||
private String imageUrl;
|
||||
|
||||
/**
|
||||
* 请求时间
|
||||
*/
|
||||
@TableField("request_time")
|
||||
private LocalDateTime requestTime;
|
||||
|
||||
/**
|
||||
* 响应时间
|
||||
*/
|
||||
@TableField("response_time")
|
||||
private LocalDateTime responseTime;
|
||||
|
||||
/**
|
||||
* HTTP状态码
|
||||
*/
|
||||
@TableField("status_code")
|
||||
private Integer statusCode;
|
||||
|
||||
/**
|
||||
* 是否成功
|
||||
*/
|
||||
@TableField("success")
|
||||
private Boolean success;
|
||||
|
||||
/**
|
||||
* 检测到的人脸数量
|
||||
*/
|
||||
@TableField("face_count")
|
||||
private Integer faceCount;
|
||||
|
||||
/**
|
||||
* 完整响应数据
|
||||
*/
|
||||
@TableField("response_data")
|
||||
private String responseData;
|
||||
|
||||
/**
|
||||
* 错误信息
|
||||
*/
|
||||
@TableField("error_message")
|
||||
private String errorMessage;
|
||||
|
||||
/**
|
||||
* 处理时间(毫秒)
|
||||
*/
|
||||
@TableField("processing_time_ms")
|
||||
private Long processingTimeMs;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@TableField("created_at")
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
@TableField("updated_at")
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -37,5 +37,6 @@ public interface CustomerProfileAnalysisMapper extends BaseMapper<CustomerProfil
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
12
src/main/java/com/rj/mapper/FaceDetectLogMapper.java
Normal file
12
src/main/java/com/rj/mapper/FaceDetectLogMapper.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.rj.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.rj.entity.FaceDetectLog;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 人脸检测日志Mapper
|
||||
*/
|
||||
@Mapper
|
||||
public interface FaceDetectLogMapper extends BaseMapper<FaceDetectLog> {
|
||||
}
|
||||
@@ -78,5 +78,6 @@ public class LoginResponse {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -97,5 +97,6 @@ public class AudioStatisticsScheduler {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
45
src/main/java/com/rj/service/IFaceDetectLogService.java
Normal file
45
src/main/java/com/rj/service/IFaceDetectLogService.java
Normal file
@@ -0,0 +1,45 @@
|
||||
package com.rj.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.rj.entity.FaceDetectLog;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 人脸检测日志服务接口
|
||||
*/
|
||||
public interface IFaceDetectLogService extends IService<FaceDetectLog> {
|
||||
|
||||
/**
|
||||
* 保存人脸检测日志
|
||||
* @param faceDetectLog 日志对象
|
||||
* @return 是否保存成功
|
||||
*/
|
||||
boolean saveFaceDetectLog(FaceDetectLog faceDetectLog);
|
||||
|
||||
/**
|
||||
* 执行人脸检测并保存日志
|
||||
* @param imageUrl 图片URL
|
||||
* @return 人脸检测日志对象
|
||||
*/
|
||||
FaceDetectLog detectFaceAndSave(String imageUrl);
|
||||
|
||||
/**
|
||||
* 分页查询人脸检测日志
|
||||
* @param current 当前页
|
||||
* @param size 每页大小
|
||||
* @param success 成功状态筛选
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @return 分页结果
|
||||
*/
|
||||
com.baomidou.mybatisplus.extension.plugins.pagination.Page<FaceDetectLog> getPageList(
|
||||
Integer current, Integer size, Boolean success, String startTime, String endTime);
|
||||
|
||||
/**
|
||||
* 获取统计信息
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @return 统计信息
|
||||
*/
|
||||
Map<String, Object> getStatistics(String startTime, String endTime);
|
||||
}
|
||||
@@ -58,5 +58,6 @@ public interface ICustomerProfileAnalysisService extends IService<CustomerProfil
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -93,5 +93,6 @@ public class CustomerProfileAnalysisServiceImpl extends ServiceImpl<CustomerProf
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
338
src/main/java/com/rj/service/impl/FaceDetectLogServiceImpl.java
Normal file
338
src/main/java/com/rj/service/impl/FaceDetectLogServiceImpl.java
Normal file
@@ -0,0 +1,338 @@
|
||||
package com.rj.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.rj.entity.FaceDetectLog;
|
||||
import com.rj.mapper.FaceDetectLogMapper;
|
||||
import com.rj.service.IFaceDetectLogService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.HttpServerErrorException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 人脸检测日志服务实现
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class FaceDetectLogServiceImpl extends ServiceImpl<FaceDetectLogMapper, FaceDetectLog> implements IFaceDetectLogService {
|
||||
|
||||
private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2video/face-detect";
|
||||
|
||||
@Value("${dashscope.api.key:}")
|
||||
private String apiKey;
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public FaceDetectLogServiceImpl() {
|
||||
this.restTemplate = new RestTemplate();
|
||||
this.objectMapper = new ObjectMapper();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean saveFaceDetectLog(FaceDetectLog faceDetectLog) {
|
||||
try {
|
||||
return save(faceDetectLog);
|
||||
} catch (Exception e) {
|
||||
log.error("保存人脸检测日志失败: {}", e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行人脸检测并保存日志
|
||||
*/
|
||||
public FaceDetectLog detectFaceAndSave(String imageUrl) {
|
||||
if (apiKey == null || apiKey.trim().isEmpty()) {
|
||||
log.error("DASHSCOPE_API_KEY未配置");
|
||||
return createErrorLog(imageUrl, "DASHSCOPE_API_KEY未配置");
|
||||
}
|
||||
|
||||
// 创建日志记录
|
||||
FaceDetectLog faceDetectLog = new FaceDetectLog();
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
LocalDateTime requestTime = LocalDateTime.now();
|
||||
|
||||
faceDetectLog.setRequestId(requestId);
|
||||
faceDetectLog.setModel("liveportrait-detect");
|
||||
faceDetectLog.setImageUrl(imageUrl);
|
||||
faceDetectLog.setRequestTime(requestTime);
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
try {
|
||||
// 创建请求体
|
||||
Map<String, Object> requestBody = new HashMap<>();
|
||||
requestBody.put("model", "liveportrait-detect");
|
||||
|
||||
Map<String, String> input = new HashMap<>();
|
||||
input.put("image_url", imageUrl);
|
||||
requestBody.put("input", input);
|
||||
|
||||
// 设置请求头
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.setBearerAuth(apiKey);
|
||||
|
||||
// 创建请求实体
|
||||
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
|
||||
|
||||
// 发送请求
|
||||
log.info("发送人脸检测请求,请求ID: {}, 图片URL: {}", requestId, imageUrl);
|
||||
|
||||
ResponseEntity<String> response = restTemplate.exchange(
|
||||
API_URL,
|
||||
HttpMethod.POST,
|
||||
requestEntity,
|
||||
String.class
|
||||
);
|
||||
|
||||
// 计算处理时间
|
||||
long endTime = System.currentTimeMillis();
|
||||
long processingTime = endTime - startTime;
|
||||
|
||||
// 更新日志记录
|
||||
faceDetectLog.setResponseTime(LocalDateTime.now());
|
||||
faceDetectLog.setStatusCode(response.getStatusCode().value());
|
||||
faceDetectLog.setProcessingTimeMs(processingTime);
|
||||
faceDetectLog.setResponseData(response.getBody());
|
||||
|
||||
// 处理响应
|
||||
log.info("人脸检测响应,状态码: {}, 处理时间: {}ms", response.getStatusCode(), processingTime);
|
||||
|
||||
// 解析JSON响应
|
||||
if (response.getStatusCode() == HttpStatus.OK) {
|
||||
JsonNode jsonResponse = objectMapper.readTree(response.getBody());
|
||||
|
||||
// 根据pass字段判断是否成功
|
||||
boolean isSuccess = false;
|
||||
if (jsonResponse.has("output") && jsonResponse.get("output").has("pass")) {
|
||||
isSuccess = jsonResponse.get("output").get("pass").asBoolean();
|
||||
faceDetectLog.setSuccess(isSuccess);
|
||||
|
||||
log.info("人脸检测结果 - pass: {}", isSuccess);
|
||||
} else {
|
||||
// 如果没有pass字段,则根据HTTP状态码判断
|
||||
isSuccess = response.getStatusCode().is2xxSuccessful();
|
||||
faceDetectLog.setSuccess(isSuccess);
|
||||
}
|
||||
|
||||
// 检查是否有检测到人脸
|
||||
int faceCount = 0;
|
||||
if (jsonResponse.has("output") && jsonResponse.get("output").has("faces")) {
|
||||
JsonNode faces = jsonResponse.get("output").get("faces");
|
||||
faceCount = faces.size();
|
||||
faceDetectLog.setFaceCount(faceCount);
|
||||
|
||||
log.info("检测到人脸数量: {}", faceCount);
|
||||
for (int i = 0; i < faces.size(); i++) {
|
||||
JsonNode face = faces.get(i);
|
||||
log.debug("人脸 {}: {}", i + 1, face.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// 记录请求ID
|
||||
if (jsonResponse.has("request_id")) {
|
||||
String apiRequestId = jsonResponse.get("request_id").asText();
|
||||
log.info("API请求ID: {}", apiRequestId);
|
||||
}
|
||||
|
||||
// 记录使用情况
|
||||
if (jsonResponse.has("usage")) {
|
||||
JsonNode usage = jsonResponse.get("usage");
|
||||
if (usage.has("image_count")) {
|
||||
int imageCount = usage.get("image_count").asInt();
|
||||
log.info("处理的图片数量: {}", imageCount);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// HTTP状态码不是200,直接标记为失败
|
||||
faceDetectLog.setSuccess(false);
|
||||
}
|
||||
|
||||
// 保存到数据库
|
||||
boolean saved = saveFaceDetectLog(faceDetectLog);
|
||||
if (saved) {
|
||||
log.info("人脸检测日志已保存,请求ID: {}", requestId);
|
||||
} else {
|
||||
log.error("保存人脸检测日志失败,请求ID: {}", requestId);
|
||||
}
|
||||
|
||||
return faceDetectLog;
|
||||
|
||||
} catch (HttpClientErrorException e) {
|
||||
return handleError(faceDetectLog, e, "客户端错误 (4xx): " + e.getStatusCode(), startTime);
|
||||
} catch (HttpServerErrorException e) {
|
||||
return handleError(faceDetectLog, e, "服务器错误 (5xx): " + e.getStatusCode(), startTime);
|
||||
} catch (Exception e) {
|
||||
return handleError(faceDetectLog, e, "人脸检测请求失败: " + e.getMessage(), startTime);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理错误并保存到数据库
|
||||
*/
|
||||
private FaceDetectLog handleError(FaceDetectLog faceDetectLog, Exception e, String errorMessage, long startTime) {
|
||||
long endTime = System.currentTimeMillis();
|
||||
long processingTime = endTime - startTime;
|
||||
|
||||
faceDetectLog.setResponseTime(LocalDateTime.now());
|
||||
faceDetectLog.setSuccess(false);
|
||||
faceDetectLog.setProcessingTimeMs(processingTime);
|
||||
faceDetectLog.setErrorMessage(errorMessage);
|
||||
|
||||
if (e instanceof HttpClientErrorException) {
|
||||
faceDetectLog.setStatusCode(((HttpClientErrorException) e).getStatusCode().value());
|
||||
faceDetectLog.setResponseData(((HttpClientErrorException) e).getResponseBodyAsString());
|
||||
} else if (e instanceof HttpServerErrorException) {
|
||||
faceDetectLog.setStatusCode(((HttpServerErrorException) e).getStatusCode().value());
|
||||
faceDetectLog.setResponseData(((HttpServerErrorException) e).getResponseBodyAsString());
|
||||
}
|
||||
|
||||
log.error("人脸检测失败: {}", errorMessage);
|
||||
log.error("错误详情: {}", e.getMessage());
|
||||
|
||||
// 保存错误日志到数据库
|
||||
try {
|
||||
saveFaceDetectLog(faceDetectLog);
|
||||
log.info("错误日志已保存,请求ID: {}", faceDetectLog.getRequestId());
|
||||
} catch (Exception saveException) {
|
||||
log.error("保存错误日志失败: {}", saveException.getMessage());
|
||||
}
|
||||
|
||||
return faceDetectLog;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建错误日志
|
||||
*/
|
||||
private FaceDetectLog createErrorLog(String imageUrl, String errorMessage) {
|
||||
FaceDetectLog faceDetectLog = new FaceDetectLog();
|
||||
faceDetectLog.setRequestId(UUID.randomUUID().toString());
|
||||
faceDetectLog.setModel("liveportrait-detect");
|
||||
faceDetectLog.setImageUrl(imageUrl);
|
||||
faceDetectLog.setRequestTime(LocalDateTime.now());
|
||||
faceDetectLog.setResponseTime(LocalDateTime.now());
|
||||
faceDetectLog.setSuccess(false);
|
||||
faceDetectLog.setErrorMessage(errorMessage);
|
||||
faceDetectLog.setFaceCount(0);
|
||||
|
||||
try {
|
||||
saveFaceDetectLog(faceDetectLog);
|
||||
} catch (Exception e) {
|
||||
log.error("保存错误日志失败: {}", e.getMessage());
|
||||
}
|
||||
|
||||
return faceDetectLog;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询人脸检测日志
|
||||
*/
|
||||
@Override
|
||||
public com.baomidou.mybatisplus.extension.plugins.pagination.Page<FaceDetectLog> getPageList(
|
||||
Integer current, Integer size, Boolean success, String startTime, String endTime) {
|
||||
|
||||
com.baomidou.mybatisplus.extension.plugins.pagination.Page<FaceDetectLog> page =
|
||||
new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size);
|
||||
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<FaceDetectLog> queryWrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
|
||||
// 添加查询条件
|
||||
if (success != null) {
|
||||
queryWrapper.eq(FaceDetectLog::getSuccess, success);
|
||||
}
|
||||
if (startTime != null && !startTime.trim().isEmpty()) {
|
||||
queryWrapper.ge(FaceDetectLog::getRequestTime, startTime);
|
||||
}
|
||||
if (endTime != null && !endTime.trim().isEmpty()) {
|
||||
queryWrapper.le(FaceDetectLog::getRequestTime, endTime);
|
||||
}
|
||||
|
||||
// 按请求时间倒序排列
|
||||
queryWrapper.orderByDesc(FaceDetectLog::getRequestTime);
|
||||
|
||||
return page(page, queryWrapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取统计信息
|
||||
*/
|
||||
@Override
|
||||
public Map<String, Object> getStatistics(String startTime, String endTime) {
|
||||
Map<String, Object> statistics = new HashMap<>();
|
||||
|
||||
// 构建查询条件
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<FaceDetectLog> queryWrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
|
||||
// 时间范围筛选
|
||||
if (startTime != null && !startTime.trim().isEmpty()) {
|
||||
queryWrapper.ge(FaceDetectLog::getRequestTime, startTime);
|
||||
}
|
||||
if (endTime != null && !endTime.trim().isEmpty()) {
|
||||
queryWrapper.le(FaceDetectLog::getRequestTime, endTime);
|
||||
}
|
||||
|
||||
// 查询总数
|
||||
long totalCount = count(queryWrapper);
|
||||
|
||||
// 查询成功数
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<FaceDetectLog> successWrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
|
||||
// 时间范围筛选
|
||||
if (startTime != null && !startTime.trim().isEmpty()) {
|
||||
successWrapper.ge(FaceDetectLog::getRequestTime, startTime);
|
||||
}
|
||||
if (endTime != null && !endTime.trim().isEmpty()) {
|
||||
successWrapper.le(FaceDetectLog::getRequestTime, endTime);
|
||||
}
|
||||
successWrapper.eq(FaceDetectLog::getSuccess, true);
|
||||
long successCount = count(successWrapper);
|
||||
|
||||
// 查询失败数
|
||||
long failureCount = totalCount - successCount;
|
||||
|
||||
// 计算成功率
|
||||
double successRate = totalCount > 0 ? (double) successCount / totalCount * 100 : 0;
|
||||
|
||||
// 查询平均处理时间
|
||||
java.util.List<FaceDetectLog> logs = list(queryWrapper);
|
||||
double avgProcessingTime = logs.stream()
|
||||
.filter(log -> log.getProcessingTimeMs() != null)
|
||||
.mapToLong(FaceDetectLog::getProcessingTimeMs)
|
||||
.average()
|
||||
.orElse(0.0);
|
||||
|
||||
// 查询总人脸数量
|
||||
int totalFaceCount = logs.stream()
|
||||
.filter(log -> log.getFaceCount() != null)
|
||||
.mapToInt(FaceDetectLog::getFaceCount)
|
||||
.sum();
|
||||
|
||||
// 构建统计结果
|
||||
statistics.put("totalCount", totalCount);
|
||||
statistics.put("successCount", successCount);
|
||||
statistics.put("failureCount", failureCount);
|
||||
statistics.put("successRate", Math.round(successRate * 100.0) / 100.0);
|
||||
statistics.put("avgProcessingTimeMs", Math.round(avgProcessingTime));
|
||||
statistics.put("totalFaceCount", totalFaceCount);
|
||||
|
||||
log.info("统计信息查询完成,总数: {}, 成功数: {}, 失败数: {}, 成功率: {}%",
|
||||
totalCount, successCount, failureCount, successRate);
|
||||
|
||||
return statistics;
|
||||
}
|
||||
}
|
||||
@@ -60,5 +60,6 @@ public interface IMenuService extends IService<Menu> {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -60,5 +60,6 @@ public interface IUserRoleService extends IService<UserRole> {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -64,5 +64,6 @@ public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IM
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -64,5 +64,6 @@ public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IR
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -64,5 +64,6 @@ public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> i
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -74,5 +74,6 @@ spring:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
|
||||
# DashScope API配置
|
||||
dashscope:
|
||||
api:
|
||||
key: ${DASHSCOPE_API_KEY}
|
||||
|
||||
langchain4j:
|
||||
open-ai:
|
||||
chat-model:
|
||||
|
||||
@@ -50,5 +50,6 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -252,3 +252,4 @@
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -12,3 +12,4 @@ AFTER `sales_name`;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
22
src/main/sql/face_detect_log.sql
Normal file
22
src/main/sql/face_detect_log.sql
Normal file
@@ -0,0 +1,22 @@
|
||||
-- 人脸检测日志表
|
||||
CREATE TABLE IF NOT EXISTS `face_detect_log` (
|
||||
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`request_id` varchar(64) NOT NULL COMMENT '请求ID',
|
||||
`model` varchar(100) NOT NULL COMMENT '使用的模型',
|
||||
`image_url` varchar(500) NOT NULL COMMENT '图片URL',
|
||||
`request_time` datetime NOT NULL COMMENT '请求时间',
|
||||
`response_time` datetime DEFAULT NULL COMMENT '响应时间',
|
||||
`status_code` int(11) DEFAULT NULL COMMENT 'HTTP状态码',
|
||||
`success` tinyint(1) DEFAULT 0 COMMENT '是否成功',
|
||||
`face_count` int(11) DEFAULT 0 COMMENT '检测到的人脸数量',
|
||||
`response_data` longtext COMMENT '完整响应数据',
|
||||
`error_message` text COMMENT '错误信息',
|
||||
`processing_time_ms` bigint(20) DEFAULT NULL COMMENT '处理时间(毫秒)',
|
||||
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_request_id` (`request_id`),
|
||||
KEY `idx_request_time` (`request_time`),
|
||||
KEY `idx_success` (`success`),
|
||||
KEY `idx_face_count` (`face_count`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='人脸检测日志表';
|
||||
97
src/test/java/com/rj/audio/FaceDetectTest.java
Normal file
97
src/test/java/com/rj/audio/FaceDetectTest.java
Normal file
@@ -0,0 +1,97 @@
|
||||
package com.rj.audio;
|
||||
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.HttpServerErrorException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.rj.entity.FaceDetectLog;
|
||||
import com.rj.service.IFaceDetectLogService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class FaceDetectTest {
|
||||
|
||||
private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2video/face-detect";
|
||||
private static final String API_KEY = System.getenv("DASHSCOPE_API_KEY");
|
||||
|
||||
@Autowired
|
||||
private IFaceDetectLogService faceDetectLogService;
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (API_KEY == null || API_KEY.trim().isEmpty()) {
|
||||
System.err.println("请设置DASHSCOPE_API_KEY环境变量");
|
||||
return;
|
||||
}
|
||||
String imageUrl = "http://101.35.52.237:19006/api/v1/download-shared-object/aHR0cDovLzEyNy4wLjAuMTo5MDA1L3NyYy1iYXNlLWF1ZGlvLXZpZGVvLyVFNSVCRSVBRSVFNCVCRiVBMSVFNSU5QiVCRSVFNyU4OSU4N18yMDI1MTAwNTEyMDIwNV81Nl80OS5qcGc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD0wRUE4RlhHQUlTN1FQSk9VQUZIOSUyRjIwMjUxMDA1JTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MTAwNVQwNDE3NDVaJlgtQW16LUV4cGlyZXM9NDMyMDAmWC1BbXotU2VjdXJpdHktVG9rZW49ZXlKaGJHY2lPaUpJVXpVeE1pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SmhZMk5sYzNOTFpYa2lPaUl3UlVFNFJsaEhRVWxUTjFGUVNrOVZRVVpJT1NJc0ltVjRjQ0k2TVRjMU9UWTNPVGN4TkN3aWNHRnlaVzUwSWpvaWJXbHVhVzloWkcxcGJpSjkuLWhSOFRobUpXUFNQdGVQM2V4TzdITmlkUHQ1RXBDeWRJMVV2cG0yQXJxczJsR0hBcnBTeEZWZEdJY1ZOUHdKNlF2QUZjbUJQOWQtQmtFampyUXpGaGcmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JnZlcnNpb25JZD1udWxsJlgtQW16LVNpZ25hdHVyZT1mN2NjODUxNWFiYzgxZDFlNDZmNjg1YzBkMzAxMzM0MjAyZjM5NmIxODMzMzY4MGM0OWE3ZGYxYmQ5ODk5ZWM4";
|
||||
try {
|
||||
// 创建请求体
|
||||
Map<String, Object> requestBody = new HashMap<>();
|
||||
requestBody.put("model", "liveportrait-detect");
|
||||
|
||||
Map<String, String> input = new HashMap<>();
|
||||
input.put("image_url",imageUrl);
|
||||
requestBody.put("input", input);
|
||||
|
||||
// 设置请求头
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.setBearerAuth(API_KEY);
|
||||
|
||||
// 创建请求实体
|
||||
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
|
||||
|
||||
// 发送请求
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
System.out.println("发送人脸检测请求到: " + API_URL);
|
||||
System.out.println("请求参数: " + new ObjectMapper().writeValueAsString(requestBody));
|
||||
|
||||
ResponseEntity<String> response = restTemplate.exchange(
|
||||
API_URL,
|
||||
HttpMethod.POST,
|
||||
requestEntity,
|
||||
String.class
|
||||
);
|
||||
|
||||
// 处理响应
|
||||
System.out.println("响应状态码: " + response.getStatusCode());
|
||||
System.out.println("响应头: " + response.getHeaders());
|
||||
System.out.println("响应体: " + response.getBody());
|
||||
|
||||
// 解析JSON响应
|
||||
if (response.getStatusCode() == HttpStatus.OK) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
JsonNode jsonResponse = mapper.readTree(response.getBody());
|
||||
System.out.println("解析后的响应: " + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonResponse));
|
||||
|
||||
// 检查是否有检测到人脸
|
||||
if (jsonResponse.has("output") && jsonResponse.get("output").has("faces")) {
|
||||
JsonNode faces = jsonResponse.get("output").get("faces");
|
||||
System.out.println("检测到人脸数量: " + faces.size());
|
||||
for (int i = 0; i < faces.size(); i++) {
|
||||
JsonNode face = faces.get(i);
|
||||
System.out.println("人脸 " + (i + 1) + ": " + face.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (HttpClientErrorException e) {
|
||||
System.err.println("客户端错误 (4xx): " + e.getStatusCode());
|
||||
System.err.println("错误响应: " + e.getResponseBodyAsString());
|
||||
e.printStackTrace();
|
||||
} catch (HttpServerErrorException e) {
|
||||
System.err.println("服务器错误 (5xx): " + e.getStatusCode());
|
||||
System.err.println("错误响应: " + e.getResponseBodyAsString());
|
||||
e.printStackTrace();
|
||||
} catch (Exception e) {
|
||||
System.err.println("人脸检测请求失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
50
src/test/java/com/rj/audio/VoiceEnrollmentSampleCodes.java
Normal file
50
src/test/java/com/rj/audio/VoiceEnrollmentSampleCodes.java
Normal file
@@ -0,0 +1,50 @@
|
||||
package com.rj.audio;
|
||||
|
||||
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
|
||||
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
|
||||
import com.alibaba.dashscope.exception.InputRequiredException;
|
||||
import com.alibaba.dashscope.exception.NoApiKeyException;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import static java.lang.System.exit;
|
||||
|
||||
public class VoiceEnrollmentSampleCodes {
|
||||
public static String apiKey = System.getenv("DASHSCOPE_API_KEY"); // 如果您没有配置环境变量,请在此处用您的API-KEY进行替换
|
||||
private static String targetModel = "cosyvoice-v2";
|
||||
// private static String targetModel = "cosyvoice-v3";
|
||||
|
||||
public static void main(String[] args)
|
||||
throws NoApiKeyException, InputRequiredException {
|
||||
// 复刻声音
|
||||
// VoiceEnrollmentService service = new VoiceEnrollmentService(apiKey);
|
||||
// Voice myVoice = service.createVoice(targetModel, prefix, fileUrl);
|
||||
// System.out.println("RequestId: " + service.getLastRequestId());
|
||||
// System.out.println("your voice id is " + myVoice.getVoiceId()); //cosyvoice-v3-mayun-224491d8b48344a5a483c8980eeb22fc cosyvoice-v2-mayun-5c4ee144ead34ded8b12970101cef484
|
||||
// 使用复刻的声音来合成文本为语音
|
||||
System.out.println("开始TTS合成,使用语音: longanran");
|
||||
SpeechSynthesisParam param = SpeechSynthesisParam.builder()
|
||||
.apiKey(apiKey)
|
||||
.model(targetModel)
|
||||
.voice("longyingling")
|
||||
.voice("longyuan_v2")
|
||||
.build();
|
||||
SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
|
||||
String testText = "您好, 您可以通过以下步骤使用通义万相进行视频生成,如果您在使用过程中遇到权限问题,可以尝试在阿里云官网搜索通义万相视频生成申请体验权限";
|
||||
System.out.println("合成文本: " + testText);
|
||||
ByteBuffer audio = synthesizer.call(testText);
|
||||
// 保存合成的语音到文件
|
||||
System.out.println("TTS RequestId: " + synthesizer.getLastRequestId());
|
||||
System.out.println("音频数据大小: " + audio.array().length + " bytes");
|
||||
File file = new File("output_longyuan_v2.mp3");
|
||||
try (FileOutputStream fos = new FileOutputStream(file)) {
|
||||
fos.write(audio.array());
|
||||
System.out.println("音频文件已保存到: " + file.getAbsolutePath());
|
||||
} catch (IOException e) {
|
||||
System.err.println("保存音频文件失败: " + e.getMessage());
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.rj.controller;
|
||||
|
||||
import com.rj.entity.FaceDetectLog;
|
||||
import com.rj.service.IFaceDetectLogService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* 人脸检测控制器集成测试
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
@Transactional
|
||||
public class FaceDetectControllerIntegrationTest {
|
||||
|
||||
|
||||
@Autowired
|
||||
private IFaceDetectLogService faceDetectLogService;
|
||||
|
||||
@Test
|
||||
public void testDetectFaceWithValidUrl() {
|
||||
// 使用测试图片URL
|
||||
String testImageUrl = "http://101.35.52.237:19006/api/v1/download-shared-object/aHR0cDovLzEyNy4wLjAuMTo5MDA1L3NyYy1iYXNlLWF1ZGlvLXZpZGVvLyVFNSVCRSVBRSVFNCVCRiVBMSVFNSU5QiVCRSVFNyU4OSU4N18yMDI1MTAwNTEyMDIwNV81Nl80OS5qcGc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD0wRUE4RlhHQUlTN1FQSk9VQUZIOSUyRjIwMjUxMDA1JTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MTAwNVQwNDE3NDVaJlgtQW16LUV4cGlyZXM9NDMyMDAmWC1BbXotU2VjdXJpdHktVG9rZW49ZXlKaGJHY2lPaUpJVXpVeE1pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SmhZMk5sYzNOTFpYa2lPaUl3UlVFNFJsaEhRVWxUTjFGUVNrOVZRVVpJT1NJc0ltVjRjQ0k2TVRjMU9UWTNPVGN4TkN3aWNHRnlaVzUwSWpvaWJXbHVhVzloWkcxcGJpSjkuLWhSOFRobUpXUFNQdGVQM2V4TzdITmlkUHQ1RXBDeWRJMVV2cG0yQXJxczJsR0hBcnBTeEZWZEdJY1ZOUHdKNlF2QUZjbUJQOWQtQmtFampyUXpGaGcmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JnZlcnNpb25JZD1udWxsJlgtQW16LVNpZ25hdHVyZT1mN2NjODUxNWFiYzgxZDFlNDZmNjg1YzBkMzAxMzM0MjAyZjM5NmIxODMzMzY4MGM0OWE3ZGYxYmQ5ODk5ZWM4";
|
||||
|
||||
try {
|
||||
// 执行人脸检测
|
||||
FaceDetectLog result = faceDetectLogService.detectFaceAndSave(testImageUrl);
|
||||
|
||||
// 验证结果
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getRequestId());
|
||||
assertEquals("liveportrait-detect", result.getModel());
|
||||
assertEquals(testImageUrl, result.getImageUrl());
|
||||
assertNotNull(result.getRequestTime());
|
||||
|
||||
System.out.println("人脸检测测试结果:");
|
||||
System.out.println("请求ID: " + result.getRequestId());
|
||||
System.out.println("成功状态: " + result.getSuccess());
|
||||
System.out.println("人脸数量: " + result.getFaceCount());
|
||||
System.out.println("处理时间: " + result.getProcessingTimeMs() + "ms");
|
||||
System.out.println("HTTP状态码: " + result.getStatusCode());
|
||||
|
||||
if (!result.getSuccess()) {
|
||||
System.out.println("错误信息: " + result.getErrorMessage());
|
||||
}
|
||||
|
||||
// 验证响应数据包含pass字段
|
||||
if (result.getResponseData() != null) {
|
||||
System.out.println("响应数据: " + result.getResponseData());
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("人脸检测测试失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetectFaceWithInvalidUrl() {
|
||||
// 使用无效的图片URL
|
||||
String invalidImageUrl = "https://invalid-url.com/nonexistent.jpg";
|
||||
|
||||
try {
|
||||
// 执行人脸检测
|
||||
FaceDetectLog result = faceDetectLogService.detectFaceAndSave(invalidImageUrl);
|
||||
|
||||
// 验证结果
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getRequestId());
|
||||
assertEquals("liveportrait-detect", result.getModel());
|
||||
assertEquals(invalidImageUrl, result.getImageUrl());
|
||||
|
||||
System.out.println("无效URL测试结果:");
|
||||
System.out.println("请求ID: " + result.getRequestId());
|
||||
System.out.println("成功状态: " + result.getSuccess());
|
||||
System.out.println("错误信息: " + result.getErrorMessage());
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("无效URL测试失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPassFieldLogic() {
|
||||
// 测试pass字段逻辑
|
||||
System.out.println("=== 测试pass字段逻辑 ===");
|
||||
|
||||
// 模拟响应数据
|
||||
String mockResponseData = "{\"output\":{\"message\":\"\",\"pass\":true},\"usage\":{\"image_count\":1},\"request_id\":\"ee4a54ca-c190-4594-990e-d9546cbbd5ed\"}";
|
||||
|
||||
try {
|
||||
// 创建测试日志
|
||||
FaceDetectLog testLog = new FaceDetectLog();
|
||||
testLog.setRequestId("test-pass-logic-" + System.currentTimeMillis());
|
||||
testLog.setModel("liveportrait-detect");
|
||||
testLog.setImageUrl("https://example.com/test.jpg");
|
||||
testLog.setRequestTime(java.time.LocalDateTime.now());
|
||||
testLog.setResponseTime(java.time.LocalDateTime.now());
|
||||
testLog.setStatusCode(200);
|
||||
testLog.setResponseData(mockResponseData);
|
||||
testLog.setProcessingTimeMs(1500L);
|
||||
|
||||
// 解析响应数据中的pass字段
|
||||
com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
com.fasterxml.jackson.databind.JsonNode jsonResponse = mapper.readTree(mockResponseData);
|
||||
|
||||
boolean isSuccess = false;
|
||||
if (jsonResponse.has("output") && jsonResponse.get("output").has("pass")) {
|
||||
isSuccess = jsonResponse.get("output").get("pass").asBoolean();
|
||||
testLog.setSuccess(isSuccess);
|
||||
|
||||
System.out.println("解析到的pass值: " + isSuccess);
|
||||
System.out.println("设置的成功状态: " + testLog.getSuccess());
|
||||
}
|
||||
|
||||
// 验证pass字段解析
|
||||
assertTrue(isSuccess, "pass字段应该为true");
|
||||
assertTrue(testLog.getSuccess(), "成功状态应该为true");
|
||||
|
||||
System.out.println("pass字段逻辑测试通过");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("pass字段逻辑测试失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSaveFaceDetectLog() {
|
||||
// 创建测试日志
|
||||
FaceDetectLog testLog = new FaceDetectLog();
|
||||
testLog.setRequestId("test-request-id-" + System.currentTimeMillis());
|
||||
testLog.setModel("liveportrait-detect");
|
||||
testLog.setImageUrl("https://example.com/test.jpg");
|
||||
testLog.setRequestTime(java.time.LocalDateTime.now());
|
||||
testLog.setResponseTime(java.time.LocalDateTime.now());
|
||||
testLog.setStatusCode(200);
|
||||
testLog.setSuccess(true);
|
||||
testLog.setFaceCount(1);
|
||||
testLog.setResponseData("{\"output\":{\"faces\":[{\"bbox\":[100,100,200,200]}]}}");
|
||||
testLog.setProcessingTimeMs(1500L);
|
||||
|
||||
// 保存日志
|
||||
boolean saved = faceDetectLogService.saveFaceDetectLog(testLog);
|
||||
|
||||
// 验证保存结果
|
||||
assertTrue(saved);
|
||||
System.out.println("日志保存测试成功,请求ID: " + testLog.getRequestId());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user