diff --git a/README.en.md b/README.en.md index a60ce703..5f15dd41 100644 --- a/README.en.md +++ b/README.en.md @@ -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). diff --git a/README.md b/README.md index f3fe0b86..7770d7d2 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ ### 讲解与演示 -- **🎬 SVG 动画讲解**:AI 按解题思路生成分步骤的 SVG 动画,支持播放/暂停、拖动进度、重播和全屏。默认开启,可在「设置 → 通用」中关闭。 +- **🎬 SVG 动画讲解**:AI 按解题思路生成分步骤的 SVG 动画,支持播放/暂停、拖动进度、重播和全屏。动画文字与界面语言一致:中文界面生成中文版、英文界面生成英文版,两种版本分别保存,切换语言时自动显示对应版本。默认开启,可在「设置 → 通用」中关闭。 - **📐 GeoGebra 动态演示**:数学、物理题可由 AI 生成交互式 GeoGebra 图形。默认关闭,可在「设置 → 通用」中开启。 - 已生成的动画讲解和 GeoGebra 演示都可删除(需二次确认)。 diff --git a/doc/wiki/User-Guide.md b/doc/wiki/User-Guide.md index 1be78928..fdc83115 100644 --- a/doc/wiki/User-Guide.md +++ b/doc/wiki/User-Guide.md @@ -50,7 +50,7 @@ ## 配图和动态讲解 - **SVG 配图**:由 AI 根据题目生成静态 SVG,供详情、练习和打印使用;原图可单独查看。 -- **SVG 动画讲解**:按解题思路分步骤演示,支持暂停、拖动进度、重播和全屏,个人设置默认开启。 +- **SVG 动画讲解**:按解题思路分步骤演示,支持暂停、拖动进度、重播和全屏,个人设置默认开启。动画文字跟随界面语言,中英文版本分别生成和保存,切换语言时自动显示对应版本。 - **GeoGebra 动态演示**:供数学、物理题生成交互图形,个人设置默认关闭。 已生成的动画和 GeoGebra 演示可在确认后删除。生成的图形和解答需要人工核对,尤其是几何位置、计数过程和结论。 diff --git a/prisma/migrations/20261022000141_add_svg_animation_en/migration.sql b/prisma/migrations/20261022000141_add_svg_animation_en/migration.sql new file mode 100644 index 00000000..183abbc0 --- /dev/null +++ b/prisma/migrations/20261022000141_add_svg_animation_en/migration.sql @@ -0,0 +1,2 @@ +-- 仅新增列:英文版 SVG 动画讲解(svgAnimation 为中文版),不影响已有数据。 +ALTER TABLE "ErrorItem" ADD COLUMN "svgAnimationEn" TEXT; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 6d99f6ee..ee3fb829 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -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[] diff --git a/src/__tests__/integration/svg-animation.test.ts b/src/__tests__/integration/svg-animation.test.ts index 461f32e2..dbd6d8df 100644 --- a/src/__tests__/integration/svg-animation.test.ts +++ b/src/__tests__/integration/svg-animation.test.ts @@ -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 = ''; @@ -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', '底乘高', ''); + expect(mocks.generateSvgAnimation).toHaveBeenCalledWith('求面积', '6', '底乘高', '', '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', '底乘高', '', '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); diff --git a/src/__tests__/unit/ai/openai-provider.test.ts b/src/__tests__/unit/ai/openai-provider.test.ts index 40a78db5..93af0701 100644 --- a/src/__tests__/unit/ai/openai-provider.test.ts +++ b/src/__tests__/unit/ai/openai-provider.test.ts @@ -392,6 +392,17 @@ describe('OpenAI Provider SVG 动画讲解', () => { expect(svg).not.toContain(' { + mockCompletionCreate.mockResolvedValue({ choices: [{ finish_reason: 'stop', message: { content: `${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: '无法生成' } }] }); const provider = new OpenAIProvider({ apiKey: 'test-key', model: 'gpt-4o' }); diff --git a/src/__tests__/unit/svg-animation-explainer.test.tsx b/src/__tests__/unit/svg-animation-explainer.test.tsx new file mode 100644 index 00000000..ba88afc6 --- /dev/null +++ b/src/__tests__/unit/svg-animation-explainer.test.tsx @@ -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 }) =>
{svg}
})); + +const 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( + + + , + )); +} + +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('已有英文版动画讲解'); + }); +}); diff --git a/src/__tests__/unit/svg-animation.test.ts b/src/__tests__/unit/svg-animation.test.ts index e4ef7b56..8b7de163 100644 --- a/src/__tests__/unit/svg-animation.test.ts +++ b/src/__tests__/unit/svg-animation.test.ts @@ -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'; diff --git a/src/app/api/error-items/[id]/svg-animation/route.ts b/src/app/api/error-items/[id]/svg-animation/route.ts index 83d3c2b9..5e9c05b3 100644 --- a/src/app/api/error-items/[id]/svg-animation/route.ts +++ b/src/app/api/error-items/[id]/svg-animation/route.ts @@ -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'); diff --git a/src/app/error-items/[id]/page.tsx b/src/app/error-items/[id]/page.tsx index aed98466..be9d0d8f 100644 --- a/src/app/error-items/[id]/page.tsx +++ b/src/app/error-items/[id]/page.tsx @@ -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() {
- {svgAnimationEnabled && } + {svgAnimationEnabled && ( + // 切换界面语言时自动显示对应语言的动画;key 让播放器随语言重新加载 + + )} {geogebraEnabled && (item.geogebraCommands ? ( diff --git a/src/components/svg-animation-explainer.tsx b/src/components/svg-animation-explainer.tsx index 86247909..b0807021 100644 --- a/src/components/svg-animation-explainer.tsx +++ b/src/components/svg-animation-explainer.tsx @@ -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(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)[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
{error &&

{error}

} -

{t.svgAnimation.hint}

+

{hasOtherLanguage ? t.svgAnimation.otherLanguageAvailable : t.svgAnimation.hint}

); } diff --git a/src/lib/ai/anthropic-provider.ts b/src/lib/ai/anthropic-provider.ts index 5cd9ff3a..6210b52c 100644 --- a/src/lib/ai/anthropic-provider.ts +++ b/src/lib/ai/anthropic-provider.ts @@ -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 { + async generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null, language: 'zh' | 'en' = 'zh'): Promise { 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) { diff --git a/src/lib/ai/azure-provider.ts b/src/lib/ai/azure-provider.ts index 45739958..28525dde 100644 --- a/src/lib/ai/azure-provider.ts +++ b/src/lib/ai/azure-provider.ts @@ -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 { - const prompt = generateSvgAnimationPrompt(questionText, answerText, analysis, figureSvg); + async generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null, language: 'zh' | 'en' = 'zh'): Promise { + 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')); diff --git a/src/lib/ai/gemini-provider.ts b/src/lib/ai/gemini-provider.ts index 30456f23..79566748 100644 --- a/src/lib/ai/gemini-provider.ts +++ b/src/lib/ai/gemini-provider.ts @@ -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 { - const prompt = generateSvgAnimationPrompt(questionText, answerText, analysis, figureSvg); + async generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null, language: 'zh' | 'en' = 'zh'): Promise { + 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 || ''; diff --git a/src/lib/ai/openai-provider.ts b/src/lib/ai/openai-provider.ts index 1ecc831d..93b231e0 100644 --- a/src/lib/ai/openai-provider.ts +++ b/src/lib/ai/openai-provider.ts @@ -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 { - const prompt = generateSvgAnimationPrompt(questionText, answerText, analysis, figureSvg); + async generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null, language: 'zh' | 'en' = 'zh'): Promise { + 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')); diff --git a/src/lib/ai/prompts.ts b/src/lib/ai/prompts.ts index 210f1726..7cc4ae64 100644 --- a/src/lib/ai/prompts.ts +++ b/src/lib/ai/prompts.ts @@ -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 动画(、、、)实现,用 begin 属性按时间排列(如 begin="4s");需要先隐藏的元素设 opacity="0" 再用 或 显示。 - 公式不要用 LaTeX,用普通文字和 Unicode 符号(如 x²、√2、π、×、÷、≤、≥、∠、△、⊥、∥)。 @@ -856,16 +857,29 @@ export const DEFAULT_SVG_ANIMATION_TEMPLATE = `【角色与核心任务 (ROLE AN 完整的 SVG 动画 `; +/** 生成 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() || '(无)', diff --git a/src/lib/ai/types.ts b/src/lib/ai/types.ts index 1a2da7e5..d171ad4c 100644 --- a/src/lib/ai/types.ts +++ b/src/lib/ai/types.ts @@ -86,8 +86,8 @@ export interface AIService { analyzeForGeogebra(questionText: string, answerText: string, analysis: string, previousErrors?: string): Promise; /** 只修复各字段中的 LaTeX 语法,返回 AI 修复后的字段内容 */ fixLatex(input: LatexFixInput): Promise; - /** 生成 SVG 动画讲解(已净化),无有效 SVG 时返回 null;figureSvg 为题目配图 */ - generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null): Promise; + /** 生成 SVG 动画讲解(已净化),无有效 SVG 时返回 null;figureSvg 为题目配图,language 决定动画中文字的语言 */ + generateSvgAnimation(questionText: string, answerText: string, analysis: string, figureSvg?: string | null, language?: 'zh' | 'en'): Promise; evaluateMastery(input: MasteryEvaluationInput): Promise; /** 从标签库中选知识点,并评定难度星级 */ suggestKnowledgeTags(input: TagSuggestionInput): Promise; diff --git a/src/lib/translations.ts b/src/lib/translations.ts index 435ffad8..c996cf18 100644 --- a/src/lib/translations.ts +++ b/src/lib/translations.ts @@ -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: "题目文字为空,无法生成动画讲解",