Browse Source

feat(tongue): SC-P-70 tongue.emotion.capture 情绪照片识别契约闭环 (S-cfc-506)

- /api/mind/emotion/analyze 补齐 MIME 校验:非照片(text/plain)拒绝并提示『请上传清晰舌苔照』,不触发识别服务 (TC-P-70-E)
- 模糊/低锐度(is_blur/sharpness)拒绝,提示『请上传清晰舌苔照』
- 主导情绪置信度 < 0.5 提示『识别不清晰,建议重拍』
- 隐私白名单清洗:仅保留 §4.37 契约键,剔除 rawResponse/privacy_annotation (TC-P-70-E 隐私不外露)
- 回传测评关联标识 assessmentRef(识别→关联测评闭环)
- EmotionCheckinDTO 增加 assessmentRef 采集载体字段
- EmotionRecognitionResult 移除调试用 rawResponse 字段
- analyze/analyze-url 共用 finishRecognize 收口,契约一致
zxyj-langgraph 1 hour ago
parent
commit
68ce07fcdf

+ 119 - 9
cfc-backend/src/main/java/com/etotem/cfc/controller/mind/EmotionRecognitionController.java

@@ -11,25 +11,57 @@ import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
+import java.util.Arrays;
 import java.util.Base64;
 import java.util.LinkedHashMap;
