fix: 题目相似度忽略 AI 附加的图示描述与填空差异,识别时逐字转录题干,默认判重阈值改为 90%

- 相似度规范化时去掉题干后以「图示」开头的图形描述段落(首行保留),统一填空横线与空括号
- 识别提示词要求逐字转录题干、统一填空写法、图形描述只用一段「图示:」
- 新账号默认判重阈值由 99% 改为 90%(重建 User 表,已有数据原样保留)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
margrop
2026-10-19 07:35:57 +08:00
parent 8f49cdee64
commit e4844aa333
8 changed files with 112 additions and 30 deletions

View File

@@ -61,8 +61,8 @@
* **触发**:用户点击 "保存到错题本"。
* **后端处理**:
1. 数据发送至 `/api/error-items`。
2. **自动判重**:与当前用户全部错题本中的完整题干比较,不受导入时间限制。规范化全角字符、换行和连续空白后,按 `1 - 字符编辑距离 / 较长题干长度` 计算相似度。
3. **阈值设置**:在首页「设置 → 通用」中保存个人判重阈值,默认 99%,支持 1%~100%、最多两位小数。相似度**严格大于**阈值才判重;设为 100% 时不自动判重。
2. **自动判重**:与当前用户全部错题本中的完整题干比较,不受导入时间限制。规范化全角字符、换行和连续空白,去掉题干后 AI 附加的「图示…」图形描述段落(第一行始终保留),并把不同长度的填空横线、空括号视为相同后,按 `1 - 字符编辑距离 / 较长题干长度` 计算相似度。
3. **阈值设置**:在首页「设置 → 通用」中保存个人判重阈值,新账号默认 90%(2026-10-19 前创建的账号保持原值 99%,可自行修改),支持 1%~100%、最多两位小数。相似度**严格大于**阈值才判重;设为 100% 时不自动判重。
4. **重复题目**:保留原题,不新建 `ErrorItem`;在原题的举一反三记录中新增一次「做错」,保存本次题目、答案、作答文字、错因和图片,并重新评估掌握情况。页面提示本次错误已记录。
5. **新题目**:在 `ErrorItem` 表中创建记录,关联 `Subject` 和知识点标签;原图以 Base64 格式存储。没有可用题干或 OCR 文字的图片不会自动合并。
6. 图片识别后导入、人工校对保存、直接录入、框选批量导入、Openclaw 批量上传和 JSON 数据导入均使用同一判重规则。

View File

@@ -0,0 +1,27 @@
-- 新账号的判重阈值默认值由 99 改为 90。SQLite 不能直接修改列默认值,需按 Prisma 标准方式重建 User 表;
-- 已有账号的阈值原样复制,不做修改(部署脚本会校验所有已有行不变)。
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_User" (
"id" TEXT NOT NULL PRIMARY KEY,
"email" TEXT NOT NULL,
"password" TEXT NOT NULL,
"name" TEXT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"educationStage" TEXT,
"enrollmentYear" INTEGER,
"role" TEXT NOT NULL DEFAULT 'user',
"isActive" BOOLEAN NOT NULL DEFAULT true,
"confirmBeforeImport" BOOLEAN NOT NULL DEFAULT false,
"questionDuplicateThreshold" REAL NOT NULL DEFAULT 90,
"enableGeogebra" BOOLEAN NOT NULL DEFAULT false
);
INSERT INTO "new_User" ("confirmBeforeImport", "createdAt", "educationStage", "email", "enableGeogebra", "enrollmentYear", "id", "isActive", "name", "password", "questionDuplicateThreshold", "role", "updatedAt") SELECT "confirmBeforeImport", "createdAt", "educationStage", "email", "enableGeogebra", "enrollmentYear", "id", "isActive", "name", "password", "questionDuplicateThreshold", "role", "updatedAt" FROM "User";
DROP TABLE "User";
ALTER TABLE "new_User" RENAME TO "User";
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;

View File

