Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

Release 2026-08-17: drama assets, queues, billing, and admin ops

yi092b428951a6
diff --git a/admin/src/App.tsx b/admin/src/App.tsx
index d081c75..2c80a82 100644
--- a/admin/src/App.tsx
+++ b/admin/src/App.tsx
@@ -6,6 +6,7 @@ import { LoginPage } from "@/pages/LoginPage";
import { OrdersPage } from "@/pages/OrdersPage";
import { ProjectsPage } from "@/pages/ProjectsPage";
import { DramaProjectsPage } from "@/pages/DramaProjectsPage";
+import { QueuesPage } from "@/pages/QueuesPage";
import { TemplatesPage } from "@/pages/TemplatesPage";
import { UsersPage } from "@/pages/UsersPage";
import { WorksPage } from "@/pages/WorksPage";
@@ -34,6 +35,7 @@ export default function App() {
<Route path="drama-projects" element={<DramaProjectsPage />} />
<Route path="works" element={<WorksPage />} />
<Route path="templates" element={<TemplatesPage />} />
+ <Route path="queues" element={<QueuesPage />} />
</Route>
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
diff --git a/admin/src/api/client.ts b/admin/src/api/client.ts
index dc68873..6462dcc 100644
--- a/admin/src/api/client.ts
+++ b/admin/src/api/client.ts
@@ -145,6 +145,79 @@ export type AdminWork = {
published_at: string;
};
+export type AdminQueueTask = {
+ task_id: string;
+ task_name: string;
+ label: string;
+ args_repr: string;
+ queue: string;
+ state: string;
+ worker?: string | null;
+ started_at?: number | null;
+ ref_id?: number | null;
+ position?: number | null;
+};
+
+export type AdminQueueSummary = {
+ name: string;
+ label: string;
+ pending: number;
+ sample: AdminQueueTask[];
+};
+
+export type AdminWorkerRow = {
+ name: string;
+ status: string;
+ active_count: number;
+ processed?: number | null;
+ pool?: string | null;
+};
+
+export type AdminWorkerControl = {
+ mode: string;
+ systemd_unit?: string | null;
+ systemd_active?: boolean | null;
+ pools: Array<{
+ name: string;
+ pool_implementation?: string;
+ max_concurrency?: number | null;
+ process_count?: number | null;
+ }>;
+ total_processes: number;
+ max_concurrency?: number | null;
+ pool_max_limit: number;
+ can_pool_grow: boolean;
+ can_pool_shrink: boolean;
+ can_restart: boolean;
+ autoscale_running: boolean;
+ autoscale_enabled: boolean;
+ autoscale_pid?: number | null;
+ autoscale_workers: number;
+ bounds_min: number;
+ bounds_max: number;
+ bounds_source: string;
+};
+
+export type AdminQueuesSnapshot = {
+ ok: boolean;
+ redis_ok: boolean;
+ use_celery: boolean;
+ worker_queues: string;
+ unacked: number;
+ total_pending: number;
+ active_count: number;
+ reserved_count: number;
+ workers_online: number;
+ queues: AdminQueueSummary[];
+ pending_tasks: AdminQueueTask[];
+ active_tasks: AdminQueueTask[];
+ reserved_tasks: AdminQueueTask[];
+ workers: AdminWorkerRow[];
+ worker_control?: AdminWorkerControl | null;
+ autoscale: Record<string, number>;
+ fetched_at: string;
+};
+
export type AdminTemplate = {
id: string;
name: string;
diff --git a/admin/src/components/layout/AdminLayout.tsx b/admin/src/components/layout/AdminLayout.tsx
index e0be84f..f68c6c7 100644
--- a/admin/src/components/layout/AdminLayout.tsx
+++ b/admin/src/components/layout/AdminLayout.tsx
@@ -5,12 +5,12 @@ import {
Clapperboard,
FileVideo,
Film,
+ Layers,
LayoutDashboard,
LogOut,
Maximize2,
Menu,
Receipt,
- Settings,
Shapes,
Users,
} from "lucide-react";
@@ -25,6 +25,7 @@ const navItems = [
{ to: "/drama-projects", label: "漫剧项目", icon: Film },
{ to: "/works", label: "作品审核", icon: FileVideo },
{ to: "/templates", label: "模板管理", icon: Shapes },
+ { to: "/queues", label: "队列任务", icon: Layers },
];
const titles: Record<string, string> = {
@@ -35,6 +36,7 @@ const titles: Record<string, string> = {
"/drama-projects": "漫剧项目",
"/works": "作品审核",
"/templates": "模板管理",
+ "/queues": "队列任务",
};
// Admin shell: sidebar + top bar matching ops console design
@@ -81,10 +83,6 @@ export function AdminLayout() {
{!collapsed && <span>{item.label}</span>}
</NavLink>
))}
- <div className="admin-nav-item is-disabled" title="系统设置(即将开放)">
- <Settings className="h-[18px] w-[18px] shrink-0" />
- {!collapsed && <span>系统设置</span>}
- </div>
</nav>
<div className="admin-user-card">
<div className="admin-avatar">{initial}</div>
diff --git a/admin/src/pages/DashboardPage.tsx b/admin/src/pages/DashboardPage.tsx
index df2fce5..f3cd9e1 100644
--- a/admin/src/pages/DashboardPage.tsx
+++ b/admin/src/pages/DashboardPage.tsx
@@ -3,6 +3,7 @@ import { Link } from "react-router-dom";
import {
Banknote,
Clapperboard,
+ Layers,
Receipt,
Shapes,
Users,
@@ -177,6 +178,10 @@ export function DashboardPage() {
<Clapperboard className="h-4 w-4 text-[#67c23a]" />
项目管理
</Link>
+ <Link to="/queues" className="admin-quick-btn">
+ <Layers className="h-4 w-4 text-[#67c23a]" />
+ 队列任务
+ </Link>
</div>
<div className="mt-5 rounded-xl border border-[#ebeef5] bg-[#fafbfc] p-4">
<div className="mb-2 flex items-center justify-between text-sm">
diff --git a/admin/src/pages/QueuesPage.tsx b/admin/src/pages/QueuesPage.tsx
new file mode 100644
index 0000000..e53c8ac
--- /dev/null
+++ b/admin/src/pages/QueuesPage.tsx
@@ -0,0 +1,434 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { Activity, Layers, Loader2, Minus, Plus, Power, RefreshCw, Server } from "lucide-react";
+import { toast } from "sonner";
+import { api, type AdminQueuesSnapshot, type AdminQueueTask } from "@/api/client";
+import { cn } from "@/lib/utils";
+
+const REFRESH_MS = 15000;
+const LIGHT_QUERY = "?detail=0";
+const FULL_QUERY = "?detail=1";
+
+// 任务状态 → 样式
+function stateClass(state: string): string {
+ if (state === "active") return "is-run";
+ if (state === "reserved") return "is-warn";
+ return "is-warn";
+}
+
+function stateLabel(state: string): string {
+ if (state === "active") return "执行中";
+ if (state === "reserved") return "已预取";
+ return "排队中";
+}
+
+function formatTime(ts: number | null | undefined): string {
+ if (!ts) return "—";
+ return new Date(ts * 1000).toLocaleString();
+}
+
+// 队列任务监控页
+export function QueuesPage() {
+ /*
+ * data 最新快照
+ * loading 首次加载
+ * refreshing 手动/定时刷新
+ * tab 当前任务列表视图
+ */
+ const [data, setData] = useState<AdminQueuesSnapshot | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [refreshing, setRefreshing] = useState(false);
+ const [tab, setTab] = useState<"pending" | "active" | "reserved">("pending");
+ const [actionLoading, setActionLoading] = useState<string | null>(null);
+ const [boundsMin, setBoundsMin] = useState("1");
+ const [boundsMax, setBoundsMax] = useState("3");
+
+ const control = data?.worker_control;
+
+ useEffect(() => {
+ if (!control) return;
+ setBoundsMin(String(control.bounds_min));
+ setBoundsMax(String(control.bounds_max));
+ }, [control?.bounds_min, control?.bounds_max]);
+
+ const load = useCallback(async (silent = false, full = false) => {
+ if (!silent) setRefreshing(true);
+ try {
+ const snap = await api<AdminQueuesSnapshot>(
+ `/api/admin/queues${full ? FULL_QUERY : LIGHT_QUERY}`,
+ );
+ setData(snap);
+ } catch (err) {
+ if (!silent) {
+ toast.error(err instanceof Error ? err.message : "加载队列失败");
+ }
+ } finally {
+ setLoading(false);
+ setRefreshing(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void load(false, true);
+ const timer = window.setInterval(() => void load(true, false), REFRESH_MS);
+ return () => window.clearInterval(timer);
+ }, [load]);
+
+ const runAction = useCallback(
+ async (key: string, path: string, options?: RequestInit) => {
+ setActionLoading(key);
+ try {
+ await api(path, options);
+ toast.success("操作已提交");
+ await load(true, true);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "操作失败");
+ } finally {
+ setActionLoading(null);
+ }
+ },
+ [load],
+ );
+
+ const modeLabel = (mode: string | undefined) => {
+ if (mode === "systemd") return "Systemd 托管";
+ if (mode === "autoscale") return "Autoscale 动态进程";
+ return "Celery";
+ };
+
+ const tasks = useMemo(() => {
+ if (!data) return [] as AdminQueueTask[];
+ if (tab === "active") return data.active_tasks;
+ if (tab === "reserved") return data.reserved_tasks;
+ return data.pending_tasks;
+ }, [data, tab]);
+
+ const maxPending = useMemo(() => {
+ if (!data?.queues.length) return 1;
+ return Math.max(1, ...data.queues.map((q) => q.pending));
+ }, [data]);
+
+ return (
+ <div className="space-y-5">
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <div>
+ <h2 className="text-xl font-semibold text-[#303133]">队列任务</h2>
+ <p className="mt-1 text-sm text-[#909399]">
+ Celery 各队列排队与 Worker 执行状态 · 轻量刷新 {REFRESH_MS / 1000}s · 手动刷新拉全量明细
+ </p>
+ </div>
+ <button
+ type="button"
+ className="admin-quick-btn !inline-flex !w-auto items-center gap-2 px-4"
+ onClick={() => void load(false, true)}
+ disabled={refreshing}
+ >
+ {refreshing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
+ 刷新
+ </button>
+ </div>
+
+ {loading && !data ? (
+ <div className="admin-panel flex items-center justify-center py-16 text-[#909399]">
+ <Loader2 className="mr-2 h-5 w-5 animate-spin" />
+ 加载中…
+ </div>
+ ) : (
+ <>
+ <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
+ <div className="admin-panel admin-stat-card">
+ <div className="admin-stat-icon">
+ <Layers className="h-5 w-5" />
+ </div>
+ <div className="text-sm text-[#909399]">排队总数</div>
+ <div className="mt-2 text-3xl font-semibold">{data?.total_pending ?? 0}</div>
+ <div className="mt-1 text-xs text-[#c0c4cc]">unacked {data?.unacked ?? 0}</div>
+ </div>
+ <div className="admin-panel admin-stat-card">
+ <div className="admin-stat-icon">
+ <Activity className="h-5 w-5" />
+ </div>
+ <div className="text-sm text-[#909399]">执行中</div>
+ <div className="mt-2 text-3xl font-semibold">{data?.active_count ?? 0}</div>
+ <div className="mt-1 text-xs text-[#c0c4cc]">预取 {data?.reserved_count ?? 0}</div>
+ </div>
+ <div className="admin-panel admin-stat-card">
+ <div className="admin-stat-icon">
+ <Server className="h-5 w-5" />
+ </div>
+ <div className="text-sm text-[#909399]">Worker 在线</div>
+ <div className="mt-2 text-3xl font-semibold">{data?.workers_online ?? 0}</div>
+ <div className="mt-1 text-xs text-[#c0c4cc]">
+ Redis {data?.redis_ok ? "正常" : "异常"} · Celery {data?.use_celery ? "开" : "关"}
+ </div>
+ </div>
+ <div className="admin-panel admin-stat-card">
+ <div className="admin-stat-icon">
+ <RefreshCw className="h-5 w-5" />
+ </div>
+ <div className="text-sm text-[#909399]">监听队列</div>
+ <div className="mt-2 text-sm font-medium leading-snug">{data?.worker_queues ?? "—"}</div>
+ <div className="mt-1 text-xs text-[#c0c4cc]">
+ 更新 {data?.fetched_at ? new Date(data.fetched_at).toLocaleTimeString() : "—"}
+ </div>
+ </div>
+ </div>
+
+ <div className="admin-panel">
+ <div className="mb-4 text-sm font-medium text-[#303133]">各队列积压</div>
+ <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
+ {(data?.queues ?? []).map((q) => (
+ <div key={q.name} className="rounded-xl border border-[#ebeef5] bg-[#fafbfc] p-4">
+ <div className="flex items-center justify-between gap-2">
+ <div>
+ <div className="text-sm font-medium text-[#303133]">{q.label}</div>
+ <div className="mt-0.5 font-mono text-xs text-[#909399]">{q.name}</div>
+ </div>
+ <span
+ className={cn(
+ "admin-status-pill",
+ q.pending > 20 ? "is-fail" : q.pending > 0 ? "is-warn" : "is-done",
+ )}
+ >
+ {q.pending}
+ </span>
+ </div>
+ <div className="mt-3 h-2 overflow-hidden rounded-full bg-[#ebeef5]">
+ <div
+ className="h-full rounded-full bg-[#67c23a] transition-all"
+ style={{ width: `${Math.min(100, (q.pending / maxPending) * 100)}%` }}
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {control ? (
+ <div className="admin-panel">
+ <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
+ <div>
+ <div className="text-sm font-medium text-[#303133]">Worker 动态管理</div>
+ <p className="mt-1 text-xs text-[#909399]">
+ 模式:{modeLabel(control.mode)}
+ {control.systemd_active ? " · systemd 运行中" : ""}
+ {control.autoscale_running ? ` · autoscale pid ${control.autoscale_pid}` : ""}
+ </p>
+ </div>
+ <span className="admin-status-pill is-run">
+ 进程 {control.total_processes}
+ {control.max_concurrency != null ? ` / 并发上限 ${control.max_concurrency}` : ""}
+ </span>
+ </div>
+
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ className="admin-quick-btn !inline-flex !w-auto items-center gap-1.5 px-3 py-2 text-sm"
+ disabled={!control.can_pool_grow || actionLoading !== null}
+ onClick={() => void runAction("grow", "/api/admin/workers/pool-grow?n=1", { method: "POST" })}
+ >
+ {actionLoading === "grow" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
+ Pool +1
+ </button>
+ <button
+ type="button"
+ className="admin-quick-btn !inline-flex !w-auto items-center gap-1.5 px-3 py-2 text-sm"
+ disabled={!control.can_pool_shrink || actionLoading !== null}
+ onClick={() => void runAction("shrink", "/api/admin/workers/pool-shrink?n=1", { method: "POST" })}
+ >
+ {actionLoading === "shrink" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Minus className="h-4 w-4" />}
+ Pool -1
+ </button>
+ <button
+ type="button"
+ className="admin-quick-btn !inline-flex !w-auto items-center gap-1.5 px-3 py-2 text-sm"
+ disabled={!control.can_restart || actionLoading !== null}
+ onClick={() => {
+ if (!window.confirm("确定重启 Celery Worker?执行中的任务会中断后由 Redis 重新投递。")) return;
+ void runAction("restart", "/api/admin/workers/restart", { method: "POST" });
+ }}
+ >
+ {actionLoading === "restart" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Power className="h-4 w-4" />}
+ 重启 Worker
+ </button>
+ </div>
+ <p className="mt-2 text-xs text-[#909399]">
+ Pool 扩缩仅对 prefork 进程池有效(线上 systemd worker);上限 {control.pool_max_limit}。solo 池请用下方 Autoscale。
+ </p>
+
+ <div className="mt-5 rounded-xl border border-[#ebeef5] bg-[#fafbfc] p-4">
+ <div className="mb-3 text-sm font-medium text-[#303133]">Autoscale 自动扩缩(开发 / 备选)</div>
+ <div className="flex flex-wrap items-end gap-3">
+ <label className="text-xs text-[#606266]">
+ 最小进程
+ <input
+ className="mt-1 block w-20 rounded-lg border border-[#dcdfe6] px-2 py-1.5 text-sm"
+ value={boundsMin}
+ onChange={(e) => setBoundsMin(e.target.value)}
+ />
+ </label>
+ <label className="text-xs text-[#606266]">
+ 最大进程
+ <input
+ className="mt-1 block w-20 rounded-lg border border-[#dcdfe6] px-2 py-1.5 text-sm"
+ value={boundsMax}
+ onChange={(e) => setBoundsMax(e.target.value)}
+ />
+ </label>
+ <button
+ type="button"
+ className="rounded-lg border border-[#dcdfe6] bg-white px-3 py-2 text-xs hover:border-[#67c23a]"
+ disabled={actionLoading !== null}
+ onClick={() =>
+ void runAction("bounds", "/api/admin/workers/autoscale", {
+ method: "PATCH",
+ body: JSON.stringify({
+ min_workers: Number(boundsMin),
+ max_workers: Number(boundsMax),
+ }),
+ })
+ }
+ >
+ 保存边界
+ </button>
+ <button
+ type="button"
+ className="rounded-lg border border-[#67c23a] bg-[#f0f9eb] px-3 py-2 text-xs text-[#67c23a]"
+ disabled={actionLoading !== null || control.autoscale_running}
+ onClick={() => void runAction("autostart", "/api/admin/workers/autoscale/start", { method: "POST" })}
+ >
+ 启动 Autoscale
+ </button>
+ <button
+ type="button"
+ className="rounded-lg border border-[#f56c6c] bg-[#fef0f0] px-3 py-2 text-xs text-[#f56c6c]"
+ disabled={actionLoading !== null || !control.autoscale_running}
+ onClick={() => void runAction("autostop", "/api/admin/workers/autoscale/stop", { method: "POST" })}
+ >
+ 停止 Autoscale
+ </button>
+ </div>
+ <p className="mt-2 text-xs text-[#909399]">
+ 配置来源:{control.bounds_source === "redis" ? "Redis 覆盖" : "环境变量"} ·
+ 当前 autoscale 子进程 {control.autoscale_workers} 个
+ </p>
+ </div>
+ </div>
+ ) : null}
+
+ {data?.workers && data.workers.length > 0 ? (
+ <div className="admin-panel">
+ <div className="mb-3 text-sm font-medium text-[#303133]">Worker 进程</div>
+ <div className="admin-table-wrap">
+ <table>
+ <thead>
+ <tr>
+ <th>Worker</th>
+ <th>状态</th>
+ <th>执行中</th>
+ <th>Pool</th>
+ </tr>
+ </thead>
+ <tbody>
+ {data.workers.map((w) => (
+ <tr key={w.name}>
+ <td className="font-mono text-xs">{w.name}</td>
+ <td>
+ <span className="admin-status-pill is-done">{w.status}</span>
+ </td>
+ <td>{w.active_count}</td>
+ <td className="text-xs text-[#909399]">{w.pool || "—"}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ ) : null}
+
+ <div className="admin-panel">
+ <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
+ <div className="text-sm font-medium text-[#303133]">任务明细</div>
+ <div className="flex flex-wrap gap-2">
+ {(
+ [
+ ["pending", `排队中 (${data?.pending_tasks.length ?? 0})`],
+ ["active", `执行中 (${data?.active_count ?? 0})`],
+ ["reserved", `已预取 (${data?.reserved_count ?? 0})`],
+ ] as const
+ ).map(([key, label]) => (
+ <button
+ key={key}
+ type="button"
+ className={cn(
+ "rounded-lg border px-3 py-1.5 text-xs transition-colors",
+ tab === key
+ ? "border-[#67c23a] bg-[#f0f9eb] text-[#67c23a]"
+ : "border-[#ebeef5] bg-white text-[#606266] hover:border-[#dcdfe6]",
+ )}
+ onClick={() => setTab(key)}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="admin-table-wrap">
+ <table>
+ <thead>
+ <tr>
+ <th>队列</th>
+ <th>任务</th>
+ <th>参数 / ID</th>
+ <th>状态</th>
+ <th>Worker</th>
+ <th>时间</th>
+ </tr>
+ </thead>
+ <tbody>
+ {tasks.length === 0 ? (
+ <tr>
+ <td colSpan={6} className="!text-center text-[#909399]">
+ 暂无{stateLabel(tab === "pending" ? "pending" : tab)}任务
+ </td>
+ </tr>
+ ) : (
+ tasks.map((t) => (
+ <tr key={`${t.state}-${t.task_id || t.args_repr}-${t.position ?? ""}`}>
+ <td>
+ <div className="text-sm">{t.queue}</div>
+ {tab === "pending" && t.position ? (
+ <div className="text-xs text-[#c0c4cc]">#{t.position}</div>
+ ) : null}
+ </td>
+ <td>
+ <div className="text-sm">{t.label}</div>
+ <div className="font-mono text-[11px] text-[#c0c4cc]">{t.task_name}</div>
+ </td>
+ <td className="max-w-[240px] truncate font-mono text-xs" title={t.args_repr}>
+ {t.args_repr || t.ref_id || "—"}
+ </td>
+ <td>
+ <span className={`admin-status-pill ${stateClass(t.state)}`}>
+ {stateLabel(t.state)}
+ </span>
+ </td>
+ <td className="font-mono text-xs text-[#909399]">{t.worker || "—"}</td>
+ <td className="text-xs text-[#909399]">{formatTime(t.started_at)}</td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </div>
+ {tab === "pending" && (data?.total_pending ?? 0) > (data?.pending_tasks.length ?? 0) ? (
+ <p className="mt-3 text-xs text-[#909399]">
+ 仅展示各队列前 30 条排队任务,其余 {(data?.total_pending ?? 0) - (data?.pending_tasks.length ?? 0)} 条未列出。
+ </p>
+ ) : null}
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/backend/.env.example b/backend/.env.example
index e15b789..5cf3c67 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -44,6 +44,8 @@ CELERY_AUTOSCALE_MAX=3
CELERY_AUTOSCALE_POLL_SEC=5
CELERY_AUTOSCALE_IDLE_SEC=45
CELERY_AUTOSCALE_QUEUE=pipeline
+# Worker 监听队列(逗号分隔;drama 优先,避免漫剧 LLM 被 pipeline 成片堵住)
+CELERY_WORKER_QUEUES=drama,oss,video,pipeline
# 防僵死:任务超时 + Redis 可见性超时(需 > time_limit)+ 进度停滞自动重派
CELERY_TASK_SOFT_TIME_LIMIT=1800
CELERY_TASK_TIME_LIMIT=2100
@@ -58,8 +60,10 @@ MODEL_IMAGE=doubao-seedream-5-0-260128
MODEL_VIDEO=doubao-seedance-2-5-260628
SEEDANCE_DURATION_MIN=4
SEEDANCE_DURATION_MAX=30
-# 科普 full:Seedance 视频模型配音(跳过 TTS + 重合成,仅拼接镜头);静图成片仍走 TTS
-KEPU_SEEDANCE_GENERATE_AUDIO=true
+# 已废弃:科普成片走外部 TTS,不再直出口播(管线忽略此开关)
+KEPU_SEEDANCE_GENERATE_AUDIO=false
+# 科普 Seedance 仍出音轨:只要键盘/点击等操作环境音,不要口播与 BGM
+KEPU_SEEDANCE_SFX_AUDIO=true
MODEL_AUDIO=seed-tts-2.0
# 豆包语音合成(openspeech,与方舟 Key 不同)。不配则自动用 edge-tts 兜底
diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py
index 7b42c37..082aa72 100644
--- a/backend/app/api/admin/__init__.py
+++ b/backend/app/api/admin/__init__.py
@@ -1,10 +1,12 @@
# Admin API router aggregation
from fastapi import APIRouter
-from app.api.admin import dashboard, drama_projects, ledger, orders, projects, templates, users, works
+from app.api.admin import dashboard, drama_projects, ledger, orders, projects, queues, templates, users, workers, works
router = APIRouter(prefix="/admin", tags=["admin"])
router.include_router(dashboard.router)
+router.include_router(queues.router)
+router.include_router(workers.router)
router.include_router(users.router)
router.include_router(orders.router)
router.include_router(ledger.router)
diff --git a/backend/app/api/admin/queues.py b/backend/app/api/admin/queues.py
new file mode 100644
index 0000000..497542b
--- /dev/null
+++ b/backend/app/api/admin/queues.py
@@ -0,0 +1,35 @@
+# Admin queue monitoring API
+import asyncio
+
+from fastapi import APIRouter, Depends, Query
+
+from app.deps import get_current_admin
+from app.models import User
+from app.schemas import AdminQueuesOut
+from app.services.queue_monitor import collect_queue_snapshot
+from app.services.worker_manager import get_worker_control_status
+
+router = APIRouter()
+
+
+def _build_queues_response(*, detail: bool) -> dict:
+ data = collect_queue_snapshot(include_inspect=detail)
+ pools = data.pop("_inspect_pools", None)
+ data.pop("_inspect_stats", None)
+ data.pop("_inspect_active", None)
+ data.pop("inspect_included", None)
+ data["worker_control"] = get_worker_control_status(
+ pools=pools if detail else None,
+ skip_inspect=not detail,
+ )
+ return data
+
+
[email protected]("/queues", response_model=AdminQueuesOut)
+async def admin_queues(
+ detail: bool = Query(default=False, description="true=含 Celery inspect 任务明细,较慢"),
+ _admin: User = Depends(get_current_admin),
+) -> AdminQueuesOut:
+ # 队列监控:默认轻量(仅 Redis 计数);detail=1 才拉 worker 执行态
+ data = await asyncio.to_thread(_build_queues_response, detail=detail)
+ return AdminQueuesOut.model_validate(data)
diff --git a/backend/app/api/admin/workers.py b/backend/app/api/admin/workers.py
new file mode 100644
index 0000000..0042963
--- /dev/null
+++ b/backend/app/api/admin/workers.py
@@ -0,0 +1,97 @@
+# Admin worker control API
+from fastapi import APIRouter, Depends, HTTPException
+
+from app.deps import get_current_admin
+from app.models import User
+from app.schemas import (
+ AdminAutoscalePatch,
+ AdminWorkerActionOut,
+ AdminWorkerControlOut,
+)
+from app.services.worker_manager import (
+ get_worker_control_status,
+ pool_grow,
+ pool_shrink,
+ restart_systemd_worker,
+ start_autoscale_daemon,
+ stop_autoscale_daemon,
+ update_autoscale_config,
+)
+
+router = APIRouter()
+
+
[email protected]("/workers", response_model=AdminWorkerControlOut)
+async def admin_worker_status(_admin: User = Depends(get_current_admin)) -> AdminWorkerControlOut:
+ # Worker 管理模式与 pool 状态
+ return AdminWorkerControlOut.model_validate(get_worker_control_status())
+
+
[email protected]("/workers/pool-grow", response_model=AdminWorkerActionOut)
+async def admin_pool_grow(
+ n: int = 1,
+ _admin: User = Depends(get_current_admin),
+) -> AdminWorkerActionOut:
+ try:
+ result = pool_grow(n=n)
+ except RuntimeError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ result["control"] = get_worker_control_status()
+ return AdminWorkerActionOut.model_validate(result)
+
+
[email protected]("/workers/pool-shrink", response_model=AdminWorkerActionOut)
+async def admin_pool_shrink(
+ n: int = 1,
+ _admin: User = Depends(get_current_admin),
+) -> AdminWorkerActionOut:
+ try:
+ result = pool_shrink(n=n)
+ except RuntimeError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ result["control"] = get_worker_control_status()
+ return AdminWorkerActionOut.model_validate(result)
+
+
[email protected]("/workers/restart", response_model=AdminWorkerActionOut)
+async def admin_worker_restart(_admin: User = Depends(get_current_admin)) -> AdminWorkerActionOut:
+ try:
+ result = restart_systemd_worker()
+ except RuntimeError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ result["control"] = get_worker_control_status()
+ return AdminWorkerActionOut.model_validate(result)
+
+
[email protected]("/workers/autoscale", response_model=AdminWorkerActionOut)
+async def admin_autoscale_patch(
+ body: AdminAutoscalePatch,
+ _admin: User = Depends(get_current_admin),
+) -> AdminWorkerActionOut:
+ result = update_autoscale_config(
+ min_workers=body.min_workers,
+ max_workers=body.max_workers,
+ enabled=body.enabled,
+ )
+ result["control"] = get_worker_control_status()
+ return AdminWorkerActionOut.model_validate(result)
+
+
[email protected]("/workers/autoscale/start", response_model=AdminWorkerActionOut)
+async def admin_autoscale_start(_admin: User = Depends(get_current_admin)) -> AdminWorkerActionOut:
+ try:
+ result = start_autoscale_daemon()
+ except RuntimeError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ result["control"] = get_worker_control_status()
+ return AdminWorkerActionOut.model_validate(result)
+
+
[email protected]("/workers/autoscale/stop", response_model=AdminWorkerActionOut)
+async def admin_autoscale_stop(_admin: User = Depends(get_current_admin)) -> AdminWorkerActionOut:
+ try:
+ result = stop_autoscale_daemon()
+ except RuntimeError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ result["control"] = get_worker_control_status()
+ return AdminWorkerActionOut.model_validate(result)
diff --git a/backend/app/api/api_keys.py b/backend/app/api/api_keys.py
new file mode 100644
index 0000000..9986c3c
--- /dev/null
+++ b/backend/app/api/api_keys.py
@@ -0,0 +1,45 @@
+from fastapi import APIRouter, Depends, Header, HTTPException
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.database import get_db
+from app.deps import get_current_user
+from app.models import User
+from app.schemas_api import ApiKeyCreateRequest, ApiKeyCreatedOut, ApiKeyOut
+from app.services import api_keys
+
+router = APIRouter(prefix="/user/api-keys", tags=["api-keys"])
+
+
[email protected]("", response_model=list[ApiKeyOut])
+async def list_keys(
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> list[ApiKeyOut]:
+ rows = await api_keys.list_api_keys(db, user.id)
+ return [ApiKeyOut.model_validate(row) for row in rows]
+
+
[email protected]("", response_model=ApiKeyCreatedOut)
+async def create_key(
+ body: ApiKeyCreateRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> ApiKeyCreatedOut:
+ row, raw = await api_keys.create_api_key(db, user, body.name)
+ await db.commit()
+ await db.refresh(row)
+ out = ApiKeyOut.model_validate(row)
+ return ApiKeyCreatedOut(**out.model_dump(), secret=raw)
+
+
[email protected]("/{key_id}")
+async def revoke_key(
+ key_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ ok = await api_keys.revoke_api_key(db, user.id, key_id)
+ if not ok:
+ raise HTTPException(status_code=404, detail="Key 不存在或已撤销")
+ await db.commit()
+ return {"ok": True}
diff --git a/backend/app/api/auth.py b/backend/app/api/auth.py
index b7fcbd8..351fe12 100644
--- a/backend/app/api/auth.py
+++ b/backend/app/api/auth.py
@@ -1,17 +1,21 @@
-from fastapi import APIRouter, Depends, HTTPException, status
+from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status
+from pathlib import Path
+
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import get_settings
from app.database import get_db
from app.deps import get_current_user
from app.models import User, WalletLedger
-from app.schemas import LoginRequest, RegisterRequest, TokenResponse, UserOut
+from app.schemas import LoginRequest, ProfileUpdateRequest, RegisterRequest, TokenResponse, UserOut
+from app.services import storage
from app.services.auth import (
create_access_token,
get_user_by_email,
hash_password,
verify_password,
)
+from app.services.profile import ProfileError, prepare_profile_update
router = APIRouter(prefix="/auth", tags=["auth"])
settings = get_settings()
@@ -61,3 +65,69 @@ async def login(body: LoginRequest, db: AsyncSession = Depends(get_db)) -> Token
@router.get("/me", response_model=UserOut)
async def me(user: User = Depends(get_current_user)) -> User:
return user
+
+
[email protected]("/me", response_model=UserOut)
+async def update_me(
+ body: ProfileUpdateRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> User:
+ """更新当前用户的用户名、登录邮箱与联系手机号(仅记录,无验证码)。"""
+ try:
+ fields = prepare_profile_update(
+ nickname=body.nickname,
+ email=body.email,
+ phone=body.phone,
+ )
+ except ProfileError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ if fields["email"] != user.email:
+ taken = await get_user_by_email(db, fields["email"])
+ if taken and taken.id != user.id:
+ raise HTTPException(status_code=400, detail="该邮箱已被使用")
+
+ user.nickname = fields["nickname"]
+ user.email = fields["email"]
+ user.phone = fields["phone"]
+ await db.commit()
+ await db.refresh(user)
+ return user
+
+
[email protected]("/avatar", response_model=UserOut)
+async def upload_avatar(
+ file: UploadFile = File(...),
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> User:
+ """Upload or replace the current user's profile avatar."""
+ content_type = (file.content_type or "").lower()
+ allowed = {
+ "image/jpeg": ".jpg",
+ "image/jpg": ".jpg",
+ "image/png": ".png",
+ "image/webp": ".webp",
+ "image/gif": ".gif",
+ }
+ ext = allowed.get(content_type)
+ if not ext:
+ suffix = Path(file.filename or "").suffix.lower()
+ if suffix in {".jpg", ".jpeg", ".png", ".webp", ".gif"}:
+ ext = ".jpg" if suffix == ".jpeg" else suffix
+ else:
+ raise HTTPException(status_code=400, detail="仅支持 JPG / PNG / WebP / GIF")
+
+ raw = await file.read()
+ if not raw:
+ raise HTTPException(status_code=400, detail="空文件")
+ if len(raw) > 5 * 1024 * 1024:
+ raise HTTPException(status_code=400, detail="头像不能超过 5MB")
+
+ dest = storage.user_dir(user.id) / f"avatar{ext}"
+ dest.write_bytes(raw)
+ user.avatar_url = storage.publish_local(dest)
+ await db.commit()
+ await db.refresh(user)
+ return user
diff --git a/backend/app/api/billing.py b/backend/app/api/billing.py
index 70f002c..62645cb 100644
--- a/backend/app/api/billing.py
+++ b/backend/app/api/billing.py
@@ -18,7 +18,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.config import get_settings
from app.database import get_db
from app.deps import get_current_user
-from app.models import Order, UsageEvent, User
+from app.models import Order, Project, UsageEvent, User
from app.services import billing, epay
logger = logging.getLogger(__name__)
@@ -74,6 +74,8 @@ async def create_order(
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
) -> dict:
+ # 下单前先清理该用户已过期的待支付单
+ await billing.close_expired_pending_orders(db, user_id=user.id)
sku = billing.sku_by_id(body.sku_id)
if not sku:
raise HTTPException(status_code=400, detail="未知充值包")
@@ -119,7 +121,7 @@ async def create_order(
"payurl": mapi.get("payurl") or "",
"img": mapi.get("img") or "",
"qr_payload": mapi.get("qr_payload") or "",
- "expire_seconds": 300,
+ "expire_seconds": billing.ORDER_EXPIRE_SECONDS,
"submit_url": epay.submit_url(fields),
}
@@ -158,13 +160,71 @@ async def usage_summary(
}
[email protected]("/usage/events")
+async def usage_events(
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+ page: int = Query(1, ge=1),
+ page_size: int = Query(20, ge=1, le=100),
+) -> dict:
+ """分页返回当前用户的按次扣费记录(新→旧)。"""
+ from app.models_drama import DramaProject
+
+ count_stmt = select(func.count()).select_from(UsageEvent).where(UsageEvent.user_id == user.id)
+ total = int((await db.execute(count_stmt)).scalar_one() or 0)
+
+ stmt = (
+ select(UsageEvent, Project.title, DramaProject.title)
+ .outerjoin(Project, UsageEvent.project_id == Project.id)
+ .outerjoin(DramaProject, UsageEvent.drama_project_id == DramaProject.id)
+ .where(UsageEvent.user_id == user.id)
+ .order_by(UsageEvent.id.desc())
+ .offset((page - 1) * page_size)
+ .limit(page_size)
+ )
+ rows = (await db.execute(stmt)).all()
+
+ items = []
+ for ev, kepu_title, drama_title in rows:
+ if drama_title:
+ context = f"漫剧 · {drama_title}"
+ elif kepu_title:
+ context = f"科普 · {kepu_title}"
+ elif ev.project_id:
+ context = f"科普 · 项目 #{ev.project_id}"
+ elif ev.drama_project_id:
+ context = f"漫剧 · 项目 #{ev.drama_project_id}"
+ else:
+ context = "工具创作"
+ charge_fen = int(ev.charge_fen or 0)
+ items.append(
+ {
+ "id": ev.id,
+ "billing_key": ev.billing_key,
+ "billing_label": billing.billing_key_label(ev.billing_key),
+ "model": ev.model or "",
+ "context": context,
+ "total_tokens": int(ev.total_tokens or 0),
+ "charge_fen": charge_fen,
+ "charge_yuan": round(charge_fen / 100, 2),
+ "estimated": bool(ev.estimated),
+ "created_at": ev.created_at.isoformat() if ev.created_at else None,
+ }
+ )
+ return {
+ "items": items,
+ "meta": {"page": page, "page_size": page_size, "total": total},
+ }
+
+
@router.get("/orders")
async def list_orders(
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
limit: int = Query(50, ge=1, le=100),
) -> dict:
- """充值订单列表(新→旧)。"""
+ """充值订单列表(新→旧);返回前自动关闭过期待支付单。"""
+ await billing.close_expired_pending_orders(db, user_id=user.id)
result = await db.execute(
select(Order)
.where(Order.user_id == user.id)
@@ -198,6 +258,7 @@ async def get_order(
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
) -> dict:
+ await billing.close_expired_pending_orders(db, user_id=user.id, out_trade_no=out_trade_no)
result = await db.execute(select(Order).where(Order.out_trade_no == out_trade_no))
order = result.scalar_one_or_none()
if not order or order.user_id != user.id:
@@ -212,6 +273,28 @@ async def get_order(
}
[email protected]("/orders/{out_trade_no}/close")
+async def close_order(
+ out_trade_no: str,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ """用户主动取消支付时关闭待支付订单(过期订单由系统自动关闭)。"""
+ result = await db.execute(select(Order).where(Order.out_trade_no == out_trade_no))
+ order = result.scalar_one_or_none()
+ if not order or order.user_id != user.id:
+ raise HTTPException(status_code=404, detail="订单不存在")
+ if order.status == "paid":
+ raise HTTPException(status_code=400, detail="已支付订单无法关闭")
+ if order.status == "closed":
+ return {"out_trade_no": order.out_trade_no, "status": "closed"}
+ if order.status != "pending":
+ raise HTTPException(status_code=400, detail="当前状态不可关闭")
+ order.status = "closed"
+ await db.commit()
+ return {"out_trade_no": order.out_trade_no, "status": "closed"}
+
+
def _notify_success(params: dict) -> bool:
status = str(params.get("trade_status") or params.get("status") or "")
if status.upper() in {"TRADE_SUCCESS", "SUCCESS", "1"}:
diff --git a/backend/app/api/drama/agents.py b/backend/app/api/drama/agents.py
index 26ddb98..d0ad5b2 100644
--- a/backend/app/api/drama/agents.py
+++ b/backend/app/api/drama/agents.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import logging
+from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
@@ -30,6 +31,23 @@ from app.services.drama.llm import DramaLlmUnavailableError, drama_chat_text
router = APIRouter()
logger = logging.getLogger("app.drama.agents")
+# summary_generating_at 超过该时长仍无结果,允许重新入队
+SUMMARY_GENERATING_STALE_MINUTES = 25
+
+
+def _summary_generating_is_stale(params: dict) -> bool:
+ # 判断 generating 是否已超时(避免 Celery 失败/丢任务后前端永久转圈)
+ started_raw = params.get("summary_generating_at")
+ if not started_raw:
+ return True
+ try:
+ started = datetime.fromisoformat(str(started_raw).replace("Z", "+00:00"))
+ except ValueError:
+ return True
+ if started.tzinfo is None:
+ started = started.replace(tzinfo=timezone.utc)
+ return datetime.now(timezone.utc) - started > timedelta(minutes=SUMMARY_GENERATING_STALE_MINUTES)
+
@router.post("/agents/script_summary")
async def script_summary(
@@ -58,7 +76,7 @@ async def script_summary(
proj_params["image_style_id"] = str(body.image_style_id)
project.params = proj_params
existing_status = str(params.get("summary_status") or "")
- if existing_status == "generating":
+ if existing_status == "generating" and not _summary_generating_is_stale(params):
logger.info(
"剧本摘要已在生成中,跳过重复入队 project_id=%s user_id=%s",
project.id,
@@ -72,7 +90,15 @@ async def script_summary(
"task_id": None,
"script": DramaScriptOut.model_validate(project.script).model_dump(),
}
+ if existing_status == "generating":
+ logger.warning(
+ "剧本摘要 generating 超时,允许重新入队 project_id=%s user_id=%s started=%s",
+ project.id,
+ user.id,
+ params.get("summary_generating_at"),
+ )
params["summary_status"] = "generating"
+ params["summary_generating_at"] = datetime.now(timezone.utc).isoformat()
params.pop("summary_error", None)
project.script.params = params
await db.commit()
diff --git a/backend/app/api/drama/assets.py b/backend/app/api/drama/assets.py
index f0eaea2..49666d0 100644
--- a/backend/app/api/drama/assets.py
+++ b/backend/app/api/drama/assets.py
@@ -162,6 +162,13 @@ async def upload_asset_media(
asset.cover = url
if not asset.asset_type or asset.asset_type == "none":
asset.asset_type = "image"
+ params = dict(asset.params or {})
+ gen = params.get("generation")
+ if isinstance(gen, dict):
+ params["generation"] = {**gen, "status": "done", "source": "upload"}
+ else:
+ params["generation"] = {"status": "done", "source": "upload"}
+ asset.params = params
await db.commit()
await db.refresh(asset)
return DramaAssetOut.model_validate(asset)
diff --git a/backend/app/api/projects.py b/backend/app/api/projects.py
index db14a50..d2d8ef7 100644
--- a/backend/app/api/projects.py
+++ b/backend/app/api/projects.py
@@ -499,11 +499,8 @@ async def generate_project(
else:
# Continue: label the real next stage so UI never shows「拆分镜中」
image_text = (project.pipeline_mode or "full") == "image_text"
- from app.config import get_settings
-
- native_audio = (not image_text) and bool(get_settings().kepu_seedance_generate_audio)
has_images = all(bool(s.image_url or s.image_ark_url) for s in shots)
- has_audio = True if native_audio else all(bool(s.audio_url) for s in shots)
+ has_audio = all(bool(s.audio_url) for s in shots)
has_videos = all(bool(s.video_url) for s in shots)
if not has_images or not has_audio:
project.status = ProjectStatus.IMAGING
@@ -624,16 +621,26 @@ async def update_shot(
raise HTTPException(status_code=404, detail="分镜不存在")
data = body.model_dump(exclude_unset=True)
if "segment_script" in data and data["segment_script"] is not None:
- from app.services.seedance_segments import apply_segment_script_edit
+ from app.services.seedance_segments import (
+ apply_segment_script_edit,
+ replace_first_visual_in_script,
+ replace_narration_in_script,
+ )
bgm = (getattr(project, "bgm_lock", None) or shot.bgm_mood or "").strip()
- normalized = apply_segment_script_edit(str(data["segment_script"]), bgm_mood=bgm)
+ script = str(data["segment_script"])
+ # 弹窗旁白/首帧优先写回脚本,避免保存时被旧脚本盖掉
+ if "narration" in data and data["narration"] is not None:
+ script = replace_narration_in_script(script, str(data["narration"]))
+ if "img_prompt" in data and data["img_prompt"] is not None:
+ script = replace_first_visual_in_script(script, str(data["img_prompt"]))
+ normalized = apply_segment_script_edit(script, bgm_mood=bgm)
data["segment_script"] = normalized["segment_script"]
data["duration"] = normalized["duration"]
data["video_prompt"] = normalized["video_prompt"]
if normalized.get("narration"):
data["narration"] = normalized["narration"]
- if normalized.get("img_prompt") and "img_prompt" not in data:
+ if normalized.get("img_prompt"):
data["img_prompt"] = normalized["img_prompt"]
if "duration" in data and data["duration"] is not None:
tpl = await db.get(Template, project.template_id)
@@ -778,15 +785,10 @@ async def compose_only(
ProjectStatus.AUDITING,
}:
raise HTTPException(status_code=409, detail="生成进行中,请稍后")
- image_text = (project.pipeline_mode or "full") == "image_text"
- from app.config import get_settings
-
- native_audio = (not image_text) and bool(get_settings().kepu_seedance_generate_audio)
- if native_audio:
- if not project.shots or not any(s.video_url for s in project.shots):
- raise HTTPException(status_code=400, detail="缺少镜头视频,无法拼接成片")
- elif not project.shots or not any(s.image_url for s in project.shots):
- raise HTTPException(status_code=400, detail="缺少分镜图,无法合成")
+ if not project.shots or not (
+ any(s.image_url for s in project.shots) or any(s.video_url for s in project.shots)
+ ):
+ raise HTTPException(status_code=400, detail="缺少分镜图或镜头视频,无法合成")
project.status = ProjectStatus.COMPOSING
project.progress = 90
project.error_msg = None
diff --git a/backend/app/api/v1/__init__.py b/backend/app/api/v1/__init__.py
new file mode 100644
index 0000000..cde5af6
--- /dev/null
+++ b/backend/app/api/v1/__init__.py
@@ -0,0 +1,6 @@
+from fastapi import APIRouter
+
+from app.api.v1 import generation
+
+router = APIRouter()
+router.include_router(generation.router)
diff --git a/backend/app/api/v1/generation.py b/backend/app/api/v1/generation.py
new file mode 100644
index 0000000..d4869eb
--- /dev/null
+++ b/backend/app/api/v1/generation.py
@@ -0,0 +1,192 @@
+"""对外 REST API:生图 / 生视频 / Seedance 转发。"""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends, Header, HTTPException
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config import get_settings
+from app.database import get_db
+from app.deps import get_api_user
+from app.models import User
+from app.schemas_api import (
+ V1GenerationOut,
+ V1ImageGenerateRequest,
+ V1SeedanceTaskRequest,
+ V1VideoGenerateRequest,
+)
+from app.services.billing import record_usage, settle_usage_charge
+from app.services.studio_tools import poll_video_task, ratio_to_size
+from app.services import storage
+
+router = APIRouter(prefix="/v1", tags=["public-api"])
+
+
+async def _resolve_api_user(
+ db: AsyncSession = Depends(get_db),
+ authorization: str | None = Header(default=None),
+ x_api_key: str | None = Header(default=None, alias="X-Api-Key"),
+) -> User:
+ from fastapi.security import HTTPAuthorizationCredentials
+
+ creds = None
+ if authorization and authorization.lower().startswith("bearer "):
+ creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials=authorization[7:].strip())
+ return await get_api_user(creds=creds, db=db, x_api_key=x_api_key)
+
+
[email protected]("/images/generations", response_model=V1GenerationOut)
+async def generate_image(
+ body: V1ImageGenerateRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(_resolve_api_user),
+) -> V1GenerationOut:
+ """文生图 / 图生图(Seedream)。"""
+ ark = get_ark()
+ refs: list[str] | None = None
+ prompt = body.prompt.strip()
+ if body.image_url:
+ refs = [body.image_url.strip()]
+ prompt = f"{prompt}。在保持主体可识别的前提下适度改变风格"
+ size = ratio_to_size(body.ratio)
+ try:
+ result = await ark.gen_image(
+ prompt,
+ body.negative,
+ refs,
+ project_id=0,
+ shot_no=user.id,
+ size=size,
+ )
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc
+
+ ev = await record_usage(
+ db,
+ user_id=user.id,
+ project_id=None,
+ billing_key="seedream",
+ model=get_settings().model_image,
+ estimated=True,
+ raw={"source": "api_v1_image"},
+ )
+ try:
+ await settle_usage_charge(db, user, int(ev.charge_fen or 0), ref_type="api", ref_id=f"img:{ev.id}")
+ except ValueError as exc:
+ raise HTTPException(status_code=402, detail=str(exc)) from exc
+
+ url = result.local_url or result.remote_url or ""
+ if url:
+ url = storage.republish_url(url, sync=True) or url
+ await db.commit()
+ return V1GenerationOut(status="succeeded", kind="image", urls=[url] if url else [])
+
+
[email protected]("/videos/generations", response_model=V1GenerationOut)
+async def generate_video(
+ body: V1VideoGenerateRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(_resolve_api_user),
+) -> V1GenerationOut:
+ """首帧图 + 文案 → Seedance 图生视频,返回 task_id。"""
+ ark = get_ark()
+ try:
+ task_id = await ark.gen_video_i2v(
+ body.image_url.strip(),
+ body.prompt.strip(),
+ body.duration,
+ resolution=body.resolution,
+ generate_audio=body.generate_audio,
+ )
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc
+
+ ev = await record_usage(
+ db,
+ user_id=user.id,
+ project_id=None,
+ billing_key="seedance2:video0",
+ model=get_settings().model_video,
+ estimated=True,
+ raw={"source": "api_v1_video", "duration": body.duration},
+ )
+ try:
+ await settle_usage_charge(db, user, int(ev.charge_fen or 0), ref_type="api", ref_id=f"vid:{ev.id}")
+ except ValueError as exc:
+ raise HTTPException(status_code=402, detail=str(exc)) from exc
+
+ await db.commit()
+ return V1GenerationOut(
+ status="queued",
+ kind="video",
+ task_id=task_id,
+ preview_url=body.image_url,
+ urls=[],
+ )
+
+
[email protected]("/seedance/tasks", response_model=V1GenerationOut)
+async def forward_seedance(
+ body: V1SeedanceTaskRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(_resolve_api_user),
+) -> V1GenerationOut:
+ """转发 Seedance 多模态 body 到火山方舟。"""
+ if not body.content:
+ raise HTTPException(status_code=400, detail="content 不能为空")
+ settings = get_settings()
+ payload: dict = {
+ "model": settings.model_video,
+ "content": body.content,
+ "resolution": body.resolution,
+ "watermark": body.watermark,
+ "generate_audio": body.generate_audio,
+ "return_last_frame": body.return_last_frame,
+ }
+ if body.duration is not None:
+ payload["duration"] = body.duration
+ if body.ratio:
+ payload["ratio"] = body.ratio
+
+ ark = get_ark()
+ try:
+ task_id = await ark.gen_video_seedance_body(payload, project_id=0)
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc
+
+ ev = await record_usage(
+ db,
+ user_id=user.id,
+ project_id=None,
+ billing_key="seedance2:video0",
+ model=settings.model_video,
+ estimated=True,
+ raw={"source": "api_v1_seedance"},
+ )
+ try:
+ await settle_usage_charge(db, user, int(ev.charge_fen or 0), ref_type="api", ref_id=f"sd:{ev.id}")
+ except ValueError as exc:
+ raise HTTPException(status_code=402, detail=str(exc)) from exc
+
+ await db.commit()
+ return V1GenerationOut(status="queued", kind="video", task_id=task_id, urls=[])
+
+
[email protected]("/tasks/{task_id}", response_model=V1GenerationOut)
+async def get_task(
+ task_id: str,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(_resolve_api_user),
+) -> V1GenerationOut:
+ """查询 Seedance 视频任务状态。"""
+ if not task_id.strip():
+ raise HTTPException(status_code=400, detail="缺少 task_id")
+ data = await poll_video_task(user, task_id.strip())
+ await db.commit()
+ return V1GenerationOut(
+ status=str(data.get("status") or "running"),
+ kind="video",
+ urls=list(data.get("urls") or []),
+ task_id=task_id.strip(),
+ error=data.get("error"),
+ )
diff --git a/backend/app/config.py b/backend/app/config.py
index 365da43..2018d44 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -53,8 +53,10 @@ class Settings(BaseSettings):
# Seedance 2.5 官方并发上限约 10
pipeline_video_concurrency: int = 10
pipeline_audio_concurrency: int = 4
- # 科普 full:Seedance generate_audio 配音,跳过 TTS + 重合成,仅拼接镜头
- kepu_seedance_generate_audio: bool = True
+ # 已废弃:科普不再直出口播(即使 .env 为 true 也会被管线忽略)
+ kepu_seedance_generate_audio: bool = False
+ # 科普 Seedance 仍出音轨:只要操作/环境音效,不要口播与 BGM
+ kepu_seedance_sfx_audio: bool = True
ark_mock: bool = False
use_celery: bool = True
@@ -65,7 +67,12 @@ class Settings(BaseSettings):
celery_autoscale_max: int = 3
celery_autoscale_poll_sec: float = 5.0
celery_autoscale_idle_sec: float = 45.0
+ # 主监控队列(历史字段;未设 celery_worker_queues 时作 fallback)
celery_autoscale_queue: str = "pipeline"
+ # Worker 消费与 autoscale 监控的全部队列(逗号分隔)
+ celery_worker_queues: str = "drama,oss,video,pipeline"
+ # Admin pool_grow 上限
+ celery_pool_max: int = 8
# Prevent zombie tasks: hard kill hung workers; Redis redelivers after visibility_timeout
# 视频阶段包含多镜头/多重试(Seedance/合成/OSS回填),线上曾触发 soft time limit 导致 project 进度停在中间。
# 这里适当放大,确保在“可预期的失败重试窗口”内有足够时间完成状态回写/标记失败。
diff --git a/backend/app/database.py b/backend/app/database.py
index 243b067..9487e4d 100644
--- a/backend/app/database.py
+++ b/backend/app/database.py
@@ -28,6 +28,7 @@ async def init_db() -> None:
from app import models # noqa: F401
from app import models_agent # noqa: F401
from app import models_drama # noqa: F401
+ from app import models_api # noqa: F401
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
diff --git a/backend/app/deps.py b/backend/app/deps.py
index 65092fd..47ed216 100644
--- a/backend/app/deps.py
+++ b/backend/app/deps.py
@@ -1,4 +1,4 @@
-from fastapi import Depends, HTTPException, status
+from fastapi import Depends, HTTPException, Header, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
@@ -9,18 +9,49 @@ from app.services.auth import decode_token, get_user_by_id
security = HTTPBearer(auto_error=False)
+from app.database import get_db
+from app.models import User
+from app.services.api_keys import API_KEY_PREFIX, user_from_api_key
+from app.services.auth import decode_token, get_user_by_id
+
+security = HTTPBearer(auto_error=False)
+
+
+async def _user_from_bearer(db: AsyncSession, token: str) -> User | None:
+ if token.startswith(API_KEY_PREFIX):
+ return await user_from_api_key(db, token)
+ sub = decode_token(token)
+ if not sub:
+ return None
+ return await get_user_by_id(db, int(sub))
+
+
async def get_current_user(
creds: HTTPAuthorizationCredentials | None = Depends(security),
db: AsyncSession = Depends(get_db),
) -> User:
if not creds:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="未登录")
- sub = decode_token(creds.credentials)
- if not sub:
+ user = await _user_from_bearer(db, creds.credentials)
+ if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效")
- user = await get_user_by_id(db, int(sub))
+ return user
+
+
+async def get_api_user(
+ creds: HTTPAuthorizationCredentials | None = Depends(security),
+ db: AsyncSession = Depends(get_db),
+ x_api_key: str | None = Header(default=None, alias="X-Api-Key"),
+) -> User:
+ """对外 API:支持 JWT 或 pf_live_ API Key(Bearer / X-Api-Key)。"""
+ token = (x_api_key or "").strip()
+ if not token and creds:
+ token = creds.credentials
+ if not token:
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="缺少 API Key")
+ user = await _user_from_bearer(db, token)
if not user:
- raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户不存在")
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="API Key 无效或已撤销")
return user
diff --git a/backend/app/main.py b/backend/app/main.py
index 8be7576..0868c64 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -8,6 +8,8 @@ from fastapi.staticfiles import StaticFiles
from sqlalchemy import select, text
from app.api import auth, billing, projects, templates, tools
+from app.api import api_keys as user_api_keys
+from app.api.v1 import router as v1_router
from app.api.admin import router as admin_router
from app.api.drama import router as drama_router
from app.config import get_settings
@@ -81,6 +83,8 @@ app.include_router(templates.router, prefix="/api")
app.include_router(projects.router, prefix="/api")
app.include_router(billing.router, prefix="/api")
app.include_router(tools.router, prefix="/api")
+app.include_router(user_api_keys.router, prefix="/api")
+app.include_router(v1_router, prefix="/api")
app.include_router(drama_router, prefix="/api")
app.include_router(admin_router, prefix="/api")
@@ -178,6 +182,10 @@ async def _migrate_sqlite() -> None:
)
if "role" not in ucols:
await conn.execute(text("ALTER TABLE users ADD COLUMN role VARCHAR(16) DEFAULT 'user'"))
+ if "avatar_url" not in ucols:
+ await conn.execute(text("ALTER TABLE users ADD COLUMN avatar_url VARCHAR(512) DEFAULT ''"))
+ if "phone" not in ucols:
+ await conn.execute(text("ALTER TABLE users ADD COLUMN phone VARCHAR(32) DEFAULT ''"))
# UsageEvent.drama_project_id for drama module billing
if is_sqlite:
@@ -269,16 +277,26 @@ async def health() -> dict:
redis_ok = False
queue_pending = None
queue_unacked = None
+ queues_detail: dict[str, int] = {}
try:
import redis
+ from app.workers.queues import parse_worker_queues
+
r = redis.Redis.from_url(
s.redis_url, decode_responses=True, socket_connect_timeout=2, socket_timeout=2
)
redis_ok = bool(r.ping())
if redis_ok:
- q = (s.celery_autoscale_queue or "pipeline").strip() or "pipeline"
- queue_pending = int(r.llen(q) or 0)
+ monitor = parse_worker_queues(
+ (s.celery_worker_queues or s.celery_autoscale_queue or "").strip() or None
+ )
+ for qname in monitor:
+ try:
+ queues_detail[qname] = int(r.llen(qname) or 0)
+ except Exception: # noqa: BLE001
+ queues_detail[qname] = 0
+ queue_pending = sum(queues_detail.values())
try:
queue_unacked = int(r.hlen("unacked") or 0)
except Exception: # noqa: BLE001
@@ -290,7 +308,12 @@ async def health() -> dict:
"ark_mock": s.ark_mock,
"use_celery": s.use_celery,
"redis_ok": redis_ok,
- "queue": {"name": s.celery_autoscale_queue, "pending": queue_pending, "unacked": queue_unacked},
+ "queue": {
+ "name": s.celery_worker_queues or s.celery_autoscale_queue,
+ "pending": queue_pending,
+ "unacked": queue_unacked,
+ "by_name": queues_detail,
+ },
"autoscale": {
"min": s.celery_autoscale_min,
"max": s.celery_autoscale_max,
diff --git a/backend/app/models.py b/backend/app/models.py
index 48806ec..81c2b16 100644
--- a/backend/app/models.py
+++ b/backend/app/models.py
@@ -47,6 +47,9 @@ class User(Base):
billing_unlimited: Mapped[bool] = mapped_column(Boolean, default=False)
# user | admin
role: Mapped[str] = mapped_column(String(16), default="user")
+ avatar_url: Mapped[str] = mapped_column(String(512), default="")
+ # 联系手机,仅记录,不走短信验证
+ phone: Mapped[str] = mapped_column(String(32), default="")
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
projects: Mapped[list["Project"]] = relationship(back_populates="owner")
diff --git a/backend/app/models_api.py b/backend/app/models_api.py
new file mode 100644
index 0000000..0c99edd
--- /dev/null
+++ b/backend/app/models_api.py
@@ -0,0 +1,21 @@
+"""对外 API Key 模型。"""
+
+from datetime import datetime
+
+from sqlalchemy import DateTime, ForeignKey, Integer, String, func
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.database import Base
+
+
+class UserApiKey(Base):
+ __tablename__ = "user_api_keys"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
+ name: Mapped[str] = mapped_column(String(64), default="默认 Key")
+ key_prefix: Mapped[str] = mapped_column(String(24), index=True)
+ key_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+ last_used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+ revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
diff --git a/backend/app/schemas.py b/backend/app/schemas.py
index d06a3ed..ff153de 100644
--- a/backend/app/schemas.py
+++ b/backend/app/schemas.py
@@ -1,4 +1,5 @@
from datetime import datetime
+from typing import Any
from pydantic import BaseModel, EmailStr, Field
@@ -30,10 +31,18 @@ class UserOut(BaseModel):
plan: str = "free"
billing_unlimited: bool = False
role: str = "user"
+ avatar_url: str = ""
+ phone: str = ""
model_config = {"from_attributes": True}
+class ProfileUpdateRequest(BaseModel):
+ nickname: str = Field(max_length=64)
+ email: str = Field(max_length=255)
+ phone: str = Field(default="", max_length=32)
+
+
# ---- Templates ----
class TemplateOut(BaseModel):
id: str
@@ -254,6 +263,104 @@ class AdminStatsOut(BaseModel):
project_status_counts: dict[str, int]
+class AdminQueueTaskOut(BaseModel):
+ task_id: str
+ task_name: str
+ label: str
+ args_repr: str
+ queue: str
+ state: str
+ worker: str | None = None
+ started_at: float | None = None
+ ref_id: int | None = None
+ position: int | None = None
+
+
+class AdminQueueSummaryOut(BaseModel):
+ name: str
+ label: str
+ pending: int
+ sample: list[AdminQueueTaskOut]
+
+
+class AdminWorkerOut(BaseModel):
+ name: str
+ status: str
+ active_count: int
+ processed: int | None = None
+ pool: str | None = None
+
+
+class AdminWorkerPoolOut(BaseModel):
+ name: str
+ pool_implementation: str = ""
+ max_concurrency: int | None = None
+ process_count: int | None = None
+ writes: dict[str, Any] | None = None
+
+
+class AdminWorkerControlOut(BaseModel):
+ mode: str
+ systemd_unit: str | None = None
+ systemd_active: bool | None = None
+ pools: list[AdminWorkerPoolOut] = []
+ total_processes: int = 0
+ max_concurrency: int | None = None
+ pool_max_limit: int = 8
+ can_pool_grow: bool = False
+ can_pool_shrink: bool = False
+ can_restart: bool = False
+ autoscale_running: bool = False
+ autoscale_enabled: bool = False
+ autoscale_pid: int | None = None
+ autoscale_workers: int = 0
+ bounds_min: int = 1
+ bounds_max: int = 3
+ bounds_source: str = "env"
+
+
+class AdminAutoscalePatch(BaseModel):
+ min_workers: int | None = None
+ max_workers: int | None = None
+ enabled: bool | None = None
+
+
+class AdminWorkerActionOut(BaseModel):
+ ok: bool
+ action: str | None = None
+ n: int | None = None
+ unit: str | None = None
+ message: str | None = None
+ pid: int | None = None
+ stopped: bool | None = None
+ already_running: bool | None = None
+ bounds_min: int | None = None
+ bounds_max: int | None = None
+ bounds_source: str | None = None
+ autoscale_enabled: bool | None = None
+ control: AdminWorkerControlOut | None = None
+
+
+class AdminQueuesOut(BaseModel):
+ ok: bool
+ redis_ok: bool
+ use_celery: bool
+ worker_queues: str
+ unacked: int
+ total_pending: int
+ active_count: int
+ reserved_count: int
+ workers_online: int
+ queues: list[AdminQueueSummaryOut]
+ pending_tasks: list[AdminQueueTaskOut]
+ active_tasks: list[AdminQueueTaskOut]
+ reserved_tasks: list[AdminQueueTaskOut]
+ workers: list[AdminWorkerOut]
+ worker_control: AdminWorkerControlOut | None = None
+ autoscale: dict[str, float | int]
+ fetched_at: str
+
+
class AdminUserOut(BaseModel):
id: int
email: EmailStr
@@ -264,6 +371,7 @@ class AdminUserOut(BaseModel):
plan: str
billing_unlimited: bool
role: str
+ phone: str = ""
created_at: datetime | None = None
model_config = {"from_attributes": True}
diff --git a/backend/app/schemas_api.py b/backend/app/schemas_api.py
new file mode 100644
index 0000000..72017b9
--- /dev/null
+++ b/backend/app/schemas_api.py
@@ -0,0 +1,57 @@
+from datetime import datetime
+
+from pydantic import BaseModel, Field
+
+
+class ApiKeyCreateRequest(BaseModel):
+ name: str = Field(default="默认 Key", max_length=64)
+
+
+class ApiKeyOut(BaseModel):
+ id: int
+ name: str
+ key_prefix: str
+ created_at: datetime | None = None
+ last_used_at: datetime | None = None
+
+ model_config = {"from_attributes": True}
+
+
+class ApiKeyCreatedOut(ApiKeyOut):
+ secret: str
+
+
+class V1ImageGenerateRequest(BaseModel):
+ prompt: str = Field(min_length=1, max_length=4000)
+ negative: str = Field(default="", max_length=2000)
+ ratio: str = Field(default="1:1", description="1:1 | 16:9 | 9:16")
+ image_url: str | None = Field(default=None, description="参考图 URL,传入则为图生图")
+
+
+class V1VideoGenerateRequest(BaseModel):
+ prompt: str = Field(min_length=1, max_length=8000)
+ image_url: str = Field(min_length=8, description="首帧图公网 URL")
+ duration: int = Field(default=5, ge=4, le=15)
+ resolution: str = Field(default="480p")
+ generate_audio: bool = False
+
+
+class V1SeedanceTaskRequest(BaseModel):
+ """接近火山 Seedance 的任务体,服务端补全 model 并转发。"""
+
+ content: list[dict]
+ duration: int | None = Field(default=None, ge=4, le=30)
+ resolution: str = Field(default="480p")
+ ratio: str | None = None
+ generate_audio: bool = False
+ return_last_frame: bool = True
+ watermark: bool = False
+
+
+class V1GenerationOut(BaseModel):
+ status: str
+ kind: str
+ urls: list[str] = Field(default_factory=list)
+ task_id: str | None = None
+ preview_url: str | None = None
+ error: str | None = None
diff --git a/backend/app/services/api_keys.py b/backend/app/services/api_keys.py
new file mode 100644
index 0000000..e182761
--- /dev/null
+++ b/backend/app/services/api_keys.py
@@ -0,0 +1,76 @@
+"""用户 API Key 创建、校验与撤销。"""
+
+from __future__ import annotations
+
+import hashlib
+import secrets
+from datetime import datetime, timezone
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models import User
+from app.models_api import UserApiKey
+
+API_KEY_PREFIX = "pf_live_"
+
+
+def _hash_key(raw: str) -> str:
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()
+
+
+def generate_api_key() -> tuple[str, str, str]:
+ """返回 (完整 key, 展示前缀, hash)。"""
+ secret = secrets.token_urlsafe(24).replace("-", "").replace("_", "")[:32]
+ raw = f"{API_KEY_PREFIX}{secret}"
+ prefix = raw[:16]
+ return raw, prefix, _hash_key(raw)
+
+
+async def create_api_key(db: AsyncSession, user: User, name: str) -> tuple[UserApiKey, str]:
+ raw, prefix, key_hash = generate_api_key()
+ row = UserApiKey(
+ user_id=user.id,
+ name=(name or "默认 Key").strip()[:64] or "默认 Key",
+ key_prefix=prefix,
+ key_hash=key_hash,
+ )
+ db.add(row)
+ await db.flush()
+ return row, raw
+
+
+async def list_api_keys(db: AsyncSession, user_id: int) -> list[UserApiKey]:
+ result = await db.execute(
+ select(UserApiKey)
+ .where(UserApiKey.user_id == user_id, UserApiKey.revoked_at.is_(None))
+ .order_by(UserApiKey.id.desc())
+ )
+ return list(result.scalars().all())
+
+
+async def revoke_api_key(db: AsyncSession, user_id: int, key_id: int) -> bool:
+ row = await db.get(UserApiKey, key_id)
+ if not row or row.user_id != user_id or row.revoked_at is not None:
+ return False
+ row.revoked_at = datetime.now(timezone.utc)
+ await db.flush()
+ return True
+
+
+async def user_from_api_key(db: AsyncSession, raw_key: str) -> User | None:
+ if not raw_key.startswith(API_KEY_PREFIX):
+ return None
+ key_hash = _hash_key(raw_key.strip())
+ result = await db.execute(
+ select(UserApiKey, User)
+ .join(User, User.id == UserApiKey.user_id)
+ .where(UserApiKey.key_hash == key_hash, UserApiKey.revoked_at.is_(None))
+ )
+ row = result.first()
+ if not row:
+ return None
+ api_key, user = row
+ api_key.last_used_at = datetime.now(timezone.utc)
+ await db.flush()
+ return user
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
index 6ec4ac4..9b4e40d 100644
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@ -238,10 +238,22 @@ class ArkGateway:
mode = "character"
if mode == "diverse":
+ if (character_hint or "").strip():
+ person_rule = (
+ "character_bible:概括用户人物设定(可换具体个人,但须同类)。"
+ "【人物硬性】每镜必须出现符合用户人物设定的真人,面容清晰可见"
+ "(三分之四侧脸或浅景深半身),禁止只拍手部、后脑勺、过肩无脸或空界面无人。"
+ "img_prompt 须写清该镜人物族裔/发型/服装与可见面容角度,以及面前界面类型;各镜可换人。"
+ )
+ else:
+ person_rule = (
+ "character_bible:填「无固定人物,各镜为独立系统/场景界面」。"
+ "每镜 img_prompt 必须写清该镜独特的界面类型、布局分区、主色与信息层级,不要粘贴人物锁定。"
+ )
consistency = (
"必须输出严格 JSON 对象(不要数组、不要 markdown、不要代码围栏):"
'{"character_bible":"...","shots":[...]}。'
- "character_bible:填「无固定人物,各镜为独立系统/场景界面」。"
+ f"{person_rule}"
f"视觉气质仅作底线参考(不要被其颜色绑架):{style_prefix}。"
f"{user_constraints}"
"【动态规划】先分析用户内容的领域、产品形态与使用场景,再决定色板与界面类型,"
@@ -249,7 +261,6 @@ class ArkGateway:
"配色与材质必须贴合内容(浅色SaaS、文档站、深色IDE、终端、架构图、白板均可),"
"禁止默认霓虹蓝/赛博大屏/蓝紫渐变HUD,禁止各镜画面雷同,禁止待办任务清单,"
"禁止同一仪表盘复制粘贴换字。"
- "每镜 img_prompt 必须写清该镜独特的界面类型、布局分区、主色与信息层级,不要粘贴人物锁定。"
)
elif mode == "style":
consistency = (
@@ -273,16 +284,19 @@ class ArkGateway:
"每镜 img_prompt 只写本镜场景与构图(景物、动作、光影),不要重复粘贴大段画风/人物锁定原文;"
"出现人物时用短句点出与 character_bible 一致的关键特征即可。"
)
- # shot_cap 单镜 duration 上限(秒),写入 prompt 与校验说明
+ # shot_cap 单镜 duration 上限(秒);shot_lo/shot_hi 按文案字数动态拆镜数
shot_cap = min(duration_max, max_shot_duration)
+ shot_lo, shot_hi = segplan.suggested_kepu_shot_range(source_text, pipeline_mode=pipeline_mode)
+ shot_range = f"{shot_lo}-{shot_hi}"
# segment_rules 科普逐段脚本生产约束(对齐漫剧 cue,无 @asset)
segment_rules = (
"【segments 生产规范】"
- "segments 必填;系统会落成 @duration +【字幕】/【BGM】/【旁白·慢速清晰·同步字幕】生产脚本,"
+ "segments 必填;系统会落成 @duration +【字幕】/【BGM】/【旁白·自然语速·同步字幕】生产脚本,"
"因此 kind/text/duration 必须可直接消费。"
"段序优先「画面→旁白」交替,首段尽量 kind=visual(保证首帧有料);"
"visual/action 的 text 必须含景别+主体动作+场景/界面类型,禁止空镜与模糊氛围词堆砌;"
- "narration 的 text 为一句一事、可朗读口播,按约 3 字/秒估 duration;"
+ "narration 的 text 为一句一事、可朗读口播,按约 5 字/秒估 duration(语速自然偏快);"
+ "旁白 duration 严格跟字数,最多多 1 秒呼吸,禁止把短句拉满到镜长上限或拖腔注水;"
"单段 duration 3-12 秒,镜内各段之和约等于本镜 duration,且不超过 "
f"{shot_cap} 秒。"
"禁止真实商标/公司名/人名(改用泛称)。"
@@ -290,7 +304,7 @@ class ArkGateway:
)
if pipeline_mode == "image_text":
diversity_note = (
- "拆成 5-10 个分镜,每镜一个独立视觉场景;"
+ f"拆成 {shot_range} 个分镜,每镜一个独立视觉场景;"
+ (
"画风气质可统一,但界面/场景构图必须明显不同。"
if mode != "character"
@@ -322,15 +336,15 @@ class ArkGateway:
)
else:
diversity_note = (
- "拆成 4-6 个分镜;各镜场景随内容变化,禁止雷同空镜。"
+ f"拆成 {shot_range} 个分镜,短镜快切,各镜场景随内容变化,禁止雷同空镜。"
if mode != "character"
- else "画风与人物必须全片一致;倾向 4-6 镜。"
+ else f"画风与人物必须全片一致;拆成 {shot_range} 镜,短镜快切。"
)
system = (
"你是短视频分镜编剧。所有字段必须使用简体中文"
"(包括 title、text、img_prompt、video_prompt、camera、bgm、segments)。"
f"{consistency}{llm_system_addon}"
- f"每镜 duration 在 {duration_min}-{shot_cap} 秒。"
+ f"每镜 duration 在 {duration_min}-{shot_cap} 秒,不要为凑满上限而注水。"
"shots 字段说明:"
"shot(序号)、duration(秒)、"
"title(对本镜旁白的概括短标题,2-8字,语义完整;"
@@ -348,7 +362,7 @@ class ArkGateway:
)
user = (
f"输入类型:{source_type}。请先理解内容与应用场景,再拆成精确到每一段的分镜"
- f"(4-6 镜为佳,完整模式):\n{source_text}"
+ f"({shot_range} 镜,短镜快切,禁止拖腔注水):\n{source_text}"
)
content = await chat_completions(system, user, temperature=0.6, timeout=120.0)
return self._parse_storyboard(
@@ -1212,7 +1226,11 @@ class ArkGateway:
]
if len(chunks) < 3:
chunks = chunks + ["补充画面过渡", "收尾总结"]
- chunks = chunks[:10]
+ # shot_lo/shot_hi 与正式拆镜区间一致,避免 mock 仍只出 5 镜
+ shot_lo, shot_hi = segplan.suggested_kepu_shot_range(source_text, pipeline_mode=pipeline_mode)
+ chunks = chunks[:shot_hi]
+ while len(chunks) < shot_lo:
+ chunks.append("补充画面过渡")
mid = (duration_min + duration_max) // 2
if pipeline_mode == "image_text":
mid = min(mid, max(duration_min, 3))
diff --git a/backend/app/services/billing.py b/backend/app/services/billing.py
index 0a3ca4a..b24cb37 100644
--- a/backend/app/services/billing.py
+++ b/backend/app/services/billing.py
@@ -302,3 +302,85 @@ def sku_by_id(sku_id: str) -> dict[str, Any] | None:
if s["id"] == sku_id:
return s
return None
+
+
+# 待支付订单有效期(秒),与前端扫码倒计时一致
+ORDER_EXPIRE_SECONDS = 300
+
+
+async def close_expired_pending_orders(
+ db: AsyncSession,
+ *,
+ user_id: int | None = None,
+ out_trade_no: str | None = None,
+) -> int:
+ """将超时未支付的 pending 订单自动标为 closed,返回关闭条数。"""
+ from datetime import datetime, timedelta, timezone
+
+ from app.models import Order
+
+ now = datetime.now(timezone.utc)
+ stmt = select(Order).where(Order.status == "pending")
+ if user_id is not None:
+ stmt = stmt.where(Order.user_id == user_id)
+ if out_trade_no is not None:
+ stmt = stmt.where(Order.out_trade_no == out_trade_no)
+ rows = (await db.execute(stmt)).scalars().all()
+ closed = 0
+ for order in rows:
+ created = order.created_at
+ if created is None:
+ continue
+ if created.tzinfo is None:
+ created = created.replace(tzinfo=timezone.utc)
+ age = (now - created).total_seconds()
+ if age < ORDER_EXPIRE_SECONDS:
+ continue
+ order.status = "closed"
+ closed += 1
+ if closed:
+ await db.commit()
+ return closed
+
+
+async def settle_usage_charge(
+ db: AsyncSession,
+ user: User,
+ charge_fen: int,
+ *,
+ ref_type: str = "api",
+ ref_id: str = "",
+) -> None:
+ """API 等即时扣费:余额不足时抛 ValueError。"""
+ if not billing_active(user):
+ return
+ need = max(0, int(charge_fen))
+ if need <= 0:
+ return
+ available = int(user.balance_fen or 0)
+ if available < need:
+ raise ValueError(f"余额不足:需要 ¥{need / 100:.2f},当前 ¥{available / 100:.2f},请先充值")
+ await _ledger(
+ db,
+ user,
+ -need,
+ "settle",
+ ref_type=ref_type,
+ ref_id=ref_id,
+ note="api_usage",
+ )
+ await db.flush()
+
+
+def billing_key_label(billing_key: str) -> str:
+ """把 billing_key 转成用户可读的能力名称。"""
+ key = (billing_key or "").strip().lower()
+ if key == "llm_chat":
+ return "LLM 对话"
+ if key == "seedream":
+ return "图片生成"
+ if key.startswith("seedance"):
+ return "视频生成"
+ if key == "tts":
+ return "语音合成"
+ return billing_key or "其他"
diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.py
index 0ef9297..00bbf59 100644
--- a/backend/app/services/drama/jobs.py
+++ b/backend/app/services/drama/jobs.py
@@ -32,6 +32,7 @@ from app.services.drama.agents import (
from app.services.drama.asset_video import generate_asset_video
from app.services.drama.generation import generate_asset_image, generate_fragment_video
from app.services.drama.visual_prompt import resolve_visual_prompt_for_asset
+from app.workers.queues import DRAMA_QUEUE, PIPELINE_QUEUE, VIDEO_QUEUE
logger = logging.getLogger(__name__)
@@ -47,7 +48,7 @@ VIDEO_CELERY_TASKS = frozenset(
"app.workers.tasks.regen_video_task",
}
)
-VIDEO_QUEUES = ("video", "pipeline")
+VIDEO_QUEUES = (VIDEO_QUEUE,)
ACTIVE_VIDEO_GEN_STATUSES = frozenset({"queued", "running", "generating"})
@@ -310,7 +311,7 @@ def dispatch_script_summary_job(project_id: int) -> str:
if _use_celery():
from app.workers.drama_tasks import drama_script_summary_task
- result = drama_script_summary_task.apply_async(args=[project_id], queue="pipeline")
+ result = drama_script_summary_task.apply_async(args=[project_id], queue=DRAMA_QUEUE)
logger.info("dispatch 剧本摘要 → Celery project_id=%s task_id=%s", project_id, result.id)
return str(result.id)
@@ -349,6 +350,7 @@ async def run_script_summary_job(project_id: int) -> dict[str, Any]:
params = dict(script.params or {})
params["summary_status"] = "failed"
params["summary_error"] = str(exc)[:500]
+ params.pop("summary_generating_at", None)
script.params = params
await db.commit()
logger.exception("剧本摘要失败 project_id=%s err=%s", project_id, exc)
@@ -359,6 +361,7 @@ async def run_script_summary_job(project_id: int) -> dict[str, Any]:
params["summary_text"] = format_summary_text(summary)
params["summary_status"] = "completed"
params["summary_error"] = None
+ params.pop("summary_generating_at", None)
params["episode_content_status"] = params.get("episode_content_status") or "pending"
script.params = params
one_line = str(summary.get("oneLineStory") or "").strip()
@@ -401,7 +404,7 @@ def dispatch_episode_scripts_job(project_id: int, force: bool = False) -> str:
result = drama_episode_scripts_task.apply_async(
args=[project_id, force],
- queue="pipeline",
+ queue=DRAMA_QUEUE,
)
logger.info(
"dispatch 分集剧本 → Celery project_id=%s force=%s task_id=%s",
@@ -556,7 +559,7 @@ def dispatch_episode_fragment_plan_job(episode_id: int, *, fallback_rules: bool
result = drama_episode_fragment_plan_task.apply_async(
args=[episode_id, fallback_rules],
- queue="pipeline",
+ queue=DRAMA_QUEUE,
)
logger.info(
"dispatch 单集分镜 → Celery episode_id=%s task_id=%s",
@@ -773,7 +776,7 @@ def dispatch_episode_generate_job(
result = drama_episode_generate_task.apply_async(
args=[episode_id, user_id, fragment_ids],
- queue="video",
+ queue=VIDEO_QUEUE,
)
_episode_video_celery_ids[int(episode_id)] = str(result.id)
logger.info(
@@ -989,7 +992,7 @@ def dispatch_asset_image_job(
"aspect_ratio": aspect_ratio,
"resolution": resolution,
},
- queue="pipeline",
+ queue=DRAMA_QUEUE,
)
logger.info(
"dispatch 资产生图 → Celery project_id=%s asset_id=%s kind=%s task_id=%s",
@@ -1158,7 +1161,7 @@ def dispatch_asset_video_job(
"image_style_id": image_style_id,
"reference_asset_ids": reference_asset_ids or [],
},
- queue="video",
+ queue=VIDEO_QUEUE,
)
logger.info(
"dispatch 资产生视频 → Celery project_id=%s asset_id=%s task_id=%s",
diff --git a/backend/app/services/drama/llm.py b/backend/app/services/drama/llm.py
index 8859992..903e099 100644
--- a/backend/app/services/drama/llm.py
+++ b/backend/app/services/drama/llm.py
@@ -18,20 +18,57 @@ logger = logging.getLogger(__name__)
# 兼容旧引用
DramaLlmUnavailableError = LlmUnavailableError
+_JSON_FENCE_RE = re.compile(r"^```(?:json)?\s*", re.IGNORECASE)
+_JSON_FENCE_TAIL_RE = re.compile(r"\s*```$")
+_TRAILING_COMMA_RE = re.compile(r",(\s*[}\]])")
+_SMART_QUOTE_MAP = str.maketrans(
+ {
+ "\u201c": '"',
+ "\u201d": '"',
+ "\u2018": "'",
+ "\u2019": "'",
+ }
+)
-def _extract_json(text: str) -> Any:
- # Parse JSON object/array from model output (strip fences if present)
+
+def _strip_json_fences(text: str) -> str:
+ # 去掉 markdown 代码围栏
raw = (text or "").strip()
- if raw.startswith("```"):
- raw = re.sub(r"^```(?:json)?\s*", "", raw)
- raw = re.sub(r"\s*```$", "", raw)
- try:
- return json.loads(raw)
- except json.JSONDecodeError:
- m = re.search(r"(\{[\s\S]*\}|\[[\s\S]*\])", raw)
- if not m:
- raise
- return json.loads(m.group(1))
+ raw = _JSON_FENCE_RE.sub("", raw)
+ raw = _JSON_FENCE_TAIL_RE.sub("", raw)
+ return raw.strip()
+
+
+def _repair_json_text(raw: str) -> str:
+ # 常见 LLM JSON 瑕疵:智能引号、尾逗号
+ repaired = raw.translate(_SMART_QUOTE_MAP)
+ repaired = _TRAILING_COMMA_RE.sub(r"\1", repaired)
+ return repaired
+
+
+def _extract_json(text: str) -> Any:
+ # 从模型输出解析 JSON(去围栏、修复常见格式错误)
+ raw = _strip_json_fences(text)
+ candidates = [raw, _repair_json_text(raw)]
+
+ m = re.search(r"(\{[\s\S]*\}|\[[\s\S]*\])", raw)
+ if m and m.group(1) not in candidates:
+ snippet = m.group(1)
+ candidates.extend([snippet, _repair_json_text(snippet)])
+
+ last_error: json.JSONDecodeError | None = None
+ for candidate in candidates:
+ if not candidate:
+ continue
+ try:
+ return json.loads(candidate)
+ except json.JSONDecodeError as exc:
+ last_error = exc
+ continue
+
+ if last_error:
+ raise last_error
+ raise json.JSONDecodeError("empty JSON payload", text or "", 0)
async def drama_chat_json(
@@ -42,14 +79,51 @@ async def drama_chat_json(
max_tokens: int = DEFAULT_MAX_TOKENS,
) -> Any:
"""Call text LLM and parse JSON from the reply."""
- content = await chat_completions(
- system,
- user,
- temperature=temperature,
- max_tokens=max_tokens,
- timeout=300.0,
- )
- return _extract_json(content)
+ json_format = {"type": "json_object"}
+ try:
+ content = await chat_completions(
+ system,
+ user,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ timeout=300.0,
+ response_format=json_format,
+ )
+ except RuntimeError as exc:
+ # 部分兼容网关不支持 response_format,降级为普通调用
+ if "response_format" not in str(exc).lower():
+ raise
+ logger.warning("LLM 不支持 response_format,降级普通调用: %s", exc)
+ content = await chat_completions(
+ system,
+ user,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ timeout=300.0,
+ )
+
+ try:
+ return _extract_json(content)
+ except json.JSONDecodeError as first_error:
+ logger.warning(
+ "JSON 解析失败,重试一次 err=%s content_head=%s",
+ first_error,
+ (content or "")[:200],
+ )
+ retry_user = (
+ f"{user}\n\n"
+ "【重要】上次输出不是合法 JSON。请只输出一个完整、可 json.loads 的 JSON 对象,"
+ "不要 markdown、不要代码围栏、字符串内不要未转义换行。"
+ )
+ content = await chat_completions(
+ system,
+ retry_user,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ timeout=300.0,
+ response_format=json_format,
+ )
+ return _extract_json(content)
async def drama_chat_text(
diff --git a/backend/app/services/drama/seed.py b/backend/app/services/drama/seed.py
index a6f01e0..e8f59b2 100644
--- a/backend/app/services/drama/seed.py
+++ b/backend/app/services/drama/seed.py
@@ -519,6 +519,19 @@ async def seed_episodes_from_script(
return await _reload_episodes(db, project.id)
+async def _list_episode_fragments(
+ db: AsyncSession,
+ episode_id: int,
+) -> list[DramaEpisodeFragment]:
+ # 显式查询分镜,避免 async 会话下 lazy load episode.fragments 触发 MissingGreenlet
+ result = await db.execute(
+ select(DramaEpisodeFragment)
+ .where(DramaEpisodeFragment.episode_id == episode_id)
+ .order_by(DramaEpisodeFragment.sort_order.asc())
+ )
+ return list(result.scalars().all())
+
+
async def _replace_episode_fragments(
db: AsyncSession,
episode: DramaEpisode,
@@ -532,7 +545,7 @@ async def _replace_episode_fragments(
continuation: bool = False,
) -> list[dict[str, Any]]:
# 删除旧分镜并重建;preserve_protected 时保留已有视频/手改分镜
- existing = list(episode.fragments or [])
+ existing = await _list_episode_fragments(db, episode.id)
protected = (
sorted(
[f for f in existing if _fragment_is_protected(f)],
diff --git a/backend/app/services/ffmpeg_compose.py b/backend/app/services/ffmpeg_compose.py
index 498968f..d2aae74 100644
--- a/backend/app/services/ffmpeg_compose.py
+++ b/backend/app/services/ffmpeg_compose.py
@@ -51,13 +51,16 @@ class ComposeOptions:
# One continuous TTS track for the whole film (preferred over per-shot audio)
full_audio_path: Path | None = None
# Overlay / caption sizing & layout (from template.subtitle_config)
- subtitle_layout: str = "top" # top | split (title top, subtitle bottom)
+ subtitle_layout: str = "top" # top | split(标题在上;口播字幕始终底部)
title_scale: float = 1.35
sub_scale: float = 1.3
caption_scale: float = 1.25
# Optional continuous BGM under narration
bgm_path: Path | None = None
bgm_volume: float = 0.22
+ # 保留镜头视频里的操作音效,后期与 TTS 叠轨(科普 full)
+ keep_video_sfx: bool = False
+ sfx_volume: float = 0.22
def allocate_durations_by_narration(
@@ -89,6 +92,34 @@ def allocate_durations_by_narration(
return [*head, last]
+def _probe_has_audio(path: Path) -> bool:
+ """片源是否含音轨(操作音效/人声均算)。"""
+ ffprobe = shutil.which(get_settings().ffprobe_path) or shutil.which("ffprobe")
+ if not ffprobe or not path.exists():
+ return False
+ try:
+ proc = subprocess.run(
+ [
+ ffprobe,
+ "-v",
+ "error",
+ "-select_streams",
+ "a",
+ "-show_entries",
+ "stream=codec_type",
+ "-of",
+ "csv=p=0",
+ str(path),
+ ],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return bool((proc.stdout or "").strip())
+ except Exception: # noqa: BLE001
+ return False
+
+
def probe_duration(path: Path) -> float | None:
"""Return media duration in seconds via ffprobe, or None."""
ffprobe = shutil.which(get_settings().ffprobe_path) or shutil.which("ffprobe")
@@ -567,7 +598,7 @@ def _overlay_drawtext(
title_scale: float = 1.35,
sub_scale: float = 1.3,
) -> str:
- """Title + subtitle overlays. layout=split → title top / subtitle bottom (开源展示风)."""
+ """顶部标题叠字。split 也把副标题放在标题下方,底部留给口播字幕。"""
title = _strip_caption_punct(title)
subtitle = _strip_caption_punct(subtitle)
title_cap = 14 if layout == "split" else 12
@@ -582,20 +613,14 @@ def _overlay_drawtext(
title_size = max(34, min(52, int(w * 0.058 * max(0.8, title_scale))))
sub_size = max(24, min(36, int(w * 0.042 * max(0.8, sub_scale))))
title_y = int(h * 0.055)
- if layout == "split":
- sub_y = max(0, h - sub_size - int(h * 0.07))
- else:
- sub_y = title_y + title_size + int(h * 0.014)
+ sub_y = title_y + title_size + int(h * 0.014)
parts: list[str] = []
- # Soft vignette behind text
- if layout == "split":
- parts.append(f"drawbox=x=0:y=0:w={w}:h={int(h * 0.16)}:[email protected]:t=fill")
- parts.append(
- f"drawbox=x=0:y={h - int(h * 0.16)}:w={w}:h={int(h * 0.16)}:[email protected]:t=fill"
- )
- else:
- parts.append(f"drawbox=x=0:y=0:w={w}:h={int(h * 0.2)}:[email protected]:t=fill")
+ if not title_e and not sub_e:
+ return ""
+ # Soft vignette behind title block (bottom is reserved for narration captions)
+ bar_h = int(h * 0.22) if layout == "split" else int(h * 0.2)
+ parts.append(f"drawbox=x=0:y=0:w={w}:h={bar_h}:[email protected]:t=fill")
font_opt = f":fontfile='{_escape_fontfile(font)}'" if font else ""
@@ -614,6 +639,42 @@ def _overlay_drawtext(
return ",".join(parts)
+def build_video_caption_vf(
+ *,
+ narration: str,
+ duration: float,
+ w: int,
+ h: int,
+ font: str | None,
+ title: str = "",
+ subtitle: str = "",
+ subtitle_layout: str = "top",
+ title_scale: float = 1.35,
+ sub_scale: float = 1.3,
+ caption_scale: float = 1.25,
+) -> str:
+ """合成阶段字幕滤镜:顶部标题 + 底部口播,始终烧录(含 split 布局)。"""
+ parts: list[str] = []
+ overlay = _overlay_drawtext(
+ w,
+ h,
+ title,
+ subtitle,
+ font,
+ layout=subtitle_layout,
+ title_scale=title_scale,
+ sub_scale=sub_scale,
+ )
+ if overlay:
+ parts.append(overlay)
+ captions = _bottom_caption_drawtext(
+ narration, duration=duration, w=w, h=h, font=font, scale=caption_scale
+ )
+ if captions:
+ parts.append(captions)
+ return ",".join(parts)
+
+
def _image_to_video_kenburns(
image: Path,
duration: float,
@@ -633,25 +694,21 @@ def _image_to_video_kenburns(
) -> None:
ffmpeg = _which("ffmpeg")
vf = _ken_burns_filter(w, h, duration, shot_no)
- overlay = _overlay_drawtext(
- w,
- h,
- title,
- subtitle,
- font,
- layout=subtitle_layout,
+ captions = build_video_caption_vf(
+ narration=narration,
+ duration=duration,
+ w=w,
+ h=h,
+ font=font,
+ title=title,
+ subtitle=subtitle,
+ subtitle_layout=subtitle_layout,
title_scale=title_scale,
sub_scale=sub_scale,
+ caption_scale=caption_scale,
)
- if overlay:
- vf = f"{vf},{overlay}"
- # split 布局底部已是副标题,不再叠旁白滚动字幕以免抢戏
- if subtitle_layout != "split":
- captions = _bottom_caption_drawtext(
- narration, duration=duration, w=w, h=h, font=font, scale=caption_scale
- )
- if captions:
- vf = f"{vf},{captions}"
+ if captions:
+ vf = f"{vf},{captions}"
_run(
[
ffmpeg,
@@ -690,48 +747,44 @@ def _burn_captions_on_video(
subtitle_layout: str = "top",
title_scale: float = 1.35,
sub_scale: float = 1.3,
+ keep_audio: bool = False,
) -> None:
- """Burn title/subtitle + timed bottom captions onto an existing video clip (full mode)."""
- parts: list[str] = []
- overlay = _overlay_drawtext(
- w,
- h,
- title,
- subtitle,
- font,
- layout=subtitle_layout,
+ """Burn title + timed bottom narration captions onto an existing video clip."""
+ vf = build_video_caption_vf(
+ narration=narration,
+ duration=duration,
+ w=w,
+ h=h,
+ font=font,
+ title=title,
+ subtitle=subtitle,
+ subtitle_layout=subtitle_layout,
title_scale=title_scale,
sub_scale=sub_scale,
+ caption_scale=caption_scale,
)
- if overlay:
- parts.append(overlay)
- # split 布局底部已是副标题,不再叠旁白滚动字幕以免抢戏
- if subtitle_layout != "split":
- captions = _bottom_caption_drawtext(
- narration, duration=duration, w=w, h=h, font=font, scale=caption_scale
- )
- if captions:
- parts.append(captions)
ffmpeg = _which("ffmpeg")
- if not parts:
+ if not vf:
_run([ffmpeg, "-y", "-i", str(video_in), "-c", "copy", str(video_out)])
return
- _run(
- [
- ffmpeg,
- "-y",
- "-i",
- str(video_in),
- "-vf",
- ",".join(parts),
- "-c:v",
- "libx264",
- "-pix_fmt",
- "yuv420p",
- "-an",
- str(video_out),
- ]
- )
+ cmd = [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(video_in),
+ "-vf",
+ vf,
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ ]
+ if keep_audio and _probe_has_audio(video_in):
+ cmd.extend(["-c:a", "aac", "-ac", "2", "-ar", "44100"])
+ else:
+ cmd.append("-an")
+ cmd.append(str(video_out))
+ _run(cmd)
@@ -767,6 +820,7 @@ def _pad_or_trim_video(
*,
w: int,
h: int,
+ keep_audio: bool = False,
) -> None:
"""Scale video to canvas and force exact duration: trim if longer, freeze-pad if shorter.
@@ -782,79 +836,195 @@ def _pad_or_trim_video(
vf = f"{base_vf},tpad=stop_mode=clone:stop_duration={pad:.3f},format=yuv420p"
else:
vf = f"{base_vf},format=yuv420p"
+ cmd = [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(src),
+ "-t",
+ f"{target:.3f}",
+ "-vf",
+ vf,
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ ]
+ if keep_audio and _probe_has_audio(src):
+ cmd.extend(["-af", "apad", "-c:a", "aac", "-ac", "2", "-ar", "44100"])
+ else:
+ cmd.append("-an")
+ cmd.append(str(dest))
+ _run(cmd)
+
+
+def _mux_shot(
+ video: Path,
+ audio: Path,
+ duration: float,
+ out: Path,
+ *,
+ mix_video_sfx: bool = False,
+ sfx_volume: float = 0.22,
+) -> None:
+ """把镜头画面与配音封装;可选把视频里的操作音效压低叠在 TTS 下。"""
+ ffmpeg = _which("ffmpeg")
+ target = max(float(duration), 0.5)
+ if mix_video_sfx and _probe_has_audio(video):
+ vol = max(0.0, min(float(sfx_volume), 1.0))
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(video),
+ "-i",
+ str(audio),
+ "-filter_complex",
+ f"[0:a]volume={vol:.3f}[sfx];[1:a]volume=1.0[vo];"
+ "[sfx][vo]amix=inputs=2:duration=first:dropout_transition=0:normalize=0[a]",
+ "-map",
+ "0:v:0",
+ "-map",
+ "[a]",
+ "-t",
+ f"{target:.3f}",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:a",
+ "aac",
+ "-ac",
+ "2",
+ "-ar",
+ "44100",
+ str(out),
+ ]
+ )
+ return
_run(
[
ffmpeg,
"-y",
"-i",
- str(src),
+ str(video),
+ "-i",
+ str(audio),
"-t",
f"{target:.3f}",
- "-vf",
- vf,
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
- "-an",
- str(dest),
+ "-c:a",
+ "aac",
+ # Video was already fitted to target; avoid -shortest cutting early
+ str(out),
]
)
-def _mux_shot(video: Path, audio: Path, duration: float, out: Path) -> None:
+def _copy_fitted_clip(video: Path, duration: float, out: Path) -> None:
+ """把已对齐时长的镜头重封装成成片段,保留操作音效轨。"""
ffmpeg = _which("ffmpeg")
- target = max(float(duration), 0.5)
_run(
[
ffmpeg,
"-y",
"-i",
str(video),
- "-i",
- str(audio),
"-t",
- f"{target:.3f}",
+ f"{max(duration, 0.5):.3f}",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-c:a",
"aac",
- # Video was already fitted to target; avoid -shortest cutting early
+ "-ac",
+ "2",
+ "-ar",
+ "44100",
str(out),
]
)
-def _mux_continuous_narration(merged: Path, narration: Path, output: Path) -> None:
- """Attach full-film TTS; pad video with freeze if shorter so旁白不被裁切."""
+def _mux_continuous_narration(
+ merged: Path,
+ narration: Path,
+ output: Path,
+ *,
+ mix_video_sfx: bool = False,
+ sfx_volume: float = 0.22,
+) -> None:
+ """叠整片 TTS;可选把镜头操作音效压低混入。视频偏短时冻帧补齐,避免旁白被裁切。"""
ffmpeg = _which("ffmpeg")
vid_d = probe_duration(merged) or 0.0
aud_d = probe_duration(narration) or 0.0
video_in = merged
tmp_pad: Path | None = None
+ keep_sfx = bool(mix_video_sfx and _probe_has_audio(merged))
if aud_d > 0.5 and vid_d > 0.05 and aud_d > vid_d + 0.12:
tmp_pad = merged.with_name(merged.stem + "_pad.mp4")
pad = aud_d - vid_d
+ pad_cmd = [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(merged),
+ "-vf",
+ f"tpad=stop_mode=clone:stop_duration={pad:.3f}",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ ]
+ if keep_sfx:
+ pad_cmd.extend(["-af", "apad", "-c:a", "aac", "-ac", "2", "-ar", "44100"])
+ else:
+ pad_cmd.append("-an")
+ pad_cmd.append(str(tmp_pad))
+ _run(pad_cmd)
+ video_in = tmp_pad
+ keep_sfx = bool(mix_video_sfx and _probe_has_audio(video_in))
+ out_t = max(aud_d, vid_d, 0.5)
+ if keep_sfx:
+ vol = max(0.0, min(float(sfx_volume), 1.0))
_run(
[
ffmpeg,
"-y",
"-i",
- str(merged),
- "-vf",
- f"tpad=stop_mode=clone:stop_duration={pad:.3f}",
+ str(video_in),
+ "-i",
+ str(narration),
+ "-filter_complex",
+ f"[0:a]volume={vol:.3f}[sfx];[1:a]volume=1.0[vo];"
+ "[sfx][vo]amix=inputs=2:duration=longest:dropout_transition=2:normalize=0[a]",
+ "-map",
+ "0:v:0",
+ "-map",
+ "[a]",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
- "-an",
- str(tmp_pad),
+ "-c:a",
+ "aac",
+ "-ac",
+ "2",
+ "-ar",
+ "44100",
+ "-t",
+ f"{out_t:.3f}",
+ "-movflags",
+ "+faststart",
+ str(output),
]
)
- video_in = tmp_pad
- out_t = max(aud_d, vid_d, 0.5)
+ return
_run(
[
ffmpeg,
@@ -900,6 +1070,8 @@ def compose_project(
tmp_path = Path(tmp)
segment_paths: list[Path] = []
continuous = bool(opts.full_audio_path and opts.full_audio_path.exists())
+ keep_sfx = bool(opts.keep_video_sfx)
+ sfx_vol = float(opts.sfx_volume or 0.22)
for shot in shots:
seg = tmp_path / f"shot_{shot.shot_no:03d}.mp4"
@@ -960,6 +1132,7 @@ def compose_project(
shot.duration,
w=w,
h=h,
+ keep_audio=keep_sfx,
)
_burn_captions_on_video(
raw_v,
@@ -975,6 +1148,7 @@ def compose_project(
subtitle_layout=opts.subtitle_layout or "top",
title_scale=opts.title_scale,
sub_scale=opts.sub_scale,
+ keep_audio=keep_sfx,
)
elif shot.image_path and shot.image_path.exists():
_image_to_video(shot.image_path, shot.duration, video, w=w, h=h)
@@ -1012,7 +1186,17 @@ def compose_project(
]
)
- _mux_shot(video, audio, shot.duration, seg)
+ if continuous and keep_sfx and _probe_has_audio(video):
+ _copy_fitted_clip(video, shot.duration, seg)
+ else:
+ _mux_shot(
+ video,
+ audio,
+ shot.duration,
+ seg,
+ mix_video_sfx=keep_sfx and not continuous,
+ sfx_volume=sfx_vol,
+ )
segment_paths.append(seg)
concat_list = tmp_path / "concat.txt"
@@ -1038,9 +1222,15 @@ def compose_project(
)
if continuous and opts.full_audio_path:
- # Replace silent concat audio with one continuous narration track
+ # 整片 TTS 叠在镜头操作音效上(无音效则只保留旁白)
voiced = tmp_path / "voiced.mp4"
- _mux_continuous_narration(merged, opts.full_audio_path, voiced)
+ _mux_continuous_narration(
+ merged,
+ opts.full_audio_path,
+ voiced,
+ mix_video_sfx=keep_sfx,
+ sfx_volume=sfx_vol,
+ )
staged = voiced
else:
staged = merged
diff --git a/backend/app/services/llm_client.py b/backend/app/services/llm_client.py
index 25728ee..8af95e0 100644
--- a/backend/app/services/llm_client.py
+++ b/backend/app/services/llm_client.py
@@ -71,6 +71,7 @@ async def chat_completions(
temperature: float = 0.6,
max_tokens: int = DEFAULT_MAX_TOKENS,
timeout: float = 300.0,
+ response_format: dict[str, Any] | None = None,
) -> str:
settings = get_settings()
api_key = resolve_llm_api_key()
@@ -91,6 +92,8 @@ async def chat_completions(
extra = _llm_extra_body(model)
if extra:
payload.update(extra)
+ if response_format:
+ payload["response_format"] = response_format
logger.info(
"调用文字 LLM model=%s base=%s user_len=%s max_tokens=%s",
diff --git a/backend/app/services/oss.py b/backend/app/services/oss.py
index b4747e4..e33f27a 100644
--- a/backend/app/services/oss.py
+++ b/backend/app/services/oss.py
@@ -73,6 +73,13 @@ def ensure_browser_cors() -> None:
for extra in (
"https://kepu.printfilm.com",
"http://kepu.printfilm.com",
+ "https://www.printfilm.com",
+ "http://www.printfilm.com",
+ "https://printfilm.com",
+ "http://printfilm.com",
+ "https://admin.kepu.printfilm.com",
+ "https://admin.printfilm.com",
+ "http://admin.printfilm.com",
"http://localhost:5173",
"http://127.0.0.1:5173",
"http://localhost:4173",
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.py
index 4999eaf..203da38 100644
--- a/backend/app/services/pipeline.py
+++ b/backend/app/services/pipeline.py
@@ -23,6 +23,7 @@ from app.services.ffmpeg_compose import (
is_near_silent_audio,
probe_duration,
)
+from app.workers.queues import PIPELINE_QUEUE
from app.services.progress import publish_progress
from app.services import storage
from app.services.style_lock import (
@@ -120,7 +121,7 @@ def start_pipeline(project_id: int) -> str:
purge_pipeline_queue_for_project(project_id)
clear_pipeline_run_lock(project_id)
- async_result = run_pipeline_task.apply_async(args=[project_id], queue="pipeline")
+ async_result = run_pipeline_task.apply_async(args=[project_id], queue=PIPELINE_QUEUE)
task_id = str(async_result.id)
_celery_task_ids[project_id] = task_id
return task_id
@@ -187,10 +188,15 @@ def _is_image_text(project: Project) -> bool:
def _use_native_video_audio(project: Project | None = None) -> bool:
- """科普 full 管线:用 Seedance generate_audio,跳过 TTS 与重合成。"""
+ """是否跳过 TTS、直拼 Seedance 口播。科普已改回外部合成,恒为 False。"""
+ return False
+
+
+def _kepu_seedance_sfx_audio(project: Project | None = None) -> bool:
+ """科普 full:向 Seedance 要操作/环境音效(不含口播与 BGM)。"""
if project is not None and _is_image_text(project):
return False
- return bool(get_settings().kepu_seedance_generate_audio)
+ return bool(get_settings().kepu_seedance_sfx_audio)
def _project_output_ratio(project: Project) -> str:
@@ -213,13 +219,14 @@ def _project_voice(project: Project) -> str:
def clamp_shot_duration(duration: float, *, pipeline_mode: str, tpl_min: int, tpl_max: int) -> float:
+ """将单镜时长钳到模板区间;完整模式再压到科普节奏上限。"""
settings = get_settings()
if pipeline_mode == "image_text":
lo = IMAGE_TEXT_DURATION_MIN
hi = IMAGE_TEXT_DURATION_MAX
else:
- lo = max(1, tpl_min)
- hi = min(max(tpl_max, lo), settings.max_shot_duration)
+ hi = min(max(tpl_max, 1), settings.max_shot_duration, segplan.KEPU_FULL_SHOT_DURATION_MAX)
+ lo = max(1, min(tpl_min, hi))
return float(max(lo, min(float(duration), hi)))
@@ -341,7 +348,7 @@ async def _resume_plan(project_id: int) -> tuple[bool, bool, bool, bool]:
return False
return not is_near_silent_audio(path)
- # 模型配音模式不依赖 TTS;静图成片仍要整片配音
+ # 科普改回外部 TTS,成片前必须有旁白音轨
has_audio = (
True
if native_audio
@@ -421,9 +428,7 @@ async def run_pipeline(project_id: int) -> None:
"沿用已有分镜图与配音,开始合成"
if image_text
else (
- "沿用已有分镜图,继续生成带配音的 AI 视频"
- if _use_native_video_audio(project)
- else "沿用已有分镜图与配音,继续生成 AI 视频"
+ "沿用已有分镜图与配音,继续生成 AI 视频"
)
),
},
@@ -558,7 +563,11 @@ async def _script_stage(project_id: int) -> None:
d_min, d_max = IMAGE_TEXT_DURATION_MIN, IMAGE_TEXT_DURATION_MAX
else:
d_min = tpl.shot_duration_min
- d_max = min(tpl.shot_duration_max, get_settings().max_shot_duration)
+ d_max = min(
+ tpl.shot_duration_max,
+ get_settings().max_shot_duration,
+ segplan.KEPU_FULL_SHOT_DURATION_MAX,
+ )
style = _effective_style(project)
extra = _effective_extra(project)
@@ -571,9 +580,10 @@ async def _script_stage(project_id: int) -> None:
llm_system_addon=tpl.llm_system_addon,
duration_min=d_min,
duration_max=d_max,
- max_shot_duration=d_max if image_text else get_settings().max_shot_duration,
+ max_shot_duration=d_max,
pipeline_mode=mode,
- character_hint=char_hint if consist == "character" else "",
+ # 用户角色限制在 diverse/style 下也必须进分镜,否则出镜人物会被模板默认成「过肩无脸」
+ character_hint=char_hint,
extra_requirements=extra,
consistency_mode=consist,
output_ratio=_project_output_ratio(project),
@@ -581,6 +591,9 @@ async def _script_stage(project_id: int) -> None:
plans = plans_result.shots
if consist == "character":
project.character_bible = _effective_character_bible(project, plans_result.character_bible)
+ elif char_hint:
+ # 多样人物:保留用户角色限制,不锁成同一张脸
+ project.character_bible = char_hint
else:
project.character_bible = "无固定人物,各镜独立场景"
tpl_bgm = ""
@@ -735,7 +748,7 @@ def _db_write_lock() -> asyncio.Lock:
async def _parallel_image_and_audio(project_id: int) -> None:
- """Generate storyboard images; TTS only for image_text (full 用视频模型配音)。"""
+ """Generate storyboard images and continuous TTS (full 再并行图生视频)。"""
await _set_status(project_id, ProjectStatus.IMAGING, 18, "PARALLEL_ASSETS")
cfg = get_settings()
ark = get_ark()
@@ -787,7 +800,7 @@ async def _parallel_image_and_audio(project_id: int) -> None:
img_sem = asyncio.Semaphore(max(1, cfg.pipeline_image_concurrency))
done_img = 0
progress_lock = asyncio.Lock()
- # 模型配音:跳过整片 TTS;静图成片仍合成连贯旁白
+ # 静图成片与完整模式都合成连贯旁白;已有音轨则跳过
need_audio = (not native_audio) and (not _continuous_audio_ok(project_id))
async def bump_images() -> None:
@@ -982,9 +995,7 @@ async def _parallel_image_and_audio(project_id: int) -> None:
"stage": "ASSETS_READY",
"percent": 70 if image_text else 50,
"message": (
- "分镜图已完成,准备视频模型配音"
- if native_audio
- else "分镜图与整片配音已完成"
+ "分镜图与整片配音已完成"
),
},
)
@@ -1004,8 +1015,9 @@ async def _parallel_videos(project_id: int) -> None:
)
project = result.scalar_one()
tpl = project.template
- # 科普 full:以 KEPU_SEEDANCE_GENERATE_AUDIO 为准(忽略库内旧模板 False)
- generate_audio = _use_native_video_audio(project)
+ # 科普 full:Seedance 出操作音效,口播改后期 TTS
+ generate_audio = _kepu_seedance_sfx_audio(project)
+ ambient_only = generate_audio
consistency = template_consistency_mode(tpl) == "character" and bool(
tpl.seedance_config.get("character_consistency", True)
)
@@ -1063,6 +1075,7 @@ async def _parallel_videos(project_id: int) -> None:
style_prefix=style_prefix,
motion_bias=motion,
camera=str(meta.get("camera") or ""),
+ ambient_only=ambient_only,
)
dur = segplan.resolve_api_duration(
script,
@@ -1153,7 +1166,7 @@ async def _parallel_videos(project_id: int) -> None:
"total": total,
"percent": pct,
"message": (
- f"AI 视频+配音 {done}/{total}"
+ f"AI 视频(含操作音效){done}/{total}"
if generate_audio
else f"AI 视频 {done}/{total}"
),
@@ -1266,7 +1279,8 @@ async def _video_stage(project_id: int) -> None:
)
project = result.scalar_one()
tpl = project.template
- generate_audio = _use_native_video_audio(project)
+ generate_audio = _kepu_seedance_sfx_audio(project)
+ ambient_only = generate_audio
consistency = template_consistency_mode(tpl) == "character" and bool(
tpl.seedance_config.get("character_consistency", True)
)
@@ -1286,6 +1300,7 @@ async def _video_stage(project_id: int) -> None:
style_prefix=style_prefix,
motion_bias=motion,
camera=shot.camera or "",
+ ambient_only=ambient_only,
)
dur = segplan.resolve_api_duration(
script,
@@ -1449,7 +1464,9 @@ async def _compose_stage(project_id: int) -> None:
bgm_mood = (project.shots[0].bgm_mood or "").strip()
if not bgm_mood and project.template and isinstance(project.template.audio_config, dict):
bgm_mood = str(project.template.audio_config.get("bgm_mood") or "").strip()
- bgm_path = resolve_bgm_path(bgm_mood)
+ # 科普 full:不要后期 BGM;静图成片仍可叠配乐
+ bgm_path = None if mode != "image_text" else resolve_bgm_path(bgm_mood)
+ keep_video_sfx = _kepu_seedance_sfx_audio(project)
await asyncio.to_thread(
compose_project,
@@ -1466,6 +1483,8 @@ async def _compose_stage(project_id: int) -> None:
caption_scale=_f("caption_scale", 1.25),
bgm_path=bgm_path,
bgm_volume=0.22,
+ keep_video_sfx=keep_video_sfx,
+ sfx_volume=0.22,
),
)
project.final_video_url = storage.publish_local(out)
@@ -1537,7 +1556,7 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
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 ValueError("shot image required")
- generate_audio = _use_native_video_audio(project)
+ generate_audio = _kepu_seedance_sfx_audio(project)
motion = str(project.template.seedance_config.get("motion_bias", ""))
consistency = template_consistency_mode(project.template) == "character" and bool(
project.template.seedance_config.get("character_consistency", True)
@@ -1552,6 +1571,7 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
style_prefix=_effective_style(project),
motion_bias=motion,
camera=shot.camera or "",
+ ambient_only=generate_audio,
)
dur = segplan.resolve_api_duration(
script,
diff --git a/backend/app/services/profile.py b/backend/app/services/profile.py
new file mode 100644
index 0000000..1a341a8
--- /dev/null
+++ b/backend/app/services/profile.py
@@ -0,0 +1,54 @@
+"""Normalize and validate self-serve account profile fields."""
+
+from __future__ import annotations
+
+import re
+
+from pydantic import EmailStr, TypeAdapter, ValidationError
+
+_EMAIL = TypeAdapter(EmailStr)
+_PHONE_KEEP = re.compile(r"[^\d+]")
+
+
+class ProfileError(ValueError):
+ """用户可见的资料校验错误。"""
+
+
+def normalize_phone(raw: str | None) -> str:
+ """去掉空格/横线,+86 / 86 前缀收成 11 位国内号;空则表示未绑定。"""
+ if raw is None:
+ return ""
+ compact = _PHONE_KEEP.sub("", raw.strip())
+ if not compact:
+ return ""
+ if compact.startswith("+86"):
+ compact = compact[3:]
+ elif compact.startswith("86") and len(compact) >= 13:
+ compact = compact[2:]
+ return compact
+
+
+def prepare_profile_update(*, nickname: str, email: str, phone: str | None) -> dict[str, str]:
+ """校验并规范化用户名、邮箱、手机号(手机号只记录,不验证码)。"""
+ name = (nickname or "").strip()
+ if not name:
+ raise ProfileError("用户名不能为空")
+ if len(name) > 64:
+ raise ProfileError("用户名不能超过 64 个字符")
+
+ raw_email = (email or "").strip()
+ try:
+ parsed_email = str(_EMAIL.validate_python(raw_email)).lower()
+ except ValidationError as exc:
+ raise ProfileError("邮箱格式不正确") from exc
+
+ raw_phone = (phone or "").strip()
+ if raw_phone and re.search(r"[A-Za-z]", raw_phone):
+ raise ProfileError("手机号格式不正确")
+ normalized_phone = normalize_phone(raw_phone)
+ if normalized_phone and (
+ not normalized_phone.isdigit() or not (8 <= len(normalized_phone) <= 15)
+ ):
+ raise ProfileError("手机号格式不正确")
+
+ return {"nickname": name, "email": parsed_email, "phone": normalized_phone}
diff --git a/backend/app/services/queue_monitor.py b/backend/app/services/queue_monitor.py
new file mode 100644
index 0000000..f23e25b
--- /dev/null
+++ b/backend/app/services/queue_monitor.py
@@ -0,0 +1,337 @@
+"""Celery / Redis 队列监控:供管理后台可视化排队与执行状态。"""
+
+from __future__ import annotations
+
+import base64
+import json
+import logging
+from datetime import datetime, timezone
+from typing import Any
+
+import redis
+
+from app.config import get_settings
+from app.workers.queues import parse_worker_queues
+
+logger = logging.getLogger(__name__)
+
+# 各队列中文说明
+QUEUE_LABELS: dict[str, str] = {
+ "drama": "漫剧(LLM / 生图)",
+ "pipeline": "科普 / Studio 成片",
+ "video": "视频生成",
+ "oss": "OSS 异步上传",
+}
+
+# Celery 任务名 → 展示标签
+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.upload_media_task": "OSS 上传",
+ "drama.script_summary": "漫剧·剧本摘要",
+ "drama.episode_scripts": "漫剧·分集剧本",
+ "drama.episode_fragment_plan": "漫剧·分镜规划",
+ "drama.episode_generate": "漫剧·分集视频",
+ "drama.asset_image": "漫剧·资产生图",
+ "drama.asset_video": "漫剧·资产视频",
+}
+
+PENDING_SAMPLE_LIMIT = 30
+INSPECT_TIMEOUT_SEC = 1.0
+# oss 队列量大时只统计数量,不解析消息体
+OSS_SAMPLE_MAX_PENDING = 15
+CACHE_TTL_SEC = 4.0
+
+_cache_lock = __import__("threading").Lock()
+_cache: dict[str, tuple[float, dict[str, Any]]] = {}
+
+
+def _redis_client() -> redis.Redis:
+ return redis.Redis.from_url(
+ get_settings().redis_url,
+ decode_responses=True,
+ socket_connect_timeout=3,
+ socket_timeout=5,
+ )
+
+
+def task_label(task_name: str) -> str:
+ # 任务展示名;未知任务退回短名
+ name = (task_name or "").strip()
+ if not name:
+ return "未知任务"
+ if name in TASK_LABELS:
+ return TASK_LABELS[name]
+ if name.startswith("drama."):
+ return f"漫剧·{name.split('.')[-1]}"
+ short = name.rsplit(".", 1)[-1]
+ return short or name
+
+
+def queue_label(queue_name: str) -> str:
+ return QUEUE_LABELS.get(queue_name, queue_name)
+
+
+def _first_int_arg(args: Any) -> int | None:
+ if isinstance(args, int):
+ return args
+ if isinstance(args, (list, tuple)) and args:
+ try:
+ return int(args[0])
+ except (TypeError, ValueError):
+ return None
+ return None
+
+
+def parse_broker_message(raw: str, *, queue: str, position: int) -> dict[str, Any] | None:
+ # 从 Redis broker 消息解析任务摘要
+ try:
+ msg = json.loads(raw)
+ except json.JSONDecodeError:
+ return None
+
+ headers = msg.get("headers") or {}
+ props = msg.get("properties") or {}
+ delivery = props.get("delivery_info") or {}
+ task_id = str(headers.get("id") or "")
+ task_name = str(headers.get("task") or "")
+ args_repr = str(headers.get("argsrepr") or "")
+ routing_key = str(delivery.get("routing_key") or queue)
+
+ ref_id = None
+ body = msg.get("body")
+ if body:
+ try:
+ payload = json.loads(base64.b64decode(body).decode("utf-8"))
+ args = payload[0] if isinstance(payload, (list, tuple)) and payload else None
+ ref_id = _first_int_arg(args)
+ except Exception: # noqa: BLE001
+ ref_id = None
+
+ return {
+ "task_id": task_id,
+ "task_name": task_name,
+ "label": task_label(task_name),
+ "args_repr": args_repr,
+ "queue": routing_key or queue,
+ "state": "pending",
+ "worker": None,
+ "started_at": None,
+ "ref_id": ref_id,
+ "position": position,
+ }
+
+
+def _inspect_tasks(
+ payload: dict[str, list[dict[str, Any]]] | None,
+ *,
+ state: str,
+) -> list[dict[str, Any]]:
+ if not payload:
+ return []
+ rows: list[dict[str, Any]] = []
+ for worker_name, tasks in payload.items():
+ for task in tasks or []:
+ if not isinstance(task, dict):
+ continue
+ delivery = task.get("delivery_info") or {}
+ queue = str(delivery.get("routing_key") or "")
+ args = task.get("args")
+ rows.append(
+ {
+ "task_id": str(task.get("id") or ""),
+ "task_name": str(task.get("name") or ""),
+ "label": task_label(str(task.get("name") or "")),
+ "args_repr": str(task.get("args") or ""),
+ "queue": queue,
+ "state": state,
+ "worker": worker_name,
+ "started_at": task.get("time_start"),
+ "ref_id": _first_int_arg(args),
+ "position": None,
+ }
+ )
+ return rows
+
+
+def _celery_inspect_bundle() -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
+ # 单次 inspect 拉取 active / reserved / stats,避免三次 RPC
+ from app.workers.celery_app import celery_app
+
+ inspect = celery_app.control.inspect(timeout=INSPECT_TIMEOUT_SEC)
+ return (
+ inspect.active() or {},
+ inspect.reserved() or {},
+ inspect.stats() or {},
+ )
+
+
+def _pools_from_stats(stats_map: dict[str, Any]) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for worker_name, data in stats_map.items():
+ if not isinstance(data, dict):
+ continue
+ pool = data.get("pool") or {}
+ processes = pool.get("processes")
+ proc_count = len(processes) if isinstance(processes, list) else None
+ max_conc = pool.get("max-concurrency")
+ try:
+ max_conc_int = int(max_conc) if max_conc is not None else None
+ except (TypeError, ValueError):
+ max_conc_int = None
+ rows.append(
+ {
+ "name": worker_name,
+ "pool_implementation": str(pool.get("implementation") or ""),
+ "max_concurrency": max_conc_int,
+ "process_count": proc_count,
+ "writes": pool.get("writes"),
+ }
+ )
+ return rows
+
+
+def _get_cached(key: str) -> dict[str, Any] | None:
+ import time
+
+ with _cache_lock:
+ hit = _cache.get(key)
+ if not hit:
+ return None
+ ts, payload = hit
+ if time.time() - ts > CACHE_TTL_SEC:
+ _cache.pop(key, None)
+ return None
+ return payload
+
+
+def _set_cached(key: str, payload: dict[str, Any]) -> None:
+ import time
+
+ with _cache_lock:
+ _cache[key] = (time.time(), payload)
+
+
+def collect_queue_snapshot(
+ *,
+ include_inspect: bool = True,
+ pending_sample_limit: int = PENDING_SAMPLE_LIMIT,
+) -> dict[str, Any]:
+ # 汇总 Redis 排队 + Celery worker 执行态(同步;调用方应 asyncio.to_thread)
+ cache_key = f"detail={int(include_inspect)}"
+ cached = _get_cached(cache_key)
+ if cached is not None:
+ return cached
+ settings = get_settings()
+ monitor_queues = parse_worker_queues(
+ (settings.celery_worker_queues or settings.celery_autoscale_queue or "").strip() or None
+ )
+
+ redis_ok = False
+ unacked = 0
+ queue_rows: list[dict[str, Any]] = []
+ pending_tasks: list[dict[str, Any]] = []
+
+ try:
+ r = _redis_client()
+ redis_ok = bool(r.ping())
+ if redis_ok:
+ try:
+ unacked = int(r.hlen("unacked") or 0)
+ except Exception: # noqa: BLE001
+ unacked = 0
+
+ for qname in monitor_queues:
+ try:
+ pending = int(r.llen(qname) or 0)
+ except Exception: # noqa: BLE001
+ pending = 0
+
+ sample: list[dict[str, Any]] = []
+ parse_limit = pending_sample_limit
+ if qname == "oss" and pending > OSS_SAMPLE_MAX_PENDING:
+ parse_limit = 0
+ if pending > 0 and parse_limit > 0:
+ raw_items = r.lrange(qname, 0, max(0, parse_limit - 1)) or []
+ for idx, raw in enumerate(raw_items):
+ row = parse_broker_message(str(raw), queue=qname, position=idx + 1)
+ if row:
+ sample.append(row)
+ pending_tasks.append(row)
+
+ queue_rows.append(
+ {
+ "name": qname,
+ "label": queue_label(qname),
+ "pending": pending,
+ "sample": sample,
+ }
+ )
+ except Exception: # noqa: BLE001
+ logger.exception("queue monitor redis failed")
+ redis_ok = False
+
+ active_tasks: list[dict[str, Any]] = []
+ reserved_tasks: list[dict[str, Any]] = []
+ workers: list[dict[str, Any]] = []
+ workers_online = 0
+ stats_map: dict[str, Any] = {}
+ active_map: dict[str, Any] = {}
+
+ if include_inspect and settings.use_celery:
+ try:
+ active_map, reserved_map, stats_map = _celery_inspect_bundle()
+ active_tasks = _inspect_tasks(active_map, state="active")
+ reserved_tasks = _inspect_tasks(reserved_map, state="reserved")
+ workers_online = len(stats_map)
+
+ for worker_name, stats in stats_map.items():
+ if not isinstance(stats, dict):
+ continue
+ pool = stats.get("pool") or {}
+ total = stats.get("total") or {}
+ workers.append(
+ {
+ "name": worker_name,
+ "status": "online",
+ "active_count": len(active_map.get(worker_name) or []),
+ "processed": int(total.get("tasks.app.workers.tasks.run_pipeline_task", 0))
+ if isinstance(total, dict)
+ else None,
+ "pool": str(pool.get("implementation") or pool.get("max-concurrency") or ""),
+ }
+ )
+ except Exception: # noqa: BLE001
+ logger.exception("queue monitor celery inspect failed")
+
+ total_pending = sum(int(q["pending"]) for q in queue_rows)
+ payload = {
+ "ok": True,
+ "redis_ok": redis_ok,
+ "use_celery": settings.use_celery,
+ "worker_queues": settings.celery_worker_queues or settings.celery_autoscale_queue,
+ "unacked": unacked,
+ "total_pending": total_pending,
+ "active_count": len(active_tasks),
+ "reserved_count": len(reserved_tasks),
+ "workers_online": workers_online,
+ "queues": queue_rows,
+ "pending_tasks": pending_tasks,
+ "active_tasks": active_tasks,
+ "reserved_tasks": reserved_tasks,
+ "workers": workers,
+ "autoscale": {
+ "min": settings.celery_autoscale_min,
+ "max": settings.celery_autoscale_max,
+ "poll_sec": settings.celery_autoscale_poll_sec,
+ "idle_sec": settings.celery_autoscale_idle_sec,
+ },
+ "fetched_at": datetime.now(timezone.utc).isoformat(),
+ "inspect_included": include_inspect,
+ "_inspect_stats": stats_map,
+ "_inspect_active": active_map,
+ "_inspect_pools": _pools_from_stats(stats_map) if stats_map else [],
+ }
+ _set_cached(cache_key, payload)
+ return payload
diff --git a/backend/app/services/seedance_segments.py b/backend/app/services/seedance_segments.py
index a4d5ce1..d29ea18 100644
--- a/backend/app/services/seedance_segments.py
+++ b/backend/app/services/seedance_segments.py
@@ -14,9 +14,13 @@ SEGMENT_DURATION_MIN = 3
SEGMENT_DURATION_MAX = 12
SHOT_DURATION_MIN = 4
SHOT_DURATION_MAX = 30
+# 科普 AI 视频单镜上限:避免 16–20s 一镜到底导致拖沓
+KEPU_FULL_SHOT_DURATION_MAX = 12
DURATION_TOKEN_RE = re.compile(r"@duration:(\d+)")
-NARRATION_PREFIX = "【旁白·慢速清晰·同步字幕】"
+# 科普旁白:自然偏快;漫剧仍用慢速前缀(见 drama/build_fragments)
+NARRATION_PREFIX = "【旁白·自然语速·同步字幕】"
+LEGACY_NARRATION_PREFIX = "【旁白·慢速清晰·同步字幕】"
DIALOGUE_PREFIX = "【对白·慢速清晰·同步字幕】"
VISUAL_PREFIX = "【画面·无配音仅环境音】"
EMPTY_SHOT_PREFIX = "【空镜·可仅环境音与 BGM】"
@@ -191,6 +195,23 @@ class SegmentBeat:
text: str
+def suggested_kepu_shot_range(source_text: str, *, pipeline_mode: str = "full") -> tuple[int, int]:
+ """按文案字数给出科普分镜数量区间(完整模式偏多镜、短镜)。"""
+ # n 去掉空白后的字数,用于短/中/长文分档
+ n = len(re.sub(r"\s+", "", source_text or ""))
+ if pipeline_mode == "image_text":
+ if n < 180:
+ return 5, 8
+ if n < 400:
+ return 6, 10
+ return 8, 10
+ if n < 180:
+ return 6, 8
+ if n < 400:
+ return 7, 10
+ return 8, 10
+
+
def clamp_segment_duration(seconds: float | int) -> int:
return int(max(SEGMENT_DURATION_MIN, min(int(round(float(seconds))), SEGMENT_DURATION_MAX)))
@@ -202,12 +223,13 @@ def clamp_shot_total(
def estimate_narration_duration(text: str) -> int:
- """~3 Chinese chars per second for slow clear VO; clamp to segment range."""
+ """约 4.5–5 字/秒(科普自然偏快口播);钳到单段时长范围。"""
clean = re.sub(r"\s+", "", (text or "").strip())
clean = re.sub(r"^【[^】]*】", "", clean).strip()
if not clean:
return SEGMENT_DURATION_MIN
- secs = max(SEGMENT_DURATION_MIN, int((len(clean) + 2) // 3) + 1)
+ # (n + 4) // 5 ≈ 5 字/秒,略留半拍呼吸
+ secs = max(SEGMENT_DURATION_MIN, int((len(clean) + 4) // 5) + 1)
return clamp_segment_duration(secs)
@@ -239,8 +261,25 @@ def build_production_cues(bgm_mood: str) -> list[str]:
return [SUBTITLE_CUE, f"【BGM:{mood}】"]
-def build_seedance_production_section(segment_script: str) -> str:
- """组装 Seedance 音频/字幕/BGM 强制约束(科普旁白 / 漫剧画面+对白混排)。"""
+def build_seedance_production_section(
+ segment_script: str,
+ *,
+ ambient_only: bool = False,
+) -> str:
+ """组装 Seedance 音频/字幕/BGM 强制约束(科普旁白 / 漫剧画面+对白混排)。
+
+ ambient_only:科普后期 TTS 模式——模型只出操作环境音,禁止口播与 BGM。
+ """
+ if ambient_only:
+ lines = [
+ "1. 配音:本镜口播由后期外部 TTS 完成;视频内禁止任何旁白、对白、解说、哼唱、人声。",
+ "2. 字幕:禁止在画面内烧录字幕、标题、水印或口播文字。",
+ "3. 背景音乐:禁止任何 BGM、配乐、旋律、哼唱垫乐。",
+ "4. 音效:必须生成与画面同步的操作环境音(键盘敲击、鼠标点击、界面切换、轻微办公底噪);"
+ "音量克制,不要盖过人声(人声后期再叠)。",
+ ]
+ return f"{SEEDANCE_PRODUCTION_SECTION_HEADER}\n" + "\n".join(lines)
+
has_vo = script_has_narration_cue(segment_script)
has_dialogue = script_has_dialogue_cue(segment_script)
drama_mixed = script_is_drama_mixed(segment_script)
@@ -299,19 +338,20 @@ def build_seedance_production_section(segment_script: str) -> str:
)
return f"{SEEDANCE_PRODUCTION_SECTION_HEADER}\n" + "\n".join(lines)
- # 科普旁白模式:整镜以旁白段为主
+ # 科普旁白模式:整镜以旁白段为主(语速自然偏快,避免拖沓)
lines = [
- "1. 语速:旁白语速自然偏慢,吐字清晰,留有呼吸与停顿;严禁加速赶词、压缩台词或提高播放倍速。",
+ "1. 语速:旁白语速自然偏快、吐字清晰,节奏紧凑有呼吸感;"
+ "避免刻意放慢、拖腔或长时间停顿;不要压缩到含糊赶词,也不要提高播放倍速。",
"2. 字幕:全程烧录简体中文字幕,位置底部居中,字号清晰可读;旁白须逐句同步显示,字幕与口播一致。",
]
if has_vo:
lines.append(
- "3. 旁白:脚本含旁白段落时以第三人称旁白配音,沉稳清晰、语速偏慢;"
+ "3. 旁白:脚本含旁白段落时以第三人称旁白配音,沉稳清晰、语速自然偏快;"
"视频内不要自行添加嘈杂对白;旁白出现时字幕同步显示全文。"
)
else:
lines.append(
- "3. 旁白:若脚本含旁白标记,按第三人称旁白慢速清晰配音,并同步烧录字幕;"
+ "3. 旁白:若脚本含旁白标记,按第三人称旁白自然偏快清晰配音,并同步烧录字幕;"
"视频内不要自行添加嘈杂对白。"
)
lines.append(
@@ -410,6 +450,73 @@ def first_visual_prompt(content: str) -> str:
return ""
+def _is_narration_script_line(line: str) -> bool:
+ """判断脚本行是否为旁白口播(含新旧前缀);字幕 cue 里虽含「旁白」二字但不算。"""
+ stripped = (line or "").strip()
+ if not stripped or stripped.startswith("【字幕") or stripped.startswith("【BGM"):
+ return False
+ return stripped.startswith("【旁白") or NARRATION_PREFIX in stripped or LEGACY_NARRATION_PREFIX in stripped
+
+
+def replace_narration_in_script(content: str, narration: str) -> str:
+ """把编辑弹窗里的旁白写回脚本旁白段,配音与视频以脚本为准。"""
+ text = (narration or "").strip()
+ lines = (content or "").replace("\r\n", "\n").split("\n")
+ out: list[str] = []
+ replaced = False
+ for raw in lines:
+ stripped = raw.strip()
+ if text and _is_narration_script_line(stripped) and not replaced:
+ prefix_m = re.match(r"^(【[^】]*】)\s*", stripped)
+ prefix = prefix_m.group(1) if prefix_m else NARRATION_PREFIX
+ out.append(f"{prefix}{text}")
+ replaced = True
+ continue
+ out.append(raw.rstrip())
+ if text and not replaced:
+ dur = estimate_narration_duration(text)
+ out.append(f"@duration:{dur}")
+ out.append(f"{NARRATION_PREFIX}{text}")
+ return "\n".join(out).strip()
+
+
+def replace_first_visual_in_script(content: str, visual: str) -> str:
+ """把编辑弹窗里的首帧画面写回脚本第一段 visual。"""
+ text = (visual or "").strip()
+ if not text:
+ return (content or "").strip()
+ lines = (content or "").replace("\r\n", "\n").split("\n")
+ out: list[str] = []
+ replaced = False
+ # cue_end 字幕/BGM 行之后的插入点
+ cue_end = 0
+ for i, raw in enumerate(lines):
+ stripped = raw.strip()
+ if stripped.startswith("【字幕") or stripped.startswith("【BGM") or not stripped:
+ cue_end = i + 1
+ continue
+ break
+ for i, raw in enumerate(lines):
+ stripped = raw.strip()
+ if (
+ not replaced
+ and stripped
+ and not stripped.startswith("@duration:")
+ and not stripped.startswith("【字幕")
+ and not stripped.startswith("【BGM")
+ and not _is_narration_script_line(stripped)
+ ):
+ out.append(text)
+ replaced = True
+ continue
+ out.append(raw.rstrip())
+ if not replaced:
+ insert_at = min(cue_end, len(out))
+ extra = [f"@duration:{SEGMENT_DURATION_MIN}", text]
+ out = out[:insert_at] + extra + out[insert_at:]
+ return "\n".join(out).strip()
+
+
def build_segment_script(
beats: list[SegmentBeat],
*,
@@ -455,10 +562,13 @@ def parse_beats_from_llm_shot(item: dict[str, Any], narration_fallback: str = ""
continue
raw_dur = seg.get("duration")
if kind in {"narration", "vo", "旁白"}:
- dur = int(raw_dur) if raw_dur else estimate_narration_duration(text)
+ # est 按字数估时;LLM 值钳在 [est, est+1],禁止把短句撑满镜长
+ est = estimate_narration_duration(text)
if raw_dur:
- # 旁白时长再按字数下限钳制,避免 LLM 给过短 duration
- dur = max(dur, estimate_narration_duration(text))
+ given = int(raw_dur)
+ dur = max(est, min(given, est + 1))
+ else:
+ dur = est
else:
dur = int(raw_dur) if raw_dur else estimate_visual_duration(text)
beats.append(
@@ -485,12 +595,35 @@ def parse_beats_from_llm_shot(item: dict[str, Any], narration_fallback: str = ""
return beats
+def seedance_timeline_without_voice(segment_script: str) -> str:
+ """时间轴保留画面;旁白/字幕/BGM 行改成无口播的操作环境音,避免模型念稿。"""
+ last_visual = "工位操作,手部点击界面,保持主体稳定"
+ out: list[str] = []
+ for raw in (segment_script or "").replace("\r\n", "\n").split("\n"):
+ stripped = raw.strip()
+ if stripped.startswith("【字幕") or stripped.startswith("【BGM"):
+ continue
+ if _is_narration_script_line(stripped):
+ out.append(
+ f"【画面·无配音仅环境音】{last_visual};"
+ "持续键盘、点击、界面操作音效,禁止人声禁止配乐禁止字幕"
+ )
+ continue
+ if stripped and not stripped.startswith("@"):
+ visual = re.sub(r"^【[^】]*】", "", stripped).strip()
+ if visual:
+ last_visual = visual
+ out.append(raw.rstrip())
+ return "\n".join(out).strip()
+
+
def build_seedance_prompt(
segment_script: str,
*,
style_prefix: str = "",
motion_bias: str = "",
camera: str = "",
+ ambient_only: bool = False,
) -> str:
"""Assemble final Seedance text: style lock + production constraints + timed body."""
parts: list[str] = []
@@ -500,7 +633,9 @@ def build_seedance_prompt(
"【强制约束:视频画面风格】全片画面必须严格遵循以下风格描述,"
f"严禁偏离或混用其他画风:{style}"
)
- parts.append(build_seedance_production_section(segment_script))
+ parts.append(
+ build_seedance_production_section(segment_script, ambient_only=ambient_only)
+ )
parts.append(
"【强制约束:节奏与画面】严格按时间轴段落演绎画面;"
"保持主体外形与首帧一致,动作自然。"
@@ -508,7 +643,12 @@ def build_seedance_prompt(
if motion_bias or camera:
bits = [b for b in (motion_bias.strip(), camera.strip()) if b]
parts.append("【运镜】" + ";".join(bits))
- body = replace_duration_with_time_ranges(segment_script or "")
+ body_src = (
+ seedance_timeline_without_voice(segment_script)
+ if ambient_only
+ else (segment_script or "")
+ )
+ body = replace_duration_with_time_ranges(body_src)
parts.append(body.strip())
return "\n".join(p for p in parts if p).strip()
diff --git a/backend/app/services/storage.py b/backend/app/services/storage.py
index c080df1..150d171 100644
--- a/backend/app/services/storage.py
+++ b/backend/app/services/storage.py
@@ -29,6 +29,12 @@ def project_dir(project_id: int) -> Path:
return path
+def user_dir(user_id: int) -> Path:
+ path = GENERATED_ROOT / "users" / f"u{user_id}"
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+
def to_public_url(rel_or_abs: str) -> str:
"""Convert /static/... path to absolute URL for frontend."""
if rel_or_abs.startswith("http://") or rel_or_abs.startswith("https://"):
diff --git a/backend/app/services/templates_seed.py b/backend/app/services/templates_seed.py
index f8439a9..7e8a2e4 100644
--- a/backend/app/services/templates_seed.py
+++ b/backend/app/services/templates_seed.py
@@ -35,7 +35,7 @@ TEMPLATES: list[dict] = [
),
"default_ratio": "9:16",
"shot_duration_min": 5,
- "shot_duration_max": 16,
+ "shot_duration_max": 12,
"llm_system_addon": (
"这是开源/产品展示片。先【分析】用户文案:项目类型、核心能力、典型用户与使用路径,"
"再规划分镜与视觉,不要套固定蓝光大屏。"
@@ -96,12 +96,12 @@ TEMPLATES: list[dict] = [
),
"default_ratio": "16:9",
"shot_duration_min": 6,
- "shot_duration_max": 20,
+ "shot_duration_max": 12,
"llm_system_addon": (
- "这是开源「真人工作场景」片。先分析项目能力与使用路径,再拆 4-6 镜。"
+ "这是开源「真人工作场景」片。先分析项目能力与使用路径,再按内容拆多镜短镜。"
"【硬性】每镜必须出现真人在工位操作系统(侧脸/过肩/手部焦点,少正脸特写)。"
"【逐段】每镜必须输出 segments 数组:交替 visual(景别+动作+界面类型)与 narration(口播);"
- "单段 duration 3-12 秒,镜内合计不超过 20 秒;旁白按约 3 字/秒估时长。"
+ "单段 duration 3-12 秒,镜内合计不超过 12 秒;旁白按约 5 字/秒估时长,禁止拖腔注水。"
"【节拍】痛点工位→接入配置→核心工作台→流程结果→协作/部署;构图与操作动作禁止雷同。"
"title=模块短名,subtitle=卖点句,bgm 全片统一为轻快专业。"
),
@@ -149,7 +149,7 @@ TEMPLATES: list[dict] = [
"negative_prompt": "卡通,动漫,赛璐璐,二次元,棚拍浓妆,CGI假人,霓虹赛博,画面文字水印",
"default_ratio": "9:16",
"shot_duration_min": 5,
- "shot_duration_max": 18,
+ "shot_duration_max": 12,
"llm_system_addon": (
"真人街访/口播节奏。每镜输出 segments:建立环境 visual → narration 口播 → 反应/细节 visual。"
"人物外形全片一致;少正脸极端特写。title 短、subtitle 观点句。"
@@ -185,7 +185,7 @@ TEMPLATES: list[dict] = [
"negative_prompt": "卡通,动漫,赛璐璐,二次元,空桌无手,霓虹赛博,画面乱码文字水印",
"default_ratio": "16:9",
"shot_duration_min": 5,
- "shot_duration_max": 18,
+ "shot_duration_max": 12,
"llm_system_addon": (
"桌面演示片。每镜 segments 必须含手部操作 visual + narration;"
"景别在全桌建立、手部特写、屏幕内容之间切换,禁止各镜雷同。"
diff --git a/backend/app/services/worker_manager.py b/backend/app/services/worker_manager.py
new file mode 100644
index 0000000..508026d
--- /dev/null
+++ b/backend/app/services/worker_manager.py
@@ -0,0 +1,349 @@
+"""Admin Worker 动态管理:pool 扩缩、systemd 重启、autoscale 配置。"""
+
+from __future__ import annotations
+
+import logging
+import os
+import signal
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any
+
+import redis
+
+from app.config import get_settings
+
+logger = logging.getLogger(__name__)
+
+AUTOSCALE_MIN_KEY = "ai_movie:autoscale:min"
+AUTOSCALE_MAX_KEY = "ai_movie:autoscale:max"
+AUTOSCALE_ENABLED_KEY = "ai_movie:autoscale:enabled"
+
+SYSTEMD_WORKER_UNIT = "ai-movie-worker.service"
+BACKEND_ROOT = Path(__file__).resolve().parents[2]
+AUTOSCALE_STATE_DIR = BACKEND_ROOT / ".celery_autoscale"
+AUTOSCALE_LOCK = AUTOSCALE_STATE_DIR / "autoscale.pid"
+
+
+def _redis_client() -> redis.Redis:
+ return redis.Redis.from_url(
+ get_settings().redis_url,
+ decode_responses=True,
+ socket_connect_timeout=3,
+ socket_timeout=5,
+ )
+
+
+def _pid_alive(pid: int) -> bool:
+ if pid <= 0:
+ return False
+ if os.name == "nt":
+ try:
+ import ctypes
+
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
+ handle = kernel32.OpenProcess(0x1000, False, pid)
+ if handle:
+ kernel32.CloseHandle(handle)
+ return True
+ return False
+ except Exception: # noqa: BLE001
+ return False
+ try:
+ os.kill(pid, 0)
+ return True
+ except OSError:
+ return False
+
+
+def _systemctl(*args: str) -> tuple[bool, str]:
+ # 调用 systemctl;非 Linux 或无 systemd 时返回失败
+ if os.name == "nt" or not _which("systemctl"):
+ return False, "systemctl 不可用"
+ try:
+ proc = subprocess.run(
+ ["systemctl", *args],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ )
+ out = (proc.stdout or proc.stderr or "").strip()
+ return proc.returncode == 0, out
+ except Exception as exc: # noqa: BLE001
+ return False, str(exc)
+
+
+def _which(cmd: str) -> str | None:
+ from shutil import which
+
+ return which(cmd)
+
+
+def read_autoscale_bounds() -> tuple[int, int, str]:
+ # 读取 autoscale min/max(Redis 覆盖 env)
+ settings = get_settings()
+ env_min = max(0, int(settings.celery_autoscale_min))
+ env_max = max(env_min, int(settings.celery_autoscale_max))
+ source = "env"
+ try:
+ r = _redis_client()
+ raw_min = r.get(AUTOSCALE_MIN_KEY)
+ raw_max = r.get(AUTOSCALE_MAX_KEY)
+ if raw_min is not None:
+ env_min = max(0, int(raw_min))
+ source = "redis"
+ if raw_max is not None:
+ env_max = max(env_min, int(raw_max))
+ source = "redis"
+ except Exception: # noqa: BLE001
+ logger.exception("read autoscale bounds failed")
+ return env_min, max(env_min, env_max), source
+
+
+def is_autoscale_enabled() -> bool:
+ try:
+ r = _redis_client()
+ raw = r.get(AUTOSCALE_ENABLED_KEY)
+ if raw is None:
+ return False
+ return str(raw).strip().lower() in {"1", "true", "yes", "on"}
+ except Exception: # noqa: BLE001
+ return False
+
+
+def autoscale_process_status() -> tuple[bool, int | None, int]:
+ # 返回 (running, pid, subprocess_worker_count)
+ pid: int | None = None
+ running = False
+ worker_count = 0
+ if AUTOSCALE_LOCK.is_file():
+ try:
+ pid = int(AUTOSCALE_LOCK.read_text(encoding="utf-8").strip())
+ running = _pid_alive(pid)
+ except Exception: # noqa: BLE001
+ pid = None
+ if AUTOSCALE_STATE_DIR.is_dir():
+ worker_count = len(list(AUTOSCALE_STATE_DIR.glob("worker-*.pid")))
+ return running, pid, worker_count
+
+
+def _inspect_worker_pools() -> list[dict[str, Any]]:
+ settings = get_settings()
+ if not settings.use_celery:
+ return []
+ try:
+ from app.workers.celery_app import celery_app
+
+ stats = celery_app.control.inspect(timeout=2.0).stats() or {}
+ except Exception: # noqa: BLE001
+ logger.exception("inspect worker stats failed")
+ return []
+
+ rows: list[dict[str, Any]] = []
+ for worker_name, data in stats.items():
+ if not isinstance(data, dict):
+ continue
+ pool = data.get("pool") or {}
+ processes = pool.get("processes")
+ proc_count = len(processes) if isinstance(processes, list) else None
+ max_conc = pool.get("max-concurrency")
+ try:
+ max_conc_int = int(max_conc) if max_conc is not None else None
+ except (TypeError, ValueError):
+ max_conc_int = None
+ rows.append(
+ {
+ "name": worker_name,
+ "pool_implementation": str(pool.get("implementation") or ""),
+ "max_concurrency": max_conc_int,
+ "process_count": proc_count,
+ "writes": pool.get("writes"),
+ }
+ )
+ return rows
+
+
+def get_worker_control_status(
+ *,
+ pools: list[dict[str, Any]] | None = None,
+ skip_inspect: bool = False,
+) -> dict[str, Any]:
+ # 汇总 Worker 管理模式与可操作性;pools 可由 queue_monitor 传入避免重复 inspect
+ settings = get_settings()
+ bounds_min, bounds_max, bounds_source = read_autoscale_bounds()
+ autoscale_running, autoscale_pid, autoscale_workers = autoscale_process_status()
+ autoscale_enabled = is_autoscale_enabled()
+ if pools is None and not skip_inspect:
+ pools = _inspect_worker_pools()
+ pool_rows = pools or []
+
+ systemd_active: bool | None = None
+ mode = "celery"
+ if _which("systemctl"):
+ ok, _ = _systemctl("is-active", "--quiet", SYSTEMD_WORKER_UNIT)
+ systemd_active = ok
+ if ok and not autoscale_running:
+ mode = "systemd"
+
+ if autoscale_running:
+ mode = "autoscale"
+
+ total_processes = sum(int(p.get("process_count") or 0) for p in pool_rows)
+ max_concurrency = max(
+ (int(p["max_concurrency"]) for p in pool_rows if p.get("max_concurrency") is not None),
+ default=None,
+ )
+
+ pool_impl = pool_rows[0]["pool_implementation"] if pool_rows else ""
+ can_pool_grow = bool(
+ pool_rows
+ and settings.use_celery
+ and pool_impl
+ and "solo" not in pool_impl.lower()
+ and (max_concurrency is None or total_processes < int(settings.celery_pool_max))
+ )
+ can_pool_shrink = bool(
+ pool_rows
+ and settings.use_celery
+ and pool_impl
+ and "solo" not in pool_impl.lower()
+ and total_processes > 1
+ )
+
+ return {
+ "mode": mode,
+ "systemd_unit": SYSTEMD_WORKER_UNIT,
+ "systemd_active": systemd_active,
+ "pools": pool_rows,
+ "total_processes": total_processes,
+ "max_concurrency": max_concurrency,
+ "pool_max_limit": int(settings.celery_pool_max),
+ "can_pool_grow": can_pool_grow,
+ "can_pool_shrink": can_pool_shrink,
+ "can_restart": bool(_which("systemctl")),
+ "autoscale_running": autoscale_running,
+ "autoscale_enabled": autoscale_enabled,
+ "autoscale_pid": autoscale_pid,
+ "autoscale_workers": autoscale_workers,
+ "bounds_min": bounds_min,
+ "bounds_max": bounds_max,
+ "bounds_source": bounds_source,
+ }
+
+
+def pool_grow(*, n: int = 1) -> dict[str, Any]:
+ # Celery pool 扩容
+ settings = get_settings()
+ if not settings.use_celery:
+ raise RuntimeError("Celery 未启用")
+ n = max(1, min(int(n), 4))
+ status = get_worker_control_status()
+ if not status["can_pool_grow"]:
+ raise RuntimeError("当前 Worker 池不支持动态扩容(solo 池或已达上限)")
+ total = int(status["total_processes"])
+ if total + n > int(settings.celery_pool_max):
+ raise RuntimeError(f"超过 pool 上限 {settings.celery_pool_max}")
+
+ from app.workers.celery_app import celery_app
+
+ celery_app.control.pool_grow(n=n)
+ logger.info("admin pool_grow n=%s", n)
+ return {"ok": True, "action": "pool_grow", "n": n}
+
+
+def pool_shrink(*, n: int = 1) -> dict[str, Any]:
+ # Celery pool 缩容
+ settings = get_settings()
+ if not settings.use_celery:
+ raise RuntimeError("Celery 未启用")
+ n = max(1, min(int(n), 4))
+ status = get_worker_control_status()
+ if not status["can_pool_shrink"]:
+ raise RuntimeError("当前 Worker 池不支持缩容或仅剩 1 进程")
+ from app.workers.celery_app import celery_app
+
+ celery_app.control.pool_shrink(n=n)
+ logger.info("admin pool_shrink n=%s", n)
+ return {"ok": True, "action": "pool_shrink", "n": n}
+
+
+def restart_systemd_worker() -> dict[str, Any]:
+ # systemd 重启 Celery worker
+ ok, msg = _systemctl("restart", SYSTEMD_WORKER_UNIT)
+ if not ok:
+ raise RuntimeError(msg or "重启 worker 失败")
+ logger.info("admin restart %s", SYSTEMD_WORKER_UNIT)
+ return {"ok": True, "action": "restart", "unit": SYSTEMD_WORKER_UNIT, "message": msg}
+
+
+def update_autoscale_config(
+ *,
+ min_workers: int | None = None,
+ max_workers: int | None = None,
+ enabled: bool | None = None,
+) -> dict[str, Any]:
+ # 写入 Redis autoscale 配置
+ r = _redis_client()
+ if min_workers is not None:
+ r.set(AUTOSCALE_MIN_KEY, str(max(0, int(min_workers))))
+ if max_workers is not None:
+ r.set(AUTOSCALE_MAX_KEY, str(max(1, int(max_workers))))
+ if enabled is not None:
+ r.set(AUTOSCALE_ENABLED_KEY, "1" if enabled else "0")
+ bounds_min, bounds_max, bounds_source = read_autoscale_bounds()
+ if bounds_max < bounds_min:
+ bounds_max = bounds_min
+ r.set(AUTOSCALE_MAX_KEY, str(bounds_max))
+ return {
+ "ok": True,
+ "bounds_min": bounds_min,
+ "bounds_max": bounds_max,
+ "bounds_source": bounds_source,
+ "autoscale_enabled": is_autoscale_enabled(),
+ }
+
+
+def start_autoscale_daemon() -> dict[str, Any]:
+ # 启动 autoscale 守护进程
+ running, pid, _ = autoscale_process_status()
+ if running and pid:
+ return {"ok": True, "already_running": True, "pid": pid}
+
+ update_autoscale_config(enabled=True)
+ py = sys.executable
+ AUTOSCALE_STATE_DIR.mkdir(parents=True, exist_ok=True)
+ log_path = AUTOSCALE_STATE_DIR / "autoscale-stdout.log"
+ log_f = open(log_path, "a", encoding="utf-8", errors="replace") # noqa: SIM115
+ creationflags = 0
+ if os.name == "nt":
+ creationflags = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]
+ proc = subprocess.Popen(
+ [py, "-m", "app.workers.autoscale"],
+ cwd=str(BACKEND_ROOT),
+ stdout=log_f,
+ stderr=subprocess.STDOUT,
+ creationflags=creationflags,
+ env={**os.environ, "PYTHONUNBUFFERED": "1"},
+ )
+ logger.info("admin start autoscale pid=%s", proc.pid)
+ return {"ok": True, "action": "autoscale_start", "pid": proc.pid}
+
+
+def stop_autoscale_daemon() -> dict[str, Any]:
+ # 停止 autoscale 守护进程
+ update_autoscale_config(enabled=False)
+ running, pid, _ = autoscale_process_status()
+ if not running or not pid:
+ return {"ok": True, "action": "autoscale_stop", "stopped": False}
+
+ try:
+ if os.name == "nt":
+ os.kill(pid, signal.CTRL_BREAK_EVENT) # type: ignore[attr-defined]
+ else:
+ os.kill(pid, signal.SIGTERM)
+ except Exception as exc: # noqa: BLE001
+ raise RuntimeError(f"停止 autoscale 失败: {exc}") from exc
+ logger.info("admin stop autoscale pid=%s", pid)
+ return {"ok": True, "action": "autoscale_stop", "stopped": True, "pid": pid}
diff --git a/backend/app/workers/autoscale.py b/backend/app/workers/autoscale.py
index ac8b5ba..7d43d89 100644
--- a/backend/app/workers/autoscale.py
+++ b/backend/app/workers/autoscale.py
@@ -25,6 +25,7 @@ import redis
from app.config import get_settings, reload_settings
from app.logging_setup import configure_logging
+from app.workers.queues import parse_worker_queues, worker_queues_csv
_settings = get_settings()
configure_logging(level="INFO", sql_echo=_settings.sql_echo)
@@ -34,7 +35,6 @@ logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
BACKEND_ROOT = Path(__file__).resolve().parents[2]
STATE_DIR = BACKEND_ROOT / ".celery_autoscale"
-QUEUE_NAME = "pipeline"
@dataclass
@@ -52,13 +52,20 @@ class CeleryAutoscaler:
self.max_workers = max(self.min_workers, int(self.settings.celery_autoscale_max))
self.poll_sec = max(2.0, float(self.settings.celery_autoscale_poll_sec))
self.scale_down_sec = max(5.0, float(self.settings.celery_autoscale_idle_sec))
- self.queue = (self.settings.celery_autoscale_queue or QUEUE_NAME).strip() or QUEUE_NAME
- # Always also consume OSS + 漫剧视频队列,避免被资产生图堵住
- queues = [q.strip() for q in self.queue.split(",") if q.strip()]
- for extra in ("oss", "video"):
- if extra not in queues:
- queues.append(extra)
- self.worker_queues = ",".join(queues)
+ raw_queues = (
+ (self.settings.celery_worker_queues or "").strip()
+ or (self.settings.celery_autoscale_queue or "").strip()
+ )
+ self.monitor_queues = parse_worker_queues(raw_queues or None)
+ self.worker_queues = worker_queues_csv(raw_queues or None)
+ try:
+ from app.services.worker_manager import read_autoscale_bounds
+
+ rmin, rmax, _ = read_autoscale_bounds()
+ self.min_workers = rmin
+ self.max_workers = rmax
+ except Exception: # noqa: BLE001
+ pass
self.host = socket.gethostname().split(".")[0]
self.workers: dict[int, WorkerProc] = {}
self._idle_since: float | None = None
@@ -85,10 +92,10 @@ class CeleryAutoscaler:
def queue_load(self) -> tuple[int, int, int]:
"""Return (pending, unacked, load)."""
- pending = int(self._redis.llen(self.queue) or 0)
- for extra_q in ("oss", "video"):
+ pending = 0
+ for queue_name in self.monitor_queues:
try:
- pending += int(self._redis.llen(extra_q) or 0)
+ pending += int(self._redis.llen(queue_name) or 0)
except Exception: # noqa: BLE001
pass
try:
@@ -228,8 +235,8 @@ class CeleryAutoscaler:
def run_forever(self) -> None:
logger.info(
- "start queue=%s min=%s max=%s poll=%.1fs idle_down=%.1fs redis=%s",
- self.queue,
+ "start queues=%s min=%s max=%s poll=%.1fs idle_down=%.1fs redis=%s",
+ self.worker_queues,
self.min_workers,
self.max_workers,
self.poll_sec,
@@ -266,6 +273,14 @@ class CeleryAutoscaler:
self.max_workers = max(self.min_workers, int(self.settings.celery_autoscale_max))
self.poll_sec = max(2.0, float(self.settings.celery_autoscale_poll_sec))
self.scale_down_sec = max(5.0, float(self.settings.celery_autoscale_idle_sec))
+ try:
+ from app.services.worker_manager import read_autoscale_bounds
+
+ rmin, rmax, _ = read_autoscale_bounds()
+ self.min_workers = rmin
+ self.max_workers = rmax
+ except Exception: # noqa: BLE001
+ pass
self.reconcile()
loops += 1
# Every ~2 min: redispatch projects with no progress
diff --git a/backend/app/workers/celery_app.py b/backend/app/workers/celery_app.py
index 5306176..57fc9f8 100644
--- a/backend/app/workers/celery_app.py
+++ b/backend/app/workers/celery_app.py
@@ -1,6 +1,12 @@
from celery import Celery
from app.config import reload_settings
+from app.workers.queues import (
+ DRAMA_QUEUE,
+ OSS_QUEUE,
+ PIPELINE_QUEUE,
+ VIDEO_QUEUE,
+)
settings = reload_settings()
@@ -30,14 +36,15 @@ celery_app.conf.update(
},
worker_cancel_long_running_tasks_on_connection_loss=True,
task_routes={
- "app.workers.tasks.run_pipeline_task": {"queue": "pipeline"},
- "app.workers.tasks.regen_image_task": {"queue": "pipeline"},
- "app.workers.tasks.regen_video_task": {"queue": "pipeline"},
- "app.workers.tasks.upload_media_task": {"queue": "oss"},
- "drama.script_summary": {"queue": "pipeline"},
- "drama.episode_scripts": {"queue": "pipeline"},
- # 分镜视频独立队列,避免被资产生图堵在 pipeline 后面
- "drama.episode_generate": {"queue": "video"},
- "drama.asset_image": {"queue": "pipeline"},
+ "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.upload_media_task": {"queue": OSS_QUEUE},
+ "drama.script_summary": {"queue": DRAMA_QUEUE},
+ "drama.episode_scripts": {"queue": DRAMA_QUEUE},
+ "drama.episode_fragment_plan": {"queue": DRAMA_QUEUE},
+ "drama.episode_generate": {"queue": VIDEO_QUEUE},
+ "drama.asset_image": {"queue": DRAMA_QUEUE},
+ "drama.asset_video": {"queue": VIDEO_QUEUE},
},
)
diff --git a/backend/app/workers/queue_dedupe.py b/backend/app/workers/queue_dedupe.py
index 8aaf1ea..9d39895 100644
--- a/backend/app/workers/queue_dedupe.py
+++ b/backend/app/workers/queue_dedupe.py
@@ -14,7 +14,7 @@ from app.config import get_settings
logger = logging.getLogger(__name__)
-PIPELINE_QUEUE = "pipeline"
+from app.workers.queues import PIPELINE_QUEUE
_ARGS_RE = re.compile(r"\[(\d+)\]|\((\d+),?\)")
diff --git a/backend/app/workers/queues.py b/backend/app/workers/queues.py
new file mode 100644
index 0000000..3c6d51f
--- /dev/null
+++ b/backend/app/workers/queues.py
@@ -0,0 +1,30 @@
+"""Celery 队列名:按任务类型拆分,避免漫剧 LLM 被科普成片 pipeline 堵住。"""
+
+from __future__ import annotations
+
+# pipeline:科普/Studio 多阶段成片(耗时长)
+PIPELINE_QUEUE = "pipeline"
+# drama:漫剧 LLM 与资产生图(用户交互敏感)
+DRAMA_QUEUE = "drama"
+# video:所有视频生成(Seedance 等)
+VIDEO_QUEUE = "video"
+# oss:异步 OSS 上传回填
+OSS_QUEUE = "oss"
+
+# Worker 应消费的全部队列(顺序:优先处理短任务)
+DEFAULT_WORKER_QUEUES = (DRAMA_QUEUE, OSS_QUEUE, VIDEO_QUEUE, PIPELINE_QUEUE)
+
+
+def parse_worker_queues(raw: str | None) -> tuple[str, ...]:
+ # 解析逗号分隔队列配置,过滤空项
+ if not raw or not str(raw).strip():
+ return DEFAULT_WORKER_QUEUES
+ parts = [q.strip() for q in str(raw).split(",") if q.strip()]
+ return tuple(parts) if parts else DEFAULT_WORKER_QUEUES
+
+
+def worker_queues_csv(raw: str | None = None) -> str:
+ # 返回 Celery -Q 参数字符串
+ if raw is None:
+ return ",".join(DEFAULT_WORKER_QUEUES)
+ return ",".join(parse_worker_queues(raw))
diff --git a/backend/tests/test_celery_queues.py b/backend/tests/test_celery_queues.py
new file mode 100644
index 0000000..7fdf9c0
--- /dev/null
+++ b/backend/tests/test_celery_queues.py
@@ -0,0 +1,28 @@
+"""Celery 队列配置单测。"""
+
+from app.workers.queues import (
+ DEFAULT_WORKER_QUEUES,
+ DRAMA_QUEUE,
+ parse_worker_queues,
+ worker_queues_csv,
+)
+
+
+def test_default_worker_queues_order():
+ # drama 优先,避免被 pipeline 堵住
+ assert DEFAULT_WORKER_QUEUES[0] == DRAMA_QUEUE
+ assert "pipeline" in DEFAULT_WORKER_QUEUES
+
+
+def test_parse_worker_queues():
+ assert parse_worker_queues("drama,oss,video,pipeline") == (
+ "drama",
+ "oss",
+ "video",
+ "pipeline",
+ )
+ assert parse_worker_queues("") == DEFAULT_WORKER_QUEUES
+
+
+def test_worker_queues_csv():
+ assert worker_queues_csv("drama,video") == "drama,video"
diff --git a/backend/tests/test_drama_llm_json.py b/backend/tests/test_drama_llm_json.py
new file mode 100644
index 0000000..a4c1c6b
--- /dev/null
+++ b/backend/tests/test_drama_llm_json.py
@@ -0,0 +1,36 @@
+"""drama LLM JSON 解析单测。"""
+
+import json
+
+import pytest
+
+from app.services.drama.llm import _extract_json
+
+
+def test_extract_json_plain_object():
+ data = _extract_json('{"oneLineStory": "测试"}')
+ assert data["oneLineStory"] == "测试"
+
+
+def test_extract_json_strips_fences():
+ raw = '```json\n{"episodeCount": 12}\n```'
+ data = _extract_json(raw)
+ assert data["episodeCount"] == 12
+
+
+def test_extract_json_repairs_trailing_comma():
+ raw = '{"characters": [{"name": "沈令仪",},], "synopsis": "test",}'
+ data = _extract_json(raw)
+ assert data["characters"][0]["name"] == "沈令仪"
+ assert data["synopsis"] == "test"
+
+
+def test_extract_json_repairs_smart_quotes():
+ raw = '{"oneLineStory": "将门孤女"}'
+ data = _extract_json(raw)
+ assert "将门孤女" in data["oneLineStory"]
+
+
+def test_extract_json_raises_on_invalid_payload():
+ with pytest.raises(json.JSONDecodeError):
+ _extract_json("not json at all")
diff --git a/backend/tests/test_ffmpeg_captions.py b/backend/tests/test_ffmpeg_captions.py
new file mode 100644
index 0000000..1847a0a
--- /dev/null
+++ b/backend/tests/test_ffmpeg_captions.py
@@ -0,0 +1,24 @@
+"""合成阶段 ffmpeg 字幕:口播须烧进画面,split 布局也不能省略。"""
+
+from app.services.ffmpeg_compose import build_video_caption_vf
+
+
+def test_split_layout_burns_narration_captions():
+ """开源展示 split 布局仍要把旁白烧成底部字幕,不能只叠标题。"""
+ vf = build_video_caption_vf(
+ narration="搭物联网最耗时的,往往不是业务本身。",
+ duration=12.0,
+ w=720,
+ h=1280,
+ font=None,
+ title="物模型",
+ subtitle="统一管理设备",
+ subtitle_layout="split",
+ )
+ assert "drawtext" in vf
+ assert "搭物联网最耗时的" in vf
+ assert "往往不是业务本身" in vf
+ assert "enable='between(t\\," in vf
+ assert ":y=70" in vf
+ assert ":y=1176" in vf
+ assert vf.count("drawtext=") >= 3
diff --git a/backend/tests/test_profile.py b/backend/tests/test_profile.py
new file mode 100644
index 0000000..950c100
--- /dev/null
+++ b/backend/tests/test_profile.py
@@ -0,0 +1,39 @@
+"""账号资料:昵称 / 邮箱 / 手机号规范化。"""
+
+from app.services.profile import normalize_phone, prepare_profile_update, ProfileError
+import pytest
+
+
+def test_normalize_phone_strips_and_drops_plus86():
+ assert normalize_phone(" 138 0013 8000 ") == "13800138000"
+ assert normalize_phone("+86-138-0013-8000") == "13800138000"
+ assert normalize_phone("8613800138000") == "13800138000"
+ assert normalize_phone("") == ""
+ assert normalize_phone(" ") == ""
+ assert normalize_phone(None) == ""
+
+
+def test_prepare_profile_update_accepts_record_only_phone():
+ out = prepare_profile_update(
+ nickname=" 阿强 ",
+ email=" [email protected] ",
+ phone="13800138000",
+ )
+ assert out["nickname"] == "阿强"
+ assert out["email"] == "[email protected]"
+ assert out["phone"] == "13800138000"
+
+
+def test_prepare_profile_update_allows_empty_phone():
+ out = prepare_profile_update(nickname="创作者", email="[email protected]", phone="")
+ assert out["phone"] == ""
+
+
+def test_prepare_profile_update_rejects_bad_phone():
+ with pytest.raises(ProfileError, match="手机号"):
+ prepare_profile_update(nickname="创作者", email="[email protected]", phone="abc")
+
+
+def test_prepare_profile_update_rejects_blank_nickname():
+ with pytest.raises(ProfileError, match="用户名"):
+ prepare_profile_update(nickname=" ", email="[email protected]", phone="")
diff --git a/backend/tests/test_queue_monitor.py b/backend/tests/test_queue_monitor.py
new file mode 100644
index 0000000..581a49b
--- /dev/null
+++ b/backend/tests/test_queue_monitor.py
@@ -0,0 +1,27 @@
+"""队列监控解析单测。"""
+
+import json
+
+from app.services.queue_monitor import parse_broker_message, task_label
+
+
+def test_task_label_known():
+ assert task_label("drama.script_summary") == "漫剧·剧本摘要"
+
+
+def test_parse_broker_message_minimal():
+ msg = {
+ "headers": {
+ "id": "abc-123",
+ "task": "drama.script_summary",
+ "argsrepr": "(9,)",
+ },
+ "properties": {"delivery_info": {"routing_key": "drama"}},
+ "body": __import__("base64").b64encode(json.dumps([[9], {}, {}]).encode()).decode(),
+ }
+ row = parse_broker_message(json.dumps(msg), queue="drama", position=1)
+ assert row is not None
+ assert row["task_id"] == "abc-123"
+ assert row["queue"] == "drama"
+ assert row["ref_id"] == 9
+ assert row["state"] == "pending"
diff --git a/backend/tests/test_seedance_segments.py b/backend/tests/test_seedance_segments.py
index 96fb4de..4b9e26e 100644
--- a/backend/tests/test_seedance_segments.py
+++ b/backend/tests/test_seedance_segments.py
@@ -8,10 +8,15 @@ from app.services.seedance_segments import (
build_segment_script,
build_seedance_production_section,
build_seedance_prompt,
+ estimate_narration_duration,
+ first_visual_prompt,
narration_from_script,
parse_beats_from_llm_shot,
replace_duration_with_time_ranges,
+ replace_first_visual_in_script,
+ replace_narration_in_script,
resolve_api_duration,
+ suggested_kepu_shot_range,
sum_duration,
)
@@ -28,7 +33,7 @@ def test_build_segment_script_and_time_ranges():
assert "【BGM:" in script
assert "@duration:4" in script
assert "@duration:8" in script
- assert "【旁白·慢速清晰·同步字幕】" in script
+ assert "【旁白·自然语速·同步字幕】" in script
assert sum_duration(script) == 12
timed = replace_duration_with_time_ranges(script)
assert "00:00-00:04" in timed
@@ -68,6 +73,7 @@ def test_build_seedance_production_section_detects_vo():
section = build_seedance_production_section(script)
assert section.startswith(SEEDANCE_PRODUCTION_SECTION_HEADER)
assert "第三人称旁白配音" in section
+ assert "自然偏快" in section
assert "轻快专业" in section
@@ -91,9 +97,34 @@ def test_parse_beats_clamps_short_narration_duration():
assert beats[1].duration <= 12
+def test_parse_beats_does_not_pad_short_narration_to_shot_max():
+ text = "质检痛点切入。"
+ est = estimate_narration_duration(text)
+ beats = parse_beats_from_llm_shot(
+ {
+ "segments": [
+ {"kind": "visual", "duration": 4, "text": "工位过肩打开质检看板"},
+ {"kind": "narration", "duration": 20, "text": text},
+ ]
+ }
+ )
+ assert beats[1].duration <= est + 1
+ assert beats[1].duration >= est
+ assert beats[1].duration < 12
+
+
+def test_suggested_kepu_shot_range_full_mode():
+ short = suggested_kepu_shot_range("工业AI平台简介", pipeline_mode="full")
+ medium = suggested_kepu_shot_range("字" * 250, pipeline_mode="full")
+ long = suggested_kepu_shot_range("字" * 500, pipeline_mode="full")
+ assert short == (6, 8)
+ assert medium == (7, 10)
+ assert long == (8, 10)
+
+
def test_apply_segment_script_edit_fills_cues():
out = apply_segment_script_edit(
- "@duration:6\n过肩演示产品\n@duration:6\n【旁白·慢速清晰·同步字幕】一句话介绍能力",
+ "@duration:6\n过肩演示产品\n@duration:6\n【旁白·自然语速·同步字幕】一句话介绍能力",
bgm_mood="冷静纪实",
)
assert out["duration"] == 12.0
@@ -102,6 +133,21 @@ def test_apply_segment_script_edit_fills_cues():
assert out["narration"]
+def test_replace_narration_and_visual_write_back_into_script():
+ script = (
+ "【字幕:全程简体中文字幕,旁白逐句同步烧录】\n"
+ "【BGM:轻快专业,音量低于人声】\n"
+ "@duration:4\n侧脸打开深色仪表盘\n"
+ f"@duration:8\n{NARRATION_PREFIX}旧旁白一句"
+ )
+ with_vo = replace_narration_in_script(script, "一句话给出方向和信心度。")
+ assert "旧旁白一句" not in with_vo
+ assert narration_from_script(with_vo) == "一句话给出方向和信心度。"
+ with_vis = replace_first_visual_in_script(with_vo, "过肩工位,大屏亮绿色看多信号")
+ assert first_visual_prompt(with_vis) == "过肩工位,大屏亮绿色看多信号"
+ assert "侧脸打开深色仪表盘" not in with_vis
+
+
def test_empty_shot_misclassified_as_dialogue_is_rewritten():
from app.services.seedance_segments import (
DRAMA_SUBTITLE_CUE,
@@ -152,3 +198,45 @@ def test_character_intro_cue_normalized_beside_character():
section = build_seedance_production_section(fixed)
assert "角色身旁" in section
assert "禁止居中大标题" in section
+
+
+def test_build_seedance_production_section_ambient_only():
+ script = build_segment_script(
+ [
+ SegmentBeat(duration=4, kind="visual", text="过肩工位打开工作台"),
+ SegmentBeat(duration=8, kind="narration", text="很多人找开源工具却卡在接入"),
+ ],
+ bgm_mood="轻快专业",
+ )
+ section = build_seedance_production_section(script, ambient_only=True)
+ assert section.startswith(SEEDANCE_PRODUCTION_SECTION_HEADER)
+ assert "后期外部 TTS" in section
+ assert "禁止任何旁白" in section
+ assert "禁止任何 BGM" in section
+ assert "操作环境音" in section
+ assert "第三人称旁白配音" not in section
+ assert "轻快专业" not in section
+
+
+def test_build_seedance_prompt_ambient_only_rewrites_narration():
+ from app.services.seedance_segments import seedance_timeline_without_voice
+
+ script = build_segment_script(
+ [
+ SegmentBeat(duration=5, kind="visual", text="手部点击配置"),
+ SegmentBeat(duration=6, kind="narration", text="一键接入即可开始监控"),
+ ],
+ bgm_mood="轻快专业",
+ )
+ body = seedance_timeline_without_voice(script)
+ assert "手部点击配置" in body
+ assert "一键接入即可开始监控" not in body
+ assert "【BGM" not in body
+ assert "【字幕" not in body
+ assert "无配音仅环境音" in body
+
+ prompt = build_seedance_prompt(script, ambient_only=True)
+ assert "禁止任何旁白" in prompt
+ assert "一键接入即可开始监控" not in prompt
+ assert "00:00-00:05" in prompt
+ assert NARRATION_PREFIX not in prompt
diff --git a/backend/tests/test_worker_manager.py b/backend/tests/test_worker_manager.py
new file mode 100644
index 0000000..0e2e401
--- /dev/null
+++ b/backend/tests/test_worker_manager.py
@@ -0,0 +1,20 @@
+"""Worker 管理配置单测。"""
+
+from app.services.worker_manager import read_autoscale_bounds
+
+
+def test_read_autoscale_bounds_defaults(monkeypatch):
+ monkeypatch.setattr(
+ "app.services.worker_manager.get_settings",
+ lambda: type("S", (), {"celery_autoscale_min": 1, "celery_autoscale_max": 3, "redis_url": "redis://127.0.0.1:9"})(),
+ )
+
+ class FakeRedis:
+ def get(self, _key):
+ return None
+
+ monkeypatch.setattr("app.services.worker_manager._redis_client", lambda: FakeRedis())
+ min_w, max_w, source = read_autoscale_bounds()
+ assert min_w == 1
+ assert max_w == 3
+ assert source == "env"
diff --git a/deploy/.env.prod.example b/deploy/.env.prod.example
index 20c4691..3538230 100644
--- a/deploy/.env.prod.example
+++ b/deploy/.env.prod.example
@@ -11,7 +11,7 @@ DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:change-me-strong-db-password@1
REDIS_URL=redis://127.0.0.1:16379/0
PUBLIC_BASE_URL=https://kepu.printfilm.com
-CORS_ORIGINS=https://kepu.printfilm.com
+CORS_ORIGINS=https://kepu.printfilm.com,https://admin.kepu.printfilm.com,https://www.printfilm.com,https://printfilm.com,https://admin.printfilm.com
ARK_MOCK=false
@@ -37,3 +37,4 @@ EPAY_RETURN_URL=https://kepu.printfilm.com/pricing?paid=1
CELERY_AUTOSCALE_MIN=1
CELERY_AUTOSCALE_MAX=3
+CELERY_WORKER_QUEUES=drama,oss,video,pipeline
diff --git a/deploy/README.md b/deploy/README.md
index 49ffc9d..c75e687 100644
--- a/deploy/README.md
+++ b/deploy/README.md
@@ -49,7 +49,7 @@ pip install -r requirements.txt
uvicorn app.main:app --host 0.0.0.0 --port 8000
# 另开终端 — 固定并发
-celery -A app.workers.celery_app.celery_app worker -Q pipeline,oss -l info --concurrency=2
+celery -A app.workers.celery_app.celery_app worker -Q drama,oss,video,pipeline -l info --concurrency=2
# 或 Windows 动态加减进程
python -m app.workers.autoscale
diff --git a/deploy/scripts/import_drama_sqlite_to_postgres.py b/deploy/scripts/import_drama_sqlite_to_postgres.py
index 3be1499..80ed9f2 100644
--- a/deploy/scripts/import_drama_sqlite_to_postgres.py
+++ b/deploy/scripts/import_drama_sqlite_to_postgres.py
@@ -1,14 +1,14 @@
#!/usr/bin/env python3
"""
-从 sqlite(本地开发的 backend/ai_movie.db)导入漫剧模块数据到线上 Postgres。
+从 sqlite(本地 backend/ai_movie.db)导入漫剧模块数据到 Postgres。
导入范围:drama_projects / drama_scripts / drama_assets / drama_episodes /
drama_episode_fragments / drama_fragment_asset_refs / drama_asset_episodes
+(含 project.content 里的 canvas_nodes / canvas_edges)。
-用户映射策略:
-- 依据源 sqlite 中 drama_projects.owner 对应 users.email
-- 在目标 Postgres 的 users 表里按 email 查找 user_id
-- 若目标不存在该 email:跳过该项目(不会创建用户,以避免密钥/密码缺失)
+用户映射:按 owner email 对齐目标 users.id;缺失用户默认跳过该项目。
+
+--replace:先清空目标库全部漫剧表,再按源表主键原样写入(画布 assetId 才能对上)。
"""
from __future__ import annotations
@@ -16,11 +16,12 @@ from __future__ import annotations
import argparse
import asyncio
import json
+import re
import sqlite3
from datetime import datetime
from typing import Any, Optional
-from sqlalchemy import select
+from sqlalchemy import select, text
from app.database import AsyncSessionLocal
from app.models import User
@@ -34,20 +35,32 @@ from app.models_drama import (
DramaScript,
)
+# 清空 / 重置序号时的表顺序(子表在前)
+DRAMA_TABLES = (
+ "drama_fragment_asset_refs",
+ "drama_asset_episodes",
+ "drama_episode_fragments",
+ "drama_assets",
+ "drama_scripts",
+ "drama_episodes",
+ "drama_projects",
+)
+
+_ASSET_MENTION = re.compile(r"@asset:(\d+)")
+_ASSET_NODE = re.compile(r"^asset-(\d+)$")
+
def _parse_dt(raw: Any) -> Optional[datetime]:
+ # 把 sqlite 时间字段转成 datetime
if raw is None:
return None
if isinstance(raw, datetime):
return raw
if isinstance(raw, (int, float)):
- # sqlite timestamp fallback
return datetime.fromtimestamp(raw)
- s = str(raw)
- s = s.strip()
+ s = str(raw).strip()
if not s:
return None
- # 默认匹配 sqlite 常见:YYYY-MM-DD HH:MM:SS
try:
return datetime.fromisoformat(s)
except ValueError:
@@ -59,6 +72,7 @@ def _parse_dt(raw: Any) -> Optional[datetime]:
def _jload(raw: Any) -> Any:
+ # sqlite JSON 文本 → dict/list
if raw is None:
return None
if isinstance(raw, (dict, list)):
@@ -74,22 +88,84 @@ def _jload(raw: Any) -> Any:
return None
+def _rewrite_json(
+ obj: Any,
+ asset_map: dict[int, int],
+ episode_map: dict[int, int],
+ project_map: dict[int, int],
+) -> Any:
+ """把嵌套 JSON 里的资产/分集/项目 id(含画布 assetId、@asset:n)改成目标库 id。"""
+ if isinstance(obj, list):
+ return [_rewrite_json(x, asset_map, episode_map, project_map) for x in obj]
+ if isinstance(obj, dict):
+ out: dict[str, Any] = {}
+ for key, val in obj.items():
+ if key in {"assetId", "asset_id"} and isinstance(val, int):
+ out[key] = asset_map.get(val, val)
+ elif key in {"episodeId", "episode_id"} and isinstance(val, int):
+ out[key] = episode_map.get(val, val)
+ elif key in {"projectId", "project_id"} and isinstance(val, int):
+ out[key] = project_map.get(val, val)
+ elif key in {"id", "canvas_node_id"} and isinstance(val, str):
+ matched = _ASSET_NODE.match(val)
+ if matched:
+ new_id = asset_map.get(int(matched.group(1)))
+ out[key] = f"asset-{new_id}" if new_id else val
+ else:
+ out[key] = _rewrite_json(val, asset_map, episode_map, project_map)
+ else:
+ out[key] = _rewrite_json(val, asset_map, episode_map, project_map)
+ return out
+ if isinstance(obj, str):
+
+ def _sub(match: re.Match[str]) -> str:
+ old = int(match.group(1))
+ return f"@asset:{asset_map.get(old, old)}"
+
+ return _ASSET_MENTION.sub(_sub, obj)
+ return obj
+
+
+async def _wipe_drama_tables(session: Any) -> None:
+ # 清空漫剧表;用量记录只断开关联,不删账本
+ await session.execute(
+ text("UPDATE usage_events SET drama_project_id = NULL WHERE drama_project_id IS NOT NULL")
+ )
+ await session.execute(
+ text(
+ "TRUNCATE TABLE "
+ + ", ".join(DRAMA_TABLES)
+ + " RESTART IDENTITY CASCADE"
+ )
+ )
+
+
+async def _reset_id_sequences(session: Any) -> None:
+ # 显式写入主键后,把 serial 拨到当前 MAX(id)
+ for table in DRAMA_TABLES:
+ await session.execute(
+ text(
+ f"SELECT setval(pg_get_serial_sequence('{table}', 'id'), "
+ f"COALESCE((SELECT MAX(id) FROM {table}), 1))"
+ )
+ )
+
+
async def import_one(
source_sqlite: str,
dry_run: bool,
project_ids: list[int] | None,
import_missing_users: bool,
+ replace: bool,
) -> None:
con = sqlite3.connect(source_sqlite)
con.row_factory = sqlite3.Row
cur = con.cursor()
- # 1) 取源 users email 映射
cur.execute("select id as user_id, email from users")
src_users = cur.fetchall()
user_email_by_id = {int(r["user_id"]): r["email"] for r in src_users if r["email"]}
- # 2) 取源 drama_projects
cur.execute(
"select id, user_id, title, description, content, params, created_at, updated_at "
"from drama_projects order by id"
@@ -103,7 +179,6 @@ async def import_one(
print("No drama_projects found in source sqlite.")
return
- # 3) 依据源项目 owner email 查目标 users
src_owner_emails = sorted({user_email_by_id.get(int(r["user_id"])) for r in src_projects})
src_owner_emails = [e for e in src_owner_emails if e]
@@ -121,7 +196,6 @@ async def import_one(
if missing_emails:
print(f"[users] missing in destination: {missing_emails}")
if import_missing_users and not dry_run:
- # 直接拷贝源 users(包含 hashed_password),确保后续项目归属可见
cur.execute(
"select id, email, nickname, hashed_password, quota_left, balance_fen, frozen_fen, plan, billing_unlimited, role, created_at "
"from users"
@@ -152,17 +226,22 @@ async def import_one(
else:
print("[users] import-missing-users disabled or dry-run; projects for these owners will be skipped.")
- # 映射表
project_id_map: dict[int, int] = {}
asset_id_map: dict[int, int] = {}
episode_id_map: dict[int, int] = {}
fragment_id_map: dict[int, int] = {}
+ preserve_ids = bool(replace)
- # 用事务包住插入,便于回滚
try:
- # 4) projects
+ if replace:
+ print("[replace] wipe all drama_* tables on destination")
+ if not dry_run:
+ await _wipe_drama_tables(session)
+ await session.flush()
+
inserted_projects = 0
skipped_projects = 0
+ pending_project_json: list[tuple[int, Any, Any]] = []
for r in src_projects:
old_pid = int(r["id"])
old_uid = int(r["user_id"])
@@ -174,33 +253,38 @@ async def import_one(
continue
if dry_run:
- project_id_map[old_pid] = -1
+ project_id_map[old_pid] = old_pid if preserve_ids else -1
inserted_projects += 1
continue
+ content = _jload(r["content"])
+ params = _jload(r["params"])
proj = DramaProject(
user_id=new_uid,
title=r["title"] or "未命名漫剧",
description=r["description"],
- content=_jload(r["content"]),
- params=_jload(r["params"]),
+ content=content,
+ params=params,
created_at=_parse_dt(r["created_at"]),
updated_at=_parse_dt(r["updated_at"]),
)
+ if preserve_ids:
+ proj.id = old_pid
session.add(proj)
await session.flush()
project_id_map[old_pid] = int(proj.id)
+ pending_project_json.append((int(proj.id), content, params))
inserted_projects += 1
print(f"[projects] inserted={inserted_projects} skipped={skipped_projects}")
- # 5) scripts(按项目注入)
cur.execute(
"select id, project_id, episode_id, name, source, summary, episode_content, params, created_at, updated_at "
"from drama_scripts order by id"
)
src_scripts = cur.fetchall()
inserted_scripts = 0
+ pending_script_rows: list[tuple[DramaScript, Any, Any, Any]] = []
for r in src_scripts:
old_pid = int(r["project_id"])
new_pid = project_id_map.get(old_pid)
@@ -210,28 +294,34 @@ async def import_one(
inserted_scripts += 1
continue
+ summary = _jload(r["summary"])
+ episode_content = _jload(r["episode_content"])
+ params = _jload(r["params"])
scr = DramaScript(
project_id=new_pid,
episode_id=int(r["episode_id"]) if r["episode_id"] is not None else None,
name=r["name"] or "剧本",
source=r["source"],
- summary=_jload(r["summary"]),
- episode_content=_jload(r["episode_content"]),
- params=_jload(r["params"]),
+ summary=summary,
+ episode_content=episode_content,
+ params=params,
created_at=_parse_dt(r["created_at"]),
updated_at=_parse_dt(r["updated_at"]),
)
+ if preserve_ids:
+ scr.id = int(r["id"])
session.add(scr)
await session.flush()
+ pending_script_rows.append((scr, summary, episode_content, params))
inserted_scripts += 1
print(f"[scripts] inserted={inserted_scripts}")
- # 6) episodes
cur.execute(
"select id, project_id, name, params, created_at, updated_at "
"from drama_episodes order by id"
)
src_episodes = cur.fetchall()
+ pending_episode_json: list[tuple[DramaEpisode, Any]] = []
for r in src_episodes:
old_eid = int(r["id"])
old_pid = int(r["project_id"])
@@ -240,28 +330,37 @@ async def import_one(
continue
if dry_run:
- episode_id_map[old_eid] = -1
+ episode_id_map[old_eid] = old_eid if preserve_ids else -1
continue
+ params = _jload(r["params"])
ep = DramaEpisode(
project_id=new_pid,
name=r["name"] or "",
- params=_jload(r["params"]),
+ params=params,
created_at=_parse_dt(r["created_at"]),
updated_at=_parse_dt(r["updated_at"]),
)
+ if preserve_ids:
+ ep.id = old_eid
session.add(ep)
await session.flush()
episode_id_map[old_eid] = int(ep.id)
+ pending_episode_json.append((ep, params))
print(f"[episodes] mapped={len(episode_id_map)}")
- # 7) assets
+ if not dry_run:
+ for scr, _summary, _ec, _params in pending_script_rows:
+ if scr.episode_id is not None:
+ scr.episode_id = episode_id_map.get(int(scr.episode_id), scr.episode_id)
+
cur.execute(
"select id, project_id, type, asset_type, name, cover, url, params, derive_id, created_at, updated_at "
"from drama_assets order by id"
)
src_assets = cur.fetchall()
+ pending_assets: list[tuple[DramaAsset, Any]] = []
for r in src_assets:
old_aid = int(r["id"])
old_pid = int(r["project_id"])
@@ -270,9 +369,10 @@ async def import_one(
continue
if dry_run:
- asset_id_map[old_aid] = -1
+ asset_id_map[old_aid] = old_aid if preserve_ids else -1
continue
+ params = _jload(r["params"])
asset = DramaAsset(
project_id=new_pid,
type=r["type"] or "none",
@@ -280,23 +380,26 @@ async def import_one(
name=r["name"],
cover=r["cover"],
url=r["url"],
- params=_jload(r["params"]),
+ params=params,
derive_id=r["derive_id"],
created_at=_parse_dt(r["created_at"]),
updated_at=_parse_dt(r["updated_at"]),
)
+ if preserve_ids:
+ asset.id = old_aid
session.add(asset)
await session.flush()
asset_id_map[old_aid] = int(asset.id)
+ pending_assets.append((asset, params))
print(f"[assets] mapped={len(asset_id_map)}")
- # 8) fragments
cur.execute(
"select id, episode_id, sort_order, content, cover, video, duration_sec, params, created_at, updated_at "
"from drama_episode_fragments order by id"
)
src_fragments = cur.fetchall()
+ pending_frags: list[tuple[DramaEpisodeFragment, Any]] = []
for r in src_fragments:
old_fid = int(r["id"])
old_eid = int(r["episode_id"])
@@ -305,9 +408,10 @@ async def import_one(
continue
if dry_run:
- fragment_id_map[old_fid] = -1
+ fragment_id_map[old_fid] = old_fid if preserve_ids else -1
continue
+ params = _jload(r["params"])
frag = DramaEpisodeFragment(
episode_id=new_eid,
sort_order=int(r["sort_order"] or 0),
@@ -315,18 +419,39 @@ async def import_one(
cover=r["cover"] or "",
video=r["video"] or "",
duration_sec=r["duration_sec"],
- params=_jload(r["params"]),
+ params=params,
created_at=_parse_dt(r["created_at"]),
updated_at=_parse_dt(r["updated_at"]),
)
+ if preserve_ids:
+ frag.id = old_fid
session.add(frag)
await session.flush()
fragment_id_map[old_fid] = int(frag.id)
+ pending_frags.append((frag, params))
print(f"[fragments] mapped={len(fragment_id_map)}")
- # 9) join tables
- # drama_asset_episodes
+ if not dry_run:
+ for pid, content, params in pending_project_json:
+ proj = await session.get(DramaProject, pid)
+ if proj is None:
+ continue
+ proj.content = _rewrite_json(content, asset_id_map, episode_id_map, project_id_map)
+ proj.params = _rewrite_json(params, asset_id_map, episode_id_map, project_id_map)
+ for scr, summary, episode_content, params in pending_script_rows:
+ scr.summary = _rewrite_json(summary, asset_id_map, episode_id_map, project_id_map)
+ scr.episode_content = _rewrite_json(
+ episode_content, asset_id_map, episode_id_map, project_id_map
+ )
+ scr.params = _rewrite_json(params, asset_id_map, episode_id_map, project_id_map)
+ for ep, params in pending_episode_json:
+ ep.params = _rewrite_json(params, asset_id_map, episode_id_map, project_id_map)
+ for asset, params in pending_assets:
+ asset.params = _rewrite_json(params, asset_id_map, episode_id_map, project_id_map)
+ for frag, params in pending_frags:
+ frag.params = _rewrite_json(params, asset_id_map, episode_id_map, project_id_map)
+
cur.execute("select id, asset_id, episode_id, created_at from drama_asset_episodes order by id")
src_asset_episodes = cur.fetchall()
inserted_asset_episodes = 0
@@ -340,17 +465,17 @@ async def import_one(
if dry_run:
inserted_asset_episodes += 1
continue
- session.add(
- DramaAssetEpisode(
- asset_id=new_aid,
- episode_id=new_eid,
- created_at=_parse_dt(r["created_at"]),
- )
+ row = DramaAssetEpisode(
+ asset_id=new_aid,
+ episode_id=new_eid,
+ created_at=_parse_dt(r["created_at"]),
)
+ if preserve_ids:
+ row.id = int(r["id"])
+ session.add(row)
inserted_asset_episodes += 1
print(f"[drama_asset_episodes] inserted={inserted_asset_episodes}")
- # drama_fragment_asset_refs
cur.execute("select id, fragment_id, asset_id from drama_fragment_asset_refs order by id")
src_frag_refs = cur.fetchall()
inserted_frag_refs = 0
@@ -364,13 +489,18 @@ async def import_one(
if dry_run:
inserted_frag_refs += 1
continue
- session.add(DramaFragmentAssetRef(fragment_id=new_fid, asset_id=new_aid))
+ row = DramaFragmentAssetRef(fragment_id=new_fid, asset_id=new_aid)
+ if preserve_ids:
+ row.id = int(r["id"])
+ session.add(row)
inserted_frag_refs += 1
print(f"[drama_fragment_asset_refs] inserted={inserted_frag_refs}")
- print("Import done.")
if not dry_run:
+ await session.flush()
+ await _reset_id_sequences(session)
await session.commit()
+ print("Import done.")
except Exception:
if not dry_run:
await session.rollback()
@@ -393,6 +523,11 @@ def _parse_args() -> argparse.Namespace:
action="store_true",
help="目标库 users 表中缺失的 owner email:从源 sqlite 插入(会同步 hashed_password)",
)
+ p.add_argument(
+ "--replace",
+ action="store_true",
+ help="先清空目标 drama_* 表,再按源主键原样写入(含画布节点 assetId)",
+ )
return p.parse_args()
@@ -407,10 +542,10 @@ def main() -> None:
dry_run=bool(args.dry_run),
project_ids=project_ids,
import_missing_users=bool(args.import_missing_users),
+ replace=bool(args.replace),
)
)
if __name__ == "__main__":
main()
-
diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md
index dbd5d85..0c1f4c7 100644
--- a/docs/DEPLOY.md
+++ b/docs/DEPLOY.md
@@ -5,7 +5,9 @@
| 站点 | 地址 | 静态根目录 |
|------|------|------------|
| 用户前台 | https://kepu.printfilm.com/ | `/opt/ai_movie/frontend/dist` |
+| 用户前台(别名) | https://www.printfilm.com/ 、 https://printfilm.com/ | 同上 |
| 管理后台 | https://admin.kepu.printfilm.com/ | `/opt/ai_movie/admin/dist` |
+| 管理后台(别名) | https://admin.printfilm.com/ | 同上 |
| API | 同源 `/api` → `127.0.0.1:8000` | uvicorn `ai-movie-api` |
服务器路径约定:`/opt/ai_movie`。Postgres/Redis 走本机 Docker(端口 `15432` / `16379`,与旧 kepu 隔离)。
@@ -17,7 +19,7 @@
1. 本地改动已提交(或明确要打进本次包的未提交文件)。
2. 确认 **不要**用 `deploy/scripts/upload_oss_web.py` 代替站点发布。
3. 生产前端构建必须 `VITE_API_BASE=`(空,同源);禁止把本地 API 地址打进 dist。
-4. Celery 需监听队列:`pipeline,oss`。
+4. Celery 需监听队列:`drama,oss,video,pipeline`(漫剧 LLM 独立 `drama` 队列,避免被科普成片 `pipeline` 堵住)。
---
@@ -40,14 +42,14 @@ python deploy/scripts/deploy_kepu.py
1. 打包源码(排除 `.venv` / `node_modules` / `dist` / 生成媒体等)
2. SSH 上传并解压到 `/opt/ai_movie`(保留远端 venv / node_modules)
-3. 写入 compose env、`backend/.env`、systemd、nginx(含前台 + admin)
+3. 写入 compose env、`backend/.env`、systemd、nginx(含前台 + admin + `www.printfilm.com` / `admin.printfilm.com` 别名)
4. `docker compose up -d`(Postgres/Redis)
5. `pip install -r requirements.txt`
6. `frontend`:`npm ci && VITE_API_BASE= npm run build`
7. `admin`:`npm ci && npm run build`
8. 重启 `ai-movie-api` / `ai-movie-worker`,reload nginx
-9. 为 `admin.kepu.printfilm.com` 申请/续签证书(certbot,幂等)
-10. 健康检查:`/api/health`、前台与后台首页
+9. 为 `admin.kepu.printfilm.com`、`www.printfilm.com`、`admin.printfilm.com` 申请/续签证书(certbot,幂等)
+10. 健康检查:`/api/health`、前台与后台首页(含别名域名)
**注意**:全量脚本会覆盖远端 `backend/.env` 为脚本内嵌模板。若线上临时改过密钥/回调,发布后核对 EPAY / CORS / OSS 等项。
@@ -85,7 +87,7 @@ cd /opt/ai_movie/admin && npm ci && npm run build
| 单元 | 说明 |
|------|------|
| `ai-movie-api.service` | uvicorn `127.0.0.1:8000` |
-| `ai-movie-worker.service` | celery `-Q pipeline,oss` |
+| `ai-movie-worker.service` | celery `-Q drama,oss,video,pipeline` |
| `ai-movie-pg` / `ai-movie-redis` | Docker |
常用命令:
@@ -95,7 +97,9 @@ systemctl status ai-movie-api ai-movie-worker
journalctl -u ai-movie-api -n 80 --no-pager
curl -fsS http://127.0.0.1:8000/api/health
curl -fsSI https://kepu.printfilm.com/ | head
+curl -fsSI https://www.printfilm.com/ | head
curl -fsSI https://admin.kepu.printfilm.com/ | head
+curl -fsSI https://admin.printfilm.com/ | head
```
API 起不来时优先看:启动 seed 是否卡在 OSS、双 worker `create_all` 竞态、`.env` 是否被覆盖。
diff --git a/docs/STANDARDS.md b/docs/STANDARDS.md
index 62d2b24..f08c8e9 100644
--- a/docs/STANDARDS.md
+++ b/docs/STANDARDS.md
@@ -177,7 +177,7 @@ docs/ 产品与工程文档(本规范所在处)
## 8. 安全与配置
- 示例配置只放 `*.example`;真实值只在服务器 / 本机 `.env`。
-- CORS 只放真实前台域名(含 `admin.kepu.printfilm.com` 等)。
+- CORS 只放真实前台域名(含 `kepu.printfilm.com`、`www.printfilm.com`、`admin.kepu.printfilm.com`、`admin.printfilm.com` 等)。
- 管理接口必须 `role=admin`;bootstrap 邮箱仅提升已有用户,不造号。
---
diff --git a/docs/releases/2026-08-17.md b/docs/releases/2026-08-17.md
new file mode 100644
index 0000000..7f28ca8
--- /dev/null
+++ b/docs/releases/2026-08-17.md
@@ -0,0 +1,144 @@
+# 发布记录 · 2026-08-17
+
+## 2026-08-17 17:30 · 当日汇总全量发布
+
+- **操作者**:Agent(按用户要求)
+- **方式**:`deploy_kepu.py` 全量
+- **范围**:frontend / admin / api / worker / nginx / env
+- **变更摘要**(含当日已热修项,一并打包上线):
+ - **漫剧**:资产已出图/上传 UX;项目资产库分页;分集 `seed_from_script` MissingGreenlet 修复;LLM JSON 解析加固;摘要 generating 超时重入队
+ - **队列**:Celery 独立 `drama` 队列;管理后台队列监控 `/queues`;Worker 动态管理 API
+ - **API 性能**:admin 队列 inspect 轻量/缓存,避免阻塞主 API
+ - **用户端**:定价/钱包/充值记录、账号资料编辑、API Key、法务页等
+ - **成片**:ffmpeg 字幕烧录、Seedance 分镜约束等
+- **验证**:
+ - [x] `ai-movie-api` / `ai-movie-worker` active
+ - [x] `https://kepu.printfilm.com/api/health` ok
+ - [x] `https://www.printfilm.com/` HTTP 200
+ - [x] `https://admin.printfilm.com/` HTTP 200
+ - [x] 队列积压 `by_name` 均为 0
+- **备注 / 回滚**:
+ - 全量脚本已覆盖远端 `backend/.env` 模板;若 EPAY/OSS 回调有手工改动请核对
+ - 回滚可用 `/opt/ai_movie.bak`(若存在)或 git 版本 + 重跑 deploy
+
+## 2026-08-17 17:22 · 分集切分镜 500 + 资产库分页(热修)
+
+- **操作者**:Agent(按用户要求)
+- **方式**:SSH 热修 backend seed + 前台 build + 重启 api
+- **范围**:backend / frontend
+- **变更摘要**:
+ - 修复 `POST /api/drama/episodes/seed_from_script` 新建分集时 `MissingGreenlet`(async 下 lazy load `episode.fragments`)
+ - 项目工作流资产库增加分页(12/24/36 条每页)
+- **验证**:
+ - [x] 线上 project 12 调用 `seed_episodes_from_script` 成功:5 集 / 68 分镜
+ - [x] `ai-movie-api` active,health ok
+- **备注 / 回滚**:
+ - 根因见 `seed.py` `_list_episode_fragments` 显式查询替代 relationship lazy load
+
+## 2026-08-17 17:14 · 资产已出图/上传 UX(热修)
+
+- **操作者**:Agent(按用户要求)
+- **方式**:SSH 热修 4 文件 + 前台 build + 重启 api
+- **范围**:frontend / api
+- **变更摘要**:
+ - 已有图(AI 生成或本地上传)视为已出图,按钮改为「重新生成形象」
+ - 「一键生成未出图」计数排除已有图资产
+ - 资产详情弹窗支持上传/更换图片
+ - 上传接口写入 `generation.status=done`,避免仍显示生成中
+- **验证**:
+ - [x] 服务器 `frontend` build 成功
+ - [x] `ai-movie-api` / `ai-movie-worker` active
+ - [x] `https://www.printfilm.com/` HTTP 200
+ - [x] `/api/health` ok
+- **备注 / 回滚**:
+ - 仅热修相关文件;回滚需还原 4 个文件并 rebuild 前台
+
+## 2026-08-17 15:05 · Celery 队列拆分(热修)
+
+- **操作者**:Agent(按用户要求)
+- **方式**:SSH 热修 api/worker + systemd 单元
+- **范围**:backend Celery / worker
+- **变更摘要**:
+ - 新增 `drama` 队列:漫剧 LLM(摘要/分集/分镜)与资产生图,不再与科普 `pipeline` 共用
+ - `video`:所有视频生成;`oss`:异步上传;`pipeline`:仅科普/Studio 多阶段成片
+ - Worker 监听 `-Q drama,oss,video,pipeline`(drama 优先)
+ - 管理后台「队列任务」页:`/queues`,API `GET /api/admin/queues`
+ - `/api/health` 返回各队列 `by_name` 积压
+- **验证**:
+ - [x] `ai-movie-api` / `ai-movie-worker` active
+ - [x] health 显示 `by_name: {drama:0, oss:159, video:1, pipeline:6}`
+- **备注 / 回滚**:
+ - 旧任务若仍在 `pipeline` 队列会照常消费;新漫剧任务走 `drama`
+
+## 2026-08-17 14:26 · 账号资料可编辑(热修)
+
+- **操作者**:Agent(按用户要求)
+- **方式**:SSH 热修 api + 前台 build;未跑全量
+- **范围**:frontend / api
+- **变更摘要**:
+ - 账号信息:用户名、邮箱、手机号可编辑保存
+ - 手机号只记录联系方式,不发验证码
+- **验证**:
+ - [x] 前台 `npm run build` 成功
+ - [x] `ai-movie-api` active
+ - [x] `PATCH /api/auth/me` 已注册,`phone` 字段可读
+- **备注 / 回滚**:
+ - 新增 `users.phone` 列;回滚代码后列可保留
+
+## 2026-08-17 13:55 · 清空线上漫剧并全量同步本地(含画布)
+
+- **操作者**:Agent(按用户要求)
+- **方式**:SSH 热修数据;`import_drama_sqlite_to_postgres.py --replace`
+- **范围**:Postgres `drama_*` 表
+- **变更摘要**:
+ - 删除线上全部漫剧项目/资产/分集/分镜
+ - 按本地 sqlite 主键原样写入(项目 id 2 / 7 / 8),画布 `canvas_nodes.assetId` 可对齐
+- **验证**:
+ - [x] 3 项目 / 197 资产 / 12 集 / 142 分镜 / 728 分镜资产引用
+ - [x] 大禹治水 91 个画布节点 assetId 全部存在
+ - [x] 自由测试 5 节点 + 5 边
+- **备注 / 回滚**:
+ - 旧线上漫剧行已删除,无法从库内回滚;媒体仍在 OSS
+ - 用量 `usage_events.drama_project_id` 已置空,未改账本金额
+
+## 2026-08-17 13:42 · 绑定 www / admin.printfilm.com(热修)
+
+- **操作者**:Agent(按用户要求)
+- **方式**:SSH 热修 nginx + certbot + CORS;未跑全量 `deploy_kepu.py`
+- **范围**:nginx / env / oss CORS
+- **变更摘要**:
+ - 禁用旧站 `printfilm.conf`(原反代 7050/7051 的 ai-manju)
+ - `www.printfilm.com` / `printfilm.com` 改为 PRINTFILM 前台 dist(含 `/api`、`/static`、`/epay/notify`)
+ - `admin.printfilm.com` → 管理后台 dist
+ - `CORS_ORIGINS` 与 OSS 浏览器 CORS 增加上述 HTTPS 源
+ - 发布脚本会持续禁用 `printfilm.conf`,避免下次全量抢回域名
+- **验证**:
+ - [x] `https://www.printfilm.com/` HTTPS 200
+ - [x] `https://www.printfilm.com/api/health` ok
+ - [x] `https://admin.printfilm.com/` HTTPS 200
+ - [x] `https://admin.printfilm.com/api/health` ok
+ - [x] 原 `kepu.printfilm.com` / `admin.kepu.printfilm.com` 保持不变
+- **备注 / 回滚**:
+ - 旧配置仍在 `/etc/nginx/sites-available/printfilm.conf`;恢复软链并去掉新 www 站点即可回滚
+ - 易支付回调仍走 `https://kepu.printfilm.com/epay/notify`
+
+## 2026-08-17 12:04 · 字幕合成修复 + 分镜台清理(全量)
+
+- **操作者**:Agent(按用户要求)
+- **方式**:`deploy_kepu.py` 全量(首次因 frontend TS 类型错误中断,修复后重跑成功)
+- **范围**:frontend / admin / api / worker / nginx / env
+- **变更摘要**:
+ - 成片字幕:合成阶段始终用 ffmpeg 烧录口播字幕;`split` 布局不再跳过底部字幕(标题叠字留在顶部)
+ - 分镜工作台:去掉「结构摘要」旁错误的「示例聚合」占位,以及无实际作用的「分镜设置」假控件
+ - 顺带修前端构建:`composeEpisodeVideoClient` BlobPart 类型、`CanvasStore` 重复 `kind === 'video'` 判断
+- **验证**:
+ - [x] `https://kepu.printfilm.com/api/health` ok
+ - [x] 前台首页 HTTPS 200(`index-3tb1K94l.js` / `index-s_7zELqT.css`)
+ - [x] `https://admin.kepu.printfilm.com/` HTTPS 200
+ - [x] `https://admin.kepu.printfilm.com/api/health` ok
+ - [x] api / worker active
+ - [ ] 业务冒烟:开源展示模板成片底部口播字幕、分镜台无「示例聚合」
+- **备注 / 回滚**:
+ - 全量脚本覆盖远端 `backend/.env`;EPAY/CORS/OSS 与脚本模板一致
+ - Celery worker 已重启,监听 `pipeline,oss`
+ - 旧成片需在工作室点「拼接成片」或重新合成后才会带新字幕逻辑
diff --git a/docs/releases/README.md b/docs/releases/README.md
index 29e0beb..6c3db04 100644
--- a/docs/releases/README.md
+++ b/docs/releases/README.md
@@ -1,6 +1,6 @@
# 发布记录
-每次对 **https://kepu.printfilm.com/** / **https://admin.kepu.printfilm.com/** 的发布或线上热修,都在本目录留下一条记录。
+每次对 **https://kepu.printfilm.com/** / **https://www.printfilm.com/** / **https://admin.kepu.printfilm.com/** / **https://admin.printfilm.com/** 的发布或线上热修,都在本目录留下一条记录。
## 约定
@@ -33,6 +33,14 @@
| 日期 | 摘要 | 文件 |
|------|------|------|
+| 2026-08-17 | **全量**:漫剧资产/分集/队列/admin/定价等当日汇总 | [2026-08-17.md](./2026-08-17.md) |
+| 2026-08-17 | 分集切分镜 500 + 资产库分页(热修) | [2026-08-17.md](./2026-08-17.md) |
+| 2026-08-17 | 资产已出图/上传 UX(热修) | [2026-08-17.md](./2026-08-17.md) |
+| 2026-08-17 | Celery 队列拆分 + admin 队列页(热修) | [2026-08-17.md](./2026-08-17.md) |
+| 2026-08-17 | 账号资料可编辑(用户名/邮箱/手机号) | [2026-08-17.md](./2026-08-17.md) |
+| 2026-08-17 | 清空线上漫剧并全量同步本地(含画布) | [2026-08-17.md](./2026-08-17.md) |
+| 2026-08-17 | 绑定 www.printfilm.com / admin.printfilm.com(热修) | [2026-08-17.md](./2026-08-17.md) |
+| 2026-08-17 | 字幕 ffmpeg 合成修复 + 分镜台清理(全量) | [2026-08-17.md](./2026-08-17.md) |
| 2026-08-12 | UI 打磨 + 全局弹窗 + 本地同步线上 | [2026-08-12.md](./2026-08-12.md) |
| 2026-08-12 | 漫剧分镜/分集全量:人物介绍 LLM、画面不配音、分镜非互斥、分集 UI | [2026-08-12.md](./2026-08-12.md) |
| 2026-08-11 | 全量上线 + admin 域名 + 易支付/定价热修 | [2026-08-11.md](./2026-08-11.md) |
diff --git a/frontend/public/payment/alipay.svg b/frontend/public/payment/alipay.svg
new file mode 100644
index 0000000..0ea7460
--- /dev/null
+++ b/frontend/public/payment/alipay.svg
@@ -0,0 +1,6 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" role="img" aria-label="Alipay">
+ <rect width="48" height="48" rx="11" fill="#1677FF"/>
+ <g transform="translate(9 9) scale(1.25)">
+ <path fill="#fff" d="M19.695 15.07c3.426 1.158 4.203 1.22 4.203 1.22V3.846c0-2.124-1.705-3.845-3.81-3.845H3.914C1.808.001.102 1.722.102 3.846v16.31c0 2.123 1.706 3.845 3.813 3.845h16.173c2.105 0 3.81-1.722 3.81-3.845v-.157s-6.19-2.602-9.315-4.119c-2.096 2.602-4.8 4.181-7.607 4.181-4.75 0-6.361-4.19-4.112-6.949.49-.602 1.324-1.175 2.617-1.497 2.025-.502 5.247.313 8.266 1.317a16.796 16.796 0 0 0 1.341-3.302H5.781v-.952h4.799V6.975H4.77v-.953h5.81V3.591s0-.409.411-.409h2.347v2.84h5.744v.951h-5.744v1.704h4.69a19.453 19.453 0 0 1-1.986 5.06c1.424.52 2.702 1.011 3.654 1.333m-13.81-2.032c-.596.06-1.71.325-2.321.869-1.83 1.608-.735 4.55 2.968 4.55 2.151 0 4.301-1.388 5.99-3.61-2.403-1.182-4.438-2.028-6.637-1.809"/>
+ </g>
+</svg>
diff --git a/frontend/public/payment/unionpay.svg b/frontend/public/payment/unionpay.svg
new file mode 100644
index 0000000..71c5954
--- /dev/null
+++ b/frontend/public/payment/unionpay.svg
@@ -0,0 +1,7 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" role="img" aria-label="银联">
+ <rect width="48" height="48" rx="11" fill="#fff"/>
+ <rect x="7" y="13" width="9" height="22" rx="2" fill="#E21836"/>
+ <rect x="19" y="13" width="9" height="22" rx="2" fill="#00447C"/>
+ <rect x="31" y="13" width="9" height="22" rx="2" fill="#007B84"/>
+ <path fill="#fff" d="M19 24h9v2h-9z" opacity="0.9"/>
+</svg>
diff --git a/frontend/public/payment/wechatpay.svg b/frontend/public/payment/wechatpay.svg
new file mode 100644
index 0000000..4780181
--- /dev/null
+++ b/frontend/public/payment/wechatpay.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" role="img" aria-label="WeChat Pay">
+ <rect width="48" height="48" rx="11" fill="#07C160"/>
+ <path fill="#fff" d="M16.46 13.69c-3.6 0-6.52 2.47-6.52 5.51 0 1.66.88 3.15 2.25 4.16a.44.44 0 0 1 .16.5l-.29 1.11c-.01.05-.04.1-.04.16 0 .12.1.22.22.22a.24.24 0 0 0 .13-.04l1.43-.84a.65.65 0 0 1 .54-.07c.7.17 1.42.26 2.13.26.2 0 .41-.02.61-.04-.64-1.93.12-3.73 1.45-4.83 1.28-1.06 2.91-1.49 4.39-1.38-.43-2.69-3.15-4.76-6.46-4.76zm-2.18 2.85c.48 0 .87.4.87.89a.88.88 0 0 1-.87.88.88.88 0 0 1-.87-.88c0-.49.39-.89.87-.89zm4.36 0c.48 0 .87.4.87.89a.88.88 0 0 1-.87.88.88.88 0 0 1-.87-.88c0-.49.39-.89.87-.89zm4.01 2.15c-1.35-.04-2.81.38-3.96 1.34-1.29 1.07-2.02 2.79-1.34 4.67.71 1.84 2.75 3.17 5.16 3.17.62 0 1.22-.09 1.77-.25a.54.54 0 0 1 .45.06l1.19.7a.2.2 0 0 0 .1.03c.1 0 .18-.08.18-.18 0-.05-.02-.09-.03-.13l-.25-.93a.44.44 0 0 1-.02-.12.37.37 0 0 1 .15-.3c1.35-1.02 2.08-2.26 2.08-3.64 0-2.41-2.2-4.38-4.99-4.57-.1-.01-.2-.02-.3-.02zm-1.9 2.46c.4 0 .73.33.73.74a.73.73 0 0 1-.73.73.73.73 0 0 1-.73-.73c0-.41.33-.74.73-.74zm3.63 0c.4 0 .73.33.73.74a.73.73 0 0 1-.73.73.73.73 0 0 1-.73-.73c0-.41.33-.74.73-.74z"/>
+</svg>
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 41bdc39..6b11ed1 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -7,6 +7,8 @@ import HomePage from './pages/HomePage'
import ToolsPage from './pages/ToolsPage'
import ToolDetailPage from './pages/ToolDetailPage'
import HelpPage from './pages/HelpPage'
+import { PrivacyPage, TermsPage } from './pages/LegalDocPage'
+import ContactPage from './pages/ContactPage'
import SettingsPage from './pages/SettingsPage'
import PricingPage from './pages/PricingPage'
import StudioPage from './pages/StudioPage'
@@ -35,6 +37,9 @@ export default function App() {
<Route path="/tools/:toolId" element={<ToolDetailPage />} />
<Route path="/assets" element={<AssetLibraryPage />} />
<Route path="/help" element={<HelpPage />} />
+ <Route path="/terms" element={<TermsPage />} />
+ <Route path="/privacy" element={<PrivacyPage />} />
+ <Route path="/contact" element={<ContactPage />} />
<Route path="/settings" element={<SettingsPage />} />
<Route path="/pricing" element={<PricingPage />} />
<Route path="/history" element={<HistoryPage />} />
diff --git a/frontend/src/api.ts b/frontend/src/api.ts
index 30a0a59..2589d58 100644
--- a/frontend/src/api.ts
+++ b/frontend/src/api.ts
@@ -159,6 +159,8 @@ export type User = {
frozen_fen?: number
plan?: string
billing_unlimited?: boolean
+ avatar_url?: string
+ phone?: string
}
export type BillingSku = {
@@ -195,6 +197,24 @@ export type UsageSummary = {
frozen_yuan: number
}
+export type UsageChargeRecord = {
+ id: number
+ billing_key: string
+ billing_label: string
+ model: string
+ context: string
+ total_tokens: number
+ charge_fen: number
+ charge_yuan: number
+ estimated: boolean
+ created_at: string | null
+}
+
+export type UsageChargeList = {
+ items: UsageChargeRecord[]
+ meta: { page: number; page_size: number; total: number }
+}
+
export type Wallet = {
balance_fen: number
frozen_fen: number
@@ -240,6 +260,34 @@ export const api = {
me() {
return request<User>('/api/auth/me')
},
+ updateProfile(body: { nickname: string; email: string; phone: string }) {
+ return request<User>('/api/auth/me', {
+ method: 'PATCH',
+ body: JSON.stringify(body),
+ })
+ },
+ async uploadAvatar(file: File) {
+ const token = localStorage.getItem('token')
+ const form = new FormData()
+ form.append('file', file)
+ const res = await fetch(`${API_BASE}/api/auth/avatar`, {
+ method: 'POST',
+ headers: token ? { Authorization: `Bearer ${token}` } : {},
+ body: form,
+ })
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({ detail: res.statusText }))
+ const detail = err.detail
+ const message =
+ typeof detail === 'string'
+ ? detail
+ : Array.isArray(detail)
+ ? detail.map((d: { msg?: string }) => d.msg || JSON.stringify(d)).join('; ')
+ : res.statusText
+ throw new Error(message || '头像上传失败')
+ }
+ return res.json() as Promise<User>
+ },
templates() {
return request<Template[]>('/api/templates')
},
@@ -454,12 +502,24 @@ export const api = {
credit_fen: number
}>(`/api/billing/orders/${encodeURIComponent(outTradeNo)}`)
},
+ /** 关闭待支付订单 */
+ closeBillingOrder(outTradeNo: string) {
+ return request<{ out_trade_no: string; status: string }>(
+ `/api/billing/orders/${encodeURIComponent(outTradeNo)}/close`,
+ { method: 'POST' },
+ )
+ },
listBillingOrders(limit = 50) {
return request<{ orders: BillingOrder[] }>(`/api/billing/orders?limit=${limit}`)
},
usageSummary() {
return request<UsageSummary>('/api/billing/usage/summary')
},
+ usageEvents(page = 1, pageSize = 20) {
+ return request<UsageChargeList>(
+ `/api/billing/usage/events?page=${page}&page_size=${pageSize}`,
+ )
+ },
eventsUrl(projectId: number) {
return `${API_BASE}/api/projects/${projectId}/events`
},
diff --git a/frontend/src/api/apiKeys.ts b/frontend/src/api/apiKeys.ts
new file mode 100644
index 0000000..6414a18
--- /dev/null
+++ b/frontend/src/api/apiKeys.ts
@@ -0,0 +1,69 @@
+/** API Key 管理客户端(/api/user/api-keys) */
+
+function defaultApiBase() {
+ if (typeof window !== 'undefined' && window.location?.hostname) {
+ const { protocol, hostname } = window.location
+ return `${protocol}//${hostname}:8000`
+ }
+ return 'http://127.0.0.1:8000'
+}
+
+const API_BASE =
+ import.meta.env.VITE_API_BASE === undefined || import.meta.env.VITE_API_BASE === null
+ ? defaultApiBase()
+ : String(import.meta.env.VITE_API_BASE)
+
+export type ApiKeyItem = {
+ id: number
+ name: string
+ key_prefix: string
+ created_at: string | null
+ last_used_at: string | null
+}
+
+export type ApiKeyCreated = ApiKeyItem & {
+ secret: string
+}
+
+async function request<T>(path: string, init?: RequestInit): Promise<T> {
+ const token = localStorage.getItem('token')
+ const res = await fetch(`${API_BASE}${path}`, {
+ ...init,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
+ ...(init?.headers || {}),
+ },
+ })
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({ detail: res.statusText }))
+ const detail = err.detail
+ const message =
+ typeof detail === 'string'
+ ? detail
+ : Array.isArray(detail)
+ ? detail.map((d: { msg?: string }) => d.msg || JSON.stringify(d)).join('; ')
+ : res.statusText
+ throw new Error(message || '请求失败')
+ }
+ return res.json() as Promise<T>
+}
+
+export function getPublicApiBase() {
+ return API_BASE
+}
+
+export const apiKeysApi = {
+ list() {
+ return request<ApiKeyItem[]>('/api/user/api-keys')
+ },
+ create(name: string) {
+ return request<ApiKeyCreated>('/api/user/api-keys', {
+ method: 'POST',
+ body: JSON.stringify({ name }),
+ })
+ },
+ revoke(id: number) {
+ return request<{ ok: boolean }>(`/api/user/api-keys/${id}`, { method: 'DELETE' })
+ },
+}
diff --git a/frontend/src/components/UserAvatar.tsx b/frontend/src/components/UserAvatar.tsx
new file mode 100644
index 0000000..50192aa
--- /dev/null
+++ b/frontend/src/components/UserAvatar.tsx
@@ -0,0 +1,32 @@
+import { api, type User } from '../api'
+
+type Props = {
+ user: Pick<User, 'nickname' | 'avatar_url'> | null | undefined
+ size?: 'sm' | 'md' | 'lg' | 'xl'
+ className?: string
+ title?: string
+}
+
+const SIZE_CLASS = {
+ sm: 'pf-user-avatar--sm',
+ md: 'pf-user-avatar--md',
+ lg: 'pf-user-avatar--lg',
+ xl: 'pf-user-avatar--xl',
+} as const
+
+/** 用户头像:有图显示图片,否则昵称首字母占位 */
+export default function UserAvatar({ user, size = 'md', className = '', title }: Props) {
+ const nickname = user?.nickname || 'P'
+ const initial = nickname.slice(0, 1).toUpperCase()
+ const src = user?.avatar_url ? api.assetUrl(user.avatar_url, user.avatar_url) : ''
+
+ return (
+ <span
+ className={`pf-user-avatar ${SIZE_CLASS[size]} ${src ? 'has-image' : ''} ${className}`.trim()}
+ title={title}
+ aria-hidden={title ? undefined : true}
+ >
+ {src ? <img src={src} alt="" /> : initial}
+ </span>
+ )
+}
diff --git a/frontend/src/components/billing/PaymentBrandIcon.tsx b/frontend/src/components/billing/PaymentBrandIcon.tsx
new file mode 100644
index 0000000..d63ee86
--- /dev/null
+++ b/frontend/src/components/billing/PaymentBrandIcon.tsx
@@ -0,0 +1,30 @@
+type PayBrand = 'alipay' | 'wxpay' | 'unionpay'
+
+type Props = {
+ brand: PayBrand
+ /** sm 用于按钮内;md 用于弹窗标题 */
+ size?: 'sm' | 'md'
+ className?: string
+}
+
+const BRAND_META: Record<PayBrand, { src: string; alt: string }> = {
+ alipay: { src: '/payment/alipay.svg', alt: '支付宝' },
+ wxpay: { src: '/payment/wechatpay.svg', alt: '微信支付' },
+ unionpay: { src: '/payment/unionpay.svg', alt: '银联支付' },
+}
+
+/** 支付渠道品牌图标 */
+export default function PaymentBrandIcon({ brand, size = 'sm', className = '' }: Props) {
+ const meta = BRAND_META[brand]
+ return (
+ <img
+ src={meta.src}
+ alt={meta.alt}
+ className={`pf-pay-brand-icon is-${size}${className ? ` ${className}` : ''}`}
+ width={size === 'md' ? 28 : 22}
+ height={size === 'md' ? 28 : 22}
+ loading="lazy"
+ decoding="async"
+ />
+ )
+}
diff --git a/frontend/src/components/billing/PaymentModal.tsx b/frontend/src/components/billing/PaymentModal.tsx
index 7acfaf2..06dde68 100644
--- a/frontend/src/components/billing/PaymentModal.tsx
+++ b/frontend/src/components/billing/PaymentModal.tsx
@@ -1,6 +1,7 @@
import { useEffect, useEffectEvent, useState } from 'react'
import QRCode from 'qrcode'
import Modal from '../ui/Modal'
+import PaymentBrandIcon from './PaymentBrandIcon'
import { api } from '../../api'
export type PayCheckout = {
@@ -51,6 +52,19 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
onPaid()
})
+ /** 取消支付:关闭弹窗,并尽量把待支付订单置为 closed */
+ async function handleCancel() {
+ const tradeNo = checkout?.out_trade_no
+ if (tradeNo && status !== 'paid') {
+ try {
+ await api.closeBillingOrder(tradeNo)
+ } catch {
+ /* 忽略关闭失败,仍允许退出弹窗 */
+ }
+ }
+ onClose()
+ }
+
useEffect(() => {
if (!open || !checkout) return
/*
@@ -98,6 +112,8 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
if (left <= 0) {
setStatus('expired')
window.clearInterval(tick)
+ // 倒计时结束:后端自动关闭(拉取一次触发过期清理)
+ void api.getBillingOrder(checkout.out_trade_no).catch(() => undefined)
}
}, 250)
@@ -110,6 +126,10 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
window.clearInterval(poll)
window.clearInterval(tick)
handlePaid()
+ } else if (order.status === 'closed') {
+ setStatus('expired')
+ window.clearInterval(poll)
+ window.clearInterval(tick)
}
} catch {
/* ignore transient poll errors */
@@ -159,10 +179,10 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
<div className="pf-pay-sheet">
<header className="pf-pay-sheet-head">
<div className="pf-pay-sheet-title">
- <span className={`pf-pay-logo ${isAlipay ? 'alipay' : 'wxpay'}`} aria-hidden />
+ <PaymentBrandIcon brand={isAlipay ? 'alipay' : 'wxpay'} size="md" />
<strong>{title}</strong>
</div>
- <button type="button" className="pf-pay-sheet-close" onClick={onClose} aria-label="关闭">
+ <button type="button" className="pf-pay-sheet-close" onClick={() => void handleCancel()} aria-label="关闭">
×
</button>
</header>
@@ -206,7 +226,7 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
{error ? <p className="pf-error pf-pay-error">{error}</p> : null}
<div className="pf-pay-actions">
- <button type="button" className="pf-pay-btn ghost" onClick={onClose}>
+ <button type="button" className="pf-pay-btn ghost" onClick={() => void handleCancel()}>
取消支付
</button>
<button
diff --git a/frontend/src/components/billing/PricingWalletCard.tsx b/frontend/src/components/billing/PricingWalletCard.tsx
new file mode 100644
index 0000000..f6dedd0
--- /dev/null
+++ b/frontend/src/components/billing/PricingWalletCard.tsx
@@ -0,0 +1,83 @@
+import { Eye, EyeOff } from 'lucide-react'
+import { useState } from 'react'
+import type { UsageSummary, Wallet } from '../../api'
+
+type Props = {
+ wallet: Wallet | null
+ usage: UsageSummary | null
+ loggedIn: boolean
+ updatedAt: Date | null
+ onHistory: () => void
+}
+
+function planLabel(wallet: Wallet | null) {
+ if (!wallet) return 'Free'
+ if (wallet.billing_unlimited) return 'Unlimited'
+ const p = (wallet.plan || 'free').toLowerCase()
+ if (p === 'free') return 'Free'
+ if (p === 'pro') return 'Pro'
+ return wallet.plan
+}
+
+function formatUpdated(d: Date | null) {
+ if (!d) return '—'
+ const pad = (n: number) => String(n).padStart(2, '0')
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
+}
+
+/** 定价页深色余额卡片:余额展示、冻结/套餐、充值记录 */
+export default function PricingWalletCard({ wallet, usage, loggedIn, updatedAt, onHistory }: Props) {
+ const [balanceVisible, setBalanceVisible] = useState(true)
+
+ const balanceYuan = wallet?.balance_yuan ?? usage?.balance_yuan ?? 0
+ const frozenYuan = wallet?.frozen_yuan ?? usage?.frozen_yuan ?? 0
+ const monthCharge = usage?.charge_yuan ?? 0
+
+ return (
+ <aside className="pf-pricing-wallet-dark">
+ <div className="pf-pricing-wallet-dark-head">
+ <span className="pf-pricing-wallet-dark-label">可用余额</span>
+ <div className="pf-pricing-wallet-dark-actions">
+ <button
+ type="button"
+ className="pf-pricing-wallet-eye"
+ aria-label={balanceVisible ? '隐藏余额' : '显示余额'}
+ onClick={() => setBalanceVisible((v) => !v)}
+ >
+ {balanceVisible ? <Eye size={16} /> : <EyeOff size={16} />}
+ </button>
+ <button
+ type="button"
+ className="pf-pricing-wallet-history"
+ disabled={!loggedIn}
+ title={loggedIn ? '查看充值记录' : '请先登录'}
+ onClick={onHistory}
+ >
+ 充值记录
+ </button>
+ </div>
+ </div>
+
+ <strong className="pf-pricing-wallet-dark-balance">
+ {balanceVisible ? `¥${balanceYuan.toFixed(2)}` : '¥ ****'}
+ </strong>
+
+ <dl className="pf-pricing-wallet-dark-meta">
+ <div>
+ <dt>本次消耗</dt>
+ <dd>{loggedIn ? `¥${monthCharge.toFixed(2)}` : '—'}</dd>
+ </div>
+ <div>
+ <dt>当前套餐</dt>
+ <dd>{planLabel(wallet)}</dd>
+ </div>
+ </dl>
+
+ {frozenYuan > 0 ? (
+ <p className="pf-pricing-wallet-dark-frozen">冻结中 ¥{frozenYuan.toFixed(2)}</p>
+ ) : null}
+
+ <p className="pf-pricing-wallet-dark-updated">更新于 {formatUpdated(updatedAt)}</p>
+ </aside>
+ )
+}
diff --git a/frontend/src/components/billing/TopupHistoryModal.tsx b/frontend/src/components/billing/TopupHistoryModal.tsx
index 8d1becd..c38268d 100644
--- a/frontend/src/components/billing/TopupHistoryModal.tsx
+++ b/frontend/src/components/billing/TopupHistoryModal.tsx
@@ -32,7 +32,7 @@ function formatTime(iso?: string | null) {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}
-/** 充值记录弹窗:列出近期订单与到账状态 */
+/** 充值记录弹窗:列出近期订单与到账状态(过期待支付由后台自动关闭) */
export default function TopupHistoryModal({ open, onClose }: Props) {
/*
* orders 订单列表
diff --git a/frontend/src/components/billing/UsageChargeRecords.tsx b/frontend/src/components/billing/UsageChargeRecords.tsx
new file mode 100644
index 0000000..86bd628
--- /dev/null
+++ b/frontend/src/components/billing/UsageChargeRecords.tsx
@@ -0,0 +1,137 @@
+import { useCallback, useEffect, useState } from 'react'
+import { api, type UsageChargeRecord } from '../../api'
+import Pagination from '../ui/Pagination'
+import { pageCountOf } from '../../lib/pagination'
+
+/** 格式化相对时间展示 */
+function formatWhen(iso?: string | null) {
+ 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',
+ })
+}
+
+/** 格式化 token 数量 */
+function formatTokens(n: number) {
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1)}M`
+ if (n >= 10_000) return `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1)}k`
+ return n.toLocaleString('zh-CN')
+}
+
+type UsageChargeRecordsProps = {
+ /** 嵌入设置页时为 compact */
+ variant?: 'panel' | 'compact'
+}
+
+/** 使用扣费记录列表:按次展示 LLM / 生图 / 生视频等计费明细 */
+export default function UsageChargeRecords({ variant = 'compact' }: UsageChargeRecordsProps) {
+ /*
+ * items 当前页记录
+ * page 当前页码
+ * pageSize 每页条数
+ * total 总条数
+ * loading 加载中
+ * error 错误信息
+ */
+ const [items, setItems] = useState<UsageChargeRecord[]>([])
+ const [page, setPage] = useState(1)
+ const [pageSize, setPageSize] = useState(5)
+ const [total, setTotal] = useState(0)
+ const [loading, setLoading] = useState(true)
+ const [error, setError] = useState('')
+
+ const pageCount = pageCountOf(total, pageSize)
+
+ // 拉取指定页
+ const loadPage = useCallback(async (nextPage: number, size: number) => {
+ if (!localStorage.getItem('token')) {
+ setItems([])
+ setTotal(0)
+ setLoading(false)
+ return
+ }
+ setLoading(true)
+ setError('')
+ try {
+ const res = await api.usageEvents(nextPage, size)
+ setTotal(res.meta.total)
+ setPage(nextPage)
+ setItems(res.items)
+ } catch (e) {
+ setError(e instanceof Error ? e.message : '加载扣费记录失败')
+ setItems([])
+ setTotal(0)
+ } finally {
+ setLoading(false)
+ }
+ }, [])
+
+ useEffect(() => {
+ void loadPage(page, pageSize)
+ }, [loadPage, page, pageSize])
+
+ function handlePageSizeChange(nextSize: number) {
+ setPageSize(nextSize)
+ setPage(1)
+ }
+
+ return (
+ <section className={`pf-usage-records${variant === 'compact' ? ' is-compact' : ''}`}>
+ <header className="pf-usage-records-head">
+ <h3>使用扣费记录</h3>
+ <p className="pf-muted">每次 AI 调用的 token 用量与扣费明细</p>
+ </header>
+
+ {loading ? <p className="pf-muted">加载中…</p> : null}
+ {error ? <p className="pf-error">{error}</p> : null}
+
+ {!loading && !error && items.length === 0 ? (
+ <div className="pf-settings-empty">
+ <p>暂无扣费记录</p>
+ </div>
+ ) : null}
+
+ {items.length > 0 ? (
+ <ul className="pf-settings-list pf-usage-records-list">
+ {items.map((item) => (
+ <li key={item.id}>
+ <div className="pf-settings-list-row pf-usage-record-row">
+ <span className="pf-settings-list-main">
+ <strong>{item.billing_label}</strong>
+ <em className="pf-muted">
+ {item.context}
+ {item.total_tokens > 0 ? ` · ${formatTokens(item.total_tokens)} tokens` : ''}
+ {item.estimated ? ' · 估算' : ''}
+ </em>
+ </span>
+ <span className="pf-settings-list-meta pf-usage-record-meta">
+ <strong className="pf-usage-record-charge">
+ {item.charge_fen > 0 ? `-¥${item.charge_yuan.toFixed(2)}` : '—'}
+ </strong>
+ <em className="pf-muted">{formatWhen(item.created_at)}</em>
+ </span>
+ </div>
+ </li>
+ ))}
+ </ul>
+ ) : null}
+
+ {!loading && total > 0 ? (
+ <Pagination
+ page={page}
+ pageCount={pageCount}
+ total={total}
+ pageSize={pageSize}
+ onPageSizeChange={handlePageSizeChange}
+ onChange={setPage}
+ ariaLabel="扣费记录分页"
+ />
+ ) : null}
+ </section>
+ )
+}
diff --git a/frontend/src/components/layout/AppShell.tsx b/frontend/src/components/layout/AppShell.tsx
index 631d3fe..1f1ebd9 100644
--- a/frontend/src/components/layout/AppShell.tsx
+++ b/frontend/src/components/layout/AppShell.tsx
@@ -1,4 +1,5 @@
import type { ReactNode } from 'react'
+import { Link } from 'react-router-dom'
import SiteNav, { type NavActive } from './SiteNav'
type Props = {
@@ -19,6 +20,12 @@ 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>
<p>© {new Date().getFullYear()} PRINTFILM. All rights reserved.</p>
</footer>
) : null}
diff --git a/frontend/src/components/layout/SiteNav.tsx b/frontend/src/components/layout/SiteNav.tsx
index f3d317c..e79f5b5 100644
--- a/frontend/src/components/layout/SiteNav.tsx
+++ b/frontend/src/components/layout/SiteNav.tsx
@@ -2,10 +2,12 @@ import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom'
import { useEffect, useState } from 'react'
import { api } from '../../api'
import type { User } from '../../api'
+import UserAvatar from '../UserAvatar'
import BrandMark from '../BrandMark'
import { IconHelp } from '../ui/Icons'
import Button from '../ui/Button'
import CreateChoiceModal from '../ui/CreateChoiceModal'
+import { USER_UPDATED_EVENT } from '../../lib/userEvents'
export type NavActive = 'home' | 'drama' | 'kepu' | 'tools' | 'assets' | 'pricing' | 'templates' | 'studio' | 'history'
@@ -51,6 +53,15 @@ export default function SiteNav({ active }: Props) {
api.me().then(setUser).catch(() => localStorage.removeItem('token'))
}, [])
+ useEffect(() => {
+ const onUserUpdated = (event: Event) => {
+ const detail = (event as CustomEvent<User>).detail
+ if (detail) setUser(detail)
+ }
+ window.addEventListener(USER_UPDATED_EVENT, onUserUpdated)
+ return () => window.removeEventListener(USER_UPDATED_EVENT, onUserUpdated)
+ }, [])
+
useEffect(() => {
setMenuOpen(false)
}, [location.pathname])
@@ -109,7 +120,7 @@ export default function SiteNav({ active }: Props) {
title={`${user.nickname} · 个人中心`}
onClick={() => nav('/settings')}
>
- {user.nickname.slice(0, 1).toUpperCase()}
+ <UserAvatar user={user} size="sm" />
</button>
) : (
<Link to="/auth?next=/" className="pf-link pf-nav-login">
diff --git a/frontend/src/components/ui/Pagination.tsx b/frontend/src/components/ui/Pagination.tsx
index ba58714..61232d5 100644
--- a/frontend/src/components/ui/Pagination.tsx
+++ b/frontend/src/components/ui/Pagination.tsx
@@ -1,11 +1,21 @@
import { cn } from '../../lib/cn'
+import { DEFAULT_PAGE_SIZE_OPTIONS } from '../../lib/pagination'
type Props = {
page: number
pageCount: number
onChange: (page: number) => void
+ /** 总条数,传入后显示摘要 */
+ total?: number
+ /** 当前每页条数 */
+ pageSize?: number
+ /** 每页条数选项;配合 onPageSizeChange 显示切换器 */
+ pageSizeOptions?: readonly number[]
+ onPageSizeChange?: (pageSize: number) => void
className?: string
ariaLabel?: string
+ /** 是否显示「第 x / y 页 · 共 z 条」摘要 */
+ showSummary?: boolean
}
// 生成带省略号的页码序列
@@ -23,55 +33,97 @@ function buildPageItems(page: number, pageCount: number): Array<number | '…'>
return items
}
-/** 统一分页控件 */
+/** 统一分页控件:页码导航 + 可选每页条数 + 摘要 */
export default function Pagination({
page,
pageCount,
onChange,
+ total,
+ pageSize,
+ pageSizeOptions = DEFAULT_PAGE_SIZE_OPTIONS,
+ onPageSizeChange,
className,
ariaLabel = '分页',
+ showSummary = true,
}: Props) {
- if (pageCount <= 1) return null
+ const sizeOptions = onPageSizeChange ? pageSizeOptions : undefined
+ const canPickSize = Boolean(sizeOptions?.length && pageSize && onPageSizeChange)
+ const showNav = pageCount > 1
+ const summaryVisible = showSummary && total != null && total >= 0
+
+ if (!showNav && !canPickSize && !summaryVisible) return null
const items = buildPageItems(page, pageCount)
return (
- <nav className={cn('pf-pagination', className)} aria-label={ariaLabel}>
- <button
- type="button"
- className="pf-page-btn"
- disabled={page <= 1}
- aria-label="上一页"
- onClick={() => onChange(Math.max(1, page - 1))}
- >
- ‹
- </button>
- {items.map((item, i) =>
- item === '…' ? (
- <span key={`e-${i}`} className="pf-page-ellipsis">
- …
- </span>
- ) : (
- <button
- key={item}
- type="button"
- className={cn('pf-page-btn', page === item && 'active')}
- aria-current={page === item ? 'page' : undefined}
- onClick={() => onChange(item)}
- >
- {item}
- </button>
- ),
+ <div className={cn('pf-list-pagination', className)}>
+ {summaryVisible ? (
+ <p className="pf-list-pagination-summary">
+ 第 {page} / {pageCount} 页 · 共 {total} 条
+ </p>
+ ) : null}
+
+ {(showNav || canPickSize) && (
+ <div className="pf-list-pagination-bar">
+ {canPickSize ? (
+ <label className="pf-page-size">
+ <span>每页</span>
+ <select
+ value={pageSize}
+ aria-label="每页条数"
+ onChange={(e) => onPageSizeChange?.(Number(e.target.value))}
+ >
+ {sizeOptions!.map((n) => (
+ <option key={n} value={n}>
+ {n}
+ </option>
+ ))}
+ </select>
+ <span>条</span>
+ </label>
+ ) : null}
+
+ {showNav ? (
+ <nav className="pf-pagination" aria-label={ariaLabel}>
+ <button
+ type="button"
+ className="pf-page-btn"
+ disabled={page <= 1}
+ aria-label="上一页"
+ onClick={() => onChange(Math.max(1, page - 1))}
+ >
+ ‹
+ </button>
+ {items.map((item, i) =>
+ item === '…' ? (
+ <span key={`e-${i}`} className="pf-page-ellipsis">
+ …
+ </span>
+ ) : (
+ <button
+ key={item}
+ type="button"
+ className={cn('pf-page-btn', page === item && 'active')}
+ aria-current={page === item ? 'page' : undefined}
+ onClick={() => onChange(item)}
+ >
+ {item}
+ </button>
+ ),
+ )}
+ <button
+ type="button"
+ className="pf-page-btn"
+ disabled={page >= pageCount}
+ aria-label="下一页"
+ onClick={() => onChange(Math.min(pageCount, page + 1))}
+ >
+ ›
+ </button>
+ </nav>
+ ) : null}
+ </div>
)}
- <button
- type="button"
- className="pf-page-btn"
- disabled={page >= pageCount}
- aria-label="下一页"
- onClick={() => onChange(Math.min(pageCount, page + 1))}
- >
- ›
- </button>
- </nav>
+ </div>
)
}
diff --git a/frontend/src/lib/composeEpisodeVideoClient.ts b/frontend/src/lib/composeEpisodeVideoClient.ts
index 9d347ee..c646717 100644
--- a/frontend/src/lib/composeEpisodeVideoClient.ts
+++ b/frontend/src/lib/composeEpisodeVideoClient.ts
@@ -59,7 +59,7 @@ export async function composeEpisodeVideoClient(
if (clips.length === 1) {
const single = buffers[0]
- return new Blob([single], { type: 'video/mp4' })
+ return new Blob([copyToArrayBuffer(single)], { type: 'video/mp4' })
}
onProgress?.({ phase: 'concat', done: 0, total: clips.length })
@@ -80,5 +80,12 @@ export async function composeEpisodeVideoClient(
}
const merged = concatMp4(buffers)
onProgress?.({ phase: 'concat', done: clips.length, total: clips.length })
- return new Blob([merged], { type: 'video/mp4' })
+ return new Blob([copyToArrayBuffer(merged)], { type: 'video/mp4' })
+}
+
+// 拷成独立 ArrayBuffer,避免 Uint8Array 视图在 TS 里不能当 BlobPart
+function copyToArrayBuffer(bytes: Uint8Array): ArrayBuffer {
+ const copy = new ArrayBuffer(bytes.byteLength)
+ new Uint8Array(copy).set(bytes)
+ return copy
}
diff --git a/frontend/src/lib/dramaAssetImage.ts b/frontend/src/lib/dramaAssetImage.ts
new file mode 100644
index 0000000..557ea1c
--- /dev/null
+++ b/frontend/src/lib/dramaAssetImage.ts
@@ -0,0 +1,44 @@
+/** 漫剧资产是否已有形象图(AI 生成或本地上传) */
+import type { DramaAsset } from '../api/drama'
+
+// 从 params 中读取可能存在的预览 URL(画布同步等)
+function readParamsMediaUrl(asset: DramaAsset): string {
+ const params = asset.params
+ if (!params || typeof params !== 'object') return ''
+ const record = params as Record<string, unknown>
+ for (const key of ['mediaUrl', 'previewUrl', 'imageUrl']) {
+ const value = String(record[key] || '').trim()
+ if (value) return value
+ }
+ const gen = record.generation
+ if (gen && typeof gen === 'object') {
+ const g = gen as Record<string, unknown>
+ for (const key of ['cover', 'url', 'imageUrl']) {
+ const value = String(g[key] || '').trim()
+ if (value) return value
+ }
+ }
+ return ''
+}
+
+// 资产是否已有有效形象图
+export function dramaAssetHasImage(asset: DramaAsset): boolean {
+ if ((asset.cover || '').trim() || (asset.url || '').trim()) return true
+ return Boolean(readParamsMediaUrl(asset))
+}
+
+// 是否仍需生图(无图且非纯音频类资产时可批量入队)
+export function dramaAssetNeedsImageGeneration(asset: DramaAsset): boolean {
+ const kind = (asset.type || '').toLowerCase()
+ if (['voice', 'video', 'audio', 'text'].includes(kind)) return false
+ return !dramaAssetHasImage(asset)
+}
+
+// 卡片/弹窗生图按钮文案(queueLabel 为排队态文案,有值时优先)
+export function dramaAssetImageGenButtonLabel(
+ asset: DramaAsset,
+ queueLabel: string | null,
+): string {
+ if (queueLabel) return queueLabel
+ return dramaAssetHasImage(asset) ? '重新生成形象' : '生成形象'
+}
diff --git a/frontend/src/lib/legalContent.ts b/frontend/src/lib/legalContent.ts
new file mode 100644
index 0000000..b5c2d9a
--- /dev/null
+++ b/frontend/src/lib/legalContent.ts
@@ -0,0 +1,193 @@
+/** 法律与联系页文案:用户协议、隐私政策、联系渠道 */
+
+export type LegalSection = {
+ title: string
+ paragraphs?: string[]
+ bullets?: string[]
+}
+
+export type LegalDoc = {
+ slug: 'terms' | 'privacy'
+ title: string
+ updatedAt: string
+ intro: string
+ sections: LegalSection[]
+}
+
+export const LEGAL_DOCS: Record<'terms' | 'privacy', LegalDoc> = {
+ terms: {
+ slug: 'terms',
+ title: '用户协议',
+ updatedAt: '2026-08-17',
+ intro:
+ '欢迎使用 PRINTFILM(以下简称「本平台」)。在注册或使用本平台服务前,请仔细阅读本协议。一旦您开始使用,即视为已阅读并同意以下条款。',
+ sections: [
+ {
+ title: '1. 服务说明',
+ paragraphs: [
+ 'PRINTFILM 提供 AI 漫剧、科普视频及创作工具(含文生图、图生图、文生视频等)相关服务。服务内容可能随产品迭代调整,我们将尽可能在页面或公告中说明重大变更。',
+ '本平台按实际上游模型用量计费,余额充值后永久有效,不设强制订阅。具体价格与赠送规则以定价页及下单时展示为准。',
+ ],
+ },
+ {
+ title: '2. 账号与安全',
+ bullets: [
+ '您应使用真实、有效的信息进行注册,并对账号下的全部行为负责。',
+ '请妥善保管登录凭证;因账号泄露、共用导致的损失,由您自行承担。',
+ '如发现未经授权的使用,请及时通过「联系我们」告知我们。',
+ '我们有权在发现违规、欺诈或滥用时限制、冻结或注销相关账号。',
+ ],
+ },
+ {
+ title: '3. 内容与知识产权',
+ paragraphs: [
+ '您输入的提示词、脚本、素材等仍归您或原权利人所有。您保证对上传内容拥有合法权利,不得侵犯第三方知识产权、肖像权、隐私权等。',
+ '使用 AI 生成的内容可能存在不准确、不完整或与预期不符的情况,请在正式发布前自行审核。因您对外发布、商用使用生成内容引发的纠纷,由您自行负责。',
+ '本平台的界面、商标、软件与文档等知识产权归 PRINTFILM 或相关权利人所有,未经许可不得复制、反向工程或用于与本服务无关的商业用途。',
+ ],
+ },
+ {
+ title: '4. 计费与充值',
+ bullets: [
+ '生成类任务按上游 token 或约定单价计费;开始任务时可能预扣估算金额,结束后按实际用量结算(多退少补)。',
+ '充值通过支付宝、微信支付等渠道完成,到账以系统记录为准。',
+ '除法律法规另有规定或本平台明确约定外,已到账的充值余额一般不予退款。',
+ '若因系统故障导致重复扣款或未到账,请保留订单号并联系客服核实处理。',
+ ],
+ },
+ {
+ title: '5. 禁止行为',
+ bullets: [
+ '利用本服务制作、传播违法、色情、暴力、仇恨、欺诈或侵犯他人权益的内容。',
+ '对平台进行攻击、爬取、绕过计费、滥用接口或干扰其他用户。',
+ '未经授权转售账号、批量注册或从事其他损害平台公平运营的行为。',
+ ],
+ },
+ {
+ title: '6. 免责与责任限制',
+ paragraphs: [
+ '在法律允许的范围内,本平台对因网络故障、第三方服务中断、不可抗力导致的服务中断或数据损失不承担责任。',
+ 'AI 输出仅为辅助创作工具,不构成专业建议。因依赖生成内容造成的直接或间接损失,本平台不承担超出您已支付服务费范围以外的责任(法律另有强制规定的除外)。',
+ ],
+ },
+ {
+ title: '7. 协议变更与终止',
+ paragraphs: [
+ '我们可能适时修订本协议,修订后的版本将在本页面公布,并以「更新日期」为准。若您继续使用服务,视为接受修订后的协议。',
+ '您可随时停止使用并申请注销账号;我们也可在您严重违反本协议时终止向您提供服务。',
+ ],
+ },
+ {
+ title: '8. 联系方式',
+ paragraphs: [
+ '如对本协议有疑问,请前往「联系我们」页面提交反馈,或发送邮件至 [email protected]。',
+ ],
+ },
+ ],
+ },
+ privacy: {
+ slug: 'privacy',
+ title: '隐私政策',
+ updatedAt: '2026-08-17',
+ intro:
+ 'PRINTFILM 重视您的隐私。本政策说明我们如何收集、使用、存储与保护您的个人信息。使用本平台即表示您理解本政策所述处理方式。',
+ sections: [
+ {
+ title: '1. 我们收集的信息',
+ bullets: [
+ '账号信息:注册邮箱、昵称、头像、登录与鉴权相关数据。',
+ '使用数据:创作项目、提示词、生成任务状态、工具运行记录、资产库内容等业务数据。',
+ '计费信息:余额、冻结金额、充值订单、用量与扣费明细(支付由第三方渠道完成,我们不存储完整银行卡号等敏感支付信息)。',
+ '技术日志:IP、浏览器类型、访问时间等用于安全与故障排查的必要日志。',
+ ],
+ },
+ {
+ title: '2. 信息的使用目的',
+ bullets: [
+ '提供、维护与改进漫剧、科普与工具等创作服务。',
+ '完成身份验证、计费结算、订单查询与客服支持。',
+ '保障账号与系统安全,防范欺诈与滥用。',
+ '在获得同意或法律法规允许的情况下,向您发送服务通知或产品更新。',
+ ],
+ },
+ {
+ title: '3. 存储与第三方',
+ paragraphs: [
+ '您的媒体与创作文件可能存储于云端对象存储(如阿里云 OSS),以便预览与下载。',
+ '支付由易支付等合作方处理;大模型推理由上游模型服务商完成。我们仅向其提供完成服务所必需的数据,并要求其按约定保护信息。',
+ '除法律法规要求、获得您明确同意,或为保护本平台及用户合法权益所必需外,我们不会向无关第三方出售您的个人信息。',
+ ],
+ },
+ {
+ title: '4. Cookie 与本地存储',
+ paragraphs: [
+ '为维持登录态与偏好设置,我们可能使用 Cookie 或浏览器本地存储(如 token)。您可在浏览器中清除,但这可能导致需要重新登录。',
+ ],
+ },
+ {
+ title: '5. 您的权利',
+ bullets: [
+ '查阅、更正账号资料(可在个人中心操作)。',
+ '导出或下载您有权访问的创作成果(在产品功能允许范围内)。',
+ '申请注销账号;注销后我们将按法规要求删除或匿名化相关个人信息,法律法规要求保留的除外。',
+ '对隐私相关问题进行咨询或投诉。',
+ ],
+ },
+ {
+ title: '6. 未成年人保护',
+ paragraphs: [
+ '本平台主要面向具备完全民事行为能力的用户。若您为未成年人,请在监护人指导下阅读本政策并使用服务。',
+ ],
+ },
+ {
+ title: '7. 政策更新',
+ paragraphs: [
+ '我们可能更新本政策,并在本页公布最新版本与更新日期。重大变更时,我们会通过站内提示等方式尽量告知。',
+ ],
+ },
+ {
+ title: '8. 联系我们',
+ paragraphs: [
+ '如对本政策有任何疑问,请访问「联系我们」或发送邮件至 [email protected]。',
+ ],
+ },
+ ],
+ },
+}
+
+export type ContactChannel = {
+ title: string
+ desc: string
+ href?: string
+ actionLabel?: string
+}
+
+export const CONTACT_CHANNELS: ContactChannel[] = [
+ {
+ 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%20企业合作',
+ actionLabel: '发送合作邮件',
+ },
+]
+
+export const CONTACT_TOPICS = [
+ '账号与登录',
+ '充值与到账',
+ '创作任务异常',
+ '下载与素材',
+ '隐私与账号注销',
+ '其他',
+] as const
diff --git a/frontend/src/lib/pagination.ts b/frontend/src/lib/pagination.ts
new file mode 100644
index 0000000..9a3455f
--- /dev/null
+++ b/frontend/src/lib/pagination.ts
@@ -0,0 +1,7 @@
+/** 全局分页默认每页条数选项 */
+export const DEFAULT_PAGE_SIZE_OPTIONS = [5, 8, 12, 20] as const
+
+/** 根据总数与每页条数计算页数 */
+export function pageCountOf(total: number, pageSize: number) {
+ return Math.max(1, Math.ceil(Math.max(0, total) / Math.max(1, pageSize)))
+}
diff --git a/frontend/src/lib/segmentDuration.ts b/frontend/src/lib/segmentDuration.ts
index 61ce61e..f1e1a80 100644
--- a/frontend/src/lib/segmentDuration.ts
+++ b/frontend/src/lib/segmentDuration.ts
@@ -18,8 +18,8 @@ export const SEGMENT_DURATION_PRESETS = [4, 6, 8, 10, 12] as const
/** 与后端一致的字幕 cue */
export const SUBTITLE_CUE = '【字幕:全程简体中文字幕,旁白逐句同步烧录】'
-/** 与后端一致的旁白前缀 */
-export const NARRATION_PREFIX = '【旁白·慢速清晰·同步字幕】'
+/** 与后端一致的旁白前缀(科普自然偏快;旧稿「慢速清晰」仍可识别) */
+export const NARRATION_PREFIX = '【旁白·自然语速·同步字幕】'
/** 脚本编辑区 placeholder */
export const SEGMENT_SCRIPT_PLACEHOLDER = `${SUBTITLE_CUE}\n【BGM:轻快专业,音量低于人声】\n@duration:4\n过肩工位操作画面…\n@duration:8\n${NARRATION_PREFIX}口播内容…`
@@ -144,3 +144,109 @@ export function parseSegmentScript(script: string | undefined | null): {
return { cues, beats }
}
+
+const NARRATION_LINE_PREFIX = /^【旁白[^】]*】/
+
+/** 脚本行是否为旁白口播(字幕 cue 含「旁白」二字但不算) */
+export function isNarrationScriptLine(line: string): boolean {
+ const stripped = line.trim()
+ if (stripped.startsWith('【字幕') || stripped.startsWith('【BGM')) return false
+ return NARRATION_LINE_PREFIX.test(stripped)
+}
+
+/** 去掉旁白前缀,得到可朗读正文 */
+export function stripNarrationPrefix(line: string): string {
+ return line.trim().replace(NARRATION_LINE_PREFIX, '').trim()
+}
+
+/** 从脚本提取旁白正文(多段拼接) */
+export function narrationFromScript(script: string | undefined | null): string {
+ const parts: string[] = []
+ for (const line of String(script || '').replace(/\r\n/g, '\n').split('\n')) {
+ if (isNarrationScriptLine(line)) {
+ const text = stripNarrationPrefix(line)
+ if (text) parts.push(text)
+ }
+ }
+ return parts.join('')
+}
+
+/** 从脚本提取首段画面(非旁白、非 cue) */
+export function firstVisualFromScript(script: string | undefined | null): string {
+ for (const line of String(script || '').replace(/\r\n/g, '\n').split('\n')) {
+ const stripped = line.trim()
+ if (
+ !stripped ||
+ stripped.startsWith('@duration:') ||
+ stripped.startsWith('【字幕') ||
+ stripped.startsWith('【BGM') ||
+ isNarrationScriptLine(stripped)
+ ) {
+ continue
+ }
+ return stripped.replace(/^【[^】]*】/, '').trim() || stripped
+ }
+ return ''
+}
+
+/** 把弹窗旁白写回脚本中的旁白段 */
+export function replaceNarrationInScript(script: string, narration: string): string {
+ const text = narration.trim()
+ const lines = String(script || '').replace(/\r\n/g, '\n').split('\n')
+ const out: string[] = []
+ let replaced = false
+ for (const raw of lines) {
+ const stripped = raw.trim()
+ if (text && isNarrationScriptLine(stripped) && !replaced) {
+ const prefix = stripped.match(NARRATION_LINE_PREFIX)?.[0] || NARRATION_PREFIX
+ out.push(`${prefix}${text}`)
+ replaced = true
+ continue
+ }
+ out.push(raw.replace(/\s+$/, ''))
+ }
+ if (text && !replaced) {
+ out.push('@duration:6')
+ out.push(`${NARRATION_PREFIX}${text}`)
+ }
+ return out.join('\n').trim()
+}
+
+/** 把弹窗首帧画面写回脚本第一段 visual */
+export function replaceFirstVisualInScript(script: string, visual: string): string {
+ const text = visual.trim()
+ if (!text) return String(script || '').trim()
+ const lines = String(script || '').replace(/\r\n/g, '\n').split('\n')
+ const out: string[] = []
+ let replaced = false
+ let cueEnd = 0
+ for (let i = 0; i < lines.length; i += 1) {
+ const stripped = lines[i].trim()
+ if (stripped.startsWith('【字幕') || stripped.startsWith('【BGM') || !stripped) {
+ cueEnd = i + 1
+ continue
+ }
+ break
+ }
+ for (const raw of lines) {
+ const stripped = raw.trim()
+ if (
+ !replaced &&
+ stripped &&
+ !stripped.startsWith('@duration:') &&
+ !stripped.startsWith('【字幕') &&
+ !stripped.startsWith('【BGM') &&
+ !isNarrationScriptLine(stripped)
+ ) {
+ out.push(text)
+ replaced = true
+ continue
+ }
+ out.push(raw.replace(/\s+$/, ''))
+ }
+ if (!replaced) {
+ const extra = [`@duration:${SEGMENT_DURATION_MIN}`, text]
+ return [...out.slice(0, cueEnd), ...extra, ...out.slice(cueEnd)].join('\n').trim()
+ }
+ return out.join('\n').trim()
+}
diff --git a/frontend/src/lib/userEvents.ts b/frontend/src/lib/userEvents.ts
new file mode 100644
index 0000000..e8ef7b6
--- /dev/null
+++ b/frontend/src/lib/userEvents.ts
@@ -0,0 +1,8 @@
+import type { User } from '../api'
+
+export const USER_UPDATED_EVENT = 'pf-user-updated'
+
+/** 广播用户资料变更,供顶栏等组件同步头像 */
+export function dispatchUserUpdated(user: User) {
+ window.dispatchEvent(new CustomEvent(USER_UPDATED_EVENT, { detail: user }))
+}
diff --git a/frontend/src/pages/ContactPage.tsx b/frontend/src/pages/ContactPage.tsx
new file mode 100644
index 0000000..7a9add4
--- /dev/null
+++ b/frontend/src/pages/ContactPage.tsx
@@ -0,0 +1,138 @@
+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'
+
+const CHANNEL_ICONS = [Mail, HelpCircle, Building2] as const
+
+/** 联系我们:渠道说明 + 本地反馈表单(引导发邮件) */
+export default function ContactPage() {
+ /*
+ * topic 反馈主题
+ * email 联系邮箱
+ * message 问题描述
+ * sent 是否已生成邮件草稿提示
+ */
+ const [topic, setTopic] = useState<string>(CONTACT_TOPICS[0])
+ const [email, setEmail] = useState('')
+ const [message, setMessage] = useState('')
+ const [sent, setSent] = useState(false)
+
+ function onSubmit(e: FormEvent) {
+ e.preventDefault()
+ const body = [
+ `主题:${topic}`,
+ `联系邮箱:${email.trim() || '(未填写)'}`,
+ '',
+ message.trim() || '(无详细描述)',
+ ].join('\n')
+ const href = `mailto:[email protected]?subject=${encodeURIComponent(
+ `[PRINTFILM] ${topic}`,
+ )}&body=${encodeURIComponent(body)}`
+ window.location.href = href
+ setSent(true)
+ }
+
+ return (
+ <AppShell>
+ <div className="pf-legal-page pf-contact-page">
+ <header className="pf-legal-hero">
+ <p className="pf-legal-crumb">
+ <Link to="/">首页</Link>
+ <span aria-hidden> / </span>
+ <span>联系我们</span>
+ </p>
+ <h1>联系我们</h1>
+ <p className="pf-legal-intro">
+ 充值、账号、创作任务或合作咨询,欢迎通过以下方式联系。提交前也可先查看{' '}
+ <Link to="/help">帮助中心</Link>。
+ </p>
+ </header>
+
+ <div className="pf-contact-channels">
+ {CONTACT_CHANNELS.map((ch, i) => {
+ const Icon = CHANNEL_ICONS[i] || Mail
+ const isExternal = ch.href?.startsWith('mailto:')
+ return (
+ <article key={ch.title} className="pf-contact-card">
+ <span className="pf-contact-card-icon" aria-hidden>
+ <Icon size={22} strokeWidth={1.8} />
+ </span>
+ <h2>{ch.title}</h2>
+ <p>{ch.desc}</p>
+ {ch.href ? (
+ isExternal ? (
+ <a className="pf-contact-card-link" href={ch.href}>
+ {ch.actionLabel || '联系'}
+ </a>
+ ) : (
+ <Link className="pf-contact-card-link" to={ch.href}>
+ {ch.actionLabel || '前往'}
+ </Link>
+ )
+ ) : null}
+ </article>
+ )
+ })}
+ </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>
+
+ <form className="pf-contact-form" onSubmit={onSubmit}>
+ <label>
+ <span>问题类型</span>
+ <select value={topic} onChange={(e) => setTopic(e.target.value)}>
+ {CONTACT_TOPICS.map((t) => (
+ <option key={t} value={t}>
+ {t}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label>
+ <span>联系邮箱</span>
+ <input
+ type="email"
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ placeholder="便于我们回复"
+ autoComplete="email"
+ />
+ </label>
+ <label>
+ <span>问题描述</span>
+ <textarea
+ value={message}
+ onChange={(e) => setMessage(e.target.value)}
+ rows={5}
+ placeholder="请尽量说明账号邮箱、订单号、发生时间与报错信息"
+ required
+ />
+ </label>
+ <button type="submit" className="pf-btn pf-btn-lime">
+ 打开邮件草稿
+ </button>
+ {sent ? (
+ <p className="pf-contact-sent pf-muted">
+ 若未自动打开邮件客户端,请直接发送至{' '}
+ <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>
+ </div>
+ </AppShell>
+ )
+}
diff --git a/frontend/src/pages/HelpPage.tsx b/frontend/src/pages/HelpPage.tsx
index 6c61180..02d52c4 100644
--- a/frontend/src/pages/HelpPage.tsx
+++ b/frontend/src/pages/HelpPage.tsx
@@ -89,7 +89,9 @@ export default function HelpPage() {
<p className="pf-muted">
更多操作可在{' '}
<Link to="/settings">个人中心</Link> 查看项目与创作记录,或前往{' '}
- <Link to="/pricing">定价</Link> 充值后继续创作。
+ <Link to="/pricing">定价</Link> 充值后继续创作。也可查阅{' '}
+ <Link to="/terms">用户协议</Link>、<Link to="/privacy">隐私政策</Link>,或{' '}
+ <Link to="/contact">联系我们</Link>。
</p>
</section>
</div>
diff --git a/frontend/src/pages/HistoryPage.tsx b/frontend/src/pages/HistoryPage.tsx
index 7ef590d..3b4e4c5 100644
--- a/frontend/src/pages/HistoryPage.tsx
+++ b/frontend/src/pages/HistoryPage.tsx
@@ -4,6 +4,7 @@ import { api } from '../api'
import type { Project } from '../api'
import AppShell from '../components/layout/AppShell'
import PillTabs from '../components/ui/PillTabs'
+import Pagination from '../components/ui/Pagination'
import StatCard from '../components/ui/StatCard'
import {
IconClapper,
@@ -25,6 +26,7 @@ import {
zipVideosClient,
} from '../lib/clientDownload'
import { isRunning, STATUS_CN, statusTone } from '../lib/status'
+import { pageCountOf } from '../lib/pagination'
type HistoryItem = Omit<Project, 'shots'> & {
published?: boolean
@@ -35,7 +37,7 @@ type HistoryItem = Omit<Project, 'shots'> & {
updated_at?: string
}
-const PAGE_SIZE = 8
+const PAGE_SIZE_DEFAULT = 8
const TAB_STATUS: Record<string, 'all' | 'draft' | 'running' | 'done' | 'published'> = {
全部: 'all',
@@ -82,6 +84,7 @@ export default function HistoryPage() {
* q 搜索框
* debouncedQ 防抖后的搜索词
* page 页码
+ * pageSize 每页条数
* preview 预览弹层
*/
const [items, setItems] = useState<HistoryItem[]>([])
@@ -99,6 +102,7 @@ export default function HistoryPage() {
const [q, setQ] = useState('')
const [debouncedQ, setDebouncedQ] = useState('')
const [page, setPage] = useState(1)
+ const [pageSize, setPageSize] = useState(PAGE_SIZE_DEFAULT)
const [preview, setPreview] = useState<{
url: string
title: string
@@ -120,7 +124,7 @@ export default function HistoryPage() {
try {
const res = await api.listProjects({
page,
- page_size: PAGE_SIZE,
+ page_size: pageSize,
status: TAB_STATUS[tab] || 'all',
q: debouncedQ,
pipeline_mode: typeMode,
@@ -156,7 +160,7 @@ export default function HistoryPage() {
setLoading(true)
load().catch(() => undefined)
// eslint-disable-next-line react-hooks/exhaustive-deps -- intentional reload keys
- }, [page, tab, typeMode, debouncedQ])
+ }, [page, pageSize, tab, typeMode, debouncedQ])
useEffect(() => {
if (!hasRunning) return
@@ -165,13 +169,13 @@ export default function HistoryPage() {
}, 2000)
return () => clearInterval(timer)
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [hasRunning, page, tab, typeMode, debouncedQ])
+ }, [hasRunning, page, pageSize, tab, typeMode, debouncedQ])
useEffect(() => {
setPage(1)
- }, [tab, debouncedQ, typeMode])
+ }, [tab, debouncedQ, typeMode, pageSize])
- const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE))
+ const pageCount = pageCountOf(total, pageSize)
const pageItems = items
// 筛选后若当前页超出范围则回退
@@ -276,20 +280,6 @@ export default function HistoryPage() {
else nav(`/studio/${p.id}`)
}
- function pageButtons() {
- const buttons: (number | '…')[] = []
- if (pageCount <= 7) {
- for (let i = 1; i <= pageCount; i++) buttons.push(i)
- return buttons
- }
- buttons.push(1)
- if (page > 3) buttons.push('…')
- for (let i = Math.max(2, page - 1); i <= Math.min(pageCount - 1, page + 1); i++) buttons.push(i)
- if (page < pageCount - 2) buttons.push('…')
- buttons.push(pageCount)
- return buttons
- }
-
return (
<AppShell active="kepu" wide>
<div className="pf-history-head">
@@ -490,40 +480,18 @@ export default function HistoryPage() {
</div>
{total > 0 ? (
- <div className="pf-pagination">
- <button
- type="button"
- className="pf-page-btn"
- disabled={page <= 1}
- onClick={() => setPage((p) => Math.max(1, p - 1))}
- >
- ‹
- </button>
- {pageButtons().map((b, i) =>
- b === '…' ? (
- <span key={`e-${i}`} className="pf-page-ellipsis">
- …
- </span>
- ) : (
- <button
- key={b}
- type="button"
- className={page === b ? 'pf-page-btn active' : 'pf-page-btn'}
- onClick={() => setPage(b)}
- >
- {b}
- </button>
- ),
- )}
- <button
- type="button"
- className="pf-page-btn"
- disabled={page >= pageCount}
- onClick={() => setPage((p) => Math.min(pageCount, p + 1))}
- >
- ›
- </button>
- </div>
+ <Pagination
+ page={page}
+ pageCount={pageCount}
+ total={total}
+ pageSize={pageSize}
+ onPageSizeChange={(size) => {
+ setPageSize(size)
+ setPage(1)
+ }}
+ onChange={setPage}
+ ariaLabel="科普历史分页"
+ />
) : null}
</section>
</div>
diff --git a/frontend/src/pages/HomePage.tsx b/frontend/src/pages/HomePage.tsx
index 181e955..03fd40a 100644
--- a/frontend/src/pages/HomePage.tsx
+++ b/frontend/src/pages/HomePage.tsx
@@ -216,6 +216,9 @@ export default function HomePage() {
<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>
<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.tsx
new file mode 100644
index 0000000..86f5bee
--- /dev/null
+++ b/frontend/src/pages/LegalDocPage.tsx
@@ -0,0 +1,68 @@
+import { Link } from 'react-router-dom'
+import AppShell from '../components/layout/AppShell'
+import { LEGAL_DOCS, type LegalDoc } from '../lib/legalContent'
+
+/** 渲染单份法律文档正文 */
+function LegalBody({ doc }: { doc: LegalDoc }) {
+ return (
+ <article className="pf-legal-doc">
+ <header className="pf-legal-hero">
+ <p className="pf-legal-crumb">
+ <Link to="/">首页</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-intro">{doc.intro}</p>
+ </header>
+
+ <div className="pf-legal-sections">
+ {doc.sections.map((sec) => (
+ <section key={sec.title} className="pf-legal-section">
+ <h2>{sec.title}</h2>
+ {sec.paragraphs?.map((p) => (
+ <p key={p.slice(0, 32)}>{p}</p>
+ ))}
+ {sec.bullets?.length ? (
+ <ul>
+ {sec.bullets.map((b) => (
+ <li key={b.slice(0, 32)}>{b}</li>
+ ))}
+ </ul>
+ ) : null}
+ </section>
+ ))}
+ </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>
+ </article>
+ )
+}
+
+/** 用户协议页 */
+export function TermsPage() {
+ return (
+ <AppShell>
+ <div className="pf-legal-page">
+ <LegalBody doc={LEGAL_DOCS.terms} />
+ </div>
+ </AppShell>
+ )
+}
+
+/** 隐私政策页 */
+export function PrivacyPage() {
+ return (
+ <AppShell>
+ <div className="pf-legal-page">
+ <LegalBody doc={LEGAL_DOCS.privacy} />
+ </div>
+ </AppShell>
+ )
+}
diff --git a/frontend/src/pages/PricingPage.tsx b/frontend/src/pages/PricingPage.tsx
index f304930..22ce2b0 100644
--- a/frontend/src/pages/PricingPage.tsx
+++ b/frontend/src/pages/PricingPage.tsx
@@ -1,25 +1,30 @@
import { useEffect, useMemo, useState } from 'react'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
+import {
+ Building2,
+ Check,
+ CreditCard,
+ Infinity,
+ ShieldCheck,
+ Zap,
+} from 'lucide-react'
import AppShell from '../components/layout/AppShell'
-import MonthlyUsageCard from '../components/billing/MonthlyUsageCard'
+import PaymentBrandIcon from '../components/billing/PaymentBrandIcon'
import PaymentModal, { type PayCheckout } from '../components/billing/PaymentModal'
+import PricingWalletCard from '../components/billing/PricingWalletCard'
import TopupHistoryModal from '../components/billing/TopupHistoryModal'
-import { api, type BillingSku, type Wallet } from '../api'
+import { api, type BillingSku, type UsageSummary, type Wallet } from '../api'
type PayType = 'alipay' | 'wxpay'
type SkuView = BillingSku & { recommended?: boolean }
-function yuan(fen: number) {
- return (fen / 100).toFixed(2)
-}
-
-function yuanShort(fen: number) {
- const v = fen / 100
- return Number.isInteger(v) ? String(v) : v.toFixed(2)
-}
+const HERO_FEATURES = [
+ { icon: Zap, text: '充值即时到账,马上可用' },
+ { icon: ShieldCheck, text: '支付安全保障' },
+ { icon: Infinity, text: '余额永久有效' },
+] as const
-/** Prefer design labels even if API still returns legacy names. */
const SKU_LABELS: Record<string, string> = {
topup_10: '体验充值',
topup_49: '基础充值',
@@ -27,24 +32,35 @@ const SKU_LABELS: Record<string, string> = {
topup_199: '专业充值',
}
-function planLabel(wallet: Wallet | null) {
- if (!wallet) return 'Free'
- if (wallet.billing_unlimited) return 'Unlimited'
- const p = (wallet.plan || 'free').toLowerCase()
- if (p === 'free') return 'Free'
- if (p === 'pro') return 'Pro'
- return wallet.plan
+const SKU_HINTS: Record<string, string> = {
+ topup_10: '适合初次体验',
+ topup_49: '日常创作够用',
+ topup_99: '高频创作推荐',
+ topup_199: '团队 / 批量生产',
+}
+
+function yuan(fen: number) {
+ return (fen / 100).toFixed(2)
}
+function yuanShort(fen: number) {
+ const v = fen / 100
+ return Number.isInteger(v) ? String(v) : v.toFixed(2)
+}
+
+/** 定价与充值页 */
export default function PricingPage() {
const nav = useNavigate()
const [params] = useSearchParams()
const [wallet, setWallet] = useState<Wallet | null>(null)
+ const [usage, setUsage] = useState<UsageSummary | null>(null)
+ const [updatedAt, setUpdatedAt] = useState<Date | null>(null)
const [skus, setSkus] = useState<SkuView[]>([])
const [payType, setPayType] = useState<PayType>('alipay')
const [busy, setBusy] = useState<string | null>(null)
const [error, setError] = useState('')
const [hint, setHint] = useState('')
+ const [payTip, setPayTip] = useState('')
const [checkout, setCheckout] = useState<PayCheckout | null>(null)
const [historyOpen, setHistoryOpen] = useState(false)
const loggedIn = Boolean(localStorage.getItem('token'))
@@ -59,10 +75,15 @@ export default function PricingPage() {
async function refresh() {
if (!loggedIn) {
setWallet(null)
+ setUsage(null)
+ setUpdatedAt(null)
return
}
try {
- setWallet(await api.wallet())
+ const [w, u] = await Promise.all([api.wallet(), api.usageSummary()])
+ setWallet(w)
+ setUsage(u)
+ setUpdatedAt(new Date())
} catch {
/* ignore */
}
@@ -106,8 +127,13 @@ export default function PricingPage() {
}
}
- function closeCheckout() {
- setCheckout(null)
+ function pickPay(type: PayType) {
+ setPayType(type)
+ setPayTip('')
+ }
+
+ function pickUnavailable(label: string) {
+ setPayTip(`${label}即将上线,请先使用支付宝或微信支付`)
}
async function onPaid() {
@@ -116,152 +142,207 @@ export default function PricingPage() {
await refresh()
}
- const balanceYuan = wallet?.balance_yuan ?? 0
- const frozenYuan = wallet?.frozen_yuan ?? 0
-
return (
- <AppShell active="pricing">
+ <AppShell active="pricing" hideFooter wide>
<div className="pf-pricing-page">
- <section className="pf-pricing-hero">
- <div className="pf-pricing-hero-copy">
- <span className="pf-pricing-pill">简单透明 · 按量计费</span>
- <h1>按需充值,用多少算多少</h1>
- <p>按上游模型 token 实际用量计费,余额永久有效,无订阅、无隐藏费用。</p>
- </div>
-
- <div className="pf-pricing-balance-card">
- <div className="pf-pricing-balance-main">
- <span className="pf-pricing-balance-label">可用余额</span>
- <strong>¥{balanceYuan.toFixed(2)}</strong>
+ <section className="pf-pricing-hero-band">
+ <div className="pf-pricing-hero-inner">
+ <div className="pf-pricing-hero-copy">
+ <h1>按需充值,灵活使用</h1>
+ <p>按实际消耗 token 计费,余量永久有效,不设过期</p>
+ <ul className="pf-pricing-hero-features">
+ {HERO_FEATURES.map(({ icon: Icon, text }) => (
+ <li key={text}>
+ <span className="pf-pricing-hero-feature-icon" aria-hidden>
+ <Icon size={15} strokeWidth={2.2} />
+ </span>
+ {text}
+ </li>
+ ))}
+ </ul>
+ {!loggedIn ? (
+ <p className="pf-pricing-guest-tip">
+ <Link to="/auth?next=%2Fpricing">登录</Link> 后查看余额与本月用量
+ </p>
+ ) : null}
</div>
- <div className="pf-pricing-balance-side">
- <span className="pf-pricing-balance-label">冻结中</span>
- <em>¥{frozenYuan.toFixed(2)}</em>
- </div>
- <div className="pf-pricing-balance-side">
- <span className="pf-pricing-balance-label">当前套餐</span>
- <em>{planLabel(wallet)}</em>
- </div>
- <button
- type="button"
- className="pf-btn pf-btn-ghost pf-btn-sm"
- disabled={!loggedIn}
- title={loggedIn ? '查看充值记录' : '请先登录'}
- onClick={() => setHistoryOpen(true)}
- >
- 充值记录
- </button>
+ <PricingWalletCard
+ wallet={wallet}
+ usage={usage}
+ loggedIn={loggedIn}
+ updatedAt={updatedAt}
+ onHistory={() => setHistoryOpen(true)}
+ />
</div>
</section>
- {loggedIn ? (
- <section className="pf-pricing-usage" aria-label="本月使用情况">
- <MonthlyUsageCard variant="compact" showTopup={false} />
- </section>
- ) : null}
+ <div className="pf-pricing-body">
+ {hint ? <p className="pf-pricing-hint">{hint}</p> : null}
+ {error ? <p className="pf-error pf-pricing-error">{error}</p> : null}
- {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="支付方式">
+ <header className="pf-pricing-section-head is-row">
+ <h2>支付方式</h2>
+ <div className="pf-pricing-pay-trust">
+ <ShieldCheck size={16} aria-hidden />
+ <span>支付安全保障</span>
+ </div>
+ </header>
- <section className="pf-pricing-skus" id="pricing-skus">
- <header className="pf-pricing-section-head">
- <h2>选择充值金额</h2>
- <p>充值即时到账,赠送金额自动计入余额</p>
- </header>
+ {payTip ? <p className="pf-pricing-pay-tip">{payTip}</p> : null}
- <div className="pf-pricing-sku-grid">
- {displaySkus.map((sku) => {
- const bonus = sku.credit_fen - sku.amount_fen
- const recommended = Boolean(sku.recommended)
- return (
- <article
- key={sku.id}
- id={`sku-${sku.id}`}
- className={`pf-pricing-sku-card${recommended ? ' is-recommended' : ''}`}
- >
- {recommended ? <span className="pf-pricing-rec-badge">推荐</span> : null}
- <h3>{SKU_LABELS[sku.id] || sku.name}</h3>
- <div className="pf-pricing-sku-price">
- <span className="yen">¥</span>
- <strong>{(sku.amount_fen / 100).toFixed(0)}</strong>
- </div>
- <p className="pf-pricing-sku-credit">到账 ¥{yuan(sku.credit_fen)}</p>
- {bonus > 0 ? (
- <p className="pf-pricing-sku-bonus">额外赠送 ¥{yuanShort(bonus)}</p>
- ) : (
- <p className="pf-pricing-sku-bonus is-empty">&nbsp;</p>
- )}
- <button
- type="button"
- className={`pf-pricing-sku-cta${recommended ? ' is-primary' : ''}`}
- disabled={Boolean(busy)}
- onClick={() => pay(sku)}
- >
- {busy === sku.id ? '下单中…' : '立即充值'}
- </button>
- </article>
- )
- })}
- </div>
- </section>
+ <div className="pf-pricing-pay-grid">
+ <button
+ type="button"
+ className={`pf-pricing-pay-tile${payType === 'alipay' ? ' is-active' : ''}`}
+ onClick={() => pickPay('alipay')}
+ 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>
+ {payType === 'alipay' ? (
+ <span className="pf-pricing-pay-tile-check" aria-hidden>
+ <Check size={14} strokeWidth={3} />
+ </span>
+ ) : null}
+ </button>
- <section className="pf-pricing-paybar">
- <div className="pf-pricing-pay-left">
- <span className="pf-pricing-pay-label">支付方式</span>
- <button
- type="button"
- className={`pf-pricing-pay-opt${payType === 'alipay' ? ' is-active' : ''}`}
- onClick={() => setPayType('alipay')}
- >
- <span className="pf-pay-logo alipay" aria-hidden />
- 支付宝
- {payType === 'alipay' ? <span className="pf-pay-check" aria-hidden>✓</span> : null}
- </button>
- <button
- type="button"
- className={`pf-pricing-pay-opt${payType === 'wxpay' ? ' is-active' : ''}`}
- onClick={() => setPayType('wxpay')}
- >
- <span className="pf-pay-logo wxpay" aria-hidden />
- 微信支付
- {payType === 'wxpay' ? <span className="pf-pay-check" aria-hidden>✓</span> : null}
- </button>
- </div>
- <div className="pf-pricing-pay-secure">
- <span className="pf-pay-shield" aria-hidden />
- 支付安全保障
- </div>
- </section>
+ <button
+ type="button"
+ className={`pf-pricing-pay-tile${payType === 'wxpay' ? ' is-active' : ''}`}
+ onClick={() => pickPay('wxpay')}
+ aria-pressed={payType === 'wxpay'}
+ >
+ <PaymentBrandIcon brand="wxpay" size="md" />
+ <span className="pf-pricing-pay-tile-label">微信支付</span>
+ {payType === 'wxpay' ? (
+ <span className="pf-pricing-pay-tile-check" aria-hidden>
+ <Check size={14} strokeWidth={3} />
+ </span>
+ ) : null}
+ </button>
- <section className="pf-pricing-info">
- <div>
- <h3>计费说明</h3>
- <ul>
- <li>拆分镜、出图、配音、AI 视频分别按上游 token 用量计费</li>
- <li>开始生成时预扣估算金额,结束后按实际用量结算(多退少补)</li>
- <li>图文模式成本更低;开启 AI 动态视频时消耗更高</li>
- </ul>
- </div>
- <div>
- <h3>为什么按量计费</h3>
- <ul className="pf-pricing-checks">
- <li>无需订阅,用多少充多少</li>
- <li>余额永久有效,不设过期</li>
- <li>账单清晰可查,每次调用可追溯</li>
- </ul>
- </div>
- </section>
+ <button
+ type="button"
+ className="pf-pricing-pay-tile is-disabled"
+ title="即将上线"
+ onClick={() => pickUnavailable('银联支付')}
+ >
+ <PaymentBrandIcon brand="unionpay" size="md" />
+ <span className="pf-pricing-pay-tile-label">银联支付</span>
+ <span className="pf-pricing-pay-tile-soon">即将上线</span>
+ </button>
+
+ <button
+ type="button"
+ className="pf-pricing-pay-tile is-disabled"
+ title="企业用户请联系客服"
+ onClick={() => pickUnavailable('对公转账')}
+ >
+ <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>
+ </button>
+ </div>
+ </section>
+
+ <section className="pf-pricing-skus" id="pricing-skus">
+ <header className="pf-pricing-section-head">
+ <h2>选择充值金额</h2>
+ </header>
+
+ <div className="pf-pricing-sku-grid">
+ {displaySkus.map((sku) => {
+ const bonus = sku.credit_fen - sku.amount_fen
+ const recommended = Boolean(sku.recommended)
+ const label = SKU_LABELS[sku.id] || sku.name
+ const tierHint = SKU_HINTS[sku.id] || '余额永久有效'
+ return (
+ <article
+ key={sku.id}
+ id={`sku-${sku.id}`}
+ className={`pf-pricing-sku-card${recommended ? ' is-recommended' : ''}`}
+ >
+ {recommended ? <span className="pf-pricing-rec-badge">推荐</span> : null}
+ <p className="pf-pricing-sku-tier">{label}</p>
+ <p className="pf-pricing-sku-hint">{tierHint}</p>
+ <div className="pf-pricing-sku-price">
+ <span className="yen">¥</span>
+ <strong>{(sku.amount_fen / 100).toFixed(0)}</strong>
+ </div>
+ <p className="pf-pricing-sku-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 is-empty">&nbsp;</p>
+ )}
+ <button
+ type="button"
+ className={`pf-pricing-sku-cta${recommended ? ' is-primary' : ''}`}
+ disabled={Boolean(busy)}
+ onClick={() => pay(sku)}
+ >
+ {busy === sku.id ? '下单中…' : '立即充值'}
+ </button>
+ </article>
+ )
+ })}
+ </div>
+ </section>
+
+ <section className="pf-pricing-info">
+ <article className="pf-pricing-info-card">
+ <div className="pf-pricing-info-visual is-billing" aria-hidden>
+ <CreditCard size={28} strokeWidth={1.6} />
+ </div>
+ <div>
+ <h3>计费说明</h3>
+ <ul>
+ <li>拆分镜、出图、配音、AI 视频分别按上游 token 用量计费</li>
+ <li>开始生成时预扣估算金额,结束后按实际用量结算(多退少补)</li>
+ <li>图文模式成本更低;开启 AI 动态视频时消耗更高</li>
+ </ul>
+ </div>
+ </article>
+ <article className="pf-pricing-info-card">
+ <div className="pf-pricing-info-visual is-value" aria-hidden>
+ <Check size={28} strokeWidth={2.5} />
+ </div>
+ <div>
+ <h3>为什么按量计费</h3>
+ <ul className="pf-pricing-checks">
+ <li>无需订阅,用多少充多少</li>
+ <li>余额永久有效,不设过期</li>
+ <li>账单清晰可查,每次调用可追溯</li>
+ </ul>
+ </div>
+ </article>
+ </section>
- <p className="pf-pricing-foot">
- <Link to="/">PRINTFILM</Link>
- <span> · AI 知识视频创作伙伴</span>
- </p>
+ <footer className="pf-pricing-site-foot">
+ <p className="pf-pricing-site-brand">
+ <Link to="/">PRINTFILM</Link>
+ <span> · AI 短视频创作伙伴</span>
+ </p>
+ <nav className="pf-pricing-site-links" aria-label="页脚链接">
+ <Link to="/terms">用户协议</Link>
+ <Link to="/privacy">隐私政策</Link>
+ <Link to="/contact">联系我们</Link>
+ </nav>
+ <p className="pf-pricing-site-copy">© {new Date().getFullYear()} PRINTFILM. All rights reserved.</p>
+ </footer>
+ </div>
</div>
<PaymentModal
open={Boolean(checkout)}
checkout={checkout}
- onClose={closeCheckout}
+ onClose={() => setCheckout(null)}
onPaid={() => void onPaid()}
/>
<TopupHistoryModal open={historyOpen} onClose={() => setHistoryOpen(false)} />
diff --git a/frontend/src/pages/SettingsPage.tsx b/frontend/src/pages/SettingsPage.tsx
index fd37798..9be6528 100644
--- a/frontend/src/pages/SettingsPage.tsx
+++ b/frontend/src/pages/SettingsPage.tsx
@@ -1,9 +1,13 @@
import { useEffect, useState } from 'react'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import AppShell from '../components/layout/AppShell'
+import UserAvatar from '../components/UserAvatar'
import { api, type User, type Wallet } from '../api'
import { dramaApi, type DramaProjectListItem } from '../api/drama'
import MonthlyUsageCard from '../components/billing/MonthlyUsageCard'
+import UsageChargeRecords from '../components/billing/UsageChargeRecords'
+import ApiKeysPanel from './settings/ApiKeysPanel'
+import AccountProfileCard from './settings/AccountProfileCard'
import ComingSoon from '../components/ui/ComingSoon'
import { dramaProjectEntryPath, formatDramaCardMeta } from '../lib/dramaWorkflow'
import { STATUS_CN } from '../lib/status'
@@ -41,7 +45,7 @@ const SIDE_ITEMS: { id: SettingsTab; label: string; soon?: boolean; group?: 'wor
{ id: 'assets', label: '资产管理', group: 'work' },
{ id: 'subscription', label: '订阅与余额', group: 'account' },
{ id: 'team', label: '团队管理', soon: true, group: 'account' },
- { id: 'api', label: 'API', soon: true, group: 'account' },
+ { id: 'api', label: 'API', group: 'account' },
{ id: 'notify', label: '通知偏好', soon: true, group: 'account' },
{ id: 'security', label: '安全', group: 'account' },
]
@@ -158,9 +162,7 @@ export default function SettingsPage() {
<div className="pf-settings">
<aside className="pf-settings-side">
<div className="pf-settings-profile">
- <div className="pf-settings-avatar" aria-hidden>
- {(user?.nickname || 'P').slice(0, 1).toUpperCase()}
- </div>
+ <UserAvatar user={user} size="lg" className="pf-settings-avatar" />
<div>
<strong>{user?.nickname || '创作者'}</strong>
<p className="pf-muted">ID: {user?.id ?? '—'}</p>
@@ -186,29 +188,7 @@ export default function SettingsPage() {
</aside>
<main className="pf-settings-main">
- {tab === 'account' ? (
- <section className="pf-settings-card">
- <h1>账号信息</h1>
- <p className="pf-muted">管理你的资料与联系方式</p>
- <div className="pf-settings-fields">
- <label>
- <span>用户名</span>
- <input value={user?.nickname || ''} readOnly />
- </label>
- <label>
- <span>邮箱</span>
- <input value={user?.email || ''} readOnly />
- </label>
- <label>
- <span>手机号</span>
- <input value="" placeholder="未绑定" readOnly />
- </label>
- </div>
- <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled>
- 申请注销 <ComingSoon />
- </button>
- </section>
- ) : null}
+ {tab === 'account' ? <AccountProfileCard user={user} onUserChange={setUser} /> : null}
{tab === 'projects' ? (
<section className="pf-settings-card">
@@ -339,6 +319,7 @@ export default function SettingsPage() {
</div>
</div>
<MonthlyUsageCard variant="compact" showTopup={false} />
+ <UsageChargeRecords variant="compact" />
<div className="pf-settings-actions">
<Link className="pf-btn pf-btn-lime pf-btn-sm" to="/pricing">
去充值
@@ -363,7 +344,9 @@ export default function SettingsPage() {
</section>
) : null}
- {tab === 'team' || tab === 'api' || tab === 'notify' ? (
+ {tab === 'api' ? <ApiKeysPanel /> : null}
+
+ {tab === 'team' || tab === 'notify' ? (
<section className="pf-settings-card">
<h1>{SIDE_ITEMS.find((s) => s.id === tab)?.label}</h1>
<p className="pf-muted">该模块即将上线,敬请期待。</p>
diff --git a/frontend/src/pages/SettingsToolRunsPanel.tsx b/frontend/src/pages/SettingsToolRunsPanel.tsx
index 1b1c160..4eb1d67 100644
--- a/frontend/src/pages/SettingsToolRunsPanel.tsx
+++ b/frontend/src/pages/SettingsToolRunsPanel.tsx
@@ -11,8 +11,9 @@ import {
type ToolRunRecord,
} from '../api/tools'
import { getToolDef } from '../lib/toolsCatalog'
+import { pageCountOf } from '../lib/pagination'
-const PAGE_SIZE = 8
+const PAGE_SIZE_DEFAULT = 8
const STATUS_CN: Record<string, string> = {
queued: '生成中',
@@ -58,6 +59,7 @@ function downloadName(item: ToolRunRecord, url: string): string {
export default function SettingsToolRunsPanel() {
/*
* page 页码
+ * pageSize 每页条数
* items 当前页记录
* total 总数
* loading 加载中
@@ -68,6 +70,7 @@ export default function SettingsToolRunsPanel() {
* actionError 下载/详情错误
*/
const [page, setPage] = useState(1)
+ const [pageSize, setPageSize] = useState(PAGE_SIZE_DEFAULT)
const [items, setItems] = useState<ToolRunRecord[]>([])
const [total, setTotal] = useState(0)
const [loading, setLoading] = useState(true)
@@ -81,7 +84,7 @@ export default function SettingsToolRunsPanel() {
let cancelled = false
setLoading(true)
setError('')
- listToolRuns(page, PAGE_SIZE)
+ listToolRuns(page, pageSize)
.then((res) => {
if (cancelled) return
setItems(res.items)
@@ -96,9 +99,9 @@ export default function SettingsToolRunsPanel() {
return () => {
cancelled = true
}
- }, [page])
+ }, [page, pageSize])
- const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE))
+ const pageCount = pageCountOf(total, pageSize)
// 打开详情:再拉一次接口,确保 OSS 地址最新
async function openDetail(item: ToolRunRecord) {
@@ -211,7 +214,18 @@ export default function SettingsToolRunsPanel() {
})}
</ul>
) : null}
- <Pagination page={page} pageCount={pageCount} onChange={setPage} ariaLabel="工具创作分页" />
+ <Pagination
+ page={page}
+ pageCount={pageCount}
+ total={total}
+ pageSize={pageSize}
+ onPageSizeChange={(size) => {
+ setPageSize(size)
+ setPage(1)
+ }}
+ onChange={setPage}
+ ariaLabel="工具创作分页"
+ />
<Modal
open={Boolean(detail)}
diff --git a/frontend/src/pages/drama/AssetLibraryPage.tsx b/frontend/src/pages/drama/AssetLibraryPage.tsx
index 252c30f..5b507f9 100644
--- a/frontend/src/pages/drama/AssetLibraryPage.tsx
+++ b/frontend/src/pages/drama/AssetLibraryPage.tsx
@@ -16,12 +16,14 @@ import {
import { readAssetVoiceBinding } from './CharacterVoiceBindModal'
import { DramaImageLightbox } from './DramaImageLightbox'
import { filterDramaLibraryAssets, isDramaLibraryAsset } from '../../lib/dramaLibraryAssets'
+import { pageCountOf } from '../../lib/pagination'
import RequireAuth from './RequireAuth'
import './drama.css'
type AssetTabKey = 'all' | 'character' | 'scene' | 'prop' | 'voice'
-const PAGE_SIZE = 12
+const PAGE_SIZE_DEFAULT = 12
+const PAGE_SIZE_OPTIONS = [12, 24, 36] as const
const TABS: Array<{ value: AssetTabKey; label: string }> = [
{ value: 'all', label: '全部' },
@@ -100,6 +102,7 @@ function AssetLibraryInner() {
const [tab, setTab] = useState<AssetTabKey>('all')
const [query, setQuery] = useState('')
const [page, setPage] = useState(1)
+ const [pageSize, setPageSize] = useState(PAGE_SIZE_DEFAULT)
const [playingId, setPlayingId] = useState<number | null>(null)
const [lightbox, setLightbox] = useState<{ src: string; alt: string } | null>(null)
const [error, setError] = useState('')
@@ -174,16 +177,16 @@ function AssetLibraryInner() {
})
}, [assets, tab, query, projectNameById])
- const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE))
+ const pageCount = pageCountOf(filtered.length, pageSize)
const safePage = Math.min(page, pageCount)
const pageItems = useMemo(() => {
- const start = (safePage - 1) * PAGE_SIZE
- return filtered.slice(start, start + PAGE_SIZE)
- }, [filtered, safePage])
+ const start = (safePage - 1) * pageSize
+ return filtered.slice(start, start + pageSize)
+ }, [filtered, safePage, pageSize])
useEffect(() => {
setPage(1)
- }, [tab, query, projectId])
+ }, [tab, query, projectId, pageSize])
// 卡片缩略图上试听 / 暂停音色
function toggleVoice(asset: DramaAsset) {
@@ -326,7 +329,19 @@ function AssetLibraryInner() {
)
})}
</div>
- <Pagination page={safePage} pageCount={pageCount} onChange={setPage} />
+ <Pagination
+ page={safePage}
+ pageCount={pageCount}
+ total={filtered.length}
+ pageSize={pageSize}
+ pageSizeOptions={PAGE_SIZE_OPTIONS}
+ onPageSizeChange={(size) => {
+ setPageSize(size)
+ setPage(1)
+ }}
+ onChange={setPage}
+ ariaLabel="资产库分页"
+ />
</>
)}
diff --git a/frontend/src/pages/drama/AssetsStep.tsx b/frontend/src/pages/drama/AssetsStep.tsx
index 1803d69..a7f9995 100644
--- a/frontend/src/pages/drama/AssetsStep.tsx
+++ b/frontend/src/pages/drama/AssetsStep.tsx
@@ -1,5 +1,5 @@
/** 资产库步骤:进入时 seed,分类 Tab + 生图队列 + 角色音色绑定 */
-import { useEffect, useRef, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import { Boxes, Sparkles } from 'lucide-react'
import { dramaApi, resolveDramaMediaUrl, type DramaAsset, type DramaProject } from '../../api/drama'
@@ -23,9 +23,15 @@ import { DramaAssetDetailModal } from './DramaAssetDetailModal'
import { DramaImageLightbox } from './DramaImageLightbox'
import { GlobalAssetPickerModal, importGlobalAssetToProject } from './GlobalAssetPickerModal'
import { DramaVoiceAssetCard } from './DramaVoiceAssetCard'
+import Pagination from '../../components/ui/Pagination'
import { dialog } from '../../lib/dialog'
+import { pageCountOf } from '../../lib/pagination'
import { readVisualPrompt } from '../../lib/dramaVisualPrompt'
import { filterDramaLibraryAssets } from '../../lib/dramaLibraryAssets'
+import {
+ dramaAssetImageGenButtonLabel,
+ dramaAssetNeedsImageGeneration,
+} from '../../lib/dramaAssetImage'
type AssetTabKey = 'character' | 'scene' | 'prop' | 'material' | 'voice'
@@ -37,6 +43,9 @@ const ASSET_TABS: Array<{ key: AssetTabKey; label: string }> = [
{ key: 'voice', label: '音色' },
]
+const PAGE_SIZE_DEFAULT = 12
+const PAGE_SIZE_OPTIONS = [12, 24, 36] as const
+
type AssetsStepProps = {
projectId: number
onError: (m: string) => void
@@ -47,11 +56,9 @@ function normalizeAssetList(value: unknown): DramaAsset[] {
return filterDramaLibraryAssets(Array.isArray(value) ? (value as DramaAsset[]) : [])
}
-// 判断资产是否尚未出图(无有效封面/主图)
+// 判断资产是否尚未出图(无有效封面/主图,上传或 AI 生成均视为已出图)
function needsImageGeneration(asset: DramaAsset): boolean {
- const cover = (asset.cover || '').trim()
- const url = (asset.url || '').trim()
- return !cover && !url
+ return dramaAssetNeedsImageGeneration(asset)
}
// 渲染资产库步骤
@@ -65,12 +72,17 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
* voiceAsset 打开音色弹窗的角色
* detailAsset 打开详情操作框的资产
* lightbox 图片放大预览
+ * batchVoiceBusy 批量生成音色中
+ * page 当前页码
+ * pageSize 每页条数
* genQueue 全局生图队列
*/
const [assets, setAssets] = useState<DramaAsset[]>([])
const [tab, setTab] = useState<AssetTabKey>('character')
const [loading, setLoading] = useState(true)
const [batchBusy, setBatchBusy] = useState(false)
+ const [page, setPage] = useState(1)
+ const [pageSize, setPageSize] = useState(PAGE_SIZE_DEFAULT)
const [genOptions, setGenOptions] = useState<ImageGenerationOptions>(() =>
defaultOptionsForAssetKind('character'),
)
@@ -146,8 +158,13 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
if (tab !== 'character') {
setSelectedCharacterIds([])
}
+ setPage(1)
}, [tab])
+ useEffect(() => {
+ setPage(1)
+ }, [pageSize])
+
// 队列完成时把最新封面写回卡片
useEffect(() => {
const projectJobs = genQueue.filter((j) => j.projectId === projectId)
@@ -200,6 +217,12 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
// 未出图:无有效 cover/url,且当前未在队列中
const pending = filtered.filter((a) => needsImageGeneration(a) && !busyAssetIds.has(a.id))
const queueBusy = busyAssetIds.size > 0
+ const pageCount = pageCountOf(filtered.length, pageSize)
+ const safePage = Math.min(page, pageCount)
+ const pageItems = useMemo(() => {
+ const start = (safePage - 1) * pageSize
+ return filtered.slice(start, start + pageSize)
+ }, [filtered, safePage, pageSize])
// 持久化项目画面风格
async function persistStyle(styleId: string) {
@@ -520,17 +543,22 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
}
}
- // 卡片按钮文案
- function genButtonLabel(assetId: number): string {
+ // 卡片按钮文案(已有图时显示「重新生成形象」)
+ function genButtonLabel(asset: DramaAsset): string {
const job = genQueue.find(
(j) =>
- j.assetId === assetId && (j.status === 'queued' || j.status === 'running'),
+ j.assetId === asset.id && (j.status === 'queued' || j.status === 'running'),
)
- if (!job) return '生成形象'
- if (job.status === 'running') return '生成中…'
- const queuedOnly = genQueue.filter((j) => j.status === 'queued' || j.status === 'running')
- const pos = queuedOnly.findIndex((j) => j.id === job.id) + 1
- return pos > 1 ? `排队 #${pos}` : '排队中…'
+ let queueLabel: string | null = null
+ if (job) {
+ if (job.status === 'running') queueLabel = '生成中…'
+ else {
+ const queuedOnly = genQueue.filter((j) => j.status === 'queued' || j.status === 'running')
+ const pos = queuedOnly.findIndex((j) => j.id === job.id) + 1
+ queueLabel = pos > 1 ? `排队 #${pos}` : '排队中…'
+ }
+ }
+ return dramaAssetImageGenButtonLabel(asset, queueLabel)
}
const imageAssetCount = assetList.filter((a) => {
@@ -548,8 +576,8 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
<div>
<h2>资产库</h2>
<p className="drama-step-hero-sub">
- 共 <strong>{assetList.length}</strong> 项资产 · 待生图{' '}
- <strong>{pending.length}</strong>
+ 共 <strong>{assetList.length}</strong> 项资产 · 当前分类{' '}
+ <strong>{filtered.length}</strong> 项 · 待生图 <strong>{pending.length}</strong>
</p>
</div>
</div>
@@ -663,8 +691,14 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
{loading ? <p className="drama-muted">正在从剧本抽取资产(含道具/素材)…</p> : null}
+ {!loading && filtered.length > 0 ? (
+ <p className="drama-muted drama-assets-page-meta">
+ 第 {safePage} / {pageCount} 页 · 本分类共 {filtered.length} 项
+ </p>
+ ) : null}
+
<div className={`drama-asset-grid${tab === 'voice' ? ' is-voice' : ''}`}>
- {filtered.map((asset) => {
+ {pageItems.map((asset) => {
if (tab === 'voice') {
const promptValue = voicePromptDrafts[asset.id] ?? readVoicePrompt(asset)
const synthBusy = voiceSynthBusyId === asset.id
@@ -764,7 +798,7 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
disabled={busy || batchBusy}
onClick={() => enqueueOne(asset)}
>
- {genButtonLabel(asset.id)}
+ {genButtonLabel(asset)}
</button>
{isCharacter ? (
<>
@@ -805,12 +839,29 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
</div>
{!loading && filtered.length === 0 ? <p className="drama-muted">该分类暂无资产</p> : null}
+ {!loading && filtered.length > 0 ? (
+ <Pagination
+ page={safePage}
+ pageCount={pageCount}
+ total={filtered.length}
+ pageSize={pageSize}
+ pageSizeOptions={PAGE_SIZE_OPTIONS}
+ onPageSizeChange={(size) => {
+ setPageSize(size)
+ setPage(1)
+ }}
+ onChange={setPage}
+ ariaLabel="资产库分页"
+ className="drama-assets-pagination"
+ />
+ ) : null}
+
{detailAsset && (detailAsset.type || '').toLowerCase() !== 'voice' ? (
<DramaAssetDetailModal
asset={detailAsset}
open
busy={busyAssetIds.has(detailAsset.id)}
- genLabel={genButtonLabel(detailAsset.id)}
+ genLabel={genButtonLabel(detailAsset)}
onClose={() => setDetailAsset(null)}
onUpdated={(updated) => {
setAssets((prev) => (prev ?? []).map((a) => (a.id === updated.id ? updated : a)))
diff --git a/frontend/src/pages/drama/DramaAssetDetailModal.tsx b/frontend/src/pages/drama/DramaAssetDetailModal.tsx
index 8d0300c..40f4f1d 100644
--- a/frontend/src/pages/drama/DramaAssetDetailModal.tsx
+++ b/frontend/src/pages/drama/DramaAssetDetailModal.tsx
@@ -1,8 +1,9 @@
-/** 资产详情操作框:预览图、生图提示词编辑、生成/音色等操作 */
-import { useEffect, useState } from 'react'
+/** 资产详情操作框:预览图、上传/生图提示词编辑、生成/音色等操作 */
+import { useEffect, useRef, useState } from 'react'
import { dramaApi, resolveDramaMediaUrl, type DramaAsset } from '../../api/drama'
import Modal from '../../components/ui/Modal'
import { readVisualPrompt } from '../../lib/dramaVisualPrompt'
+import { dramaAssetHasImage } from '../../lib/dramaAssetImage'
import { readAssetVoiceBinding } from './CharacterVoiceBindModal'
import { DramaImageLightbox } from './DramaImageLightbox'
@@ -49,13 +50,17 @@ export function DramaAssetDetailModal({
/*
* promptDraft 提示词草稿
* saving 保存中
+ * uploading 上传图片中
* lightboxSrc 放大预览图 URL
*/
const [promptDraft, setPromptDraft] = useState('')
const [saving, setSaving] = useState(false)
+ const [uploading, setUploading] = useState(false)
const [lightboxSrc, setLightboxSrc] = useState<string | null>(null)
+ const uploadInputRef = useRef<HTMLInputElement>(null)
const mediaSrc = resolveDramaMediaUrl(asset.cover || asset.url)
+ const hasImage = dramaAssetHasImage(asset)
const voice = readAssetVoiceBinding(asset)
const isCharacter = (asset.type || '').toLowerCase() === 'character'
const dirty = promptDraft.trim() !== readVisualPrompt(asset).trim()
@@ -111,6 +116,20 @@ export function DramaAssetDetailModal({
onGenerate(asset)
}
+ // 本地上传图片,视为已出图
+ async function handleUpload(file: File) {
+ setUploading(true)
+ try {
+ const updated = await dramaApi.uploadAssetMedia(asset.id, file)
+ onUpdated(updated)
+ } catch (err) {
+ onError(err instanceof Error ? err.message : '上传失败')
+ } finally {
+ setUploading(false)
+ if (uploadInputRef.current) uploadInputRef.current.value = ''
+ }
+ }
+
return (
<>
<Modal
@@ -136,7 +155,7 @@ export function DramaAssetDetailModal({
<button
type="button"
className="pf-btn drama-btn-primary"
- disabled={busy || saving || !promptDraft.trim()}
+ disabled={busy || saving || uploading || !promptDraft.trim()}
onClick={() => void handleGenerate()}
>
{busy ? '生成中…' : genLabel}
@@ -161,21 +180,31 @@ export function DramaAssetDetailModal({
<p className="drama-muted drama-asset-detail-meta">
{asset.type}
+ {hasImage ? ' · 已出图' : ' · 未出图'}
{isCharacter && voice ? ` · 已绑音色:${voice.label}` : ''}
{mediaSrc ? ' · 点击图片可放大' : ''}
</p>
- <label className="drama-field">
- <span>生图提示词</span>
- <textarea
- rows={8}
- value={promptDraft}
- onChange={(e) => setPromptDraft(e.target.value)}
- placeholder="描述外观、构图、光影与风格…"
- />
- </label>
-
<div className="drama-asset-detail-extra">
+ <input
+ ref={uploadInputRef}
+ type="file"
+ accept="image/jpeg,image/png,image/webp,image/gif"
+ className="sr-only"
+ disabled={uploading || busy}
+ onChange={(e) => {
+ const file = e.target.files?.[0]
+ if (file) void handleUpload(file)
+ }}
+ />
+ <button
+ type="button"
+ className="pf-btn pf-btn-sm"
+ disabled={uploading || busy || saving}
+ onClick={() => uploadInputRef.current?.click()}
+ >
+ {uploading ? '上传中…' : hasImage ? '更换图片' : '上传图片'}
+ </button>
{isCharacter && onBindVoice ? (
<button
type="button"
@@ -189,13 +218,23 @@ export function DramaAssetDetailModal({
<button
type="button"
className="pf-btn pf-btn-sm drama-btn-danger-text"
- disabled={busy || saving}
+ disabled={busy || saving || uploading}
onClick={() => onDelete(asset)}
>
删除角色
</button>
) : null}
</div>
+
+ <label className="drama-field">
+ <span>生图提示词</span>
+ <textarea
+ rows={8}
+ value={promptDraft}
+ onChange={(e) => setPromptDraft(e.target.value)}
+ placeholder="描述外观、构图、光影与风格…"
+ />
+ </label>
</div>
</Modal>
diff --git a/frontend/src/pages/drama/canvas/CanvasStore.tsx b/frontend/src/pages/drama/canvas/CanvasStore.tsx
index cac9d63..f036f96 100644
--- a/frontend/src/pages/drama/canvas/CanvasStore.tsx
+++ b/frontend/src/pages/drama/canvas/CanvasStore.tsx
@@ -514,7 +514,6 @@ export function CanvasStoreProvider({ projectId, children }: CanvasStoreProvider
const node = nodesRef.current.find((n) => n.id === nodeId)
if (!node) throw new Error('节点不存在')
if (node.data.kind === 'video') throw new Error('视频节点请使用视频生成')
- if (node.data.kind === 'video') throw new Error('视频节点请使用视频生成')
setNodes((current) =>
current.map((n) =>
diff --git a/frontend/src/pages/drama/drama.css b/frontend/src/pages/drama/drama.css
index 0c91a56..b31b268 100644
--- a/frontend/src/pages/drama/drama.css
+++ b/frontend/src/pages/drama/drama.css
@@ -1112,6 +1112,15 @@
margin-top: 14px;
}
+.drama-assets-page-meta {
+ margin: 12px 0 0;
+ font-size: 0.875rem;
+}
+
+.drama-assets-pagination {
+ margin-top: 20px;
+}
+
.drama-asset-card {
background: #fafafa;
border: 1px solid var(--drama-line);
diff --git a/frontend/src/pages/settings/AccountProfileCard.tsx b/frontend/src/pages/settings/AccountProfileCard.tsx
new file mode 100644
index 0000000..c9ea06a
--- /dev/null
+++ b/frontend/src/pages/settings/AccountProfileCard.tsx
@@ -0,0 +1,170 @@
+import { useEffect, useRef, useState } from 'react'
+import UserAvatar from '../../components/UserAvatar'
+import ComingSoon from '../../components/ui/ComingSoon'
+import { api, type User } from '../../api'
+import { dispatchUserUpdated } from '../../lib/userEvents'
+
+type AccountProfileCardProps = {
+ user: User | null
+ onUserChange: (user: User) => void
+}
+
+/** 账号资料:头像、用户名、邮箱、手机号(手机号仅记录) */
+export default function AccountProfileCard({ user, onUserChange }: AccountProfileCardProps) {
+ /*
+ * nickname / email / phone 表单值
+ * saveBusy 保存中
+ * saveError 保存失败
+ * saveOk 保存成功提示
+ * avatarBusy 头像上传中
+ * avatarError 头像失败原因
+ */
+ const [nickname, setNickname] = useState('')
+ const [email, setEmail] = useState('')
+ const [phone, setPhone] = useState('')
+ const [saveBusy, setSaveBusy] = useState(false)
+ const [saveError, setSaveError] = useState('')
+ const [saveOk, setSaveOk] = useState(false)
+ const [avatarBusy, setAvatarBusy] = useState(false)
+ const [avatarError, setAvatarError] = useState('')
+ const avatarInputRef = useRef<HTMLInputElement>(null)
+
+ useEffect(() => {
+ if (!user) return
+ setNickname(user.nickname || '')
+ setEmail(user.email || '')
+ setPhone(user.phone || '')
+ }, [user])
+
+ const dirty =
+ !!user &&
+ (nickname.trim() !== (user.nickname || '') ||
+ email.trim() !== (user.email || '') ||
+ phone.trim() !== (user.phone || ''))
+
+ // 选择并上传头像
+ async function handleAvatarChange(file: File | undefined) {
+ if (!file || avatarBusy) return
+ setAvatarError('')
+ setAvatarBusy(true)
+ try {
+ const updated = await api.uploadAvatar(file)
+ onUserChange(updated)
+ dispatchUserUpdated(updated)
+ } catch (e) {
+ setAvatarError(e instanceof Error ? e.message : '头像上传失败')
+ } finally {
+ setAvatarBusy(false)
+ if (avatarInputRef.current) avatarInputRef.current.value = ''
+ }
+ }
+
+ // 保存用户名、邮箱、手机号
+ async function handleSave() {
+ if (!user || saveBusy) return
+ setSaveError('')
+ setSaveOk(false)
+ setSaveBusy(true)
+ try {
+ const updated = await api.updateProfile({
+ nickname: nickname.trim(),
+ email: email.trim(),
+ phone: phone.trim(),
+ })
+ onUserChange(updated)
+ dispatchUserUpdated(updated)
+ setSaveOk(true)
+ } catch (e) {
+ setSaveError(e instanceof Error ? e.message : '保存失败')
+ } finally {
+ setSaveBusy(false)
+ }
+ }
+
+ return (
+ <section className="pf-settings-card">
+ <h1>账号信息</h1>
+ <p className="pf-muted">管理你的资料与联系方式</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>
+ <div className="pf-settings-actions">
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime pf-btn-sm"
+ disabled={avatarBusy}
+ onClick={() => avatarInputRef.current?.click()}
+ >
+ {avatarBusy ? '上传中…' : user?.avatar_url ? '更换头像' : '上传头像'}
+ </button>
+ </div>
+ {avatarError ? <p className="pf-error">{avatarError}</p> : null}
+ <input
+ ref={avatarInputRef}
+ type="file"
+ accept="image/jpeg,image/png,image/webp,image/gif"
+ hidden
+ onChange={(e) => void handleAvatarChange(e.target.files?.[0])}
+ />
+ </div>
+ </div>
+ <div className="pf-settings-fields">
+ <label>
+ <span>用户名</span>
+ <input
+ value={nickname}
+ maxLength={64}
+ autoComplete="nickname"
+ onChange={(e) => {
+ setNickname(e.target.value)
+ setSaveOk(false)
+ }}
+ />
+ </label>
+ <label>
+ <span>邮箱</span>
+ <input
+ type="email"
+ value={email}
+ autoComplete="email"
+ onChange={(e) => {
+ setEmail(e.target.value)
+ setSaveOk(false)
+ }}
+ />
+ </label>
+ <label>
+ <span>手机号</span>
+ <input
+ type="tel"
+ value={phone}
+ inputMode="numeric"
+ autoComplete="tel"
+ placeholder="未绑定"
+ onChange={(e) => {
+ setPhone(e.target.value)
+ setSaveOk(false)
+ }}
+ />
+ <em className="pf-muted">仅记录联系方式,无需验证码</em>
+ </label>
+ </div>
+ {saveError ? <p className="pf-error">{saveError}</p> : null}
+ {saveOk ? <p className="pf-muted">已保存</p> : null}
+ <div className="pf-settings-actions">
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime pf-btn-sm"
+ disabled={!user || saveBusy || !dirty}
+ onClick={() => void handleSave()}
+ >
+ {saveBusy ? '保存中…' : '保存资料'}
+ </button>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled>
+ 申请注销 <ComingSoon />
+ </button>
+ </div>
+ </section>
+ )
+}
diff --git a/frontend/src/pages/settings/ApiKeysPanel.tsx b/frontend/src/pages/settings/ApiKeysPanel.tsx
new file mode 100644
index 0000000..eeba25e
--- /dev/null
+++ b/frontend/src/pages/settings/ApiKeysPanel.tsx
@@ -0,0 +1,195 @@
+import { useEffect, useState } from 'react'
+import { apiKeysApi, getPublicApiBase, type ApiKeyItem } from '../../api/apiKeys'
+import { dialog } from '../../lib/dialog'
+
+/** 格式化时间 */
+function formatWhen(iso?: string | null) {
+ 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',
+ })
+}
+
+/** 设置页 API:Key 管理与调用文档 */
+export default function ApiKeysPanel() {
+ /*
+ * keys Key 列表
+ * name 新建名称
+ * busy 提交中
+ * error 错误
+ * createdSecret 刚创建的一次性 secret
+ */
+ const [keys, setKeys] = useState<ApiKeyItem[]>([])
+ const [name, setName] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const [createdSecret, setCreatedSecret] = useState('')
+
+ const base = getPublicApiBase()
+
+ async function reload() {
+ setError('')
+ try {
+ setKeys(await apiKeysApi.list())
+ } catch (e) {
+ setError(e instanceof Error ? e.message : '加载失败')
+ }
+ }
+
+ useEffect(() => {
+ void reload()
+ }, [])
+
+ async function handleCreate() {
+ if (busy) return
+ setBusy(true)
+ setError('')
+ setCreatedSecret('')
+ try {
+ const row = await apiKeysApi.create(name.trim() || '默认 Key')
+ setCreatedSecret(row.secret)
+ setName('')
+ await reload()
+ } catch (e) {
+ setError(e instanceof Error ? e.message : '创建失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function handleRevoke(item: ApiKeyItem) {
+ const ok = await dialog.confirm({
+ title: '撤销 API Key',
+ message: `确定撤销「${item.name}」(${item.key_prefix}…)?撤销后无法恢复。`,
+ confirmText: '撤销',
+ })
+ if (!ok) return
+ setBusy(true)
+ setError('')
+ try {
+ await apiKeysApi.revoke(item.id)
+ await reload()
+ } catch (e) {
+ setError(e instanceof Error ? e.message : '撤销失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function copyText(text: string) {
+ try {
+ await navigator.clipboard.writeText(text)
+ } catch {
+ /* ignore */
+ }
+ }
+
+ return (
+ <section className="pf-settings-card">
+ <h1>API</h1>
+ <p className="pf-muted">使用 API Key 调用生图、生视频与 Seedance 转发,按量从余额扣费</p>
+
+ <div className="pf-api-create">
+ <input
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="Key 名称,如「生产环境」"
+ maxLength={64}
+ />
+ <button type="button" className="pf-btn pf-btn-lime pf-btn-sm" disabled={busy} onClick={() => void handleCreate()}>
+ {busy ? '处理中…' : '创建 Key'}
+ </button>
+ </div>
+
+ {createdSecret ? (
+ <div className="pf-api-secret">
+ <p>
+ <strong>请立即复制保存,关闭后无法再次查看:</strong>
+ </p>
+ <code>{createdSecret}</code>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" onClick={() => void copyText(createdSecret)}>
+ 复制 Key
+ </button>
+ </div>
+ ) : null}
+
+ {error ? <p className="pf-error">{error}</p> : null}
+
+ {keys.length > 0 ? (
+ <ul className="pf-settings-list pf-api-key-list">
+ {keys.map((item) => (
+ <li key={item.id}>
+ <div className="pf-settings-list-row">
+ <span className="pf-settings-list-main">
+ <strong>{item.name}</strong>
+ <em className="pf-muted">
+ {item.key_prefix}… · 创建于 {formatWhen(item.created_at)}
+ {item.last_used_at ? ` · 最近使用 ${formatWhen(item.last_used_at)}` : ''}
+ </em>
+ </span>
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-sm"
+ disabled={busy}
+ onClick={() => void handleRevoke(item)}
+ >
+ 撤销
+ </button>
+ </div>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <div className="pf-settings-empty">
+ <p>还没有 API Key</p>
+ </div>
+ )}
+
+ <div className="pf-api-docs">
+ <h3>调用说明</h3>
+ <p className="pf-muted">鉴权:Header 任选其一</p>
+ <pre>{`Authorization: Bearer pf_live_...\nX-Api-Key: pf_live_...`}</pre>
+
+ <p className="pf-muted">生图(Seedream)</p>
+ <pre>{`POST ${base}/api/v1/images/generations
+Content-Type: application/json
+
+{
+ "prompt": "赛博朋克城市夜景",
+ "ratio": "16:9",
+ "image_url": null
+}`}</pre>
+
+ <p className="pf-muted">生视频(Seedance 首帧图生视频)</p>
+ <pre>{`POST ${base}/api/v1/videos/generations
+
+{
+ "prompt": "镜头缓慢推进,霓虹闪烁",
+ "image_url": "https://.../first_frame.jpg",
+ "duration": 5,
+ "resolution": "480p"
+}`}</pre>
+
+ <p className="pf-muted">Seedance 转发(多模态 body)</p>
+ <pre>{`POST ${base}/api/v1/seedance/tasks
+
+{
+ "content": [
+ { "type": "text", "text": "描述..." },
+ { "type": "image_url", "image_url": { "url": "https://..." }, "role": "first_frame" }
+ ],
+ "duration": 5,
+ "resolution": "480p"
+}`}</pre>
+
+ <p className="pf-muted">查询视频任务</p>
+ <pre>{`GET ${base}/api/v1/tasks/{task_id}`}</pre>
+ </div>
+ </section>
+ )
+}
diff --git a/frontend/src/pages/studio/StoryboardPage.tsx b/frontend/src/pages/studio/StoryboardPage.tsx
index 9a15759..855d705 100644
--- a/frontend/src/pages/studio/StoryboardPage.tsx
+++ b/frontend/src/pages/studio/StoryboardPage.tsx
@@ -4,7 +4,6 @@ import { api, defaultsFromTemplate } from '../../api'
import type { Project, Shot, Template } from '../../api'
import AppShell from '../../components/layout/AppShell'
import Stepper from '../../components/ui/Stepper'
-import ComingSoon from '../../components/ui/ComingSoon'
import {
IconChevronLeft,
IconDownload,
@@ -31,7 +30,11 @@ import {
import {
SEGMENT_SCRIPT_PLACEHOLDER,
SHOT_DURATION_MAX,
+ firstVisualFromScript,
+ narrationFromScript,
parseSegmentScript,
+ replaceFirstVisualInScript,
+ replaceNarrationInScript,
validateSegmentScriptDuration,
} from '../../lib/segmentDuration'
@@ -247,6 +250,7 @@ export default function StoryboardPage() {
? '继续生成视频'
: '继续生成'
+ // 工作台进度:完整模式要镜头视频 + 外部 TTS,静图模式只配音合成
const progressItems = useMemo(() => {
if (!project) return []
const list = project.shots || []
@@ -266,7 +270,7 @@ export default function StoryboardPage() {
]
if (full) {
items.push({
- label: `视频模型配音 (${vids}/${list.length || 0})`,
+ label: `镜头视频 (${vids}/${list.length || 0})`,
done:
list.length > 0 &&
(vids === list.length ||
@@ -274,12 +278,13 @@ export default function StoryboardPage() {
run: stage === 'VIDEOING',
pct: stage === 'VIDEOING' ? project.progress : undefined,
})
- } else {
- items.push({
- label: `配音合成 (${auds}/${list.length || 0})`,
- done: list.length > 0 && auds === list.length,
- })
}
+ items.push({
+ label: `配音合成 (${auds}/${list.length || 0})`,
+ done: list.length > 0 && auds === list.length,
+ run: stage === 'AUDIOING',
+ pct: stage === 'AUDIOING' ? project.progress : undefined,
+ })
items.push({
label: full ? '镜头拼接' : '成片渲染',
done: Boolean(project.final_video_url) || project.status === 'DONE',
@@ -506,6 +511,44 @@ export default function StoryboardPage() {
setMenuShotId(null)
}
+ // 改旁白时同步写入脚本旁白段
+ function patchEditingNarration(value: string) {
+ if (!editing) return
+ const script = editing.segment_script || editing.video_prompt || ''
+ const next = replaceNarrationInScript(script, value)
+ setEditing({
+ ...editing,
+ narration: value,
+ segment_script: next,
+ video_prompt: next,
+ })
+ }
+
+ // 改首帧画面时同步写入脚本第一段 visual
+ function patchEditingVisual(value: string) {
+ if (!editing) return
+ const script = editing.segment_script || editing.video_prompt || ''
+ const next = replaceFirstVisualInScript(script, value)
+ setEditing({
+ ...editing,
+ img_prompt: value,
+ segment_script: next,
+ video_prompt: next,
+ })
+ }
+
+ // 改脚本时回填旁白与首帧画面
+ function patchEditingScript(value: string) {
+ if (!editing) return
+ setEditing({
+ ...editing,
+ segment_script: value,
+ video_prompt: value,
+ narration: narrationFromScript(value),
+ img_prompt: firstVisualFromScript(value) || editing.img_prompt,
+ })
+ }
+
async function saveShot() {
if (!project || !editing) return
// scriptText 当前编辑中的逐段脚本
@@ -836,9 +879,7 @@ title="用当前镜头重新拼接"
</div>
</article>
<article className="pf-create-col">
- <h3>
- 结构摘要 <ComingSoon label="示例聚合" />
- </h3>
+ <h3>结构摘要</h3>
<ul className="pf-meta-list">
{structure.length ? (
structure.map((s) => (
@@ -1131,36 +1172,6 @@ title="用当前镜头重新拼接"
</div>
<aside className="pf-create-col pf-board-settings">
- <h3>分镜设置</h3>
- <label className="pf-board-field">
- <span>时长(秒)</span>
- <input
- type="number"
- min={1}
- step={0.5}
- value={shots[0] ? Number(shots[0].duration) || '' : ''}
- readOnly
- title="选中镜头后可在表格中编辑;此处为布局预览"
- />
- </label>
- <label className="pf-board-field">
- <span>运镜</span>
- <select disabled defaultValue="auto">
- <option value="auto">自动</option>
- <option value="push">推进</option>
- <option value="pan">横移</option>
- </select>
- </label>
- <label className="pf-board-field">
- <span>转场</span>
- <select disabled defaultValue="cut">
- <option value="cut">硬切</option>
- <option value="fade">淡入淡出</option>
- </select>
- </label>
- <p className="pf-muted" style={{ fontSize: '0.75rem', margin: '0.35rem 0 1rem' }}>
- 运镜 / 转场能力即将接入,当前可先在分镜表中改时长与旁白。
- </p>
<h3>生成进度</h3>
<ul className="pf-progress-list">
{progressItems.map((item) => (
@@ -1293,6 +1304,9 @@ title="用当前镜头重新拼接"
value={editing.overlay_title || ''}
onChange={(e) => setEditing({ ...editing, overlay_title: e.target.value })}
/>
+ <span className="pf-muted" style={{ fontSize: '0.75rem', marginTop: 4, display: 'block' }}>
+ 分镜列表名称;图文成片会叠到画面顶部
+ </span>
</label>
<label>
副标题
@@ -1300,17 +1314,20 @@ title="用当前镜头重新拼接"
value={editing.overlay_subtitle || ''}
onChange={(e) => setEditing({ ...editing, overlay_subtitle: e.target.value })}
/>
+ <span className="pf-muted" style={{ fontSize: '0.75rem', marginTop: 4, display: 'block' }}>
+ 图文成片叠字;AI 视频成片不烧这行,只作分镜说明
+ </span>
</label>
<label>
旁白
<textarea
autoFocus={editFocus === 'narration'}
value={editing.narration}
- onChange={(e) => setEditing({ ...editing, narration: e.target.value })}
+ onChange={(e) => patchEditingNarration(e.target.value)}
rows={3}
/>
<span className="pf-muted" style={{ fontSize: '0.75rem', marginTop: 4, display: 'block' }}>
- 保存后将按脚本中旁白段回写
+ 会同步到下方脚本旁白段,配音与视频按脚本生成
</span>
</label>
<label>
@@ -1318,11 +1335,11 @@ title="用当前镜头重新拼接"
<textarea
autoFocus={editFocus === 'img_prompt'}
value={editing.img_prompt}
- onChange={(e) => setEditing({ ...editing, img_prompt: e.target.value })}
+ onChange={(e) => patchEditingVisual(e.target.value)}
rows={3}
/>
<span className="pf-muted" style={{ fontSize: '0.75rem', marginTop: 4, display: 'block' }}>
- 保存后将按脚本首段画面回写
+ 会同步到脚本首段画面,出图与视频都用这一段
</span>
</label>
<label>
@@ -1330,13 +1347,7 @@ title="用当前镜头重新拼接"
<textarea
autoFocus={editFocus === 'segment_script' || editFocus === ''}
value={editing.segment_script || editing.video_prompt || ''}
- onChange={(e) =>
- setEditing({
- ...editing,
- segment_script: e.target.value,
- video_prompt: e.target.value,
- })
- }
+ onChange={(e) => patchEditingScript(e.target.value)}
rows={10}
placeholder={SEGMENT_SCRIPT_PLACEHOLDER}
/>
diff --git a/frontend/src/styles/printfilm.css b/frontend/src/styles/printfilm.css
index 5ff41c6..27ef7df 100644
--- a/frontend/src/styles/printfilm.css
+++ b/frontend/src/styles/printfilm.css
@@ -140,6 +140,25 @@
text-align: center;
}
+.pf-shell-footer-links {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 0.85rem 1.35rem;
+ margin-bottom: 0.75rem;
+}
+
+.pf-shell-footer-links a {
+ color: var(--pf-muted);
+ text-decoration: none;
+ font-size: 0.85rem;
+ font-weight: 600;
+}
+
+.pf-shell-footer-links a:hover {
+ color: var(--pf-ink);
+}
+
.pf-shell-footer p {
margin: 0;
font-size: 0.85rem;
@@ -1395,14 +1414,70 @@
}
.pf-settings-avatar {
- width: 48px;
- height: 48px;
+ flex-shrink: 0;
+}
+
+.pf-settings-avatar-row {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ margin: 1.25rem 0 1.5rem;
+ padding-bottom: 1.25rem;
+ border-bottom: 1px solid var(--pf-line);
+}
+
+.pf-settings-avatar-actions {
+ display: flex;
+ flex-direction: column;
+ gap: 0.45rem;
+ min-width: 0;
+}
+
+.pf-settings-avatar-actions .pf-muted {
+ margin: 0;
+ font-size: 0.82rem;
+}
+
+.pf-user-avatar {
border-radius: 999px;
background: var(--pf-lime);
display: grid;
place-items: center;
font-weight: 700;
flex-shrink: 0;
+ overflow: hidden;
+ color: var(--pf-ink);
+}
+
+.pf-user-avatar img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+}
+
+.pf-user-avatar--sm {
+ width: 34px;
+ height: 34px;
+ font-size: 0.75rem;
+}
+
+.pf-user-avatar--md {
+ width: 48px;
+ height: 48px;
+ font-size: 1rem;
+}
+
+.pf-user-avatar--lg {
+ width: 48px;
+ height: 48px;
+ font-size: 1rem;
+}
+
+.pf-user-avatar--xl {
+ width: 72px;
+ height: 72px;
+ font-size: 1.35rem;
}
.pf-settings-profile strong {
@@ -1494,7 +1569,18 @@
border-radius: 12px;
padding: 0.65rem 0.8rem;
font: inherit;
+ background: #fff;
+}
+
+.pf-settings-fields input:read-only {
background: var(--pf-bg);
+ color: var(--pf-muted);
+ cursor: default;
+}
+
+.pf-settings-fields em {
+ font-style: normal;
+ font-size: 0.8rem;
}
.pf-settings-actions {
@@ -2062,6 +2148,231 @@
text-decoration: underline;
}
+/* —— Legal / contact pages —— */
+.pf-legal-page {
+ width: min(760px, 100%);
+ margin: 0 auto;
+ padding: 0.5rem 0 2.5rem;
+}
+
+.pf-legal-hero {
+ margin-bottom: 1.75rem;
+}
+
+.pf-legal-crumb {
+ margin: 0 0 0.75rem;
+ font-size: 0.82rem;
+ color: var(--pf-muted);
+}
+
+.pf-legal-crumb a {
+ color: inherit;
+ text-decoration: none;
+ font-weight: 600;
+}
+
+.pf-legal-crumb a:hover {
+ color: var(--pf-ink);
+}
+
+.pf-legal-hero h1 {
+ margin: 0 0 0.45rem;
+ font-size: clamp(1.65rem, 3vw, 2rem);
+ font-weight: 800;
+ letter-spacing: -0.02em;
+}
+
+.pf-legal-meta {
+ margin: 0 0 1rem;
+ font-size: 0.82rem;
+ color: var(--pf-muted);
+}
+
+.pf-legal-intro {
+ margin: 0;
+ font-size: 0.95rem;
+ line-height: 1.75;
+ color: #3d4654;
+}
+
+.pf-legal-intro a {
+ color: var(--pf-ink);
+ font-weight: 700;
+}
+
+.pf-legal-sections {
+ display: flex;
+ flex-direction: column;
+ gap: 1.35rem;
+}
+
+.pf-legal-section h2 {
+ margin: 0 0 0.55rem;
+ font-size: 1.05rem;
+ font-weight: 800;
+}
+
+.pf-legal-section p {
+ margin: 0 0 0.65rem;
+ font-size: 0.92rem;
+ line-height: 1.8;
+ color: #3d4654;
+}
+
+.pf-legal-section ul {
+ margin: 0;
+ padding-left: 1.15rem;
+ color: #3d4654;
+ font-size: 0.92rem;
+ line-height: 1.8;
+}
+
+.pf-legal-section li + li {
+ margin-top: 0.25rem;
+}
+
+.pf-legal-foot-nav {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.75rem 1.25rem;
+ margin-top: 2.25rem;
+ padding-top: 1.25rem;
+ border-top: 1px solid var(--pf-line);
+}
+
+.pf-legal-foot-nav a {
+ color: var(--pf-muted);
+ text-decoration: none;
+ font-size: 0.86rem;
+ font-weight: 600;
+}
+
+.pf-legal-foot-nav a:hover {
+ color: var(--pf-ink);
+}
+
+.pf-contact-channels {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 0.85rem;
+ margin-bottom: 2rem;
+}
+
+.pf-contact-card {
+ background: #fff;
+ border: 1px solid var(--pf-line);
+ border-radius: 16px;
+ padding: 1.15rem 1.1rem;
+ text-align: left;
+ box-shadow: 0 6px 18px rgba(17, 19, 24, 0.04);
+}
+
+.pf-contact-card-icon {
+ display: inline-grid;
+ place-items: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ border-radius: 12px;
+ background: color-mix(in srgb, var(--pf-lime) 28%, #fff);
+ color: #3d4a12;
+ margin-bottom: 0.75rem;
+}
+
+.pf-contact-card h2 {
+ margin: 0 0 0.4rem;
+ font-size: 0.98rem;
+ font-weight: 800;
+}
+
+.pf-contact-card p {
+ margin: 0 0 0.85rem;
+ font-size: 0.84rem;
+ line-height: 1.6;
+ color: var(--pf-muted);
+}
+
+.pf-contact-card-link {
+ font-size: 0.86rem;
+ font-weight: 700;
+ color: var(--pf-ink);
+ text-decoration: none;
+}
+
+.pf-contact-card-link:hover {
+ text-decoration: underline;
+}
+
+.pf-contact-form-block {
+ background: #f6f8fa;
+ border: 1px solid color-mix(in srgb, var(--pf-line) 70%, transparent);
+ border-radius: 16px;
+ padding: 1.25rem 1.35rem 1.35rem;
+}
+
+.pf-contact-form-block h2 {
+ margin: 0 0 0.35rem;
+ font-size: 1.05rem;
+ font-weight: 800;
+}
+
+.pf-contact-form-block > .pf-muted {
+ margin: 0 0 1rem;
+ font-size: 0.86rem;
+}
+
+.pf-contact-form {
+ display: flex;
+ flex-direction: column;
+ gap: 0.85rem;
+}
+
+.pf-contact-form label {
+ display: flex;
+ flex-direction: column;
+ gap: 0.35rem;
+ font-size: 0.86rem;
+ font-weight: 600;
+}
+
+.pf-contact-form input,
+.pf-contact-form select,
+.pf-contact-form textarea {
+ appearance: none;
+ border: 1px solid var(--pf-line);
+ border-radius: 10px;
+ padding: 0.6rem 0.75rem;
+ font: inherit;
+ font-weight: 500;
+ background: #fff;
+ color: var(--pf-ink);
+}
+
+.pf-contact-form textarea {
+ resize: vertical;
+ min-height: 120px;
+}
+
+.pf-contact-form .pf-btn {
+ align-self: flex-start;
+ margin-top: 0.25rem;
+}
+
+.pf-contact-sent {
+ margin: 0;
+ font-size: 0.84rem;
+}
+
+.pf-contact-sent a {
+ color: var(--pf-ink);
+ font-weight: 700;
+}
+
+@media (max-width: 800px) {
+ .pf-contact-channels {
+ grid-template-columns: 1fr;
+ }
+}
+
.pf-asset-thumb video {
width: 100%;
height: 100%;
@@ -2233,6 +2544,16 @@
font-size: 0.75rem;
font-weight: 700;
color: var(--pf-ink);
+ padding: 0;
+ overflow: hidden;
+ cursor: pointer;
+}
+
+.pf-avatar .pf-user-avatar {
+ width: 100%;
+ height: 100%;
+ border: none;
+ background: transparent;
}
.pf-btn {
@@ -4230,16 +4551,66 @@ button.pf-shot-editable:disabled {
justify-content: center;
align-items: center;
gap: 0.35rem;
+ margin-top: 0;
+}
+
+.pf-list-pagination {
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ gap: 0.65rem;
margin-top: 1.25rem;
}
-.pf-page-btn {
- min-width: 34px;
- height: 34px;
- border: 1px solid var(--pf-line);
- background: #fff;
- border-radius: 8px;
- color: var(--pf-ink);
+.pf-list-pagination-summary {
+ margin: 0;
+ font-size: 0.78rem;
+ color: var(--pf-muted);
+ text-align: right;
+}
+
+.pf-list-pagination-bar {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.75rem 1rem;
+}
+
+.pf-list-pagination-bar .pf-pagination {
+ margin-left: auto;
+}
+
+.pf-page-size {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ font-size: 0.82rem;
+ color: var(--pf-muted);
+}
+
+.pf-page-size select {
+ border: 1px solid var(--pf-line);
+ border-radius: 8px;
+ padding: 0.35rem 0.5rem;
+ font: inherit;
+ font-size: 0.82rem;
+ color: var(--pf-ink);
+ background: #fff;
+ cursor: pointer;
+}
+
+.pf-page-size select:hover {
+ border-color: rgba(182, 255, 0, 0.7);
+}
+
+.pf-page-btn {
+ min-width: 34px;
+ height: 34px;
+ border: 1px solid var(--pf-line);
+ background: #fff;
+ border-radius: 8px;
+ color: var(--pf-ink);
font-weight: 600;
font-size: 0.88rem;
}
@@ -4398,6 +4769,111 @@ button.pf-shot-editable:disabled {
margin-top: 1rem;
}
+.pf-usage-records {
+ margin-top: 1.25rem;
+}
+
+.pf-usage-records.is-compact {
+ margin-top: 1.5rem;
+}
+
+.pf-usage-records-head {
+ margin-bottom: 0.75rem;
+}
+
+.pf-usage-records-head h3 {
+ margin: 0 0 0.2rem;
+ font-size: 1rem;
+}
+
+.pf-usage-records-head p {
+ margin: 0;
+ font-size: 0.82rem;
+}
+
+.pf-usage-records-list {
+ margin-top: 0;
+}
+
+.pf-usage-record-row {
+ align-items: flex-start;
+}
+
+.pf-usage-record-meta {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-end;
+ gap: 0.15rem;
+ flex-shrink: 0;
+}
+
+.pf-usage-record-meta strong {
+ font-variant-numeric: tabular-nums;
+}
+
+.pf-usage-record-charge {
+ color: #b45309;
+}
+
+.pf-api-create {
+ display: flex;
+ gap: 0.6rem;
+ margin: 1rem 0;
+ flex-wrap: wrap;
+}
+
+.pf-api-create input {
+ flex: 1;
+ min-width: 180px;
+ border: 1px solid var(--pf-line);
+ border-radius: 10px;
+ padding: 0.55rem 0.75rem;
+ font: inherit;
+}
+
+.pf-api-secret {
+ margin: 0.75rem 0 1rem;
+ padding: 0.85rem 1rem;
+ border-radius: 12px;
+ border: 1px solid #fde68a;
+ background: #fffbeb;
+}
+
+.pf-api-secret code {
+ display: block;
+ margin: 0.5rem 0;
+ word-break: break-all;
+ font-size: 0.82rem;
+}
+
+.pf-api-key-list {
+ margin-top: 0.75rem;
+}
+
+.pf-api-docs {
+ margin-top: 1.5rem;
+ padding-top: 1.25rem;
+ border-top: 1px solid var(--pf-line);
+}
+
+.pf-api-docs h3 {
+ margin: 0 0 0.75rem;
+ font-size: 1rem;
+}
+
+.pf-api-docs pre {
+ margin: 0.35rem 0 1rem;
+ padding: 0.75rem 0.85rem;
+ border-radius: 10px;
+ background: #0f172a;
+ color: #e2e8f0;
+ font-size: 0.75rem;
+ line-height: 1.45;
+ overflow-x: auto;
+ white-space: pre-wrap;
+ word-break: break-all;
+}
+
.pf-usage-card-head {
margin-bottom: 0.85rem;
}
@@ -4499,17 +4975,27 @@ button.pf-shot-editable:disabled {
/* —— Pricing / top-up page —— */
.pf-pricing-page {
- width: min(1080px, 100%);
+ width: 100%;
margin: 0 auto;
- padding: 1.75rem 0 3rem;
+ padding: 0 0 2rem;
+}
+
+.pf-pricing-hero-band {
+ margin: 0 calc(-1 * var(--pf-shell-pad, 1.5rem)) 0;
+ padding: 2.5rem var(--pf-shell-pad, 1.5rem) 3.25rem;
+ background:
+ radial-gradient(ellipse 70% 80% at 0% 0%, rgba(186, 230, 253, 0.55), transparent 58%),
+ radial-gradient(ellipse 60% 70% at 100% 20%, rgba(190, 242, 100, 0.35), transparent 55%),
+ linear-gradient(180deg, #f3f8fc 0%, #fafcfb 100%);
}
-.pf-pricing-hero {
+.pf-pricing-hero-inner {
display: grid;
- grid-template-columns: minmax(0, 1.15fr) minmax(320px, 0.95fr);
+ grid-template-columns: minmax(0, 1.15fr) minmax(300px, 380px);
gap: 1.5rem;
- align-items: stretch;
- margin-bottom: 2rem;
+ align-items: center;
+ max-width: 1180px;
+ margin: 0 auto;
}
.pf-pricing-hero-copy {
@@ -4517,108 +5003,178 @@ button.pf-shot-editable:disabled {
padding-top: 0.35rem;
}
-.pf-pricing-pill {
+.pf-pricing-hero-copy h1 {
+ margin: 0 0 0.55rem;
+ font-size: clamp(2rem, 3.5vw, 2.65rem);
+ line-height: 1.15;
+ letter-spacing: -0.03em;
+ font-weight: 800;
+}
+
+.pf-pricing-hero-copy > p {
+ margin: 0;
+ max-width: 32rem;
+ color: var(--pf-muted);
+ font-size: 0.98rem;
+ line-height: 1.65;
+}
+
+.pf-pricing-hero-features {
+ list-style: none;
+ margin: 1.35rem 0 0;
+ padding: 0;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.65rem 1.25rem;
+}
+
+.pf-pricing-hero-features li {
display: inline-flex;
align-items: center;
- padding: 0.28rem 0.7rem;
- border-radius: 999px;
- background: color-mix(in srgb, var(--pf-lime) 28%, #fff);
- color: #3d4a12;
- font-size: 0.78rem;
+ gap: 0.4rem;
+ font-size: 0.86rem;
font-weight: 600;
- letter-spacing: 0.02em;
+ color: #3d4654;
}
-.pf-pricing-hero-copy h1 {
- margin: 0.85rem 0 0.55rem;
- font-size: clamp(1.85rem, 3.2vw, 2.35rem);
- line-height: 1.2;
- letter-spacing: -0.02em;
- font-weight: 800;
+.pf-pricing-hero-feature-icon {
+ display: inline-grid;
+ place-items: center;
+ width: 1.65rem;
+ height: 1.65rem;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--pf-lime) 38%, #fff);
+ color: #3d4a12;
}
-.pf-pricing-hero-copy p {
- margin: 0;
- max-width: 34rem;
+.pf-pricing-guest-tip {
+ margin: 1.1rem 0 0;
+ font-size: 0.9rem;
color: var(--pf-muted);
- font-size: 0.95rem;
- line-height: 1.7;
}
-.pf-pricing-balance-card {
- display: grid;
- grid-template-columns: 1.35fr 0.85fr 0.85fr auto;
- gap: 1rem;
+.pf-pricing-guest-tip a {
+ color: var(--pf-ink);
+ font-weight: 700;
+}
+
+/* 深色余额卡片 */
+.pf-pricing-wallet-dark {
+ background: linear-gradient(155deg, #243041 0%, #151c26 52%, #111820 100%);
+ color: #f3f5f8;
+ border-radius: 20px;
+ padding: 1.25rem 1.2rem 1rem;
+ box-shadow: 0 22px 48px rgba(17, 24, 39, 0.28);
+ transform: translateY(0.35rem);
+}
+
+.pf-pricing-wallet-dark-head {
+ display: flex;
align-items: center;
- background: var(--pf-card);
- border: 1px solid var(--pf-line);
- border-radius: 16px;
- box-shadow: var(--pf-shadow);
- padding: 1.15rem 1.2rem;
+ justify-content: space-between;
+ gap: 0.75rem;
+ margin-bottom: 0.45rem;
}
-.pf-pricing-balance-main {
- position: relative;
- padding-left: 0.85rem;
+.pf-pricing-wallet-dark-label {
+ font-size: 0.78rem;
+ color: rgba(243, 245, 248, 0.72);
}
-.pf-pricing-balance-main::before {
- content: '';
- position: absolute;
- left: 0;
- top: 0.15rem;
- bottom: 0.15rem;
- width: 4px;
+.pf-pricing-wallet-dark-actions {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+}
+
+.pf-pricing-wallet-eye,
+.pf-pricing-wallet-history {
+ appearance: none;
+ border: none;
+ background: rgba(255, 255, 255, 0.08);
+ color: rgba(243, 245, 248, 0.88);
border-radius: 999px;
- background: var(--pf-lime);
+ cursor: pointer;
+ transition: background 0.15s ease;
}
-.pf-pricing-balance-label {
- display: block;
- color: var(--pf-muted);
- font-size: 0.78rem;
- margin-bottom: 0.25rem;
+.pf-pricing-wallet-eye {
+ display: inline-grid;
+ place-items: center;
+ width: 1.75rem;
+ height: 1.75rem;
+ padding: 0;
}
-.pf-pricing-balance-main strong {
- font-size: 1.85rem;
+.pf-pricing-wallet-history {
+ padding: 0.32rem 0.7rem;
+ font-size: 0.74rem;
+ font-weight: 600;
+}
+
+.pf-pricing-wallet-eye:hover,
+.pf-pricing-wallet-history:hover:not(:disabled) {
+ background: rgba(255, 255, 255, 0.14);
+}
+
+.pf-pricing-wallet-history:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.pf-pricing-wallet-dark-balance {
+ display: block;
+ font-size: clamp(2rem, 4.5vw, 2.35rem);
font-weight: 800;
letter-spacing: -0.03em;
- line-height: 1.1;
+ line-height: 1.05;
+ margin-bottom: 1rem;
}
-.pf-pricing-balance-side em {
- font-style: normal;
- font-size: 1.05rem;
+.pf-pricing-wallet-dark-meta {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 0.75rem;
+ margin: 0;
+ padding-top: 0.85rem;
+ border-top: 1px solid rgba(255, 255, 255, 0.1);
+}
+
+.pf-pricing-wallet-dark-meta dt {
+ margin: 0 0 0.15rem;
+ font-size: 0.72rem;
+ color: rgba(243, 245, 248, 0.58);
+ font-weight: 500;
+}
+
+.pf-pricing-wallet-dark-meta dd {
+ margin: 0;
+ font-size: 0.98rem;
font-weight: 700;
}
-.pf-pricing-history-btn {
- appearance: none;
- border: 1px solid var(--pf-line);
- background: #fff;
- color: var(--pf-ink);
- border-radius: 999px;
- padding: 0.45rem 0.9rem;
- font-size: 0.82rem;
- font-weight: 600;
- cursor: pointer;
- white-space: nowrap;
+.pf-pricing-wallet-dark-frozen {
+ margin: 0.65rem 0 0;
+ font-size: 0.76rem;
+ color: rgba(243, 245, 248, 0.55);
}
-.pf-pricing-history-btn:hover:not(:disabled) {
- background: #f4f5f7;
+.pf-pricing-wallet-dark-updated {
+ margin: 0.75rem 0 0;
+ font-size: 0.72rem;
+ color: rgba(243, 245, 248, 0.42);
}
-.pf-pricing-history-btn:disabled {
- cursor: not-allowed;
- opacity: 0.55;
+.pf-pricing-body {
+ max-width: 1180px;
+ margin: 0 auto;
+ padding: 1.75rem var(--pf-shell-pad, 1.5rem) 0;
}
.pf-pricing-hint,
.pf-pricing-error {
text-align: left;
- margin: -0.5rem 0 1.25rem;
+ margin: 0 0 1.25rem;
}
.pf-pricing-section-head {
@@ -4626,9 +5182,17 @@ button.pf-shot-editable:disabled {
margin-bottom: 1rem;
}
+.pf-pricing-section-head.is-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1rem;
+ flex-wrap: wrap;
+}
+
.pf-pricing-section-head h2 {
- margin: 0 0 0.35rem;
- font-size: 1.25rem;
+ margin: 0;
+ font-size: 1.2rem;
font-weight: 800;
}
@@ -4638,6 +5202,127 @@ button.pf-shot-editable:disabled {
font-size: 0.9rem;
}
+.pf-pricing-pay-section {
+ margin-bottom: 2rem;
+}
+
+.pf-pricing-pay-tip {
+ margin: -0.35rem 0 0.85rem;
+ font-size: 0.84rem;
+ color: #b45309;
+}
+
+.pf-pricing-pay-grid {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: 0.75rem;
+}
+
+.pf-pricing-pay-tile {
+ position: relative;
+ appearance: none;
+ display: flex;
+ align-items: center;
+ gap: 0.55rem;
+ min-height: 58px;
+ padding: 0.75rem 0.9rem;
+ border: 1.5px solid var(--pf-line);
+ border-radius: 14px;
+ background: #fff;
+ color: var(--pf-ink);
+ cursor: pointer;
+ text-align: left;
+ transition: border-color 0.15s ease, box-shadow 0.15s ease;
+}
+
+.pf-pricing-pay-tile:hover:not(:disabled) {
+ border-color: color-mix(in srgb, var(--pf-ink) 22%, var(--pf-line));
+}
+
+.pf-pricing-pay-tile.is-active {
+ border-color: var(--pf-lime);
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--pf-lime) 65%, transparent);
+}
+
+.pf-pricing-pay-tile.is-disabled {
+ opacity: 0.72;
+ cursor: not-allowed;
+ background: #fafbfc;
+}
+
+.pf-pricing-pay-tile-label {
+ font-size: 0.92rem;
+ font-weight: 700;
+}
+
+.pf-pricing-pay-tile-badge {
+ font-size: 0.65rem;
+ font-weight: 800;
+ color: #3d4a12;
+ background: color-mix(in srgb, var(--pf-lime) 55%, #fff);
+ padding: 0.12rem 0.38rem;
+ border-radius: 999px;
+}
+
+.pf-pricing-pay-tile-soon,
+.pf-pricing-pay-tile-sub {
+ margin-left: auto;
+ font-size: 0.72rem;
+ font-weight: 600;
+ color: var(--pf-muted);
+}
+
+.pf-pricing-pay-tile-check {
+ margin-left: auto;
+ display: inline-grid;
+ place-items: center;
+ width: 1.35rem;
+ height: 1.35rem;
+ border-radius: 50%;
+ background: var(--pf-lime);
+ color: var(--pf-ink);
+}
+
+.pf-pricing-pay-tile-icon {
+ display: inline-grid;
+ place-items: center;
+ width: 28px;
+ height: 28px;
+ border-radius: 8px;
+ background: #eef0f3;
+ color: #4b5563;
+ flex-shrink: 0;
+}
+
+.pf-pricing-pay-trust {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ color: var(--pf-muted);
+ font-size: 0.84rem;
+ font-weight: 600;
+}
+
+.pf-pay-brand-icon {
+ display: block;
+ flex-shrink: 0;
+ border-radius: 8px;
+}
+
+.pf-pay-brand-icon.is-sm {
+ width: 22px;
+ height: 22px;
+}
+
+.pf-pay-brand-icon.is-md {
+ width: 28px;
+ height: 28px;
+}
+
+.pf-pricing-skus {
+ margin-bottom: 2rem;
+}
+
.pf-pricing-sku-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
@@ -4647,19 +5332,27 @@ button.pf-shot-editable:disabled {
.pf-pricing-sku-card {
position: relative;
text-align: left;
- background: var(--pf-card);
+ background: #fff;
border: 1px solid var(--pf-line);
- border-radius: 16px;
- padding: 1.25rem 1.1rem 1.15rem;
- box-shadow: 0 6px 20px rgba(17, 19, 24, 0.04);
+ border-radius: 18px;
+ padding: 1.2rem 1.05rem 1.1rem;
+ box-shadow: 0 8px 24px rgba(17, 19, 24, 0.04);
display: flex;
flex-direction: column;
- min-height: 250px;
+ min-height: 260px;
+ transition: transform 0.15s ease, box-shadow 0.15s ease;
+}
+
+.pf-pricing-sku-card:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 12px 28px rgba(17, 19, 24, 0.07);
}
.pf-pricing-sku-card.is-recommended {
border-color: var(--pf-lime);
- box-shadow: 0 10px 28px color-mix(in srgb, var(--pf-lime) 28%, transparent);
+ box-shadow:
+ 0 0 0 1px color-mix(in srgb, var(--pf-lime) 55%, transparent),
+ 0 14px 32px color-mix(in srgb, var(--pf-lime) 20%, transparent);
}
.pf-pricing-rec-badge {
@@ -4674,10 +5367,18 @@ button.pf-shot-editable:disabled {
border-radius: 999px;
}
-.pf-pricing-sku-card h3 {
- margin: 0 0 0.85rem;
- font-size: 0.95rem;
+.pf-pricing-sku-tier {
+ margin: 0 0 0.15rem;
+ font-size: 0.92rem;
font-weight: 700;
+ color: var(--pf-ink);
+}
+
+.pf-pricing-sku-hint {
+ margin: 0 0 0.85rem;
+ font-size: 0.78rem;
+ font-weight: 500;
+ color: var(--pf-muted);
}
.pf-pricing-sku-price {
@@ -4693,7 +5394,7 @@ button.pf-shot-editable:disabled {
}
.pf-pricing-sku-price strong {
- font-size: 2.35rem;
+ font-size: 2.45rem;
font-weight: 800;
letter-spacing: -0.04em;
line-height: 1;
@@ -4705,6 +5406,12 @@ button.pf-shot-editable:disabled {
font-size: 0.88rem;
}
+.pf-pricing-sku-credit em {
+ font-style: normal;
+ color: var(--pf-ink);
+ font-weight: 700;
+}
+
.pf-pricing-sku-bonus {
margin: 0.35rem 0 0;
color: #5f7a12;
@@ -4750,117 +5457,51 @@ button.pf-shot-editable:disabled {
cursor: wait;
}
-.pf-pricing-paybar {
- margin-top: 1.35rem;
- display: flex;
- align-items: center;
- justify-content: space-between;
+.pf-pricing-info {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
gap: 1rem;
- flex-wrap: wrap;
- background: #eef0f3;
- border: none;
- border-radius: 14px;
- padding: 0.85rem 1.1rem;
-}
-
-.pf-pricing-pay-left {
- display: flex;
- align-items: center;
- gap: 0.65rem;
- flex-wrap: wrap;
-}
-
-.pf-pricing-pay-label {
- color: var(--pf-muted);
- font-size: 0.88rem;
- font-weight: 600;
- margin-right: 0.25rem;
-}
-
-.pf-pricing-pay-opt {
- appearance: none;
- display: inline-flex;
- align-items: center;
- gap: 0.4rem;
- border: 1px solid var(--pf-line);
- background: #fff;
- color: var(--pf-ink);
- border-radius: 999px;
- padding: 0.45rem 0.85rem;
- font-size: 0.88rem;
- font-weight: 600;
- cursor: pointer;
-}
-
-.pf-pricing-pay-opt.is-active {
- background: var(--pf-ink);
- border-color: var(--pf-ink);
- color: #fff;
+ margin-bottom: 2.5rem;
}
-.pf-pay-logo {
- width: 1.05rem;
- height: 1.05rem;
- border-radius: 0.25rem;
- display: inline-block;
- background: center / contain no-repeat;
-}
-
-.pf-pay-logo.alipay {
- background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Crect width='24' height='24' rx='4' fill='%231677FF'/%3E%3Cpath fill='%23fff' d='M5.2 14.2c1.7 1.1 3.8 2 6.2 2.4.4-1 .8-2.2 1.1-3.4H8.2V11h5.1c.1-.5.2-1 .2-1.4H8.2V8h6.8v1.1c0 .6-.1 1.4-.3 2.2H18v1.5h-2.7c-.3 1.2-.7 2.4-1.2 3.5 2.1-.1 4-.7 5.5-1.5v1.8c-1.9 1.1-4.3 1.8-7 1.8-3.4 0-6.4-1.1-8.4-2.6l1-.6z'/%3E%3C/svg%3E");
-}
-
-.pf-pay-logo.wxpay {
- background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Crect width='24' height='24' rx='4' fill='%2307C160'/%3E%3Cpath fill='%23fff' d='M9.4 7.2c-2.9 0-5.2 1.9-5.2 4.2 0 1.3.7 2.5 1.9 3.3l-.5 1.5 1.7-.9c.6.2 1.2.3 1.9.3.2 0 .4 0 .6-.1-.3-.5-.4-1.1-.4-1.7 0-2.3 2.2-4.2 4.9-4.2.2 0 .5 0 .7.1C14.3 8.4 12 7.2 9.4 7.2zm-2 2.5a.7.7 0 1 1 0 1.4.7.7 0 0 1 0-1.4zm3.4 0a.7.7 0 1 1 0 1.4.7.7 0 0 1 0-1.4zm4.1.8c-2.4 0-4.3 1.6-4.3 3.6 0 .7.3 1.4.7 1.9l-.4 1.2 1.4-.7c.5.2 1 .3 1.5.3 2.4 0 4.3-1.6 4.3-3.6s-1.9-2.7-4.3-2.7zm-1.5 2a.55.55 0 1 1 0 1.1.55.55 0 0 1 0-1.1zm2.9 0a.55.55 0 1 1 0 1.1.55.55 0 0 1 0-1.1z'/%3E%3C/svg%3E");
+.pf-pricing-info-card {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 1rem;
+ align-items: start;
+ background: #f6f8fa;
+ border: 1px solid color-mix(in srgb, var(--pf-line) 70%, transparent);
+ border-radius: 16px;
+ padding: 1.25rem 1.35rem;
+ text-align: left;
}
-.pf-pay-check {
- display: inline-grid;
+.pf-pricing-info-visual {
+ display: grid;
place-items: center;
- width: 1rem;
- height: 1rem;
- border-radius: 50%;
- background: #fff;
- color: var(--pf-ink);
- font-size: 0.65rem;
- font-weight: 800;
- line-height: 1;
+ width: 3.5rem;
+ height: 3.5rem;
+ border-radius: 14px;
+ flex-shrink: 0;
}
-.pf-pricing-pay-secure {
- display: inline-flex;
- align-items: center;
- gap: 0.4rem;
- color: var(--pf-muted);
- font-size: 0.86rem;
- font-weight: 600;
+.pf-pricing-info-visual.is-billing {
+ background: linear-gradient(145deg, #dbeafe, #eff6ff);
+ color: #2563eb;
}
-.pf-pay-shield {
- width: 0.95rem;
- height: 0.95rem;
- background: center / contain no-repeat
- url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23111318' stroke-width='2'%3E%3Cpath d='M12 3l7 3v5c0 5-3.5 8.5-7 10-3.5-1.5-7-5-7-10V6l7-3z'/%3E%3Cpath d='M9.5 12.2l1.8 1.8 3.4-3.6'/%3E%3C/svg%3E");
-}
-
-.pf-pricing-info {
- margin-top: 1.35rem;
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 2rem;
- background: #eef0f3;
- border-radius: 16px;
- padding: 1.35rem 1.5rem;
- text-align: left;
+.pf-pricing-info-visual.is-value {
+ background: linear-gradient(145deg, color-mix(in srgb, var(--pf-lime) 45%, #fff), #f7fee7);
+ color: #4d7c0f;
}
-.pf-pricing-info h3 {
+.pf-pricing-info-card h3 {
margin: 0 0 0.7rem;
font-size: 1rem;
font-weight: 800;
}
-.pf-pricing-info ul {
+.pf-pricing-info-card ul {
margin: 0;
padding-left: 1.1rem;
color: var(--pf-muted);
@@ -4891,31 +5532,62 @@ button.pf-shot-editable:disabled {
center / 0.7rem no-repeat;
}
-.pf-pricing-foot {
- margin: 2rem 0 0;
- text-align: center;
+.pf-pricing-site-foot {
+ display: grid;
+ grid-template-columns: 1fr auto 1fr;
+ align-items: center;
+ gap: 1rem;
+ padding: 1.5rem 0 0.5rem;
+ border-top: 1px solid var(--pf-line);
color: var(--pf-muted);
- font-size: 0.85rem;
+ font-size: 0.82rem;
+}
+
+.pf-pricing-site-brand {
+ margin: 0;
+ justify-self: start;
}
-.pf-pricing-foot a {
+.pf-pricing-site-brand a {
color: inherit;
text-decoration: none;
font-weight: 700;
}
-@media (max-width: 960px) {
- .pf-pricing-hero {
+.pf-pricing-site-links {
+ display: inline-flex;
+ gap: 1.25rem;
+ flex-wrap: wrap;
+ justify-content: center;
+}
+
+.pf-pricing-site-links a {
+ color: inherit;
+ text-decoration: none;
+}
+
+.pf-pricing-site-links a:hover {
+ color: var(--pf-ink);
+}
+
+.pf-pricing-site-copy {
+ margin: 0;
+ justify-self: end;
+ text-align: right;
+}
+
+@media (max-width: 1024px) {
+ .pf-pricing-hero-inner {
grid-template-columns: 1fr;
}
- .pf-pricing-balance-card {
- grid-template-columns: 1fr 1fr;
+ .pf-pricing-wallet-dark {
+ transform: none;
+ max-width: 420px;
}
- .pf-pricing-history-btn {
- grid-column: 1 / -1;
- justify-self: start;
+ .pf-pricing-pay-grid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
}
.pf-pricing-sku-grid {
@@ -4924,13 +5596,35 @@ button.pf-shot-editable:disabled {
}
@media (max-width: 640px) {
+ .pf-pricing-hero-band {
+ padding-top: 1.75rem;
+ padding-bottom: 2rem;
+ }
+
+ .pf-pricing-hero-features {
+ flex-direction: column;
+ gap: 0.55rem;
+ }
+
+ .pf-pricing-pay-grid,
.pf-pricing-sku-grid,
.pf-pricing-info {
grid-template-columns: 1fr;
}
- .pf-pricing-balance-card {
+ .pf-pricing-info-card {
+ grid-template-columns: 1fr;
+ }
+
+ .pf-pricing-site-foot {
grid-template-columns: 1fr;
+ text-align: center;
+ }
+
+ .pf-pricing-site-brand,
+ .pf-pricing-site-copy {
+ justify-self: center;
+ text-align: center;
}
}
@@ -5064,19 +5758,17 @@ button.pf-shot-editable:disabled {
width: 2rem;
height: 2rem;
transform: translate(-50%, -50%);
- border-radius: 0.4rem;
+ border-radius: 0.45rem;
box-shadow: 0 0 0 3px #fff;
background: center / contain no-repeat;
}
.pf-pay-qr-badge.alipay {
- background-color: #1677ff;
- background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23fff' d='M5.2 14.2c1.7 1.1 3.8 2 6.2 2.4.4-1 .8-2.2 1.1-3.4H8.2V11h5.1c.1-.5.2-1 .2-1.4H8.2V8h6.8v1.1c0 .6-.1 1.4-.3 2.2H18v1.5h-2.7c-.3 1.2-.7 2.4-1.2 3.5 2.1-.1 4-.7 5.5-1.5v1.8c-1.9 1.1-4.3 1.8-7 1.8-3.4 0-6.4-1.1-8.4-2.6l1-.6z'/%3E%3C/svg%3E");
+ background-image: url('/payment/alipay.svg');
}
.pf-pay-qr-badge.wxpay {
- background-color: #07c160;
- background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23fff' d='M9.4 7.2c-2.9 0-5.2 1.9-5.2 4.2 0 1.3.7 2.5 1.9 3.3l-.5 1.5 1.7-.9c.6.2 1.2.3 1.9.3.2 0 .4 0 .6-.1-.3-.5-.4-1.1-.4-1.7 0-2.3 2.2-4.2 4.9-4.2.2 0 .5 0 .7.1C14.3 8.4 12 7.2 9.4 7.2zm-2 2.5a.7.7 0 1 1 0 1.4.7.7 0 0 1 0-1.4zm3.4 0a.7.7 0 1 1 0 1.4.7.7 0 0 1 0-1.4zm4.1.8c-2.4 0-4.3 1.6-4.3 3.6 0 .7.3 1.4.7 1.9l-.4 1.2 1.4-.7c.5.2 1 .3 1.5.3 2.4 0 4.3-1.6 4.3-3.6s-1.9-2.7-4.3-2.7zm-1.5 2a.55.55 0 1 1 0 1.1.55.55 0 0 1 0-1.1zm2.9 0a.55.55 0 1 1 0 1.1.55.55 0 0 1 0-1.1z'/%3E%3C/svg%3E");
+ background-image: url('/payment/wechatpay.svg');
}
.pf-pay-tip {
@@ -5189,6 +5881,13 @@ button.pf-shot-editable:disabled {
cursor: not-allowed;
}
+.pf-pay-shield {
+ width: 0.95rem;
+ height: 0.95rem;
+ background: center / contain no-repeat
+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23111318' stroke-width='2'%3E%3Cpath d='M12 3l7 3v5c0 5-3.5 8.5-7 10-3.5-1.5-7-5-7-10V6l7-3z'/%3E%3Cpath d='M9.5 12.2l1.8 1.8 3.4-3.6'/%3E%3C/svg%3E");
+}
+
.pf-pay-secure-line {
margin: 0;
display: inline-flex;