+import java.util.List;
 import java.util.Map;
 
 /**
  * 情绪识别接口 — 基于 DeepFace 的人脸情绪分析
  * 前端上传照片 → 后端转 base64 → 调用 LangGraph /api/v1/emotion/recognize
+ *
+ * <p><b>SC-P-70({@code tongue.emotion.capture})契约</b>(TC-P-70 / TC-P-70-E / TC-P-70-P):
+ * 拍照/上传 → 识别情绪标签 → 关联测评;非照片/模糊拒绝;低置信度提示重拍;隐私标注不外露。</p>
+ *
+ * <p>两条识别端点(文件上传 / URL)共用 {@link #finishRecognize} 收口,保证契约一致:
+ * ①MIME 校验拒绝非照片(不触发识别服务);②模糊/低锐度拒绝;③主导情绪置信度过低提示重拍;
+ * ④隐私白名单清洗(剔除 rawResponse / privacy_annotation 等调试/标注字段);
+ * ⑤回传测评关联标识 {@code assessmentRef}。</p>
  */
 @Slf4j
 @RestController
 @RequestMapping("/api/mind/emotion")
 public class EmotionRecognitionController {
 
+    /** 非照片 / 模糊照片统一提示(TC-P-70-E) */
+    private static final String MSG_NOT_CLEAR_PHOTO = "请上传清晰舌苔照";
+    /** 低置信度统一提示(TC-P-70-E) */
+    private static final String MSG_LOW_CONFIDENCE = "识别不清晰,建议重拍";
+
+    /** 支持的照片 MIME 类型(§4.37:JPEG/PNG) */
+    private static final List<String> SUPPORTED_IMAGE_TYPES =
+            Arrays.asList("image/jpeg", "image/jpg", "image/png");
+
+    /** 主导情绪置信度低于该阈值 → 提示重拍(DeepFace 0-1 置信度) */
+    private static final double LOW_CONFIDENCE_THRESHOLD = 0.5;
+    /** 锐度低于该值视为模糊(与 gateway 返回的 is_blur 配合) */
+    private static final double BLUR_SHARPNESS_THRESHOLD = 10.0;
+
+    /**
+     * 回传给前端的白名单结果键 —— 仅保留 §4.37 响应契约键,
+     * 剔除 rawResponse / privacy_annotation 等调试与隐私标注字段(TC-P-70-E)。
+     */
+    private static final String[] SAFE_RESULT_KEYS = {
+            "emotions", "dominant_emotion", "dominant_label_zh", "all_emotions"
+    };
+
     @Resource
     private AiGateway aiGateway;
 
     /**
      * 照片情绪识别(文件上传方式)
-     * 返回: { emotions: [{emotion, confidence}], dominant_emotion, dominant_label_zh, all_emotions }
+     * 返回: { emotions: [{emotion, confidence}], dominant_emotion, dominant_label_zh, all_emotions, assessmentRef }
      */
     @PostMapping("/analyze")
     public Result<Map<String, Object>> analyze(
@@ -41,14 +73,15 @@ public class EmotionRecognitionController {
         if (file.getSize() > 10 * 1024 * 1024) {
             return Result.error("图片过大,请上传10MB以内的图片");
         }
+        // 非照片(如 text/plain)直接拒绝,不触发识别服务(TC-P-70-E)
+        if (!isSupportedImage(file)) {
+            return Result.error(MSG_NOT_CLEAR_PHOTO);
+        }
 
         try {
             String base64 = Base64.getEncoder().encodeToString(file.getBytes());
             Map<String, Object> result = aiGateway.analyzeEmotion(base64);
-            if (result == null) {
-                return Result.error(500, "情绪识别服务暂不可用,请稍后重试");
-            }
-            return Result.success(result);
+            return finishRecognize(userId, result);
         } catch (Exception e) {
             log.error("情绪识别失败: userId={}, error={}", userId, e.getMessage());
             return Result.error("情绪识别失败: " + e.getMessage());
@@ -69,13 +102,90 @@ public class EmotionRecognitionController {
         }
         try {
             Map<String, Object> result = aiGateway.analyzeEmotionByUrl(imageUrl);
-            if (result == null) {
-                return Result.error(500, "情绪识别服务暂不可用,请稍后重试");
-            }
-            return Result.success(result);
+            return finishRecognize(userId, result);
         } catch (Exception e) {
             log.error("情绪识别失败(URL): userId={}, error={}", userId, e.getMessage());
             return Result.error("情绪识别失败: " + e.getMessage());
         }
     }
+
+    /**
+     * 识别结果统一收口:模糊拒绝 → 低置信度提示重拍 → 隐私白名单清洗 → 测评关联标识透传。
+     *
+     * <p>两条识别端点(文件 / URL)共用,保证契约一致(SC-P-70 / TC-P-70-E)。</p>
+     */
+    private Result<Map<String, Object>> finishRecognize(Long userId, Map<String, Object> result) {
+        if (result == null) {
+            return Result.error(500, "情绪识别服务暂不可用,请稍后重试");
+        }
+        // 模糊照片 / 低锐度 → 拒绝(TC-P-70-E)
+        if (isBlurry(result)) {
+            return Result.error(MSG_NOT_CLEAR_PHOTO);
+        }
+        // 主导情绪置信度过低 → 提示重拍(TC-P-70-E)
+        if (isLowConfidence(result)) {
+            return Result.error(MSG_LOW_CONFIDENCE);
+        }
+        // 隐私白名单清洗:仅保留 §4.37 契约键,剔除原始响应/隐私标注
+        Map<String, Object> sanitized = sanitize(result);
+        // 测评关联标识透传(SC-P-70 主流程「识别情绪标签 → 关联测评」)
+        sanitized.put("assessmentRef", buildAssessmentRef(userId));
+        return Result.success(sanitized);
+    }
+
+    /** 照片 MIME 类型校验(§4.37 仅支持 JPEG/PNG) */
+    private boolean isSupportedImage(MultipartFile file) {
+        String contentType = file.getContentType();
+        return contentType != null && SUPPORTED_IMAGE_TYPES.contains(contentType.toLowerCase());
+    }
+
+    /** 模糊判定:gateway 显式 is_blur=true,或锐度低于阈值 */
+    private boolean isBlurry(Map<String, Object> result) {
+        if (Boolean.TRUE.equals(result.get("is_blur"))) {
+            return true;
+        }
+        Object sharpness = result.get("sharpness");
+        if (sharpness instanceof Number) {
+            return ((Number) sharpness).doubleValue() < BLUR_SHARPNESS_THRESHOLD;
+        }
+        return false;
+    }
+
+    /** 主导情绪置信度过低判定(gateway 按置信度降序返回 emotions,取首个) */
+    private boolean isLowConfidence(Map<String, Object> result) {
+        Double top = topConfidence(result);
+        return top != null && top < LOW_CONFIDENCE_THRESHOLD;
+    }
+
+    /** 取最高置信度;无 emotions 或无 confidence 时返回 null(不误判为低置信度) */
+    @SuppressWarnings("unchecked")
+    private Double topConfidence(Map<String, Object> result) {
+        Object emotionsObj = result.get("emotions");
+        if (emotionsObj instanceof List && !((List<?>) emotionsObj).isEmpty()) {
+            Object first = ((List<?>) emotionsObj).get(0);
+            if (first instanceof Map) {
+                Object confidence = ((Map<String, Object>) first).get("confidence");
+                if (confidence instanceof Number) {
+                    return ((Number) confidence).doubleValue();
+                }
+            }
+        }
+        return null;
+    }
+
+    /** 白名单重建结果,仅保留 §4.37 契约键,剔除原始响应/隐私标注(TC-P-70-E) */
+    private Map<String, Object> sanitize(Map<String, Object> result) {
+        Map<String, Object> sanitized = new LinkedHashMap<>();
+        for (String key : SAFE_RESULT_KEYS) {
+            if (result.containsKey(key)) {
+                sanitized.put(key, result.get(key));
+            }
+        }
+        return sanitized;
+    }
+
+    /** 生成本次采集的测评关联标识(capture 事件引用,供后续「关联测评」回填闭环) */
+    private String buildAssessmentRef(Long userId) {
+        return "EMO-" + userId + "-" + System.currentTimeMillis();
+    }
 }

+ 3 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/EmotionCheckinDTO.java

@@ -22,4 +22,7 @@ public class EmotionCheckinDTO implements Serializable {
     // === 睡眠字段 (Phase 3.1, 预埋) ===
     private Float sleepHours;             // 睡眠时长
     private Integer sleepQuality;         // 睡眠质量 1-5
+
+    // === SC-P-70 舌诊/情绪采集 · 测评关联标识(tongue.emotion.capture)===
+    private String assessmentRef;         // 关联测评引用标识(照片识别后回填,供「关联测评」闭环)
 }

+ 0 - 2
cfc-backend/src/main/java/com/etotem/cfc/dto/EmotionRecognitionResult.java

@@ -12,8 +12,6 @@ public class EmotionRecognitionResult {
     private List<EmotionItem> emotions;
     /** 综合心情天气(sunny/cloudy/rainy/stormy) */
     private String moodWeather;
-    /** 原始响应(调试用) */
-    private String rawResponse;
 
     @Data
     public static class EmotionItem {