PRINTFILM: AI short-video marketing and AI short-drama creation platform
Add zh/en i18n with browser locale detection and async Celery side jobs.
yi10aea4735c9c
diff --git a/backend/app/api/drama/assets.py b/backend/app/api/drama/assets.pyindex 49666d0..3058f6c 100644--- a/backend/app/api/drama/assets.py+++ b/backend/app/api/drama/assets.py@@ -3,6 +3,7 @@from __future__ import annotationsimport uuid+from datetime import datetime, timezonefrom pathlib import Pathfrom fastapi import APIRouter, Depends, File, HTTPException, UploadFile@@ -15,6 +16,7 @@ from app.models import Userfrom app.models_drama import DramaAssetfrom app.schemas_drama import DramaAssetCreate, DramaAssetOut, DramaAssetUpdate, SeedAssetsFromScriptOutfrom app.services.drama.access import get_owned_drama_project+from app.services.drama.jobs import dispatch_seed_assets_jobfrom app.services.drama.seed import seed_assets_from_scriptrouter = APIRouter()@@ -204,6 +206,33 @@ async def seed_assets(user: User = Depends(get_current_user),) -> SeedAssetsFromScriptOut:project = await get_owned_drama_project(db, project_id, user, with_script=True)+ heavy = bool(refresh_prompts or reextract_props)++ if heavy:+ params = dict(project.params or {}) if isinstance(project.params, dict) else {}+ if str(params.get("assets_seed_status") or "") == "generating":+ raise HTTPException(status_code=409, detail="资产抽取进行中,请稍候")+ params["assets_seed_status"] = "generating"+ params["assets_seed_generating_at"] = datetime.now(timezone.utc).isoformat()+ params.pop("assets_seed_error", None)+ project.params = params+ await db.commit()+ dispatch_seed_assets_job(+ project_id,+ refresh_prompts=refresh_prompts,+ reextract_props=reextract_props,+ )+ existing = list(+ (await db.execute(select(DramaAsset).where(DramaAsset.project_id == project.id)))+ .scalars()+ .all()+ )+ return SeedAssetsFromScriptOut(+ assets=[DramaAssetOut.model_validate(a) for a in existing],+ status="generating",+ message="资产抽取任务已提交,请稍候刷新",+ )+try:result = await seed_assets_from_script(db,@@ -221,4 +250,5 @@ async def seed_assets(prompts_refreshed=result.prompts_refreshed,props_updated=result.props_updated,llm_errors=result.llm_errors,+ status="done",)diff --git a/backend/app/api/projects.py b/backend/app/api/projects.pyindex d2d8ef7..c07b179 100644--- a/backend/app/api/projects.py+++ b/backend/app/api/projects.py@@ -87,6 +87,20 @@ async def _get_owned_project(db: AsyncSession, project_id: int, user: User) -> Preturn project+def _ensure_side_task_allowed(project: Project) -> None:+ """重绘/重生/合成侧任务:流水线进行中时拒绝,避免与 Celery pipeline 冲突。"""+ running = {+ ProjectStatus.SCRIPTING,+ ProjectStatus.IMAGING,+ ProjectStatus.VIDEOING,+ ProjectStatus.AUDIOING,+ ProjectStatus.COMPOSING,+ ProjectStatus.AUDITING,+ }+ if project.status in running:+ raise HTTPException(status_code=409, detail="生成进行中,请稍后")++@router.post("/projects", response_model=ProjectOut)async def create_project(body: ProjectCreate,@@ -672,67 +686,63 @@ async def update_shot(return shot[email protected]("/projects/{project_id}/shots/{shot_id}/regen-image", response_model=ShotOut)[email protected]("/projects/{project_id}/shots/{shot_id}/regen-image", response_model=ProjectOut)async def regen_image(project_id: int,shot_id: int,db: AsyncSession = Depends(get_db),user: User = Depends(get_current_user),-) -> Shot:- await _get_owned_project(db, project_id, user)- try:- await pipeline.regen_shot_image(project_id, shot_id)- except ValueError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- except Exception as exc: # noqa: BLE001- msg = str(exc)- if "PolicyViolation" in msg or "SensitiveContent" in msg:- raise HTTPException(- status_code=400,- detail="画面提示词触发内容安全策略,请编辑分镜去掉品牌/人名后重试",- ) from exc- raise HTTPException(status_code=502, detail=msg[:500]) from exc+) -> Project:project = await _get_owned_project(db, project_id, user)- shot = next(s for s in project.shots if s.id == shot_id)- return shot+ _ensure_side_task_allowed(project)+ shot = next((s for s in project.shots if s.id == shot_id), None)+ if not shot:+ raise HTTPException(status_code=404, detail="分镜不存在")+ project.status = ProjectStatus.IMAGING+ project.error_msg = None+ await db.commit()+ pipeline.dispatch_regen_image(project_id, shot_id)+ return await _get_owned_project(db, project_id, user)[email protected]("/projects/{project_id}/shots/{shot_id}/regen-video", response_model=ShotOut)[email protected]("/projects/{project_id}/shots/{shot_id}/regen-video", response_model=ProjectOut)async def regen_video(project_id: int,shot_id: int,db: AsyncSession = Depends(get_db),user: User = Depends(get_current_user),-) -> Shot:- await _get_owned_project(db, project_id, user)- try:- await pipeline.regen_shot_video(project_id, shot_id)- except ValueError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- except Exception as exc: # noqa: BLE001- raise HTTPException(status_code=502, detail=str(exc)[:500]) from exc+) -> Project:project = await _get_owned_project(db, project_id, user)- shot = next(s for s in project.shots if s.id == shot_id)- return shot+ _ensure_side_task_allowed(project)+ if (project.pipeline_mode or "full") == "image_text":+ raise HTTPException(status_code=400, detail="图文模式无需生成 AI 视频,请直接重新合成成片")+ shot = next((s for s in project.shots if s.id == shot_id), None)+ if not shot or not (shot.image_url or shot.image_ark_url):+ raise HTTPException(status_code=400, detail="请先生成该镜画面")+ project.status = ProjectStatus.VIDEOING+ project.error_msg = None+ await db.commit()+ pipeline.dispatch_regen_video(project_id, shot_id)+ return await _get_owned_project(db, project_id, user)[email protected]("/projects/{project_id}/shots/{shot_id}/regen-audio", response_model=ShotOut)[email protected]("/projects/{project_id}/shots/{shot_id}/regen-audio", response_model=ProjectOut)async def regen_audio(project_id: int,shot_id: int,db: AsyncSession = Depends(get_db),user: User = Depends(get_current_user),-) -> Shot:- await _get_owned_project(db, project_id, user)- try:- await pipeline.regen_shot_audio(project_id, shot_id)- except ValueError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- except Exception as exc: # noqa: BLE001- raise HTTPException(status_code=502, detail=str(exc)[:500]) from exc+) -> Project:project = await _get_owned_project(db, project_id, user)- shot = next(s for s in project.shots if s.id == shot_id)- return shot+ _ensure_side_task_allowed(project)+ shot = next((s for s in project.shots if s.id == shot_id), None)+ if not shot:+ raise HTTPException(status_code=404, detail="分镜不存在")+ project.status = ProjectStatus.AUDIOING+ project.error_msg = None+ await db.commit()+ pipeline.dispatch_regen_audio(project_id, shot_id)+ return await _get_owned_project(db, project_id, user)@router.post("/projects/{project_id}/regen-audio", response_model=ProjectOut)@@ -759,12 +769,7 @@ async def regen_all_audio(project.error_msg = Noneproject.final_video_url = Noneawait db.commit()- try:- await pipeline.regen_project_audio_and_compose(project_id)- except ValueError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- except Exception as exc: # noqa: BLE001- raise HTTPException(status_code=502, detail=str(exc)[:500]) from exc+ pipeline.dispatch_regen_project_audio_and_compose(project_id)return await _get_owned_project(db, project_id, user)@@ -793,12 +798,7 @@ async def compose_only(project.progress = 90project.error_msg = Noneawait db.commit()- try:- await pipeline.compose_only(project_id)- except ValueError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- except Exception as exc: # noqa: BLE001- raise HTTPException(status_code=502, detail=str(exc)[:500]) from exc+ pipeline.dispatch_compose_only(project_id)return await _get_owned_project(db, project_id, user)diff --git a/backend/app/api/tools.py b/backend/app/api/tools.pyindex ab92a26..b737f57 100644--- a/backend/app/api/tools.py+++ b/backend/app/api/tools.py@@ -5,6 +5,7 @@ from __future__ import annotationsfrom pathlib import Pathfrom fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile+from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.database import get_db@@ -12,11 +13,12 @@ from app.deps import get_current_userfrom app.models import ToolRun, Userfrom app.schemas_tools import ToolRunListOut, ToolRunOut, ToolRunRecordOut, ToolTaskOutfrom app.services.studio_tools import (+ enqueue_image_tool,get_tool_run,list_tool_runs,persist_tool_run,+ poll_image_tool_task,poll_video_task,- run_image_tool,save_upload,start_video_tool,update_tool_run_task,@@ -28,7 +30,7 @@ IMAGE_TOOLS = {"t2i", "i2i", "i2p", "ecom"}VIDEO_TOOLS = {"t2v", "v2v"}-# 提交独立工具生成(生图同步返回;生视频返回 task_id 供轮询)+# 提交独立工具生成(生图异步 Celery;生视频返回 Seedance task_id 供轮询)@router.post("/run", response_model=ToolRunOut)async def run_tool(tool_id: str = Form(...),@@ -46,6 +48,15 @@ async def run_tool() -> ToolRunOut:tid = (tool_id or "").strip()saved: list[Path] = []+ tool_params = {+ "negative": negative,+ "ratio": ratio,+ "strength": strength,+ "mode": mode,+ "pack": pack,+ "duration": duration,+ "motion": motion,+ }try:for item in files or []:raw = await item.read()@@ -55,7 +66,7 @@ async def run_tool(raise ValueError("单个文件不能超过 40MB")saved.append(save_upload(user.id, raw, item.filename or "upload.bin"))if tid in IMAGE_TOOLS:- data = await run_image_tool(+ data = await enqueue_image_tool(db,user,tool_id=tid,@@ -66,6 +77,7 @@ async def run_tool(mode=mode or None,pack=pack or None,files=saved,+ params=tool_params,)elif tid in VIDEO_TOOLS:data = await start_video_tool(@@ -78,24 +90,16 @@ async def run_tool(motion=motion or None,files=saved,)+ await persist_tool_run(+ db,+ user_id=user.id,+ tool_id=tid,+ prompt=prompt,+ params=tool_params,+ data=data,+ )else:raise ValueError("未知工具")- await persist_tool_run(- db,- user_id=user.id,- tool_id=tid,- prompt=prompt,- params={- "negative": negative,- "ratio": ratio,- "strength": strength,- "mode": mode,- "pack": pack,- "duration": duration,- "motion": motion,- },- data=data,- )await db.commit()except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc@@ -104,7 +108,7 @@ async def run_tool(return ToolRunOut.model_validate(data)-# 查询 Seedance 视频任务状态(单次,不阻塞),并回写创作记录+# 查询工具异步任务(生图 Celery / 生视频 Seedance),并回写创作记录@router.get("/tasks/{task_id}", response_model=ToolTaskOut)async def get_tool_task(task_id: str,@@ -113,8 +117,17 @@ async def get_tool_task() -> ToolTaskOut:if not task_id.strip():raise HTTPException(status_code=400, detail="缺少任务")- data = await poll_video_task(user, task_id.strip())- await update_tool_run_task(db, user.id, task_id.strip(), data)+ tid = task_id.strip()+ row = (+ await db.execute(+ select(ToolRun).where(ToolRun.user_id == user.id, ToolRun.task_id == tid).limit(1)+ )+ ).scalar_one_or_none()+ if row and row.kind == "image":+ data = await poll_image_tool_task(db, user, tid)+ else:+ data = await poll_video_task(user, tid)+ await update_tool_run_task(db, user.id, tid, data)await db.commit()return ToolTaskOut.model_validate(data)diff --git a/backend/app/main.py b/backend/app/main.pyindex 0868c64..7bc260a 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -65,6 +65,8 @@ async def log_requests(request: Request, call_next):msg = f"{request.method} {path} → {response.status_code} ({elapsed_ms:.0f}ms)"if response.status_code >= 400:logger.warning(msg)+ elif elapsed_ms >= 3000:+ logger.warning("SLOW %s", msg)elif is_poll and elapsed_ms < 800:return responseelse:diff --git a/backend/app/schemas_drama.py b/backend/app/schemas_drama.pyindex e01cff0..dcc9ff3 100644--- a/backend/app/schemas_drama.py+++ b/backend/app/schemas_drama.py@@ -68,11 +68,13 @@ class DramaProjectUsageStats(BaseModel):class SeedAssetsFromScriptOut(BaseModel):"""从剧本抽取/刷新资产的结果统计。"""- assets: list[DramaAssetOut]+ assets: list[DramaAssetOut] = Field(default_factory=list)created_count: int = 0prompts_refreshed: int = 0props_updated: int = 0llm_errors: list[str] = Field(default_factory=list)+ status: str = "done"+ message: str | None = Noneclass DramaFragmentOut(BaseModel):diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.pyindex 00bbf59..a62f504 100644--- a/backend/app/services/drama/jobs.py+++ b/backend/app/services/drama/jobs.py@@ -1273,3 +1273,102 @@ async def run_asset_video_job(exc,)return {"ok": False, "error": str(exc)[:500]}+++# ---------- seed assets from script ----------+++async def run_seed_assets_job(+ project_id: int,+ *,+ refresh_prompts: bool = False,+ reextract_props: bool = False,+) -> dict[str, Any]:+ """从剧本抽取/刷新资产(含 LLM 提示词刷新)。"""+ from app.services.drama.seed import seed_assets_from_script++ logger.info(+ "开始抽取漫剧资产 project_id=%s refresh=%s reextract=%s",+ project_id,+ refresh_prompts,+ reextract_props,+ )+ async with AsyncSessionLocal() as db:+ project = await db.get(+ DramaProject,+ project_id,+ options=[selectinload(DramaProject.script)],+ )+ if not project:+ return {"ok": False, "error": "project_not_found"}+ params = dict(project.params or {}) if isinstance(project.params, dict) else {}+ try:+ result = await seed_assets_from_script(+ db,+ project,+ refresh_prompts=refresh_prompts,+ reextract_props=reextract_props,+ )+ params["assets_seed_status"] = "done"+ params.pop("assets_seed_error", None)+ params.pop("assets_seed_generating_at", None)+ params["assets_seed_created"] = result.created_count+ params["assets_seed_refreshed"] = result.prompts_refreshed+ params["assets_seed_props_updated"] = result.props_updated+ if result.llm_errors:+ params["assets_seed_llm_errors"] = result.llm_errors[:20]+ else:+ params.pop("assets_seed_llm_errors", None)+ project.params = params+ await db.commit()+ return {+ "ok": True,+ "created_count": result.created_count,+ "prompts_refreshed": result.prompts_refreshed,+ "props_updated": result.props_updated,+ "llm_errors": result.llm_errors,+ }+ except Exception as exc: # noqa: BLE001+ params["assets_seed_status"] = "failed"+ params["assets_seed_error"] = str(exc)[:500]+ params.pop("assets_seed_generating_at", None)+ project.params = params+ await db.commit()+ logger.exception("抽取漫剧资产失败 project_id=%s", project_id)+ return {"ok": False, "error": str(exc)[:500]}+++def dispatch_seed_assets_job(+ project_id: int,+ *,+ refresh_prompts: bool = False,+ reextract_props: bool = False,+) -> str:+ """投递资产抽取任务;refresh/reextract 等重 LLM 路径走 Celery。"""+ if _use_celery():+ from app.workers.drama_tasks import drama_seed_assets_task++ result = drama_seed_assets_task.apply_async(+ args=[project_id, refresh_prompts, reextract_props],+ queue=DRAMA_QUEUE,+ )+ logger.info(+ "dispatch 抽取资产 → Celery project_id=%s task_id=%s",+ project_id,+ result.id,+ )+ return str(result.id)++ key = _job_key("seed_assets", project_id)+ if key in _running and not _running[key].done():+ logger.info("dispatch 抽取资产 → 进程内已在跑 project_id=%s", project_id)+ return "in-process"+ _running[key] = asyncio.create_task(+ run_seed_assets_job(+ project_id,+ refresh_prompts=refresh_prompts,+ reextract_props=reextract_props,+ )+ )+ logger.info("dispatch 抽取资产 → 进程内新建 project_id=%s", project_id)+ return "in-process"diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.pyindex 67fc223..9dac2df 100644--- a/backend/app/services/pipeline.py+++ b/backend/app/services/pipeline.py@@ -23,7 +23,7 @@ from app.services.ffmpeg_compose import (is_near_silent_audio,probe_duration,)-from app.workers.queues import PIPELINE_QUEUE+from app.workers.queues import PIPELINE_QUEUE, VIDEO_QUEUEfrom app.services.progress import publish_progressfrom app.services import storagefrom app.services.style_lock import (@@ -183,6 +183,124 @@ def _redis_ok() -> bool:return False+# 单镜重生 / 合成等短任务的进程内 fallback(Celery 不可用时)+_regen_tasks: dict[str, asyncio.Task] = {}+++def _dispatch_side_task(+ key: str,+ *,+ celery_task_name: str,+ celery_args: list,+ queue: str,+ coro_factory,+) -> str:+ """投递 Celery 侧任务;Redis 不可用时在 API 进程内 asyncio 执行。"""+ settings = get_settings()+ if settings.use_celery and _redis_ok():+ from app.workers.celery_app import celery_app++ async_result = celery_app.send_task(+ celery_task_name,+ args=celery_args,+ queue=queue,+ )+ return str(async_result.id)++ existing = _regen_tasks.get(key)+ if existing and not existing.done():+ return "in-process"++ async def _runner() -> None:+ try:+ await coro_factory()+ except Exception: # noqa: BLE001+ logger.exception("in-process side task failed key=%s", key)++ _regen_tasks[key] = asyncio.create_task(_runner())+ return "in-process"+++def dispatch_regen_image(project_id: int, shot_id: int) -> str:+ """异步重绘单镜首帧图。"""+ key = f"regen-image:{project_id}:{shot_id}"++ async def _coro() -> None:+ await regen_shot_image(project_id, shot_id)++ return _dispatch_side_task(+ key,+ celery_task_name="app.workers.tasks.regen_image_task",+ celery_args=[project_id, shot_id],+ queue=PIPELINE_QUEUE,+ coro_factory=_coro,+ )+++def dispatch_regen_video(project_id: int, shot_id: int) -> str:+ """异步重生单镜 Seedance 视频。"""+ key = f"regen-video:{project_id}:{shot_id}"++ async def _coro() -> None:+ await regen_shot_video(project_id, shot_id)++ return _dispatch_side_task(+ key,+ celery_task_name="app.workers.tasks.regen_video_task",+ celery_args=[project_id, shot_id],+ queue=VIDEO_QUEUE,+ coro_factory=_coro,+ )+++def dispatch_regen_audio(project_id: int, shot_id: int) -> str:+ """异步重配单镜旁白(整片连贯 TTS)。"""+ key = f"regen-audio:{project_id}:{shot_id}"++ async def _coro() -> None:+ await regen_shot_audio(project_id, shot_id)++ return _dispatch_side_task(+ key,+ celery_task_name="app.workers.tasks.regen_audio_task",+ celery_args=[project_id, shot_id],+ queue=PIPELINE_QUEUE,+ coro_factory=_coro,+ )+++def dispatch_regen_project_audio_and_compose(project_id: int) -> str:+ """异步整片重配音并合成成片。"""+ key = f"regen-all-audio:{project_id}"++ async def _coro() -> None:+ await regen_project_audio_and_compose(project_id)++ return _dispatch_side_task(+ key,+ celery_task_name="app.workers.tasks.regen_audio_compose_task",+ celery_args=[project_id],+ queue=PIPELINE_QUEUE,+ coro_factory=_coro,+ )+++def dispatch_compose_only(project_id: int) -> str:+ """异步仅合成成片(不重跑 AI 阶段)。"""+ key = f"compose:{project_id}"++ async def _coro() -> None:+ await compose_only(project_id)++ return _dispatch_side_task(+ key,+ celery_task_name="app.workers.tasks.compose_only_task",+ celery_args=[project_id],+ queue=PIPELINE_QUEUE,+ coro_factory=_coro,+ )++def _is_image_text(project: Project) -> bool:return (project.pipeline_mode or "full") == "image_text"@@ -1627,12 +1745,24 @@ async def regen_shot_audio(project_id: int, shot_id: int) -> None:project_id, voice=voice, shot_rows=shots, force=True)async with AsyncSessionLocal() as db:- project = await db.get(Project, project_id)+ result = await db.execute(+ select(Project)+ .where(Project.id == project_id)+ .options(selectinload(Project.shots))+ )+ project = result.scalar_one_or_none()shot = await db.get(Shot, shot_id)if shot:shot.version += 1if project:project.final_video_url = None+ shots = list(project.shots or [])+ if _is_image_text(project):+ project.status = ProjectStatus.IMAGE_READY+ elif shots and all(s.video_url for s in shots):+ project.status = ProjectStatus.VIDEO_READY+ else:+ project.status = ProjectStatus.IMAGE_READYawait db.commit()diff --git a/backend/app/services/queue_monitor.py b/backend/app/services/queue_monitor.pyindex f23e25b..9e96f2a 100644--- a/backend/app/services/queue_monitor.py+++ b/backend/app/services/queue_monitor.py@@ -28,6 +28,10 @@ TASK_LABELS: dict[str, str] = {"app.workers.tasks.run_pipeline_task": "科普成片 Pipeline","app.workers.tasks.regen_image_task": "重生成图片","app.workers.tasks.regen_video_task": "重生成视频",+ "app.workers.tasks.regen_audio_task": "重生成配音",+ "app.workers.tasks.regen_audio_compose_task": "重配音并合成",+ "app.workers.tasks.compose_only_task": "拼接成片",+ "app.workers.tasks.tool_image_task": "工具·生图","app.workers.tasks.upload_media_task": "OSS 上传","drama.script_summary": "漫剧·剧本摘要","drama.episode_scripts": "漫剧·分集剧本",@@ -35,6 +39,7 @@ TASK_LABELS: dict[str, str] = {"drama.episode_generate": "漫剧·分集视频","drama.asset_image": "漫剧·资产生图","drama.asset_video": "漫剧·资产视频",+ "drama.seed_assets": "漫剧·抽取资产",}PENDING_SAMPLE_LIMIT = 30diff --git a/backend/app/services/studio_tools.py b/backend/app/services/studio_tools.pyindex e5d606a..8fe18c3 100644--- a/backend/app/services/studio_tools.py+++ b/backend/app/services/studio_tools.py@@ -208,6 +208,177 @@ async def run_image_tool(return {"kind": "image", "urls": [url], "status": "succeeded"}+def _redis_ok() -> bool:+ try:+ import redis++ r = redis.Redis.from_url(+ get_settings().redis_url,+ decode_responses=True,+ socket_connect_timeout=2,+ socket_timeout=2,+ )+ return bool(r.ping())+ except Exception: # noqa: BLE001+ return False+++def _dispatch_tool_image(run_id: int) -> str:+ """投递工具生图 Celery 任务;不可用时在进程内 asyncio 执行。"""+ settings = get_settings()+ if settings.use_celery and _redis_ok():+ from app.workers.tasks import tool_image_task+ from app.workers.queues import PIPELINE_QUEUE++ result = tool_image_task.apply_async(args=[run_id], queue=PIPELINE_QUEUE)+ return str(result.id)+ import asyncio++ asyncio.create_task(execute_image_tool_run(run_id))+ return f"local-{run_id}"+++# 提交生图任务:立即返回 task_id,实际生成在 Celery / 后台执行+async def enqueue_image_tool(+ db: AsyncSession,+ user: User,+ *,+ tool_id: str,+ prompt: str,+ negative: str,+ ratio: str | None,+ strength: str | None,+ mode: str | None,+ pack: str | None,+ files: list[Path],+ params: dict,+) -> dict:+ row = ToolRun(+ user_id=user.id,+ tool_id=tool_id,+ kind="image",+ status="queued",+ prompt=(prompt or "").strip()[:2000],+ params={+ **(params or {}),+ "file_paths": [str(p) for p in files],+ },+ )+ db.add(row)+ await db.flush()+ task_id = _dispatch_tool_image(row.id)+ row.task_id = task_id+ await db.flush()+ return {+ "kind": "image",+ "urls": [],+ "task_id": task_id,+ "status": "queued",+ "message": "生图任务已提交,请稍候",+ "run_id": row.id,+ }+++# Worker / 进程内:执行已入队的生图任务并回写 tool_runs+async def execute_image_tool_run(run_id: int) -> dict:+ from app.database import AsyncSessionLocal++ async with AsyncSessionLocal() as db:+ row = await db.get(ToolRun, run_id)+ if not row:+ return {"ok": False, "error": "run_not_found"}+ if row.status == "succeeded" and row.urls:+ return {"ok": True, "run_id": run_id}++ user = await db.get(User, row.user_id)+ if not user:+ row.status = "failed"+ row.error = "用户不存在"+ await db.commit()+ return {"ok": False, "error": row.error}++ stored = row.params if isinstance(row.params, dict) else {}+ file_paths = [Path(p) for p in stored.get("file_paths") or [] if p]+ row.status = "running"+ await db.commit()++ try:+ data = await run_image_tool(+ db,+ user,+ tool_id=row.tool_id,+ prompt=row.prompt or "",+ negative=str(stored.get("negative") or ""),+ ratio=stored.get("ratio") or None,+ strength=stored.get("strength") or None,+ mode=stored.get("mode") or None,+ pack=stored.get("pack") or None,+ files=file_paths,+ )+ urls = ensure_public_urls(list(data.get("urls") or []))+ row.kind = str(data.get("kind") or "image")+ row.status = str(data.get("status") or "succeeded")+ row.urls = urls+ row.preview_url = urls[0] if urls else row.preview_url+ row.error = None+ await db.commit()+ return {"ok": True, "run_id": run_id, "urls": urls}+ except Exception as exc: # noqa: BLE001+ row.status = "failed"+ row.error = str(exc)[:512]+ await db.commit()+ logger.exception("execute_image_tool_run failed run_id=%s", run_id)+ return {"ok": False, "run_id": run_id, "error": row.error}+++# 轮询生图 Celery 任务(或本地 fallback)状态+async def poll_image_tool_task(db: AsyncSession, user: User, task_id: str) -> dict:+ stmt = select(ToolRun).where(ToolRun.user_id == user.id, ToolRun.task_id == task_id)+ row = (await db.execute(stmt)).scalar_one_or_none()+ if not row:+ return {"status": "failed", "kind": "image", "urls": [], "error": "任务不存在"}++ if row.status == "succeeded":+ row = await hydrate_tool_run_urls(db, row)+ return {"status": "succeeded", "kind": "image", "urls": list(row.urls or [])}+ if row.status == "failed":+ return {+ "status": "failed",+ "kind": "image",+ "urls": [],+ "error": row.error or "生成失败",+ }++ if task_id.startswith("local-"):+ return {"status": "running", "kind": "image", "urls": []}++ try:+ from celery.result import AsyncResult++ from app.workers.celery_app import celery_app++ async_result = AsyncResult(task_id, app=celery_app)+ state = async_result.state or "PENDING"+ if state in {"PENDING", "STARTED", "RETRY"}:+ return {"status": "running", "kind": "image", "urls": []}+ if state == "SUCCESS":+ row = await hydrate_tool_run_urls(db, row)+ if row.status == "succeeded" and row.urls:+ return {"status": "succeeded", "kind": "image", "urls": list(row.urls or [])}+ return {"status": "running", "kind": "image", "urls": []}+ if state == "FAILURE":+ err = str(async_result.result or row.error or "生成失败")[:512]+ if row.status != "failed":+ row.status = "failed"+ row.error = err+ await db.flush()+ return {"status": "failed", "kind": "image", "urls": [], "error": err}+ except Exception: # noqa: BLE001+ logger.exception("poll_image_tool_task celery state failed task=%s", task_id)++ return {"status": "running", "kind": "image", "urls": []}++# 文生视频 / 视频生视频:先出静帧再提交 Seedance,返回 task_idasync def start_video_tool(db: AsyncSession,diff --git a/backend/app/workers/celery_app.py b/backend/app/workers/celery_app.pyindex 57fc9f8..ac4a5ee 100644--- a/backend/app/workers/celery_app.py+++ b/backend/app/workers/celery_app.py@@ -39,6 +39,10 @@ celery_app.conf.update("app.workers.tasks.run_pipeline_task": {"queue": PIPELINE_QUEUE},"app.workers.tasks.regen_image_task": {"queue": PIPELINE_QUEUE},"app.workers.tasks.regen_video_task": {"queue": VIDEO_QUEUE},+ "app.workers.tasks.regen_audio_task": {"queue": PIPELINE_QUEUE},+ "app.workers.tasks.regen_audio_compose_task": {"queue": PIPELINE_QUEUE},+ "app.workers.tasks.compose_only_task": {"queue": PIPELINE_QUEUE},+ "app.workers.tasks.tool_image_task": {"queue": PIPELINE_QUEUE},"app.workers.tasks.upload_media_task": {"queue": OSS_QUEUE},"drama.script_summary": {"queue": DRAMA_QUEUE},"drama.episode_scripts": {"queue": DRAMA_QUEUE},@@ -46,5 +50,6 @@ celery_app.conf.update("drama.episode_generate": {"queue": VIDEO_QUEUE},"drama.asset_image": {"queue": DRAMA_QUEUE},"drama.asset_video": {"queue": VIDEO_QUEUE},+ "drama.seed_assets": {"queue": DRAMA_QUEUE},},)diff --git a/backend/app/workers/drama_tasks.py b/backend/app/workers/drama_tasks.pyindex bb6bf90..30967e1 100644--- a/backend/app/workers/drama_tasks.py+++ b/backend/app/workers/drama_tasks.py@@ -169,3 +169,30 @@ def drama_asset_video_task())return result+++@celery_app.task(name="drama.seed_assets", bind=True, max_retries=1)+def drama_seed_assets_task(+ self,+ project_id: int,+ refresh_prompts: bool = False,+ reextract_props: bool = False,+) -> dict:+ # Celery:从剧本抽取/刷新漫剧资产+ from app.services.drama.jobs import run_seed_assets_job++ logger.info(+ "[Celery] 领取抽取资产任务 project_id=%s refresh=%s task_id=%s",+ project_id,+ refresh_prompts,+ self.request.id,+ )+ result = _run(+ run_seed_assets_job(+ project_id,+ refresh_prompts=refresh_prompts,+ reextract_props=reextract_props,+ )+ )+ logger.info("[Celery] 抽取资产任务结束 project_id=%s result=%s", project_id, result)+ return resultdiff --git a/backend/app/workers/tasks.py b/backend/app/workers/tasks.pyindex 678c575..514a9de 100644--- a/backend/app/workers/tasks.py+++ b/backend/app/workers/tasks.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport asyncioimport logging+from app.models import ProjectStatusfrom app.workers.celery_app import celery_applogger = logging.getLogger(__name__)@@ -29,6 +30,37 @@ def _run(coro):return asyncio.run(_wrapped())+async def _mark_project_failed(project_id: int, message: str) -> None:+ """侧任务失败时写回项目状态,供前端轮询感知。"""+ from app.database import AsyncSessionLocal+ from app.models import Project++ async with AsyncSessionLocal() as db:+ project = await db.get(Project, project_id)+ if not project:+ return+ if project.status in {ProjectStatus.DONE, ProjectStatus.CANCELLED}:+ return+ project.status = ProjectStatus.FAILED+ project.error_msg = (message or "任务失败")[:500]+ await db.commit()+++def _run_side_task(coro_factory, *, project_id: int) -> dict:+ """执行单项目侧任务并在异常时标记 FAILED。"""+ try:+ _run(coro_factory())+ return {"ok": True, "project_id": project_id}+ except Exception as exc: # noqa: BLE001+ msg = str(exc)+ logger.exception("side task failed project=%s: %s", project_id, msg[:400])+ try:+ _run(_mark_project_failed(project_id, msg))+ except Exception: # noqa: BLE001+ logger.exception("mark project failed project=%s", project_id)+ return {"ok": False, "project_id": project_id, "error": msg[:500]}++@celery_app.task(name="app.workers.tasks.run_pipeline_task",bind=True,@@ -115,18 +147,82 @@ def run_pipeline_task(self, project_id: int) -> dict:@celery_app.task(name="app.workers.tasks.regen_image_task")def regen_image_task(project_id: int, shot_id: int) -> dict:+ from app.config import reload_settings+ from app.services.ark import reset_arkfrom app.services.pipeline import regen_shot_image- _run(regen_shot_image(project_id, shot_id))- return {"ok": True}+ reload_settings()+ reset_ark()+ return _run_side_task(+ lambda: regen_shot_image(project_id, shot_id),+ project_id=project_id,+ )@celery_app.task(name="app.workers.tasks.regen_video_task")def regen_video_task(project_id: int, shot_id: int) -> dict:+ from app.config import reload_settings+ from app.services.ark import reset_arkfrom app.services.pipeline import regen_shot_video- _run(regen_shot_video(project_id, shot_id))- return {"ok": True}+ reload_settings()+ reset_ark()+ return _run_side_task(+ lambda: regen_shot_video(project_id, shot_id),+ project_id=project_id,+ )+++@celery_app.task(name="app.workers.tasks.regen_audio_task")+def regen_audio_task(project_id: int, shot_id: int) -> dict:+ from app.config import reload_settings+ from app.services.pipeline import regen_shot_audio++ reload_settings()+ return _run_side_task(+ lambda: regen_shot_audio(project_id, shot_id),+ project_id=project_id,+ )+++@celery_app.task(name="app.workers.tasks.regen_audio_compose_task")+def regen_audio_compose_task(project_id: int) -> dict:+ from app.config import reload_settings+ from app.services.pipeline import regen_project_audio_and_compose++ reload_settings()+ return _run_side_task(+ lambda: regen_project_audio_and_compose(project_id),+ project_id=project_id,+ )+++@celery_app.task(name="app.workers.tasks.compose_only_task")+def compose_only_task(project_id: int) -> dict:+ from app.config import reload_settings+ from app.services.pipeline import compose_only++ reload_settings()+ return _run_side_task(+ lambda: compose_only(project_id),+ project_id=project_id,+ )+++@celery_app.task(name="app.workers.tasks.tool_image_task", bind=True, max_retries=0)+def tool_image_task(self, run_id: int) -> dict:+ """独立工具生图:在 worker 中跑 Seedream + OSS。"""+ from app.config import reload_settings+ from app.services.ark import reset_ark+ from app.services.studio_tools import execute_image_tool_run++ reload_settings()+ reset_ark()+ try:+ return _run(execute_image_tool_run(run_id))+ except Exception as exc: # noqa: BLE001+ logger.exception("tool image task failed run_id=%s", run_id)+ return {"ok": False, "run_id": run_id, "error": str(exc)[:500]}@celery_app.task(diff --git a/frontend/src/App.css b/frontend/src/App.cssindex 2e87912..f50a0c1 100644--- a/frontend/src/App.css+++ b/frontend/src/App.css@@ -17,6 +17,13 @@background: #fff;}+.auth-panel-top {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+}+.auth-panel h1 {font-family: 'Space Grotesk', 'Noto Sans SC', sans-serif;font-size: 2rem;diff --git a/frontend/src/api.ts b/frontend/src/api.tsindex 2589d58..25d228c 100644--- a/frontend/src/api.ts+++ b/frontend/src/api.ts@@ -436,17 +436,17 @@ export const api = {})},regenImage(projectId: number, shotId: number) {- return request<Shot>(`/api/projects/${projectId}/shots/${shotId}/regen-image`, {+ return request<Project>(`/api/projects/${projectId}/shots/${shotId}/regen-image`, {method: 'POST',})},regenVideo(projectId: number, shotId: number) {- return request<Shot>(`/api/projects/${projectId}/shots/${shotId}/regen-video`, {+ return request<Project>(`/api/projects/${projectId}/shots/${shotId}/regen-video`, {method: 'POST',})},regenAudio(projectId: number, shotId: number) {- return request<Shot>(`/api/projects/${projectId}/shots/${shotId}/regen-audio`, {+ return request<Project>(`/api/projects/${projectId}/shots/${shotId}/regen-audio`, {method: 'POST',})},diff --git a/frontend/src/api/drama.ts b/frontend/src/api/drama.tsindex 1c74b8f..61d0e69 100644--- a/frontend/src/api/drama.ts+++ b/frontend/src/api/drama.ts@@ -128,6 +128,8 @@ export type SeedAssetsResult = {prompts_refreshed: numberprops_updated: numberllm_errors: string[]+ status?: string+ message?: string | null}export type DramaFragment = {@@ -302,6 +304,8 @@ export const dramaApi = {prompts_refreshed: result?.prompts_refreshed ?? 0,props_updated: result?.props_updated ?? 0,llm_errors: Array.isArray(result?.llm_errors) ? result.llm_errors : [],+ status: result?.status ?? 'done',+ message: result?.message ?? null,}},diff --git a/frontend/src/components/layout/AppShell.tsx b/frontend/src/components/layout/AppShell.tsxindex 1f1ebd9..8e4cd5c 100644--- a/frontend/src/components/layout/AppShell.tsx+++ b/frontend/src/components/layout/AppShell.tsx@@ -1,5 +1,6 @@import type { ReactNode } from 'react'import { Link } from 'react-router-dom'+import { useI18n } from '../../i18n'import SiteNav, { type NavActive } from './SiteNav'type Props = {@@ -12,6 +13,8 @@ type Props = {}export default function AppShell({ children, active, wide, flush, hideFooter }: Props) {+ const { t } = useI18n()+return (<div className="pf-shell"><SiteNav active={active} />@@ -20,11 +23,11 @@ export default function AppShell({ children, active, wide, flush, hideFooter }:</main>{!hideFooter && !flush ? (<footer className="pf-shell-footer">- <nav className="pf-shell-footer-links" aria-label="页脚链接">- <Link to="/terms">用户协议</Link>- <Link to="/privacy">隐私政策</Link>- <Link to="/contact">联系我们</Link>- <Link to="/help">帮助中心</Link>+ <nav className="pf-shell-footer-links" aria-label={t('footer.links')}>+ <Link to="/terms">{t('footer.terms')}</Link>+ <Link to="/privacy">{t('footer.privacy')}</Link>+ <Link to="/contact">{t('footer.contact')}</Link>+ <Link to="/help">{t('footer.help')}</Link></nav><p>© {new Date().getFullYear()} PRINTFILM. All rights reserved.</p></footer>diff --git a/frontend/src/components/layout/LanguageSwitch.tsx b/frontend/src/components/layout/LanguageSwitch.tsxnew file mode 100644index 0000000..e97c7f7--- /dev/null+++ b/frontend/src/components/layout/LanguageSwitch.tsx@@ -0,0 +1,23 @@+import { LOCALES, type Locale } from '../../i18n/detect'+import { useI18n } from '../../i18n'++/** 顶栏中/英切换:点击后写入偏好,覆盖浏览器语言 */+export default function LanguageSwitch() {+ const { locale, setLocale, t } = useI18n()++ return (+ <div className="pf-nav-lang" role="group" aria-label={t('nav.language')}>+ {LOCALES.map((code: Locale) => (+ <button+ key={code}+ type="button"+ className={locale === code ? 'is-active' : undefined}+ aria-pressed={locale === code}+ onClick={() => setLocale(code)}+ >+ {code === 'zh' ? t('nav.langZh') : t('nav.langEn')}+ </button>+ ))}+ </div>+ )+}diff --git a/frontend/src/components/layout/SiteNav.tsx b/frontend/src/components/layout/SiteNav.tsxindex e79f5b5..bd8fb4d 100644--- a/frontend/src/components/layout/SiteNav.tsx+++ b/frontend/src/components/layout/SiteNav.tsx@@ -8,6 +8,8 @@ import { IconHelp } from '../ui/Icons'import Button from '../ui/Button'import CreateChoiceModal from '../ui/CreateChoiceModal'import { USER_UPDATED_EVENT } from '../../lib/userEvents'+import { useI18n } from '../../i18n'+import LanguageSwitch from './LanguageSwitch'export type NavActive = 'home' | 'drama' | 'kepu' | 'tools' | 'assets' | 'pricing' | 'templates' | 'studio' | 'history'@@ -37,6 +39,7 @@ function normalizeActive(active: NavActive | undefined, pathname: string): NavAcexport default function SiteNav({ active }: Props) {const nav = useNavigate()const location = useLocation()+ const { t } = useI18n()/** user 当前用户* menuOpen 移动端抽屉@@ -80,22 +83,22 @@ export default function SiteNav({ active }: Props) {const centerLinks = (<><NavLink to="/" end className={() => isActive('home')}>- 工作台+ {t('nav.workbench')}</NavLink><NavLink to="/drama" className={() => isActive('drama')}>- 漫剧+ {t('nav.drama')}</NavLink><NavLink to="/history" className={() => isActive('kepu')}>- 科普+ {t('nav.kepu')}</NavLink><NavLink to="/tools" className={() => isActive('tools')}>- 工具+ {t('nav.tools')}</NavLink><NavLink to="/assets" className={() => isActive('assets')}>- 资产+ {t('nav.assets')}</NavLink><NavLink to="/pricing" className={() => isActive('pricing')}>- 定价+ {t('nav.pricing')}</NavLink></>)@@ -105,35 +108,36 @@ export default function SiteNav({ active }: Props) {<div className="pf-nav-left"><BrandMark /></div>- <nav className="pf-nav-center" aria-label="主导航">+ <nav className="pf-nav-center" aria-label={t('nav.main')}>{centerLinks}</nav><div className="pf-nav-right">- <button type="button" className="pf-nav-help-btn" title="帮助中心" onClick={() => nav('/help')}>+ <LanguageSwitch />+ <button type="button" className="pf-nav-help-btn" title={t('nav.helpCenter')} onClick={() => nav('/help')}><IconHelp size={18} className="pf-nav-help-icon" />- <span>帮助</span>+ <span>{t('nav.help')}</span></button>{user ? (<buttontype="button"className="pf-avatar"- title={`${user.nickname} · 个人中心`}+ title={`${user.nickname} · ${t('nav.profile')}`}onClick={() => nav('/settings')}><UserAvatar user={user} size="sm" /></button>) : (<Link to="/auth?next=/" className="pf-link pf-nav-login">- 登录+ {t('nav.login')}</Link>)}<Button variant="lime" size="sm" icon onClick={goCreate}>- 开始创作+ {t('nav.startCreate')}</Button><buttontype="button"className="pf-nav-burger"- aria-label={menuOpen ? '关闭菜单' : '打开菜单'}+ aria-label={menuOpen ? t('nav.closeMenu') : t('nav.openMenu')}aria-expanded={menuOpen}onClick={() => setMenuOpen((v) => !v)}>@@ -143,7 +147,7 @@ export default function SiteNav({ active }: Props) {</button></div>{menuOpen ? (- <div className="pf-nav-drawer" role="dialog" aria-label="移动导航">+ <div className="pf-nav-drawer" role="dialog" aria-label={t('nav.mobileNav')}><nav className="pf-nav-drawer-links">{centerLinks}</nav></div>) : null}diff --git a/frontend/src/components/ui/ComingSoon.tsx b/frontend/src/components/ui/ComingSoon.tsxindex 7aa9a15..96390c5 100644--- a/frontend/src/components/ui/ComingSoon.tsx+++ b/frontend/src/components/ui/ComingSoon.tsx@@ -1,7 +1,10 @@+import { useI18n } from '../../i18n'+type Props = {label?: string}-export default function ComingSoon({ label = '即将推出' }: Props) {- return <span className="pf-coming">{label}</span>+export default function ComingSoon({ label }: Props) {+ const { t } = useI18n()+ return <span className="pf-coming">{label || t('common.comingSoon')}</span>}diff --git a/frontend/src/components/ui/CreateChoiceModal.tsx b/frontend/src/components/ui/CreateChoiceModal.tsxindex 764ff19..60d8cff 100644--- a/frontend/src/components/ui/CreateChoiceModal.tsx+++ b/frontend/src/components/ui/CreateChoiceModal.tsx@@ -1,5 +1,6 @@import { Link, useNavigate } from 'react-router-dom'import { Clapperboard, Video } from 'lucide-react'+import { useI18n } from '../../i18n'import Modal from './Modal'type Props = {@@ -10,6 +11,7 @@ type Props = {/** 开始创作:在漫剧与科普之间选择入口 */export default function CreateChoiceModal({ open, onClose }: Props) {const nav = useNavigate()+ const { t } = useI18n()// 跳转到目标产品并关闭弹层function go(path: string) {@@ -18,28 +20,32 @@ export default function CreateChoiceModal({ open, onClose }: Props) {}return (- <Modal open={open} onClose={onClose} title="开始创作" size="md">+ <Modal open={open} onClose={onClose} title={t('create.title')} size="md"><p className="pf-muted" style={{ marginTop: 0 }}>- 选择一个产品线,进入对应工作流+ {t('create.hint')}</p><div className="pf-create-choice"><button type="button" className="pf-create-choice-card" onClick={() => go('/drama')}><span className="pf-ws-product-icon" aria-hidden><Clapperboard size={24} strokeWidth={1.6} /></span>- <strong>AI 漫剧</strong>- <span className="pf-muted">剧本 · 分集 · 成片</span>+ <strong>{t('create.drama')}</strong>+ <span className="pf-muted">{t('create.dramaHint')}</span></button><button type="button" className="pf-create-choice-card" onClick={() => go('/studio/new')}><span className="pf-ws-product-icon" aria-hidden><Video size={24} strokeWidth={1.6} /></span>- <strong>科普视频</strong>- <span className="pf-muted">分镜流水线出片</span>+ <strong>{t('create.kepu')}</strong>+ <span className="pf-muted">{t('create.kepuHint')}</span></button></div><p className="pf-create-choice-foot">- 也可以先去 <Link to="/tools" onClick={onClose}>工具中心</Link> 浏览独立能力+ {t('create.toolsFootPrefix')}{' '}+ <Link to="/tools" onClick={onClose}>+ {t('create.toolsFootLink')}+ </Link>+ {t('create.toolsFootSuffix') ? ` ${t('create.toolsFootSuffix')}` : ''}</p></Modal>)diff --git a/frontend/src/components/ui/DialogHost.tsx b/frontend/src/components/ui/DialogHost.tsxindex 6f7e47d..40b8114 100644--- a/frontend/src/components/ui/DialogHost.tsx+++ b/frontend/src/components/ui/DialogHost.tsx@@ -14,6 +14,7 @@ import {type DialogRequest,type DialogTone,} from '../../lib/dialog'+import { useI18n } from '../../i18n'// 按弹窗类型与语气返回图标function dialogIcon(kind: DialogRequest['kind'], tone: DialogTone | undefined): LucideIcon {@@ -45,6 +46,7 @@ function acceptRequest(active: DialogRequest, promptValue: string) {}export default function DialogHost() {+ const { t } = useI18n()const req = useSyncExternalStore(subscribeDialog, getDialogRequest, getDialogRequest)const [promptValue, setPromptValue] = useState('')const inputRef = useRef<HTMLInputElement>(null)@@ -82,14 +84,18 @@ export default function DialogHost() {const Icon = dialogIcon(active.kind, tone)const title =active.options.title ||- (active.kind === 'confirm' ? '请确认' : active.kind === 'prompt' ? '请输入' : '提示')+ (active.kind === 'confirm'+ ? t('dialog.confirmTitle')+ : active.kind === 'prompt'+ ? t('dialog.promptTitle')+ : t('dialog.alertTitle'))const message =active.kind === 'prompt' ? active.options.message || '' : active.options.messageconst confirmText =active.kind === 'alert'- ? active.options.confirmText || '知道了'- : active.options.confirmText || '确定'- const cancelText = active.kind === 'alert' ? '' : active.options.cancelText || '取消'+ ? active.options.confirmText || t('dialog.ok')+ : active.options.confirmText || t('dialog.confirm')+ const cancelText = active.kind === 'alert' ? '' : active.options.cancelText || t('dialog.cancel')function onSubmit(e: FormEvent) {e.preventDefault()diff --git a/frontend/src/components/ui/HelpCenter.tsx b/frontend/src/components/ui/HelpCenter.tsxindex f43e6d3..4f9d3e3 100644--- a/frontend/src/components/ui/HelpCenter.tsx+++ b/frontend/src/components/ui/HelpCenter.tsx@@ -1,11 +1,8 @@import { useMemo, useState } from 'react'import { Link } from 'react-router-dom'import Modal from './Modal'-import {- HELP_FAQ_ITEMS,- HELP_GUIDE_STEPS,- filterHelpFaq,-} from '../../lib/helpContent'+import { useI18n } from '../../i18n'+import { filterHelpFaq } from '../../lib/helpContent'type Tab = 'guide' | 'faq' | 'tools'@@ -14,14 +11,9 @@ type Props = {onClose: () => void}-const CATEGORIES = [- { id: 'guide' as const, title: '快速开始', desc: '四步上手创作' },- { id: 'faq' as const, title: '常见问题', desc: '下载 · 生成 · 充值' },- { id: 'tools' as const, title: '工具说明', desc: '文生图与短视频' },-]-/** 帮助中心抽屉(与 /help 页共用文案) */export default function HelpCenter({ open, onClose }: Props) {+ const { t, m } = useI18n()/** tab 当前分区* openFaq 展开的 FAQ@@ -31,43 +23,43 @@ export default function HelpCenter({ open, onClose }: Props) {const [openFaq, setOpenFaq] = useState<number | null>(0)const [q, setQ] = useState('')- const faqFiltered = useMemo(() => filterHelpFaq(HELP_FAQ_ITEMS, q), [q])+ const faqFiltered = useMemo(() => filterHelpFaq([...m.help.faq], q), [m.help.faq, q])return (<Modalopen={open}onClose={onClose}- title="帮助中心"+ title={t('help.title')}variant="drawer"className="pf-help-modal"footer={<><Link to="/help" className="pf-btn pf-btn-ghost pf-btn-sm" onClick={onClose}>- 完整帮助页+ {t('help.fullPage')}</Link><button type="button" className="pf-btn pf-btn-lime pf-btn-sm" onClick={onClose}>- 知道了+ {t('help.gotIt')}</button></>}><div className="pf-help"><label className="pf-help-search">- <span className="sr-only">搜索帮助</span>+ <span className="sr-only">{t('help.search')}</span><inputvalue={q}onChange={(e) => setQ(e.target.value)}- placeholder="搜索指南或常见问题"+ placeholder={t('help.drawerSearch')}/></label><div className="pf-help-cats">- {CATEGORIES.map((c) => (+ {m.help.drawerCats.map((c) => (<buttonkey={c.id}type="button"className={`pf-help-cat${tab === c.id ? ' is-active' : ''}`}- onClick={() => setTab(c.id)}+ onClick={() => setTab(c.id as Tab)}><strong>{c.title}</strong><span>{c.desc}</span>@@ -77,7 +69,7 @@ export default function HelpCenter({ open, onClose }: Props) {{tab === 'guide' ? (<ol className="pf-help-steps">- {HELP_GUIDE_STEPS.map((s) => (+ {m.help.steps.map((s) => (<li key={s.n}><span className="pf-help-step-n" aria-hidden>{s.n}@@ -110,21 +102,19 @@ export default function HelpCenter({ open, onClose }: Props) {</div>)})}- {faqFiltered.length === 0 ? <p className="pf-muted">没有匹配的问题</p> : null}+ {faqFiltered.length === 0 ? <p className="pf-muted">{t('help.noFaq')}</p> : null}</div>) : null}{tab === 'tools' ? (<div className="pf-help-tools-note">- <p>- 工具中心已开放文生图、图生图、图生产品、文生视频、视频生视频与电商拼图。生成结果会保存到云端,并在个人中心「工具创作」中支持查看与下载。- </p>+ <p>{t('help.toolsNote')}</p><div className="pf-help-tools-actions"><Link to="/tools" className="pf-btn pf-btn-lime pf-btn-sm" onClick={onClose}>- 打开工具+ {t('help.openTools')}</Link><Link to="/settings?tab=tools" className="pf-btn pf-btn-ghost pf-btn-sm" onClick={onClose}>- 创作记录+ {t('help.toolRecords')}</Link></div></div>diff --git a/frontend/src/components/ui/Modal.tsx b/frontend/src/components/ui/Modal.tsxindex d6ea76f..db723e2 100644--- a/frontend/src/components/ui/Modal.tsx+++ b/frontend/src/components/ui/Modal.tsx@@ -1,5 +1,6 @@import { useEffect, type ReactNode } from 'react'import { createPortal } from 'react-dom'+import { useI18n } from '../../i18n'type ModalProps = {open: boolean@@ -28,6 +29,7 @@ export default function Modal({footer,className = '',}: ModalProps) {+ const { t } = useI18n()useEffect(() => {if (!open) returnconst prev = document.body.style.overflow@@ -70,13 +72,13 @@ export default function Modal({.join(' ')}role="dialog"aria-modal="true"- aria-label={title || '对话框'}+ aria-label={title || t('common.dialog')}>{title ? (<header className="pf-modal-head"><h3>{title}</h3>{dismissible ? (- <button type="button" className="pf-modal-close" onClick={onClose} aria-label="关闭">+ <button type="button" className="pf-modal-close" onClick={onClose} aria-label={t('common.close')}>×</button>) : null}diff --git a/frontend/src/components/ui/Pagination.tsx b/frontend/src/components/ui/Pagination.tsxindex 61232d5..2757af3 100644--- a/frontend/src/components/ui/Pagination.tsx+++ b/frontend/src/components/ui/Pagination.tsx@@ -1,5 +1,6 @@import { cn } from '../../lib/cn'import { DEFAULT_PAGE_SIZE_OPTIONS } from '../../lib/pagination'+import { useI18n } from '../../i18n'type Props = {page: number@@ -43,9 +44,11 @@ export default function Pagination({pageSizeOptions = DEFAULT_PAGE_SIZE_OPTIONS,onPageSizeChange,className,- ariaLabel = '分页',+ ariaLabel,showSummary = true,}: Props) {+ const { t } = useI18n()+ const navLabel = ariaLabel || t('common.pagination')const sizeOptions = onPageSizeChange ? pageSizeOptions : undefinedconst canPickSize = Boolean(sizeOptions?.length && pageSize && onPageSizeChange)const showNav = pageCount > 1@@ -54,12 +57,14 @@ export default function Pagination({if (!showNav && !canPickSize && !summaryVisible) return nullconst items = buildPageItems(page, pageCount)+ const pageSizeBefore = t('common.pageSizeBefore')+ const pageSizeAfter = t('common.pageSizeAfter')return (<div className={cn('pf-list-pagination', className)}>{summaryVisible ? (<p className="pf-list-pagination-summary">- 第 {page} / {pageCount} 页 · 共 {total} 条+ {t('common.pageSummary', { page, pageCount, total: total ?? 0 })}</p>) : null}@@ -67,10 +72,10 @@ export default function Pagination({<div className="pf-list-pagination-bar">{canPickSize ? (<label className="pf-page-size">- <span>每页</span>+ {pageSizeBefore ? <span>{pageSizeBefore}</span> : null}<selectvalue={pageSize}- aria-label="每页条数"+ aria-label={t('common.pageSize')}onChange={(e) => onPageSizeChange?.(Number(e.target.value))}>{sizeOptions!.map((n) => (@@ -79,17 +84,17 @@ export default function Pagination({</option>))}</select>- <span>条</span>+ {pageSizeAfter ? <span>{pageSizeAfter}</span> : null}</label>) : null}{showNav ? (- <nav className="pf-pagination" aria-label={ariaLabel}>+ <nav className="pf-pagination" aria-label={navLabel}><buttontype="button"className="pf-page-btn"disabled={page <= 1}- aria-label="上一页"+ aria-label={t('common.prevPage')}onClick={() => onChange(Math.max(1, page - 1))}>‹@@ -115,7 +120,7 @@ export default function Pagination({type="button"className="pf-page-btn"disabled={page >= pageCount}- aria-label="下一页"+ aria-label={t('common.nextPage')}onClick={() => onChange(Math.min(pageCount, page + 1))}>›diff --git a/frontend/src/i18n/context.tsx b/frontend/src/i18n/context.tsxnew file mode 100644index 0000000..1f6cd94--- /dev/null+++ b/frontend/src/i18n/context.tsx@@ -0,0 +1,63 @@+import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'+import { applyLocale, detectLocale, type Locale } from './detect'+import { interpolate, lookupMessage, type TVars } from './lookup'+import { messages, type Messages } from './messages'++export type TFunction = (path: string, vars?: TVars) => string++type I18nValue = {+ locale: Locale+ setLocale: (next: Locale) => void+ t: TFunction+ m: Messages+}++const I18nContext = createContext<I18nValue | null>(null)++// 同步 document title / description+function syncDocumentMeta(m: Messages) {+ if (typeof document === 'undefined') return+ document.title = m.meta.title+ const desc = document.querySelector('meta[name="description"]')+ if (desc) desc.setAttribute('content', m.meta.description)+}++/** 全站语言:浏览器自动识别,手动选择后写入 localStorage */+export function I18nProvider({ children }: { children: ReactNode }) {+ const [locale, setLocaleState] = useState<Locale>(() => {+ const next = detectLocale()+ applyLocale(next, false)+ return next+ })++ const m = messages[locale]++ useEffect(() => {+ applyLocale(locale, false)+ syncDocumentMeta(m)+ }, [locale, m])++ const setLocale = useCallback((next: Locale) => {+ applyLocale(next, true)+ setLocaleState(next)+ }, [])++ const t = useCallback<TFunction>(+ (path, vars) => {+ const raw = lookupMessage(m, path)+ if (!raw) return path+ return interpolate(raw, vars)+ },+ [m],+ )++ const value = useMemo(() => ({ locale, setLocale, t, m }), [locale, setLocale, t, m])++ return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>+}++export function useI18n(): I18nValue {+ const ctx = useContext(I18nContext)+ if (!ctx) throw new Error('useI18n must be used within I18nProvider')+ return ctx+}diff --git a/frontend/src/i18n/detect.ts b/frontend/src/i18n/detect.tsnew file mode 100644index 0000000..d555598--- /dev/null+++ b/frontend/src/i18n/detect.ts@@ -0,0 +1,83 @@+/** 浏览器语言检测、本地覆盖与 html lang 同步 */++export type Locale = 'zh' | 'en'++export const LOCALES: Locale[] = ['zh', 'en']++export const LOCALE_STORAGE_KEY = 'printfilm.locale'++export const LOCALE_HTML: Record<Locale, string> = {+ zh: 'zh-CN',+ en: 'en',+}++export const LOCALE_DATE: Record<Locale, string> = {+ zh: 'zh-CN',+ en: 'en-US',+}++// 当前生效语言(供非 React 工具函数读取)+let activeLocale: Locale = 'zh'++// 是否为已支持的语言代码+export function isLocale(value: unknown): value is Locale {+ return value === 'zh' || value === 'en'+}++// 从 Accept-Language / navigator 映射到 zh 或 en+export function localeFromBrowser(lang?: string): Locale {+ const raw = (lang || '').trim().toLowerCase()+ return raw.startsWith('zh') ? 'zh' : 'en'+}++// 读取用户手动选择;无记录则返回 null(跟随浏览器)+export function readStoredLocale(): Locale | null {+ try {+ const raw = localStorage.getItem(LOCALE_STORAGE_KEY)+ return isLocale(raw) ? raw : null+ } catch {+ return null+ }+}++// 首次进入:有手动选择用手动,否则跟浏览器+export function detectLocale(): Locale {+ const stored = typeof window === 'undefined' ? null : readStoredLocale()+ if (stored) return stored+ if (typeof navigator === 'undefined') return 'zh'+ const hint = navigator.language || navigator.languages?.[0] || 'zh'+ return localeFromBrowser(hint)+}++export function getActiveLocale(): Locale {+ return activeLocale+}++// 应用语言:写 html lang;persist 时才写入 localStorage+export function applyLocale(locale: Locale, persist: boolean): void {+ activeLocale = locale+ if (persist) {+ try {+ localStorage.setItem(LOCALE_STORAGE_KEY, locale)+ } catch {+ /* ignore quota / private mode */+ }+ }+ if (typeof document !== 'undefined') {+ document.documentElement.lang = LOCALE_HTML[locale]+ }+}++// 日期时间按当前语言格式化+export function formatDateTime(value?: string | Date | null, locale: Locale = activeLocale): string {+ if (!value) return '—'+ const d = value instanceof Date ? value : new Date(value)+ if (Number.isNaN(d.getTime())) return '—'+ return d.toLocaleString(LOCALE_DATE[locale], {+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ })+}diff --git a/frontend/src/i18n/index.ts b/frontend/src/i18n/index.tsnew file mode 100644index 0000000..815e452--- /dev/null+++ b/frontend/src/i18n/index.ts@@ -0,0 +1,11 @@+export { I18nProvider, useI18n, type TFunction } from './context'+export {+ applyLocale,+ detectLocale,+ formatDateTime,+ getActiveLocale,+ isLocale,+ localeFromBrowser,+ type Locale,+} from './detect'+export { messages, type Messages } from './messages'diff --git a/frontend/src/i18n/locales/en.ts b/frontend/src/i18n/locales/en.tsnew file mode 100644index 0000000..8111fe8--- /dev/null+++ b/frontend/src/i18n/locales/en.ts@@ -0,0 +1,7 @@+import { enPages } from './en/pages'+import { enShell } from './en/shell'++export const en = {+ ...enShell,+ ...enPages,+}diff --git a/frontend/src/i18n/locales/en/pages.ts b/frontend/src/i18n/locales/en/pages.tsnew file mode 100644index 0000000..ae60899--- /dev/null+++ b/frontend/src/i18n/locales/en/pages.ts@@ -0,0 +1,461 @@+/** 英文:首页、帮助、联系、工具、定价、历史、漫剧列表 */++export const enPages = {+ home: {+ headlineBefore: 'Turn stories into',+ headlineEm: 'films you can play',+ lede: 'AI drama from script to episodic film. Explainer videos from storyboard to voice and compose. One studio, two ways to ship.',+ startCreate: 'Start creating',+ browseTools: 'Browse tools',+ products: 'Products',+ dramaTitle: 'AI Drama',+ dramaFor: 'For short-drama makers',+ dramaDesc: 'Generate a script from one line, lock characters and scenes, then board each episode.',+ kepuTitle: 'Explainer video',+ kepuFor: 'For knowledge creators',+ kepuDesc: 'Pick a look, write narration boards, and run the pipeline to a short explainer.',+ howKicker: 'How it works',+ howTitle: 'Three steps to a film',+ capsKicker: 'Capabilities',+ capsTitle: 'What the studio actually does',+ toolsKicker: 'Tools',+ toolsTitle: 'One-shot creation tools',+ allTools: 'All tools →',+ whoKicker: 'For',+ whoTitle: 'Who it’s for',+ closeTitle: 'Start from one idea',+ closeLead: 'Sign in, pick Drama or Explainers, and enter the matching workspace.',+ viewPricing: 'View pricing',+ footBrand: 'AI drama and explainer video studio',+ footNav: 'Footer',+ dramaSteps: ['AI script', 'Cast & scenes', 'Episode boards', 'Export'],+ kepuSteps: ['Pick a style', 'Write boards', 'Voice & compose', 'Batch output'],+ pipeline: [+ { step: '01', title: 'Write the idea', desc: 'A one-line story, a knowledge point, or a full script — any of these can start a project.' },+ { step: '02', title: 'Build assets', desc: 'Characters, scenes, props, and voices stay consistent across later shots.' },+ { step: '03', title: 'Board and ship', desc: 'Split episodes, cite assets, generate stills and video, then export a playable film.' },+ ],+ capabilities: [+ { title: '19 film looks', desc: 'From mythic epics to urban realism and neon cyberpunk — one style carries the whole piece.' },+ { title: 'Reusable assets', desc: 'Generate a character once, reuse it across the series instead of redrawing every shot.' },+ { title: 'Editable boards', desc: '@-mention assets, set duration and camera moves, and see the shot before you generate.' },+ { title: 'Two output paths', desc: 'Drama for episodic stories, explainers for storyboard pipelines — one account and one wallet.' },+ ],+ audiences: [+ { title: 'Short-drama creators', desc: 'Break a story into shootable episodes. Assets first, film second.' },+ { title: 'Knowledge creators', desc: 'Turn articles into vertical explainers with a consistent look and pace.' },+ { title: 'Small teams', desc: 'Keep projects, assets, and history in one place instead of hopping tools.' },+ ],+ },+ help: {+ title: 'Help center',+ lead: 'Search a problem, or jump in from a category below',+ search: 'Search help',+ searchPlaceholder: 'Search: download, tools, top-up, drama…',+ guideTitle: 'Four steps to start',+ faqTitle: 'FAQ',+ noMatch: 'No matching questions. Try “download”, “tools”, or “top-up”.',+ morePrefix: 'See projects and runs in',+ profile: 'your account',+ moreMid: ', or',+ pricing: 'add credits',+ moreMid2: '. You can also read the',+ terms: 'Terms',+ privacy: 'Privacy Policy',+ moreOr: ', or',+ contact: 'contact us',+ moreSuffix: '.',+ fullPage: 'Full help page',+ gotIt: 'Got it',+ drawerSearch: 'Search guides or FAQ',+ noFaq: 'No matching questions',+ cats: [+ { id: 'start', title: 'Quick start', desc: 'Pick a product on Home', href: '/' },+ { id: 'drama', title: 'Drama', desc: 'Script · episodes · film', href: '/drama' },+ { id: 'kepu', title: 'Explainers', desc: 'Storyboard pipeline', href: '/history' },+ { id: 'tools', title: 'Tools', desc: 'Text-to-image / video', href: '/tools' },+ { id: 'settings', title: 'Account', desc: 'Projects · runs · downloads', href: '/settings?tab=tools' },+ { id: 'billing', title: 'Billing', desc: 'Pay as you go, no expiry', href: '/pricing' },+ ],+ steps: [+ {+ n: '01',+ title: 'Choose an entry',+ body: 'Open AI Drama or Explainer video from Home. For a single image or clip, use Tools in the top nav.',+ },+ {+ n: '02',+ title: 'Configure and generate',+ body: 'Drama: idea → outline → assets → episodes. Explainers: topic → style → boards → film. Tools: fill a prompt or upload media, then generate.',+ },+ {+ n: '03',+ title: 'Review and iterate',+ body: 'Regenerate a still, clip, or voice track without remaking the whole film. Tool results can be previewed and run again.',+ },+ {+ n: '04',+ title: 'Save and download',+ body: 'Outputs land in cloud storage. Explainers download from History; drama from the project workspace; tool runs from Account.',+ },+ ],+ faq: [+ {+ q: 'Where should I start?',+ a: 'Open Home and pick AI Drama or Explainer video. Drama is for episodic stories and character consistency; explainers are a short-video storyboard pipeline. For a single image or clip, go to Tools.',+ },+ {+ q: 'What’s the difference between AI video and stills-to-film?',+ a: 'AI video has stronger motion and costs more. Stills-to-film (image + narration) is faster and more stable for explainers. Choose when you create a new explainer project.',+ },+ {+ q: 'Can I leave the page while it generates?',+ a: 'Yes. Jobs keep running on the server. Check explainer History, the drama project workspace, or Account for tool-run status. For in-page video tools, staying until it finishes is safer.',+ },+ {+ q: 'What can the tool hub do?',+ a: 'Text-to-image, image-to-image, product shots, text-to-video, video-to-video, and e-commerce collages. Sign in, pick a tool, then prompt or upload.',+ },+ {+ q: 'Where are tool results stored?',+ a: 'Each successful run is saved, and media syncs to object storage. Open your avatar → Account → Tool runs to see covers, status, and prompts.',+ },+ {+ q: 'How do I view or download tool results?',+ a: 'In Account → Tool runs, use View to preview and Download to save from the cloud URL. The tool page also links back to Account after a success.',+ },+ {+ q: 'Where do I download finished films or assets?',+ a: 'Explainers: History in the top nav. Drama: the project workspace. Global assets: Assets in the top nav.',+ },+ {+ q: 'What’s in Account?',+ a: 'Profile, drama projects, explainer history, tool runs, asset library entry, and plan & balance. Team, API, and notifications are still in progress.',+ },+ {+ q: 'How do top-ups and charges work?',+ a: 'Open Pricing, pick a pack, and pay with Alipay or WeChat. Usage is metered; balance never expires and there is no forced subscription.',+ },+ {+ q: 'Generation failed or the image is off?',+ a: 'Tweak the prompt, negative prompt, or reference image and retry. Drama and explainers support per-shot regen. Check network and balance; safety filters may block sensitive content.',+ },+ ],+ drawerCats: [+ { id: 'guide', title: 'Quick start', desc: 'Four steps to create' },+ { id: 'faq', title: 'FAQ', desc: 'Download · generate · billing' },+ { id: 'tools', title: 'Tools', desc: 'Images and short video' },+ ],+ toolsNote:+ 'The tool hub includes text-to-image, image-to-image, product shots, text-to-video, video-to-video, and e-commerce collages. Results are stored in the cloud and can be viewed or downloaded under Account → Tool runs.',+ openTools: 'Open tools',+ toolRecords: 'Run history',+ },+ contact: {+ crumb: 'Contact',+ title: 'Contact us',+ introPrefix: 'For billing, accounts, jobs, or partnerships, reach us below. You can also check the',+ introLink: 'help center',+ introSuffix: ' first.',+ formTitle: 'Send feedback',+ formLead: 'Submit opens your mail client with a draft to [email protected]. Please send it after you review.',+ topic: 'Topic',+ email: 'Your email',+ emailPlaceholder: 'So we can reply',+ message: 'Details',+ messagePlaceholder: 'Include account email, order ID, time, and any error text',+ submit: 'Open email draft',+ sentPrefix: 'If the mail app did not open, email us at',+ related: 'Related',+ pricing: 'Pricing',+ contactAction: 'Contact',+ goAction: 'Open',+ mailSubject: 'Topic: {topic}',+ mailEmail: 'Contact email: {email}',+ mailEmailEmpty: '(not provided)',+ mailEmpty: '(no details)',+ channels: [+ {+ title: 'Email support',+ desc: 'We usually reply in 1–2 business days. Please include your account email and order ID if you have one.',+ href: 'mailto:[email protected]',+ actionLabel: '[email protected]',+ },+ {+ title: 'Help center',+ desc: 'Billing, downloads, drama, and tools are covered in self-serve help.',+ href: '/help',+ actionLabel: 'Go to help',+ },+ {+ title: 'Enterprise / wire transfer',+ desc: 'For bulk credits, API partnerships, or invoices, email your company name and request.',+ href: 'mailto:[email protected]?subject=PRINTFILM%20Enterprise',+ actionLabel: 'Email partnerships',+ },+ ],+ topics: [+ 'Account & sign-in',+ 'Top-up & arrival',+ 'Generation issues',+ 'Downloads & media',+ 'Privacy & account deletion',+ 'Other',+ ],+ },+ tools: {+ title: 'AI creation tools',+ lead: 'Open a tool workspace to generate images and short video.',+ goDrama: 'Go to Drama',+ goDramaHint: 'Script · episodes · film',+ goKepu: 'Explainer history',+ goKepuHint: 'Storyboard pipeline',+ generating: 'Generating…',+ generatingVideo: 'Generating video…',+ generatingShort: 'Generating',+ generatingVideoShort: 'Generating video',+ savedPrefix: 'Saved. View it in',+ savedLink: 'Account · Tool runs',+ savedSuffix: '',+ allTools: 'All tools',+ uploadHint: 'Click or drag to upload',+ filesSelected: '{count} file(s) selected',+ inputPlaceholder: 'Enter {label}…',+ resultArea: 'Results',+ resultEmpty: 'Preview area',+ resultEmptyHint: 'Output will appear here when ready',+ videoWaitHint: 'Usually 1–3 minutes — you can stay on this page',+ imageWaitHint: 'Images usually take about 20–40 seconds',+ previewAlt: 'Still preview',+ resultAlt: 'Generated output',+ downloadVideo: 'Download video',+ downloadImage: 'Download image',+ errors: {+ fillPrompt: 'Please enter a prompt',+ uploadRef: 'Please upload a reference image',+ fillScript: 'Please enter a video script',+ uploadSource: 'Please upload a source video or first frame',+ uploadProduct: 'Please upload a product image',+ uploadTwoImages: 'Upload at least 2 images for a collage',+ videoFailed: 'Video generation failed',+ pollFailed: 'Could not refresh task status',+ generateFailed: 'Generation failed',+ notLoggedIn: 'Not signed in',+ },+ items: {+ t2i: {+ title: 'Text to image',+ desc: 'Describe a scene and generate a still',+ panelHint: 'Describe the frame, pick an aspect ratio, then generate.',+ cta: 'Generate',+ fields: {+ prompt: { label: 'Prompt', placeholder: 'Subject, scene, light, and style…' },+ negative: { label: 'Negative prompt', placeholder: 'What to avoid, e.g. text, watermark…' },+ ratio: { label: 'Aspect ratio' },+ },+ },+ i2i: {+ title: 'Image to image',+ desc: 'Upload a reference and generate a matching variant',+ panelHint: 'Upload a reference and describe what to keep or change.',+ cta: 'Generate',+ fields: {+ ref: { label: 'Reference' },+ prompt: { label: 'Prompt', placeholder: 'Keep the subject, night cinematic lighting…' },+ strength: { label: 'Similarity' },+ },+ },+ i2p: {+ title: 'Product shots',+ desc: 'White-background and lifestyle product images',+ panelHint: 'Upload a product photo, then pick white, scene, or long-detail.',+ cta: 'Generate product shot',+ fields: {+ product: { label: 'Product image' },+ mode: { label: 'Output' },+ prompt: { label: 'Extra notes (optional)', placeholder: 'Material, placement, setting…' },+ },+ },+ t2v: {+ title: 'Text to video',+ desc: 'Turn a script into a short clip',+ panelHint: 'Write a script, generate a still first, then a short video (about 1–3 min).',+ cta: 'Generate video',+ fields: {+ script: { label: 'Script', placeholder: 'Camera move, action, and mood…' },+ duration: { label: 'Duration' },+ ratio: { label: 'Aspect ratio' },+ },+ },+ v2v: {+ title: 'Video to video',+ desc: 'Restyle motion and look of an existing clip',+ panelHint: 'Upload a source video or first frame, then describe style and motion.',+ cta: 'Transform',+ fields: {+ source: { label: 'Source / first frame' },+ prompt: { label: 'Transform', placeholder: 'Cyberpunk night, slow push-in…' },+ motion: { label: 'Motion' },+ },+ },+ ecom: {+ title: 'E-commerce tools',+ desc: 'Hero collages, detail layouts, and selling posters',+ panelHint: 'Collage needs at least 2 images. Selling posters need 1 product photo.',+ cta: 'Start',+ fields: {+ pack: { label: 'Tool' },+ images: { label: 'Images' },+ prompt: { label: 'Selling points (poster, optional)', placeholder: 'Material and use case…' },+ },+ },+ },+ chips: {+ 低: 'Low',+ 中: 'Medium',+ 高: 'High',+ 弱: 'Subtle',+ 强: 'Strong',+ 白底图: 'White bg',+ 场景图: 'Lifestyle',+ 详情长图: 'Long detail',+ 主图拼接: 'Hero collage',+ 详情排版: 'Detail layout',+ 卖点海报: 'Selling poster',+ },+ },+ pricing: {+ title: 'Pay as you go',+ lead: 'Metered by actual token use. Credits never expire.',+ featInstant: 'Credits are ready as soon as payment lands',+ featSafe: 'Secure payments',+ featForever: 'Balance never expires',+ guestPrefix: '',+ guestLogin: 'Sign in',+ guestSuffix: ' to see balance and this month’s usage',+ paidHint: 'Payment complete. If the balance is stale, refresh in a moment.',+ paidOk: 'Payment succeeded. Balance updated.',+ orderFailed: 'Could not create the order',+ payMethods: 'Payment methods',+ paySafe: 'Secure payments',+ alipay: 'Alipay',+ wechat: 'WeChat Pay',+ recommended: 'Recommended',+ unionpay: 'UnionPay',+ transfer: 'Wire transfer',+ enterprise: 'Enterprise',+ soonTitle: 'Coming soon',+ transferTitle: 'Contact support for enterprise billing',+ unavailable: '{label} is coming soon. Please use Alipay or WeChat Pay.',+ chooseAmount: 'Choose an amount',+ credit: 'You receive',+ bonus: 'Bonus ¥{amount}',+ foreverHint: 'Balance never expires',+ ordering: 'Creating order…',+ payNow: 'Top up',+ billingTitle: 'How billing works',+ billing1: 'Storyboard, stills, voice, and AI video are billed from upstream token use',+ billing2: 'We pre-authorize an estimate, then settle the real usage (refund or top-up the difference)',+ billing3: 'Image+narration is cheaper; turning on AI motion video costs more',+ whyTitle: 'Why metered billing',+ why1: 'No subscription — pay for what you use',+ why2: 'Credits never expire',+ why3: 'Every call is itemized and traceable',+ footBrand: 'AI short-video studio',+ skus: {+ topup_10: 'Starter',+ topup_49: 'Basic',+ topup_99: 'Plus',+ topup_199: 'Pro',+ },+ skuHints: {+ topup_10: 'Try the product',+ topup_49: 'Everyday creating',+ topup_99: 'Best for frequent use',+ topup_199: 'Teams / batch jobs',+ },+ walletBalance: 'Available',+ hideBalance: 'Hide balance',+ showBalance: 'Show balance',+ history: 'Top-up history',+ loginFirst: 'Sign in first',+ monthCharge: 'This period',+ currentPlan: 'Plan',+ frozen: 'On hold ¥{amount}',+ updatedAt: 'Updated {time}',+ },+ history: {+ title: 'Explainer history',+ lead: 'Manage explainer projects — keep editing or download the film.',+ newKepu: 'New explainer',+ goDrama: 'Go to Drama',+ statTotal: 'Projects',+ statRunning: 'In progress',+ runningNow: 'Generating now',+ noTask: 'No active jobs',+ statDone: 'Done',+ statDuration: 'This month',+ durationSoon: 'Usage stats coming soon',+ tabs: {+ all: 'All',+ draft: 'Draft',+ running: 'Generating',+ done: 'Done',+ published: 'Published',+ },+ statusAria: 'Project status',+ typeAria: 'Project type',+ typeAll: 'All types',+ typeFull: 'AI video',+ typeImageText: 'Stills + voice',+ searchPlaceholder: 'Search by title',+ packing: 'Zipping {progress}…',+ packDownload: 'Download zip ({count})',+ empty: 'No explainer projects yet. Click “New explainer” to start.',+ noCover: 'No cover',+ published: 'Published',+ templateMeta: 'Template {name} · {when}',+ continueEdit: 'Continue',+ deleteTitle: 'Delete project',+ deleteMessage: 'Delete this project? Media and the finished film will be removed.',+ deleteFailed: 'Delete failed',+ downloadFailed: 'Download failed',+ packFailed: 'Zip failed',+ pagination: 'Explainer history pages',+ },+ dramaList: {+ title: 'My drama projects',+ assets: 'Asset library',+ canvas: 'Free canvas',+ creating: 'Creating…',+ newProject: 'New project',+ filterAria: 'Filter projects',+ searchAria: 'Search projects',+ searchPlaceholder: 'Search by title',+ createAria: 'Create',+ aiScript: 'AI script',+ collapse: 'Hide',+ tipStrong1: 'setup',+ tipStrong2: 'characters',+ tipStrong3: 'plot',+ tipRest: 'Spell out the {a}, {b}, {c}, and how it ends.',+ storyLabel: 'Story idea',+ filters: {+ all: 'All',+ running: 'In progress',+ done: 'Done',+ draft: 'Draft',+ },+ renameTitle: 'Rename project',+ renameMessage: 'Enter a new name',+ renameFailed: 'Rename failed',+ deleteTitle: 'Delete project',+ deleteOne: 'Delete “{title}”? Episodes, scripts, and assets will be removed and cannot be undone.',+ deleteMany: 'Delete {count} selected projects, including episodes, scripts, and assets? This cannot be undone.',+ deleteFailed: 'Delete failed',+ },+ legal: {+ updatedAt: 'Updated {date}',+ related: 'Related pages',+ },+} as constdiff --git a/frontend/src/i18n/locales/en/shell.ts b/frontend/src/i18n/locales/en/shell.tsnew file mode 100644index 0000000..cb84e75--- /dev/null+++ b/frontend/src/i18n/locales/en/shell.ts@@ -0,0 +1,182 @@+/** 英文:壳层、通用、账号、状态 */++export const enShell = {+ meta: {+ title: 'PRINTFILM · AI video studio',+ description:+ 'PRINTFILM: turn scripts into episodic AI dramas, or storyboards into explainer videos.',+ },+ common: {+ comingSoon: 'Coming soon',+ loading: 'Loading…',+ loadFailed: 'Failed to load',+ fail: 'Failed',+ save: 'Save',+ saving: 'Saving…',+ saved: 'Saved',+ cancel: 'Cancel',+ close: 'Close',+ confirm: 'OK',+ delete: 'Delete',+ download: 'Download',+ downloading: 'Downloading…',+ preview: 'Preview',+ copy: 'Copy',+ search: 'Search',+ home: 'Home',+ creator: 'Creator',+ dialog: 'Dialog',+ pagination: 'Pagination',+ prevPage: 'Previous page',+ nextPage: 'Next page',+ pageSize: 'Items per page',+ pageSizeBefore: '',+ pageSizeAfter: 'per page',+ pageSummary: 'Page {page} of {pageCount} · {total} items',+ loginRequired: 'Please sign in',+ generateFailed: 'Generation failed',+ queryFailed: 'Query failed',+ },+ dialog: {+ confirmTitle: 'Please confirm',+ promptTitle: 'Enter a value',+ alertTitle: 'Notice',+ ok: 'Got it',+ confirm: 'OK',+ cancel: 'Cancel',+ },+ nav: {+ workbench: 'Home',+ drama: 'Drama',+ kepu: 'Explainers',+ tools: 'Tools',+ assets: 'Assets',+ pricing: 'Pricing',+ help: 'Help',+ helpCenter: 'Help center',+ login: 'Sign in',+ startCreate: 'Start creating',+ profile: 'Account',+ main: 'Main navigation',+ openMenu: 'Open menu',+ closeMenu: 'Close menu',+ mobileNav: 'Mobile navigation',+ language: 'Language',+ langZh: '中',+ langEn: 'EN',+ },+ footer: {+ terms: 'Terms',+ privacy: 'Privacy',+ contact: 'Contact',+ help: 'Help',+ links: 'Footer links',+ },+ auth: {+ loginTitle: 'Back to the studio',+ registerTitle: 'Create a creator account',+ lede: 'PRINTFILM · AI drama and explainer videos',+ nickname: 'Display name',+ email: 'Email',+ password: 'Password',+ login: 'Sign in',+ register: 'Sign up',+ processing: 'Working…',+ toRegister: 'No account? Sign up',+ toLogin: 'Already have an account? Sign in',+ },+ create: {+ title: 'Start creating',+ hint: 'Pick a product and enter its workflow',+ drama: 'AI Drama',+ dramaHint: 'Script · episodes · film',+ kepu: 'Explainer video',+ kepuHint: 'Storyboard pipeline',+ toolsFootPrefix: 'Or browse standalone tools in the',+ toolsFootLink: 'tool hub',+ toolsFootSuffix: '',+ },+ settings: {+ nav: 'Settings',+ planScheme: '{plan} plan',+ logout: 'Sign out',+ tabs: {+ account: 'Profile',+ projects: 'Drama projects',+ kepu: 'Explainer history',+ tools: 'Tool runs',+ assets: 'Assets',+ subscription: 'Plan & balance',+ team: 'Team',+ api: 'API',+ notify: 'Notifications',+ security: 'Security',+ },+ workGroup: 'Work',+ accountGroup: 'Account',+ accountLead: 'Manage your profile and contact details',+ avatarHint: 'JPG / PNG / WebP, up to 5MB',+ uploadAvatar: 'Upload avatar',+ changeAvatar: 'Change avatar',+ uploading: 'Uploading…',+ avatarFailed: 'Avatar upload failed',+ nickname: 'Display name',+ email: 'Email',+ phone: 'Phone',+ phonePlaceholder: 'Not linked',+ phoneHint: 'Stored for contact only — no SMS verification',+ saveProfile: 'Save profile',+ saveFailed: 'Save failed',+ requestDelete: 'Delete account',+ language: 'Interface language',+ languageHint: 'Follows the browser until you pick a language. Chinese and English for now.',+ languageAuto: 'Follow browser',+ dramaLead: 'Your AI drama projects and episode progress',+ allProjects: 'All projects',+ newDrama: 'New drama',+ noDrama: 'No drama projects yet',+ goCreate: 'Create one',+ projectFallback: 'Project #{id}',+ kepuLead: 'Explainer projects and finished films',+ allHistory: 'All history',+ newKepu: 'New explainer',+ noKepu: 'No explainer projects yet',+ assetsLead: 'Characters, scenes, props, and media live in the asset library',+ openAssets: 'Open library',+ subLead: 'Pay as you go — balance never expires',+ balance: 'Available',+ frozen: 'On hold',+ currentPlan: 'Current plan',+ goTopup: 'Add credits',+ securityLead: 'Sign-in and account security',+ loginEmail: 'Sign-in email',+ changePassword: 'Change password',+ soonModule: 'This section is coming soon.',+ },+ status: {+ DRAFT: 'Draft',+ SCRIPTING: 'Storyboarding',+ SCRIPT_READY: 'Boards ready',+ IMAGING: 'Generating stills',+ IMAGE_READY: 'Stills ready',+ VIDEOING: 'Generating video',+ VIDEO_READY: 'Clips ready',+ AUDIOING: 'Generating voice',+ COMPOSING: 'Composing',+ AUDITING: 'Reviewing',+ DONE: 'Done',+ FAILED: 'Failed',+ CANCELLED: 'Cancelled',+ REJECTED: 'Rejected',+ PARALLEL_ASSETS: 'Generating stills',+ ASSETS_READY: 'Assets ready',+ },+ shotStatus: {+ PENDING: 'Waiting',+ IMAGE_READY: 'Image ready',+ VIDEO_READY: 'Video ready',+ AUDIO_READY: 'Done',+ DONE: 'Done',+ FAILED: 'Failed',+ },+} as constdiff --git a/frontend/src/i18n/locales/zh.ts b/frontend/src/i18n/locales/zh.tsnew file mode 100644index 0000000..fc18058--- /dev/null+++ b/frontend/src/i18n/locales/zh.ts@@ -0,0 +1,7 @@+import { zhPages } from './zh/pages'+import { zhShell } from './zh/shell'++export const zh = {+ ...zhShell,+ ...zhPages,+}diff --git a/frontend/src/i18n/locales/zh/pages.ts b/frontend/src/i18n/locales/zh/pages.tsnew file mode 100644index 0000000..236eb48--- /dev/null+++ b/frontend/src/i18n/locales/zh/pages.ts@@ -0,0 +1,454 @@+/** 中文:首页、帮助、联系、工具、定价、历史、漫剧列表 */++export const zhPages = {+ home: {+ headlineBefore: '把故事做成',+ headlineEm: '能播的片子',+ lede: 'AI 漫剧从剧本到分集成片,科普视频从分镜到配音合成。一套工作台,两种出片方式。',+ startCreate: '开始创作',+ browseTools: '浏览工具',+ products: '主产品',+ dramaTitle: 'AI 漫剧',+ dramaFor: '给短剧创作者',+ dramaDesc: '从一句话生成剧本,沉淀角色与场景,再按集分镜成片。',+ kepuTitle: '科普视频',+ kepuFor: '给知识创作者',+ kepuDesc: '选定画面风格,写好分镜旁白,沿流水线出讲解短片。',+ howKicker: 'How it works',+ howTitle: '三步出片',+ capsKicker: 'Capabilities',+ capsTitle: '工作台里真正能用的',+ toolsKicker: 'Tools',+ toolsTitle: '单点创作工具',+ allTools: '全部工具 →',+ whoKicker: 'For',+ whoTitle: '适合谁用',+ closeTitle: '从一条创意开始',+ closeLead: '登录后选择漫剧或科普,进入对应工作台。',+ viewPricing: '查看定价',+ footBrand: 'AI 漫剧与科普视频创作平台',+ footNav: '页脚导航',+ dramaSteps: ['AI 生剧本', '角色与场景', '分集分镜', '成片导出'],+ kepuSteps: ['选画面风格', '写分镜旁白', '配音与成片', '批量出片'],+ pipeline: [+ { step: '01', title: '写下创意', desc: '一句话故事、知识点或完整剧本,都能作为起点。' },+ { step: '02', title: '生成资产', desc: '角色、场景、道具与音色入库,后续镜头保持同一套面孔。' },+ { step: '03', title: '分镜成片', desc: '按集拆镜、引用资产、生成画面与视频,导出可播成片。' },+ ],+ capabilities: [+ { title: '19 种成片风格', desc: '从神话史诗到都市写实、赛博霓虹,选定后贯穿整部作品。' },+ { title: '资产可复用', desc: '角色、场景、道具、音色一次生成,全剧引用,避免每镜重画。' },+ { title: '分镜可编辑', desc: '脚本里 @ 引用资产、插入时长与运镜,生成前就能看清这一镜。' },+ { title: '两条出片路径', desc: '漫剧走分集叙事,科普走分镜流水线,同一套账号与积分。' },+ ],+ audiences: [+ { title: '短剧创作者', desc: '把故事拆成可拍的分集,先出资产再成片。' },+ { title: '知识博主', desc: '把文章变成竖屏讲解片,风格统一、节奏可控。' },+ { title: '团队制作', desc: '项目、资产、历史集中在一处,少在工具间来回搬。' },+ ],+ },+ help: {+ title: '帮助中心',+ lead: '搜索你遇到的问题,或从下方分类快速进入',+ search: '搜索帮助',+ searchPlaceholder: '搜索:下载、工具、充值、漫剧…',+ guideTitle: '上手四步',+ faqTitle: '常见问题',+ noMatch: '没有匹配的问题,试试「下载」「工具」「充值」',+ morePrefix: '更多操作可在',+ profile: '个人中心',+ moreMid: '查看项目与创作记录,或前往',+ pricing: '定价',+ moreMid2: '充值后继续创作。也可查阅',+ terms: '用户协议',+ privacy: '隐私政策',+ moreOr: ',或',+ contact: '联系我们',+ moreSuffix: '。',+ fullPage: '完整帮助页',+ gotIt: '知道了',+ drawerSearch: '搜索指南或常见问题',+ noFaq: '没有匹配的问题',+ cats: [+ { id: 'start', title: '快速开始', desc: '工作台选产品入口', href: '/' },+ { id: 'drama', title: '漫剧创作', desc: '剧本 · 分集 · 成片', href: '/drama' },+ { id: 'kepu', title: '科普视频', desc: '分镜流水线与成片', href: '/history' },+ { id: 'tools', title: '创作工具', desc: '文生图 / 图生图 / 视频', href: '/tools' },+ { id: 'settings', title: '个人中心', desc: '项目 · 记录 · 下载', href: '/settings?tab=tools' },+ { id: 'billing', title: '充值说明', desc: '按量计费,余额永久有效', href: '/pricing' },+ ],+ steps: [+ {+ n: '01',+ title: '选创作入口',+ body: '工作台进入「AI 漫剧」或「科普视频」;单点能力也可从顶栏「工具」进入文生图、图生图、文生视频等。',+ },+ {+ n: '02',+ title: '配置并生成',+ body: '漫剧:创意 → 大纲 → 资产 → 分集;科普:主题 → 风格 → 分镜 → 成片;工具:填提示词或上传素材后点生成。',+ },+ {+ n: '03',+ title: '审阅与迭代',+ body: '漫剧 / 科普可单镜重绘、重生视频或重配音,不必整片重做。工具结果可在工作台预览后再次生成。',+ },+ {+ n: '04',+ title: '保存与下载',+ body: '结果会写入云端存储。科普在历史页下载;漫剧在项目工作台查看;工具创作在个人中心查看详情并下载。',+ },+ ],+ faq: [+ {+ q: '第一次使用从哪开始?',+ a: '打开工作台,选择「AI 漫剧」或「科普视频」。漫剧适合分集叙事与角色一致性;科普适合短视频分镜流水线。若只要单张图或短片段,可直接进入「工具」。',+ },+ {+ q: '「AI 视频」和「静图成片」有什么区别?',+ a: 'AI 视频镜头运动更强、成本更高;静图成片(图文视频)以画面 + 旁白为主,更快更稳,适合讲解类科普。新建科普项目时按需求选择即可。',+ },+ {+ q: '生成中可以离开页面吗?',+ a: '可以。任务在服务端继续执行。科普可回「科普」历史页看进度;漫剧回对应项目工作台;工具视频任务请尽量停留在当前页等待完成,或稍后在个人中心查看状态。',+ },+ {+ q: '工具中心能做什么?',+ a: '已开放文生图、图生图、图生产品、文生视频、视频生视频与电商拼图。登录后进入「工具」选择对应能力,填写提示词或上传素材即可生成。',+ },+ {+ q: '工具生成结果保存在哪里?',+ a: '每次成功生成都会写入创作记录,媒体文件同步到云端对象存储(OSS)。可在头像 → 个人中心 →「工具创作」查看封面、状态与提示词。',+ },+ {+ q: '如何查看和下载工具结果?',+ a: '打开个人中心「工具创作」,点击「查看」可预览大图或视频;点击「下载」将从云端地址保存到本地。生成页右侧成功后也会提示可前往个人中心回看。',+ },+ {+ q: '成片或素材在哪里下载?',+ a: '科普成片:顶栏「科普」历史页,已完成项目可下载或打包。漫剧:进入对应项目工作台查看分镜与成片。全局资产:顶栏「资产」管理角色、场景、道具与音色。',+ },+ {+ q: '个人中心有哪些内容?',+ a: '包含账号信息、漫剧项目、科普历史、工具创作记录、资产管理入口,以及订阅与余额。团队、API、通知偏好等能力仍在建设中。',+ },+ {+ q: '如何充值?余额怎么扣?',+ a: '打开「定价」选择充值档位,支持支付宝与微信支付;未登录会先引导登录。按实际调用量扣费,余额永久有效,无强制订阅。用量可在定价页或个人中心「订阅与余额」查看。',+ },+ {+ q: '生成失败或画面不符合预期怎么办?',+ a: '可调整提示词、反向提示词或参考图后重试;漫剧 / 科普支持单镜重生。若反复失败,请检查网络与余额,或稍后重试。敏感内容可能被模型安全策略拦截。',+ },+ ],+ drawerCats: [+ { id: 'guide', title: '快速开始', desc: '四步上手创作' },+ { id: 'faq', title: '常见问题', desc: '下载 · 生成 · 充值' },+ { id: 'tools', title: '工具说明', desc: '文生图与短视频' },+ ],+ toolsNote:+ '工具中心已开放文生图、图生图、图生产品、文生视频、视频生视频与电商拼图。生成结果会保存到云端,并在个人中心「工具创作」中支持查看与下载。',+ openTools: '打开工具',+ toolRecords: '创作记录',+ },+ contact: {+ crumb: '联系我们',+ title: '联系我们',+ introPrefix: '充值、账号、创作任务或合作咨询,欢迎通过以下方式联系。提交前也可先查看',+ introLink: '帮助中心',+ introSuffix: '。',+ formTitle: '留言反馈',+ formLead: '填写后将打开您的邮件客户端,预填发往 [email protected] 的草稿,请确认后发送。',+ topic: '问题类型',+ email: '联系邮箱',+ emailPlaceholder: '便于我们回复',+ message: '问题描述',+ messagePlaceholder: '请尽量说明账号邮箱、订单号、发生时间与报错信息',+ submit: '打开邮件草稿',+ sentPrefix: '若未自动打开邮件客户端,请直接发送至',+ related: '相关页面',+ pricing: '定价充值',+ contactAction: '联系',+ goAction: '前往',+ mailSubject: '主题:{topic}',+ mailEmail: '联系邮箱:{email}',+ mailEmailEmpty: '(未填写)',+ mailEmpty: '(无详细描述)',+ channels: [+ {+ title: '邮箱支持',+ desc: '工作日一般 1–2 个工作日内回复;请附上账号邮箱与订单号(如有)。',+ href: 'mailto:[email protected]',+ actionLabel: '[email protected]',+ },+ {+ title: '帮助中心',+ desc: '充值、下载、漫剧与工具等常见问题可先在帮助中心自助查询。',+ href: '/help',+ actionLabel: '前往帮助中心',+ },+ {+ title: '企业合作 / 对公转账',+ desc: '企业批量充值、API 合作或发票需求,请邮件说明公司名称与需求,我们会安排对接。',+ href: 'mailto:[email protected]?subject=PRINTFILM%20Enterprise',+ actionLabel: '发送合作邮件',+ },+ ],+ topics: ['账号与登录', '充值与到账', '创作任务异常', '下载与素材', '隐私与账号注销', '其他'],+ },+ tools: {+ title: 'AI 创作工具',+ lead: '进入工具工作台,生成图片与短视频。',+ goDrama: '去漫剧创作',+ goDramaHint: '剧本 · 分集 · 成片',+ goKepu: '去科普历史',+ goKepuHint: '分镜流水线出片',+ generating: '生成中…',+ generatingVideo: '视频生成中…',+ generatingShort: '正在生成',+ generatingVideoShort: '视频生成中',+ savedPrefix: '已保存,可在',+ savedLink: '个人中心 · 工具创作',+ savedSuffix: '查看',+ allTools: '全部工具',+ uploadHint: '点击或拖拽上传',+ filesSelected: '已选 {count} 个文件',+ inputPlaceholder: '输入{label}…',+ resultArea: '生成结果',+ resultEmpty: '结果预览区',+ resultEmptyHint: '生成完成后将在此展示',+ videoWaitHint: '通常需要 1–3 分钟,可停留在本页等待',+ imageWaitHint: '画面生成大约 20–40 秒',+ previewAlt: '静帧预览',+ resultAlt: '生成结果',+ downloadVideo: '下载视频',+ downloadImage: '下载图片',+ errors: {+ fillPrompt: '请填写提示词',+ uploadRef: '请上传参考图',+ fillScript: '请填写视频脚本',+ uploadSource: '请上传源视频或首帧图',+ uploadProduct: '请上传商品图',+ uploadTwoImages: '拼接至少上传 2 张图片',+ videoFailed: '视频生成失败',+ pollFailed: '查询失败',+ generateFailed: '生成失败',+ notLoggedIn: '未登录',+ },+ items: {+ t2i: {+ title: '文生图',+ desc: '用文字描述生成高质量画面',+ panelHint: '用文字描述画面,选择画幅后即可生成。',+ cta: '生成',+ fields: {+ prompt: { label: '提示词', placeholder: '描述主体、场景、光线与风格…' },+ negative: { label: '反向提示词', placeholder: '不想出现的内容,如文字、水印…' },+ ratio: { label: '画幅' },+ },+ },+ i2i: {+ title: '图生图',+ desc: '上传参考图,生成风格一致的变体',+ panelHint: '上传参考图,描述希望保留或改变的部分。',+ cta: '生成',+ fields: {+ ref: { label: '参考图' },+ prompt: { label: '提示词', placeholder: '保持主体,改为电影感夜景…' },+ strength: { label: '相似度' },+ },+ },+ i2p: {+ title: '图生产品',+ desc: '一键生成白底图与场景商品图',+ panelHint: '上传商品图,选择白底、场景或详情长图。',+ cta: '生成商品图',+ fields: {+ product: { label: '商品图' },+ mode: { label: '输出类型' },+ prompt: { label: '补充描述(可选)', placeholder: '材质、摆放、使用场景…' },+ },+ },+ t2v: {+ title: '文生视频',+ desc: '从脚本生成短视频片段',+ panelHint: '填写脚本后先出静帧,再生成短视频(约 1–3 分钟)。',+ cta: '生成视频',+ fields: {+ script: { label: '视频脚本', placeholder: '描述镜头运动、主体动作与氛围…' },+ duration: { label: '时长' },+ ratio: { label: '画幅' },+ },+ },+ v2v: {+ title: '视频生视频',+ desc: '对已有视频做风格与运动变换',+ panelHint: '上传源视频或首帧图,描述风格与运动强度。',+ cta: '开始变换',+ fields: {+ source: { label: '源视频 / 首帧' },+ prompt: { label: '变换描述', placeholder: '改为赛博朋克夜景,镜头缓缓推进…' },+ motion: { label: '运动强度' },+ },+ },+ ecom: {+ title: '电商工具',+ desc: '主图拼接、详情排版等小工具合集',+ panelHint: '拼接至少 2 张图;卖点海报上传 1 张商品图即可生成。',+ cta: '开始制作',+ fields: {+ pack: { label: '工具包' },+ images: { label: '图片' },+ prompt: { label: '卖点描述(海报可选)', placeholder: '突出材质与使用场景…' },+ },+ },+ },+ chips: {+ 低: '低',+ 中: '中',+ 高: '高',+ 弱: '弱',+ 强: '强',+ 白底图: '白底图',+ 场景图: '场景图',+ 详情长图: '详情长图',+ 主图拼接: '主图拼接',+ 详情排版: '详情排版',+ 卖点海报: '卖点海报',+ },+ },+ pricing: {+ title: '按需充值,灵活使用',+ lead: '按实际消耗 token 计费,余量永久有效,不设过期',+ featInstant: '充值即时到账,马上可用',+ featSafe: '支付安全保障',+ featForever: '余额永久有效',+ guestPrefix: '',+ guestLogin: '登录',+ guestSuffix: ' 后查看余额与本月用量',+ paidHint: '支付完成。若余额未更新,请稍候刷新本页。',+ paidOk: '支付成功,余额已更新',+ orderFailed: '下单失败',+ payMethods: '支付方式',+ paySafe: '支付安全保障',+ alipay: '支付宝',+ wechat: '微信支付',+ recommended: '推荐',+ unionpay: '银联支付',+ transfer: '对公转账',+ enterprise: '企业用户',+ soonTitle: '即将上线',+ transferTitle: '企业用户请联系客服',+ unavailable: '{label}即将上线,请先使用支付宝或微信支付',+ chooseAmount: '选择充值金额',+ credit: '到账',+ bonus: '额外赠送 ¥{amount}',+ foreverHint: '余额永久有效',+ ordering: '下单中…',+ payNow: '立即充值',+ billingTitle: '计费说明',+ billing1: '拆分镜、出图、配音、AI 视频分别按上游 token 用量计费',+ billing2: '开始生成时预扣估算金额,结束后按实际用量结算(多退少补)',+ billing3: '图文模式成本更低;开启 AI 动态视频时消耗更高',+ whyTitle: '为什么按量计费',+ why1: '无需订阅,用多少充多少',+ why2: '余额永久有效,不设过期',+ why3: '账单清晰可查,每次调用可追溯',+ footBrand: 'AI 短视频创作伙伴',+ skus: {+ topup_10: '体验充值',+ topup_49: '基础充值',+ topup_99: '进阶充值',+ topup_199: '专业充值',+ },+ skuHints: {+ topup_10: '适合初次体验',+ topup_49: '日常创作够用',+ topup_99: '高频创作推荐',+ topup_199: '团队 / 批量生产',+ },+ walletBalance: '可用余额',+ hideBalance: '隐藏余额',+ showBalance: '显示余额',+ history: '充值记录',+ loginFirst: '请先登录',+ monthCharge: '本次消耗',+ currentPlan: '当前套餐',+ frozen: '冻结中 ¥{amount}',+ updatedAt: '更新于 {time}',+ },+ history: {+ title: '科普历史',+ lead: '管理你的科普视频项目,继续编辑或下载成片。',+ newKepu: '新建科普',+ goDrama: '去漫剧',+ statTotal: '总作品数',+ statRunning: '生成中',+ runningNow: '正在生成中',+ noTask: '暂无任务',+ statDone: '已完成',+ statDuration: '本月时长',+ durationSoon: '额度统计即将推出',+ tabs: {+ all: '全部',+ draft: '草稿',+ running: '生成中',+ done: '已完成',+ published: '已发布',+ },+ statusAria: '项目状态',+ typeAria: '项目类型',+ typeAll: '全部类型',+ typeFull: '成片视频',+ typeImageText: '图文视频',+ searchPlaceholder: '搜索项目名称',+ packing: '打包中 {progress}…',+ packDownload: '打包下载 ({count})',+ empty: '暂无科普项目,点击「新建科普」开始创作',+ noCover: '无封面',+ published: '已发布',+ templateMeta: '模板 {name} · {when}',+ continueEdit: '继续编辑',+ deleteTitle: '删除项目',+ deleteMessage: '确定删除该项目?素材与成片将一并清除。',+ deleteFailed: '删除失败',+ downloadFailed: '下载失败',+ packFailed: '打包失败',+ pagination: '科普历史分页',+ },+ dramaList: {+ title: '我的漫剧项目',+ assets: '资产库',+ canvas: '自由画布',+ creating: '创建中…',+ newProject: '新建项目',+ filterAria: '项目筛选',+ searchAria: '搜索项目',+ searchPlaceholder: '搜索项目名称',+ createAria: '创作入口',+ aiScript: 'AI 生剧本',+ collapse: '收起',+ tipStrong1: '故事设定',+ tipStrong2: '人物特征',+ tipStrong3: '剧情脉络',+ tipRest: '建议写明 {a}、{b}、{c} 与结局走向。',+ storyLabel: '故事创意',+ filters: {+ all: '全部',+ running: '进行中',+ done: '已完成',+ draft: '草稿',+ },+ renameTitle: '重命名项目',+ renameMessage: '输入新的项目名称',+ renameFailed: '重命名失败',+ deleteTitle: '删除项目',+ deleteOne: '确定删除「{title}」?分集、剧本与资产将一并删除,且无法恢复。',+ deleteMany: '将删除已选择的 {count} 个项目,包含分集、剧本与资产等数据,删除后无法恢复。',+ deleteFailed: '删除失败',+ },+ legal: {+ updatedAt: '更新日期:{date}',+ related: '相关页面',+ },+} as constdiff --git a/frontend/src/i18n/locales/zh/shell.ts b/frontend/src/i18n/locales/zh/shell.tsnew file mode 100644index 0000000..514950b--- /dev/null+++ b/frontend/src/i18n/locales/zh/shell.ts@@ -0,0 +1,181 @@+/** 中文:壳层、通用、账号、状态 */++export const zhShell = {+ meta: {+ title: 'PRINTFILM · 科普视频平台',+ description: 'PRINTFILM:AI 漫剧从剧本到分集成片,科普视频从分镜到配音合成。',+ },+ common: {+ comingSoon: '即将推出',+ loading: '加载中…',+ loadFailed: '加载失败',+ fail: '失败',+ save: '保存',+ saving: '保存中…',+ saved: '已保存',+ cancel: '取消',+ close: '关闭',+ confirm: '确定',+ delete: '删除',+ download: '下载',+ downloading: '下载中…',+ preview: '预览',+ copy: '复制',+ search: '搜索',+ home: '首页',+ creator: '创作者',+ dialog: '对话框',+ pagination: '分页',+ prevPage: '上一页',+ nextPage: '下一页',+ pageSize: '每页条数',+ pageSizeBefore: '每页',+ pageSizeAfter: '条',+ pageSummary: '第 {page} / {pageCount} 页 · 共 {total} 条',+ loginRequired: '未登录',+ generateFailed: '生成失败',+ queryFailed: '查询失败',+ },+ dialog: {+ confirmTitle: '请确认',+ promptTitle: '请输入',+ alertTitle: '提示',+ ok: '知道了',+ confirm: '确定',+ cancel: '取消',+ },+ nav: {+ workbench: '工作台',+ drama: '漫剧',+ kepu: '科普',+ tools: '工具',+ assets: '资产',+ pricing: '定价',+ help: '帮助',+ helpCenter: '帮助中心',+ login: '登录',+ startCreate: '开始创作',+ profile: '个人中心',+ main: '主导航',+ openMenu: '打开菜单',+ closeMenu: '关闭菜单',+ mobileNav: '移动导航',+ language: '语言',+ langZh: '中',+ langEn: 'EN',+ },+ footer: {+ terms: '用户协议',+ privacy: '隐私政策',+ contact: '联系我们',+ help: '帮助中心',+ links: '页脚链接',+ },+ auth: {+ loginTitle: '回到工作台',+ registerTitle: '创建创作者账号',+ lede: 'PRINTFILM · AI 漫剧与科普视频创作平台',+ nickname: '昵称',+ email: '邮箱',+ password: '密码',+ login: '登录',+ register: '注册',+ processing: '处理中…',+ toRegister: '没有账号?注册',+ toLogin: '已有账号?登录',+ },+ create: {+ title: '开始创作',+ hint: '选择一个产品线,进入对应工作流',+ drama: 'AI 漫剧',+ dramaHint: '剧本 · 分集 · 成片',+ kepu: '科普视频',+ kepuHint: '分镜流水线出片',+ toolsFootPrefix: '也可以先去',+ toolsFootLink: '工具中心',+ toolsFootSuffix: '浏览独立能力',+ },+ settings: {+ nav: '设置导航',+ planScheme: '{plan} 方案',+ logout: '退出登录',+ tabs: {+ account: '账号信息',+ projects: '漫剧项目',+ kepu: '科普历史',+ tools: '工具创作',+ assets: '资产管理',+ subscription: '订阅与余额',+ team: '团队管理',+ api: 'API',+ notify: '通知偏好',+ security: '安全',+ },+ workGroup: '创作',+ accountGroup: '账号',+ accountLead: '管理你的资料与联系方式',+ avatarHint: '支持 JPG / PNG / WebP,不超过 5MB',+ uploadAvatar: '上传头像',+ changeAvatar: '更换头像',+ uploading: '上传中…',+ avatarFailed: '头像上传失败',+ nickname: '用户名',+ email: '邮箱',+ phone: '手机号',+ phonePlaceholder: '未绑定',+ phoneHint: '仅记录联系方式,无需验证码',+ saveProfile: '保存资料',+ saveFailed: '保存失败',+ requestDelete: '申请注销',+ language: '界面语言',+ languageHint: '未手动选择时,跟随浏览器语言。当前支持中文与 English。',+ languageAuto: '跟随浏览器',+ dramaLead: '你的 AI 漫剧创作与分集进度',+ allProjects: '全部项目',+ newDrama: '新建漫剧',+ noDrama: '还没有漫剧项目',+ goCreate: '去创建',+ projectFallback: '项目 #{id}',+ kepuLead: '科普视频项目与成片记录',+ allHistory: '全部历史',+ newKepu: '新建科普',+ noKepu: '还没有科普项目',+ assetsLead: '角色、场景、道具与成片素材统一存放在资产库',+ openAssets: '打开资产库',+ subLead: '按量充值,余额永久有效',+ balance: '可用余额',+ frozen: '冻结中',+ currentPlan: '当前方案',+ goTopup: '去充值',+ securityLead: '登录与账号安全设置',+ loginEmail: '登录邮箱',+ changePassword: '修改密码',+ soonModule: '该模块即将上线,敬请期待。',+ },+ status: {+ DRAFT: '草稿',+ SCRIPTING: '拆分镜中',+ SCRIPT_READY: '分镜待确认',+ IMAGING: '出图中',+ IMAGE_READY: '分镜图完成',+ VIDEOING: '生成带配音视频',+ VIDEO_READY: '镜头视频完成',+ AUDIOING: '生成配音',+ COMPOSING: '拼接成片',+ AUDITING: '审核中',+ DONE: '已完成',+ FAILED: '失败',+ CANCELLED: '已取消',+ REJECTED: '未通过',+ PARALLEL_ASSETS: '出图中',+ ASSETS_READY: '素材就绪',+ },+ shotStatus: {+ PENDING: '等待中',+ IMAGE_READY: '图已生成',+ VIDEO_READY: '视频已生成',+ AUDIO_READY: '已完成',+ DONE: '已完成',+ FAILED: '失败',+ },+} as constdiff --git a/frontend/src/i18n/lookup.ts b/frontend/src/i18n/lookup.tsnew file mode 100644index 0000000..2633d69--- /dev/null+++ b/frontend/src/i18n/lookup.ts@@ -0,0 +1,22 @@+/** 按点路径取文案,并用 {name} 做插值 */++export type TVars = Record<string, string | number>++// 从嵌套对象按 "nav.home" 取字符串+export function lookupMessage(source: unknown, path: string): string | undefined {+ const parts = path.split('.')+ let cur: unknown = source+ for (const part of parts) {+ if (cur == null || typeof cur !== 'object') return undefined+ cur = (cur as Record<string, unknown>)[part]+ }+ return typeof cur === 'string' ? cur : undefined+}++// 将模板中的 {key} 替换为 vars+export function interpolate(template: string, vars?: TVars): string {+ if (!vars) return template+ return template.replace(/\{(\w+)\}/g, (match, key: string) =>+ Object.prototype.hasOwnProperty.call(vars, key) ? String(vars[key]) : match,+ )+}diff --git a/frontend/src/i18n/messages.ts b/frontend/src/i18n/messages.tsnew file mode 100644index 0000000..6d5682e--- /dev/null+++ b/frontend/src/i18n/messages.ts@@ -0,0 +1,10 @@+import type { Locale } from './detect'+import { en } from './locales/en'+import { zh } from './locales/zh'++export type Messages = typeof zh++export const messages: Record<Locale, Messages> = {+ zh,+ en: en as unknown as Messages,+}diff --git a/frontend/src/lib/legalContent.ts b/frontend/src/lib/legalContent.tsindex b5c2d9a..3ed0309 100644--- a/frontend/src/lib/legalContent.ts+++ b/frontend/src/lib/legalContent.ts@@ -155,6 +155,153 @@ export const LEGAL_DOCS: Record<'terms' | 'privacy', LegalDoc> = {},}+export const LEGAL_DOCS_EN: Record<'terms' | 'privacy', LegalDoc> = {+ terms: {+ slug: 'terms',+ title: 'Terms of Service',+ updatedAt: '2026-08-17',+ intro:+ 'Welcome to PRINTFILM (“the Platform”). Please read these terms before you register or use the service. Using the Platform means you have read and agree to them.',+ sections: [+ {+ title: '1. The service',+ paragraphs: [+ 'PRINTFILM provides AI drama, explainer video, and creation tools (including text-to-image, image-to-image, and text-to-video). Features may change as the product evolves; we will try to note material changes on the site or in notices.',+ 'Billing follows actual upstream model usage. Topped-up balance does not expire and there is no forced subscription. Prices and bonuses follow the Pricing page and the checkout screen.',+ ],+ },+ {+ title: '2. Accounts and security',+ bullets: [+ 'Register with accurate information and you are responsible for activity under the account.',+ 'Keep credentials safe. Losses from leaks or sharing are yours to bear.',+ 'If you see unauthorized use, tell us via Contact.',+ 'We may limit, freeze, or close accounts for abuse, fraud, or policy violations.',+ ],+ },+ {+ title: '3. Content and IP',+ paragraphs: [+ 'Prompts, scripts, and uploads remain yours or the original rights holder’s. You warrant you have the right to upload them and will not infringe IP, portrait, or privacy rights.',+ 'AI output may be inaccurate or unexpected. Review it before publishing. Disputes from your public or commercial use are your responsibility.',+ 'The Platform UI, marks, software, and docs belong to PRINTFILM or licensors. Do not copy, reverse-engineer, or use them outside this service without permission.',+ ],+ },+ {+ title: '4. Billing and top-ups',+ bullets: [+ 'Generation jobs are billed by upstream tokens or agreed unit prices. We may pre-authorize an estimate and settle the real usage afterward.',+ 'Top-ups go through Alipay, WeChat Pay, and similar channels. Arrival follows system records.',+ 'Except where law requires otherwise or we explicitly agree, arrived credits are generally non-refundable.',+ 'If a fault causes a double charge or missing credit, keep the order ID and contact support.',+ ],+ },+ {+ title: '5. Prohibited use',+ bullets: [+ 'Do not create or spread illegal, pornographic, violent, hateful, fraudulent, or otherwise infringing content.',+ 'Do not attack, scrape, bypass billing, abuse APIs, or disrupt other users.',+ 'Do not resell accounts, bulk-register, or otherwise harm fair operation.',+ ],+ },+ {+ title: '6. Disclaimers',+ paragraphs: [+ 'To the extent allowed by law, we are not liable for outages or data loss from network faults, third-party interruptions, or force majeure.',+ 'AI output is a creation aid, not professional advice. We are not liable beyond fees you paid for losses from relying on generated content, except where law requires otherwise.',+ ],+ },+ {+ title: '7. Changes and termination',+ paragraphs: [+ 'We may revise these terms and post the new version here with an updated date. Continued use means you accept the revision.',+ 'You may stop using the service and request account deletion. We may also stop serving you if you seriously breach these terms.',+ ],+ },+ {+ title: '8. Contact',+ paragraphs: [+ 'Questions about these terms: use Contact or email [email protected].',+ ],+ },+ ],+ },+ privacy: {+ slug: 'privacy',+ title: 'Privacy Policy',+ updatedAt: '2026-08-17',+ intro:+ 'PRINTFILM respects your privacy. This policy explains how we collect, use, store, and protect personal information. Using the Platform means you understand this processing.',+ sections: [+ {+ title: '1. Information we collect',+ bullets: [+ 'Account data: email, display name, avatar, and authentication data.',+ 'Usage data: projects, prompts, job status, tool runs, and asset library content.',+ 'Billing data: balance, holds, top-up orders, and usage ledgers (payment is handled by third parties; we do not store full card numbers).',+ 'Technical logs: IP, browser type, and access time for security and debugging.',+ ],+ },+ {+ title: '2. How we use it',+ bullets: [+ 'Provide, maintain, and improve drama, explainer, and tool services.',+ 'Identity checks, billing, order queries, and support.',+ 'Account and system security, fraud and abuse prevention.',+ 'Service notices or product updates where you consent or law allows.',+ ],+ },+ {+ title: '3. Storage and third parties',+ paragraphs: [+ 'Media and project files may live in cloud object storage (such as Alibaba Cloud OSS) for preview and download.',+ 'Payments go through partners such as Epay; model inference goes through upstream providers. We share only what is needed to complete the service.',+ 'We do not sell personal information to unrelated third parties except as required by law, with your consent, or to protect the Platform and users.',+ ],+ },+ {+ title: '4. Cookies and local storage',+ paragraphs: [+ 'We may use cookies or local storage (such as a token) to keep you signed in and remember preferences. Clearing them may require signing in again.',+ ],+ },+ {+ title: '5. Your rights',+ bullets: [+ 'View and correct profile data in Account.',+ 'Export or download creative output where the product allows.',+ 'Request account deletion; we will delete or anonymize personal data as required, except records the law keeps.',+ 'Ask questions or complain about privacy.',+ ],+ },+ {+ title: '6. Children',+ paragraphs: [+ 'The Platform is intended for users with full civil capacity. If you are a minor, read this policy and use the service with a guardian.',+ ],+ },+ {+ title: '7. Policy updates',+ paragraphs: [+ 'We may update this policy and post the latest version and date here. For material changes we will try to notify you in-product.',+ ],+ },+ {+ title: '8. Contact',+ paragraphs: [+ 'Questions: use Contact or email [email protected].',+ ],+ },+ ],+ },+}++// 按界面语言取用户协议 / 隐私政策+export function getLegalDoc(slug: 'terms' | 'privacy', locale: string): LegalDoc {+ const pack = locale === 'en' ? LEGAL_DOCS_EN : LEGAL_DOCS+ return pack[slug]+}+export type ContactChannel = {title: stringdesc: stringdiff --git a/frontend/src/lib/status.ts b/frontend/src/lib/status.tsindex 39ab785..c411205 100644--- a/frontend/src/lib/status.ts+++ b/frontend/src/lib/status.ts@@ -1,3 +1,6 @@+import { getActiveLocale } from '../i18n/detect'+import { messages } from '../i18n/messages'+export const RUNNING = new Set(['SCRIPTING','IMAGING',@@ -8,24 +11,16 @@ export const RUNNING = new Set(['PARALLEL_ASSETS',])-export const STATUS_CN: Record<string, string> = {- DRAFT: '草稿',- SCRIPTING: '拆分镜中',- SCRIPT_READY: '分镜待确认',- IMAGING: '出图中',- IMAGE_READY: '分镜图完成',- VIDEOING: '生成带配音视频',- VIDEO_READY: '镜头视频完成',- AUDIOING: '生成配音',- COMPOSING: '拼接成片',- AUDITING: '审核中',- DONE: '已完成',- FAILED: '失败',- CANCELLED: '已取消',- REJECTED: '未通过',- PARALLEL_ASSETS: '出图中',- ASSETS_READY: '素材就绪',-}+// 按当前界面语言取状态文案(兼容旧的 STATUS_CN[code] 写法)+export const STATUS_CN: Record<string, string> = new Proxy(+ {},+ {+ get(_target, prop: string) {+ const map = messages[getActiveLocale()].status as Record<string, string>+ return map[prop] || prop+ },+ },+)export function isRunning(status: string) {return RUNNING.has(status)@@ -74,14 +69,15 @@ export function statusTone(status: string): 'ok' | 'bad' | 'run' | 'idle' {}/** Per-shot statuses from pipeline */-export const SHOT_STATUS_CN: Record<string, string> = {- PENDING: '等待中',- IMAGE_READY: '图已生成',- VIDEO_READY: '视频已生成',- AUDIO_READY: '已完成',- DONE: '已完成',- FAILED: '失败',-}+export const SHOT_STATUS_CN: Record<string, string> = new Proxy(+ {},+ {+ get(_target, prop: string) {+ const map = messages[getActiveLocale()].shotStatus as Record<string, string>+ return map[prop] || STATUS_CN[prop] || prop+ },+ },+)export function shotStatusLabel(status: string) {return SHOT_STATUS_CN[status] || STATUS_CN[status] || statusdiff --git a/frontend/src/lib/toolsCatalog.ts b/frontend/src/lib/toolsCatalog.tsindex d2245ce..fa79a31 100644--- a/frontend/src/lib/toolsCatalog.ts+++ b/frontend/src/lib/toolsCatalog.ts@@ -1,5 +1,6 @@import { Clapperboard, Image, Images, Play, ShoppingBag, Sparkles, Video } from 'lucide-react'import type { LucideIcon } from 'lucide-react'+import type { Messages } from '../i18n'export type ToolId = 't2i' | 'i2i' | 'i2p' | 't2v' | 'v2v' | 'ecom'@@ -124,7 +125,7 @@ export function getToolDef(id: string | undefined): ToolDef | undefined {export const PRODUCT_ICONS = { drama: Clapperboard, kepu: Video }-// 芯片字段的默认选中项(取 options 第一项)+// 芯片字段的默认选中项(取 options 第一项;值为中文枚举,给后端)export function defaultToolChips(tool: ToolDef): Record<string, string> {const chips: Record<string, string> = {}for (const field of tool.fields) {@@ -132,3 +133,35 @@ export function defaultToolChips(tool: ToolDef): Record<string, string> {}return chips}++// 用当前语言覆盖工具标题、说明与字段文案(options 值保持中文给 API)+export function localizeToolDef(tool: ToolDef, m: Messages): ToolDef {+ const pack = m.tools.items[tool.id]+ return {+ ...tool,+ title: pack.title,+ desc: pack.desc,+ panelHint: pack.panelHint,+ cta: pack.cta,+ fields: tool.fields.map((field) => {+ const f = pack.fields[field.key as keyof typeof pack.fields] as+ | { label?: string; placeholder?: string }+ | undefined+ return {+ ...field,+ label: f?.label || field.label,+ placeholder: f?.placeholder || field.placeholder,+ }+ }),+ }+}++export function localizeToolDefs(m: Messages): ToolDef[] {+ return TOOL_DEFS.map((tool) => localizeToolDef(tool, m))+}++// 芯片展示文案;未知值原样返回+export function chipDisplayLabel(value: string, m: Messages): string {+ const chips = m.tools.chips as Record<string, string>+ return chips[value] || value+}diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex fab1219..af4fdfb 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -1,10 +1,13 @@import { StrictMode } from 'react'import { createRoot } from 'react-dom/client'import App from './App'+import { I18nProvider } from './i18n'import './index.css'createRoot(document.getElementById('root')!).render(<StrictMode>- <App />+ <I18nProvider>+ <App />+ </I18nProvider></StrictMode>,)diff --git a/frontend/src/pages/AuthPage.tsx b/frontend/src/pages/AuthPage.tsxindex 8c5a402..c135da3 100644--- a/frontend/src/pages/AuthPage.tsx+++ b/frontend/src/pages/AuthPage.tsx@@ -3,6 +3,8 @@ import type { FormEvent } from 'react'import { useNavigate, useSearchParams } from 'react-router-dom'import { api } from '../api'import BrandMark from '../components/BrandMark'+import LanguageSwitch from '../components/layout/LanguageSwitch'+import { useI18n } from '../i18n'// 仅允许站内相对路径回跳,防止开放重定向function safeNextPath(raw: string | null, fallback = '/') {@@ -13,6 +15,7 @@ function safeNextPath(raw: string | null, fallback = '/') {export default function AuthPage() {const nav = useNavigate()+ const { t } = useI18n()const [params] = useSearchParams()const nextPath = safeNextPath(params.get('next'), '/')const [mode, setMode] = useState<'login' | 'register'>('login')@@ -34,7 +37,7 @@ export default function AuthPage() {localStorage.setItem('token', res.access_token)nav(nextPath)} catch (err) {- setError(err instanceof Error ? err.message : '失败')+ setError(err instanceof Error ? err.message : t('common.fail'))} finally {setLoading(false)}@@ -43,18 +46,21 @@ export default function AuthPage() {return (<div className="auth-shell"><div className="auth-panel">- <BrandMark />- <h1>{mode === 'login' ? '回到工作台' : '创建创作者账号'}</h1>- <p className="lede">PRINTFILM · AI 漫剧与科普视频创作平台</p>+ <div className="auth-panel-top">+ <BrandMark />+ <LanguageSwitch />+ </div>+ <h1>{mode === 'login' ? t('auth.loginTitle') : t('auth.registerTitle')}</h1>+ <p className="lede">{t('auth.lede')}</p><form onSubmit={onSubmit} className="stack">{mode === 'register' && (<label>- 昵称+ {t('auth.nickname')}<input value={nickname} onChange={(e) => setNickname(e.target.value)} required /></label>)}<label>- 邮箱+ {t('auth.email')}<inputtype="email"value={email}@@ -63,7 +69,7 @@ export default function AuthPage() {/></label><label>- 密码+ {t('auth.password')}<inputtype="password"value={password}@@ -74,7 +80,7 @@ export default function AuthPage() {</label>{error && <p className="error">{error}</p>}<button className="btn primary" disabled={loading}>- {loading ? '处理中…' : mode === 'login' ? '登录' : '注册'}+ {loading ? t('auth.processing') : mode === 'login' ? t('auth.login') : t('auth.register')}</button></form><button@@ -82,7 +88,7 @@ export default function AuthPage() {className="linkish"onClick={() => setMode(mode === 'login' ? 'register' : 'login')}>- {mode === 'login' ? '没有账号?注册' : '已有账号?登录'}+ {mode === 'login' ? t('auth.toRegister') : t('auth.toLogin')}</button></div><div className="auth-visual" aria-hidden>@@ -91,3 +97,4 @@ export default function AuthPage() {</div>)}+diff --git a/frontend/src/pages/ContactPage.tsx b/frontend/src/pages/ContactPage.tsxindex 7a9add4..6379888 100644--- a/frontend/src/pages/ContactPage.tsx+++ b/frontend/src/pages/ContactPage.tsx@@ -2,19 +2,20 @@ import { useState, type FormEvent } from 'react'import { Link } from 'react-router-dom'import { HelpCircle, Mail, Building2 } from 'lucide-react'import AppShell from '../components/layout/AppShell'-import { CONTACT_CHANNELS, CONTACT_TOPICS } from '../lib/legalContent'+import { useI18n } from '../i18n'const CHANNEL_ICONS = [Mail, HelpCircle, Building2] as const/** 联系我们:渠道说明 + 本地反馈表单(引导发邮件) */export default function ContactPage() {+ const { t, m } = useI18n()/** topic 反馈主题* email 联系邮箱* message 问题描述* sent 是否已生成邮件草稿提示*/- const [topic, setTopic] = useState<string>(CONTACT_TOPICS[0])+ const [topic, setTopic] = useState<string>(m.contact.topics[0])const [email, setEmail] = useState('')const [message, setMessage] = useState('')const [sent, setSent] = useState(false)@@ -22,10 +23,10 @@ export default function ContactPage() {function onSubmit(e: FormEvent) {e.preventDefault()const body = [- `主题:${topic}`,- `联系邮箱:${email.trim() || '(未填写)'}`,+ t('contact.mailSubject', { topic }),+ t('contact.mailEmail', { email: email.trim() || t('contact.mailEmailEmpty') }),'',- message.trim() || '(无详细描述)',+ message.trim() || t('contact.mailEmpty'),].join('\n')const href = `mailto:[email protected]?subject=${encodeURIComponent(`[PRINTFILM] ${topic}`,@@ -39,19 +40,19 @@ export default function ContactPage() {<div className="pf-legal-page pf-contact-page"><header className="pf-legal-hero"><p className="pf-legal-crumb">- <Link to="/">首页</Link>+ <Link to="/">{t('common.home')}</Link><span aria-hidden> / </span>- <span>联系我们</span>+ <span>{t('contact.crumb')}</span></p>- <h1>联系我们</h1>+ <h1>{t('contact.title')}</h1><p className="pf-legal-intro">- 充值、账号、创作任务或合作咨询,欢迎通过以下方式联系。提交前也可先查看{' '}- <Link to="/help">帮助中心</Link>。+ {t('contact.introPrefix')} <Link to="/help">{t('contact.introLink')}</Link>+ {t('contact.introSuffix')}</p></header><div className="pf-contact-channels">- {CONTACT_CHANNELS.map((ch, i) => {+ {m.contact.channels.map((ch, i) => {const Icon = CHANNEL_ICONS[i] || Mailconst isExternal = ch.href?.startsWith('mailto:')return (@@ -64,11 +65,11 @@ export default function ContactPage() {{ch.href ? (isExternal ? (<a className="pf-contact-card-link" href={ch.href}>- {ch.actionLabel || '联系'}+ {ch.actionLabel || t('contact.contactAction')}</a>) : (<Link className="pf-contact-card-link" to={ch.href}>- {ch.actionLabel || '前往'}+ {ch.actionLabel || t('contact.goAction')}</Link>)) : null}@@ -78,59 +79,57 @@ export default function ContactPage() {</div><section className="pf-contact-form-block" aria-labelledby="pf-contact-form-title">- <h2 id="pf-contact-form-title">留言反馈</h2>- <p className="pf-muted">- 填写后将打开您的邮件客户端,预填发往 [email protected] 的草稿,请确认后发送。- </p>+ <h2 id="pf-contact-form-title">{t('contact.formTitle')}</h2>+ <p className="pf-muted">{t('contact.formLead')}</p><form className="pf-contact-form" onSubmit={onSubmit}><label>- <span>问题类型</span>+ <span>{t('contact.topic')}</span><select value={topic} onChange={(e) => setTopic(e.target.value)}>- {CONTACT_TOPICS.map((t) => (- <option key={t} value={t}>- {t}+ {m.contact.topics.map((item) => (+ <option key={item} value={item}>+ {item}</option>))}</select></label><label>- <span>联系邮箱</span>+ <span>{t('contact.email')}</span><inputtype="email"value={email}onChange={(e) => setEmail(e.target.value)}- placeholder="便于我们回复"+ placeholder={t('contact.emailPlaceholder')}autoComplete="email"/></label><label>- <span>问题描述</span>+ <span>{t('contact.message')}</span><textareavalue={message}onChange={(e) => setMessage(e.target.value)}rows={5}- placeholder="请尽量说明账号邮箱、订单号、发生时间与报错信息"+ placeholder={t('contact.messagePlaceholder')}required/></label><button type="submit" className="pf-btn pf-btn-lime">- 打开邮件草稿+ {t('contact.submit')}</button>{sent ? (<p className="pf-contact-sent pf-muted">- 若未自动打开邮件客户端,请直接发送至{' '}+ {t('contact.sentPrefix')}{' '}<a href="mailto:[email protected]">[email protected]</a></p>) : null}</form></section>- <nav className="pf-legal-foot-nav" aria-label="相关页面">- <Link to="/terms">用户协议</Link>- <Link to="/privacy">隐私政策</Link>- <Link to="/help">帮助中心</Link>- <Link to="/pricing">定价充值</Link>+ <nav className="pf-legal-foot-nav" aria-label={t('contact.related')}>+ <Link to="/terms">{t('footer.terms')}</Link>+ <Link to="/privacy">{t('footer.privacy')}</Link>+ <Link to="/help">{t('footer.help')}</Link>+ <Link to="/pricing">{t('contact.pricing')}</Link></nav></div></AppShell>diff --git a/frontend/src/pages/HelpPage.tsx b/frontend/src/pages/HelpPage.tsxindex 02d52c4..cda2670 100644--- a/frontend/src/pages/HelpPage.tsx+++ b/frontend/src/pages/HelpPage.tsx@@ -1,15 +1,12 @@import { useMemo, useState } from 'react'import { Link } from 'react-router-dom'import AppShell from '../components/layout/AppShell'-import {- HELP_CATS,- HELP_FAQ_ITEMS,- HELP_GUIDE_STEPS,- filterHelpFaq,-} from '../lib/helpContent'+import { useI18n } from '../i18n'+import { filterHelpFaq } from '../lib/helpContent'/** 帮助中心整页:分类入口、上手步骤、可搜索 FAQ */export default function HelpPage() {+ const { t, m } = useI18n()/** q 搜索关键词* openFaq 当前展开的 FAQ 下标@@ -17,26 +14,26 @@ export default function HelpPage() {const [q, setQ] = useState('')const [openFaq, setOpenFaq] = useState<number | null>(0)- const faqFiltered = useMemo(() => filterHelpFaq(HELP_FAQ_ITEMS, q), [q])+ const faqFiltered = useMemo(() => filterHelpFaq([...m.help.faq], q), [m.help.faq, q])return (<AppShell><div className="pf-help-page"><header className="pf-help-page-hero">- <h1>帮助中心</h1>- <p className="pf-muted">搜索你遇到的问题,或从下方分类快速进入</p>+ <h1>{t('help.title')}</h1>+ <p className="pf-muted">{t('help.lead')}</p><label className="pf-help-search pf-help-search-lg">- <span className="sr-only">搜索帮助</span>+ <span className="sr-only">{t('help.search')}</span><inputvalue={q}onChange={(e) => setQ(e.target.value)}- placeholder="搜索:下载、工具、充值、漫剧…"+ placeholder={t('help.searchPlaceholder')}/></label></header><div className="pf-help-cats pf-help-cats-lg">- {HELP_CATS.map((c) => (+ {m.help.cats.map((c) => (<Link key={c.id} to={c.href} className="pf-help-cat"><strong>{c.title}</strong><span>{c.desc}</span>@@ -44,10 +41,10 @@ export default function HelpPage() {))}</div>- <section className="pf-help-guide-block" aria-labelledby="pf-help-guide-title">- <h2 id="pf-help-guide-title">上手四步</h2>+ <section className="pf-help-guide-block" aria-labelledby="pf-land-guide-title">+ <h2 id="pf-land-guide-title">{t('help.guideTitle')}</h2><ol className="pf-help-steps pf-help-steps-page">- {HELP_GUIDE_STEPS.map((s) => (+ {m.help.steps.map((s) => (<li key={s.n}><span className="pf-help-step-n" aria-hidden>{s.n}@@ -62,7 +59,7 @@ export default function HelpPage() {</section><section id="faq" className="pf-help-faq-block">- <h2>常见问题</h2>+ <h2>{t('help.faqTitle')}</h2><div className="pf-help-faq">{faqFiltered.map((item, i) => {const expanded = openFaq === i@@ -81,17 +78,21 @@ export default function HelpPage() {</div>)})}- {faqFiltered.length === 0 ? <p className="pf-muted">没有匹配的问题,试试「下载」「工具」「充值」</p> : null}+ {faqFiltered.length === 0 ? <p className="pf-muted">{t('help.noMatch')}</p> : null}</div></section><section className="pf-help-more"><p className="pf-muted">- 更多操作可在{' '}- <Link to="/settings">个人中心</Link> 查看项目与创作记录,或前往{' '}- <Link to="/pricing">定价</Link> 充值后继续创作。也可查阅{' '}- <Link to="/terms">用户协议</Link>、<Link to="/privacy">隐私政策</Link>,或{' '}- <Link to="/contact">联系我们</Link>。+ {t('help.morePrefix')}{' '}+ <Link to="/settings">{t('help.profile')}</Link>+ {t('help.moreMid')}{' '}+ <Link to="/pricing">{t('help.pricing')}</Link>+ {t('help.moreMid2')}{' '}+ <Link to="/terms">{t('help.terms')}</Link>、<Link to="/privacy">{t('help.privacy')}</Link>+ {t('help.moreOr')}+ <Link to="/contact">{t('help.contact')}</Link>+ {t('help.moreSuffix')}</p></section></div>diff --git a/frontend/src/pages/HistoryPage.tsx b/frontend/src/pages/HistoryPage.tsxindex 3b4e4c5..4e81910 100644--- a/frontend/src/pages/HistoryPage.tsx+++ b/frontend/src/pages/HistoryPage.tsx@@ -27,6 +27,7 @@ import {} from '../lib/clientDownload'import { isRunning, STATUS_CN, statusTone } from '../lib/status'import { pageCountOf } from '../lib/pagination'+import { formatDateTime, useI18n } from '../i18n'type HistoryItem = Omit<Project, 'shots'> & {published?: boolean@@ -37,21 +38,19 @@ type HistoryItem = Omit<Project, 'shots'> & {updated_at?: string}+type HistoryTab = 'all' | 'draft' | 'running' | 'done' | 'published'+const PAGE_SIZE_DEFAULT = 8-const TAB_STATUS: Record<string, 'all' | 'draft' | 'running' | 'done' | 'published'> = {- 全部: 'all',- 草稿: 'draft',- 生成中: 'running',- 已完成: 'done',- 已发布: 'published',+const TAB_STATUS: Record<HistoryTab, 'all' | 'draft' | 'running' | 'done' | 'published'> = {+ all: 'all',+ draft: 'draft',+ running: 'running',+ done: 'done',+ published: 'published',}-const TYPE_OPTIONS: Array<{ value: '' | 'full' | 'image_text'; label: string }> = [- { value: '', label: '全部类型' },- { value: 'full', label: '成片视频' },- { value: 'image_text', label: '图文视频' },-]+const HISTORY_TABS: HistoryTab[] = ['all', 'draft', 'running', 'done', 'published']function canDownload(p: HistoryItem) {return p.status === 'DONE' && Boolean(p.final_video_url)@@ -68,6 +67,7 @@ function statusBadgeClass(status: string) {export default function HistoryPage() {const nav = useNavigate()+ const { t, m, locale } = useI18n()/** items 当前页项目* total 筛选后总数(后端)@@ -97,7 +97,7 @@ export default function HistoryPage() {const [packing, setPacking] = useState(false)const [packProgress, setPackProgress] = useState('')const [selected, setSelected] = useState<Set<number>>(new Set())- const [tab, setTab] = useState('全部')+ const [tab, setTab] = useState<HistoryTab>('all')const [typeMode, setTypeMode] = useState<'' | 'full' | 'image_text'>('')const [q, setQ] = useState('')const [debouncedQ, setDebouncedQ] = useState('')@@ -138,7 +138,7 @@ export default function HistoryPage() {return new Set([...prev].filter((id) => ids.has(id)))})} catch (err) {- setError(err instanceof Error ? err.message : '加载失败')+ setError(err instanceof Error ? err.message : t('common.loadFailed'))} finally {setLoading(false)}@@ -200,10 +200,10 @@ export default function HistoryPage() {async function remove(id: number) {const ok = await dialog.confirm({- title: '删除项目',- message: '确定删除该项目?素材与成片将一并清除。',- confirmText: '删除',- cancelText: '取消',+ title: t('history.deleteTitle'),+ message: t('history.deleteMessage'),+ confirmText: t('common.delete'),+ cancelText: t('common.cancel'),tone: 'danger',})if (!ok) return@@ -212,7 +212,7 @@ export default function HistoryPage() {await api.deleteProject(id)await load()} catch (err) {- setError(err instanceof Error ? err.message : '删除失败')+ setError(err instanceof Error ? err.message : t('history.deleteFailed'))} finally {setBusyId(null)}@@ -229,7 +229,7 @@ export default function HistoryPage() {projectId: p.id,})} catch (err) {- setError(err instanceof Error ? err.message : '下载失败')+ setError(err instanceof Error ? err.message : t('history.downloadFailed'))} finally {setBusyId(null)}@@ -246,7 +246,7 @@ export default function HistoryPage() {projectId: preview.projectId,})} catch (err) {- setError(err instanceof Error ? err.message : '下载失败')+ setError(err instanceof Error ? err.message : t('history.downloadFailed'))} finally {setBusyId(null)}@@ -268,7 +268,7 @@ export default function HistoryPage() {)triggerBlobDownload(blob, filename)} catch (err) {- setError(err instanceof Error ? err.message : '打包失败')+ setError(err instanceof Error ? err.message : t('history.packFailed'))} finally {setPacking(false)setPackProgress('')@@ -284,43 +284,43 @@ export default function HistoryPage() {<AppShell active="kepu" wide><div className="pf-history-head"><div>- <h1>科普历史</h1>- <p>管理你的科普视频项目,继续编辑或下载成片。</p>+ <h1>{t('history.title')}</h1>+ <p>{t('history.lead')}</p></div><div className="pf-history-head-actions"><button type="button" className="pf-btn pf-btn-lime pf-btn-icon" onClick={() => nav('/studio/new')}><IconPlus size={16} />- 新建科普+ {t('history.newKepu')}</button><Link to="/drama" className="pf-btn pf-btn-ghost pf-btn-sm">- 去漫剧+ {t('history.goDrama')}</Link></div></div><div className="pf-stats"><StatCard- label="总作品数"+ label={t('history.statTotal')}value={stats.total}trend="—"icon={<IconClapper size={18} />}/><StatCard- label="生成中"+ label={t('history.statRunning')}value={stats.generating}- trend={stats.generating ? '正在生成中' : '暂无任务'}+ trend={stats.generating ? t('history.runningNow') : t('history.noTask')}icon={<IconRefresh size={18} />}/><StatCard- label="已完成"+ label={t('history.statDone')}value={stats.done}trend="—"icon={<IconSend size={18} />}/><StatCard- label="本月时长"+ label={t('history.statDuration')}value="—"- trend="额度统计即将推出"+ trend={t('history.durationSoon')}icon={<IconClock size={18} />}/></div>@@ -329,30 +329,31 @@ export default function HistoryPage() {<section className="pf-history-main"><div className="pf-history-filters"><PillTabs- items={['全部', '草稿', '生成中', '已完成', '已发布']}- value={tab}- onChange={setTab}- ariaLabel="项目状态"+ items={HISTORY_TABS.map((id) => m.history.tabs[id])}+ value={m.history.tabs[tab]}+ onChange={(label) => {+ const next = HISTORY_TABS.find((id) => m.history.tabs[id] === label)+ if (next) setTab(next)+ }}+ ariaLabel={t('history.statusAria')}/><div className="pf-history-filter-right"><selectclassName="pf-type-select"value={typeMode}- aria-label="项目类型"+ aria-label={t('history.typeAria')}onChange={(e) => setTypeMode(e.target.value as '' | 'full' | 'image_text')}>- {TYPE_OPTIONS.map((opt) => (- <option key={opt.value || 'all'} value={opt.value}>- {opt.label}- </option>- ))}+ <option value="">{t('history.typeAll')}</option>+ <option value="full">{t('history.typeFull')}</option>+ <option value="image_text">{t('history.typeImageText')}</option></select><label className="pf-search-field"><IconSearch size={15} /><inputvalue={q}onChange={(e) => setQ(e.target.value)}- placeholder="搜索项目名称"+ placeholder={t('history.searchPlaceholder')}/></label></div>@@ -367,15 +368,15 @@ export default function HistoryPage() {><IconDownload size={15} />{packing- ? `打包中 ${packProgress}…`- : `打包下载 (${selectedDownloadable.length})`}+ ? t('history.packing', { progress: packProgress })+ : t('history.packDownload', { count: selectedDownloadable.length })}</button></div>{error ? <p className="pf-error">{error}</p> : null}- {loading ? <p className="pf-muted">加载中…</p> : null}+ {loading ? <p className="pf-muted">{t('common.loading')}</p> : null}{!loading && total === 0 ? (- <div className="pf-history-empty">暂无科普项目,点击「新建科普」开始创作</div>+ <div className="pf-history-empty">{t('history.empty')}</div>) : null}<div className="pf-project-list">@@ -384,7 +385,6 @@ export default function HistoryPage() {const ratio =p.output_ratio || (p.pipeline_mode === 'image_text' ? '9:16' : '16:9')const tplName = templates[p.template_id] || p.template_id- const when = new Date(p.updated_at || p.created_at).toLocaleString()return (<article key={p.id} className="pf-project-card"><label className="pf-project-check">@@ -403,7 +403,7 @@ export default function HistoryPage() {{p.cover_url ? (<img src={api.assetUrl(p.cover_url, p.updated_at)} alt="" />) : (- <div className="ph">无封面</div>+ <div className="ph">{t('history.noCover')}</div>)}{isRunning(p.status) ? (<span className="pf-thumb-progress">{p.progress}%</span>@@ -412,14 +412,17 @@ export default function HistoryPage() {<div className="pf-project-info"><h3>{p.title}- {p.published ? <span className="pf-badge ok" style={{ marginLeft: 8 }}>已发布</span> : null}+ {p.published ? <span className="pf-badge ok" style={{ marginLeft: 8 }}>{t('history.published')}</span> : null}</h3><div className="pf-project-meta"><span className={`pf-badge ${badge}`}>{STATUS_CN[p.status] || p.status}</span><span className="pf-muted">- 模板 {tplName} · {when}+ {t('history.templateMeta', {+ name: tplName,+ when: formatDateTime(p.updated_at || p.created_at, locale),+ })}</span></div>{isRunning(p.status) ? (@@ -433,7 +436,7 @@ export default function HistoryPage() {<div className="pf-project-actions"><button type="button" className="pf-btn-text" onClick={() => continueEdit(p)}><IconEdit size={14} />- 继续编辑+ {t('history.continueEdit')}</button><buttontype="button"@@ -449,7 +452,7 @@ export default function HistoryPage() {}><IconEye size={14} />- 预览+ {t('common.preview')}</button><buttontype="button"@@ -458,17 +461,17 @@ export default function HistoryPage() {onClick={() => downloadOne(p)}><IconDownload size={14} />- {busyId === p.id ? '下载中…' : '下载'}+ {busyId === p.id ? t('common.downloading') : t('common.download')}</button>- <button type="button" className="pf-btn-text" disabled title="即将推出">+ <button type="button" className="pf-btn-text" disabled title={t('common.comingSoon')}><IconCopy size={14} />- 复制+ {t('common.copy')}</button><buttontype="button"className="pf-icon-btn danger"disabled={busyId === p.id}- title="删除"+ title={t('common.delete')}onClick={() => remove(p.id)}><IconTrash size={16} />@@ -490,7 +493,7 @@ export default function HistoryPage() {setPage(1)}}onChange={setPage}- ariaLabel="科普历史分页"+ ariaLabel={t('history.pagination')}/>) : null}</section>@@ -516,14 +519,14 @@ export default function HistoryPage() {onClick={downloadPreview}><IconDownload size={14} />- {busyId === preview.projectId ? '下载中…' : '下载'}+ {busyId === preview.projectId ? t('common.downloading') : t('common.download')}</button><buttontype="button"className="pf-btn pf-btn-ghost pf-btn-sm"onClick={() => setPreview(null)}>- 关闭+ {t('common.close')}</button></div></div>diff --git a/frontend/src/pages/HomePage.tsx b/frontend/src/pages/HomePage.tsxindex 03fd40a..ab92119 100644--- a/frontend/src/pages/HomePage.tsx+++ b/frontend/src/pages/HomePage.tsx@@ -6,22 +6,18 @@ import AppShell from '../components/layout/AppShell'import Button from '../components/ui/Button'import ComingSoon from '../components/ui/ComingSoon'import CreateChoiceModal from '../components/ui/CreateChoiceModal'+import { useI18n } from '../i18n'import { getDramaImageStylePreviewUrl } from '../lib/dramaImageStylePreviews'-import {- HOME_AUDIENCES,- HOME_CAPABILITIES,- HOME_DRAMA_STEPS,- HOME_KEPU_STEPS,- HOME_PIPELINE,-} from '../lib/homeLanding'-import { PRODUCT_ICONS, TOOL_DEFS } from '../lib/toolsCatalog'+import { PRODUCT_ICONS, localizeToolDefs } from '../lib/toolsCatalog'export default function HomePage() {const nav = useNavigate()+ const { t, m } = useI18n()const loggedIn = Boolean(localStorage.getItem('token'))const [createOpen, setCreateOpen] = useState(false)const DramaIcon = PRODUCT_ICONS.dramaconst KepuIcon = PRODUCT_ICONS.kepu+ const tools = localizeToolDefs(m)// 未登录去登录;已登录弹出产品选择function goCreate() {@@ -43,20 +39,18 @@ export default function HomePage() {<div className="pf-land-hero-copy"><p className="pf-land-kicker">PRINTFILM</p><h1>- 把故事做成+ {t('home.headlineBefore')}<br />- <em>能播的片子</em>+ <em>{t('home.headlineEm')}</em></h1>- <p className="pf-land-lede">- AI 漫剧从剧本到分集成片,科普视频从分镜到配音合成。一套工作台,两种出片方式。- </p>+ <p className="pf-land-lede">{t('home.lede')}</p><div className="pf-land-cta"><Button variant="lime" size="lg" icon onClick={goCreate}>- 开始创作+ {t('home.startCreate')}<ArrowRight size={16} strokeWidth={2} aria-hidden /></Button><Button variant="ghost" size="lg" icon to="/tools">- 浏览工具+ {t('home.browseTools')}<ArrowRight size={16} strokeWidth={2} aria-hidden /></Button></div>@@ -64,26 +58,26 @@ export default function HomePage() {<div className="pf-land-frames" aria-hidden><figure className="pf-land-frame is-drama"><img src={getDramaImageStylePreviewUrl('ancient-chinese-mythology')} alt="" />- <figcaption>AI 漫剧</figcaption>+ <figcaption>{t('home.dramaTitle')}</figcaption></figure><figure className="pf-land-frame is-kepu"><img src={getDramaImageStylePreviewUrl('neon-cyberpunk-film')} alt="" />- <figcaption>科普视频</figcaption>+ <figcaption>{t('home.kepuTitle')}</figcaption></figure></div></section>- <section className="pf-land-products" id="products" aria-label="主产品">+ <section className="pf-land-products" id="products" aria-label={t('home.products')}><button type="button" className="pf-land-product is-drama" onClick={() => goAuthOr('/drama')}><span className="pf-land-product-icon" aria-hidden><DramaIcon size={26} strokeWidth={1.6} /></span><span className="pf-land-product-body">- <strong>AI 漫剧</strong>- <em>给短剧创作者</em>- <span>从一句话生成剧本,沉淀角色与场景,再按集分镜成片。</span>+ <strong>{t('home.dramaTitle')}</strong>+ <em>{t('home.dramaFor')}</em>+ <span>{t('home.dramaDesc')}</span><span className="pf-land-chips">- {HOME_DRAMA_STEPS.map((label) => (+ {m.home.dramaSteps.map((label) => (<span key={label}>{label}</span>))}</span>@@ -97,11 +91,11 @@ export default function HomePage() {<KepuIcon size={26} strokeWidth={1.6} /></span><span className="pf-land-product-body">- <strong>科普视频</strong>- <em>给知识创作者</em>- <span>选定画面风格,写好分镜旁白,沿流水线出讲解短片。</span>+ <strong>{t('home.kepuTitle')}</strong>+ <em>{t('home.kepuFor')}</em>+ <span>{t('home.kepuDesc')}</span><span className="pf-land-chips">- {HOME_KEPU_STEPS.map((label) => (+ {m.home.kepuSteps.map((label) => (<span key={label}>{label}</span>))}</span>@@ -114,11 +108,11 @@ export default function HomePage() {<section className="pf-land-pipeline" aria-labelledby="pf-land-pipeline-title"><header className="pf-land-section-head">- <p className="pf-land-kicker">How it works</p>- <h2 id="pf-land-pipeline-title">三步出片</h2>+ <p className="pf-land-kicker">{t('home.howKicker')}</p>+ <h2 id="pf-land-pipeline-title">{t('home.howTitle')}</h2></header><ol className="pf-land-pipeline-list">- {HOME_PIPELINE.map((item) => (+ {m.home.pipeline.map((item) => (<li key={item.step}><span className="pf-land-step-no">{item.step}</span><strong>{item.title}</strong>@@ -130,11 +124,11 @@ export default function HomePage() {<section className="pf-land-caps" aria-labelledby="pf-land-caps-title"><header className="pf-land-section-head">- <p className="pf-land-kicker">Capabilities</p>- <h2 id="pf-land-caps-title">工作台里真正能用的</h2>+ <p className="pf-land-kicker">{t('home.capsKicker')}</p>+ <h2 id="pf-land-caps-title">{t('home.capsTitle')}</h2></header><div className="pf-land-cap-grid">- {HOME_CAPABILITIES.map((item) => (+ {m.home.capabilities.map((item) => (<article key={item.title}><strong>{item.title}</strong><p>{item.desc}</p>@@ -146,28 +140,28 @@ export default function HomePage() {<section className="pf-land-tools" id="tools"><header className="pf-land-section-head is-row"><div>- <p className="pf-land-kicker">Tools</p>- <h2>单点创作工具</h2>+ <p className="pf-land-kicker">{t('home.toolsKicker')}</p>+ <h2>{t('home.toolsTitle')}</h2></div><Link to="/tools" className="pf-link">- 全部工具 →+ {t('home.allTools')}</Link></header><div className="pf-land-tool-grid">- {TOOL_DEFS.map((t) => {- const Icon = t.icon+ {tools.map((tool) => {+ const Icon = tool.iconreturn (<Link- key={t.id}- to={`/tools/${t.id}`}- className={`pf-land-tool-card${t.soon ? ' is-soon' : ''}`}+ key={tool.id}+ to={`/tools/${tool.id}`}+ className={`pf-land-tool-card${tool.soon ? ' is-soon' : ''}`}><span className="pf-land-tool-icon" aria-hidden><Icon size={20} strokeWidth={1.7} /></span>- <strong>{t.title}</strong>- <span>{t.desc}</span>- {t.soon ? <ComingSoon /> : null}+ <strong>{tool.title}</strong>+ <span>{tool.desc}</span>+ {tool.soon ? <ComingSoon /> : null}</Link>)})}@@ -176,11 +170,11 @@ export default function HomePage() {<section className="pf-land-who" aria-labelledby="pf-land-who-title"><header className="pf-land-section-head">- <p className="pf-land-kicker">For</p>- <h2 id="pf-land-who-title">适合谁用</h2>+ <p className="pf-land-kicker">{t('home.whoKicker')}</p>+ <h2 id="pf-land-who-title">{t('home.whoTitle')}</h2></header><div className="pf-land-who-grid">- {HOME_AUDIENCES.map((item) => (+ {m.home.audiences.map((item) => (<article key={item.title}><strong>{item.title}</strong><p>{item.desc}</p>@@ -191,16 +185,16 @@ export default function HomePage() {<section className="pf-land-close"><div>- <h2>从一条创意开始</h2>- <p>登录后选择漫剧或科普,进入对应工作台。</p>+ <h2>{t('home.closeTitle')}</h2>+ <p>{t('home.closeLead')}</p></div><div className="pf-land-cta"><Button variant="lime" size="lg" icon onClick={goCreate}>- 开始创作+ {t('home.startCreate')}<ArrowRight size={16} strokeWidth={2} aria-hidden /></Button><Button variant="ghost" size="lg" to="/pricing">- 查看定价+ {t('home.viewPricing')}</Button></div></section>@@ -208,17 +202,17 @@ export default function HomePage() {<footer className="pf-land-foot"><div className="pf-land-foot-brand"><strong>PRINTFILM</strong>- <p>AI 漫剧与科普视频创作平台</p>+ <p>{t('home.footBrand')}</p></div>- <nav className="pf-land-foot-nav" aria-label="页脚导航">- <Link to="/drama">漫剧</Link>- <Link to="/history">科普</Link>- <Link to="/tools">工具</Link>- <Link to="/pricing">定价</Link>- <Link to="/help">帮助</Link>- <Link to="/terms">用户协议</Link>- <Link to="/privacy">隐私政策</Link>- <Link to="/contact">联系我们</Link>+ <nav className="pf-land-foot-nav" aria-label={t('home.footNav')}>+ <Link to="/drama">{t('nav.drama')}</Link>+ <Link to="/history">{t('nav.kepu')}</Link>+ <Link to="/tools">{t('nav.tools')}</Link>+ <Link to="/pricing">{t('nav.pricing')}</Link>+ <Link to="/help">{t('nav.help')}</Link>+ <Link to="/terms">{t('footer.terms')}</Link>+ <Link to="/privacy">{t('footer.privacy')}</Link>+ <Link to="/contact">{t('footer.contact')}</Link></nav><p className="pf-land-copy">© {new Date().getFullYear()} PRINTFILM. All rights reserved.</p></footer>diff --git a/frontend/src/pages/LegalDocPage.tsx b/frontend/src/pages/LegalDocPage.tsxindex 86f5bee..09bb30e 100644--- a/frontend/src/pages/LegalDocPage.tsx+++ b/frontend/src/pages/LegalDocPage.tsx@@ -1,19 +1,21 @@import { Link } from 'react-router-dom'import AppShell from '../components/layout/AppShell'-import { LEGAL_DOCS, type LegalDoc } from '../lib/legalContent'+import { useI18n } from '../i18n'+import { getLegalDoc, type LegalDoc } from '../lib/legalContent'/** 渲染单份法律文档正文 */function LegalBody({ doc }: { doc: LegalDoc }) {+ const { t } = useI18n()return (<article className="pf-legal-doc"><header className="pf-legal-hero"><p className="pf-legal-crumb">- <Link to="/">首页</Link>+ <Link to="/">{t('common.home')}</Link><span aria-hidden> / </span><span>{doc.title}</span></p><h1>{doc.title}</h1>- <p className="pf-legal-meta">更新日期:{doc.updatedAt}</p>+ <p className="pf-legal-meta">{t('legal.updatedAt', { date: doc.updatedAt })}</p><p className="pf-legal-intro">{doc.intro}</p></header>@@ -35,11 +37,11 @@ function LegalBody({ doc }: { doc: LegalDoc }) {))}</div>- <nav className="pf-legal-foot-nav" aria-label="相关页面">- <Link to="/terms">用户协议</Link>- <Link to="/privacy">隐私政策</Link>- <Link to="/contact">联系我们</Link>- <Link to="/help">帮助中心</Link>+ <nav className="pf-legal-foot-nav" aria-label={t('legal.related')}>+ <Link to="/terms">{t('footer.terms')}</Link>+ <Link to="/privacy">{t('footer.privacy')}</Link>+ <Link to="/contact">{t('footer.contact')}</Link>+ <Link to="/help">{t('footer.help')}</Link></nav></article>)@@ -47,10 +49,12 @@ function LegalBody({ doc }: { doc: LegalDoc }) {/** 用户协议页 */export function TermsPage() {+ const { locale } = useI18n()+ const doc = getLegalDoc('terms', locale)return (<AppShell><div className="pf-legal-page">- <LegalBody doc={LEGAL_DOCS.terms} />+ <LegalBody doc={doc} /></div></AppShell>)@@ -58,10 +62,12 @@ export function TermsPage() {/** 隐私政策页 */export function PrivacyPage() {+ const { locale } = useI18n()+ const doc = getLegalDoc('privacy', locale)return (<AppShell><div className="pf-legal-page">- <LegalBody doc={LEGAL_DOCS.privacy} />+ <LegalBody doc={doc} /></div></AppShell>)diff --git a/frontend/src/pages/PricingPage.tsx b/frontend/src/pages/PricingPage.tsxindex 22ce2b0..c1daf20 100644--- a/frontend/src/pages/PricingPage.tsx+++ b/frontend/src/pages/PricingPage.tsx@@ -14,30 +14,13 @@ import PaymentModal, { type PayCheckout } from '../components/billing/PaymentModimport PricingWalletCard from '../components/billing/PricingWalletCard'import TopupHistoryModal from '../components/billing/TopupHistoryModal'import { api, type BillingSku, type UsageSummary, type Wallet } from '../api'+import { useI18n } from '../i18n'type PayType = 'alipay' | 'wxpay'type SkuView = BillingSku & { recommended?: boolean }-const HERO_FEATURES = [- { icon: Zap, text: '充值即时到账,马上可用' },- { icon: ShieldCheck, text: '支付安全保障' },- { icon: Infinity, text: '余额永久有效' },-] as const--const SKU_LABELS: Record<string, string> = {- topup_10: '体验充值',- topup_49: '基础充值',- topup_99: '进阶充值',- topup_199: '专业充值',-}--const SKU_HINTS: Record<string, string> = {- topup_10: '适合初次体验',- topup_49: '日常创作够用',- topup_99: '高频创作推荐',- topup_199: '团队 / 批量生产',-}+const HERO_FEATURE_KEYS = ['featInstant', 'featSafe', 'featForever'] as constfunction yuan(fen: number) {return (fen / 100).toFixed(2)@@ -51,6 +34,7 @@ function yuanShort(fen: number) {/** 定价与充值页 */export default function PricingPage() {const nav = useNavigate()+ const { t, m } = useI18n()const [params] = useSearchParams()const [wallet, setWallet] = useState<Wallet | null>(null)const [usage, setUsage] = useState<UsageSummary | null>(null)@@ -93,9 +77,9 @@ export default function PricingPage() {api.billingSkus().then((r) => setSkus((r.skus || []) as SkuView[]))refresh()if (params.get('paid') === '1') {- setHint('支付完成。若余额未更新,请稍候刷新本页。')- const t = window.setInterval(() => refresh(), 2500)- return () => window.clearInterval(t)+ setHint(t('pricing.paidHint'))+ const timerId = window.setInterval(() => refresh(), 2500)+ return () => window.clearInterval(timerId)}}, [])@@ -108,7 +92,7 @@ export default function PricingPage() {setError('')try {const order = await api.createBillingOrder(sku.id, payType)- const label = SKU_LABELS[sku.id] || order.sku_name || sku.name+ const label = m.pricing.skus[sku.id as keyof typeof m.pricing.skus] || sku.namesetCheckout({out_trade_no: order.out_trade_no,sku_id: order.sku_id || sku.id,@@ -121,7 +105,7 @@ export default function PricingPage() {expire_seconds: order.expire_seconds ?? 300,})} catch (e) {- setError(e instanceof Error ? e.message : '下单失败')+ setError(e instanceof Error ? e.message : t('pricing.orderFailed'))} finally {setBusy(null)}@@ -133,11 +117,11 @@ export default function PricingPage() {}function pickUnavailable(label: string) {- setPayTip(`${label}即将上线,请先使用支付宝或微信支付`)+ setPayTip(t('pricing.unavailable', { label }))}async function onPaid() {- setHint('支付成功,余额已更新')+ setHint(t('pricing.paidOk'))setCheckout(null)await refresh()}@@ -148,21 +132,27 @@ export default function PricingPage() {<section className="pf-pricing-hero-band"><div className="pf-pricing-hero-inner"><div className="pf-pricing-hero-copy">- <h1>按需充值,灵活使用</h1>- <p>按实际消耗 token 计费,余量永久有效,不设过期</p>+ <h1>{t('pricing.title')}</h1>+ <p>{t('pricing.lead')}</p><ul className="pf-pricing-hero-features">- {HERO_FEATURES.map(({ icon: Icon, text }) => (- <li key={text}>+ {HERO_FEATURE_KEYS.map((key, i) => {+ const icons = [Zap, ShieldCheck, Infinity] as const+ const Icon = icons[i]+ return (+ <li key={key}><span className="pf-pricing-hero-feature-icon" aria-hidden><Icon size={15} strokeWidth={2.2} /></span>- {text}+ {t(`pricing.${key}`)}</li>- ))}+ )+ })}</ul>{!loggedIn ? (<p className="pf-pricing-guest-tip">- <Link to="/auth?next=%2Fpricing">登录</Link> 后查看余额与本月用量+ {t('pricing.guestPrefix')}+ <Link to="/auth?next=%2Fpricing">{t('pricing.guestLogin')}</Link>+ {t('pricing.guestSuffix')}</p>) : null}</div>@@ -180,12 +170,12 @@ export default function PricingPage() {{hint ? <p className="pf-pricing-hint">{hint}</p> : null}{error ? <p className="pf-error pf-pricing-error">{error}</p> : null}- <section className="pf-pricing-pay-section" aria-label="支付方式">+ <section className="pf-pricing-pay-section" aria-label={t('pricing.payMethods')}><header className="pf-pricing-section-head is-row">- <h2>支付方式</h2>+ <h2>{t('pricing.payMethods')}</h2><div className="pf-pricing-pay-trust"><ShieldCheck size={16} aria-hidden />- <span>支付安全保障</span>+ <span>{t('pricing.paySafe')}</span></div></header>@@ -199,8 +189,8 @@ export default function PricingPage() {aria-pressed={payType === 'alipay'}><PaymentBrandIcon brand="alipay" size="md" />- <span className="pf-pricing-pay-tile-label">支付宝</span>- <span className="pf-pricing-pay-tile-badge">推荐</span>+ <span className="pf-pricing-pay-tile-label">{t('pricing.alipay')}</span>+ <span className="pf-pricing-pay-tile-badge">{t('pricing.recommended')}</span>{payType === 'alipay' ? (<span className="pf-pricing-pay-tile-check" aria-hidden><Check size={14} strokeWidth={3} />@@ -215,7 +205,7 @@ export default function PricingPage() {aria-pressed={payType === 'wxpay'}><PaymentBrandIcon brand="wxpay" size="md" />- <span className="pf-pricing-pay-tile-label">微信支付</span>+ <span className="pf-pricing-pay-tile-label">{t('pricing.wechat')}</span>{payType === 'wxpay' ? (<span className="pf-pricing-pay-tile-check" aria-hidden><Check size={14} strokeWidth={3} />@@ -226,47 +216,48 @@ export default function PricingPage() {<buttontype="button"className="pf-pricing-pay-tile is-disabled"- title="即将上线"- onClick={() => pickUnavailable('银联支付')}+ title={t('pricing.soonTitle')}+ onClick={() => pickUnavailable(t('pricing.unionpay'))}><PaymentBrandIcon brand="unionpay" size="md" />- <span className="pf-pricing-pay-tile-label">银联支付</span>- <span className="pf-pricing-pay-tile-soon">即将上线</span>+ <span className="pf-pricing-pay-tile-label">{t('pricing.unionpay')}</span>+ <span className="pf-pricing-pay-tile-soon">{t('common.comingSoon')}</span></button><buttontype="button"className="pf-pricing-pay-tile is-disabled"- title="企业用户请联系客服"- onClick={() => pickUnavailable('对公转账')}+ title={t('pricing.transferTitle')}+ onClick={() => pickUnavailable(t('pricing.transfer'))}><span className="pf-pricing-pay-tile-icon" aria-hidden><Building2 size={22} strokeWidth={1.8} /></span>- <span className="pf-pricing-pay-tile-label">对公转账</span>- <span className="pf-pricing-pay-tile-sub">企业用户</span>+ <span className="pf-pricing-pay-tile-label">{t('pricing.transfer')}</span>+ <span className="pf-pricing-pay-tile-sub">{t('pricing.enterprise')}</span></button></div></section><section className="pf-pricing-skus" id="pricing-skus"><header className="pf-pricing-section-head">- <h2>选择充值金额</h2>+ <h2>{t('pricing.chooseAmount')}</h2></header><div className="pf-pricing-sku-grid">{displaySkus.map((sku) => {const bonus = sku.credit_fen - sku.amount_fenconst recommended = Boolean(sku.recommended)- const label = SKU_LABELS[sku.id] || sku.name- const tierHint = SKU_HINTS[sku.id] || '余额永久有效'+ const label = m.pricing.skus[sku.id as keyof typeof m.pricing.skus] || sku.name+ const tierHint =+ m.pricing.skuHints[sku.id as keyof typeof m.pricing.skuHints] || t('pricing.foreverHint')return (<articlekey={sku.id}id={`sku-${sku.id}`}className={`pf-pricing-sku-card${recommended ? ' is-recommended' : ''}`}>- {recommended ? <span className="pf-pricing-rec-badge">推荐</span> : null}+ {recommended ? <span className="pf-pricing-rec-badge">{t('pricing.recommended')}</span> : null}<p className="pf-pricing-sku-tier">{label}</p><p className="pf-pricing-sku-hint">{tierHint}</p><div className="pf-pricing-sku-price">@@ -274,10 +265,10 @@ export default function PricingPage() {<strong>{(sku.amount_fen / 100).toFixed(0)}</strong></div><p className="pf-pricing-sku-credit">- 到账 <em>¥{yuan(sku.credit_fen)}</em>+ {t('pricing.credit')} <em>¥{yuan(sku.credit_fen)}</em></p>{bonus > 0 ? (- <p className="pf-pricing-sku-bonus">额外赠送 ¥{yuanShort(bonus)}</p>+ <p className="pf-pricing-sku-bonus">{t('pricing.bonus', { amount: yuanShort(bonus) })}</p>) : (<p className="pf-pricing-sku-bonus is-empty"> </p>)}@@ -287,7 +278,7 @@ export default function PricingPage() {disabled={Boolean(busy)}onClick={() => pay(sku)}>- {busy === sku.id ? '下单中…' : '立即充值'}+ {busy === sku.id ? t('pricing.ordering') : t('pricing.payNow')}</button></article>)@@ -301,11 +292,11 @@ export default function PricingPage() {<CreditCard size={28} strokeWidth={1.6} /></div><div>- <h3>计费说明</h3>+ <h3>{t('pricing.billingTitle')}</h3><ul>- <li>拆分镜、出图、配音、AI 视频分别按上游 token 用量计费</li>- <li>开始生成时预扣估算金额,结束后按实际用量结算(多退少补)</li>- <li>图文模式成本更低;开启 AI 动态视频时消耗更高</li>+ <li>{t('pricing.billing1')}</li>+ <li>{t('pricing.billing2')}</li>+ <li>{t('pricing.billing3')}</li></ul></div></article>@@ -314,11 +305,11 @@ export default function PricingPage() {<Check size={28} strokeWidth={2.5} /></div><div>- <h3>为什么按量计费</h3>+ <h3>{t('pricing.whyTitle')}</h3><ul className="pf-pricing-checks">- <li>无需订阅,用多少充多少</li>- <li>余额永久有效,不设过期</li>- <li>账单清晰可查,每次调用可追溯</li>+ <li>{t('pricing.why1')}</li>+ <li>{t('pricing.why2')}</li>+ <li>{t('pricing.why3')}</li></ul></div></article>@@ -327,12 +318,12 @@ export default function PricingPage() {<footer className="pf-pricing-site-foot"><p className="pf-pricing-site-brand"><Link to="/">PRINTFILM</Link>- <span> · AI 短视频创作伙伴</span>+ <span> · {t('pricing.footBrand')}</span></p>- <nav className="pf-pricing-site-links" aria-label="页脚链接">- <Link to="/terms">用户协议</Link>- <Link to="/privacy">隐私政策</Link>- <Link to="/contact">联系我们</Link>+ <nav className="pf-pricing-site-links" aria-label={t('footer.links')}>+ <Link to="/terms">{t('footer.terms')}</Link>+ <Link to="/privacy">{t('footer.privacy')}</Link>+ <Link to="/contact">{t('footer.contact')}</Link></nav><p className="pf-pricing-site-copy">© {new Date().getFullYear()} PRINTFILM. All rights reserved.</p></footer>diff --git a/frontend/src/pages/SettingsPage.tsx b/frontend/src/pages/SettingsPage.tsxindex 9be6528..0aa0029 100644--- a/frontend/src/pages/SettingsPage.tsx+++ b/frontend/src/pages/SettingsPage.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react'+import { useEffect, useState } from 'react'import { Link, useNavigate, useSearchParams } from 'react-router-dom'import AppShell from '../components/layout/AppShell'import UserAvatar from '../components/UserAvatar'@@ -12,6 +12,7 @@ import ComingSoon from '../components/ui/ComingSoon'import { dramaProjectEntryPath, formatDramaCardMeta } from '../lib/dramaWorkflow'import { STATUS_CN } from '../lib/status'import SettingsToolRunsPanel from './SettingsToolRunsPanel'+import { formatDateTime, useI18n } from '../i18n'type SettingsTab =| 'account'@@ -37,17 +38,17 @@ type KepuItem = {* SIDE_ITEMS 侧栏导航项* TAB_IDS 合法 tab 集合(用于 URL 校验)*/-const SIDE_ITEMS: { id: SettingsTab; label: string; soon?: boolean; group?: 'work' | 'account' }[] = [- { id: 'account', label: '账号信息', group: 'account' },- { id: 'projects', label: '漫剧项目', group: 'work' },- { id: 'kepu', label: '科普历史', group: 'work' },- { id: 'tools', label: '工具创作', group: 'work' },- { id: 'assets', label: '资产管理', group: 'work' },- { id: 'subscription', label: '订阅与余额', group: 'account' },- { id: 'team', label: '团队管理', soon: true, group: 'account' },- { id: 'api', label: 'API', group: 'account' },- { id: 'notify', label: '通知偏好', soon: true, group: 'account' },- { id: 'security', label: '安全', group: 'account' },+const SIDE_ITEMS: { id: SettingsTab; soon?: boolean; group?: 'work' | 'account' }[] = [+ { id: 'account', group: 'account' },+ { id: 'projects', group: 'work' },+ { id: 'kepu', group: 'work' },+ { id: 'tools', group: 'work' },+ { id: 'assets', group: 'work' },+ { id: 'subscription', group: 'account' },+ { id: 'team', soon: true, group: 'account' },+ { id: 'api', group: 'account' },+ { id: 'notify', soon: true, group: 'account' },+ { id: 'security', group: 'account' },]const TAB_IDS = new Set(SIDE_ITEMS.map((i) => i.id))@@ -59,20 +60,13 @@ function parseTab(raw: string | null): SettingsTab {}// 格式化相对时间展示-function formatWhen(iso?: string) {- if (!iso) return '—'- const d = new Date(iso)- if (Number.isNaN(d.getTime())) return '—'- return d.toLocaleString('zh-CN', {- month: '2-digit',- day: '2-digit',- hour: '2-digit',- minute: '2-digit',- })+function formatWhen(iso: string | undefined, locale: 'zh' | 'en') {+ return formatDateTime(iso, locale)}export default function SettingsPage() {const nav = useNavigate()+ const { t, locale } = useI18n()const [params, setParams] = useSearchParams()/** tab 当前侧栏分区@@ -126,7 +120,7 @@ export default function SettingsPage() {if (!cancelled) setKepuItems(res.items)}} catch (e) {- if (!cancelled) setListError(e instanceof Error ? e.message : '加载失败')+ if (!cancelled) setListError(e instanceof Error ? e.message : t('common.loadFailed'))} finally {if (!cancelled) setListLoading(false)}@@ -164,12 +158,12 @@ export default function SettingsPage() {<div className="pf-settings-profile"><UserAvatar user={user} size="lg" className="pf-settings-avatar" /><div>- <strong>{user?.nickname || '创作者'}</strong>+ <strong>{user?.nickname || t('common.creator')}</strong><p className="pf-muted">ID: {user?.id ?? '—'}</p>- <span className="pf-settings-plan">{planLabel} 方案</span>+ <span className="pf-settings-plan">{t('settings.planScheme', { plan: planLabel })}</span></div></div>- <nav className="pf-settings-nav" aria-label="设置导航">+ <nav className="pf-settings-nav" aria-label={t('settings.nav')}>{SIDE_ITEMS.map((item) => (<buttonkey={item.id}@@ -177,13 +171,13 @@ export default function SettingsPage() {className={tab === item.id ? 'active' : ''}onClick={() => selectTab(item.id)}>- {item.label}+ {t(`settings.tabs.${item.id}`)}{item.soon ? <ComingSoon /> : null}</button>))}</nav><button type="button" className="pf-btn pf-btn-ghost pf-btn-sm pf-settings-logout" onClick={logout}>- 退出登录+ {t('settings.logout')}</button></aside>@@ -194,25 +188,25 @@ export default function SettingsPage() {<section className="pf-settings-card"><div className="pf-settings-card-head"><div>- <h1>漫剧项目</h1>- <p className="pf-muted">你的 AI 漫剧创作与分集进度</p>+ <h1>{t('settings.tabs.projects')}</h1>+ <p className="pf-muted">{t('settings.dramaLead')}</p></div><div className="pf-settings-actions"><Link className="pf-btn pf-btn-lime pf-btn-sm" to="/drama">- 全部项目+ {t('settings.allProjects')}</Link><Link className="pf-btn pf-btn-ghost pf-btn-sm" to="/drama">- 新建漫剧+ {t('settings.newDrama')}</Link></div></div>- {listLoading ? <p className="pf-muted">加载中…</p> : null}+ {listLoading ? <p className="pf-muted">{t('common.loading')}</p> : null}{listError ? <p className="pf-error">{listError}</p> : null}{!listLoading && !listError && dramaItems.length === 0 ? (<div className="pf-settings-empty">- <p>还没有漫剧项目</p>+ <p>{t('settings.noDrama')}</p><Link className="pf-btn pf-btn-lime pf-btn-sm" to="/drama">- 去创建+ {t('settings.goCreate')}</Link></div>) : null}@@ -222,10 +216,12 @@ export default function SettingsPage() {<li key={item.id}><Link to={dramaProjectEntryPath(item)} className="pf-settings-list-row"><span className="pf-settings-list-main">- <strong>{item.title || `项目 #${item.id}`}</strong>+ <strong>{item.title || t('settings.projectFallback', { id: item.id })}</strong><em className="pf-muted">{formatDramaCardMeta(item)}</em></span>- <span className="pf-settings-list-meta pf-muted">{formatWhen(item.updated_at || item.created_at)}</span>+ <span className="pf-settings-list-meta pf-muted">+ {formatWhen(item.updated_at || item.created_at, locale)}+ </span></Link></li>))}@@ -238,25 +234,25 @@ export default function SettingsPage() {<section className="pf-settings-card"><div className="pf-settings-card-head"><div>- <h1>科普历史</h1>- <p className="pf-muted">科普视频项目与成片记录</p>+ <h1>{t('settings.tabs.kepu')}</h1>+ <p className="pf-muted">{t('settings.kepuLead')}</p></div><div className="pf-settings-actions"><Link className="pf-btn pf-btn-lime pf-btn-sm" to="/history">- 全部历史+ {t('settings.allHistory')}</Link><Link className="pf-btn pf-btn-ghost pf-btn-sm" to="/studio/new">- 新建科普+ {t('settings.newKepu')}</Link></div></div>- {listLoading ? <p className="pf-muted">加载中…</p> : null}+ {listLoading ? <p className="pf-muted">{t('common.loading')}</p> : null}{listError ? <p className="pf-error">{listError}</p> : null}{!listLoading && !listError && kepuItems.length === 0 ? (<div className="pf-settings-empty">- <p>还没有科普项目</p>+ <p>{t('settings.noKepu')}</p><Link className="pf-btn pf-btn-lime pf-btn-sm" to="/studio/new">- 去创建+ {t('settings.goCreate')}</Link></div>) : null}@@ -266,11 +262,11 @@ export default function SettingsPage() {<li key={item.id}><Link to={`/studio/${item.id}`} className="pf-settings-list-row"><span className="pf-settings-list-main">- <strong>{item.title || `项目 #${item.id}`}</strong>+ <strong>{item.title || t('settings.projectFallback', { id: item.id })}</strong><em className="pf-muted">{STATUS_CN[item.status] || item.status}</em></span><span className="pf-settings-list-meta pf-muted">- {formatWhen(item.updated_at || item.created_at)}+ {formatWhen(item.updated_at || item.created_at, locale)}</span></Link></li>@@ -284,17 +280,17 @@ export default function SettingsPage() {{tab === 'assets' ? (<section className="pf-settings-card">- <h1>资产管理</h1>- <p className="pf-muted">角色、场景、道具与成片素材统一存放在资产库</p>+ <h1>{t('settings.tabs.assets')}</h1>+ <p className="pf-muted">{t('settings.assetsLead')}</p><div className="pf-settings-actions"><Link className="pf-btn pf-btn-lime pf-btn-sm" to="/assets">- 打开资产库+ {t('settings.openAssets')}</Link><Link className="pf-btn pf-btn-ghost pf-btn-sm" to="/drama">- 漫剧项目+ {t('settings.tabs.projects')}</Link><Link className="pf-btn pf-btn-ghost pf-btn-sm" to="/history">- 科普历史+ {t('settings.tabs.kepu')}</Link></div></section>@@ -302,19 +298,19 @@ export default function SettingsPage() {{tab === 'subscription' ? (<section className="pf-settings-card">- <h1>订阅与余额</h1>- <p className="pf-muted">按量充值,余额永久有效</p>+ <h1>{t('settings.tabs.subscription')}</h1>+ <p className="pf-muted">{t('settings.subLead')}</p><div className="pf-settings-balance"><div>- <span className="pf-muted">可用余额</span>+ <span className="pf-muted">{t('settings.balance')}</span><strong>¥{(wallet?.balance_yuan ?? 0).toFixed(2)}</strong></div><div>- <span className="pf-muted">冻结中</span>+ <span className="pf-muted">{t('settings.frozen')}</span><em>¥{(wallet?.frozen_yuan ?? 0).toFixed(2)}</em></div><div>- <span className="pf-muted">当前方案</span>+ <span className="pf-muted">{t('settings.currentPlan')}</span><em>{planLabel}</em></div></div>@@ -322,7 +318,7 @@ export default function SettingsPage() {<UsageChargeRecords variant="compact" /><div className="pf-settings-actions"><Link className="pf-btn pf-btn-lime pf-btn-sm" to="/pricing">- 去充值+ {t('settings.goTopup')}</Link></div></section>@@ -330,16 +326,16 @@ export default function SettingsPage() {{tab === 'security' ? (<section className="pf-settings-card">- <h1>安全</h1>- <p className="pf-muted">登录与账号安全设置</p>+ <h1>{t('settings.tabs.security')}</h1>+ <p className="pf-muted">{t('settings.securityLead')}</p><div className="pf-settings-fields"><label>- <span>登录邮箱</span>+ <span>{t('settings.loginEmail')}</span><input value={user?.email || ''} readOnly /></label></div><button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled>- 修改密码 <ComingSoon />+ {t('settings.changePassword')} <ComingSoon /></button></section>) : null}@@ -348,8 +344,8 @@ export default function SettingsPage() {{tab === 'team' || tab === 'notify' ? (<section className="pf-settings-card">- <h1>{SIDE_ITEMS.find((s) => s.id === tab)?.label}</h1>- <p className="pf-muted">该模块即将上线,敬请期待。</p>+ <h1>{t(`settings.tabs.${tab}`)}</h1>+ <p className="pf-muted">{t('settings.soonModule')}</p><ComingSoon /></section>) : null}diff --git a/frontend/src/pages/ToolDetailPage.tsx b/frontend/src/pages/ToolDetailPage.tsxindex 7ccd235..88469c5 100644--- a/frontend/src/pages/ToolDetailPage.tsx+++ b/frontend/src/pages/ToolDetailPage.tsx@@ -5,7 +5,8 @@ import { ArrowLeft, Download, Loader2 } from 'lucide-react'import AppShell from '../components/layout/AppShell'import Button from '../components/ui/Button'import { pollStudioToolTask, resolveToolMediaUrl, runStudioTool } from '../api/tools'-import { defaultToolChips, getToolDef, type ToolDef } from '../lib/toolsCatalog'+import { defaultToolChips, getToolDef, localizeToolDef, chipDisplayLabel, type ToolDef } from '../lib/toolsCatalog'+import { useI18n } from '../i18n'const VIDEO_POLL_MS = 3000@@ -23,7 +24,9 @@ export default function ToolDetailPage() {}/** 已登录后的工具表单与结果区 */-function ToolWorkspace({ tool }: { tool: ToolDef }) {+function ToolWorkspace({ tool: baseTool }: { tool: ToolDef }) {+ const { t, m } = useI18n()+ const tool = useMemo(() => localizeToolDef(baseTool, m), [baseTool, m])/** text 文本框* chips 画幅/时长等选项@@ -81,12 +84,12 @@ function ToolWorkspace({ tool }: { tool: ToolDef }) {setResultUrls(data.urls)setBusy(false)} else if (data.status === 'failed') {- setError(data.error || '视频生成失败')+ setError(data.error || t('tools.errors.videoFailed'))setBusy(false)}} catch (err) {if (cancelled) return- setError(err instanceof Error ? err.message : '查询失败')+ setError(err instanceof Error ? err.message : t('tools.errors.pollFailed'))setBusy(false)}}@@ -129,27 +132,27 @@ function ToolWorkspace({ tool }: { tool: ToolDef }) {if (busy) returnconst prompt = (text.prompt || text.script || '').trim()if (tool.id === 't2i' && prompt.length < 4) {- setError('请填写提示词')+ setError(t('tools.errors.fillPrompt'))return}if ((tool.id === 'i2i' || tool.id === 'i2p') && !files.length) {- setError('请上传参考图')+ setError(t('tools.errors.uploadRef'))return}if (tool.id === 't2v' && prompt.length < 4) {- setError('请填写视频脚本')+ setError(t('tools.errors.fillScript'))return}if (tool.id === 'v2v' && !files.length) {- setError('请上传源视频或首帧图')+ setError(t('tools.errors.uploadSource'))return}if (tool.id === 'ecom' && chips.pack === '卖点海报' && !files.length) {- setError('请上传商品图')+ setError(t('tools.errors.uploadProduct'))return}if (tool.id === 'ecom' && chips.pack !== '卖点海报' && files.length < 2) {- setError('拼接至少上传 2 张图片')+ setError(t('tools.errors.uploadTwoImages'))return}setError('')@@ -185,8 +188,8 @@ function ToolWorkspace({ tool }: { tool: ToolDef }) {}setBusy(false)} catch (err) {- const message = err instanceof Error ? err.message : '生成失败'- if (message === '未登录') {+ const message = err instanceof Error ? err.message : t('tools.errors.generateFailed')+ if (message === t('tools.errors.notLoggedIn') || message === '未登录') {nav(`/auth?next=/tools/${tool.id}`, { replace: true })return}@@ -204,7 +207,7 @@ function ToolWorkspace({ tool }: { tool: ToolDef }) {<div className="pf-tool-detail"><Link to="/tools" className="pf-tool-back"><ArrowLeft size={16} strokeWidth={2} aria-hidden />- 全部工具+ {t('tools.allTools')}</Link><header className="pf-tool-detail-head"><span className="pf-ws-tool-icon" aria-hidden>@@ -225,7 +228,7 @@ function ToolWorkspace({ tool }: { tool: ToolDef }) {{field.kind === 'textarea' ? (<textarearows={4}- placeholder={field.placeholder || `输入${field.label}…`}+ placeholder={field.placeholder || t('tools.inputPlaceholder', { label: field.label })}value={text[field.key] || ''}onChange={(e) => setText((prev) => ({ ...prev, [field.key]: e.target.value }))}/>@@ -244,11 +247,11 @@ function ToolWorkspace({ tool }: { tool: ToolDef }) {>{files.length ? (<span>- 已选 {files.length} 个文件+ {t('tools.filesSelected', { count: files.length })}{files[0] ? ` · ${files[0].name}` : ''}</span>) : (- '点击或拖拽上传'+ t('tools.uploadHint'))}{previews.length ? (<div className="pf-tool-upload-thumbs">@@ -272,7 +275,7 @@ function ToolWorkspace({ tool }: { tool: ToolDef }) {className={chips[field.key] === opt ? 'active' : ''}onClick={() => setChips((prev) => ({ ...prev, [field.key]: opt }))}>- {opt}+ {chipDisplayLabel(opt, m)}</button>))}</div>@@ -294,7 +297,7 @@ function ToolWorkspace({ tool }: { tool: ToolDef }) {{busy ? (<><Loader2 size={16} className="pf-tool-spin" aria-hidden />- {waitingVideo ? '视频生成中…' : '生成中…'}+ {waitingVideo ? t('tools.generatingVideo') : t('tools.generating')}</>) : (tool.cta@@ -304,25 +307,25 @@ function ToolWorkspace({ tool }: { tool: ToolDef }) {<sectionclassName={`pf-tool-result${hasMedia ? ' has-media' : ''}`}- aria-label="生成结果"+ aria-label={t('tools.resultArea')}>{!hasMedia && !busy ? (<div className="pf-tool-result-empty">- <p>结果预览区</p>- <span className="pf-muted">生成完成后将在此展示</span>+ <p>{t('tools.resultEmpty')}</p>+ <span className="pf-muted">{t('tools.resultEmptyHint')}</span></div>) : null}{busy && !hasMedia ? (<div className="pf-tool-result-empty"><Loader2 size={28} className="pf-tool-spin" aria-hidden />- <p>{waitingVideo ? '视频生成中' : '正在生成'}</p>+ <p>{waitingVideo ? t('tools.generatingVideoShort') : t('tools.generatingShort')}</p><span className="pf-muted">- {waitingVideo ? '通常需要 1–3 分钟,可停留在本页等待' : '画面生成大约 20–40 秒'}+ {waitingVideo ? t('tools.videoWaitHint') : t('tools.imageWaitHint')}</span></div>) : null}{previewUrl && !resultUrls.length ? (- <img src={resolveToolMediaUrl(previewUrl)} alt="静帧预览" />+ <img src={resolveToolMediaUrl(previewUrl)} alt={t('tools.previewAlt')} />) : null}{resultUrls.map((url) => {const abs = resolveToolMediaUrl(url)@@ -333,24 +336,26 @@ function ToolWorkspace({ tool }: { tool: ToolDef }) {<video src={abs} controls playsInline /><a className="pf-tool-download" href={abs} download><Download size={14} aria-hidden />- 下载视频+ {t('tools.downloadVideo')}</a></div>)}return (<div key={url} className="pf-tool-result-item">- <img src={abs} alt="生成结果" />+ <img src={abs} alt={t('tools.resultAlt')} /><a className="pf-tool-download" href={abs} download><Download size={14} aria-hidden />- 下载图片+ {t('tools.downloadImage')}</a></div>)})}{resultUrls.length ? (<p className="pf-muted pf-tool-saved">- 已保存,可在 <Link to="/settings?tab=tools">个人中心 · 工具创作</Link> 查看+ {t('tools.savedPrefix')}{' '}+ <Link to="/settings?tab=tools">{t('tools.savedLink')}</Link>+ {m.tools.savedSuffix ? ` ${t('tools.savedSuffix')}` : null}</p>) : null}</section>diff --git a/frontend/src/pages/ToolsPage.tsx b/frontend/src/pages/ToolsPage.tsxindex c03ccf2..0ce91f6 100644--- a/frontend/src/pages/ToolsPage.tsx+++ b/frontend/src/pages/ToolsPage.tsx@@ -2,28 +2,31 @@ import { Link } from 'react-router-dom'import { ArrowRight } from 'lucide-react'import AppShell from '../components/layout/AppShell'import ComingSoon from '../components/ui/ComingSoon'-import { PRODUCT_ICONS, TOOL_DEFS } from '../lib/toolsCatalog'+import { useI18n } from '../i18n'+import { PRODUCT_ICONS, localizeToolDefs } from '../lib/toolsCatalog'export default function ToolsPage() {+ const { t, m } = useI18n()const DramaIcon = PRODUCT_ICONS.dramaconst KepuIcon = PRODUCT_ICONS.kepu+ const tools = localizeToolDefs(m)return (<AppShell active="tools"><div className="pf-page-head"><div>- <h1>AI 创作工具</h1>- <p className="pf-muted">进入工具工作台,生成图片与短视频。</p>+ <h1>{t('tools.title')}</h1>+ <p className="pf-muted">{t('tools.lead')}</p></div></div><div className="pf-tools-grid pf-tools-grid-lg">- {TOOL_DEFS.map((t) => {- const Icon = t.icon+ {tools.map((tool) => {+ const Icon = tool.iconreturn (<Link- key={t.id}- to={`/tools/${t.id}`}- className={`pf-tools-card pf-tools-card-lg${t.soon ? ' is-soon' : ''}`}+ key={tool.id}+ to={`/tools/${tool.id}`}+ className={`pf-tools-card pf-tools-card-lg${tool.soon ? ' is-soon' : ''}`}><div className="pf-tools-card-top"><span className="pf-ws-tool-icon" aria-hidden>@@ -34,10 +37,10 @@ export default function ToolsPage() {</span></div><h3>- {t.title}- {t.soon ? <ComingSoon /> : null}+ {tool.title}+ {tool.soon ? <ComingSoon /> : null}</h3>- <p>{t.desc}</p>+ <p>{tool.desc}</p></Link>)})}@@ -48,8 +51,8 @@ export default function ToolsPage() {<DramaIcon size={26} strokeWidth={1.6} /></span><span className="pf-ws-product-body">- <strong>去漫剧创作</strong>- <span>剧本 · 分集 · 成片</span>+ <strong>{t('tools.goDrama')}</strong>+ <span>{t('tools.goDramaHint')}</span></span><span className="pf-ws-product-go" aria-hidden><ArrowRight size={16} strokeWidth={2} />@@ -60,8 +63,8 @@ export default function ToolsPage() {<KepuIcon size={26} strokeWidth={1.6} /></span><span className="pf-ws-product-body">- <strong>去科普历史</strong>- <span>分镜流水线出片</span>+ <strong>{t('tools.goKepu')}</strong>+ <span>{t('tools.goKepuHint')}</span></span><span className="pf-ws-product-go" aria-hidden><ArrowRight size={16} strokeWidth={2} />diff --git a/frontend/src/pages/drama/AssetsStep.tsx b/frontend/src/pages/drama/AssetsStep.tsxindex a7f9995..ea67c55 100644--- a/frontend/src/pages/drama/AssetsStep.tsx+++ b/frontend/src/pages/drama/AssetsStep.tsx@@ -513,6 +513,51 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {refreshPrompts: true,reextractProps: true,})+ if (result.status === 'generating') {+ let seedStatus = 'generating'+ for (let i = 0; i < 90; i += 1) {+ await new Promise((r) => window.setTimeout(r, 2000))+ const p = await dramaApi.getProject(projectId)+ seedStatus = String(+ (p.params as Record<string, unknown> | undefined)?.assets_seed_status || '',+ )+ if (seedStatus === 'done' || seedStatus === 'failed') break+ }+ const list = normalizeAssetList(+ await dramaApi.listAssets(projectId, { libraryOnly: true }),+ )+ setAssets(list)+ const p = await dramaApi.getProject(projectId)+ const params = (p.params || {}) as Record<string, unknown>+ const created = Number(params.assets_seed_created ?? 0)+ const refreshed = Number(params.assets_seed_refreshed ?? 0)+ const propsUpdated = Number(params.assets_seed_props_updated ?? 0)+ const llmErrors = Array.isArray(params.assets_seed_llm_errors)+ ? (params.assets_seed_llm_errors as string[])+ : []+ const failed = seedStatus === 'failed'+ const parts = [`新建 ${created} 项`, `AI 刷新提示词 ${refreshed} 项`]+ if (propsUpdated > 0) {+ parts.push(`更新道具/素材 ${propsUpdated} 项`)+ }+ let detail = failed+ ? String(params.assets_seed_error || '抽取失败')+ : `${parts.join(',')}。`+ if (!failed && created === 0 && refreshed === 0 && llmErrors.length === 0) {+ detail +=+ '角色/场景若已存在则不会重复新建;本次也没有刷新到提示词。请确认剧本摘要与分集正文已生成后重试。'+ } else if (!failed && llmErrors.length > 0) {+ detail += `\n\n以下资产 AI 刷新失败:\n${llmErrors.slice(0, 5).join('\n')}${llmErrors.length > 5 ? `\n…共 ${llmErrors.length} 项` : ''}`+ } else if (!failed) {+ detail += '可在画布查看 prompt 或点击「生成形象」验证。'+ }+ await dialog.alert({+ title: failed || llmErrors.length > 0 ? '抽取完成(部分失败)' : '抽取完成',+ message: detail,+ tone: failed || llmErrors.length > 0 ? 'danger' : 'success',+ })+ return+ }setAssets(normalizeAssetList(result?.assets))const created = result.created_count ?? 0const refreshed = result.prompts_refreshed ?? 0diff --git a/frontend/src/pages/drama/DramaListPage.tsx b/frontend/src/pages/drama/DramaListPage.tsxindex 1308226..f8e7a28 100644--- a/frontend/src/pages/drama/DramaListPage.tsx+++ b/frontend/src/pages/drama/DramaListPage.tsx@@ -1,5 +1,5 @@/** 漫剧 Agent 首页:AI 生剧本 / 自由画布 + 我的项目(多选删除) */-import { useCallback, useEffect, useState } from 'react'+import { useCallback, useEffect, useMemo, useState } from 'react'import { useNavigate } from 'react-router-dom'import {FolderOpen,@@ -23,6 +23,7 @@ import {isCanvasWorkflow,} from '../../lib/dramaWorkflow'import RequireAuth from './RequireAuth'+import { useI18n } from '../../i18n'import { DramaEpisodeCountPopover } from './DramaEpisodeCountPopover'import { DramaImageStyleModal } from './DramaImageStyleModal'import { DramaProjectCardMenu } from './DramaProjectCardMenu'@@ -52,12 +53,7 @@ function verticalTitleLabel(name: string, max = 12): string {type ProjectFilter = 'all' | 'running' | 'done' | 'draft'-const FILTER_OPTIONS: PillOption<ProjectFilter>[] = [- { value: 'all', label: '全部' },- { value: 'running', label: '进行中' },- { value: 'done', label: '已完成' },- { value: 'draft', label: '草稿' },-]+const FILTER_KEYS: ProjectFilter[] = ['all', 'running', 'done', 'draft']export default function DramaListPage() {return (@@ -70,6 +66,15 @@ export default function DramaListPage() {// 渲染 Agent 首页内容function DramaListInner() {const navigate = useNavigate()+ const { t, m } = useI18n()+ const filterOptions = useMemo<PillOption<ProjectFilter>[]>(+ () =>+ FILTER_KEYS.map((value) => ({+ value,+ label: m.dramaList.filters[value],+ })),+ [m],+ )/** storyText AI 创意输入* episodeCount 目标集数@@ -212,26 +217,26 @@ function DramaListInner() {// 重命名async function handleRename(item: DramaProjectListItem) {const name = await dialog.prompt({- title: '重命名项目',- message: '输入新的项目名称',+ title: t('dramaList.renameTitle'),+ message: t('dramaList.renameMessage'),defaultValue: item.title,- confirmText: '保存',+ confirmText: t('common.save'),})if (!name?.trim() || name.trim() === item.title) returntry {await dramaApi.updateProject(item.id, { title: name.trim() })await loadProjects()} catch (err) {- setError(err instanceof Error ? err.message : '重命名失败')+ setError(err instanceof Error ? err.message : t('dramaList.renameFailed'))}}// 删除单个async function handleDeleteOne(item: DramaProjectListItem) {const ok = await dialog.confirm({- title: '删除项目',- message: `确定删除「${item.title}」?分集、剧本与资产将一并删除,且无法恢复。`,- confirmText: '删除',+ title: t('dramaList.deleteTitle'),+ message: t('dramaList.deleteOne', { title: item.title }),+ confirmText: t('common.delete'),tone: 'danger',})if (!ok) return@@ -244,7 +249,7 @@ function DramaListInner() {})await loadProjects()} catch (err) {- setError(err instanceof Error ? err.message : '删除失败')+ setError(err instanceof Error ? err.message : t('dramaList.deleteFailed'))}}@@ -253,9 +258,9 @@ function DramaListInner() {const ids = [...selected]if (ids.length === 0) returnconst ok = await dialog.confirm({- title: '删除项目',- message: `将删除已选择的 ${ids.length} 个项目,包含分集、剧本与资产等数据,删除后无法恢复。`,- confirmText: '删除',+ title: t('dramaList.deleteTitle'),+ message: t('dramaList.deleteMany', { count: ids.length }),+ confirmText: t('common.delete'),tone: 'danger',})if (!ok) return@@ -265,7 +270,7 @@ function DramaListInner() {setSelected(new Set())await loadProjects()} catch (err) {- setError(err instanceof Error ? err.message : '删除失败')+ setError(err instanceof Error ? err.message : t('dramaList.deleteFailed'))} finally {setDeleting(false)}@@ -276,11 +281,11 @@ function DramaListInner() {<div className="drama-page drama-agent-page pf-drama-list"><header className="pf-drama-list-head"><div className="pf-drama-list-title-row">- <h1>我的漫剧项目</h1>+ <h1>{t('dramaList.title')}</h1><div className="pf-drama-list-actions"><Button variant="ghost" size="sm" to="/drama/assets"><Library size={15} strokeWidth={1.75} aria-hidden />- 资产库+ {t('dramaList.assets')}</Button><Buttonvariant="ghost"@@ -289,7 +294,7 @@ function DramaListInner() {onClick={() => handleTabClick('canvas')}><LayoutGrid size={15} strokeWidth={1.75} aria-hidden />- {canvasBusy ? '创建中…' : '自由画布'}+ {canvasBusy ? t('dramaList.creating') : t('dramaList.canvas')}</Button><Buttonvariant="lime"@@ -299,52 +304,56 @@ function DramaListInner() {handleTabClick('ai')}}>- 新建项目+ {t('dramaList.newProject')}</Button></div></div><div className="pf-drama-list-toolbar"><PillFilter<ProjectFilter>- options={FILTER_OPTIONS}+ options={filterOptions}value={filter}onChange={setFilter}- ariaLabel="项目筛选"+ ariaLabel={t('dramaList.filterAria')}/><label className="pf-drama-search"><Search size={16} strokeWidth={2} aria-hidden />- <span className="sr-only">搜索项目</span>+ <span className="sr-only">{t('dramaList.searchAria')}</span><inputvalue={query}onChange={(e) => setQuery(e.target.value)}- placeholder="搜索项目名称"+ placeholder={t('dramaList.searchPlaceholder')}/></label></div></header>{showCreate ? (- <section className="drama-agent-panel pf-drama-create-panel" aria-label="创作入口">+ <section className="drama-agent-panel pf-drama-create-panel" aria-label={t('dramaList.createAria')}><div className="drama-agent-panel-head"><div className="drama-agent-tabs" role="tablist"><button type="button" role="tab" aria-selected className="active"><PenLine size={15} strokeWidth={1.75} aria-hidden />- AI 生剧本+ {t('dramaList.aiScript')}</button></div><button type="button" className="pf-link pf-drama-collapse" onClick={() => setShowCreate(false)}>- 收起+ {t('dramaList.collapse')}</button></div><div className="drama-agent-tips" role="note"><Sparkles size={15} strokeWidth={1.75} aria-hidden /><span>- 建议写明 <strong>故事设定</strong>、<strong>人物特征</strong>、<strong>剧情脉络</strong> 与结局走向。+ {t('dramaList.tipRest', {+ a: t('dramaList.tipStrong1'),+ b: t('dramaList.tipStrong2'),+ c: t('dramaList.tipStrong3'),+ })}</span></div><div className="drama-agent-ai"><label className="drama-agent-ai-label" htmlFor="drama-agent-story">- 故事创意+ {t('dramaList.storyLabel')}</label><div className="drama-agent-ai-field"><textareadiff --git a/frontend/src/pages/settings/AccountProfileCard.tsx b/frontend/src/pages/settings/AccountProfileCard.tsxindex c9ea06a..c002de9 100644--- a/frontend/src/pages/settings/AccountProfileCard.tsx+++ b/frontend/src/pages/settings/AccountProfileCard.tsx@@ -1,8 +1,10 @@import { useEffect, useRef, useState } from 'react'import UserAvatar from '../../components/UserAvatar'import ComingSoon from '../../components/ui/ComingSoon'+import LanguageSwitch from '../../components/layout/LanguageSwitch'import { api, type User } from '../../api'import { dispatchUserUpdated } from '../../lib/userEvents'+import { useI18n } from '../../i18n'type AccountProfileCardProps = {user: User | null@@ -11,6 +13,7 @@ type AccountProfileCardProps = {/** 账号资料:头像、用户名、邮箱、手机号(手机号仅记录) */export default function AccountProfileCard({ user, onUserChange }: AccountProfileCardProps) {+ const { t } = useI18n()/** nickname / email / phone 表单值* saveBusy 保存中@@ -52,7 +55,7 @@ export default function AccountProfileCard({ user, onUserChange }: AccountProfilonUserChange(updated)dispatchUserUpdated(updated)} catch (e) {- setAvatarError(e instanceof Error ? e.message : '头像上传失败')+ setAvatarError(e instanceof Error ? e.message : t('settings.avatarFailed'))} finally {setAvatarBusy(false)if (avatarInputRef.current) avatarInputRef.current.value = ''@@ -75,7 +78,7 @@ export default function AccountProfileCard({ user, onUserChange }: AccountProfildispatchUserUpdated(updated)setSaveOk(true)} catch (e) {- setSaveError(e instanceof Error ? e.message : '保存失败')+ setSaveError(e instanceof Error ? e.message : t('settings.saveFailed'))} finally {setSaveBusy(false)}@@ -83,12 +86,12 @@ export default function AccountProfileCard({ user, onUserChange }: AccountProfilreturn (<section className="pf-settings-card">- <h1>账号信息</h1>- <p className="pf-muted">管理你的资料与联系方式</p>+ <h1>{t('settings.tabs.account')}</h1>+ <p className="pf-muted">{t('settings.accountLead')}</p><div className="pf-settings-avatar-row"><UserAvatar user={user} size="xl" /><div className="pf-settings-avatar-actions">- <p className="pf-muted">支持 JPG / PNG / WebP,不超过 5MB</p>+ <p className="pf-muted">{t('settings.avatarHint')}</p><div className="pf-settings-actions"><buttontype="button"@@ -96,7 +99,7 @@ export default function AccountProfileCard({ user, onUserChange }: AccountProfildisabled={avatarBusy}onClick={() => avatarInputRef.current?.click()}>- {avatarBusy ? '上传中…' : user?.avatar_url ? '更换头像' : '上传头像'}+ {avatarBusy ? t('settings.uploading') : user?.avatar_url ? t('settings.changeAvatar') : t('settings.uploadAvatar')}</button></div>{avatarError ? <p className="pf-error">{avatarError}</p> : null}@@ -111,7 +114,7 @@ export default function AccountProfileCard({ user, onUserChange }: AccountProfil</div><div className="pf-settings-fields"><label>- <span>用户名</span>+ <span>{t('settings.nickname')}</span><inputvalue={nickname}maxLength={64}@@ -123,7 +126,7 @@ export default function AccountProfileCard({ user, onUserChange }: AccountProfil/></label><label>- <span>邮箱</span>+ <span>{t('settings.email')}</span><inputtype="email"value={email}@@ -135,23 +138,30 @@ export default function AccountProfileCard({ user, onUserChange }: AccountProfil/></label><label>- <span>手机号</span>+ <span>{t('settings.phone')}</span><inputtype="tel"value={phone}inputMode="numeric"autoComplete="tel"- placeholder="未绑定"+ placeholder={t('settings.phonePlaceholder')}onChange={(e) => {setPhone(e.target.value)setSaveOk(false)}}/>- <em className="pf-muted">仅记录联系方式,无需验证码</em>+ <em className="pf-muted">{t('settings.phoneHint')}</em>+ </label>+ <label>+ <span>{t('settings.language')}</span>+ <div className="pf-settings-lang">+ <LanguageSwitch />+ <em className="pf-muted">{t('settings.languageHint')}</em>+ </div></label></div>{saveError ? <p className="pf-error">{saveError}</p> : null}- {saveOk ? <p className="pf-muted">已保存</p> : null}+ {saveOk ? <p className="pf-muted">{t('common.saved')}</p> : null}<div className="pf-settings-actions"><buttontype="button"@@ -159,10 +169,10 @@ export default function AccountProfileCard({ user, onUserChange }: AccountProfildisabled={!user || saveBusy || !dirty}onClick={() => void handleSave()}>- {saveBusy ? '保存中…' : '保存资料'}+ {saveBusy ? t('common.saving') : t('settings.saveProfile')}</button><button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled>- 申请注销 <ComingSoon />+ {t('settings.requestDelete')} <ComingSoon /></button></div></section>diff --git a/frontend/src/pages/studio/StoryboardPage.tsx b/frontend/src/pages/studio/StoryboardPage.tsxindex 855d705..f9ebcee 100644--- a/frontend/src/pages/studio/StoryboardPage.tsx+++ b/frontend/src/pages/studio/StoryboardPage.tsx@@ -470,8 +470,7 @@ export default function StoryboardPage() {if (!project) returnsetBusy(true)try {- await api.regenImage(project.id, shot.id)- setProject(await api.getProject(project.id))+ setProject(await api.regenImage(project.id, shot.id))} catch (err) {setError(err instanceof Error ? err.message : '重绘失败')} finally {@@ -483,8 +482,7 @@ export default function StoryboardPage() {if (!project) returnsetBusy(true)try {- await api.regenVideo(project.id, shot.id)- setProject(await api.getProject(project.id))+ setProject(await api.regenVideo(project.id, shot.id))} catch (err) {setError(err instanceof Error ? err.message : '重生视频失败')} finally {@@ -496,8 +494,7 @@ export default function StoryboardPage() {if (!project) returnsetBusy(true)try {- await api.regenAudio(project.id, shot.id)- setProject(await api.getProject(project.id))+ setProject(await api.regenAudio(project.id, shot.id))} catch (err) {setError(err instanceof Error ? err.message : '重配音失败')} finally {diff --git a/frontend/src/styles/printfilm.css b/frontend/src/styles/printfilm.cssindex 27ef7df..c3b4370 100644--- a/frontend/src/styles/printfilm.css+++ b/frontend/src/styles/printfilm.css@@ -105,6 +105,33 @@color: var(--pf-ink);}+.pf-nav-lang {+ display: inline-flex;+ align-items: stretch;+ height: 28px;+ border: 1px solid var(--pf-line);+ border-radius: 999px;+ overflow: hidden;+ flex-shrink: 0;+}++.pf-nav-lang button {+ border: none;+ background: transparent;+ color: var(--pf-muted);+ font-size: 0.72rem;+ font-weight: 650;+ letter-spacing: 0.02em;+ padding: 0 0.55rem;+ cursor: pointer;+ line-height: 1;+}++.pf-nav-lang button.is-active {+ background: var(--pf-ink);+ color: #fff;+}+.pf-nav-burger {display: none;width: 40px;@@ -1583,6 +1610,13 @@font-size: 0.8rem;}+.pf-settings-lang {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.75rem;+}+.pf-settings-actions {display: flex;flex-wrap: wrap;