@@ -26,7 +26,7 @@ model User {
isActive Boolean @default(true) // 用户是否启用
confirmBeforeImport Boolean @default(false) // 导入题目前是否进入人工校对页
questionDuplicateThreshold Float @default(99) // 百分比,相似度严格大于此值时判重
questionDuplicateThreshold Float @default(90) // 百分比,相似度严格大于此值时判重
enableGeogebra Boolean @default(false) // 是否显示 GeoGebra 动态演示
errorItems ErrorItem[]

View File

@@ -113,12 +113,12 @@ describe('题目导入自动判重(真实 SQLite)', () => {
expect(await database.errorItem.count()).toBe(1);
});
it('默认阈值为 99%,保存个人阈值后立即用于后续导入且不影响其他用户', async () => {
expect((await (await GET_PROFILE()).json()).questionDuplicateThreshold).toBe(99);
it('默认阈值为 90%,保存个人阈值后立即用于后续导入且不影响其他用户', async () => {
expect((await (await GET_PROFILE()).json()).questionDuplicateThreshold).toBe(90);
const response = await UPDATE_PROFILE(request({ questionDuplicateThreshold: 95 }, '/api/user'));
expect(response.status).toBe(200);
expect((await (await GET_PROFILE()).json()).questionDuplicateThreshold).toBe(95);
expect((await database.user.findUniqueOrThrow({ where: { id: 'user-2' } })).questionDuplicateThreshold).toBe(99);
expect((await database.user.findUniqueOrThrow({ where: { id: 'user-2' } })).questionDuplicateThreshold).toBe(90);
await existing({ questionText: '甲'.repeat(100) });
expect((await save({ questionText: '甲'.repeat(96) + '乙'.repeat(4) })).status).toBe(200);
});
@@ -128,7 +128,7 @@ describe('题目导入自动判重(真实 SQLite)', () => {
const response = await UPDATE_PROFILE(request({ questionDuplicateThreshold: value }, '/api/user'));
expect(response.status).toBe(400);
}
expect((await database.user.findUniqueOrThrow({ where: { id: 'user-1' } })).questionDuplicateThreshold).toBe(99);
expect((await database.user.findUniqueOrThrow({ where: { id: 'user-1' } })).questionDuplicateThreshold).toBe(90);
});
it('阈值可以保存为小数,100% 时同题也不自动合并', async () => {
@@ -148,19 +148,19 @@ describe('题目导入自动判重(真实 SQLite)', () => {
expect((await response.json()).records[0]).toMatchObject({ result: 'wrong', source: 'duplicate_import', wrongAnswerText: '新作答', mistakeAnalysis: '新错因', originalImageUrl: 'new-image' });
});
it('恰好 99% 时仍创建新题', async () => {
it('恰好 90% 时仍创建新题', async () => {
await existing({ questionText: '甲'.repeat(100) });
const response = await save({ questionText: '甲'.repeat(99) + '乙' });
const response = await save({ questionText: '甲'.repeat(90) + '乙'.repeat(10) });
expect(response.status).toBe(201);
expect(await database.errorItem.count()).toBe(2);
expect(await database.practiceRecord.count()).toBe(0);
});
it('大于 99% 时返回原题及实际分数', async () => {
await existing({ questionText: '甲'.repeat(101) });
const response = await save({ questionText: '甲'.repeat(100) + '乙' });
it('大于 90% 时返回原题及实际分数', async () => {
await existing({ questionText: '甲'.repeat(100) });
const response = await save({ questionText: '甲'.repeat(91) + '乙'.repeat(9) });
expect(response.status).toBe(200);
expect((await response.json()).similarity).toBeCloseTo(100 / 101);
expect((await response.json()).similarity).toBeCloseTo(0.91);
expect(await database.errorItem.count()).toBe(1);
});
@@ -278,20 +278,20 @@ describe('两题相似度比较', () => {
const response = await COMPARE_QUESTIONS(request({ ids: ['two', 'one'] }));
const data = await response.json();
expect(response.status).toBe(200);
expect(data).toMatchObject({ similarity: 0.5, threshold: 99, duplicate: false });
expect(data).toMatchObject({ similarity: 0.5, threshold: 90, duplicate: false });
expect(data.items.map((item: { id: string }) => item.id)).toEqual(['two', 'one']);
expect(await database.practiceRecord.count()).toBe(0);
});
it('调整阈值后比较结论与实际导入判重一致', async () => {
await existing({ id: 'one', questionText: '甲'.repeat(100) });
await existing({ id: 'two', questionText: '甲'.repeat(96) + '乙'.repeat(4) });
await existing({ id: 'two', questionText: '甲'.repeat(92) + '乙'.repeat(8) });
const compare = () => COMPARE_QUESTIONS(request({ ids: ['one', 'two'] }));
expect((await (await compare()).json()).duplicate).toBe(false);
expect(await (await compare()).json()).toMatchObject({ similarity: 0.92, threshold: 90, duplicate: true });
await UPDATE_PROFILE(request({ questionDuplicateThreshold: 95 }, '/api/user'));
expect(await (await compare()).json()).toMatchObject({ similarity: 0.96, threshold: 95, duplicate: true });
expect(await (await compare()).json()).toMatchObject({ similarity: 0.92, threshold: 95, duplicate: false });
await database.errorItem.delete({ where: { id: 'two' } });
expect((await save({ questionText: '甲'.repeat(96) + '乙'.repeat(4) })).status).toBe(200);
expect((await save({ questionText: '甲'.repeat(92) + '乙'.repeat(8) })).status).toBe(201);
});
it('拒绝选择同一题、选择数量错误和不存在或属于他人的题目', async () => {

View File

@@ -13,11 +13,34 @@ describe('完整题干相似度', () => {
}
});
it('默认阈值为 90%,严格区分等于和大于', () => {
expect(duplicateQuestionSimilarity('甲'.repeat(100), '甲'.repeat(90) + '乙'.repeat(10))).toBeNull();
expect(duplicateQuestionSimilarity('甲'.repeat(100), '甲'.repeat(91) + '乙'.repeat(9))).toBeCloseTo(0.91);
});
it('严格区分等于 99% 和大于 99%', () => {
expect(duplicateQuestionSimilarity('甲'.repeat(100), '甲'.repeat(99) + '乙')).toBeNull();
expect(duplicateQuestionSimilarity('甲'.repeat(101), '甲'.repeat(100) + '乙')).toBeCloseTo(100 / 101);
expect(duplicateQuestionSimilarity('甲'.repeat(200), '甲'.repeat(198) + '乙乙')).toBeNull();
expect(duplicateQuestionSimilarity('甲'.repeat(201), '甲'.repeat(199) + '乙乙')).toBeCloseTo(199 / 201);
expect(duplicateQuestionSimilarity('甲'.repeat(100), '甲'.repeat(99) + '乙', 99)).toBeNull();
expect(duplicateQuestionSimilarity('甲'.repeat(101), '甲'.repeat(100) + '乙', 99)).toBeCloseTo(100 / 101);
expect(duplicateQuestionSimilarity('甲'.repeat(200), '甲'.repeat(198) + '乙乙', 99)).toBeNull();
expect(duplicateQuestionSimilarity('甲'.repeat(201), '甲'.repeat(199) + '乙乙', 99)).toBeCloseTo(199 / 201);
});
it('忽略 AI 附加的图示描述段落,但保留以「图示」开头的题干本身', () => {
const stem = '(5分)现在两人从相距 $100$ 米的两地同时出发,如图所示,同向而行,大宽追上艾迪两次需要 ____ 分钟。';
const left = stem + '\n\n图示:环形跑道上,大宽位于左上方,艾迪位于右上方,两人之间的上方弧段长 $100$ 米。';
const right = stem + '\n\n图示信息:大宽和艾迪沿环形跑道同向跑动,大宽在后方。';
expect(calculateQuestionSimilarity(left, right)).toBe(1);
expect(calculateQuestionSimilarity(stem + '\n【图示说明】一个六边形', stem)).toBe(1);
// 图示段落之后的正文仍参与比较
expect(calculateQuestionSimilarity(stem + '\n\n图示:甲\n\n(1) 求速度', stem + '\n\n(1) 求速度')).toBe(1);
expect(calculateQuestionSimilarity(stem + '\n\n图示:甲\n\n(1) 求速度', stem + '\n\n(1) 求时间')).toBeLessThan(1);
expect(normalizeQuestionText('图示为一个 5 行 6 列的方格图,求长方形个数。')).toContain('图示为一个 5 行 6 列的方格图');
});
it('不同长度的填空横线和空括号视为相同', () => {
expect(calculateQuestionSimilarity('需要 ______ 分钟', '需要 ____ 分钟')).toBe(1);
expect(calculateQuestionSimilarity('需要 $\\underline{\\quad}$ 分钟', '需要 $__$ 分钟')).toBe(1);
expect(calculateQuestionSimilarity('答案是(  )', '答案是( )')).toBe(1);
});
it('支持自定义阈值及小数阈值,相等时不判重,100% 时不自动判重', () => {
@@ -48,7 +71,7 @@ describe('完整题干相似度', () => {
});
it('按 Unicode 字符计算距离,避免表情等字符的代理对影响阈值', () => {
expect(duplicateQuestionSimilarity('😀'.repeat(100), '😀'.repeat(99) + '😁')).toBeNull();
expect(duplicateQuestionSimilarity('😀'.repeat(100), '😀'.repeat(99) + '😁', 99)).toBeNull();
});
it('带状算法与完整编辑距离在不同长度和差异位置上保持一致', () => {
@@ -69,10 +92,11 @@ describe('完整题干相似度', () => {
for (const changed of [text.slice(0, position) + text.slice(position + 1), text.slice(0, position) + '新字' + text.slice(position + 1)]) {
const edits = distance(text, changed);
const maximum = Math.max(text.length, changed.length);
const expected = edits * 100 < maximum ? 1 - edits / maximum : null;
// 默认阈值 90%:相似度严格大于 90% 才返回分数
const expected = edits * 10 < maximum ? 1 - edits / maximum : null;
expect(duplicateQuestionSimilarity(text, changed)).toBe(expected);
expect(calculateQuestionSimilarity(text, changed)).toBe(1 - edits / maximum);
for (const threshold of [1, 50, 95, 99, 99.5, 99.99, 100]) {
for (const threshold of [1, 50, 90, 95, 99, 99.5, 99.99, 100]) {
const shouldMatch = edits * 10000 < maximum * (10000 - Math.round(threshold * 100));
expect(duplicateQuestionSimilarity(text, changed, threshold)).toBe(shouldMatch ? 1 - edits / maximum : null);
}

View File

@@ -151,6 +151,11 @@ export const DEFAULT_ANALYZE_TEMPLATE = `【角色与核心任务 (ROLE AND CORE
<question_text>
在此处填写题目的完整文本。使用 Markdown 格式。所有数学公式使用 LaTeX 符号(行内 $...$,块级 $$...$$)。
【题干转录规则】
1. **逐字照录**:按图片原文转录题干(含题号、分值和标点),不要改写、概括、增删字词或调整语序;看不清的字用 [?] 标注。
2. **填空统一**:所有填空处统一写作 ____(4 个下划线),不论原图横线长短。
3. **图形描述**:如果题目依赖图形,在题干原文之后空一行,单独写**一段**以「图示:」开头的图形描述;只能使用「图示:」这一种写法(不要写「图示信息」「图示说明」等),描述中不要重复题干已有的文字。题目不依赖图形时不要写图示段落。
【表格处理规则】
如果图片中包含表格,必须完整转录表格内容,遵循以下原则:

View File

@@ -1,10 +1,36 @@
export const DEFAULT_QUESTION_DUPLICATE_THRESHOLD = 99;
export const DEFAULT_QUESTION_DUPLICATE_THRESHOLD = 90;
/** 仅规范化排版差异,保留大小写、数字、运算符和上下标等题意信息。 */
// AI 识别时会在题干后另起一段描述图形(「图示:」「图示信息:」「图示说明:」等),每次措辞都不同
const FIGURE_DESCRIPTION = /^[【[((]?图示/u;
/** 去掉题干后面的图形描述段落;第一行始终保留,避免误删以「图示」开头的题干本身。 */
function stripFigureDescriptions(text: string): string {
const kept: string[] = [];
let seenContent = false;
let skipping = false;
for (const line of text.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed) {
skipping = false;
} else if (seenContent && FIGURE_DESCRIPTION.test(trimmed)) {
skipping = true;
}
if (!skipping) kept.push(line);
if (trimmed) seenContent = true;
}
return kept.join('\n');
}
/**
* 规范化排版差异,保留大小写、数字、运算符和上下标等题意信息:
* 忽略 AI 附加的图形描述,统一不同长度的填空横线和空括号。
*/
export function normalizeQuestionText(text: string): string {
return text.normalize('NFC')
return stripFigureDescriptions(text.normalize('NFC'))
.replace(/[\uFF01-\uFF5E]/g, (character) => String.fromCharCode(character.charCodeAt(0) - 0xFEE0))
.replace(/\\underline\{[^}]*\}|_{2,}/g, '__')
.replace(/\s+/gu, ' ')
.replace(/\( ?\)/g, '()')
.trim();
}

View File

@@ -710,7 +710,7 @@ export const translations = {
preferenceSaved: "Preference saved",
preferenceSaveFailed: "Failed to save preference",
thresholdLabel: "Duplicate question threshold",
thresholdDescription: "Default: 99%. Questions with similarity strictly above this value are recorded as repeated incorrect attempts. Range: 1–100%, up to 2 decimal places. At 100%, automatic duplicate detection is disabled.",
thresholdDescription: "Default: 90%. Figure descriptions added by AI and blank lengths are ignored when comparing. Questions with similarity strictly above this value are recorded as repeated incorrect attempts. Range: 1–100%, up to 2 decimal places. At 100%, automatic duplicate detection is disabled.",
thresholdInvalid: "Enter a value from 1 to 100, with up to 2 decimal places.",
thresholdLoadFailed: "Failed to load the saved threshold. Please retry.",
saveThreshold: "Save threshold",
@@ -1541,7 +1541,7 @@ export const translations = {
preferenceSaved: "设置已保存",
preferenceSaveFailed: "保存设置失败",
thresholdLabel: "题目判重相似度阈值",
thresholdDescription: "默认 99%。相似度严格大于此值时不再导入,并记录本次做错。支持 1%~100%,最多两位小数;设为 100% 时不自动判重。",
thresholdDescription: "默认 90%。比较时会忽略 AI 附加的图示描述和填空横线长短。相似度严格大于此值时不再导入,并记录本次做错。支持 1%~100%,最多两位小数;设为 100% 时不自动判重。",
thresholdInvalid: "请输入 1~100 之间的数值,最多两位小数。",
thresholdLoadFailed: "读取已保存的阈值失败,请重试。",
saveThreshold: "保存阈值",