feat(复习):标准思维导图生成与回忆对比
- 新增 review_standard_mind_maps / review_recall_records 数据表 - BuiltinMindMapGenerator:从报告/残片/应用场景规则生成标准导图 - MindMapAiClient 接口 + RemoteAiMindMapClient 预留 - StandardMindMapService:生成/编辑/重新生成/回忆对比 - 对比算法:标题归一化 + Bigram Jaccard 模糊匹配 - ReviewController 新增 6 个端点 - MindMapTreeTool / MindMapNode / CompareResult 工具类 - 完整单元测试(10 个,全部通过) - 更新 docs/review-module-design.md
This commit is contained in:
+359
@@ -0,0 +1,359 @@
|
||||
package com.guo.learningprogresstracker.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.guo.learningprogresstracker.entity.*;
|
||||
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
|
||||
import com.guo.learningprogresstracker.exception.OperationFailedException;
|
||||
import com.guo.learningprogresstracker.mapper.*;
|
||||
import com.guo.learningprogresstracker.service.MindMapAiClient;
|
||||
import com.guo.learningprogresstracker.service.StandardMindMapService;
|
||||
import com.guo.learningprogresstracker.utils.CompareResult;
|
||||
import com.guo.learningprogresstracker.utils.MindMapNode;
|
||||
import com.guo.learningprogresstracker.utils.MindMapTreeTool;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 标准思维导图服务实现
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class StandardMindMapServiceImpl implements StandardMindMapService {
|
||||
|
||||
private final ReviewStandardMindMapMapper standardMindMapMapper;
|
||||
private final ReviewRecallRecordMapper recallRecordMapper;
|
||||
private final TasksMapper tasksMapper;
|
||||
private final StudyReportsMapper studyReportsMapper;
|
||||
private final StudyReportFragmentsMapper studyReportFragmentsMapper;
|
||||
private final TaskApplicationMapper taskApplicationMapper;
|
||||
private final StudySessionsMapper studySessionsMapper;
|
||||
|
||||
private final List<MindMapAiClient> aiClients;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private static final String GENERATOR_BUILTIN = "BUILTIN";
|
||||
private static final String GENERATOR_USER = "USER";
|
||||
private static final String MATCH_STATUS_MATCHED = "MATCHED";
|
||||
private static final String MATCH_STATUS_MISSED = "MISSED";
|
||||
|
||||
// ============ 查询与生成 ============
|
||||
|
||||
@Override
|
||||
public ReviewStandardMindMapEntity getOrGenerate(String taskNum) throws NotFindEntitiesException, OperationFailedException {
|
||||
ensureTaskExists(taskNum);
|
||||
ReviewStandardMindMapEntity existing = queryByTaskNum(taskNum);
|
||||
return existing != null ? existing : doGenerate(taskNum);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReviewStandardMindMapEntity regenerate(String taskNum) throws NotFindEntitiesException, OperationFailedException {
|
||||
ensureTaskExists(taskNum);
|
||||
return doGenerate(taskNum);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ReviewStandardMindMapEntity updateByOutline(String taskNum, String outline) throws NotFindEntitiesException {
|
||||
ensureTaskExists(taskNum);
|
||||
ReviewStandardMindMapEntity existing = queryByTaskNum(taskNum);
|
||||
if (existing == null) {
|
||||
existing = new ReviewStandardMindMapEntity();
|
||||
existing.setTaskNum(taskNum);
|
||||
}
|
||||
|
||||
// 解析大纲为树节点
|
||||
MindMapNode root = MindMapTreeTool.parseOutline(outline);
|
||||
String contentJson = MindMapTreeTool.toJson(root, objectMapper);
|
||||
|
||||
existing.setTitle(root.getTitle() != null ? root.getTitle() : "思维导图");
|
||||
existing.setContent(contentJson);
|
||||
existing.setOutline(outline);
|
||||
existing.setGenerator(GENERATOR_USER);
|
||||
existing.setGeneratorVersion(null);
|
||||
existing.setSummary("用户编辑,共 " + MindMapTreeTool.countNodes(root) + " 个节点");
|
||||
existing.setGeneratedTime(LocalDateTime.now());
|
||||
|
||||
if (existing.getId() == null) {
|
||||
standardMindMapMapper.insert(existing);
|
||||
} else {
|
||||
standardMindMapMapper.updateById(existing);
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
// ============ 回忆对比 ============
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ReviewStandardMindMapEntity recallCompare(String taskNum, String recallOutline)
|
||||
throws NotFindEntitiesException, OperationFailedException {
|
||||
ensureTaskExists(taskNum);
|
||||
|
||||
// 1. 获取标准导图(自动生成)
|
||||
ReviewStandardMindMapEntity standard = getOrGenerate(taskNum);
|
||||
|
||||
// 2. 解析标准树和用户回忆树
|
||||
MindMapNode standardRoot = MindMapTreeTool.fromJson(standard.getContent(), objectMapper);
|
||||
MindMapNode recallRoot = MindMapTreeTool.parseOutline(recallOutline);
|
||||
|
||||
// 3. 执行对比
|
||||
CompareResult result = compareTrees(standardRoot, recallRoot);
|
||||
|
||||
// 4. 序列化对比结果
|
||||
String resultJson;
|
||||
try {
|
||||
resultJson = objectMapper.writeValueAsString(result);
|
||||
} catch (Exception e) {
|
||||
throw new OperationFailedException("对比结果序列化失败");
|
||||
}
|
||||
|
||||
// 5. 保存回忆记录
|
||||
ReviewRecallRecordEntity record = new ReviewRecallRecordEntity();
|
||||
record.setTaskNum(taskNum);
|
||||
record.setStandardMapId(standard.getId());
|
||||
record.setRecallContent(recallOutline);
|
||||
record.setCompareResult(resultJson);
|
||||
record.setRecallRatio(result.getRecallRatio());
|
||||
record.setMatchedCount(result.getMatchedCount());
|
||||
record.setMissedCount(result.getMissedCount());
|
||||
record.setExtraCount(result.getExtraCount());
|
||||
recallRecordMapper.insert(record);
|
||||
|
||||
log.info("回忆对比: taskNum={}, recallRatio={}, matched={}, missed={}, extra={}",
|
||||
taskNum, result.getRecallRatio(), result.getMatchedCount(),
|
||||
result.getMissedCount(), result.getExtraCount());
|
||||
|
||||
return standard;
|
||||
}
|
||||
|
||||
// ============ 对比算法核心 ============
|
||||
|
||||
/**
|
||||
* 两颗树的节点级对比算法。
|
||||
*/
|
||||
CompareResult compareTrees(MindMapNode standardRoot, MindMapNode recallRoot) {
|
||||
CompareResult result = new CompareResult();
|
||||
|
||||
// 展平标准树
|
||||
List<MindMapNode> standardFlat = MindMapTreeTool.flatten(standardRoot);
|
||||
// 展平回忆树(排除根节点本身)
|
||||
List<MindMapNode> recallFlat = MindMapTreeTool.flatten(recallRoot).stream()
|
||||
.filter(n -> n != recallRoot)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 构建回忆节点标题 → 节点映射(标准化后)
|
||||
Map<String, MindMapNode> recallTitleMap = new LinkedHashMap<>();
|
||||
for (MindMapNode node : recallFlat) {
|
||||
recallTitleMap.merge(normalize(node.getTitle()), node, (a, b) -> a);
|
||||
}
|
||||
|
||||
// 标注标准树
|
||||
int matched = 0, missed = 0;
|
||||
for (MindMapNode node : standardFlat) {
|
||||
if (node == standardRoot) continue; // 跳过根节点
|
||||
String key = normalize(node.getTitle());
|
||||
boolean found = recallTitleMap.containsKey(key);
|
||||
if (found) {
|
||||
node.setNotes(MATCH_STATUS_MATCHED + "|" + (node.getNotes() != null ? node.getNotes() : ""));
|
||||
matched++;
|
||||
} else {
|
||||
// 尝试模糊匹配
|
||||
found = fuzzyMatch(node.getTitle(), recallTitleMap);
|
||||
if (found) {
|
||||
node.setNotes(MATCH_STATUS_MATCHED + "|" + (node.getNotes() != null ? node.getNotes() : ""));
|
||||
matched++;
|
||||
} else {
|
||||
node.setNotes(MATCH_STATUS_MISSED + "|" + (node.getNotes() != null ? node.getNotes() : ""));
|
||||
missed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 找出额外节点(用户在回忆中新增的、标准树中没有的)
|
||||
Set<String> standardNormTitles = standardFlat.stream()
|
||||
.map(n -> normalize(n.getTitle()))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
List<CompareResult.FlatNode> extraNodes = new ArrayList<>();
|
||||
for (MindMapNode node : recallFlat) {
|
||||
String key = normalize(node.getTitle());
|
||||
if (!standardNormTitles.contains(key)) {
|
||||
CompareResult.FlatNode flat = new CompareResult.FlatNode();
|
||||
flat.setTitle(node.getTitle());
|
||||
flat.setPath(node.getTitle()); // 简化路径
|
||||
extraNodes.add(flat);
|
||||
}
|
||||
}
|
||||
|
||||
int total = matched + missed;
|
||||
result.setMatchedTree(standardRoot);
|
||||
result.setExtraNodes(extraNodes);
|
||||
result.setMatchedCount(matched);
|
||||
result.setMissedCount(missed);
|
||||
result.setExtraCount(extraNodes.size());
|
||||
result.setRecallRatio(total > 0 ? (double) matched / total : 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ============ 回忆记录查询 ============
|
||||
|
||||
@Override
|
||||
public List<ReviewRecallRecordEntity> listRecallRecords(String taskNum) throws NotFindEntitiesException {
|
||||
ensureTaskExists(taskNum);
|
||||
return recallRecordMapper.selectList(
|
||||
Wrappers.<ReviewRecallRecordEntity>lambdaQuery()
|
||||
.eq(ReviewRecallRecordEntity::getTaskNum, taskNum)
|
||||
.orderByDesc(ReviewRecallRecordEntity::getCreatedTime));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReviewRecallRecordEntity getRecallRecord(Integer recordId) throws NotFindEntitiesException {
|
||||
return Optional.ofNullable(recallRecordMapper.selectById(recordId))
|
||||
.orElseThrow(() -> new NotFindEntitiesException("回忆记录[" + recordId + "]不存在"));
|
||||
}
|
||||
|
||||
// ============ 内部方法 ============
|
||||
|
||||
private ReviewStandardMindMapEntity doGenerate(String taskNum) throws OperationFailedException {
|
||||
TaskEntity task = tasksMapper.selectOne(
|
||||
Wrappers.<TaskEntity>lambdaQuery().eq(TaskEntity::getTaskNum, taskNum).last("LIMIT 1"));
|
||||
|
||||
if (task == null) {
|
||||
throw new OperationFailedException("任务[" + taskNum + "]不存在");
|
||||
}
|
||||
|
||||
// 收集学习数据
|
||||
List<String> sessionNums = studySessionsMapper.selectList(
|
||||
Wrappers.<StudySessionsEntity>lambdaQuery()
|
||||
.eq(StudySessionsEntity::getTaskNum, taskNum)
|
||||
.select(StudySessionsEntity::getSessionNum))
|
||||
.stream().map(StudySessionsEntity::getSessionNum).collect(Collectors.toList());
|
||||
|
||||
List<StudyReportsEntity> reports = sessionNums.isEmpty() ? List.of()
|
||||
: studyReportsMapper.selectList(Wrappers.<StudyReportsEntity>lambdaQuery()
|
||||
.in(StudyReportsEntity::getSessionNum, sessionNums));
|
||||
List<StudyReportFragmentsEntity> fragments = sessionNums.isEmpty() ? List.of()
|
||||
: studyReportFragmentsMapper.selectList(Wrappers.<StudyReportFragmentsEntity>lambdaQuery()
|
||||
.in(StudyReportFragmentsEntity::getSessionNum, sessionNums));
|
||||
List<TaskApplicationEntity> applications = taskApplicationMapper.selectList(
|
||||
Wrappers.<TaskApplicationEntity>lambdaQuery().eq(TaskApplicationEntity::getTaskNum, taskNum));
|
||||
|
||||
if (reports.isEmpty() && fragments.isEmpty()) {
|
||||
throw new OperationFailedException("任务[" + taskNum + "]没有学习报告或残片,无法生成思维导图");
|
||||
}
|
||||
|
||||
// 找可用的 AI 客户端
|
||||
MindMapAiClient client = aiClients.stream()
|
||||
.filter(MindMapAiClient::isAvailable)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
if (client == null) {
|
||||
throw new OperationFailedException("没有可用的思维导图生成器");
|
||||
}
|
||||
|
||||
Optional<MindMapNode> optRoot = client.generate(task, reports, fragments, applications, null);
|
||||
if (optRoot.isEmpty()) {
|
||||
throw new OperationFailedException("思维导图生成失败");
|
||||
}
|
||||
|
||||
MindMapNode root = optRoot.get();
|
||||
String contentJson = MindMapTreeTool.toJson(root, objectMapper);
|
||||
String outline = MindMapTreeTool.toFullOutline(root);
|
||||
int nodeCount = MindMapTreeTool.countNodes(root);
|
||||
int depth = MindMapTreeTool.maxDepth(root);
|
||||
|
||||
ReviewStandardMindMapEntity entity = queryByTaskNum(taskNum);
|
||||
boolean create = entity == null;
|
||||
if (create) {
|
||||
entity = new ReviewStandardMindMapEntity();
|
||||
entity.setTaskNum(taskNum);
|
||||
}
|
||||
|
||||
entity.setTitle(root.getTitle() != null ? root.getTitle() : "思维导图");
|
||||
entity.setContent(contentJson);
|
||||
entity.setOutline(outline);
|
||||
entity.setSummary("共 " + nodeCount + " 个节点,最大层级 " + depth);
|
||||
entity.setGenerator(client.generatorName());
|
||||
entity.setGeneratorVersion("1.0");
|
||||
entity.setSourceReportCount(reports.size());
|
||||
entity.setSourceFragmentCount(fragments.size());
|
||||
entity.setGeneratedTime(LocalDateTime.now());
|
||||
|
||||
if (create) {
|
||||
standardMindMapMapper.insert(entity);
|
||||
} else {
|
||||
standardMindMapMapper.updateById(entity);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
private void ensureTaskExists(String taskNum) throws NotFindEntitiesException {
|
||||
if (!StringUtils.hasText(taskNum) || !tasksMapper.exists(
|
||||
Wrappers.<TaskEntity>lambdaQuery().eq(TaskEntity::getTaskNum, taskNum))) {
|
||||
throw new NotFindEntitiesException("任务[" + taskNum + "]不存在");
|
||||
}
|
||||
}
|
||||
|
||||
private ReviewStandardMindMapEntity queryByTaskNum(String taskNum) {
|
||||
return standardMindMapMapper.selectOne(
|
||||
Wrappers.<ReviewStandardMindMapEntity>lambdaQuery()
|
||||
.eq(ReviewStandardMindMapEntity::getTaskNum, taskNum)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
// ============ 标题归一化 ============
|
||||
|
||||
/**
|
||||
* 标准化标题用于对比:去空格、去标点、转小写。
|
||||
*/
|
||||
static String normalize(String s) {
|
||||
if (s == null) return "";
|
||||
// 先移除内部对比标记前缀,再清理标点
|
||||
String result = s.replaceAll("^(?:MATCHED|MISSED)\\|", "");
|
||||
result = result.replaceAll("[\\s 、,。!?:;()\\[\\]{},.!?:;()\\-—/\\\\|]", "");
|
||||
return result.toLowerCase(Locale.ROOT).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 模糊匹配:计算字符 bigram Jaccard 相似度
|
||||
*/
|
||||
static boolean fuzzyMatch(String title, Map<String, MindMapNode> recallTitleMap) {
|
||||
if (title == null || title.isBlank()) return false;
|
||||
String norm = normalize(title);
|
||||
Set<String> bigrams = bigramSet(norm);
|
||||
if (bigrams.isEmpty()) return false;
|
||||
|
||||
for (String recallKey : recallTitleMap.keySet()) {
|
||||
Set<String> recallBigrams = bigramSet(recallKey);
|
||||
if (recallBigrams.isEmpty()) continue;
|
||||
// Jaccard
|
||||
Set<String> intersection = new HashSet<>(bigrams);
|
||||
intersection.retainAll(recallBigrams);
|
||||
Set<String> union = new HashSet<>(bigrams);
|
||||
union.addAll(recallBigrams);
|
||||
double similarity = (double) intersection.size() / union.size();
|
||||
if (similarity >= 0.6) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static Set<String> bigramSet(String s) {
|
||||
Set<String> set = new HashSet<>();
|
||||
for (int i = 0; i < s.length() - 1; i++) {
|
||||
set.add(s.substring(i, i + 2));
|
||||
}
|
||||
return set;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user