mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-02 07:50:00 +08:00
feat: SVG 动画讲解绑定界面语言,中英文版本分别生成并随语言自动切换
- ErrorItem 新增 svgAnimationEn 列(仅新增列),svgAnimation 保存中文版 - 生成接口按 language 生成对应语言的动画,提示词和用户消息要求动画文字使用该语言;删除只影响当前语言 - 详情页按界面语言显示对应版本,切换语言时自动切换;当前语言未生成而另一语言已有时给出提示 - 同步更新四个 AI 提供商、README 与 Wiki,并补充接口、提示词和组件测试 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -122,7 +122,7 @@ Practice statistics show total practice, accuracy and active months, with distri
|
||||
|
||||
### Explanations and demos
|
||||
|
||||
- **🎬 SVG animated explanations**: AI generates step-by-step SVG animations of the solution, with play/pause, seeking, replay and full screen. On by default; turn it off in **Settings → General**.
|
||||
- **🎬 SVG animated explanations**: AI generates step-by-step SVG animations of the solution, with play/pause, seeking, replay and full screen. Animation text follows the interface language: the English interface generates an English version and the Chinese interface a Chinese one. Both are kept, and switching the language shows the matching version automatically. On by default; turn it off in **Settings → General**.
|
||||
- **📐 GeoGebra demos**: for math and physics questions, AI can generate interactive GeoGebra figures. Off by default; turn it on in **Settings → General**.
|
||||
- Generated animations and GeoGebra demos can be deleted (with confirmation).
|
||||
|
||||
|
||||
@@ -120,7 +120,7 @@
|
||||
|
||||
### 讲解与演示
|
||||
|
||||
- **🎬 SVG 动画讲解**:AI 按解题思路生成分步骤的 SVG 动画,支持播放/暂停、拖动进度、重播和全屏。默认开启,可在「设置 → 通用」中关闭。
|
||||
- **🎬 SVG 动画讲解**:AI 按解题思路生成分步骤的 SVG 动画,支持播放/暂停、拖动进度、重播和全屏。动画文字与界面语言一致:中文界面生成中文版、英文界面生成英文版,两种版本分别保存,切换语言时自动显示对应版本。默认开启,可在「设置 → 通用」中关闭。
|
||||
- **📐 GeoGebra 动态演示**:数学、物理题可由 AI 生成交互式 GeoGebra 图形。默认关闭,可在「设置 → 通用」中开启。
|
||||
- 已生成的动画讲解和 GeoGebra 演示都可删除(需二次确认)。
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
## 配图和动态讲解
|
||||
|
||||
- **SVG 配图**:由 AI 根据题目生成静态 SVG,供详情、练习和打印使用;原图可单独查看。
|
||||
- **SVG 动画讲解**:按解题思路分步骤演示,支持暂停、拖动进度、重播和全屏,个人设置默认开启。
|
||||
- **SVG 动画讲解**:按解题思路分步骤演示,支持暂停、拖动进度、重播和全屏,个人设置默认开启。动画文字跟随界面语言,中英文版本分别生成和保存,切换语言时自动显示对应版本。
|
||||
- **GeoGebra 动态演示**:供数学、物理题生成交互图形,个人设置默认关闭。
|
||||
|
||||
已生成的动画和 GeoGebra 演示可在确认后删除。生成的图形和解答需要人工核对,尤其是几何位置、计数过程和结论。
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- 仅新增列:英文版 SVG 动画讲解(svgAnimation 为中文版),不影响已有数据。
|
||||
ALTER TABLE "ErrorItem" ADD COLUMN "svgAnimationEn" TEXT;
|
||||
@@ -106,7 +106,8 @@ model ErrorItem {
|
||||
mistakeStatus String? // not_attempted, wrong_attempt, unknown
|
||||
knowledgePoints String? // [DEPRECATED] JSON string - kept for migration only
|
||||
geogebraCommands String? // GeoGebra commands for interactive demo (JSON or newline-separated)
|
||||
svgAnimation String? // AI 生成的 SVG 动画讲解(已净化)
|
||||
svgAnimation String? // AI 生成的 SVG 动画讲解(已净化),中文版
|
||||
svgAnimationEn String? // 英文版 SVG 动画讲解(已净化),界面为英文时使用
|
||||
|
||||
// New: many-to-many relation with KnowledgeTag
|
||||
tags KnowledgeTag[]
|
||||
|
||||
@@ -20,8 +20,8 @@ import { POST, DELETE } from '@/app/api/error-items/[id]/svg-animation/route';
|
||||
import { DELETE as DELETE_GEOGEBRA } from '@/app/api/error-items/[id]/geogebra/route';
|
||||
|
||||
const context = { params: Promise.resolve({ id: 'e1' }) };
|
||||
const generate = () => POST(new Request('http://localhost', { method: 'POST' }), context);
|
||||
const remove = () => DELETE(new Request('http://localhost', { method: 'DELETE' }), context);
|
||||
const generate = (body?: unknown) => POST(new Request('http://localhost', { method: 'POST', ...(body ? { body: JSON.stringify(body) } : {}) }), context);
|
||||
const remove = (query = '') => DELETE(new Request(`http://localhost${query}`, { method: 'DELETE' }), context);
|
||||
const removeGeogebra = () => DELETE_GEOGEBRA(new Request('http://localhost', { method: 'DELETE' }), context);
|
||||
const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><circle cx="5" cy="5" r="4"><animate attributeName="r" from="0" to="4" dur="1s"/></circle></svg>';
|
||||
|
||||
@@ -34,15 +34,35 @@ describe('SVG 动画讲解接口', () => {
|
||||
mocks.errorItem.update.mockResolvedValue({});
|
||||
});
|
||||
|
||||
it('POST 把题目、答案、解析和配图交给 AI,保存生成的动画', async () => {
|
||||
it('POST 把题目、答案、解析和配图交给 AI,未指定语言时生成并保存中文版动画', async () => {
|
||||
mocks.generateSvgAnimation.mockResolvedValue(svg);
|
||||
|
||||
const response = await generate();
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mocks.generateSvgAnimation).toHaveBeenCalledWith('求面积', '6', '底乘高', '<svg/>');
|
||||
expect(mocks.generateSvgAnimation).toHaveBeenCalledWith('求面积', '6', '底乘高', '<svg/>', 'zh');
|
||||
expect(mocks.errorItem.update).toHaveBeenCalledWith({ where: { id: 'e1' }, data: { svgAnimation: svg } });
|
||||
expect(await response.json()).toEqual({ svgAnimation: svg, language: 'zh' });
|
||||
});
|
||||
|
||||
it('POST language=en 时生成英文版动画,单独保存且不覆盖中文版', async () => {
|
||||
mocks.generateSvgAnimation.mockResolvedValue(svg);
|
||||
|
||||
const response = await generate({ language: 'en' });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mocks.generateSvgAnimation).toHaveBeenCalledWith('求面积', '6', '底乘高', '<svg/>', 'en');
|
||||
expect(mocks.errorItem.update).toHaveBeenCalledWith({ where: { id: 'e1' }, data: { svgAnimationEn: svg } });
|
||||
expect(await response.json()).toEqual({ svgAnimation: svg, language: 'en' });
|
||||
});
|
||||
|
||||
it('POST 不支持的语言按中文处理', async () => {
|
||||
mocks.generateSvgAnimation.mockResolvedValue(svg);
|
||||
|
||||
await generate({ language: 'fr' });
|
||||
|
||||
expect(mocks.generateSvgAnimation.mock.calls[0][4]).toBe('zh');
|
||||
expect(mocks.errorItem.update).toHaveBeenCalledWith({ where: { id: 'e1' }, data: { svgAnimation: svg } });
|
||||
expect(await response.json()).toEqual({ svgAnimation: svg });
|
||||
});
|
||||
|
||||
it('POST 题目文字为空时返回 NO_QUESTION_TEXT,不调用 AI', async () => {
|
||||
@@ -74,13 +94,20 @@ describe('SVG 动画讲解接口', () => {
|
||||
expect((await response.json()).message).toBe('AI_TIMEOUT_ERROR');
|
||||
});
|
||||
|
||||
it('DELETE 清空已生成的动画', async () => {
|
||||
it('DELETE 未指定语言时清空中文版动画', async () => {
|
||||
const response = await remove();
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mocks.errorItem.update).toHaveBeenCalledWith({ where: { id: 'e1' }, data: { svgAnimation: null } });
|
||||
});
|
||||
|
||||
it('DELETE language=en 只清空英文版动画', async () => {
|
||||
const response = await remove('?language=en');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mocks.errorItem.update).toHaveBeenCalledWith({ where: { id: 'e1' }, data: { svgAnimationEn: null } });
|
||||
});
|
||||
|
||||
it('未登录返回 401,不能操作他人的题目', async () => {
|
||||
mocks.session = null;
|
||||
expect((await generate()).status).toBe(401);
|
||||
|
||||
@@ -392,6 +392,17 @@ describe('OpenAI Provider SVG 动画讲解', () => {
|
||||
expect(svg).not.toContain('<script');
|
||||
});
|
||||
|
||||
it('language=en 时提示词和用户消息都要求动画文字使用英文', async () => {
|
||||
mockCompletionCreate.mockResolvedValue({ choices: [{ finish_reason: 'stop', message: { content: `<svg_animation>${animation}</svg_animation>` } }] });
|
||||
const provider = new OpenAIProvider({ apiKey: 'test-key', model: 'gpt-4o' });
|
||||
|
||||
await provider.generateSvgAnimation('求三角形面积', '6', '底乘高除以二', null, 'en');
|
||||
|
||||
const request = mockCompletionCreate.mock.calls[0][0];
|
||||
expect(request.messages[0].content).toContain('must be in English');
|
||||
expect(request.messages[1].content).toContain('in English');
|
||||
});
|
||||
|
||||
it('回复中没有有效 SVG 时返回 null', async () => {
|
||||
mockCompletionCreate.mockResolvedValue({ choices: [{ finish_reason: 'stop', message: { content: '<svg_animation>无法生成</svg_animation>' } }] });
|
||||
const provider = new OpenAIProvider({ apiKey: 'test-key', model: 'gpt-4o' });
|
||||
|
||||
95
src/__tests__/unit/svg-animation-explainer.test.tsx
Normal file
95
src/__tests__/unit/svg-animation-explainer.test.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* SVG 动画讲解组件:按界面语言生成、删除和提示动画
|
||||
*/
|
||||
import { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { SvgAnimationExplainer } from '@/components/svg-animation-explainer';
|
||||
import { LanguageProvider } from '@/contexts/LanguageContext';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
post: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
confirmDialog: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/api-client', () => ({ apiClient: { post: mocks.post, delete: mocks.delete } }));
|
||||
vi.mock('@/lib/feedback', () => ({ toast: { error: vi.fn() }, confirmDialog: mocks.confirmDialog }));
|
||||
vi.mock('@/components/svg-animation-player', () => ({ SvgAnimationPlayer: ({ svg }: { svg: string }) => <div data-testid="player">{svg}</div> }));
|
||||
|
||||
const svg = '<svg xmlns="http://www.w3.org/2000/svg"/>';
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
localStorage.clear();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
async function render(props: { svgAnimation?: string | null; hasOtherLanguage?: boolean; onChange?: () => void }) {
|
||||
await act(async () => root.render(
|
||||
<LanguageProvider>
|
||||
<SvgAnimationExplainer errorItemId="e1" svgAnimation={props.svgAnimation} hasOtherLanguage={props.hasOtherLanguage} onChange={props.onChange ?? vi.fn()} />
|
||||
</LanguageProvider>,
|
||||
));
|
||||
}
|
||||
|
||||
const clickButton = (text: string) => act(async () => {
|
||||
const button = [...container.querySelectorAll('button')].find((b) => b.textContent?.includes(text));
|
||||
if (!button) throw new Error(`找不到按钮:${text}`);
|
||||
button.click();
|
||||
});
|
||||
|
||||
describe('SVG 动画讲解按界面语言生成', () => {
|
||||
it('中文界面生成中文版动画', async () => {
|
||||
mocks.post.mockResolvedValue({ svgAnimation: svg });
|
||||
const onChange = vi.fn();
|
||||
await render({ onChange });
|
||||
|
||||
await clickButton('生成动画讲解');
|
||||
|
||||
expect(mocks.post).toHaveBeenCalledWith('/api/error-items/e1/svg-animation', { language: 'zh' }, expect.anything());
|
||||
expect(onChange).toHaveBeenCalledWith('zh', svg);
|
||||
});
|
||||
|
||||
it('英文界面生成英文版动画', async () => {
|
||||
localStorage.setItem('app-language', 'en');
|
||||
mocks.post.mockResolvedValue({ svgAnimation: svg });
|
||||
const onChange = vi.fn();
|
||||
await render({ onChange });
|
||||
|
||||
await clickButton('Generate animation');
|
||||
|
||||
expect(mocks.post).toHaveBeenCalledWith('/api/error-items/e1/svg-animation', { language: 'en' }, expect.anything());
|
||||
expect(onChange).toHaveBeenCalledWith('en', svg);
|
||||
});
|
||||
|
||||
it('英文界面只删除英文版动画', async () => {
|
||||
localStorage.setItem('app-language', 'en');
|
||||
mocks.confirmDialog.mockResolvedValue(true);
|
||||
mocks.delete.mockResolvedValue({ success: true });
|
||||
const onChange = vi.fn();
|
||||
await render({ svgAnimation: svg, onChange });
|
||||
|
||||
await clickButton('Delete');
|
||||
|
||||
expect(mocks.delete).toHaveBeenCalledWith('/api/error-items/e1/svg-animation?language=en');
|
||||
expect(onChange).toHaveBeenCalledWith('en', null);
|
||||
});
|
||||
|
||||
it('当前语言未生成但另一语言已有动画时提示切换语言查看', async () => {
|
||||
await render({ hasOtherLanguage: true });
|
||||
expect(container.textContent).toContain('已有英文版动画讲解');
|
||||
});
|
||||
});
|
||||
@@ -54,6 +54,22 @@ describe('generateSvgAnimationPrompt', () => {
|
||||
it('没有配图时不输出配图段落', () => {
|
||||
expect(generateSvgAnimationPrompt('求面积', '6', '解析')).not.toContain('题目配图');
|
||||
});
|
||||
|
||||
it('默认要求动画文字使用简体中文', () => {
|
||||
const prompt = generateSvgAnimationPrompt('求面积', '6', '解析');
|
||||
expect(prompt).toContain('简体中文,每行不超过 24 个字');
|
||||
expect(prompt).not.toContain('must be in English');
|
||||
expect(prompt).not.toContain('{{');
|
||||
});
|
||||
|
||||
it('language=en 时要求动画中全部文字使用英文', () => {
|
||||
const prompt = generateSvgAnimationPrompt('求面积', '6', '解析', null, 'en');
|
||||
expect(prompt).toContain('All text in the animation');
|
||||
expect(prompt).toContain('must be in English');
|
||||
expect(prompt).toContain('英文,每行不超过 48 个字符');
|
||||
expect(prompt).not.toContain('简体中文,每行不超过 24 个字');
|
||||
expect(prompt).not.toContain('{{');
|
||||
});
|
||||
});
|
||||
|
||||
import { buildSvgAnimationDocument, getSvgAnimationDuration, getSvgAspectRatio, parseClockValue } from '@/lib/svg-animation';
|
||||
|
||||
@@ -9,6 +9,16 @@ import { describeQuestion, trackBackgroundTask } from "@/lib/background-tasks";
|
||||
const logger = createLogger('api:error-items:svg-animation');
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
type AnimationLanguage = 'zh' | 'en';
|
||||
|
||||
/** 动画按语言分别保存:中文版存 svgAnimation,英文版存 svgAnimationEn;未指定时为中文 */
|
||||
function parseLanguage(value: unknown): AnimationLanguage {
|
||||
return value === 'en' ? 'en' : 'zh';
|
||||
}
|
||||
|
||||
function animationField(language: AnimationLanguage) {
|
||||
return language === 'en' ? 'svgAnimationEn' : 'svgAnimation';
|
||||
}
|
||||
|
||||
/** 当前用户拥有的错题;不存在或不属于该用户时返回 null */
|
||||
async function findOwnedItem(id: string, userId: string) {
|
||||
@@ -21,10 +31,13 @@ async function findOwnedItem(id: string, userId: string) {
|
||||
|
||||
/**
|
||||
* POST /api/error-items/:id/svg-animation
|
||||
* 由 AI 根据题目、答案和解析生成 SVG 动画讲解并保存(覆盖已有的动画)
|
||||
* 由 AI 根据题目、答案和解析生成 SVG 动画讲解并保存(覆盖该语言已有的动画)
|
||||
* 请求体 { language: 'zh' | 'en' }:动画中的文字使用该语言,未指定时为中文
|
||||
*/
|
||||
export async function POST(_req: Request, { params }: RouteContext) {
|
||||
export async function POST(req: Request, { params }: RouteContext) {
|
||||
const { id } = await params;
|
||||
const body = await req.json().catch(() => ({})) as { language?: unknown };
|
||||
const language = parseLanguage(body.language);
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
@@ -45,9 +58,9 @@ export async function POST(_req: Request, { params }: RouteContext) {
|
||||
const svgAnimation = await trackBackgroundTask(
|
||||
{ userId: user.id, kind: 'svg_animation', subject: describeQuestion(item), link: `/error-items/${id}` },
|
||||
async () => {
|
||||
const svg = await getAIService().generateSvgAnimation(questionText, item.answerText || "", item.analysis || "", item.figureSvg);
|
||||
const svg = await getAIService().generateSvgAnimation(questionText, item.answerText || "", item.analysis || "", item.figureSvg, language);
|
||||
if (!svg) throw new Error("NO_VALID_ANIMATION");
|
||||
await prisma.errorItem.update({ where: { id }, data: { svgAnimation: svg } });
|
||||
await prisma.errorItem.update({ where: { id }, data: { [animationField(language)]: svg } });
|
||||
return svg;
|
||||
}
|
||||
).catch((error: unknown) => {
|
||||
@@ -58,8 +71,8 @@ export async function POST(_req: Request, { params }: RouteContext) {
|
||||
return badRequest("NO_VALID_ANIMATION");
|
||||
}
|
||||
|
||||
logger.info({ errorItemId: id, svgLength: svgAnimation.length }, 'SVG animation generated');
|
||||
return NextResponse.json({ svgAnimation });
|
||||
logger.info({ errorItemId: id, language, svgLength: svgAnimation.length }, 'SVG animation generated');
|
||||
return NextResponse.json({ svgAnimation, language });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logger.error({ error: message }, 'Error generating SVG animation');
|
||||
@@ -69,11 +82,12 @@ export async function POST(_req: Request, { params }: RouteContext) {
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/error-items/:id/svg-animation
|
||||
* 删除已生成的 SVG 动画讲解
|
||||
* DELETE /api/error-items/:id/svg-animation?language=zh|en
|
||||
* 删除指定语言已生成的 SVG 动画讲解,另一语言的动画保留;未指定时为中文
|
||||
*/
|
||||
export async function DELETE(_req: Request, { params }: RouteContext) {
|
||||
export async function DELETE(req: Request, { params }: RouteContext) {
|
||||
const { id } = await params;
|
||||
const language = parseLanguage(new URL(req.url).searchParams.get('language'));
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
@@ -84,8 +98,8 @@ export async function DELETE(_req: Request, { params }: RouteContext) {
|
||||
return notFound("Item not found");
|
||||
}
|
||||
|
||||
await prisma.errorItem.update({ where: { id }, data: { svgAnimation: null } });
|
||||
logger.info({ errorItemId: id }, 'SVG animation deleted');
|
||||
await prisma.errorItem.update({ where: { id }, data: { [animationField(language)]: null } });
|
||||
logger.info({ errorItemId: id, language }, 'SVG animation deleted');
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
logger.error({ error }, 'Error deleting SVG animation');
|
||||
|
||||
@@ -69,7 +69,8 @@ interface ErrorItemDetail {
|
||||
hasFigure?: boolean;
|
||||
figureSvg?: string | null;
|
||||
geogebraCommands?: string | null;
|
||||
svgAnimation?: string | null;
|
||||
svgAnimation?: string | null; // 中文版动画讲解
|
||||
svgAnimationEn?: string | null; // 英文版动画讲解
|
||||
}
|
||||
|
||||
export default function ErrorDetailPage() {
|
||||
@@ -208,8 +209,9 @@ export default function ErrorDetailPage() {
|
||||
setItem((current) => current && { ...current, ...updated });
|
||||
}, []);
|
||||
|
||||
const handleSvgAnimationChange = useCallback((svgAnimation: string | null) => {
|
||||
setItem((current) => current && { ...current, svgAnimation });
|
||||
// 动画按语言分别保存,生成或删除只影响对应语言的版本
|
||||
const handleSvgAnimationChange = useCallback((animationLanguage: 'zh' | 'en', svgAnimation: string | null) => {
|
||||
setItem((current) => current && { ...current, [animationLanguage === 'en' ? 'svgAnimationEn' : 'svgAnimation']: svgAnimation });
|
||||
}, []);
|
||||
|
||||
const toggleMastery = async () => {
|
||||
@@ -672,7 +674,16 @@ export default function ErrorDetailPage() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{svgAnimationEnabled && <SvgAnimationExplainer errorItemId={item.id} svgAnimation={item.svgAnimation} onChange={handleSvgAnimationChange} />}
|
||||
{svgAnimationEnabled && (
|
||||
// 切换界面语言时自动显示对应语言的动画;key 让播放器随语言重新加载
|
||||
<SvgAnimationExplainer
|
||||
key={language}
|
||||
errorItemId={item.id}
|
||||
svgAnimation={language === 'en' ? item.svgAnimationEn : item.svgAnimation}
|
||||
hasOtherLanguage={!!(language === 'en' ? item.svgAnimation : item.svgAnimationEn)}
|
||||
onChange={handleSvgAnimationChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
{geogebraEnabled && (item.geogebraCommands ? (
|
||||
<GeogebraDemo commands={item.geogebraCommands} height={700} showToolBar={true} showAlgebraInput={false} showMenuBar={false} onRegenerate={handleAnalyzeGeogebra} onSaveCommands={handleSaveGeogebraCommands} onDelete={handleDeleteGeogebra} />
|
||||
|
||||
@@ -8,22 +8,27 @@ import { useLanguage } from "@/contexts/LanguageContext";
|
||||
import { apiClient } from "@/lib/api-client";
|
||||
import { frontendLogger } from "@/lib/frontend-logger";
|
||||
import { toast, confirmDialog } from "@/lib/feedback";
|
||||
import type { Language } from "@/lib/translations";
|
||||
|
||||
/** 动画 SVG 较长,AI 通常需要几分钟才能写完,前端等待上限与服务端 AI 请求超时一致 */
|
||||
const GENERATE_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
|
||||
interface SvgAnimationExplainerProps {
|
||||
errorItemId: string;
|
||||
/** 当前界面语言对应的动画 */
|
||||
svgAnimation: string | null | undefined;
|
||||
/** 生成或删除后回调新的动画(删除后为 null) */
|
||||
onChange: (svgAnimation: string | null) => void;
|
||||
/** 另一语言是否已有动画(当前语言未生成时提示切换语言查看) */
|
||||
hasOtherLanguage?: boolean;
|
||||
/** 生成或删除后回调该语言的新动画(删除后为 null) */
|
||||
onChange: (language: Language, svgAnimation: string | null) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 题目的 SVG 动画讲解:未生成时显示生成入口;已生成时可播放/暂停、拖动进度、重新生成和删除(删除需二次确认)。
|
||||
* 题目的 SVG 动画讲解,按界面语言分别生成和显示:中文界面用中文版动画,英文界面用英文版动画。
|
||||
* 未生成时显示生成入口;已生成时可播放/暂停、拖动进度、重新生成和删除(删除需二次确认,只删除当前语言的动画)。
|
||||
*/
|
||||
export function SvgAnimationExplainer({ errorItemId, svgAnimation, onChange }: SvgAnimationExplainerProps) {
|
||||
const { t } = useLanguage();
|
||||
export function SvgAnimationExplainer({ errorItemId, svgAnimation, hasOtherLanguage, onChange }: SvgAnimationExplainerProps) {
|
||||
const { t, language } = useLanguage();
|
||||
const [generating, setGenerating] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -32,8 +37,8 @@ export function SvgAnimationExplainer({ errorItemId, svgAnimation, onChange }: S
|
||||
setGenerating(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await apiClient.post<{ svgAnimation: string }>(`/api/error-items/${errorItemId}/svg-animation`, {}, { timeout: GENERATE_TIMEOUT_MS });
|
||||
onChange(result.svgAnimation);
|
||||
const result = await apiClient.post<{ svgAnimation: string }>(`/api/error-items/${errorItemId}/svg-animation`, { language }, { timeout: GENERATE_TIMEOUT_MS });
|
||||
onChange(language, result.svgAnimation);
|
||||
} catch (err) {
|
||||
const code = (err as { data?: { message?: string } })?.data?.message || "";
|
||||
const mapped = (t.errors as Record<string, unknown>)[code];
|
||||
@@ -52,8 +57,8 @@ export function SvgAnimationExplainer({ errorItemId, svgAnimation, onChange }: S
|
||||
if (!(await confirmDialog(t.svgAnimation.confirmDelete, { destructive: true }))) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
await apiClient.delete(`/api/error-items/${errorItemId}/svg-animation`);
|
||||
onChange(null);
|
||||
await apiClient.delete(`/api/error-items/${errorItemId}/svg-animation?language=${language}`);
|
||||
onChange(language, null);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
frontendLogger.error('[SvgAnimation]', 'Failed to delete SVG animation', { error: err instanceof Error ? err.message : String(err) });
|
||||
@@ -77,7 +82,7 @@ export function SvgAnimationExplainer({ errorItemId, svgAnimation, onChange }: S
|
||||
</Button>
|
||||
</div>
|
||||
{error && <p className="text-xs text-destructive mt-2">{error}</p>}
|
||||
<p className="text-xs text-muted-foreground mt-2">{t.svgAnimation.hint}</p>
|
||||
<p className="text-xs text-muted-foreground mt-2">{hasOtherLanguage ? t.svgAnimation.otherLanguageAvailable : t.svgAnimation.hint}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Anthropic from "@anthropic-ai/sdk";
|
||||
import { AIService, GradeLevel, ParsedQuestion, DifficultyLevel, AIConfig, ReanswerQuestionResult, GeogebraAnalysisResult, MasteryEvaluationInput, MasteryEvaluationResult, TagSuggestionInput, TagSuggestionResult, CandidateTags, FigureResult } from "./types";
|
||||
import { generateAnalyzePrompt, generateSimilarQuestionPrompt, generateGeogebraPrompt, generateMasteryPrompt, generateTagSuggestPrompt, generateReanswerPrompt, generateFigurePrompt, generateSvgAnimationPrompt, generateLatexFixPrompt } from './prompts';
|
||||
import { generateAnalyzePrompt, generateSimilarQuestionPrompt, generateGeogebraPrompt, generateMasteryPrompt, generateTagSuggestPrompt, generateReanswerPrompt, generateFigurePrompt, generateSvgAnimationPrompt, generateLatexFixPrompt, SVG_ANIMATION_REQUEST } from './prompts';
|
||||
import { sanitizeSvgAnimation } from '../svg-animation';
|
||||
import { parseLatexFix } from './latex-fix';
|
||||
import type { LatexFixInput, LatexFixResult } from './latex-fix';
|
||||
@@ -324,11 +324,11 @@ export class AnthropicProvider implements AIService {
|
||||
}
|
||||
}
|
||||
|
||||
async generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null): Promise<string | null> {
|
||||
async generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null, language: 'zh' | 'en' = 'zh'): Promise<string | null> {
|
||||
logger.info({ provider: 'Anthropic', model: this.model, questionLength: questionText.length }, 'SVG Animation Request');
|
||||
|
||||
try {
|
||||
const text = await this.complete(generateSvgAnimationPrompt(questionText, answerText, analysis, figureSvg), "请为上述题目制作 SVG 动画讲解。", 16384);
|
||||
const text = await this.complete(generateSvgAnimationPrompt(questionText, answerText, analysis, figureSvg, language), SVG_ANIMATION_REQUEST[language], 16384);
|
||||
logger.debug({ rawResponse: text }, 'SVG animation AI raw response');
|
||||
return sanitizeSvgAnimation(extractTag(text, "svg_animation") || text);
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AzureOpenAI } from "openai";
|
||||
import { AIService, GradeLevel, ParsedQuestion, DifficultyLevel, ReanswerQuestionResult, GeogebraAnalysisResult, MasteryEvaluationInput, MasteryEvaluationResult, TagSuggestionInput, TagSuggestionResult, CandidateTags, FigureResult } from "./types";
|
||||
import { generateAnalyzePrompt, generateSimilarQuestionPrompt, generateReanswerPrompt, generateGeogebraPrompt, generateMasteryPrompt, generateTagSuggestPrompt, generateFigurePrompt, generateSvgAnimationPrompt, generateLatexFixPrompt } from './prompts';
|
||||
import { generateAnalyzePrompt, generateSimilarQuestionPrompt, generateReanswerPrompt, generateGeogebraPrompt, generateMasteryPrompt, generateTagSuggestPrompt, generateFigurePrompt, generateSvgAnimationPrompt, generateLatexFixPrompt, SVG_ANIMATION_REQUEST } from './prompts';
|
||||
import { sanitizeSvgAnimation } from '../svg-animation';
|
||||
import { parseLatexFix } from './latex-fix';
|
||||
import type { LatexFixInput, LatexFixResult } from './latex-fix';
|
||||
@@ -545,8 +545,8 @@ Knowledge Points: ${knowledgePoints.join(", ")}
|
||||
}
|
||||
}
|
||||
|
||||
async generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null): Promise<string | null> {
|
||||
const prompt = generateSvgAnimationPrompt(questionText, answerText, analysis, figureSvg);
|
||||
async generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null, language: 'zh' | 'en' = 'zh'): Promise<string | null> {
|
||||
const prompt = generateSvgAnimationPrompt(questionText, answerText, analysis, figureSvg, language);
|
||||
logger.info({ provider: 'Azure OpenAI', deployment: this.deployment, questionLength: questionText.length }, 'SVG Animation Request');
|
||||
|
||||
try {
|
||||
@@ -554,7 +554,7 @@ Knowledge Points: ${knowledgePoints.join(", ")}
|
||||
model: this.deployment,
|
||||
messages: [
|
||||
{ role: "system", content: prompt },
|
||||
{ role: "user", content: "请为上述题目制作 SVG 动画讲解。" },
|
||||
{ role: "user", content: SVG_ANIMATION_REQUEST[language] },
|
||||
],
|
||||
max_tokens: maxTokens,
|
||||
}), 16384, () => logger.warn('Output truncated by reasoning, retrying with larger max_tokens'));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { GoogleGenAI } from "@google/genai";
|
||||
import { AIService, GradeLevel, ParsedQuestion, DifficultyLevel, AIConfig, ReanswerQuestionResult, GeogebraAnalysisResult, MasteryEvaluationInput, MasteryEvaluationResult, TagSuggestionInput, TagSuggestionResult, CandidateTags, FigureResult } from "./types";
|
||||
import { generateAnalyzePrompt, generateSimilarQuestionPrompt, generateGeogebraPrompt, generateMasteryPrompt, generateTagSuggestPrompt, generateFigurePrompt, generateSvgAnimationPrompt, generateLatexFixPrompt } from './prompts';
|
||||
import { generateAnalyzePrompt, generateSimilarQuestionPrompt, generateGeogebraPrompt, generateMasteryPrompt, generateTagSuggestPrompt, generateFigurePrompt, generateSvgAnimationPrompt, generateLatexFixPrompt, SVG_ANIMATION_REQUEST } from './prompts';
|
||||
import { sanitizeSvgAnimation } from '../svg-animation';
|
||||
import { parseLatexFix } from './latex-fix';
|
||||
import type { LatexFixInput, LatexFixResult } from './latex-fix';
|
||||
@@ -499,14 +499,14 @@ export class GeminiProvider implements AIService {
|
||||
}
|
||||
}
|
||||
|
||||
async generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null): Promise<string | null> {
|
||||
const prompt = generateSvgAnimationPrompt(questionText, answerText, analysis, figureSvg);
|
||||
async generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null, language: 'zh' | 'en' = 'zh'): Promise<string | null> {
|
||||
const prompt = generateSvgAnimationPrompt(questionText, answerText, analysis, figureSvg, language);
|
||||
logger.info({ provider: 'Gemini', model: this.modelName, questionLength: questionText.length }, 'SVG Animation Request');
|
||||
|
||||
try {
|
||||
const response = await this.retryOperation(() => this.ai.models.generateContent({
|
||||
model: this.modelName,
|
||||
contents: [{ text: prompt }, { text: "请为上述题目制作 SVG 动画讲解。" }],
|
||||
contents: [{ text: prompt }, { text: SVG_ANIMATION_REQUEST[language] }],
|
||||
}));
|
||||
|
||||
const text = response.text || '';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import OpenAI from "openai";
|
||||
import { AIService, GradeLevel, ParsedQuestion, DifficultyLevel, AIConfig, ReanswerQuestionResult, GeogebraAnalysisResult, MasteryEvaluationInput, MasteryEvaluationResult, TagSuggestionInput, TagSuggestionResult, CandidateTags, FigureResult } from "./types";
|
||||
import { generateAnalyzePrompt, generateSimilarQuestionPrompt, generateGeogebraPrompt, generateMasteryPrompt, generateTagSuggestPrompt, generateFigurePrompt, generateSvgAnimationPrompt, generateLatexFixPrompt } from './prompts';
|
||||
import { generateAnalyzePrompt, generateSimilarQuestionPrompt, generateGeogebraPrompt, generateMasteryPrompt, generateTagSuggestPrompt, generateFigurePrompt, generateSvgAnimationPrompt, generateLatexFixPrompt, SVG_ANIMATION_REQUEST } from './prompts';
|
||||
import { sanitizeSvgAnimation } from '../svg-animation';
|
||||
import { parseLatexFix } from './latex-fix';
|
||||
import type { LatexFixInput, LatexFixResult } from './latex-fix';
|
||||
@@ -614,8 +614,8 @@ export class OpenAIProvider implements AIService {
|
||||
}
|
||||
}
|
||||
|
||||
async generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null): Promise<string | null> {
|
||||
const prompt = generateSvgAnimationPrompt(questionText, answerText, analysis, figureSvg);
|
||||
async generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null, language: 'zh' | 'en' = 'zh'): Promise<string | null> {
|
||||
const prompt = generateSvgAnimationPrompt(questionText, answerText, analysis, figureSvg, language);
|
||||
logger.info({ provider: 'OpenAI', model: this.model, questionLength: questionText.length }, 'SVG Animation Request');
|
||||
|
||||
try {
|
||||
@@ -623,7 +623,7 @@ export class OpenAIProvider implements AIService {
|
||||
model: this.model,
|
||||
messages: [
|
||||
{ role: "system", content: prompt },
|
||||
{ role: "user", content: "请为上述题目制作 SVG 动画讲解。" },
|
||||
{ role: "user", content: SVG_ANIMATION_REQUEST[language] },
|
||||
],
|
||||
max_tokens: maxTokens,
|
||||
}), 16384, () => logger.warn('Output truncated by reasoning, retrying with larger max_tokens'));
|
||||
|
||||
@@ -840,7 +840,8 @@ export const DEFAULT_SVG_ANIMATION_TEMPLATE = `【角色与核心任务 (ROLE AN
|
||||
|
||||
【动画要求】
|
||||
- 分 3~6 个步骤,每步 4~6 秒,总时长不超过 40 秒;动画只播放一遍,全部元素使用 fill="freeze",结束时停在完整的解题结论画面。
|
||||
- 每一步在画面底部的字幕区显示该步的讲解文字(简体中文,每行不超过 24 个字,最多两行),进入下一步时替换为新字幕。
|
||||
- 每一步在画面底部的字幕区显示该步的讲解文字({{subtitle_rule}}),进入下一步时替换为新字幕。
|
||||
- {{language_instruction}}
|
||||
- 画面与讲解同步:逐步画出辅助线、标出已知条件、高亮正在讲解的部分、移动或变换图形、写出关键算式。几何题按题目条件画图;非几何题用线段图、数轴、表格、示意图或算式推导等合适的形式。
|
||||
- 用 SMIL 动画(<animate>、<set>、<animateTransform>、<animateMotion>)实现,用 begin 属性按时间排列(如 begin="4s");需要先隐藏的元素设 opacity="0" 再用 <animate> 或 <set> 显示。
|
||||
- 公式不要用 LaTeX,用普通文字和 Unicode 符号(如 x²、√2、π、×、÷、≤、≥、∠、△、⊥、∥)。
|
||||
@@ -856,16 +857,29 @@ export const DEFAULT_SVG_ANIMATION_TEMPLATE = `【角色与核心任务 (ROLE AN
|
||||
完整的 SVG 动画
|
||||
</svg_animation>`;
|
||||
|
||||
/** 生成 SVG 动画讲解时随提示词发送的用户消息 */
|
||||
export const SVG_ANIMATION_REQUEST: Record<'zh' | 'en', string> = {
|
||||
zh: '请为上述题目制作 SVG 动画讲解。',
|
||||
en: 'Please create the SVG animated explanation for the question above, with all text in English.',
|
||||
};
|
||||
|
||||
/**
|
||||
* 生成 SVG 动画讲解提示词;figureSvg 为题目配图,动画据此作图
|
||||
* 生成 SVG 动画讲解提示词;figureSvg 为题目配图,动画据此作图;language 决定动画中文字的语言
|
||||
*/
|
||||
export function generateSvgAnimationPrompt(
|
||||
questionText: string,
|
||||
answerText: string,
|
||||
analysis: string,
|
||||
figureSvg?: string | null
|
||||
figureSvg?: string | null,
|
||||
language: 'zh' | 'en' = 'zh'
|
||||
): string {
|
||||
return replaceVariables(DEFAULT_SVG_ANIMATION_TEMPLATE, {
|
||||
subtitle_rule: language === 'en'
|
||||
? '英文,每行不超过 48 个字符,最多两行'
|
||||
: '简体中文,每行不超过 24 个字,最多两行',
|
||||
language_instruction: language === 'en'
|
||||
? 'IMPORTANT: All text in the animation (title, labels, table headers, subtitles and conclusions) must be in English. If the question, answer or analysis is in Chinese, translate it into natural English; keep names of points, variables and numbers unchanged.'
|
||||
: '动画中的全部文字(标题、标注、表头、字幕和结论)使用简体中文;题目为英文时,题目原文中的专有名词与变量可保留英文。',
|
||||
question_text: questionText.trim() || '(无题目文字)',
|
||||
answer_text: answerText.trim() || '(无)',
|
||||
analysis: analysis.trim() || '(无)',
|
||||
|
||||
@@ -86,8 +86,8 @@ export interface AIService {
|
||||
analyzeForGeogebra(questionText: string, answerText: string, analysis: string, previousErrors?: string): Promise<GeogebraAnalysisResult>;
|
||||
/** 只修复各字段中的 LaTeX 语法,返回 AI 修复后的字段内容 */
|
||||
fixLatex(input: LatexFixInput): Promise<LatexFixResult>;
|
||||
/** 生成 SVG 动画讲解(已净化),无有效 SVG 时返回 null;figureSvg 为题目配图 */
|
||||
generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null): Promise<string | null>;
|
||||
/** 生成 SVG 动画讲解(已净化),无有效 SVG 时返回 null;figureSvg 为题目配图,language 决定动画中文字的语言 */
|
||||
generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null, language?: 'zh' | 'en'): Promise<string | null>;
|
||||
evaluateMastery(input: MasteryEvaluationInput): Promise<MasteryEvaluationResult>;
|
||||
/** 从标签库中选知识点,并评定难度星级 */
|
||||
suggestKnowledgeTags(input: TagSuggestionInput): Promise<TagSuggestionResult>;
|
||||
|
||||
@@ -901,7 +901,8 @@ export const translations = {
|
||||
svgAnimation: {
|
||||
title: "SVG Animated Explanation",
|
||||
alt: "Animated explanation",
|
||||
hint: "AI explains the solution step by step with an SVG animation",
|
||||
hint: "AI explains the solution step by step with an SVG animation in English",
|
||||
otherLanguageAvailable: "A Chinese version of the animation exists. Switch the language to 中文 to view it, or generate an English version here.",
|
||||
generate: "Generate animation",
|
||||
generating: "Generating animation, this takes a few minutes…",
|
||||
regenerate: "Regenerate",
|
||||
@@ -912,7 +913,7 @@ export const translations = {
|
||||
fullscreen: "Full screen",
|
||||
exitFullscreen: "Exit full screen",
|
||||
delete: "Delete",
|
||||
confirmDelete: "Delete the generated SVG animation? This cannot be undone.",
|
||||
confirmDelete: "Delete the English SVG animation? The Chinese version is kept. This cannot be undone.",
|
||||
deleteFailed: "Failed to delete the animation",
|
||||
failed: "Failed to generate the animation, please try again later",
|
||||
noQuestionText: "The question text is empty, so no animation can be generated",
|
||||
@@ -1924,7 +1925,8 @@ export const translations = {
|
||||
svgAnimation: {
|
||||
title: "SVG 动画讲解",
|
||||
alt: "动画讲解",
|
||||
hint: "AI 将按解题思路分步骤生成 SVG 动画讲解",
|
||||
hint: "AI 将按解题思路分步骤生成中文 SVG 动画讲解",
|
||||
otherLanguageAvailable: "已有英文版动画讲解,切换为英文界面即可查看;也可在此生成中文版。",
|
||||
generate: "生成动画讲解",
|
||||
generating: "生成动画中,约需几分钟…",
|
||||
regenerate: "重新生成",
|
||||
@@ -1935,7 +1937,7 @@ export const translations = {
|
||||
fullscreen: "全屏",
|
||||
exitFullscreen: "退出全屏",
|
||||
delete: "删除",
|
||||
confirmDelete: "确定删除已生成的 SVG 动画讲解吗?删除后无法恢复。",
|
||||
confirmDelete: "确定删除中文版 SVG 动画讲解吗?英文版不受影响,删除后无法恢复。",
|
||||
deleteFailed: "删除动画讲解失败",
|
||||
failed: "生成动画讲解失败,请稍后重试",
|
||||
noQuestionText: "题目文字为空,无法生成动画讲解",
|
||||
|
||||
Reference in New Issue
Block a user