Skip to content

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

Ship drama backend/frontend (nav hidden), storyboard production cues, and compose fix.

yi7cb7dbaf5ead
diff --git a/README.md b/README.md
index 5868ce4..00a2568 100644
--- a/README.md
+++ b/README.md
@@ -10,6 +10,14 @@
- 分镜编辑、单张重绘、单镜头重生视频
- 作品发布与简单浏览
+## 漫剧模块(Drama)
+
+短剧/漫剧创作工作流:大纲 → 资产 → 分集分镜 → 画布。
+
+- 前端路由:`/drama`、`/drama/dramas`、`/drama/assets`、`/drama/projects/:projectId`、`/drama/projects/:projectId/episodes/:episodeId`、`/drama/projects/:projectId/canvas`
+- 后端 API:`/api/drama/*`(项目、剧本、资产、分集、生成、画布)
+- 管理后台:`/drama-projects`(列表分页,含用户邮箱)
+
## 本地启动
### 依赖
diff --git a/admin/src/App.tsx b/admin/src/App.tsx
index 3a99166..d081c75 100644
--- a/admin/src/App.tsx
+++ b/admin/src/App.tsx
@@ -5,6 +5,7 @@ import { DashboardPage } from "@/pages/DashboardPage";
import { LoginPage } from "@/pages/LoginPage";
import { OrdersPage } from "@/pages/OrdersPage";
import { ProjectsPage } from "@/pages/ProjectsPage";
+import { DramaProjectsPage } from "@/pages/DramaProjectsPage";
import { TemplatesPage } from "@/pages/TemplatesPage";
import { UsersPage } from "@/pages/UsersPage";
import { WorksPage } from "@/pages/WorksPage";
@@ -30,6 +31,7 @@ export default function App() {
<Route path="users" element={<UsersPage />} />
<Route path="orders" element={<OrdersPage />} />
<Route path="projects" element={<ProjectsPage />} />
+ <Route path="drama-projects" element={<DramaProjectsPage />} />
<Route path="works" element={<WorksPage />} />
<Route path="templates" element={<TemplatesPage />} />
</Route>
diff --git a/admin/src/components/PaginationBar.tsx b/admin/src/components/PaginationBar.tsx
index 9d12910..557d752 100644
--- a/admin/src/components/PaginationBar.tsx
+++ b/admin/src/components/PaginationBar.tsx
@@ -1,32 +1,101 @@
-import { Button } from "@/components/ui/button";
+import { ChevronLeft, ChevronRight } from "lucide-react";
+import { buildPageItems, DEFAULT_PAGE_SIZE } from "@/lib/pagination";
+import { cn } from "@/lib/utils";
type Props = {
page: number;
- pageSize: number;
+ pageSize?: number;
total: number;
onPageChange: (page: number) => void;
+ onPageSizeChange?: (size: number) => void;
+ pageSizeOptions?: number[];
+ className?: string;
};
-// Simple prev/next pagination
-export function PaginationBar({ page, pageSize, total, onPageChange }: Props) {
+/**
+ * Global admin pagination — default 10 / page, numbered pages + optional size
+ */
+export function PaginationBar({
+ page,
+ pageSize = DEFAULT_PAGE_SIZE,
+ total,
+ onPageChange,
+ onPageSizeChange,
+ pageSizeOptions = [10, 20, 50],
+ className,
+}: Props) {
const totalPages = Math.max(1, Math.ceil(total / pageSize));
+ const items = buildPageItems(page, totalPages);
+ const from = total === 0 ? 0 : (page - 1) * pageSize + 1;
+ const to = Math.min(page * pageSize, total);
+
return (
- <div className="flex items-center justify-between gap-3 pt-4 text-sm text-muted-foreground">
- <span>
- 共 {total} 条 · 第 {page}/{totalPages} 页
- </span>
- <div className="flex gap-2">
- <Button variant="outline" size="sm" disabled={page <= 1} onClick={() => onPageChange(page - 1)}>
- 上一页
- </Button>
- <Button
- variant="outline"
- size="sm"
+ <div
+ className={cn(
+ "flex flex-wrap items-center justify-between gap-3 rounded-xl bg-[#fafbfc] px-3 py-2.5 text-sm text-[#909399]",
+ className,
+ )}
+ >
+ <div className="flex flex-wrap items-center gap-3">
+ <span>
+ 共 <em className="not-italic font-semibold text-[#303133]">{total}</em> 条
+ <span className="mx-1.5 text-[#dcdfe6]">·</span>
+ {from}-{to}
+ </span>
+ {onPageSizeChange && (
+ <label className="flex items-center gap-1.5 text-xs">
+ <span>每页</span>
+ <select
+ className="h-7 rounded-md border border-[#dcdfe6] bg-white px-1.5 text-[#606266] outline-none focus:border-[#67c23a]"
+ value={pageSize}
+ onChange={(e) => onPageSizeChange(Number(e.target.value))}
+ >
+ {pageSizeOptions.map((n) => (
+ <option key={n} value={n}>
+ {n}
+ </option>
+ ))}
+ </select>
+ <span>条</span>
+ </label>
+ )}
+ </div>
+
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ className="admin-page-btn"
+ disabled={page <= 1}
+ onClick={() => onPageChange(page - 1)}
+ aria-label="上一页"
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </button>
+ {items.map((n, idx) =>
+ n === -1 ? (
+ <span key={`e-${idx}`} className="px-1.5 text-[#c0c4cc]">
+ …
+ </span>
+ ) : (
+ <button
+ key={n}
+ type="button"
+ className={cn("admin-page-btn", n === page && "is-active")}
+ onClick={() => onPageChange(n)}
+ >
+ {n}
+ </button>
+ ),
+ )}
+ <button
+ type="button"
+ className="admin-page-btn"
disabled={page >= totalPages}
onClick={() => onPageChange(page + 1)}
+ aria-label="下一页"
>
- 下一页
- </Button>
+ <ChevronRight className="h-4 w-4" />
+ </button>
</div>
</div>
);
diff --git a/admin/src/components/layout/AdminLayout.tsx b/admin/src/components/layout/AdminLayout.tsx
index 40d7d6a..20ac476 100644
--- a/admin/src/components/layout/AdminLayout.tsx
+++ b/admin/src/components/layout/AdminLayout.tsx
@@ -1,15 +1,19 @@
-import { NavLink, Outlet, useNavigate } from "react-router-dom";
+import { useState } from "react";
+import { NavLink, Outlet, useLocation, useNavigate } from "react-router-dom";
import {
+ Bell,
Clapperboard,
FileVideo,
LayoutDashboard,
LogOut,
+ Maximize2,
+ Menu,
Receipt,
+ Settings,
Shapes,
Users,
} from "lucide-react";
import { clearAuth, getCachedUser } from "@/lib/auth";
-import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
const navItems = [
@@ -17,14 +21,31 @@ const navItems = [
{ to: "/users", label: "用户管理", icon: Users },
{ to: "/orders", label: "订单流水", icon: Receipt },
{ to: "/projects", label: "项目管理", icon: Clapperboard },
+ // 漫剧入口暂隐藏,路由与 API 仍保留
+ // { to: "/drama-projects", label: "漫剧项目", icon: Film },
{ to: "/works", label: "作品审核", icon: FileVideo },
{ to: "/templates", label: "模板管理", icon: Shapes },
];
-// Admin shell with sidebar navigation
+const titles: Record<string, string> = {
+ "/": "仪表盘",
+ "/users": "用户管理",
+ "/orders": "订单流水",
+ "/projects": "项目管理",
+ "/drama-projects": "漫剧项目",
+ "/works": "作品审核",
+ "/templates": "模板管理",
+};
+
+// Admin shell: sidebar + top bar matching ops console design
export function AdminLayout() {
const navigate = useNavigate();
+ const location = useLocation();
const user = getCachedUser();
+ /*
+ * collapsed sidebar collapsed state
+ */
+ const [collapsed, setCollapsed] = useState(false);
// Logout and return to login
function handleLogout() {
@@ -32,42 +53,87 @@ export function AdminLayout() {
navigate("/login");
}
+ const title = titles[location.pathname] ?? "管理后台";
+ const initial = (user?.nickname || user?.email || "A").slice(0, 1).toUpperCase();
+
return (
- <div className="flex min-h-screen bg-muted/30">
- <aside className="flex w-56 flex-col border-r bg-background">
- <div className="border-b px-4 py-5">
- <div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">PRINTFILM</div>
- <div className="text-lg font-semibold">管理后台</div>
+ <div className={cn("admin-app", collapsed && "is-collapsed")}>
+ <aside className="admin-sidebar">
+ <div className="admin-brand">
+ <div className="admin-brand-mark">PF</div>
+ {!collapsed && (
+ <div>
+ <div className="admin-brand-name">PRINTFILM</div>
+ <div className="admin-brand-sub">管理后台</div>
+ </div>
+ )}
</div>
- <nav className="flex flex-1 flex-col gap-1 p-3">
+ <nav className="admin-nav">
{navItems.map((item) => (
<NavLink
key={item.to}
to={item.to}
end={item.end}
- className={({ isActive }) =>
- cn(
- "flex items-center gap-2 rounded-md px-3 py-2 text-sm transition-colors",
- isActive ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-accent hover:text-accent-foreground",
- )
- }
+ className={({ isActive }) => cn("admin-nav-item", isActive && "is-active")}
+ title={item.label}
>
- <item.icon className="h-4 w-4" />
- {item.label}
+ <item.icon className="h-[18px] w-[18px] shrink-0" />
+ {!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="border-t p-3">
- <div className="mb-2 truncate px-1 text-xs text-muted-foreground">{user?.email}</div>
- <Button variant="outline" size="sm" className="w-full" onClick={handleLogout}>
+ <div className="admin-user-card">
+ <div className="admin-avatar">{initial}</div>
+ {!collapsed && (
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[13px] font-medium text-[#303133]">{user?.email}</div>
+ <div className="text-xs text-[#909399]">超级管理员</div>
+ </div>
+ )}
+ <button type="button" className="admin-icon-btn" onClick={handleLogout} title="退出登录">
<LogOut className="h-4 w-4" />
- 退出登录
- </Button>
+ </button>
</div>
</aside>
- <main className="flex-1 overflow-auto p-6">
- <Outlet />
- </main>
+
+ <div className="admin-main">
+ <header className="admin-topbar">
+ <div className="flex items-center gap-3">
+ <button
+ type="button"
+ className="admin-icon-btn"
+ onClick={() => setCollapsed((v) => !v)}
+ aria-label="折叠侧栏"
+ >
+ <Menu className="h-4 w-4" />
+ </button>
+ <h1 className="text-base font-semibold text-[#303133]">{title}</h1>
+ </div>
+ <div className="flex items-center gap-1">
+ <button type="button" className="admin-icon-btn" title="通知">
+ <Bell className="h-4 w-4" />
+ </button>
+ <button
+ type="button"
+ className="admin-icon-btn"
+ title="全屏"
+ onClick={() => {
+ if (!document.fullscreenElement) void document.documentElement.requestFullscreen();
+ else void document.exitFullscreen();
+ }}
+ >
+ <Maximize2 className="h-4 w-4" />
+ </button>
+ </div>
+ </header>
+ <main className="admin-content">
+ <Outlet />
+ </main>
+ </div>
</div>
);
}
diff --git a/admin/src/components/ui/badge.tsx b/admin/src/components/ui/badge.tsx
index 8f7f0a9..fb0a9a2 100644
--- a/admin/src/components/ui/badge.tsx
+++ b/admin/src/components/ui/badge.tsx
@@ -1,22 +1,27 @@
import * as React from "react";
import { cn } from "@/lib/utils";
-// Status / tag badge
+// Status / tag badge — soft admin chips
export function Badge({
className,
variant = "default",
...props
-}: React.ComponentProps<"span"> & { variant?: "default" | "secondary" | "outline" | "destructive" }) {
+}: React.ComponentProps<"span"> & {
+ variant?: "default" | "secondary" | "outline" | "destructive" | "success" | "warning" | "info";
+}) {
const variants = {
- default: "border-transparent bg-primary text-primary-foreground",
- secondary: "border-transparent bg-secondary text-secondary-foreground",
- outline: "text-foreground",
- destructive: "border-transparent bg-destructive text-white",
+ default: "border-transparent bg-[#303133] text-white",
+ secondary: "border-transparent bg-[#f4f4f5] text-[#606266]",
+ outline: "border-[#dcdfe6] bg-white text-[#606266]",
+ destructive: "border-transparent bg-[#fef0f0] text-[#f56c6c]",
+ success: "border-transparent bg-[#f0f9eb] text-[#67c23a]",
+ warning: "border-transparent bg-[#fdf6ec] text-[#e6a23c]",
+ info: "border-transparent bg-[#ecf5ff] text-[#409eff]",
};
return (
<span
className={cn(
- "inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-semibold",
+ "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium tracking-wide",
variants[variant],
className,
)}
diff --git a/admin/src/components/ui/button.tsx b/admin/src/components/ui/button.tsx
index 3ec645a..805d5f3 100644
--- a/admin/src/components/ui/button.tsx
+++ b/admin/src/components/ui/button.tsx
@@ -4,20 +4,25 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
- "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
+ "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg text-sm font-medium transition-all duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#c2e7b0] focus-visible:ring-offset-1 disabled:pointer-events-none disabled:opacity-45 active:scale-[0.98]",
{
variants: {
variant: {
- default: "bg-primary text-primary-foreground hover:bg-primary/90",
- secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
- outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
- ghost: "hover:bg-accent hover:text-accent-foreground",
- destructive: "bg-destructive text-white hover:bg-destructive/90",
+ default:
+ "bg-[#67c23a] text-white shadow-sm shadow-[#67c23a]/25 hover:bg-[#85ce61]",
+ secondary:
+ "bg-[#f4f4f5] text-[#606266] hover:bg-[#e9e9eb] hover:text-[#303133]",
+ outline:
+ "border border-[#dcdfe6] bg-white text-[#606266] hover:border-[#c2e7b0] hover:text-[#67c23a]",
+ ghost: "text-[#606266] hover:bg-[#f5f7fa] hover:text-[#303133]",
+ destructive:
+ "bg-[#f56c6c] text-white shadow-sm shadow-[#f56c6c]/20 hover:bg-[#f78989]",
+ soft: "bg-[#f0f9eb] text-[#67c23a] hover:bg-[#e1f3d8]",
},
size: {
- default: "h-9 px-4 py-2",
+ default: "h-9 px-4",
sm: "h-8 rounded-md px-3 text-xs",
- lg: "h-10 rounded-md px-8",
+ lg: "h-10 rounded-lg px-6",
icon: "h-9 w-9",
},
},
@@ -34,7 +39,7 @@ export interface ButtonProps
asChild?: boolean;
}
-// shadcn-style button
+// Admin primary action button
export function Button({ className, variant, size, asChild = false, ...props }: ButtonProps) {
const Comp = asChild ? Slot : "button";
return <Comp className={cn(buttonVariants({ variant, size, className }))} {...props} />;
diff --git a/admin/src/components/ui/card.tsx b/admin/src/components/ui/card.tsx
index 1d8e7e6..c526763 100644
--- a/admin/src/components/ui/card.tsx
+++ b/admin/src/components/ui/card.tsx
@@ -1,23 +1,31 @@
import * as React from "react";
import { cn } from "@/lib/utils";
-// Card container
+// Soft elevated card panel
export function Card({ className, ...props }: React.ComponentProps<"div">) {
- return <div className={cn("rounded-xl border bg-card text-card-foreground shadow-sm", className)} {...props} />;
+ return (
+ <div
+ className={cn(
+ "rounded-2xl border border-[#ebeef5] bg-white text-[#303133] shadow-[0_1px_2px_rgba(16,24,40,0.04)]",
+ className,
+ )}
+ {...props}
+ />
+ );
}
export function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
- return <div className={cn("flex flex-col gap-1.5 p-6", className)} {...props} />;
+ return <div className={cn("flex flex-col gap-1.5 p-5 pb-3", className)} {...props} />;
}
export function CardTitle({ className, ...props }: React.ComponentProps<"h3">) {
- return <h3 className={cn("font-semibold leading-none tracking-tight", className)} {...props} />;
+ return <h3 className={cn("text-base font-semibold tracking-tight text-[#303133]", className)} {...props} />;
}
export function CardDescription({ className, ...props }: React.ComponentProps<"p">) {
- return <p className={cn("text-sm text-muted-foreground", className)} {...props} />;
+ return <p className={cn("text-sm text-[#909399]", className)} {...props} />;
}
export function CardContent({ className, ...props }: React.ComponentProps<"div">) {
- return <div className={cn("p-6 pt-0", className)} {...props} />;
+ return <div className={cn("p-5 pt-0", className)} {...props} />;
}
diff --git a/admin/src/components/ui/dialog.tsx b/admin/src/components/ui/dialog.tsx
index 2fed243..fbe40ff 100644
--- a/admin/src/components/ui/dialog.tsx
+++ b/admin/src/components/ui/dialog.tsx
@@ -14,16 +14,16 @@ export function DialogContent({
}: React.ComponentProps<typeof DialogPrimitive.Content>) {
return (
<DialogPrimitive.Portal>
- <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-black/50" />
+ <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-[#0f172a]/40 backdrop-blur-[2px] data-[state=open]:animate-in data-[state=closed]:animate-out" />
<DialogPrimitive.Content
className={cn(
- "fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border bg-background p-6 shadow-lg sm:rounded-lg",
+ "fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-5 border border-[#ebeef5] bg-white p-6 shadow-[0_20px_50px_rgba(15,23,42,0.16)] sm:rounded-2xl",
className,
)}
{...props}
>
{children}
- <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 hover:opacity-100">
+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-lg p-1.5 text-[#909399] transition-colors hover:bg-[#f5f7fa] hover:text-[#303133]">
<X className="h-4 w-4" />
</DialogPrimitive.Close>
</DialogPrimitive.Content>
@@ -32,16 +32,23 @@ export function DialogContent({
}
export function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
- return <div className={cn("flex flex-col gap-1.5 text-center sm:text-left", className)} {...props} />;
+ return <div className={cn("flex flex-col gap-1.5 text-left", className)} {...props} />;
}
export function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
- return <DialogPrimitive.Title className={cn("text-lg font-semibold", className)} {...props} />;
+ return (
+ <DialogPrimitive.Title
+ className={cn("text-lg font-semibold tracking-tight text-[#303133]", className)}
+ {...props}
+ />
+ );
}
export function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
- return <DialogPrimitive.Description className={cn("text-sm text-muted-foreground", className)} {...props} />;
+ return (
+ <DialogPrimitive.Description className={cn("text-sm text-[#909399]", className)} {...props} />
+ );
}
diff --git a/admin/src/components/ui/input.tsx b/admin/src/components/ui/input.tsx
index 2b6fe46..7f80d06 100644
--- a/admin/src/components/ui/input.tsx
+++ b/admin/src/components/ui/input.tsx
@@ -1,13 +1,13 @@
import * as React from "react";
import { cn } from "@/lib/utils";
-// Text input
+// Text input with soft focus ring
export function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
className={cn(
- "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
+ "flex h-9 w-full rounded-lg border border-[#dcdfe6] bg-white px-3 text-sm text-[#303133] shadow-[0_1px_2px_rgba(16,24,40,0.03)] transition-all placeholder:text-[#c0c4cc] hover:border-[#c0c4cc] focus-visible:border-[#67c23a] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#e1f3d8] disabled:cursor-not-allowed disabled:bg-[#f5f7fa] disabled:opacity-60",
className,
)}
{...props}
diff --git a/admin/src/components/ui/label.tsx b/admin/src/components/ui/label.tsx
index 87caa75..4f2308e 100644
--- a/admin/src/components/ui/label.tsx
+++ b/admin/src/components/ui/label.tsx
@@ -6,7 +6,10 @@ import { cn } from "@/lib/utils";
export function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
- className={cn("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70", className)}
+ className={cn(
+ "text-sm font-medium leading-none text-[#606266] peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
+ className,
+ )}
{...props}
/>
);
diff --git a/admin/src/components/ui/page.tsx b/admin/src/components/ui/page.tsx
new file mode 100644
index 0000000..dca20e4
--- /dev/null
+++ b/admin/src/components/ui/page.tsx
@@ -0,0 +1,64 @@
+import type { ReactNode } from "react";
+import { cn } from "@/lib/utils";
+
+type PageHeaderProps = {
+ title: string;
+ description?: string;
+ actions?: ReactNode;
+ className?: string;
+};
+
+// Consistent page title block used across admin pages
+export function PageHeader({ title, description, actions, className }: PageHeaderProps) {
+ return (
+ <div className={cn("mb-1 flex flex-wrap items-end justify-between gap-3", className)}>
+ <div>
+ <h2 className="text-xl font-semibold tracking-tight text-[#303133]">{title}</h2>
+ {description ? <p className="mt-1 text-sm text-[#909399]">{description}</p> : null}
+ </div>
+ {actions ? <div className="flex flex-wrap items-center gap-2">{actions}</div> : null}
+ </div>
+ );
+}
+
+type EmptyStateProps = {
+ title?: string;
+ description?: string;
+ className?: string;
+};
+
+// Empty list placeholder
+export function EmptyState({
+ title = "暂无数据",
+ description = "换个筛选条件再试试",
+ className,
+}: EmptyStateProps) {
+ return (
+ <div className={cn("flex flex-col items-center justify-center gap-1 py-14 text-center", className)}>
+ <div className="mb-2 flex h-12 w-12 items-center justify-center rounded-2xl bg-[#f5f7fa] text-lg text-[#c0c4cc]">
+ ∅
+ </div>
+ <div className="text-sm font-medium text-[#606266]">{title}</div>
+ <div className="text-xs text-[#909399]">{description}</div>
+ </div>
+ );
+}
+
+type ToolbarProps = {
+ children: ReactNode;
+ className?: string;
+};
+
+// Filter / search toolbar row
+export function Toolbar({ children, className }: ToolbarProps) {
+ return (
+ <div
+ className={cn(
+ "flex flex-wrap items-center gap-2 rounded-xl border border-[#ebeef5] bg-white p-3 shadow-[0_1px_2px_rgba(16,24,40,0.03)]",
+ className,
+ )}
+ >
+ {children}
+ </div>
+ );
+}
diff --git a/admin/src/components/ui/select.tsx b/admin/src/components/ui/select.tsx
index 5f82d5a..8ef64b5 100644
--- a/admin/src/components/ui/select.tsx
+++ b/admin/src/components/ui/select.tsx
@@ -1,14 +1,18 @@
import * as React from "react";
import { cn } from "@/lib/utils";
-// Native select styled like shadcn
+// Native select with admin chrome
export function Select({ className, ...props }: React.ComponentProps<"select">) {
return (
<select
className={cn(
- "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
+ "flex h-9 w-full appearance-none rounded-lg border border-[#dcdfe6] bg-white bg-[length:12px] bg-[right_12px_center] bg-no-repeat px-3 pr-8 text-sm text-[#303133] shadow-[0_1px_2px_rgba(16,24,40,0.03)] transition-all hover:border-[#c0c4cc] focus-visible:border-[#67c23a] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#e1f3d8] disabled:cursor-not-allowed disabled:bg-[#f5f7fa] disabled:opacity-60",
className,
)}
+ style={{
+ backgroundImage:
+ "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%909399' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E\")",
+ }}
{...props}
/>
);
@@ -19,7 +23,7 @@ export function Textarea({ className, ...props }: React.ComponentProps<"textarea
return (
<textarea
className={cn(
- "flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
+ "flex min-h-[96px] w-full rounded-lg border border-[#dcdfe6] bg-white px-3 py-2.5 text-sm text-[#303133] shadow-[0_1px_2px_rgba(16,24,40,0.03)] transition-all placeholder:text-[#c0c4cc] hover:border-[#c0c4cc] focus-visible:border-[#67c23a] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#e1f3d8] disabled:cursor-not-allowed disabled:bg-[#f5f7fa] disabled:opacity-60",
className,
)}
{...props}
diff --git a/admin/src/components/ui/switch.tsx b/admin/src/components/ui/switch.tsx
index 62554a7..6127551 100644
--- a/admin/src/components/ui/switch.tsx
+++ b/admin/src/components/ui/switch.tsx
@@ -2,17 +2,17 @@ import * as React from "react";
import * as SwitchPrimitive from "@radix-ui/react-switch";
import { cn } from "@/lib/utils";
-// Toggle switch
+// Soft green toggle switch
export function Switch({ className, ...props }: React.ComponentProps<typeof SwitchPrimitive.Root>) {
return (
<SwitchPrimitive.Root
className={cn(
- "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent bg-input transition-colors data-[state=checked]:bg-primary",
+ "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent bg-[#dcdfe6] transition-colors data-[state=checked]:bg-[#67c23a] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#e1f3d8]",
className,
)}
{...props}
>
- <SwitchPrimitive.Thumb className="pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0" />
+ <SwitchPrimitive.Thumb className="pointer-events-none block h-4 w-4 rounded-full bg-white shadow-md ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0" />
</SwitchPrimitive.Root>
);
}
diff --git a/admin/src/components/ui/table.tsx b/admin/src/components/ui/table.tsx
index d5c9249..794f561 100644
--- a/admin/src/components/ui/table.tsx
+++ b/admin/src/components/ui/table.tsx
@@ -1,17 +1,17 @@
import * as React from "react";
import { cn } from "@/lib/utils";
-// Table primitives
+// Table primitives tuned for admin lists
export function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
- <div className="relative w-full overflow-auto">
+ <div className="relative w-full overflow-auto rounded-xl border border-[#ebeef5] bg-white">
<table className={cn("w-full caption-bottom text-sm", className)} {...props} />
</div>
);
}
export function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
- return <thead className={cn("[&_tr]:border-b", className)} {...props} />;
+ return <thead className={cn("bg-[#fafbfc] [&_tr]:border-b [&_tr]:border-[#ebeef5]", className)} {...props} />;
}
export function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
@@ -19,18 +19,29 @@ export function TableBody({ className, ...props }: React.ComponentProps<"tbody">
}
export function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
- return <tr className={cn("border-b transition-colors hover:bg-muted/50", className)} {...props} />;
+ return (
+ <tr
+ className={cn(
+ "border-b border-[#f2f3f5] transition-colors hover:bg-[#f8fafc] data-[state=selected]:bg-[#f0f9eb]",
+ className,
+ )}
+ {...props}
+ />
+ );
}
export function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
- className={cn("h-10 px-3 text-left align-middle font-medium text-muted-foreground", className)}
+ className={cn(
+ "h-11 px-4 text-left align-middle text-xs font-medium tracking-wide text-[#909399]",
+ className,
+ )}
{...props}
/>
);
}
export function TableCell({ className, ...props }: React.ComponentProps<"td">) {
- return <td className={cn("p-3 align-middle", className)} {...props} />;
+ return <td className={cn("px-4 py-3.5 align-middle text-[#303133]", className)} {...props} />;
}
diff --git a/admin/src/components/ui/tabs.tsx b/admin/src/components/ui/tabs.tsx
index 3b760b2..b637a08 100644
--- a/admin/src/components/ui/tabs.tsx
+++ b/admin/src/components/ui/tabs.tsx
@@ -7,7 +7,10 @@ export const Tabs = TabsPrimitive.Root;
export function TabsList({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.List>) {
return (
<TabsPrimitive.List
- className={cn("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground", className)}
+ className={cn(
+ "inline-flex h-10 items-center gap-1 rounded-xl border border-[#ebeef5] bg-[#f5f7fa] p-1 text-[#909399]",
+ className,
+ )}
{...props}
/>
);
@@ -17,7 +20,7 @@ export function TabsTrigger({ className, ...props }: React.ComponentProps<typeof
return (
<TabsPrimitive.Trigger
className={cn(
- "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium transition-all data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",
+ "inline-flex items-center justify-center whitespace-nowrap rounded-lg px-3.5 py-1.5 text-sm font-medium transition-all data-[state=active]:bg-white data-[state=active]:text-[#303133] data-[state=active]:shadow-sm hover:text-[#606266]",
className,
)}
{...props}
diff --git a/admin/src/index.css b/admin/src/index.css
index a6f40e0..6c37c44 100644
--- a/admin/src/index.css
+++ b/admin/src/index.css
@@ -286,3 +286,325 @@
font-size: clamp(2.6rem, 12vw, 4rem);
}
}
+
+/* ---- Admin console shell (reference UI) ---- */
+.admin-app {
+ --admin-bg: #f5f7fa;
+ --admin-card: #ffffff;
+ --admin-text: #303133;
+ --admin-muted: #909399;
+ --admin-border: #ebeef5;
+ --admin-accent: #67c23a;
+ --admin-accent-soft: #f0f9eb;
+ --admin-sidebar: #ffffff;
+ --admin-sidebar-w: 220px;
+ display: flex;
+ min-height: 100vh;
+ background: var(--admin-bg);
+ color: var(--admin-text);
+ font-family: "Figtree", "PingFang SC", "Microsoft YaHei", sans-serif;
+}
+
+.admin-app.is-collapsed {
+ --admin-sidebar-w: 72px;
+}
+
+.admin-sidebar {
+ width: var(--admin-sidebar-w);
+ flex-shrink: 0;
+ display: flex;
+ flex-direction: column;
+ background: var(--admin-sidebar);
+ border-right: 1px solid var(--admin-border);
+ transition: width 0.2s ease;
+}
+
+.admin-brand {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ height: 64px;
+ padding: 0 1rem;
+ border-bottom: 1px solid var(--admin-border);
+}
+
+.admin-brand-mark {
+ width: 36px;
+ height: 36px;
+ border-radius: 10px;
+ display: grid;
+ place-items: center;
+ background: linear-gradient(145deg, #85ce61, #67c23a);
+ color: #fff;
+ font-size: 12px;
+ font-weight: 700;
+ letter-spacing: 0.02em;
+ flex-shrink: 0;
+}
+
+.admin-brand-name {
+ font-size: 14px;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ line-height: 1.2;
+}
+
+.admin-brand-sub {
+ font-size: 12px;
+ color: var(--admin-muted);
+}
+
+.admin-nav {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 12px 10px;
+ flex: 1;
+ overflow: auto;
+}
+
+.admin-nav-item {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-height: 42px;
+ padding: 0 12px;
+ border-radius: 10px;
+ color: #606266;
+ text-decoration: none;
+ font-size: 14px;
+ transition: background 0.15s, color 0.15s;
+}
+
+.admin-nav-item:hover {
+ background: #f5f7fa;
+ color: var(--admin-text);
+}
+
+.admin-nav-item.is-active {
+ background: #303133;
+ color: #fff;
+}
+
+.admin-nav-item.is-disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.admin-user-card {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin: 10px;
+ padding: 10px;
+ border-radius: 12px;
+ background: #f8fafc;
+ border: 1px solid var(--admin-border);
+}
+
+.admin-avatar {
+ width: 34px;
+ height: 34px;
+ border-radius: 999px;
+ display: grid;
+ place-items: center;
+ background: var(--admin-accent-soft);
+ color: var(--admin-accent);
+ font-size: 13px;
+ font-weight: 700;
+ flex-shrink: 0;
+}
+
+.admin-main {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+}
+
+.admin-topbar {
+ height: 56px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 0 20px;
+ background: #fff;
+ border-bottom: 1px solid var(--admin-border);
+}
+
+.admin-icon-btn {
+ width: 34px;
+ height: 34px;
+ border: 0;
+ border-radius: 8px;
+ background: transparent;
+ color: #606266;
+ display: grid;
+ place-items: center;
+ cursor: pointer;
+}
+
+.admin-icon-btn:hover {
+ background: #f5f7fa;
+ color: var(--admin-text);
+}
+
+.admin-content {
+ flex: 1;
+ overflow: auto;
+ padding: 20px 24px 32px;
+}
+
+.admin-panel {
+ background: var(--admin-card);
+ border: 1px solid var(--admin-border);
+ border-radius: 12px;
+ padding: 18px 20px;
+ box-shadow: 0 1px 2px rgba(16, 24, 40, 0.03);
+}
+
+.admin-stat-card {
+ position: relative;
+ overflow: hidden;
+}
+
+.admin-stat-icon {
+ position: absolute;
+ top: 16px;
+ right: 16px;
+ width: 40px;
+ height: 40px;
+ border-radius: 10px;
+ display: grid;
+ place-items: center;
+ background: var(--admin-accent-soft);
+ color: var(--admin-accent);
+}
+
+.admin-status-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 12px;
+ border-radius: 999px;
+ font-size: 13px;
+ font-weight: 500;
+ background: #f4f4f5;
+ color: #606266;
+}
+
+.admin-status-pill.is-done {
+ background: #f0f9eb;
+ color: #67c23a;
+}
+.admin-status-pill.is-run {
+ background: #ecf5ff;
+ color: #409eff;
+}
+.admin-status-pill.is-warn {
+ background: #fdf6ec;
+ color: #e6a23c;
+}
+.admin-status-pill.is-fail {
+ background: #fef0f0;
+ color: #f56c6c;
+}
+
+.admin-page-btn {
+ min-width: 32px;
+ height: 32px;
+ padding: 0 8px;
+ border: 1px solid transparent;
+ border-radius: 8px;
+ background: #fff;
+ color: #606266;
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ box-shadow: inset 0 0 0 1px #e4e7ed;
+ transition: color 0.15s, background 0.15s, box-shadow 0.15s, transform 0.1s;
+}
+
+.admin-page-btn:hover:not(:disabled) {
+ color: #67c23a;
+ box-shadow: inset 0 0 0 1px #c2e7b0;
+ background: #f0f9eb;
+}
+
+.admin-page-btn.is-active {
+ background: linear-gradient(180deg, #85ce61, #67c23a);
+ box-shadow: 0 4px 10px rgba(103, 194, 58, 0.28);
+ color: #fff;
+}
+
+.admin-page-btn:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+
+.admin-table-wrap {
+ overflow: auto;
+ border-radius: 10px;
+ border: 1px solid var(--admin-border);
+}
+
+.admin-table-wrap table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 13px;
+}
+
+.admin-table-wrap th {
+ text-align: left;
+ padding: 12px 14px;
+ background: #fafbfc;
+ color: #909399;
+ font-weight: 500;
+ border-bottom: 1px solid var(--admin-border);
+}
+
+.admin-table-wrap td {
+ padding: 12px 14px;
+ border-bottom: 1px solid #f2f3f5;
+ color: #303133;
+}
+
+.admin-table-wrap tr:last-child td {
+ border-bottom: 0;
+}
+
+.admin-quick-btn {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 8px;
+ padding: 14px;
+ border-radius: 10px;
+ border: 1px solid var(--admin-border);
+ background: #fafbfc;
+ color: var(--admin-text);
+ text-decoration: none;
+ font-size: 13px;
+ transition: border-color 0.15s, background 0.15s;
+}
+
+.admin-quick-btn:hover {
+ border-color: #c2e7b0;
+ background: var(--admin-accent-soft);
+}
+
+@media (max-width: 900px) {
+ .admin-app {
+ --admin-sidebar-w: 72px;
+ }
+ .admin-brand-name,
+ .admin-brand-sub,
+ .admin-nav-item span,
+ .admin-user-card .min-w-0 {
+ display: none;
+ }
+}
+
diff --git a/admin/src/lib/pagination.ts b/admin/src/lib/pagination.ts
new file mode 100644
index 0000000..e61cdbe
--- /dev/null
+++ b/admin/src/lib/pagination.ts
@@ -0,0 +1,22 @@
+/** Default page size for all admin list pages */
+export const DEFAULT_PAGE_SIZE = 10;
+
+/**
+ * Build page number list with ellipsis markers
+ * @param page current page (1-based)
+ * @param totalPages total pages
+ * @returns numbers and -1 for ellipsis
+ */
+export function buildPageItems(page: number, totalPages: number): number[] {
+ if (totalPages <= 7) {
+ return Array.from({ length: totalPages }, (_, i) => i + 1);
+ }
+ const items: number[] = [1];
+ const start = Math.max(2, page - 1);
+ const end = Math.min(totalPages - 1, page + 1);
+ if (start > 2) items.push(-1);
+ for (let i = start; i <= end; i++) items.push(i);
+ if (end < totalPages - 1) items.push(-1);
+ items.push(totalPages);
+ return items;
+}
diff --git a/admin/src/lib/statusLabels.ts b/admin/src/lib/statusLabels.ts
new file mode 100644
index 0000000..cbcd81a
--- /dev/null
+++ b/admin/src/lib/statusLabels.ts
@@ -0,0 +1,90 @@
+/** Project pipeline status → Chinese label */
+export const PROJECT_STATUS_LABELS: Record<string, string> = {
+ DRAFT: "草稿",
+ SCRIPTING: "脚本生成中",
+ SCRIPT_READY: "脚本就绪",
+ IMAGING: "分镜图生成中",
+ IMAGE_READY: "分镜图就绪",
+ VIDEOING: "视频生成中",
+ VIDEO_READY: "视频就绪",
+ AUDIOING: "配音中",
+ COMPOSING: "合成中",
+ AUDITING: "审核中",
+ DONE: "已完成",
+ REJECTED: "已拒绝",
+ FAILED: "失败",
+ CANCELLED: "已取消",
+};
+
+/** Order payment status → Chinese */
+export const ORDER_STATUS_LABELS: Record<string, string> = {
+ pending: "待支付",
+ paid: "已支付",
+ closed: "已关闭",
+};
+
+/** Work audit / visibility → Chinese */
+export const AUDIT_STATUS_LABELS: Record<string, string> = {
+ pending: "待审核",
+ passed: "已通过",
+ rejected: "已拒绝",
+};
+
+export const VISIBILITY_LABELS: Record<string, string> = {
+ public: "公开",
+ private: "私密",
+ unlisted: "不公开列出",
+};
+
+/** Wallet ledger kind → Chinese */
+export const LEDGER_KIND_LABELS: Record<string, string> = {
+ topup: "充值",
+ grant: "赠送",
+ adjust: "调账",
+ freeze: "冻结",
+ unfreeze: "解冻",
+ settle: "结算",
+ refund: "退款",
+};
+
+/** Payment channel → Chinese */
+export const PAY_TYPE_LABELS: Record<string, string> = {
+ alipay: "支付宝",
+ wxpay: "微信",
+};
+
+// Resolve project status display text
+export function projectStatusLabel(status: string): string {
+ return PROJECT_STATUS_LABELS[status] ?? status;
+}
+
+// Resolve order status display text
+export function orderStatusLabel(status: string): string {
+ return ORDER_STATUS_LABELS[status] ?? status;
+}
+
+// Resolve audit status display text
+export function auditStatusLabel(status: string): string {
+ return AUDIT_STATUS_LABELS[status] ?? status;
+}
+
+// Resolve visibility display text
+export function visibilityLabel(status: string): string {
+ return VISIBILITY_LABELS[status] ?? status;
+}
+
+// Resolve ledger kind display text
+export function ledgerKindLabel(kind: string): string {
+ return LEDGER_KIND_LABELS[kind] ?? kind;
+}
+
+// Resolve pay type display text
+export function payTypeLabel(payType: string): string {
+ return PAY_TYPE_LABELS[payType] ?? payType;
+}
+
+/** Filter options for project status select (value stays English for API) */
+export const PROJECT_STATUS_OPTIONS: { value: string; label: string }[] = [
+ { value: "", label: "全部状态" },
+ ...Object.entries(PROJECT_STATUS_LABELS).map(([value, label]) => ({ value, label })),
+];
diff --git a/admin/src/pages/DashboardPage.tsx b/admin/src/pages/DashboardPage.tsx
index 1686af6..df2fce5 100644
--- a/admin/src/pages/DashboardPage.tsx
+++ b/admin/src/pages/DashboardPage.tsx
@@ -1,17 +1,48 @@
import { useEffect, useState } from "react";
+import { Link } from "react-router-dom";
+import {
+ Banknote,
+ Clapperboard,
+ Receipt,
+ Shapes,
+ Users,
+ Wallet,
+} from "lucide-react";
import { toast } from "sonner";
-import { api, type AdminStats } from "@/api/client";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { api, type AdminOrder, type AdminStats, type PageMeta } from "@/api/client";
import { fenToYuan } from "@/lib/utils";
-import { Badge } from "@/components/ui/badge";
+import { orderStatusLabel, payTypeLabel, projectStatusLabel } from "@/lib/statusLabels";
-// Dashboard overview stats
+type OrderRes = { items: AdminOrder[]; meta: PageMeta };
+
+// Map project status to pill style
+function statusClass(status: string): string {
+ if (status === "DONE") return "is-done";
+ if (status === "FAILED" || status === "REJECTED" || status === "CANCELLED") return "is-fail";
+ if (status === "SCRIPTING" || status === "IMAGING" || status === "VIDEOING" || status === "COMPOSING") {
+ return "is-run";
+ }
+ return "is-warn";
+}
+
+// Dashboard matching reference ops console
export function DashboardPage() {
+ /*
+ * stats aggregate stats
+ * orders recent orders
+ */
const [stats, setStats] = useState<AdminStats | null>(null);
+ const [orders, setOrders] = useState<AdminOrder[]>([]);
useEffect(() => {
- api<AdminStats>("/api/admin/stats")
- .then(setStats)
+ Promise.all([
+ api<AdminStats>("/api/admin/stats"),
+ api<OrderRes>("/api/admin/orders?page=1&page_size=5"),
+ ])
+ .then(([s, o]) => {
+ setStats(s);
+ setOrders(o.items);
+ })
.catch((err) => toast.error(err instanceof Error ? err.message : "加载失败"));
}, []);
@@ -20,52 +51,144 @@ export function DashboardPage() {
);
return (
- <div className="space-y-6">
- <div>
- <h1 className="text-2xl font-semibold">仪表盘</h1>
- <p className="text-sm text-muted-foreground">用户、订单与项目状态概览</p>
+ <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]">用户、订单与项目状态概览</p>
+ </div>
</div>
+
<div className="grid gap-4 md:grid-cols-3">
- <Card>
- <CardHeader>
- <CardTitle className="text-sm font-medium text-muted-foreground">用户总数</CardTitle>
- </CardHeader>
- <CardContent className="text-3xl font-semibold">{stats?.user_count ?? "—"}</CardContent>
- </Card>
- <Card>
- <CardHeader>
- <CardTitle className="text-sm font-medium text-muted-foreground">累计已付金额</CardTitle>
- </CardHeader>
- <CardContent className="text-3xl font-semibold">
+ <div className="admin-panel admin-stat-card">
+ <div className="admin-stat-icon">
+ <Users className="h-5 w-5" />
+ </div>
+ <div className="text-sm text-[#909399]">用户总数</div>
+ <div className="mt-2 text-3xl font-semibold tracking-tight">{stats?.user_count ?? "—"}</div>
+ <div className="mt-1 text-xs text-[#c0c4cc]">总注册用户</div>
+ </div>
+ <div className="admin-panel admin-stat-card">
+ <div className="admin-stat-icon">
+ <Banknote className="h-5 w-5" />
+ </div>
+ <div className="text-sm text-[#909399]">累计已付金额</div>
+ <div className="mt-2 text-3xl font-semibold tracking-tight">
¥{stats ? fenToYuan(stats.order_paid_total_fen) : "—"}
- </CardContent>
- </Card>
- <Card>
- <CardHeader>
- <CardTitle className="text-sm font-medium text-muted-foreground">今日已付金额</CardTitle>
- </CardHeader>
- <CardContent className="text-3xl font-semibold">
+ </div>
+ <div className="mt-1 text-xs text-[#c0c4cc]">历史累计付款</div>
+ </div>
+ <div className="admin-panel admin-stat-card">
+ <div className="admin-stat-icon">
+ <Wallet className="h-5 w-5" />
+ </div>
+ <div className="text-sm text-[#909399]">今日已付金额</div>
+ <div className="mt-2 text-3xl font-semibold tracking-tight">
¥{stats ? fenToYuan(stats.order_paid_today_fen) : "—"}
- </CardContent>
- </Card>
+ </div>
+ <div className="mt-1 text-xs text-[#c0c4cc]">今日付款金额</div>
+ </div>
</div>
- <Card>
- <CardHeader>
- <CardTitle>项目状态分布</CardTitle>
- </CardHeader>
- <CardContent className="flex flex-wrap gap-2">
+
+ <div className="admin-panel">
+ <div className="mb-3 text-sm font-medium text-[#303133]">项目状态分布</div>
+ <div className="flex flex-wrap gap-2">
{statusEntries.length === 0 ? (
- <span className="text-sm text-muted-foreground">暂无数据</span>
+ <span className="text-sm text-[#909399]">暂无数据</span>
) : (
statusEntries.map(([status, count]) => (
- <Badge key={status} variant="secondary" className="gap-2 px-3 py-1 text-sm font-normal">
- <span className="font-medium">{status}</span>
- <span>{count}</span>
- </Badge>
+ <span key={status} className={`admin-status-pill ${statusClass(status)}`}>
+ <span>{projectStatusLabel(status)}</span>
+ <strong className="font-semibold">{count}</strong>
+ </span>
))
)}
- </CardContent>
- </Card>
+ </div>
+ </div>
+
+ <div className="grid gap-4 xl:grid-cols-5">
+ <div className="admin-panel xl:col-span-3">
+ <div className="mb-3 flex items-center justify-between">
+ <div className="text-sm font-medium">最近订单</div>
+ <Link to="/orders" className="text-xs text-[#67c23a] hover:underline">
+ 查看全部订单 →
+ </Link>
+ </div>
+ <div className="admin-table-wrap">
+ <table>
+ <thead>
+ <tr>
+ <th>单号</th>
+ <th>用户</th>
+ <th>金额</th>
+ <th>支付</th>
+ <th>状态</th>
+ <th>时间</th>
+ </tr>
+ </thead>
+ <tbody>
+ {orders.length === 0 ? (
+ <tr>
+ <td colSpan={6} className="!text-center text-[#909399]">
+ 暂无订单
+ </td>
+ </tr>
+ ) : (
+ orders.map((o) => (
+ <tr key={o.id}>
+ <td className="font-mono text-xs">{o.out_trade_no}</td>
+ <td>{o.user_email ?? o.user_id}</td>
+ <td>¥{fenToYuan(o.amount_fen)}</td>
+ <td>{payTypeLabel(o.pay_type)}</td>
+ <td>
+ <span
+ className={`admin-status-pill ${o.status === "paid" ? "is-done" : o.status === "pending" ? "is-warn" : "is-fail"}`}
+ >
+ {orderStatusLabel(o.status)}
+ </span>
+ </td>
+ <td className="text-xs text-[#909399]">
+ {new Date(o.created_at).toLocaleString()}
+ </td>
+ </tr>
+ ))
+ )}
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <div className="admin-panel xl:col-span-2">
+ <div className="mb-3 text-sm font-medium">快捷操作</div>
+ <div className="grid grid-cols-2 gap-3">
+ <Link to="/templates" className="admin-quick-btn">
+ <Shapes className="h-4 w-4 text-[#67c23a]" />
+ 模板管理
+ </Link>
+ <Link to="/orders" className="admin-quick-btn">
+ <Receipt className="h-4 w-4 text-[#67c23a]" />
+ 充值记录
+ </Link>
+ <Link to="/users" className="admin-quick-btn">
+ <Users className="h-4 w-4 text-[#67c23a]" />
+ 用户列表
+ </Link>
+ <Link to="/projects" className="admin-quick-btn">
+ <Clapperboard 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">
+ <span className="font-medium">系统公告</span>
+ <span className="text-xs text-[#c0c4cc]">今天</span>
+ </div>
+ <p className="text-sm leading-relaxed text-[#606266]">
+ 欢迎使用 PRINTFILM 管理后台。可在此管理用户额度、审核作品与模板上下架。
+ </p>
+ </div>
+ </div>
+ </div>
</div>
);
}
diff --git a/admin/src/pages/DramaProjectsPage.tsx b/admin/src/pages/DramaProjectsPage.tsx
new file mode 100644
index 0000000..99b298e
--- /dev/null
+++ b/admin/src/pages/DramaProjectsPage.tsx
@@ -0,0 +1,88 @@
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import { api, type PageMeta } from "@/api/client";
+import { PaginationBar } from "@/components/PaginationBar";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+
+type DramaProjectRow = {
+ id: number;
+ user_id: number;
+ user_email?: string | null;
+ title: string;
+ description?: string | null;
+ created_at?: string | null;
+ updated_at?: string | null;
+};
+
+type ListRes = { items: DramaProjectRow[]; meta: PageMeta };
+
+/** Admin table listing drama projects with pagination */
+export function DramaProjectsPage() {
+ /*
+ * page current page
+ * data list response
+ */
+ const [page, setPage] = useState(1);
+ const [data, setData] = useState<ListRes | null>(null);
+
+ // Load drama projects
+ async function load(nextPage = page) {
+ try {
+ const params = new URLSearchParams({ page: String(nextPage), page_size: "20" });
+ setData(await api<ListRes>(`/api/admin/drama-projects?${params}`));
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "加载失败");
+ }
+ }
+
+ useEffect(() => {
+ void load();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [page]);
+
+ return (
+ <div className="space-y-4">
+ <div>
+ <h1 className="text-2xl font-semibold">漫剧项目</h1>
+ <p className="text-sm text-muted-foreground">查看用户创建的漫剧项目</p>
+ </div>
+ <div className="rounded-lg border bg-white">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>ID</TableHead>
+ <TableHead>标题</TableHead>
+ <TableHead>用户</TableHead>
+ <TableHead>创建时间</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {(data?.items || []).map((row) => (
+ <TableRow key={row.id}>
+ <TableCell>{row.id}</TableCell>
+ <TableCell>{row.title}</TableCell>
+ <TableCell>{row.user_email || row.user_id}</TableCell>
+ <TableCell>{row.created_at ? String(row.created_at).slice(0, 19) : "-"}</TableCell>
+ </TableRow>
+ ))}
+ {!data?.items?.length ? (
+ <TableRow>
+ <TableCell colSpan={4} className="text-center text-muted-foreground">
+ 暂无数据
+ </TableCell>
+ </TableRow>
+ ) : null}
+ </TableBody>
+ </Table>
+ </div>
+ {data?.meta ? (
+ <PaginationBar
+ page={data.meta.page}
+ pageSize={data.meta.page_size}
+ total={data.meta.total}
+ onPageChange={setPage}
+ />
+ ) : null}
+ </div>
+ );
+}
diff --git a/admin/src/pages/OrdersPage.tsx b/admin/src/pages/OrdersPage.tsx
index 14261b2..5440bcd 100644
--- a/admin/src/pages/OrdersPage.tsx
+++ b/admin/src/pages/OrdersPage.tsx
@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";
import { toast } from "sonner";
import { api, type AdminLedger, type AdminOrder, type PageMeta } from "@/api/client";
import { PaginationBar } from "@/components/PaginationBar";
+import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -9,6 +10,7 @@ import { Select } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { fenToYuan } from "@/lib/utils";
+import { ledgerKindLabel, orderStatusLabel, payTypeLabel } from "@/lib/statusLabels";
type OrderRes = { items: AdminOrder[]; meta: PageMeta };
type LedgerRes = { items: AdminLedger[]; meta: PageMeta };
@@ -39,7 +41,7 @@ export function OrdersPage() {
// Load recharge orders
async function loadOrders(page = orderPage) {
try {
- const params = new URLSearchParams({ page: String(page), page_size: "20" });
+ const params = new URLSearchParams({ page: String(page), page_size: String(DEFAULT_PAGE_SIZE) });
if (orderStatus) params.set("status", orderStatus);
if (orderUserId.trim()) params.set("user_id", orderUserId.trim());
setOrders(await api<OrderRes>(`/api/admin/orders?${params}`));
@@ -51,7 +53,7 @@ export function OrdersPage() {
// Load wallet ledger
async function loadLedger(page = ledgerPage) {
try {
- const params = new URLSearchParams({ page: String(page), page_size: "20" });
+ const params = new URLSearchParams({ page: String(page), page_size: String(DEFAULT_PAGE_SIZE) });
if (ledgerKind) params.set("kind", ledgerKind);
if (ledgerUserId.trim()) params.set("user_id", ledgerUserId.trim());
setLedger(await api<LedgerRes>(`/api/admin/ledger?${params}`));
@@ -73,8 +75,8 @@ export function OrdersPage() {
return (
<div className="space-y-4">
<div>
- <h1 className="text-2xl font-semibold">订单与流水</h1>
- <p className="text-sm text-muted-foreground">查看充值单与钱包流水</p>
+ <h2 className="text-xl font-semibold text-[#303133]">订单与流水</h2>
+ <p className="mt-1 text-sm text-[#909399]">查看充值单与钱包流水</p>
</div>
<Tabs value={tab} onValueChange={setTab}>
<TabsList>
@@ -89,9 +91,9 @@ export function OrdersPage() {
onChange={(e) => setOrderStatus(e.target.value)}
>
<option value="">全部状态</option>
- <option value="pending">pending</option>
- <option value="paid">paid</option>
- <option value="closed">closed</option>
+ <option value="pending">待支付</option>
+ <option value="paid">已支付</option>
+ <option value="closed">已关闭</option>
</Select>
<Input
className="w-40"
@@ -133,9 +135,11 @@ export function OrdersPage() {
<TableCell>{o.sku_id}</TableCell>
<TableCell>¥{fenToYuan(o.amount_fen)}</TableCell>
<TableCell>¥{fenToYuan(o.credit_fen)}</TableCell>
- <TableCell>{o.pay_type}</TableCell>
+ <TableCell>{payTypeLabel(o.pay_type)}</TableCell>
<TableCell>
- <Badge variant={o.status === "paid" ? "default" : "secondary"}>{o.status}</Badge>
+ <Badge variant={o.status === "paid" ? "success" : "secondary"}>
+ {orderStatusLabel(o.status)}
+ </Badge>
</TableCell>
<TableCell className="text-xs text-muted-foreground">
{new Date(o.created_at).toLocaleString()}
@@ -158,13 +162,13 @@ export function OrdersPage() {
<div className="flex flex-wrap gap-2">
<Select className="w-40" value={ledgerKind} onChange={(e) => setLedgerKind(e.target.value)}>
<option value="">全部类型</option>
- <option value="topup">topup</option>
- <option value="grant">grant</option>
- <option value="adjust">adjust</option>
- <option value="freeze">freeze</option>
- <option value="unfreeze">unfreeze</option>
- <option value="settle">settle</option>
- <option value="refund">refund</option>
+ <option value="topup">充值</option>
+ <option value="grant">赠送</option>
+ <option value="adjust">调账</option>
+ <option value="freeze">冻结</option>
+ <option value="unfreeze">解冻</option>
+ <option value="settle">结算</option>
+ <option value="refund">退款</option>
</Select>
<Input
className="w-40"
@@ -206,7 +210,7 @@ export function OrdersPage() {
</TableCell>
<TableCell>¥{fenToYuan(e.balance_after)}</TableCell>
<TableCell>
- <Badge variant="secondary">{e.kind}</Badge>
+ <Badge variant="secondary">{ledgerKindLabel(e.kind)}</Badge>
</TableCell>
<TableCell className="max-w-[200px] truncate">{e.note}</TableCell>
<TableCell className="text-xs text-muted-foreground">
diff --git a/admin/src/pages/ProjectsPage.tsx b/admin/src/pages/ProjectsPage.tsx
index 4e16e06..9b52c03 100644
--- a/admin/src/pages/ProjectsPage.tsx
+++ b/admin/src/pages/ProjectsPage.tsx
@@ -2,25 +2,25 @@ import { useEffect, useState } from "react";
import { toast } from "sonner";
import { api, type AdminProject, type PageMeta } from "@/api/client";
import { PaginationBar } from "@/components/PaginationBar";
+import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { PROJECT_STATUS_OPTIONS, projectStatusLabel } from "@/lib/statusLabels";
type ListRes = { items: AdminProject[]; meta: PageMeta };
-const STATUS_OPTIONS = [
- "",
- "DRAFT",
- "SCRIPTING",
- "FAILED",
- "DONE",
- "CANCELLED",
- "VIDEOING",
- "COMPOSING",
-];
+// Badge color by project status
+function statusBadgeVariant(status: string): "destructive" | "success" | "warning" | "info" | "secondary" {
+ if (status === "FAILED" || status === "REJECTED") return "destructive";
+ if (status === "DONE") return "success";
+ if (status === "CANCELLED") return "secondary";
+ if (status === "DRAFT") return "secondary";
+ return "info";
+}
// Project list and failure detail
export function ProjectsPage() {
@@ -40,7 +40,7 @@ export function ProjectsPage() {
// Load projects
async function load(nextPage = page) {
try {
- const params = new URLSearchParams({ page: String(nextPage), page_size: "20" });
+ const params = new URLSearchParams({ page: String(nextPage), page_size: String(DEFAULT_PAGE_SIZE) });
if (status) params.set("status", status);
if (q.trim()) params.set("q", q.trim());
setData(await api<ListRes>(`/api/admin/projects?${params}`));
@@ -66,14 +66,14 @@ export function ProjectsPage() {
return (
<div className="space-y-4">
<div>
- <h1 className="text-2xl font-semibold">项目管理</h1>
- <p className="text-sm text-muted-foreground">按状态筛选,查看失败原因与进度</p>
+ <h2 className="text-xl font-semibold text-[#303133]">项目管理</h2>
+ <p className="mt-1 text-sm text-[#909399]">按状态筛选,查看失败原因与进度</p>
</div>
<div className="flex flex-wrap gap-2">
<Select className="w-44" value={status} onChange={(e) => setStatus(e.target.value)}>
- {STATUS_OPTIONS.map((s) => (
- <option key={s || "all"} value={s}>
- {s || "全部状态"}
+ {PROJECT_STATUS_OPTIONS.map((opt) => (
+ <option key={opt.value || "all"} value={opt.value}>
+ {opt.label}
</option>
))}
</Select>
@@ -114,7 +114,7 @@ export function ProjectsPage() {
<TableCell className="max-w-[180px] truncate">{p.title}</TableCell>
<TableCell className="text-sm">{p.user_email ?? p.user_id}</TableCell>
<TableCell>
- <Badge variant={p.status === "FAILED" ? "destructive" : "secondary"}>{p.status}</Badge>
+ <Badge variant={statusBadgeVariant(p.status)}>{projectStatusLabel(p.status)}</Badge>
</TableCell>
<TableCell>{p.progress}%</TableCell>
<TableCell>{p.shot_count}</TableCell>
@@ -151,7 +151,7 @@ export function ProjectsPage() {
<div className="space-y-2 text-sm">
<div>用户:{detail.user_email ?? detail.user_id}</div>
<div>
- 状态:{detail.status} · 进度 {detail.progress}% · 镜头 {detail.shot_count}
+ 状态:{projectStatusLabel(detail.status)} · 进度 {detail.progress}% · 镜头 {detail.shot_count}
</div>
<div>模板:{detail.template_id}</div>
<div>管线:{detail.pipeline_mode}</div>
diff --git a/admin/src/pages/TemplatesPage.tsx b/admin/src/pages/TemplatesPage.tsx
index dc67642..5527f8c 100644
--- a/admin/src/pages/TemplatesPage.tsx
+++ b/admin/src/pages/TemplatesPage.tsx
@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";
import { toast } from "sonner";
import { api, type AdminTemplate, type PageMeta } from "@/api/client";
import { PaginationBar } from "@/components/PaginationBar";
+import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
@@ -66,7 +67,7 @@ export function TemplatesPage() {
// Load templates
async function load(nextPage = page) {
try {
- const params = new URLSearchParams({ page: String(nextPage), page_size: "50" });
+ const params = new URLSearchParams({ page: String(nextPage), page_size: String(DEFAULT_PAGE_SIZE) });
setData(await api<ListRes>(`/api/admin/templates?${params}`));
} catch (err) {
toast.error(err instanceof Error ? err.message : "加载失败");
@@ -185,8 +186,8 @@ export function TemplatesPage() {
<div className="space-y-4">
<div className="flex items-start justify-between gap-3">
<div>
- <h1 className="text-2xl font-semibold">模板管理</h1>
- <p className="text-sm text-muted-foreground">增删改、上下架与 premium</p>
+ <h2 className="text-xl font-semibold text-[#303133]">模板管理</h2>
+ <p className="mt-1 text-sm text-[#909399]">增删改、上下架与 premium</p>
</div>
<Button onClick={openCreate}>新建模板</Button>
</div>
diff --git a/admin/src/pages/UsersPage.tsx b/admin/src/pages/UsersPage.tsx
index b3f3d02..8123c7d 100644
--- a/admin/src/pages/UsersPage.tsx
+++ b/admin/src/pages/UsersPage.tsx
@@ -4,12 +4,14 @@ import { api, type AdminUserRow, type PageMeta } from "@/api/client";
import { PaginationBar } from "@/components/PaginationBar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
-import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { EmptyState, PageHeader, Toolbar } from "@/components/ui/page";
import { Select } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { fenToYuan } from "@/lib/utils";
type ListRes = { items: AdminUserRow[]; meta: PageMeta };
@@ -19,6 +21,7 @@ export function UsersPage() {
/*
* q search query
* page current page
+ * pageSize rows per page
* data list response
* loading fetch state
* editing user being edited
@@ -27,6 +30,7 @@ export function UsersPage() {
*/
const [q, setQ] = useState("");
const [page, setPage] = useState(1);
+ const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);
const [data, setData] = useState<ListRes | null>(null);
const [loading, setLoading] = useState(false);
const [editing, setEditing] = useState<AdminUserRow | null>(null);
@@ -40,12 +44,12 @@ export function UsersPage() {
const [saving, setSaving] = useState(false);
// Load paginated users
- async function load(nextPage = page, nextQ = q) {
+ async function load(nextPage = page, nextQ = q, nextSize = pageSize) {
setLoading(true);
try {
const params = new URLSearchParams({
page: String(nextPage),
- page_size: "20",
+ page_size: String(nextSize),
});
if (nextQ.trim()) params.set("q", nextQ.trim());
const res = await api<ListRes>(`/api/admin/users?${params}`);
@@ -60,7 +64,7 @@ export function UsersPage() {
useEffect(() => {
void load();
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [page]);
+ }, [page, pageSize]);
// Open edit dialog for a user
function openEdit(user: AdminUserRow) {
@@ -103,11 +107,9 @@ export function UsersPage() {
return (
<div className="space-y-4">
- <div>
- <h1 className="text-2xl font-semibold">用户管理</h1>
- <p className="text-sm text-muted-foreground">搜索用户,调整套餐、余额与无限额度</p>
- </div>
- <div className="flex flex-wrap gap-2">
+ <PageHeader title="用户管理" description="搜索用户,调整套餐、余额与无限额度" />
+
+ <Toolbar>
<Input
className="max-w-xs"
placeholder="搜索邮箱 / 昵称"
@@ -121,7 +123,7 @@ export function UsersPage() {
}}
/>
<Button
- variant="secondary"
+ variant="soft"
onClick={() => {
setPage(1);
void load(1, q);
@@ -129,8 +131,9 @@ export function UsersPage() {
>
搜索
</Button>
- </div>
- <div className="rounded-lg border bg-background">
+ </Toolbar>
+
+ <div className="space-y-3">
<Table>
<TableHeader>
<TableRow>
@@ -141,21 +144,27 @@ export function UsersPage() {
<TableHead>余额</TableHead>
<TableHead>角色</TableHead>
<TableHead>无限</TableHead>
- <TableHead></TableHead>
+ <TableHead className="w-[100px]">操作</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{(data?.items ?? []).map((u) => (
<TableRow key={u.id}>
- <TableCell>{u.id}</TableCell>
- <TableCell>{u.email}</TableCell>
+ <TableCell className="text-[#909399]">{u.id}</TableCell>
+ <TableCell className="font-medium">{u.email}</TableCell>
<TableCell>{u.nickname}</TableCell>
- <TableCell>{u.plan}</TableCell>
- <TableCell>¥{fenToYuan(u.balance_fen)}</TableCell>
<TableCell>
- <Badge variant={u.role === "admin" ? "default" : "secondary"}>{u.role}</Badge>
+ <Badge variant="info">{u.plan}</Badge>
+ </TableCell>
+ <TableCell className="tabular-nums">¥{fenToYuan(u.balance_fen)}</TableCell>
+ <TableCell>
+ <Badge variant={u.role === "admin" ? "success" : "secondary"}>{u.role}</Badge>
+ </TableCell>
+ <TableCell>
+ <Badge variant={u.billing_unlimited ? "warning" : "secondary"}>
+ {u.billing_unlimited ? "是" : "否"}
+ </Badge>
</TableCell>
- <TableCell>{u.billing_unlimited ? "是" : "否"}</TableCell>
<TableCell>
<Button size="sm" variant="outline" onClick={() => openEdit(u)}>
编辑
@@ -165,27 +174,33 @@ export function UsersPage() {
))}
{!loading && (data?.items.length ?? 0) === 0 && (
<TableRow>
- <TableCell colSpan={8} className="text-center text-muted-foreground">
- 暂无用户
+ <TableCell colSpan={8} className="p-0">
+ <EmptyState title="暂无用户" description="试试换个关键词搜索" />
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
+
+ {data && (
+ <PaginationBar
+ page={data.meta.page}
+ pageSize={pageSize}
+ total={data.meta.total}
+ onPageChange={setPage}
+ onPageSizeChange={(size) => {
+ setPageSize(size);
+ setPage(1);
+ }}
+ />
+ )}
</div>
- {data && (
- <PaginationBar
- page={data.meta.page}
- pageSize={data.meta.page_size}
- total={data.meta.total}
- onPageChange={setPage}
- />
- )}
<Dialog open={!!editing} onOpenChange={(open) => !open && setEditing(null)}>
<DialogContent>
<DialogHeader>
- <DialogTitle>编辑用户 · {editing?.email}</DialogTitle>
+ <DialogTitle>编辑用户</DialogTitle>
+ <DialogDescription>{editing?.email}</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
@@ -218,15 +233,18 @@ export function UsersPage() {
placeholder="可选"
/>
</div>
- <div className="flex items-center justify-between">
- <Label>billing_unlimited</Label>
+ <div className="flex items-center justify-between rounded-xl bg-[#fafbfc] px-3 py-3">
+ <div>
+ <Label>无限额度</Label>
+ <p className="mt-1 text-xs text-[#909399]">billing_unlimited</p>
+ </div>
<Switch
checked={form.billing_unlimited}
onCheckedChange={(v) => setForm((f) => ({ ...f, billing_unlimited: v }))}
/>
</div>
<Button className="w-full" disabled={saving} onClick={() => void saveEdit()}>
- {saving ? "保存中…" : "保存"}
+ {saving ? "保存中…" : "保存修改"}
</Button>
</div>
</DialogContent>
diff --git a/admin/src/pages/WorksPage.tsx b/admin/src/pages/WorksPage.tsx
index c922d2d..568ab80 100644
--- a/admin/src/pages/WorksPage.tsx
+++ b/admin/src/pages/WorksPage.tsx
@@ -2,10 +2,12 @@ import { useEffect, useState } from "react";
import { toast } from "sonner";
import { api, type AdminWork, type PageMeta } from "@/api/client";
import { PaginationBar } from "@/components/PaginationBar";
+import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Select } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { auditStatusLabel, visibilityLabel } from "@/lib/statusLabels";
type ListRes = { items: AdminWork[]; meta: PageMeta };
@@ -25,7 +27,7 @@ export function WorksPage() {
// Load works
async function load(nextPage = page) {
try {
- const params = new URLSearchParams({ page: String(nextPage), page_size: "20" });
+ const params = new URLSearchParams({ page: String(nextPage), page_size: String(DEFAULT_PAGE_SIZE) });
if (auditStatus) params.set("audit_status", auditStatus);
if (visibility) params.set("visibility", visibility);
setData(await api<ListRes>(`/api/admin/works?${params}`));
@@ -53,21 +55,21 @@ export function WorksPage() {
return (
<div className="space-y-4">
<div>
- <h1 className="text-2xl font-semibold">作品审核</h1>
- <p className="text-sm text-muted-foreground">调整可见性与审核状态</p>
+ <h2 className="text-xl font-semibold text-[#303133]">作品审核</h2>
+ <p className="mt-1 text-sm text-[#909399]">调整可见性与审核状态</p>
</div>
<div className="flex flex-wrap gap-2">
<Select className="w-40" value={auditStatus} onChange={(e) => setAuditStatus(e.target.value)}>
<option value="">全部审核</option>
- <option value="pending">pending</option>
- <option value="passed">passed</option>
- <option value="rejected">rejected</option>
+ <option value="pending">待审核</option>
+ <option value="passed">已通过</option>
+ <option value="rejected">已拒绝</option>
</Select>
<Select className="w-40" value={visibility} onChange={(e) => setVisibility(e.target.value)}>
<option value="">全部可见性</option>
- <option value="public">public</option>
- <option value="private">private</option>
- <option value="unlisted">unlisted</option>
+ <option value="public">公开</option>
+ <option value="private">私密</option>
+ <option value="unlisted">不公开列出</option>
</Select>
<Button
variant="secondary"
@@ -99,11 +101,11 @@ export function WorksPage() {
<TableCell className="max-w-[200px] truncate">{w.title}</TableCell>
<TableCell>{w.user_email ?? w.user_id}</TableCell>
<TableCell>
- <Badge variant="secondary">{w.visibility}</Badge>
+ <Badge variant="secondary">{visibilityLabel(w.visibility)}</Badge>
</TableCell>
<TableCell>
- <Badge variant={w.audit_status === "rejected" ? "destructive" : "secondary"}>
- {w.audit_status}
+ <Badge variant={w.audit_status === "rejected" ? "destructive" : w.audit_status === "passed" ? "success" : "warning"}>
+ {auditStatusLabel(w.audit_status)}
</Badge>
</TableCell>
<TableCell className="text-xs text-muted-foreground">
diff --git a/admin/vite.config.ts b/admin/vite.config.ts
index 0688943..f04fb23 100644
--- a/admin/vite.config.ts
+++ b/admin/vite.config.ts
@@ -18,11 +18,11 @@ export default defineConfig({
port: 5174,
proxy: {
"/api": {
- target: "http://127.0.0.1:8000",
+ target: "http://127.0.0.1:8001",
changeOrigin: true,
},
"/static": {
- target: "http://127.0.0.1:8000",
+ target: "http://127.0.0.1:8001",
changeOrigin: true,
},
},
diff --git a/backend/.env.example b/backend/.env.example
index c49c43b..11588e1 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -1,4 +1,7 @@
SECRET_KEY=dev-secret-change-me
+# DEBUG=true 时应用日志更详细;SQL_ECHO=true 才打印原始 SQL(默认关,避免刷屏)
+# DEBUG=true
+# SQL_ECHO=false
# 本地默认 SQLite;正式可改为 Postgres(Docker 见 deploy/docker-compose.yml)
# DATABASE_URL=postgresql+asyncpg://printfilm:密码@127.0.0.1:5432/printfilm
# DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:密码@127.0.0.1:5432/printfilm
@@ -43,9 +46,11 @@ CELERY_STALE_PROJECT_SEC=900
# 旗舰模型(需在方舟控制台开通;若账号仅支持接入点,可改为 ep-xxxxxxxx)
MODEL_LLM=doubao-seed-2-0-pro-260215
MODEL_IMAGE=doubao-seedream-5-0-260128
+# Seedream 4.5 接入点(可选;未配则回退 MODEL_IMAGE)
+# MODEL_IMAGE_45=ep-xxxxxxxx
MODEL_VIDEO=doubao-seedance-2-5-260628
SEEDANCE_DURATION_MIN=4
-SEEDANCE_DURATION_MAX=30
+SEEDANCE_DURATION_MAX=15
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 ddc2f69..7b42c37 100644
--- a/backend/app/api/admin/__init__.py
+++ b/backend/app/api/admin/__init__.py
@@ -1,7 +1,7 @@
# Admin API router aggregation
from fastapi import APIRouter
-from app.api.admin import dashboard, ledger, orders, projects, templates, users, works
+from app.api.admin import dashboard, drama_projects, ledger, orders, projects, templates, users, works
router = APIRouter(prefix="/admin", tags=["admin"])
router.include_router(dashboard.router)
@@ -11,3 +11,4 @@ router.include_router(ledger.router)
router.include_router(projects.router)
router.include_router(works.router)
router.include_router(templates.router)
+router.include_router(drama_projects.router)
diff --git a/backend/app/api/admin/drama_projects.py b/backend/app/api/admin/drama_projects.py
new file mode 100644
index 0000000..e57b4e3
--- /dev/null
+++ b/backend/app/api/admin/drama_projects.py
@@ -0,0 +1,64 @@
+"""Admin drama project list with pagination and owner email."""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends, Query
+from pydantic import BaseModel, ConfigDict
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import aliased
+
+from app.database import get_db
+from app.deps import get_current_admin
+from app.models import User
+from app.models_drama import DramaProject
+from app.schemas import PageMeta
+
+router = APIRouter()
+
+
+class AdminDramaProjectOut(BaseModel):
+ model_config = ConfigDict(from_attributes=True)
+
+ id: int
+ user_id: int
+ user_email: str | None = None
+ title: str
+ description: str | None = None
+ created_at: object | None = None
+ updated_at: object | None = None
+
+
+class AdminDramaProjectListOut(BaseModel):
+ items: list[AdminDramaProjectOut]
+ meta: PageMeta
+
+
[email protected]("/drama-projects", response_model=AdminDramaProjectListOut)
+async def list_drama_projects(
+ page: int = Query(1, ge=1),
+ page_size: int = Query(20, ge=1, le=100),
+ _admin: User = Depends(get_current_admin),
+ db: AsyncSession = Depends(get_db),
+) -> AdminDramaProjectListOut:
+ # Paginated drama projects joined with user email
+ owner = aliased(User)
+ stmt = select(DramaProject, owner.email).outerjoin(owner, owner.id == DramaProject.user_id)
+ count_stmt = select(func.count()).select_from(DramaProject)
+
+ total = int((await db.execute(count_stmt)).scalar_one() or 0)
+ rows = (
+ await db.execute(
+ stmt.order_by(DramaProject.id.desc()).offset((page - 1) * page_size).limit(page_size)
+ )
+ ).all()
+
+ items: list[AdminDramaProjectOut] = []
+ for project, email in rows:
+ data = AdminDramaProjectOut.model_validate(project)
+ data.user_email = email
+ items.append(data)
+
+ return AdminDramaProjectListOut(
+ items=items, meta=PageMeta(page=page, page_size=page_size, total=total)
+ )
diff --git a/backend/app/api/drama/__init__.py b/backend/app/api/drama/__init__.py
new file mode 100644
index 0000000..53b9257
--- /dev/null
+++ b/backend/app/api/drama/__init__.py
@@ -0,0 +1,14 @@
+"""Drama API package: /api/drama/*."""
+
+from fastapi import APIRouter
+
+from app.api.drama import agents, assets, canvas, episodes, generation, projects, scripts
+
+router = APIRouter(prefix="/drama", tags=["drama"])
+router.include_router(projects.router)
+router.include_router(scripts.router)
+router.include_router(agents.router)
+router.include_router(assets.router)
+router.include_router(episodes.router)
+router.include_router(generation.router)
+router.include_router(canvas.router)
diff --git a/backend/app/api/drama/agents.py b/backend/app/api/drama/agents.py
new file mode 100644
index 0000000..12deb2a
--- /dev/null
+++ b/backend/app/api/drama/agents.py
@@ -0,0 +1,232 @@
+"""Drama agent endpoints: summary, episode script, route, chat."""
+
+from __future__ import annotations
+
+import logging
+
+from fastapi import APIRouter, Depends, HTTPException
+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
+from app.schemas_drama import (
+ DramaChatRequest,
+ DramaEpisodeScriptRequest,
+ DramaRouteRequest,
+ DramaScriptOut,
+ DramaScriptSummaryRequest,
+)
+from app.services.billing import record_usage
+from app.services.drama.access import get_owned_drama_project
+from app.services.drama.agents import (
+ count_completed_episodes,
+ resolve_episode_target,
+)
+from app.services.drama.jobs import dispatch_episode_scripts_job, dispatch_script_summary_job
+from app.services.drama.llm import drama_chat_text
+
+router = APIRouter()
+logger = logging.getLogger("app.drama.agents")
+
+
[email protected]("/agents/script_summary")
+async def script_summary(
+ body: DramaScriptSummaryRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ # 入队摘要任务,立即返回;前端轮询 script.params.summary_status
+ project = await get_owned_drama_project(db, body.project_id, user, with_script=True)
+ if not project.script:
+ raise HTTPException(status_code=400, detail="缺少剧本")
+ creative = (body.creative or project.script.source or "").strip()
+ if len(creative) < 20:
+ raise HTTPException(status_code=400, detail="创意文案至少 20 字")
+
+ project.script.source = creative
+ params = dict(project.script.params or {})
+ if body.episode_count:
+ params["episode_count"] = int(body.episode_count)
+ proj_params = dict(project.params or {})
+ proj_params["episode_count"] = int(body.episode_count)
+ project.params = proj_params
+ if body.image_style_id:
+ params["image_style_id"] = str(body.image_style_id)
+ proj_params = dict(project.params or {})
+ 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":
+ logger.info(
+ "剧本摘要已在生成中,跳过重复入队 project_id=%s user_id=%s",
+ project.id,
+ user.id,
+ )
+ await db.commit()
+ return {
+ "ok": True,
+ "queued": True,
+ "status": "generating",
+ "task_id": None,
+ "script": DramaScriptOut.model_validate(project.script).model_dump(),
+ }
+ params["summary_status"] = "generating"
+ params.pop("summary_error", None)
+ project.script.params = params
+ await db.commit()
+ await db.refresh(project)
+
+ task_id = dispatch_script_summary_job(project.id)
+ logger.info(
+ "已入队剧本摘要 project_id=%s user_id=%s task_id=%s creative_len=%s",
+ project.id,
+ user.id,
+ task_id,
+ len(creative),
+ )
+ return {
+ "ok": True,
+ "queued": True,
+ "status": "generating",
+ "task_id": task_id,
+ "script": DramaScriptOut.model_validate(project.script).model_dump(),
+ }
+
+
[email protected]("/agents/episode_script")
+async def episode_script(
+ body: DramaEpisodeScriptRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ # 入队完整分集生成;前端轮询 episode_content_status / progress
+ project = await get_owned_drama_project(db, body.project_id, user, with_script=True)
+ if not project.script or not project.script.summary:
+ raise HTTPException(status_code=400, detail="请先生成剧本摘要")
+
+ summary = project.script.summary if isinstance(project.script.summary, dict) else {}
+ total = resolve_episode_target(summary, project.params, project.script.params)
+ if summary.get("episodeCount") != total:
+ summary = {**summary, "episodeCount": total}
+ project.script.summary = summary
+
+ params = dict(project.script.params or {})
+ if str(params.get("episode_content_status") or "") == "generating" and not body.force:
+ content = project.script.episode_content
+ existing: list = []
+ if isinstance(content, dict) and isinstance(content.get("episodes"), list):
+ existing = list(content["episodes"])
+ elif isinstance(content, list):
+ existing = list(content)
+ generated = count_completed_episodes(existing, total)
+ logger.info(
+ "分集剧本已在生成中,跳过重复入队 project_id=%s progress=%s/%s",
+ project.id,
+ generated,
+ total,
+ )
+ await db.commit()
+ return {
+ "ok": True,
+ "queued": True,
+ "status": "generating",
+ "task_id": None,
+ "episodes": [],
+ "total_generated": generated,
+ "total_target": total,
+ "done": False,
+ "script": DramaScriptOut.model_validate(project.script).model_dump(),
+ }
+
+ params["episode_content_status"] = "generating"
+ params["episode_count"] = total
+ params.pop("episode_content_error", None)
+ if body.force:
+ content = project.script.episode_content
+ existing: list = []
+ if isinstance(content, dict) and isinstance(content.get("episodes"), list):
+ existing = list(content["episodes"])
+ elif isinstance(content, list):
+ existing = list(content)
+ if existing:
+ project.script.episode_content = {
+ "episodes": [
+ {
+ "episodeNumber": int(item.get("episodeNumber") or 0),
+ "title": str(item.get("title") or f"第 {item.get('episodeNumber')} 集"),
+ "body": "",
+ }
+ for item in existing
+ if isinstance(item, dict) and int(item.get("episodeNumber") or 0) >= 1
+ ]
+ }
+ params["episode_content_progress"] = {"done": 0, "total": total}
+ project.script.params = params
+ await db.commit()
+ await db.refresh(project)
+
+ task_id = dispatch_episode_scripts_job(project.id, force=bool(body.force))
+ content = project.script.episode_content
+ existing = []
+ if isinstance(content, dict) and isinstance(content.get("episodes"), list):
+ existing = list(content["episodes"])
+ elif isinstance(content, list):
+ existing = list(content)
+ generated = count_completed_episodes(existing, total)
+ logger.info(
+ "已入队分集剧本 project_id=%s user_id=%s task_id=%s force=%s target=%s done=%s",
+ project.id,
+ user.id,
+ task_id,
+ bool(body.force),
+ total,
+ generated,
+ )
+ return {
+ "ok": True,
+ "queued": True,
+ "status": "generating",
+ "task_id": task_id,
+ "episodes": [],
+ "total_generated": generated,
+ "total_target": total,
+ "done": False,
+ "script": DramaScriptOut.model_validate(project.script).model_dump(),
+ }
+
+
[email protected]("/agents/route")
+async def route_agent(body: DramaRouteRequest, user: User = Depends(get_current_user)) -> dict:
+ _ = user
+ msg = (body.message or "").strip().lower()
+ if any(k in msg for k in ("剧本", "短剧", "漫剧", "分集", "大纲", "编剧")):
+ return {"agent": "drama_script", "action": "create_project"}
+ if any(k in msg for k in ("画布", "节点", "自由创作")):
+ return {"agent": "canvas", "action": "open_canvas"}
+ return {"agent": "chat", "action": "chat"}
+
+
[email protected]("/ai/chat")
+async def ai_chat(
+ body: DramaChatRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ logger.info("漫剧聊天 user_id=%s project_id=%s", user.id, body.project_id)
+ reply = await drama_chat_text(
+ "你是 PRINTFILM 漫剧创作助手,帮助用户构思短剧创意、人物与分集结构。用简洁中文回答。",
+ body.message,
+ )
+ await record_usage(
+ db,
+ user_id=user.id,
+ project_id=None,
+ drama_project_id=body.project_id,
+ billing_key="llm_chat",
+ model=get_settings().model_llm,
+ estimated=True,
+ )
+ await db.commit()
+ return {"reply": reply}
diff --git a/backend/app/api/drama/assets.py b/backend/app/api/drama/assets.py
new file mode 100644
index 0000000..d3ad05c
--- /dev/null
+++ b/backend/app/api/drama/assets.py
@@ -0,0 +1,198 @@
+"""Drama asset endpoints."""
+
+from __future__ import annotations
+
+import uuid
+from pathlib import Path
+
+from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
+from sqlalchemy import select
+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.models_drama import DramaAsset
+from app.schemas_drama import DramaAssetCreate, DramaAssetOut, DramaAssetUpdate
+from app.services.drama.access import get_owned_drama_project
+from app.services.drama.seed import seed_assets_from_script
+
+router = APIRouter()
+
+
[email protected]("/assets", response_model=list[DramaAssetOut])
+async def list_assets(
+ project_id: int | None = None,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> list[DramaAssetOut]:
+ # Global library = all assets of user's drama projects; optional project filter
+ from app.models_drama import DramaProject
+
+ q = (
+ select(DramaAsset)
+ .join(DramaProject, DramaAsset.project_id == DramaProject.id)
+ .where(DramaProject.user_id == user.id)
+ .order_by(DramaAsset.updated_at.desc())
+ )
+ if project_id is not None:
+ q = q.where(DramaAsset.project_id == project_id)
+ rows = list((await db.execute(q)).scalars().all())
+ return [DramaAssetOut.model_validate(a) for a in rows]
+
+
[email protected]("/assets", response_model=DramaAssetOut)
+async def create_asset(
+ body: DramaAssetCreate,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> DramaAssetOut:
+ await get_owned_drama_project(db, body.project_id, user)
+ asset = DramaAsset(
+ project_id=body.project_id,
+ type=body.type,
+ asset_type=body.asset_type,
+ name=body.name,
+ cover=body.cover,
+ url=body.url,
+ params=body.params,
+ )
+ db.add(asset)
+ await db.commit()
+ await db.refresh(asset)
+ return DramaAssetOut.model_validate(asset)
+
+
[email protected]("/assets/{asset_id}", response_model=DramaAssetOut)
+async def update_asset(
+ asset_id: int,
+ body: DramaAssetUpdate,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> DramaAssetOut:
+ from app.models_drama import DramaProject
+
+ result = await db.execute(
+ select(DramaAsset)
+ .join(DramaProject, DramaAsset.project_id == DramaProject.id)
+ .where(DramaAsset.id == asset_id, DramaProject.user_id == user.id)
+ )
+ asset = result.scalar_one_or_none()
+ if not asset:
+ raise HTTPException(status_code=404, detail="资产不存在")
+ for field in ("type", "asset_type", "name", "cover", "url", "params"):
+ val = getattr(body, field)
+ if val is not None:
+ setattr(asset, field, val)
+ await db.commit()
+ await db.refresh(asset)
+ return DramaAssetOut.model_validate(asset)
+
+
[email protected]("/assets/{asset_id}/upload", response_model=DramaAssetOut)
+async def upload_asset_media(
+ asset_id: int,
+ file: UploadFile = File(...),
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> DramaAssetOut:
+ """Upload image/media for a drama asset directly to OSS (no local persist)."""
+ from app.models_drama import DramaProject
+ from app.services import oss as oss_svc
+
+ if not oss_svc.oss_enabled():
+ raise HTTPException(status_code=503, detail="OSS 未启用,无法上传资产媒体")
+
+ result = await db.execute(
+ select(DramaAsset)
+ .join(DramaProject, DramaAsset.project_id == DramaProject.id)
+ .where(DramaAsset.id == asset_id, DramaProject.user_id == user.id)
+ )
+ asset = result.scalar_one_or_none()
+ if not asset:
+ raise HTTPException(status_code=404, detail="资产不存在")
+
+ 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
+ content_type = {
+ ".jpg": "image/jpeg",
+ ".png": "image/png",
+ ".webp": "image/webp",
+ ".gif": "image/gif",
+ }.get(ext, "application/octet-stream")
+ 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) > 20 * 1024 * 1024:
+ raise HTTPException(status_code=400, detail="文件不能超过 20MB")
+
+ object_key = (
+ f"{oss_svc.folder_prefix()}/generated/p{asset.project_id}/"
+ f"asset_{asset.id}_{uuid.uuid4().hex[:10]}{ext}"
+ )
+ try:
+ url = oss_svc.upload_bytes(raw, object_key, content_type=content_type or "application/octet-stream")
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=f"OSS 上传失败:{exc}") from exc
+
+ asset.url = url
+ asset.cover = url
+ if not asset.asset_type or asset.asset_type == "none":
+ asset.asset_type = "image"
+ await db.commit()
+ await db.refresh(asset)
+ return DramaAssetOut.model_validate(asset)
+
+
[email protected]("/assets/{asset_id}")
+async def delete_asset(
+ asset_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ from app.models_drama import DramaProject
+
+ result = await db.execute(
+ select(DramaAsset)
+ .join(DramaProject, DramaAsset.project_id == DramaProject.id)
+ .where(DramaAsset.id == asset_id, DramaProject.user_id == user.id)
+ )
+ asset = result.scalar_one_or_none()
+ if not asset:
+ raise HTTPException(status_code=404, detail="资产不存在")
+ await db.delete(asset)
+ await db.commit()
+ return {"ok": True}
+
+
[email protected]("/assets/seed_from_script", response_model=list[DramaAssetOut])
+async def seed_assets(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> list[DramaAssetOut]:
+ project = await get_owned_drama_project(db, project_id, user, with_script=True)
+ try:
+ created = await seed_assets_from_script(db, project)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ # Return all project assets after seed
+ all_assets = (
+ await db.execute(select(DramaAsset).where(DramaAsset.project_id == project_id))
+ ).scalars().all()
+ _ = created
+ return [DramaAssetOut.model_validate(a) for a in all_assets]
diff --git a/backend/app/api/drama/canvas.py b/backend/app/api/drama/canvas.py
new file mode 100644
index 0000000..ccc8417
--- /dev/null
+++ b/backend/app/api/drama/canvas.py
@@ -0,0 +1,105 @@
+"""Drama canvas persistence (nodes stored as project content + none-type assets)."""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends
+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.models_drama import DramaAsset
+from app.schemas_drama import DramaCanvasSaveRequest
+from app.services.drama.access import get_owned_drama_project
+
+router = APIRouter()
+
+
[email protected]("/canvas/{project_id}")
+async def get_canvas(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ project = await get_owned_drama_project(db, project_id, user, with_assets=True)
+ content = project.content if isinstance(project.content, dict) else {}
+ return {
+ "project_id": project_id,
+ "nodes": content.get("canvas_nodes") or [],
+ "edges": content.get("canvas_edges") or [],
+ }
+
+
+async def save_canvas(
+ body: DramaCanvasSaveRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ project = await get_owned_drama_project(db, body.project_id, user, with_assets=True)
+ content = dict(project.content) if isinstance(project.content, dict) else {}
+ content["canvas_nodes"] = body.nodes
+ content["canvas_edges"] = body.edges
+ project.content = content
+
+ # Upsert canvas nodes as type=none assets keyed by node id in params
+ existing = {
+ str((a.params or {}).get("canvas_node_id")): a
+ for a in (project.assets or [])
+ if a.type == "none" and (a.params or {}).get("canvas_node_id")
+ }
+ seen: set[str] = set()
+ for node in body.nodes:
+ nid = str(node.get("id") or "")
+ if not nid:
+ continue
+ seen.add(nid)
+ data = node.get("data") if isinstance(node.get("data"), dict) else {}
+ name = str(data.get("label") or data.get("name") or f"节点 {nid}")
+ url = data.get("mediaUrl") or data.get("url") or data.get("cover")
+ kind = str(data.get("kind") or "none")
+ asset_type = str(
+ data.get("asset_type")
+ or ("video" if kind == "video" else "audio" if kind == "audio" else "image")
+ )
+ # Prefer matching by explicit assetId, then by canvas_node_id
+ asset_id_raw = data.get("assetId")
+ matched = None
+ if asset_id_raw is not None:
+ try:
+ aid = int(asset_id_raw)
+ except (TypeError, ValueError):
+ aid = None
+ if aid is not None:
+ matched = next((a for a in (project.assets or []) if a.id == aid), None)
+ if matched is None:
+ matched = existing.get(nid)
+
+ if matched is not None:
+ asset = matched
+ asset.name = name
+ if kind and kind != "none":
+ asset.type = kind
+ asset.asset_type = asset_type
+ if url:
+ asset.url = str(url)
+ asset.cover = str(url)
+ params = dict(asset.params or {})
+ params["canvas"] = node
+ params["canvas_node_id"] = nid
+ asset.params = params
+ existing[nid] = asset
+ else:
+ db.add(
+ DramaAsset(
+ project_id=project.id,
+ type=kind if kind else "none",
+ asset_type=asset_type,
+ name=name,
+ cover=str(url) if url else None,
+ url=str(url) if url else None,
+ params={"canvas_node_id": nid, "canvas": node},
+ )
+ )
+ await db.commit()
+ return {"ok": True, "nodes": len(body.nodes), "edges": len(body.edges)}
diff --git a/backend/app/api/drama/episodes.py b/backend/app/api/drama/episodes.py
new file mode 100644
index 0000000..8970ad8
--- /dev/null
+++ b/backend/app/api/drama/episodes.py
@@ -0,0 +1,226 @@
+"""Drama episode / fragment endpoints."""
+
+from __future__ import annotations
+
+import logging
+
+from fastapi import APIRouter, Depends, HTTPException
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import selectinload
+
+from app.database import get_db
+from app.deps import get_current_user
+from app.models import User
+from app.models_drama import DramaEpisode, DramaEpisodeFragment, DramaFragmentAssetRef
+from app.schemas_drama import (
+ DramaEpisodeOut,
+ DramaFragmentOut,
+ DramaGenerateRequest,
+ DramaSaveFragmentsRequest,
+)
+from app.services.drama.access import get_owned_drama_project, get_owned_episode
+from app.services.drama.generation import fragment_generation_status
+from app.services.drama.jobs import dispatch_episode_generate_job
+from app.services.drama.seed import seed_episodes_from_script
+
+router = APIRouter()
+logger = logging.getLogger("app.drama.episodes")
+
+
+def _fragment_out(frag: DramaEpisodeFragment) -> DramaFragmentOut:
+ asset_ids = [r.asset_id for r in (frag.asset_references or [])]
+ return DramaFragmentOut(
+ id=frag.id,
+ episode_id=frag.episode_id,
+ sort_order=frag.sort_order,
+ content=frag.content,
+ cover=frag.cover or "",
+ video=frag.video or "",
+ duration_sec=frag.duration_sec,
+ params=frag.params,
+ asset_ids=asset_ids,
+ )
+
+
+def _episode_out(ep: DramaEpisode) -> DramaEpisodeOut:
+ frags = sorted(ep.fragments or [], key=lambda f: f.sort_order)
+ return DramaEpisodeOut(
+ id=ep.id,
+ name=ep.name,
+ params=ep.params,
+ project_id=ep.project_id,
+ fragments=[_fragment_out(f) for f in frags],
+ )
+
+
[email protected]("/episodes", response_model=list[DramaEpisodeOut])
+async def list_episodes(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> list[DramaEpisodeOut]:
+ await get_owned_drama_project(db, project_id, user)
+ result = await db.execute(
+ select(DramaEpisode)
+ .where(DramaEpisode.project_id == project_id)
+ .options(
+ selectinload(DramaEpisode.fragments).selectinload(DramaEpisodeFragment.asset_references)
+ )
+ .order_by(DramaEpisode.id.asc())
+ )
+ return [_episode_out(ep) for ep in result.scalars().all()]
+
+
[email protected]("/episodes/{episode_id}", response_model=DramaEpisodeOut)
+async def get_episode(
+ episode_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> DramaEpisodeOut:
+ ep = await get_owned_episode(db, episode_id, user)
+ return _episode_out(ep)
+
+
[email protected]("/episodes/seed_from_script", response_model=list[DramaEpisodeOut])
+async def seed_episodes(
+ project_id: int,
+ force: bool = False,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> list[DramaEpisodeOut]:
+ project = await get_owned_drama_project(db, project_id, user, with_script=True)
+ logger.info(
+ "按剧本切分镜 project_id=%s force=%s user_id=%s",
+ project_id,
+ force,
+ user.id,
+ )
+ try:
+ await seed_episodes_from_script(db, project, force=force)
+ except ValueError as exc:
+ logger.warning("切分镜失败 project_id=%s err=%s", project_id, exc)
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ result = await db.execute(
+ select(DramaEpisode)
+ .where(DramaEpisode.project_id == project_id)
+ .options(
+ selectinload(DramaEpisode.fragments).selectinload(DramaEpisodeFragment.asset_references)
+ )
+ .order_by(DramaEpisode.id.asc())
+ )
+ episodes = result.scalars().all()
+ frag_total = sum(len(ep.fragments or []) for ep in episodes)
+ logger.info(
+ "切分镜完成 project_id=%s episodes=%s fragments=%s",
+ project_id,
+ len(episodes),
+ frag_total,
+ )
+ return [_episode_out(ep) for ep in episodes]
+
+
[email protected]("/episodes/{episode_id}/fragments", response_model=DramaEpisodeOut)
+async def save_fragments(
+ episode_id: int,
+ body: DramaSaveFragmentsRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> DramaEpisodeOut:
+ ep = await get_owned_episode(db, episode_id, user)
+ for old in list(ep.fragments or []):
+ await db.delete(old)
+ await db.flush()
+ for item in body.fragments:
+ frag = DramaEpisodeFragment(
+ episode_id=ep.id,
+ sort_order=item.sort_order,
+ content=item.content or "",
+ cover=item.cover or "",
+ video=item.video or "",
+ duration_sec=item.duration_sec,
+ params=item.params,
+ )
+ db.add(frag)
+ await db.flush()
+ for aid in item.asset_ids:
+ db.add(DramaFragmentAssetRef(fragment_id=frag.id, asset_id=aid))
+ await db.commit()
+ ep = await get_owned_episode(db, episode_id, user)
+ logger.info(
+ "已保存分镜 episode_id=%s count=%s",
+ episode_id,
+ len(body.fragments),
+ )
+ return _episode_out(ep)
+
+
[email protected]("/episodes/{episode_id}/generate")
+async def generate_episode(
+ episode_id: int,
+ body: DramaGenerateRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ # 入队 Celery / 进程内任务,前端用 generate_status 轮询
+ ep = await get_owned_episode(db, episode_id, user)
+ await get_owned_drama_project(db, ep.project_id, user)
+ frags = sorted(ep.fragments or [], key=lambda f: f.sort_order)
+ if body.fragment_ids:
+ id_set = set(body.fragment_ids)
+ frags = [f for f in frags if f.id in id_set]
+ if not frags:
+ raise HTTPException(status_code=400, detail="没有可生成的分镜")
+
+ frag_ids = [f.id for f in frags]
+ for f in frags:
+ params = dict(f.params or {})
+ params["generation"] = {"status": "queued"}
+ f.params = params
+ await db.commit()
+
+ task_id = dispatch_episode_generate_job(episode_id, user.id, frag_ids)
+ logger.info(
+ "已入队分集视频 episode_id=%s project_id=%s fragments=%s task_id=%s",
+ episode_id,
+ ep.project_id,
+ len(frag_ids),
+ task_id,
+ )
+ return {
+ "ok": True,
+ "fragment_ids": frag_ids,
+ "status": "queued",
+ "task_id": task_id,
+ }
+
+
[email protected]("/episodes/{episode_id}/generate_status")
+async def generate_status(
+ episode_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ ep = await get_owned_episode(db, episode_id, user)
+ items = []
+ done = 0
+ failed = 0
+ running = 0
+ for f in sorted(ep.fragments or [], key=lambda x: x.sort_order):
+ st = fragment_generation_status(f)
+ items.append({"fragment_id": f.id, **st})
+ s = st.get("status")
+ if s == "done":
+ done += 1
+ elif s == "failed":
+ failed += 1
+ elif s in {"running", "queued"}:
+ running += 1
+ return {
+ "episode_id": episode_id,
+ "done": done,
+ "failed": failed,
+ "running": running,
+ "total": len(items),
+ "fragments": items,
+ }
diff --git a/backend/app/api/drama/generation.py b/backend/app/api/drama/generation.py
new file mode 100644
index 0000000..11f2a5b
--- /dev/null
+++ b/backend/app/api/drama/generation.py
@@ -0,0 +1,81 @@
+"""Drama Seedream generation endpoint."""
+
+from __future__ import annotations
+
+import logging
+
+from fastapi import APIRouter, Depends, 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.models_drama import DramaAsset
+from app.schemas_drama import DramaAssetOut, DramaImageGenerateRequest
+from app.services.drama.access import get_owned_drama_project
+from app.services.drama.jobs import dispatch_asset_image_job
+
+router = APIRouter()
+logger = logging.getLogger("app.drama.generation")
+
+
[email protected]("/generation/image")
+async def generate_image(
+ body: DramaImageGenerateRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ # 入队生图;返回 queued,前端轮询资产 params.generation / 列表刷新
+ project = await get_owned_drama_project(db, body.project_id, user, with_script=True)
+ asset = None
+ if body.asset_id:
+ asset = await db.get(DramaAsset, body.asset_id)
+ if not asset or asset.project_id != project.id:
+ raise HTTPException(status_code=404, detail="资产不存在")
+ params = dict(asset.params or {})
+ params["generation"] = {"status": "generating"}
+ asset.params = params
+ await db.commit()
+ await db.refresh(asset)
+
+ prompt = (body.prompt or "").strip()
+ if not prompt:
+ raise HTTPException(status_code=400, detail="缺少 prompt")
+
+ kind = body.asset_type_kind or (asset.type if asset else "character")
+ # style_id 请求优先,否则回退项目 params
+ style_id = (body.image_style_id or "").strip() or str(
+ (project.params or {}).get("image_style_id") or ""
+ ).strip() or None
+ task_id = dispatch_asset_image_job(
+ project.id,
+ user.id,
+ prompt,
+ asset_id=asset.id if asset else None,
+ name=body.name,
+ kind=kind,
+ image_style_id=style_id,
+ model_id=body.model_id,
+ aspect_ratio=body.aspect_ratio,
+ resolution=body.resolution,
+ )
+ logger.info(
+ "已入队资产生图 project_id=%s asset_id=%s kind=%s style=%s model=%s size=%s/%s task_id=%s prompt_len=%s",
+ project.id,
+ asset.id if asset else None,
+ kind,
+ style_id,
+ body.model_id,
+ body.aspect_ratio,
+ body.resolution,
+ task_id,
+ len(prompt),
+ )
+ return {
+ "ok": True,
+ "queued": True,
+ "status": "generating",
+ "task_id": task_id,
+ "asset_id": asset.id if asset else None,
+ "asset": DramaAssetOut.model_validate(asset).model_dump() if asset else None,
+ }
diff --git a/backend/app/api/drama/projects.py b/backend/app/api/drama/projects.py
new file mode 100644
index 0000000..6bafab8
--- /dev/null
+++ b/backend/app/api/drama/projects.py
@@ -0,0 +1,165 @@
+"""Drama project CRUD."""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends, HTTPException
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import selectinload
+
+from app.database import get_db
+from app.deps import get_current_user
+from app.models import User
+from app.models_drama import DramaProject, DramaScript
+from app.schemas_drama import (
+ DramaProjectCreate,
+ DramaProjectListItem,
+ DramaProjectOut,
+ DramaProjectUpdate,
+ DramaScriptOut,
+)
+from app.services.drama.access import get_owned_drama_project
+
+router = APIRouter()
+
+
+def _project_out(project: DramaProject) -> DramaProjectOut:
+ script = None
+ if project.script:
+ script = DramaScriptOut.model_validate(project.script)
+ return DramaProjectOut(
+ id=project.id,
+ user_id=project.user_id,
+ title=project.title,
+ description=project.description,
+ content=project.content,
+ params=project.params,
+ created_at=project.created_at,
+ updated_at=project.updated_at,
+ script=script,
+ asset_count=len(project.assets) if project.assets is not None else 0,
+ episode_count=len(project.episodes) if project.episodes is not None else 0,
+ )
+
+
[email protected]("/projects", response_model=list[DramaProjectListItem])
+async def list_projects(
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> list[DramaProjectListItem]:
+ # List current user's drama projects
+ result = await db.execute(
+ select(DramaProject)
+ .where(DramaProject.user_id == user.id)
+ .options(
+ selectinload(DramaProject.script),
+ selectinload(DramaProject.assets),
+ selectinload(DramaProject.episodes),
+ )
+ .order_by(DramaProject.updated_at.desc())
+ )
+ rows = list(result.scalars().all())
+ return [
+ DramaProjectListItem(
+ id=p.id,
+ title=p.title,
+ description=p.description,
+ created_at=p.created_at,
+ updated_at=p.updated_at,
+ episode_count=len(p.episodes or []),
+ asset_count=len(p.assets or []),
+ has_script=p.script is not None,
+ )
+ for p in rows
+ ]
+
+
[email protected]("/projects", response_model=DramaProjectOut)
+async def create_project(
+ body: DramaProjectCreate,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> DramaProjectOut:
+ # Create project + empty script draft from creative source
+ source = (body.source or "").strip()
+ if len(source) < 20:
+ raise HTTPException(status_code=400, detail="原始创意至少需要 20 个字")
+ title = (body.title or "").strip()
+ if not title:
+ title = source[:40] + ("…" if len(source) > 40 else "")
+ project = DramaProject(
+ user_id=user.id,
+ title=title or "未命名漫剧",
+ description=body.description,
+ params={
+ **(body.params or {}),
+ "episode_count": body.episode_count,
+ "image_style_id": body.image_style_id,
+ },
+ )
+ db.add(project)
+ await db.flush()
+ script = DramaScript(
+ project_id=project.id,
+ name=project.title,
+ source=source,
+ params={
+ "episode_count": body.episode_count,
+ "image_style_id": body.image_style_id,
+ "summary_status": "pending",
+ "episode_content_status": "pending",
+ },
+ )
+ db.add(script)
+ await db.commit()
+ project = await get_owned_drama_project(
+ db, project.id, user, with_script=True, with_assets=True, with_episodes=True
+ )
+ return _project_out(project)
+
+
[email protected]("/projects/{project_id}", response_model=DramaProjectOut)
+async def get_project(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> DramaProjectOut:
+ project = await get_owned_drama_project(
+ db, project_id, user, with_script=True, with_assets=True, with_episodes=True
+ )
+ return _project_out(project)
+
+
[email protected]("/projects/{project_id}", response_model=DramaProjectOut)
+async def update_project(
+ project_id: int,
+ body: DramaProjectUpdate,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> DramaProjectOut:
+ project = await get_owned_drama_project(db, project_id, user, with_script=True)
+ if body.title is not None:
+ project.title = body.title.strip() or project.title
+ if body.description is not None:
+ project.description = body.description
+ if body.content is not None:
+ project.content = body.content
+ if body.params is not None:
+ project.params = body.params
+ await db.commit()
+ project = await get_owned_drama_project(
+ db, project_id, user, with_script=True, with_assets=True, with_episodes=True
+ )
+ return _project_out(project)
+
+
[email protected]("/projects/{project_id}")
+async def delete_project(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ project = await get_owned_drama_project(db, project_id, user)
+ await db.delete(project)
+ await db.commit()
+ return {"ok": True}
diff --git a/backend/app/api/drama/scripts.py b/backend/app/api/drama/scripts.py
new file mode 100644
index 0000000..42ee867
--- /dev/null
+++ b/backend/app/api/drama/scripts.py
@@ -0,0 +1,66 @@
+"""Drama script endpoints."""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends, HTTPException
+from pydantic import BaseModel, Field
+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_drama import DramaScriptOut
+from app.services.drama.access import get_owned_drama_project
+
+router = APIRouter()
+
+
+class ScriptUpdateBody(BaseModel):
+ source: str | None = None
+ summary: dict | None = None
+ episode_content: dict | list | None = None
+ image_style_id: str | None = None
+ name: str | None = None
+
+
[email protected]("/scripts/{project_id}", response_model=DramaScriptOut)
+async def get_script(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> DramaScriptOut:
+ project = await get_owned_drama_project(db, project_id, user, with_script=True)
+ if not project.script:
+ raise HTTPException(status_code=404, detail="剧本不存在")
+ return DramaScriptOut.model_validate(project.script)
+
+
[email protected]("/scripts/{project_id}", response_model=DramaScriptOut)
+async def update_script(
+ project_id: int,
+ body: ScriptUpdateBody,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> DramaScriptOut:
+ project = await get_owned_drama_project(db, project_id, user, with_script=True)
+ if not project.script:
+ raise HTTPException(status_code=404, detail="剧本不存在")
+ script = project.script
+ if body.source is not None:
+ script.source = body.source
+ if body.summary is not None:
+ script.summary = body.summary
+ if body.episode_content is not None:
+ script.episode_content = body.episode_content
+ if body.name is not None:
+ script.name = body.name
+ if body.image_style_id is not None:
+ params = dict(script.params or {})
+ params["image_style_id"] = body.image_style_id
+ script.params = params
+ pparams = dict(project.params or {})
+ pparams["image_style_id"] = body.image_style_id
+ project.params = pparams
+ await db.commit()
+ await db.refresh(script)
+ return DramaScriptOut.model_validate(script)
diff --git a/backend/app/config.py b/backend/app/config.py
index f26e64d..fbeacb3 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -8,6 +8,8 @@ class Settings(BaseSettings):
app_name: str = "PRINTFILM"
debug: bool = True
+ # 是否打印 SQLAlchemy 原始 SQL(默认关,避免刷屏;需要排查 SQL 时设 SQL_ECHO=true)
+ sql_echo: bool = False
secret_key: str = "dev-secret-change-me"
access_token_expire_minutes: int = 60 * 24 * 7
@@ -19,9 +21,12 @@ class Settings(BaseSettings):
ark_base_url: str = "https://ark.cn-beijing.volces.com/api/v3"
model_llm: str = "doubao-seed-2-0-pro-260215"
model_image: str = "doubao-seedream-5-0-260128"
+ # Seedream 4.5 接入点(可选;未配则回退 model_image)
+ model_image_45: str = ""
model_video: str = "doubao-seedance-2-5-260628"
+ # Seedance 2.0/2.5 i2v 官方范围约 4–15 秒;勿超过模型上限
seedance_duration_min: int = 4
- seedance_duration_max: int = 30
+ seedance_duration_max: int = 15
model_audio: str = "seed-tts-2.0"
# 豆包语音(openspeech)— 与方舟 ARK_API_KEY 不同产品线
volc_tts_app_id: str = ""
diff --git a/backend/app/database.py b/backend/app/database.py
index 81280cd..f0156fb 100644
--- a/backend/app/database.py
+++ b/backend/app/database.py
@@ -7,7 +7,7 @@ from app.config import get_settings
settings = get_settings()
-_engine_kwargs: dict = {"echo": settings.debug}
+_engine_kwargs: dict = {"echo": bool(settings.sql_echo)}
if settings.database_url.startswith("postgresql"):
_engine_kwargs.update(pool_pre_ping=True, pool_size=10, max_overflow=20)
@@ -26,6 +26,7 @@ async def get_db() -> AsyncGenerator[AsyncSession, None]:
async def init_db() -> None:
from app import models # noqa: F401
+ from app import models_drama # noqa: F401
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
diff --git a/backend/app/logging_setup.py b/backend/app/logging_setup.py
new file mode 100644
index 0000000..383490c
--- /dev/null
+++ b/backend/app/logging_setup.py
@@ -0,0 +1,61 @@
+"""统一应用日志:可读业务日志,默认不刷 SQL / aiosqlite DEBUG。"""
+
+from __future__ import annotations
+
+import logging
+import sys
+
+_configured = False
+
+
+def configure_logging(*, level: str = "INFO", sql_echo: bool = False) -> None:
+ # 配置根日志;可重复调用以刷新级别(reload 后仍可生效)
+ global _configured
+
+ root = logging.getLogger()
+ if not root.handlers:
+ handler = logging.StreamHandler(sys.stdout)
+ handler.setFormatter(
+ logging.Formatter(
+ "%(asctime)s [%(levelname)s] %(name)s: %(message)s",
+ datefmt="%H:%M:%S",
+ )
+ )
+ root.addHandler(handler)
+
+ # 根级别用 INFO:DEBUG=true 也不刷第三方库
+ root.setLevel(logging.INFO)
+ logging.getLogger("app").setLevel(getattr(logging, level.upper(), logging.INFO))
+
+ # SQL / SQLite 驱动默认关闭
+ sql_level = logging.INFO if sql_echo else logging.WARNING
+ for name in (
+ "sqlalchemy",
+ "sqlalchemy.engine",
+ "sqlalchemy.pool",
+ "sqlalchemy.dialects",
+ "aiosqlite",
+ "sqlite3",
+ ):
+ logging.getLogger(name).setLevel(sql_level if name.startswith("sqlalchemy") else logging.WARNING)
+
+ if sql_echo:
+ logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO)
+ else:
+ logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
+ logging.getLogger("aiosqlite").setLevel(logging.WARNING)
+
+ # 其他噪音
+ for name in ("uvicorn.access", "httpx", "httpcore", "celery", "asyncio", "multipart"):
+ logging.getLogger(name).setLevel(
+ logging.INFO if name == "uvicorn.access" else logging.WARNING
+ )
+ logging.getLogger("celery").setLevel(logging.INFO)
+
+ if not _configured:
+ logging.getLogger("app").info(
+ "日志已配置 app_level=%s sql_echo=%s(已关闭 aiosqlite/SQL DEBUG)",
+ level,
+ sql_echo,
+ )
+ _configured = True
diff --git a/backend/app/main.py b/backend/app/main.py
index c32bd5f..e2059a1 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -1,18 +1,26 @@
from pathlib import Path
+import logging
+import time
-from fastapi import FastAPI
+from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from sqlalchemy import select, text
from app.api import auth, billing, projects, templates
from app.api.admin import router as admin_router
+from app.api.drama import router as drama_router
from app.config import get_settings
from app.database import AsyncSessionLocal, engine, init_db
+from app.logging_setup import configure_logging
from app.models import Template, User
from app.services.templates_seed import TEMPLATES
settings = get_settings()
+# 业务日志 INFO;DEBUG=true 不再把根日志打成 DEBUG(避免 aiosqlite 刷屏)
+configure_logging(level="INFO", sql_echo=settings.sql_echo)
+logger = logging.getLogger("app.http")
+
app = FastAPI(title=settings.app_name, version="0.2.0")
origins = [o.strip() for o in settings.cors_origins.split(",") if o.strip()]
@@ -34,6 +42,32 @@ app.add_middleware(
allow_headers=["*"],
)
+
+async def log_requests(request: Request, call_next):
+ # 业务可读请求日志(跳过静态资源;高频轮询默认不打)
+ path = request.url.path
+ started = time.perf_counter()
+ response = await call_next(request)
+ elapsed_ms = (time.perf_counter() - started) * 1000
+ if path.startswith("/static"):
+ return response
+ # 高频轮询:成功且较快时静默,避免淹没业务日志
+ is_poll = (
+ path.endswith("/generate_status")
+ or (request.method == "GET" and path.startswith("/api/drama/scripts/"))
+ or (request.method == "GET" and path.startswith("/api/drama/assets"))
+ or (request.method == "GET" and path.startswith("/api/projects/") and path.count("/") == 3)
+ )
+ msg = f"{request.method} {path} → {response.status_code} ({elapsed_ms:.0f}ms)"
+ if response.status_code >= 400:
+ logger.warning(msg)
+ elif is_poll and elapsed_ms < 800:
+ return response
+ else:
+ logger.info(msg)
+ return response
+
static_dir = Path(__file__).resolve().parent.parent / "static"
static_dir.mkdir(parents=True, exist_ok=True)
(static_dir / "templates").mkdir(exist_ok=True)
@@ -45,6 +79,7 @@ app.include_router(auth.router, prefix="/api")
app.include_router(templates.router, prefix="/api")
app.include_router(projects.router, prefix="/api")
app.include_router(billing.router, prefix="/api")
+app.include_router(drama_router, prefix="/api")
app.include_router(admin_router, prefix="/api")
@@ -141,6 +176,21 @@ async def _migrate_sqlite() -> None:
if "role" not in ucols:
await conn.execute(text("ALTER TABLE users ADD COLUMN role VARCHAR(16) DEFAULT 'user'"))
+ # UsageEvent.drama_project_id for drama module billing
+ if is_sqlite:
+ result = await conn.execute(text("PRAGMA table_info(usage_events)"))
+ uecols = {row[1] for row in result.fetchall()}
+ else:
+ result = await conn.execute(
+ text(
+ "SELECT column_name FROM information_schema.columns "
+ "WHERE table_name = 'usage_events'"
+ )
+ )
+ uecols = {row[0] for row in result.fetchall()}
+ if "drama_project_id" not in uecols:
+ await conn.execute(text("ALTER TABLE usage_events ADD COLUMN drama_project_id INTEGER"))
+
async def bootstrap_admins() -> None:
# Promote matching emails to admin (does not create users)
diff --git a/backend/app/models.py b/backend/app/models.py
index 8e566b7..a50040a 100644
--- a/backend/app/models.py
+++ b/backend/app/models.py
@@ -181,6 +181,8 @@ class UsageEvent(Base):
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
project_id: Mapped[int | None] = mapped_column(ForeignKey("projects.id"), nullable=True, index=True)
+ # Drama module billing ref (mutually exclusive with kepu project_id when set)
+ drama_project_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
shot_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
provider: Mapped[str] = mapped_column(String(32), default="ark")
billing_key: Mapped[str] = mapped_column(String(64), index=True)
diff --git a/backend/app/models_drama.py b/backend/app/models_drama.py
new file mode 100644
index 0000000..649820b
--- /dev/null
+++ b/backend/app/models_drama.py
@@ -0,0 +1,172 @@
+"""Drama module ORM models (table prefix drama_)."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+from sqlalchemy import JSON, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint, func
+from sqlalchemy.orm import Mapped, mapped_column, relationship
+
+from app.database import Base
+
+
+class DramaProject(Base):
+ # One drama series owned by a PRINTFILM user
+ __tablename__ = "drama_projects"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
+ title: Mapped[str] = mapped_column(String(200), default="未命名漫剧")
+ description: Mapped[str | None] = mapped_column(String(512), nullable=True)
+ content: Mapped[dict | list | None] = mapped_column(JSON, nullable=True)
+ params: Mapped[dict | None] = mapped_column(JSON, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
+ )
+
+ assets: Mapped[list["DramaAsset"]] = relationship(
+ back_populates="project", cascade="all, delete-orphan"
+ )
+ episodes: Mapped[list["DramaEpisode"]] = relationship(
+ back_populates="project", cascade="all, delete-orphan"
+ )
+ script: Mapped["DramaScript | None"] = relationship(
+ back_populates="project", uselist=False, cascade="all, delete-orphan"
+ )
+
+
+class DramaScript(Base):
+ # Outline summary + per-episode body JSON
+ __tablename__ = "drama_scripts"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ name: Mapped[str] = mapped_column(String(200), default="剧本")
+ source: Mapped[str | None] = mapped_column(Text, nullable=True)
+ summary: Mapped[dict | None] = mapped_column(JSON, nullable=True)
+ episode_content: Mapped[dict | list | None] = mapped_column(JSON, nullable=True)
+ params: Mapped[dict | None] = mapped_column(JSON, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
+ )
+ project_id: Mapped[int] = mapped_column(
+ ForeignKey("drama_projects.id", ondelete="CASCADE"), unique=True, index=True
+ )
+ episode_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
+
+ project: Mapped["DramaProject"] = relationship(back_populates="script")
+
+
+class DramaAsset(Base):
+ # Character / scene / prop / material / canvas node
+ __tablename__ = "drama_assets"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ type: Mapped[str] = mapped_column(String(32), default="none")
+ asset_type: Mapped[str] = mapped_column(String(32), default="image")
+ name: Mapped[str | None] = mapped_column(String(200), nullable=True)
+ cover: Mapped[str | None] = mapped_column(String(1024), nullable=True)
+ url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
+ params: Mapped[dict | None] = mapped_column(JSON, nullable=True)
+ derive_id: Mapped[str | None] = mapped_column(String(10), nullable=True, index=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
+ )
+ project_id: Mapped[int] = mapped_column(
+ ForeignKey("drama_projects.id", ondelete="CASCADE"), index=True
+ )
+
+ project: Mapped["DramaProject"] = relationship(back_populates="assets")
+ asset_episodes: Mapped[list["DramaAssetEpisode"]] = relationship(
+ back_populates="asset", cascade="all, delete-orphan"
+ )
+ fragment_refs: Mapped[list["DramaFragmentAssetRef"]] = relationship(
+ back_populates="asset", cascade="all, delete-orphan"
+ )
+
+
+class DramaEpisode(Base):
+ # One episode within a drama project
+ __tablename__ = "drama_episodes"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ name: Mapped[str] = mapped_column(String(200))
+ params: Mapped[dict | None] = mapped_column(JSON, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
+ )
+ project_id: Mapped[int] = mapped_column(
+ ForeignKey("drama_projects.id", ondelete="CASCADE"), index=True
+ )
+
+ project: Mapped["DramaProject"] = relationship(back_populates="episodes")
+ asset_episodes: Mapped[list["DramaAssetEpisode"]] = relationship(
+ back_populates="episode", cascade="all, delete-orphan"
+ )
+ fragments: Mapped[list["DramaEpisodeFragment"]] = relationship(
+ back_populates="episode", cascade="all, delete-orphan"
+ )
+
+
+class DramaEpisodeFragment(Base):
+ # Storyboard beat within an episode
+ __tablename__ = "drama_episode_fragments"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ episode_id: Mapped[int] = mapped_column(
+ ForeignKey("drama_episodes.id", ondelete="CASCADE"), index=True
+ )
+ sort_order: Mapped[int] = mapped_column(Integer, default=0)
+ content: Mapped[str] = mapped_column(Text, default="")
+ cover: Mapped[str] = mapped_column(String(1024), default="")
+ video: Mapped[str] = mapped_column(String(1024), default="")
+ duration_sec: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ params: Mapped[dict | None] = mapped_column(JSON, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
+ )
+
+ episode: Mapped["DramaEpisode"] = relationship(back_populates="fragments")
+ asset_references: Mapped[list["DramaFragmentAssetRef"]] = relationship(
+ back_populates="fragment", cascade="all, delete-orphan"
+ )
+
+
+class DramaFragmentAssetRef(Base):
+ # Fragment ↔ asset reference
+ __tablename__ = "drama_fragment_asset_refs"
+ __table_args__ = (UniqueConstraint("fragment_id", "asset_id", name="uq_drama_frag_asset"),)
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ fragment_id: Mapped[int] = mapped_column(
+ ForeignKey("drama_episode_fragments.id", ondelete="CASCADE"), index=True
+ )
+ asset_id: Mapped[int] = mapped_column(
+ ForeignKey("drama_assets.id", ondelete="CASCADE"), index=True
+ )
+
+ fragment: Mapped["DramaEpisodeFragment"] = relationship(back_populates="asset_references")
+ asset: Mapped["DramaAsset"] = relationship(back_populates="fragment_refs")
+
+
+class DramaAssetEpisode(Base):
+ # Asset ↔ episode many-to-many
+ __tablename__ = "drama_asset_episodes"
+ __table_args__ = (UniqueConstraint("asset_id", "episode_id", name="uq_drama_asset_episode"),)
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ asset_id: Mapped[int] = mapped_column(
+ ForeignKey("drama_assets.id", ondelete="CASCADE"), index=True
+ )
+ episode_id: Mapped[int] = mapped_column(
+ ForeignKey("drama_episodes.id", ondelete="CASCADE"), index=True
+ )
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+
+ asset: Mapped["DramaAsset"] = relationship(back_populates="asset_episodes")
+ episode: Mapped["DramaEpisode"] = relationship(back_populates="asset_episodes")
diff --git a/backend/app/schemas_drama.py b/backend/app/schemas_drama.py
new file mode 100644
index 0000000..1c4cbe5
--- /dev/null
+++ b/backend/app/schemas_drama.py
@@ -0,0 +1,187 @@
+"""Pydantic schemas for the drama module."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+
+class DramaProjectCreate(BaseModel):
+ title: str = Field(default="未命名漫剧", max_length=200)
+ description: str | None = None
+ source: str = Field(default="", description="原始创意文案")
+ episode_count: int = Field(default=12, ge=1, le=120)
+ image_style_id: str = Field(default="")
+ params: dict[str, Any] | None = None
+
+
+class DramaProjectUpdate(BaseModel):
+ title: str | None = None
+ description: str | None = None
+ content: dict | list | None = None
+ params: dict[str, Any] | None = None
+
+
+class DramaScriptOut(BaseModel):
+ id: int
+ name: str
+ source: str | None = None
+ summary: dict | None = None
+ episode_content: dict | list | None = None
+ params: dict | None = None
+ project_id: int
+
+ model_config = {"from_attributes": True}
+
+
+class DramaAssetOut(BaseModel):
+ id: int
+ type: str
+ asset_type: str
+ name: str | None = None
+ cover: str | None = None
+ url: str | None = None
+ params: dict | None = None
+ derive_id: str | None = None
+ project_id: int
+
+ model_config = {"from_attributes": True}
+
+
+class DramaFragmentOut(BaseModel):
+ id: int
+ episode_id: int
+ sort_order: int
+ content: str
+ cover: str = ""
+ video: str = ""
+ duration_sec: int | None = None
+ params: dict | None = None
+ asset_ids: list[int] = Field(default_factory=list)
+
+ model_config = {"from_attributes": True}
+
+
+class DramaEpisodeOut(BaseModel):
+ id: int
+ name: str
+ params: dict | None = None
+ project_id: int
+ fragments: list[DramaFragmentOut] = Field(default_factory=list)
+
+ model_config = {"from_attributes": True}
+
+
+class DramaProjectOut(BaseModel):
+ id: int
+ user_id: int
+ title: str
+ description: str | None = None
+ content: dict | list | None = None
+ params: dict | None = None
+ created_at: datetime | None = None
+ updated_at: datetime | None = None
+ script: DramaScriptOut | None = None
+ asset_count: int = 0
+ episode_count: int = 0
+
+ model_config = {"from_attributes": True}
+
+
+class DramaProjectListItem(BaseModel):
+ id: int
+ title: str
+ description: str | None = None
+ created_at: datetime | None = None
+ updated_at: datetime | None = None
+ episode_count: int = 0
+ asset_count: int = 0
+ has_script: bool = False
+
+ model_config = {"from_attributes": True}
+
+
+class DramaScriptSummaryRequest(BaseModel):
+ project_id: int
+ creative: str | None = None
+ episode_count: int | None = None
+ image_style_id: str | None = None
+
+
+class DramaEpisodeScriptRequest(BaseModel):
+ project_id: int
+ # 与原项目一致:默认逐集生成,降低超时/截断导致「只出一半」的风险
+ batch_size: int = Field(default=1, ge=1, le=12)
+ # 强制重写:清空已有正文(保留集名),再按新提示词生成
+ force: bool = False
+
+
+class DramaAssetCreate(BaseModel):
+ project_id: int
+ type: str = "none"
+ asset_type: str = "image"
+ name: str | None = None
+ cover: str | None = None
+ url: str | None = None
+ params: dict | None = None
+
+
+class DramaAssetUpdate(BaseModel):
+ type: str | None = None
+ asset_type: str | None = None
+ name: str | None = None
+ cover: str | None = None
+ url: str | None = None
+ params: dict | None = None
+
+
+class DramaImageGenerateRequest(BaseModel):
+ project_id: int
+ asset_id: int | None = None
+ prompt: str
+ name: str | None = None
+ asset_type_kind: str = "character"
+ # 内置风格 ID(可缺省,回退项目/剧本 params.image_style_id)
+ image_style_id: str | None = None
+ # 前端模型 ID:seedream-5.0 / seedream-4.5
+ model_id: str | None = None
+ # 输出比例,角色默认 3:4
+ aspect_ratio: str | None = None
+ # 清晰度 3K / 4K
+ resolution: str | None = None
+
+
+class DramaFragmentSaveItem(BaseModel):
+ id: int | None = None
+ sort_order: int = 0
+ content: str = ""
+ cover: str = ""
+ video: str = ""
+ duration_sec: int | None = None
+ params: dict | None = None
+ asset_ids: list[int] = Field(default_factory=list)
+
+
+class DramaSaveFragmentsRequest(BaseModel):
+ fragments: list[DramaFragmentSaveItem]
+
+
+class DramaGenerateRequest(BaseModel):
+ fragment_ids: list[int] | None = None
+
+
+class DramaCanvasSaveRequest(BaseModel):
+ project_id: int
+ nodes: list[dict[str, Any]] = Field(default_factory=list)
+ edges: list[dict[str, Any]] = Field(default_factory=list)
+
+
+class DramaChatRequest(BaseModel):
+ message: str
+ project_id: int | None = None
+
+
+class DramaRouteRequest(BaseModel):
+ message: str
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
index a7f6abb..d4b6ba8 100644
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@ -249,6 +249,21 @@ class ArkGateway:
"每镜 img_prompt 只写本镜场景与构图(景物、动作、光影),不要重复粘贴大段画风/人物锁定原文;"
"出现人物时用短句点出与 character_bible 一致的关键特征即可。"
)
+ # shot_cap 单镜 duration 上限(秒),写入 prompt 与校验说明
+ shot_cap = min(duration_max, max_shot_duration)
+ # segment_rules 科普逐段脚本生产约束(对齐漫剧 cue,无 @asset)
+ segment_rules = (
+ "【segments 生产规范】"
+ "segments 必填;系统会落成 @duration +【字幕】/【BGM】/【旁白·慢速清晰·同步字幕】生产脚本,"
+ "因此 kind/text/duration 必须可直接消费。"
+ "段序优先「画面→旁白」交替,首段尽量 kind=visual(保证首帧有料);"
+ "visual/action 的 text 必须含景别+主体动作+场景/界面类型,禁止空镜与模糊氛围词堆砌;"
+ "narration 的 text 为一句一事、可朗读口播,按约 3 字/秒估 duration;"
+ "单段 duration 3-12 秒,镜内各段之和约等于本镜 duration,且不超过 "
+ f"{shot_cap} 秒。"
+ "禁止真实商标/公司名/人名(改用泛称)。"
+ "character_bible 与 bgm_lock 全片唯一,各镜不得改人设或漂移 BGM 氛围。"
+ )
if pipeline_mode == "image_text":
diversity_note = (
"拆成 5-10 个分镜,每镜一个独立视觉场景;"
@@ -263,7 +278,7 @@ class ArkGateway:
system = (
f"你是{orient}图文短视频编剧。所有字段必须使用简体中文。"
f"{consistency}{llm_system_addon}"
- f"每镜 duration 在 {duration_min}-{min(duration_max, max_shot_duration)} 秒。"
+ f"每镜 duration 在 {duration_min}-{shot_cap} 秒。"
"这是「静图+叠字+配音」模式:不生成 AI 视频,但需要旁白配音;"
"画面禁止出现任何文字/水印/字幕。"
"shots 字段说明:"
@@ -273,11 +288,12 @@ class ArkGateway:
"subtitle(对本镜卖点/要点的一句概括,8-22字,同样禁止原文截取前缀)、"
"text(旁白台词,口语化,约匹配该镜时长,可供 TTS 朗读,一般 20-60 字)、"
"segments(数组,精确到每一段:每项含 duration 秒、kind=visual|narration、text;"
- "visual 写景别与画面动作,narration 写口播;单段 3-12 秒,合计约等于本镜 duration)、"
+ "visual 写景别与画面动作,narration 写口播)、"
f"img_prompt({orient} {ratio} 构图画面提示词,留出边缘给文字叠层,主体居中,"
"禁止要求画面内写字;禁止出现真实商标/公司名/人名,用泛称)、"
"video_prompt(可留空或写轻微推拉)、camera(如:缓慢推近/轻拉远)、bgm(情绪,全片尽量同一氛围)。"
"另输出顶层 bgm_lock(全片统一 BGM 氛围一句)。"
+ f"{segment_rules}"
f"{diversity_note}"
)
else:
@@ -290,24 +306,20 @@ class ArkGateway:
"你是短视频分镜编剧。所有字段必须使用简体中文"
"(包括 title、text、img_prompt、video_prompt、camera、bgm、segments)。"
f"{consistency}{llm_system_addon}"
- f"每镜 duration 在 {duration_min}-{min(duration_max, max_shot_duration)} 秒。"
+ f"每镜 duration 在 {duration_min}-{shot_cap} 秒。"
"shots 字段说明:"
"shot(序号)、duration(秒)、"
"title(对本镜旁白的概括短标题,2-8字,语义完整;"
"必须是总结提炼,禁止从 text 截取前缀,禁止截断专有名词如 ERP→ER)、"
"subtitle(可选,一句要点概括 8-22字)、"
- "text(旁白台词)、"
- "segments(必填数组,精确到每一段:每项 duration、kind=visual|narration|action、text;"
- "先画面后旁白或交替;visual/action 写清景别、主体动作、场景/界面类型;"
- "narration 为可朗读口播;单段 3-12 秒,按约 3 字/秒估旁白时长;"
- "镜内各段 duration 之和应约等于本镜 duration,且不超过 "
- f"{min(duration_max, max_shot_duration)} 秒)、"
- "img_prompt(首段画面中文提示词,含具体景物与构图;"
- "禁止真实商标/公司名/人名,改用泛称)、"
+ "text(旁白台词,与 segments 中 narration 文案一致或为其摘要)、"
+ "segments(必填数组,精确到每一段:每项 duration、kind=visual|narration|action、text)、"
+ "img_prompt(与首段 visual 一致的中文首帧提示词,含具体景物与构图)、"
"video_prompt(可与 segments 画面摘要一致)、"
"camera(运镜,如:缓慢上摇/轻推/横移)、bgm(情绪,全片同一氛围)。"
"顶层另输出 bgm_lock(全片统一 BGM 氛围一句,与各镜 bgm 一致)。"
"img_prompt 与 video_prompt 禁止英文句子,专有名词可保留原文。"
+ f"{segment_rules}"
f"{diversity_note}"
)
user = (
@@ -342,6 +354,7 @@ class ArkGateway:
project_id: int | None = None,
shot_no: int | None = None,
size: str | None = None,
+ model: str | None = None,
) -> ImageResult:
if self.mock:
local = await asyncio.to_thread(self._write_mock_image, prompt, size)
@@ -374,6 +387,7 @@ class ArkGateway:
project_id=project_id,
shot_no=shot_no,
size=size,
+ model=model,
prompt_hash_src=prompt,
)
except Exception as exc: # noqa: BLE001
@@ -398,9 +412,10 @@ class ArkGateway:
shot_no: int | None,
size: str | None,
prompt_hash_src: str,
+ model: str | None = None,
) -> ImageResult:
body: dict[str, Any] = {
- "model": self.settings.model_image,
+ "model": (model or "").strip() or self.settings.model_image,
"prompt": full_prompt,
"size": size or self.settings.ark_image_size,
"response_format": "url",
@@ -539,17 +554,24 @@ class ArkGateway:
"role": "first_frame",
},
]
+ # 首帧/首尾帧生视频:ratio 必须省略,输出比例跟随首帧图
+ # (传 ratio 会报 InvalidParameter.TaskTypeConstraint)
body: dict[str, Any] = {
"model": self.settings.model_video,
"content": content,
"duration": self._seedance_duration(duration),
- "ratio": ratio or self.settings.ark_video_ratio,
"resolution": resolution,
"watermark": False,
"generate_audio": False,
"return_last_frame": bool(return_last_frame),
}
# Do not send character_consistency — unknown fields have caused BodyFormat failures
+ logger.info(
+ "Seedance i2v create model=%s duration=%s resolution=%s (ratio omitted for first_frame)",
+ body["model"],
+ body["duration"],
+ resolution,
+ )
async with httpx.AsyncClient(timeout=60.0) as client:
resp = await client.post(
@@ -566,8 +588,19 @@ class ArkGateway:
json=body,
)
if resp.status_code >= 400:
- # Last try: drop role
+ err_text = resp.text or ""
+ # 若仍因 ratio 报错(兼容旧调用残留),显式去掉再试
+ if "ratio" in err_text.lower() and "ratio" in body:
+ body.pop("ratio", None)
+ resp = await client.post(
+ self._url("/contents/generations/tasks"),
+ headers=self._headers(),
+ json=body,
+ )
+ if resp.status_code >= 400:
+ # Last try: drop role(参考图模式,可按需带 adaptive)
body["content"][1].pop("role", None)
+ body["ratio"] = "adaptive"
resp = await client.post(
self._url("/contents/generations/tasks"),
headers=self._headers(),
diff --git a/backend/app/services/billing.py b/backend/app/services/billing.py
index 9092eac..4358ed2 100644
--- a/backend/app/services/billing.py
+++ b/backend/app/services/billing.py
@@ -173,6 +173,7 @@ async def record_usage(
raw: dict | None = None,
shot_id: int | None = None,
provider: str = "ark",
+ drama_project_id: int | None = None,
) -> UsageEvent:
s = get_settings()
total = int(tokens) or (int(prompt_tokens) + int(completion_tokens))
@@ -194,6 +195,7 @@ async def record_usage(
ev = UsageEvent(
user_id=user_id,
project_id=project_id,
+ drama_project_id=drama_project_id,
shot_id=shot_id,
provider=provider,
billing_key=billing_key,
diff --git a/backend/app/services/drama/__init__.py b/backend/app/services/drama/__init__.py
new file mode 100644
index 0000000..7381b08
--- /dev/null
+++ b/backend/app/services/drama/__init__.py
@@ -0,0 +1 @@
+"""Drama service package."""
diff --git a/backend/app/services/drama/access.py b/backend/app/services/drama/access.py
new file mode 100644
index 0000000..f0f9ea4
--- /dev/null
+++ b/backend/app/services/drama/access.py
@@ -0,0 +1,72 @@
+"""Drama access helpers."""
+
+from __future__ import annotations
+
+from fastapi import HTTPException
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import selectinload
+
+from app.models import User
+from app.models_drama import (
+ DramaEpisode,
+ DramaEpisodeFragment,
+ DramaFragmentAssetRef,
+ DramaProject,
+)
+
+
+async def get_owned_drama_project(
+ db: AsyncSession,
+ project_id: int,
+ user: User,
+ *,
+ with_script: bool = False,
+ with_assets: bool = False,
+ with_episodes: bool = False,
+) -> DramaProject:
+ # Load project owned by current user with optional relations
+ opts = []
+ if with_script:
+ opts.append(selectinload(DramaProject.script))
+ if with_assets:
+ opts.append(selectinload(DramaProject.assets))
+ if with_episodes:
+ opts.append(selectinload(DramaProject.episodes).selectinload(DramaEpisode.fragments))
+ q = select(DramaProject).where(DramaProject.id == project_id, DramaProject.user_id == user.id)
+ if opts:
+ q = q.options(*opts)
+ result = await db.execute(q)
+ project = result.scalar_one_or_none()
+ if not project:
+ raise HTTPException(status_code=404, detail="漫剧项目不存在")
+ return project
+
+
+async def get_owned_episode(
+ db: AsyncSession,
+ episode_id: int,
+ user: User,
+ *,
+ with_fragments: bool = True,
+) -> DramaEpisode:
+ # Load episode after verifying project ownership
+ opts = []
+ if with_fragments:
+ opts.append(
+ selectinload(DramaEpisode.fragments)
+ .selectinload(DramaEpisodeFragment.asset_references)
+ .selectinload(DramaFragmentAssetRef.asset)
+ )
+ q = (
+ select(DramaEpisode)
+ .join(DramaProject, DramaEpisode.project_id == DramaProject.id)
+ .where(DramaEpisode.id == episode_id, DramaProject.user_id == user.id)
+ )
+ if opts:
+ q = q.options(*opts)
+ result = await db.execute(q)
+ episode = result.scalar_one_or_none()
+ if not episode:
+ raise HTTPException(status_code=404, detail="分集不存在")
+ return episode
diff --git a/backend/app/services/drama/agents.py b/backend/app/services/drama/agents.py
new file mode 100644
index 0000000..1915535
--- /dev/null
+++ b/backend/app/services/drama/agents.py
@@ -0,0 +1,529 @@
+"""Drama script agents: summary + episode outline + episode scripts."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from app.services.drama.llm import drama_chat_json
+
+# 与 manju scriptSummary 对齐的摘要系统提示
+SCRIPT_SUMMARY_SYSTEM = """你是专业的短剧/网剧剧本策划,负责把用户提供的原始创意、故事大纲或灵感,整理成可直接用于立项与编剧开工的结构化「剧本摘要」。
+
+输出要求:
+1. 忠实于用户创意,可合理补全细节,但不要擅自改掉核心设定、主线与结局
+2. 若用户提供了目标集数,episodeCount 必须与该值完全一致;未提供时根据故事体量合理估算(短篇 12–24 集)
+3. 若用户提供了画面风格,人物 visualImage 须体现该风格的视觉美学,storyType 可融合风格相关标签
+4. storyType、coreHook 用「+」连接多个标签,风格参考:古风奇幻+神话后传+反乌托邦
+5. targetAudience 简洁,如:男频 / 大众、女频 / 青年 等
+6. oneLineStory 一句话说清主线 + 最大反转或钩子
+7. characters 至少包含全部主角与 1–2 名关键配角/反派;每人字段须饱满、可拍摄、有戏剧张力
+8. 人物小传中 growthArc 必须用「阶段A -> 阶段B -> 阶段C」格式
+9. synopsis 用一段完整中文叙述故事,从世界观、矛盾、结盟、高潮、结局到余韵,长度 200–400 字
+10. 语言统一使用简体中文,偏影视策划文档风格,避免空泛形容词堆砌
+
+必须输出严格 JSON 对象(不要 markdown、不要代码围栏),字段:
+{
+ "episodeCount": number,
+ "storyType": string,
+ "targetAudience": string,
+ "coreHook": string,
+ "oneLineStory": string,
+ "characters": [
+ {
+ "name": string,
+ "title": string,
+ "roleType": string,
+ "visualImage": string,
+ "coreTags": string,
+ "identityBackground": string,
+ "growthExperience": string,
+ "personality": string,
+ "relationships": string,
+ "growthArc": string
+ }
+ ],
+ "synopsis": string
+}"""
+
+# 与 manju episodeScript 对齐:先规划全集集名
+EPISODE_OUTLINE_SYSTEM = """你是专业的短剧/网剧编剧策划,负责根据原始创意与剧本摘要,规划全部分集的「集数 + 集名」大纲。
+
+输出要求:
+1. 必须严格按照用户给定的总集数生成,episodes 数组长度必须与总集数完全一致
+2. episodeNumber 从 1 开始连续递增,不得跳号、不得重复
+3. 每集 title 为 4-12 个汉字的集名,概括本集核心事件或冲突钩子,风格参考:金箍碎佛规、罪臣之子承玄圭
+4. 全剧分集须覆盖剧本摘要中的起承转合:前期立人设与世界观、中期升级矛盾与反转、后期高潮与结局,节奏适合短剧连载
+5. 相邻集名之间要有因果衔接与追剧钩子,避免重复套路
+6. 语言使用简体中文
+
+必须输出严格 JSON:
+{"episodes":[{"episodeNumber":1,"title":"集名"}, ...]}"""
+
+# 与 manju episodeScript 对齐:逐集撰写拍摄正文
+EPISODE_BATCH_CONTENT_SYSTEM = """你是专业的短剧/网剧编剧,负责根据原始创意、剧本摘要、分集规划与已有剧集正文,撰写指定集数的拍摄剧本正文。
+
+输出要求:
+1. 每次任务只输出用户指定批次范围内的集数,episodes 数组长度必须与批次集数完全一致
+2. episodeNumber 须与用户指定的集数一一对应,不得遗漏、不得额外生成
+3. 须携带并参考「已有剧集正文」保持剧情、人设与世界观连贯;首批次无已有正文时从第 1 集开篇写起
+4. 批次内各集之间须有因果衔接,末集结尾留追剧钩子
+5. 必须输出对象格式:{"episodes":[{"episodeNumber":数字,"title":"集名","content":"..."}]},不要直接输出数组
+6. content 为正文主字段;不要把正文写得过短
+
+格式要求(每集 content 须严格遵守):
+1. 按场次组织,场号格式为 ### 场{集数}-{场次},如第 1 集第 2 场:### 场1-2
+2. 场头下一行写时间内外景,如:日 内 灵山大雄宝殿 / 夜 外 妖寨大门外 / 晨外 羽山刑场
+3. 下一行写:出场人物:角色A、角色B
+4. 动作用 △ 开头,独占一行;动作须具体可拍(景别、调度、道具、表情),禁止一句带过
+5. 台词格式:角色名(情绪/vo/os/动作):台词内容;旁白用 vo,内心独白用 os;台词要有潜台词与冲突
+6. 关键镜头可用【空镜:描述】收尾一场或一段
+7. content 内不要输出「第X集」或「X.集名:」标题行,只输出场戏正文
+8. 每集 3-5 场;每场至少 3 段 △ 动作与 4 句以上台词(或对白+vo);整集 content 不少于 800 汉字
+9. 语言使用简体中文,偏影视剧本风格,动作与台词可拍摄、有张力"""
+
+# 正文过短阈值(汉字量近似用去空白后长度)
+MIN_EPISODE_CONTENT_CHARS = 500
+
+
+async def run_script_summary(
+ creative: str,
+ episode_count: int | None = None,
+ image_style_id: str | None = None,
+) -> dict[str, Any]:
+ # Build structured outline from creative brief
+ trimmed = (creative or "").strip()
+ if len(trimmed) < 10:
+ raise ValueError("原始创意至少需要 10 个字")
+
+ user_parts = [f"原始创意:\n{trimmed}"]
+ if episode_count:
+ user_parts.append(f"目标集数:{episode_count}(episodeCount 必须等于该值)")
+ if image_style_id:
+ user_parts.append(f"画面风格 ID:{image_style_id}")
+ data = await drama_chat_json(
+ SCRIPT_SUMMARY_SYSTEM,
+ "\n\n".join(user_parts),
+ max_tokens=8192,
+ )
+ if isinstance(data, dict) and data.get("mock"):
+ data = _mock_summary(trimmed, episode_count or 12)
+ if episode_count:
+ data["episodeCount"] = episode_count
+ return data
+
+
+def resolve_episode_target(
+ summary: dict[str, Any] | None,
+ project_params: dict[str, Any] | None = None,
+ script_params: dict[str, Any] | None = None,
+) -> int:
+ # 解析目标总集数:优先项目创建时的集数,其次摘要 / 剧本参数
+ candidates = [
+ (project_params or {}).get("episode_count"),
+ (summary or {}).get("episodeCount"),
+ (script_params or {}).get("episode_count"),
+ ]
+ for raw in candidates:
+ try:
+ value = int(raw) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ continue
+ if value >= 1:
+ return value
+ return 12
+
+
+def merge_episode_bodies(
+ existing: list[dict[str, Any]],
+ batch: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ # 按集号合并;正文更长者优先,标题非空则更新
+ by_number: dict[int, dict[str, Any]] = {}
+ for item in existing + batch:
+ if not isinstance(item, dict):
+ continue
+ try:
+ number = int(item.get("episodeNumber") or item.get("episode_number") or 0)
+ except (TypeError, ValueError):
+ continue
+ if number < 1:
+ continue
+ body = str(item.get("body") or item.get("content") or "")
+ title = str(item.get("title") or "").strip() or f"第 {number} 集"
+ prev = by_number.get(number)
+ if prev:
+ prev_body = str(prev.get("body") or "")
+ if len(prev_body.strip()) > len(body.strip()):
+ body = prev_body
+ if title.startswith("第 ") and prev.get("title"):
+ title = str(prev.get("title"))
+ elif not title or title == f"第 {number} 集":
+ title = str(prev.get("title") or title)
+ by_number[number] = {
+ "episodeNumber": number,
+ "title": title,
+ "body": body,
+ }
+ return [by_number[n] for n in sorted(by_number)]
+
+
+def count_completed_episodes(episodes: list[dict[str, Any]], total: int) -> int:
+ # 统计 1..total 中正文达到质量阈值的集数
+ done = 0
+ for item in episodes:
+ try:
+ number = int(item.get("episodeNumber") or 0)
+ except (TypeError, ValueError):
+ continue
+ body = str(item.get("body") or "").strip()
+ if 1 <= number <= total and _content_char_len(body) >= MIN_EPISODE_CONTENT_CHARS:
+ done += 1
+ return done
+
+
+def _content_char_len(text: str) -> int:
+ return len("".join((text or "").split()))
+
+
+def format_summary_text(summary: dict[str, Any]) -> str:
+ # Human-readable outline for UI / LLM context
+ lines = [
+ f"集数:{summary.get('episodeCount', '')}",
+ f"类型:{summary.get('storyType', '')}",
+ f"受众:{summary.get('targetAudience', '')}",
+ f"钩子:{summary.get('coreHook', '')}",
+ f"一句话:{summary.get('oneLineStory', '')}",
+ "",
+ "人物:",
+ ]
+ for c in summary.get("characters") or []:
+ if isinstance(c, dict):
+ lines.append(
+ f"- {c.get('name', '')}({c.get('roleType', '')}/{c.get('title', '')}):"
+ f"{c.get('visualImage', '')};标签:{c.get('coreTags', '')};"
+ f"弧光:{c.get('growthArc', '')}"
+ )
+ lines.extend(["", "梗概:", str(summary.get("synopsis") or "")])
+ return "\n".join(lines)
+
+
+def _format_episode_title_list(episodes: list[dict[str, Any]]) -> str:
+ rows: list[str] = []
+ for item in sorted(episodes, key=lambda x: int(x.get("episodeNumber") or 0)):
+ num = item.get("episodeNumber")
+ title = item.get("title") or f"第 {num} 集"
+ rows.append(f"第 {num} 集:{title}")
+ return "\n".join(rows) if rows else "(暂无分集规划)"
+
+
+def _format_existing_episode_content(episodes: list[dict[str, Any]], limit: int = 3) -> str:
+ # 仅附最近若干集正文,控制上下文长度
+ completed = [
+ item
+ for item in episodes
+ if isinstance(item, dict) and str(item.get("body") or item.get("content") or "").strip()
+ ]
+ completed.sort(key=lambda x: int(x.get("episodeNumber") or 0))
+ if not completed:
+ return "(暂无,本批次从开篇写起)"
+ tail = completed[-limit:]
+ blocks: list[str] = []
+ for item in tail:
+ num = item.get("episodeNumber")
+ title = item.get("title") or f"第 {num} 集"
+ body = str(item.get("body") or item.get("content") or "").strip()
+ # 过长时截断尾部摘要,避免挤占当前集生成空间
+ if len(body) > 1800:
+ body = body[:1800] + "\n…(上文已截断)"
+ blocks.append(f"{num}.{title}:\n{body}")
+ return "\n\n".join(blocks)
+
+
+def _titles_ready(existing: list[dict[str, Any]], total: int) -> bool:
+ titled = {
+ int(item.get("episodeNumber") or 0)
+ for item in existing
+ if isinstance(item, dict)
+ and str(item.get("title") or "").strip()
+ and not str(item.get("title") or "").startswith("第 ")
+ }
+ # 也接受「第 N 集」以外、或至少有 total 条带 title 的记录
+ with_title = [
+ item
+ for item in existing
+ if isinstance(item, dict)
+ and 1 <= int(item.get("episodeNumber") or 0) <= total
+ and str(item.get("title") or "").strip()
+ ]
+ if len(with_title) >= total:
+ # 若全是占位「第 N 集」则仍需重跑大纲
+ placeholder_only = all(
+ str(item.get("title") or "").strip() in {f"第 {item.get('episodeNumber')} 集", f"第{item.get('episodeNumber')}集"}
+ for item in with_title
+ )
+ return not placeholder_only
+ return len(titled) >= total
+
+
+async def run_episode_outline(
+ creative: str,
+ summary: dict[str, Any],
+ episode_count: int,
+) -> list[dict[str, Any]]:
+ # 生成全集集名大纲
+ summary_text = format_summary_text(summary)
+ user = "\n".join(
+ [
+ f"总集数:{episode_count} 集(episodes 数组必须恰好 {episode_count} 项)",
+ "",
+ f"原始创意:\n{(creative or '').strip()}",
+ "",
+ f"剧本摘要:\n{summary_text}",
+ "",
+ "请输出全部分集的 episodeNumber 与 title。",
+ ]
+ )
+ data = await drama_chat_json(EPISODE_OUTLINE_SYSTEM, user, max_tokens=4096)
+ if isinstance(data, dict) and data.get("mock"):
+ return [
+ {"episodeNumber": i, "title": f"第{i}集钩子", "body": ""}
+ for i in range(1, episode_count + 1)
+ ]
+ episodes = data.get("episodes") if isinstance(data, dict) else data
+ if not isinstance(episodes, list) or not episodes:
+ raise ValueError("分集大纲返回格式无效")
+ result: list[dict[str, Any]] = []
+ for i, item in enumerate(episodes):
+ if not isinstance(item, dict):
+ continue
+ try:
+ number = int(item.get("episodeNumber") or (i + 1))
+ except (TypeError, ValueError):
+ number = i + 1
+ title = str(item.get("title") or "").strip() or f"第 {number} 集"
+ result.append({"episodeNumber": number, "title": title, "body": ""})
+ if len(result) < episode_count:
+ # 补齐缺失集号
+ have = {int(x["episodeNumber"]) for x in result}
+ for n in range(1, episode_count + 1):
+ if n not in have:
+ result.append({"episodeNumber": n, "title": f"第 {n} 集", "body": ""})
+ result.sort(key=lambda x: int(x["episodeNumber"]))
+ return result[:episode_count]
+
+
+async def ensure_episode_outline(
+ creative: str,
+ summary: dict[str, Any],
+ existing: list[dict[str, Any]],
+ total: int,
+) -> list[dict[str, Any]]:
+ # 无有效集名时先跑大纲,再与已有正文合并
+ if _titles_ready(existing, total):
+ return existing
+ outline = await run_episode_outline(creative, summary, total)
+ return merge_episode_bodies(outline, existing)
+
+
+async def run_episode_script_batch(
+ summary: dict[str, Any],
+ existing: list[dict[str, Any]],
+ batch_size: int = 1,
+ total: int | None = None,
+ creative: str = "",
+) -> list[dict[str, Any]]:
+ # 按缺失集号生成下一批正文(默认逐集)
+ target = int(total or summary.get("episodeCount") or 12)
+ have_body = {
+ int(item.get("episodeNumber") or 0)
+ for item in existing
+ if isinstance(item, dict)
+ and _content_char_len(str(item.get("body") or item.get("content") or ""))
+ >= MIN_EPISODE_CONTENT_CHARS
+ }
+ missing = [n for n in range(1, target + 1) if n not in have_body]
+ if not missing:
+ return []
+ start = missing[0]
+ end = start
+ for i in range(1, min(batch_size, len(missing))):
+ if missing[i] != end + 1:
+ break
+ end = missing[i]
+
+ title_by_num = {
+ int(item.get("episodeNumber") or 0): str(item.get("title") or "")
+ for item in existing
+ if isinstance(item, dict)
+ }
+ batch_titles = "\n".join(
+ f"第 {n} 集:{title_by_num.get(n) or f'第 {n} 集'}" for n in range(start, end + 1)
+ )
+ batch_size_n = end - start + 1
+ summary_text = format_summary_text(summary)
+ user = "\n".join(
+ [
+ f"当前任务:撰写第 {start} 集至第 {end} 集(共 {batch_size_n} 集)的完整剧本正文",
+ f"全剧共 {target} 集",
+ f"episodes 输出数组必须恰好 {batch_size_n} 项,episodeNumber 从 {start} 到 {end}",
+ f"每集 content 不少于 {MIN_EPISODE_CONTENT_CHARS} 汉字,含 3-5 场戏、充分 △ 动作与台词",
+ "",
+ f"原始创意:\n{(creative or '').strip() or '(无额外创意,以摘要为准)'}",
+ "",
+ f"剧本摘要:\n{summary_text}",
+ "",
+ f"全剧分集规划:\n{_format_episode_title_list(existing)}",
+ "",
+ f"本批次待撰写:\n{batch_titles}",
+ "",
+ f"已有剧集正文:\n{_format_existing_episode_content(existing)}",
+ "",
+ f"请输出第 {start}–{end} 集各集的 content 字段(可附带 title)。",
+ ]
+ )
+
+ data = await drama_chat_json(
+ EPISODE_BATCH_CONTENT_SYSTEM,
+ user,
+ temperature=0.65,
+ max_tokens=16384,
+ )
+ if isinstance(data, dict) and data.get("mock"):
+ return [
+ {
+ "episodeNumber": i,
+ "title": title_by_num.get(i) or f"第{i}集",
+ "body": _mock_episode_body(i, summary),
+ }
+ for i in range(start, end + 1)
+ ]
+
+ episodes = data.get("episodes") if isinstance(data, dict) else data
+ if not isinstance(episodes, list):
+ raise ValueError("分集剧本返回格式无效")
+
+ normalized = _normalize_batch_episodes(episodes, start, end, title_by_num)
+ # 正文过短则带强调提示重试一次
+ too_short = [
+ item
+ for item in normalized
+ if _content_char_len(str(item.get("body") or "")) < MIN_EPISODE_CONTENT_CHARS
+ ]
+ if too_short:
+ retry_user = (
+ user
+ + "\n\n上次输出过短。请重写本批次,每集 content 必须 ≥ "
+ + str(MIN_EPISODE_CONTENT_CHARS)
+ + " 汉字,包含完整场次、△ 动作与对白,不得压缩成梗概。"
+ )
+ retry = await drama_chat_json(
+ EPISODE_BATCH_CONTENT_SYSTEM,
+ retry_user,
+ temperature=0.7,
+ max_tokens=16384,
+ )
+ retry_eps = retry.get("episodes") if isinstance(retry, dict) else retry
+ if isinstance(retry_eps, list):
+ normalized = _normalize_batch_episodes(retry_eps, start, end, title_by_num)
+
+ if not normalized:
+ raise ValueError(f"模型未返回第 {start}–{end} 集正文")
+ return normalized
+
+
+def _normalize_batch_episodes(
+ episodes: list[Any],
+ start: int,
+ end: int,
+ title_by_num: dict[int, str],
+) -> list[dict[str, Any]]:
+ normalized: list[dict[str, Any]] = []
+ for offset, item in enumerate(episodes):
+ if not isinstance(item, dict):
+ continue
+ number = item.get("episodeNumber") or item.get("episode_number") or (start + offset)
+ try:
+ number_i = int(number)
+ except (TypeError, ValueError):
+ number_i = start + offset
+ if number_i < start or number_i > end:
+ continue
+ body = str(item.get("content") or item.get("body") or "").strip()
+ if not body:
+ continue
+ title = (
+ str(item.get("title") or "").strip()
+ or title_by_num.get(number_i)
+ or f"第 {number_i} 集"
+ )
+ normalized.append(
+ {
+ "episodeNumber": number_i,
+ "title": title,
+ "body": body,
+ }
+ )
+ return normalized
+
+
+def _mock_episode_body(episode_number: int, summary: dict[str, Any]) -> str:
+ hook = str(summary.get("oneLineStory") or "主线推进")
+ chars = summary.get("characters") or []
+ names = "、".join(
+ str(c.get("name")) for c in chars if isinstance(c, dict) and c.get("name")
+ ) or "主角、配角"
+ return "\n".join(
+ [
+ f"### 场{episode_number}-1",
+ "日 外 主场景",
+ f"出场人物:{names}",
+ f"△ 远景拉开,气氛压抑,呼应钩子:{hook}",
+ "△ 主角站在高处,目光扫过众生",
+ f"主角(沉声):这一集,我们不能再退。",
+ "配角(紧绷):可对面已经布好了局。",
+ f"### 场{episode_number}-2",
+ "日 内 议事厅",
+ f"出场人物:{names}",
+ "△ 众人围桌争执,烛火晃动",
+ "△ 主角拍案而起,地图被压得发皱",
+ "主角(决断):听我的——疏,不堵。",
+ "【空镜:门外风雨将至】",
+ ]
+ )
+
+
+def _mock_summary(creative: str, episode_count: int) -> dict[str, Any]:
+ return {
+ "episodeCount": episode_count,
+ "storyType": "都市+成长",
+ "targetAudience": "大众",
+ "coreHook": "逆袭+关系反转",
+ "oneLineStory": creative[:80],
+ "characters": [
+ {
+ "name": "林辰",
+ "title": "主角",
+ "roleType": "主角",
+ "visualImage": "二十多岁青年,短发,运动夹克",
+ "coreTags": "坚韧、聪明",
+ "identityBackground": "普通人卷入变故",
+ "growthExperience": "从被动到主动",
+ "personality": "外冷内热",
+ "relationships": "与搭档互信",
+ "growthArc": "迷茫 -> 觉醒 -> 担当",
+ },
+ {
+ "name": "苏晚",
+ "title": "搭档",
+ "roleType": "配角",
+ "visualImage": "干练短发女性,浅色风衣",
+ "coreTags": "理性、锋利",
+ "identityBackground": "调查记者",
+ "growthExperience": "从旁观到共谋",
+ "personality": "直率",
+ "relationships": "与林辰搭档",
+ "growthArc": "质疑 -> 同盟 -> 并肩",
+ },
+ ],
+ "synopsis": f"(模拟)故事围绕:{creative[:200]}",
+ }
diff --git a/backend/app/services/drama/build_fragments.py b/backend/app/services/drama/build_fragments.py
new file mode 100644
index 0000000..49a5758
--- /dev/null
+++ b/backend/app/services/drama/build_fragments.py
@@ -0,0 +1,380 @@
+"""将分集剧本按场次切成视频向分镜(对齐 manju buildSerieFragmentsFromEpisode)。"""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+# 场次标题:### 场1-2 / ### 场景1-2
+SCENE_HEADER_RE = re.compile(r"^###\s*场(?:景)?\s*\d+\s*[--—]\s*\d+\s*$")
+# 兼容无空格、或标题后带说明
+SCENE_HEADER_LOOSE_RE = re.compile(r"^###\s*场(?:景)?\s*\d+\s*[--—]\s*\d+")
+# 时间内外景行
+SCENE_LOCATION_RE = re.compile(
+ r"^(?:日|夜|晨|黄昏|傍晚|凌晨|清晨|午|晚)?\s*(?:内|外|内外)\s+(.+)$"
+)
+# 出场人物行
+CAST_LINE_RE = re.compile(r"^出场人物[::]\s*(.+)$")
+EMPTY_CAST = {"无", "无出场", "无人物", "-", "—", "无。"}
+
+FRAGMENT_DURATION_MIN = 3
+FRAGMENT_DURATION_MAX = 12
+# 单分镜总时长不超过 Seedance 2.x i2v 上限(约 15s)
+FRAGMENT_TOTAL_MAX = 15
+
+
+def normalize_scene_location_name(raw: str) -> str:
+ # 去掉斜杠说明、压缩空白
+ primary = re.split(r"[//]", raw)[0].strip()
+ cleaned = re.sub(r"\s+", " ", primary).strip()
+ if len(cleaned) < 2 or len(cleaned) > 40:
+ return ""
+ return cleaned
+
+
+def parse_cast_names(raw: str) -> list[str]:
+ # 解析「出场人物:A、B」
+ trimmed = (raw or "").strip()
+ if not trimmed or trimmed.rstrip("。..") in EMPTY_CAST:
+ return []
+ names = [
+ part.strip()
+ for part in re.split(r"[、,,//|]", trimmed)
+ if part.strip() and part.strip() not in EMPTY_CAST
+ ]
+ # 去重保序
+ seen: set[str] = set()
+ out: list[str] = []
+ for name in names:
+ if name not in seen:
+ seen.add(name)
+ out.append(name)
+ return out
+
+
+def split_episode_content_into_scenes(content: str) -> list[dict[str, str]]:
+ # 按 ### 场X-Y 拆分;无场头时整集一场
+ lines = (content or "").replace("\r\n", "\n").split("\n")
+ scenes: list[dict[str, str]] = []
+ current: dict[str, Any] | None = None
+
+ for line in lines:
+ trimmed = line.strip()
+ if SCENE_HEADER_RE.match(trimmed) or SCENE_HEADER_LOOSE_RE.match(trimmed):
+ if current is not None:
+ scenes.append(
+ {
+ "heading": current["heading"],
+ "body": "\n".join(current["lines"]).strip(),
+ }
+ )
+ current = {"heading": trimmed, "lines": []}
+ continue
+ if current is not None:
+ current["lines"].append(line)
+
+ if current is not None:
+ scenes.append(
+ {
+ "heading": current["heading"],
+ "body": "\n".join(current["lines"]).strip(),
+ }
+ )
+
+ if scenes:
+ return scenes
+
+ trimmed_all = (content or "").strip()
+ if not trimmed_all:
+ return []
+ return [{"heading": "", "body": trimmed_all}]
+
+
+def extract_scene_meta(body: str) -> dict[str, Any]:
+ # 抽取地点与出场人物
+ scene_name: str | None = None
+ character_names: list[str] = []
+ for line in (body or "").replace("\r\n", "\n").split("\n"):
+ trimmed = line.strip()
+ if not trimmed:
+ continue
+ if scene_name is None:
+ loc = SCENE_LOCATION_RE.match(trimmed)
+ if loc:
+ normalized = normalize_scene_location_name(loc.group(1))
+ scene_name = normalized or None
+ cast = CAST_LINE_RE.match(trimmed)
+ if cast:
+ character_names = parse_cast_names(cast.group(1))
+ return {"sceneName": scene_name, "characterNames": character_names}
+
+
+def _find_asset_by_name(candidates: list[Any], name: str) -> Any | None:
+ target = (name or "").strip()
+ if not target:
+ return None
+ for item in candidates:
+ asset_name = (getattr(item, "name", None) or "").strip()
+ if asset_name == target:
+ return item
+ for item in candidates:
+ asset_name = (getattr(item, "name", None) or "").strip()
+ if asset_name and (target in asset_name or asset_name in target):
+ return item
+ return None
+
+
+def _strip_screenplay_meta(body: str) -> tuple[str | None, list[str]]:
+ location_line: str | None = None
+ narrative: list[str] = []
+ for line in (body or "").replace("\r\n", "\n").split("\n"):
+ trimmed = line.strip()
+ if not trimmed:
+ continue
+ if SCENE_HEADER_RE.match(trimmed) or SCENE_HEADER_LOOSE_RE.match(trimmed):
+ continue
+ if CAST_LINE_RE.match(trimmed):
+ continue
+ if location_line is None and SCENE_LOCATION_RE.match(trimmed):
+ location_line = trimmed
+ continue
+ narrative.append(trimmed)
+ return location_line, narrative
+
+
+def _format_narrative_line(line: str) -> str:
+ trimmed = line.strip()
+ if not trimmed:
+ return trimmed
+ if re.search(r"[((](?:vo|VO|旁白)[))]", trimmed):
+ return f"【旁白·慢速清晰·同步字幕】{trimmed}"
+ if re.search(r"[((](?:os|OS)[))]", trimmed):
+ return f"【内心独白·同步字幕】{trimmed}"
+ if re.match(r"^[^((::\n]{1,16}[((][^))]*[))]\s*[::].+", trimmed) or re.match(
+ r"^[^::\n]{1,16}[::].+", trimmed
+ ):
+ return f"【对白·慢速清晰·同步字幕】{trimmed}"
+ if trimmed.startswith("△") or trimmed.startswith("Δ"):
+ return trimmed.replace("Δ", "△", 1) if trimmed.startswith("Δ") else trimmed
+ if trimmed.startswith("【空镜"):
+ return f"【空镜·可仅环境音与 BGM】{trimmed}"
+ return trimmed
+
+
+def _estimate_line_duration(line: str) -> int:
+ trimmed = line.strip()
+ if not trimmed:
+ return 0
+ if trimmed.startswith("△"):
+ return 2
+ if trimmed.startswith("【空镜"):
+ return 4
+ if "旁白" in trimmed:
+ return min(8, max(3, len(re.sub(r"\s+", "", trimmed)) // 8))
+ if "对白" in trimmed or "内心独白" in trimmed:
+ return min(8, max(3, len(re.sub(r"\s+", "", trimmed)) // 10))
+ return min(6, max(2, len(re.sub(r"\s+", "", trimmed)) // 12))
+
+
+def _clamp_duration(seconds: int) -> int:
+ if seconds <= 0:
+ return 0
+ return min(max(seconds, FRAGMENT_DURATION_MIN), FRAGMENT_DURATION_MAX)
+
+
+def _inject_character_mentions(text: str, bindings: list[dict[str, Any]]) -> str:
+ if not bindings:
+ return text
+ sorted_bindings = sorted(bindings, key=lambda b: len(b["name"]), reverse=True)
+ parts = re.split(r"(@asset:\d+)", text)
+ out: list[str] = []
+ for part in parts:
+ if re.fullmatch(r"@asset:\d+", part or ""):
+ out.append(part)
+ continue
+ result = part
+ for binding in sorted_bindings:
+ result = result.replace(binding["name"], f"@asset:{binding['assetId']}")
+ out.append(result)
+ return "".join(out)
+
+
+def _format_location_opener(
+ location_line: str | None,
+ scene_asset_id: int | None,
+ scene_name: str | None,
+) -> str:
+ if not location_line:
+ if scene_asset_id and scene_name:
+ return f"@asset:{scene_asset_id} {scene_name}。"
+ return ""
+ match = SCENE_LOCATION_RE.match(location_line)
+ if match and match.group(1) and scene_asset_id:
+ prefix = location_line[: len(location_line) - len(match.group(1))].strip()
+ location_part = match.group(1).strip()
+ compressed = re.sub(r"\s+", "", prefix)
+ return f"{compressed} @asset:{scene_asset_id} {location_part}。"
+ return location_line if location_line.endswith("。") else f"{location_line}。"
+
+
+def _infer_bgm_mood(hints: str) -> str:
+ text = hints or ""
+ rules = [
+ (r"刑|斩|战|杀|怒|崩|劫|乱", "低沉紧张、鼓点渐强,烘托压迫与危机感"),
+ (r"殿|宫|朝|帝|神|礼", "庄重史诗、弦乐铺底,气势恢宏但不抢戏"),
+ (r"夜|暗|悬疑|密", "神秘悬疑、低频铺底,留白感强"),
+ (r"水|河|海|雨|洪", "流动感环境音乐,水声与弦乐交织"),
+ (r"晨|春|暖|光", "轻柔开阔、希望感,钢琴或弦乐为主"),
+ ]
+ for pattern, mood in rules:
+ if re.search(pattern, text):
+ return mood
+ return "贴合剧情氛围的轻量配乐,情绪随画面起伏"
+
+
+def _build_production_cues(
+ location_line: str | None,
+ narrative_lines: list[str],
+ character_intro_lines: list[str],
+) -> list[str]:
+ # 字幕 / BGM / 人物介绍前置提示
+ hint = " ".join(filter(None, [location_line or "", *narrative_lines[:3]]))
+ lines = [
+ "【字幕:底部居中·简体中文·对白旁白同步】",
+ f"【BGM:{_infer_bgm_mood(hint)};音量低于人声】",
+ ]
+ lines.extend(character_intro_lines)
+ return lines
+
+
+def plan_fragment_content_from_scene(
+ body: str,
+ meta: dict[str, Any],
+ scene_asset_id: int | None,
+ character_bindings: list[dict[str, Any]],
+) -> tuple[str, int]:
+ # 规划单场视频向分镜正文,返回 (content, duration_sec)
+ location_line, narrative_lines = _strip_screenplay_meta(body)
+ intro_lines = [
+ (
+ f"【人物介绍·画面叠字】{b['name']}|{b['introText']}"
+ if b.get("introText")
+ else f"【人物介绍·画面叠字】{b['name']}"
+ )
+ for b in character_bindings
+ ]
+ planned = _build_production_cues(location_line, narrative_lines, intro_lines)
+ used = 0
+
+ opener = _format_location_opener(location_line, scene_asset_id, meta.get("sceneName"))
+ if opener:
+ opener_dur = _clamp_duration(3)
+ if used + opener_dur <= FRAGMENT_TOTAL_MAX:
+ planned.append(f"@duration:{opener_dur}")
+ planned.append(_inject_character_mentions(opener, character_bindings))
+ used += opener_dur
+
+ for line in narrative_lines:
+ raw = _inject_character_mentions(line, character_bindings)
+ formatted = _format_narrative_line(raw)
+ line_dur = _clamp_duration(_estimate_line_duration(formatted))
+ if used + line_dur > FRAGMENT_TOTAL_MAX:
+ line_dur = max(FRAGMENT_TOTAL_MAX - used, 0)
+ if line_dur <= 0:
+ break
+ planned.append(f"@duration:{line_dur}")
+ planned.append(formatted)
+ used += line_dur
+
+ if used == 0:
+ planned.append(f"@duration:{FRAGMENT_DURATION_MIN}")
+ used = FRAGMENT_DURATION_MIN
+
+ return "\n".join(planned).strip(), used
+
+
+def is_raw_screenplay_fragment(content: str) -> bool:
+ # 仍为场记原文、需按新逻辑重切
+ trimmed = (content or "").strip()
+ if not trimmed:
+ return True
+ if "### 场" in trimmed or "### 场景" in trimmed:
+ return True
+ if re.search(r"^出场人物[::]", trimmed, re.M):
+ return True
+ if "【字幕:" not in trimmed and "@duration:" not in trimmed:
+ return True
+ return False
+
+
+def build_fragments_from_episode_body(
+ content: str,
+ assets: list[Any],
+) -> list[dict[str, Any]]:
+ """
+ 将一集正文拆成多场分镜草稿。
+ 返回 [{content, duration_sec, asset_ids, scene_name, character_names}, ...]
+ """
+ character_assets = [a for a in assets if getattr(a, "type", "") == "character"]
+ scene_assets = [a for a in assets if getattr(a, "type", "") == "scene"]
+ scenes = split_episode_content_into_scenes(content)
+
+ if not scenes:
+ return [
+ {
+ "content": "",
+ "duration_sec": 8,
+ "asset_ids": [],
+ "scene_name": None,
+ "character_names": [],
+ }
+ ]
+
+ fragments: list[dict[str, Any]] = []
+ for scene in scenes:
+ meta = extract_scene_meta(scene["body"])
+ matched_ids: list[int] = []
+ scene_asset_id: int | None = None
+ character_bindings: list[dict[str, Any]] = []
+
+ if meta.get("sceneName"):
+ scene_asset = _find_asset_by_name(scene_assets, str(meta["sceneName"]))
+ if scene_asset is not None:
+ scene_asset_id = int(scene_asset.id)
+ matched_ids.append(scene_asset_id)
+
+ for character_name in meta.get("characterNames") or []:
+ character_asset = _find_asset_by_name(character_assets, str(character_name))
+ if character_asset is None:
+ continue
+ intro = None
+ params = getattr(character_asset, "params", None) or {}
+ if isinstance(params, dict):
+ intro = params.get("title") or params.get("roleType") or params.get("coreTags")
+ character_bindings.append(
+ {
+ "name": str(character_name),
+ "assetId": int(character_asset.id),
+ "introText": str(intro).strip() if intro else None,
+ }
+ )
+ if character_asset.id not in matched_ids:
+ matched_ids.append(int(character_asset.id))
+
+ planned, duration = plan_fragment_content_from_scene(
+ scene["body"],
+ meta,
+ scene_asset_id,
+ character_bindings,
+ )
+ fragments.append(
+ {
+ "content": planned,
+ "duration_sec": duration or 8,
+ "asset_ids": matched_ids,
+ "scene_name": meta.get("sceneName"),
+ "character_names": meta.get("characterNames") or [],
+ }
+ )
+
+ return fragments
diff --git a/backend/app/services/drama/generation.py b/backend/app/services/drama/generation.py
new file mode 100644
index 0000000..c7bc95c
--- /dev/null
+++ b/backend/app/services/drama/generation.py
@@ -0,0 +1,193 @@
+"""Drama image / video generation helpers."""
+
+from __future__ import annotations
+
+import logging
+import time
+from typing import Any
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config import get_settings
+from app.models import User
+from app.models_drama import DramaAsset, DramaEpisodeFragment, DramaFragmentAssetRef, DramaProject
+from app.services.ark import get_ark
+from app.services.billing import record_usage
+from app.services.drama.generation_prompt import build_generation_prompt
+from app.services.drama.seedream_options import resolve_seedream_model_endpoint, resolve_seedream_size
+
+logger = logging.getLogger(__name__)
+
+
+def fragment_generation_status(fragment: DramaEpisodeFragment) -> dict[str, Any]:
+ """读取分镜片段生成状态(done / running / failed / idle)。"""
+ params = fragment.params or {}
+ gen = params.get("generation") if isinstance(params, dict) else None
+ if fragment.video:
+ return {"status": "done", "video": fragment.video, "cover": fragment.cover}
+ if isinstance(gen, dict):
+ return gen
+ return {"status": "idle"}
+
+
+async def generate_asset_image(
+ db: AsyncSession,
+ user: User,
+ project: DramaProject,
+ prompt: str,
+ *,
+ asset: DramaAsset | None = None,
+ name: str | None = None,
+ kind: str = "character",
+ image_style_id: str | None = None,
+ model_id: str | None = None,
+ aspect_ratio: str | None = None,
+ resolution: str | None = None,
+) -> DramaAsset:
+ """Generate Seedream image and attach/create asset."""
+ settings = get_settings()
+ ark = get_ark()
+
+ # style_id 请求优先,否则回退项目 params
+ style_id = (image_style_id or "").strip() or str(
+ (project.params or {}).get("image_style_id") or ""
+ ).strip() or None
+ # ratio 默认:角色 3:4,其它 16:9
+ ratio = (aspect_ratio or "").strip() or (
+ "3:4" if (kind or "").lower() == "character" else "16:9"
+ )
+ res = (resolution or "").strip() or "3K"
+ size = resolve_seedream_size(aspect_ratio=ratio, resolution=res)
+ model = resolve_seedream_model_endpoint(model_id)
+ full_prompt = build_generation_prompt(prompt, asset_type=kind, style_id=style_id)
+
+ logger.info(
+ "调用 Seedream 生图 project_id=%s asset_id=%s kind=%s style=%s model=%s size=%s prompt_len=%s",
+ project.id,
+ asset.id if asset else None,
+ kind,
+ style_id,
+ model,
+ size,
+ len(full_prompt or ""),
+ )
+ result = await ark.gen_image(
+ full_prompt.strip(),
+ project_id=project.id,
+ size=size,
+ model=model,
+ )
+ url = result.local_url or ""
+ logger.info("Seedream 返回 project_id=%s url=%s", project.id, (url or "")[:100])
+
+ await record_usage(
+ db,
+ user_id=user.id,
+ project_id=None,
+ drama_project_id=project.id,
+ billing_key="seedream",
+ model=model or settings.model_image,
+ estimated=True,
+ )
+
+ # gen_meta 写入资产 params,便于前端回显上次选项
+ gen_meta = {
+ "prompt": prompt,
+ "image_style_id": style_id,
+ "model_id": model_id or "seedream-5.0",
+ "aspect_ratio": ratio,
+ "resolution": res,
+ }
+
+ if asset is None:
+ asset = DramaAsset(
+ project_id=project.id,
+ type=kind,
+ asset_type="image",
+ name=name or "未命名资产",
+ cover=url,
+ url=url,
+ params=gen_meta,
+ )
+ db.add(asset)
+ else:
+ asset.cover = url
+ asset.url = url
+ params = dict(asset.params or {})
+ params.update(gen_meta)
+ asset.params = params
+
+ await db.commit()
+ await db.refresh(asset)
+ return asset
+
+
+async def generate_fragment_video(
+ db: AsyncSession,
+ user: User,
+ project: DramaProject,
+ fragment: DramaEpisodeFragment,
+) -> DramaEpisodeFragment:
+ """为单个分镜片段生成 Seedance 视频。"""
+ settings = get_settings()
+ ark = get_ark()
+ prompt = (fragment.content or "").strip() or "短剧分镜"
+ duration = int(fragment.duration_sec or 8)
+ duration = max(settings.seedance_duration_min, min(duration, settings.seedance_duration_max))
+
+ refs = (
+ await db.execute(
+ select(DramaFragmentAssetRef)
+ .where(DramaFragmentAssetRef.fragment_id == fragment.id)
+ .order_by(DramaFragmentAssetRef.id.asc())
+ )
+ ).scalars().all()
+ image_url = ""
+ for ref in refs:
+ asset = await db.get(DramaAsset, ref.asset_id)
+ if asset and (asset.url or asset.cover):
+ image_url = asset.url or asset.cover or ""
+ break
+
+ t0 = time.time()
+ if image_url:
+ local_video = await ark.gen_and_wait_video(
+ image_url,
+ prompt,
+ duration,
+ project_id=project.id,
+ shot_no=fragment.id,
+ ratio="16:9",
+ )
+ else:
+ still = await ark.gen_image(prompt[:500], project_id=project.id, shot_no=fragment.id)
+ local_video = await ark.gen_and_wait_video(
+ still.local_url,
+ prompt,
+ duration,
+ project_id=project.id,
+ shot_no=fragment.id,
+ ratio="16:9",
+ )
+
+ fragment.video = local_video
+ fragment.cover = fragment.cover or image_url
+ await record_usage(
+ db,
+ user_id=user.id,
+ project_id=None,
+ drama_project_id=project.id,
+ billing_key="seedance",
+ model=settings.model_video,
+ estimated=True,
+ )
+ await db.commit()
+ await db.refresh(fragment)
+ logger.info(
+ "fragment video done id=%s secs=%.1f url=%s",
+ fragment.id,
+ time.time() - t0,
+ (local_video or "")[:80],
+ )
+ return fragment
diff --git a/backend/app/services/drama/generation_prompt.py b/backend/app/services/drama/generation_prompt.py
new file mode 100644
index 0000000..2b4af9a
--- /dev/null
+++ b/backend/app/services/drama/generation_prompt.py
@@ -0,0 +1,49 @@
+"""漫剧资产生图提示词拼接(角色/场景前缀 + 内置风格)。"""
+
+from __future__ import annotations
+
+from app.services.drama.image_styles import resolve_image_style_prompt
+
+# CHARACTER_PROMPT_PREFIX 角色白底全身照强制前缀
+CHARACTER_PROMPT_PREFIX = (
+ "【强制任务:生成白底人物角色全身照】本次必须生成纯白背景、以人物为主体的全身角色形象,"
+ "人物从头到脚完整入镜,必须是画面绝对主角并占据主要视觉面积,"
+ "背景保持干净简洁的纯白色且无多余元素。"
+ "严禁生成半身照、特写、大头照、肖像、纯风景、空镜、道具特写、文字海报、抽象图案、"
+ "复杂背景或无人物主体的画面。"
+ "即使用户描述偏向场景、物品或动作片段,也必须转化为可辨识的白底全身人物角色来呈现,"
+ "并据此补全外貌、体态、服饰与神态。请严格依据以下用户描述生成白底人物角色全身照:"
+)
+
+# SCENE_PROMPT_PREFIX 场景画面强制前缀
+SCENE_PROMPT_PREFIX = (
+ "【强制任务:生成场景画面】本次必须生成以环境空间为主体的场景画面,"
+ "建筑、地貌、室内外空间或氛围环境必须是画面绝对主角。"
+ "严禁生成人物特写、角色立绘、肖像、以人物为视觉中心或人物占据画面主体的构图。"
+ "即使用户描述涉及人物、角色或动作,也必须剥离人物主体,仅保留并扩展为可独立成立的环境场景。"
+ "请严格依据以下用户描述生成场景画面:"
+)
+
+
+# 将内置风格提示词追加到正文后
+def append_style_prompt(prompt: str, style_id: str | None = None) -> str:
+ style_prompt = resolve_image_style_prompt(style_id)
+ if not style_prompt:
+ return prompt
+ return f"{prompt}。画面风格要求:{style_prompt}"
+
+
+# 按资产类型与风格 ID 组装完整 Seedream 提示词
+def build_generation_prompt(
+ user_prompt: str,
+ asset_type: str | None = None,
+ style_id: str | None = None,
+) -> str:
+ trimmed = (user_prompt or "").strip()
+ prompt = trimmed
+ kind = (asset_type or "").strip().lower()
+ if kind == "character":
+ prompt = f"{CHARACTER_PROMPT_PREFIX}{trimmed}"
+ elif kind == "scene":
+ prompt = f"{SCENE_PROMPT_PREFIX}{trimmed}"
+ return append_style_prompt(prompt, style_id)
diff --git a/backend/app/services/drama/image_styles.py b/backend/app/services/drama/image_styles.py
new file mode 100644
index 0000000..3ffc4f7
--- /dev/null
+++ b/backend/app/services/drama/image_styles.py
@@ -0,0 +1,119 @@
+"""漫剧内置图片风格 ID 与生图提示词片段。"""
+
+from __future__ import annotations
+
+# IMAGE_STYLE_IDS 内置风格 ID(与前端 dramaImageStyles 对齐)
+IMAGE_STYLE_IDS = (
+ "retro-sci-fi-atompunk",
+ "palace-intrigue-cold",
+ "domestic-suspense-cold",
+ "ancient-romance-soft",
+ "ancient-chinese-mythology",
+ "japanese-youth-film",
+ "japanese-daily-natural",
+ "korean-urban-soft",
+ "chinese-urban-realistic",
+ "wuxia-realistic-photo",
+ "90s-realistic-film",
+ "retro-narrative-film",
+ "american-retro-hollywood",
+ "neon-cyberpunk-film",
+ "90s-rural-china-film",
+ "tezuka-era-cartoon",
+ "shanghai-animation",
+ "pixel-art",
+ "shadow-puppet-illustration",
+)
+
+# IMAGE_STYLE_PROMPTS 风格 → 提示词片段
+IMAGE_STYLE_PROMPTS: dict[str, str] = {
+ "retro-sci-fi-atompunk": (
+ "复古科幻原子朋克风格,1950年代未来主义美学,流线型金属与原子能符号,"
+ "霓虹高光,金属质感,高对比色彩,轻微胶片颗粒"
+ ),
+ "palace-intrigue-cold": (
+ "中国宫廷权谋题材冷峻风格,低饱和暗调,克制光影,庄重构图,"
+ "华贵但压抑的宫廷氛围,硬朗轮廓,戏剧化侧光"
+ ),
+ "domestic-suspense-cold": (
+ "国产悬疑影视冷调风格,偏青灰色调,低调光,阴影浓重,写实摄影质感,紧张压抑氛围,细节丰富"
+ ),
+ "ancient-romance-soft": (
+ "中国古代偶像剧唯美柔光风格,梦幻柔焦,暖色薄纱光晕,精致古装妆造,背景虚化,浪漫飘逸氛围"
+ ),
+ "ancient-chinese-mythology": (
+ "中国古代神话史诗风格,上古洪荒气质,苍茫山河与云雾神光,青铜礼器与粗纻麻衣质感,"
+ "水墨青绿与矿物颜料色调,庄严神圣,史诗大场面,电影级光影,忌现代偶像剧柔光与甜宠滤镜"
+ ),
+ "japanese-youth-film": (
+ "日式青春题材胶片摄影风格,柯达胶片色调,自然阳光,浅景深,细腻颗粒,青涩真挚的日常氛围"
+ ),
+ "japanese-daily-natural": (
+ "日式生活纪录片自然光影风格,柔和自然光,低对比,真实日常场景,安静治愈,轻微胶片质感"
+ ),
+ "korean-urban-soft": "韩剧都市题材柔光风格,暖色滤镜,通透肤质,都市背景虚化,浪漫温柔灯光氛围",
+ "chinese-urban-realistic": (
+ "国产都市现实题材写实摄影风格,自然光,真实生活场景,中性色调,细节锐利,无过度美化"
+ ),
+ "wuxia-realistic-photo": (
+ "中国武侠江湖题材写实摄影风格,自然光影,真实地形与服饰质感,动态构图,江湖氛围,电影级景深"
+ ),
+ "90s-realistic-film": (
+ "1990年代写实电影风格,胶片质感,自然肤色,时代感服装与环境,柔和对比,怀旧色调"
+ ),
+ "retro-narrative-film": (
+ "复古叙事电影风格,经典电影构图,胶片色彩分级,富有故事感的场景调度,电影级布光"
+ ),
+ "american-retro-hollywood": (
+ "美式复古好莱坞黄金年代风格,高对比布光,暖调彩色或经典黑白,明星质感,华丽景深"
+ ),
+ "neon-cyberpunk-film": (
+ "霓虹赛博朋克电影风格,蓝紫霓虹灯光,雨夜反射,高对比,未来都市,烟雾与全息感光效"
+ ),
+ "90s-rural-china-film": (
+ "1990年代中国农村题材电影风格,自然光,土黄与绿色调,粗糙真实质感,乡土生活氛围"
+ ),
+ "tezuka-era-cartoon": "手冢治虫时代经典日式卡通画风,简洁线条,复古动画平涂着色,怀旧动画质感",
+ "shanghai-animation": (
+ "上海美术电影制片厂经典动画画风,中国民族绘画韵味,水彩与工笔结合,诗意唯美,传统色彩"
+ ),
+ "pixel-art": "像素艺术风格,清晰像素块,复古游戏美学,有限色板,8-bit 或 16-bit 质感",
+ "shadow-puppet-illustration": (
+ "中国皮影戏插画画风,剪影轮廓,镂空纹理,暖色背光,民间艺术装饰性,层叠投影效果"
+ ),
+}
+
+# IMAGE_STYLE_LABELS 风格展示名
+IMAGE_STYLE_LABELS: dict[str, str] = {
+ "retro-sci-fi-atompunk": "复古科幻原子朋克",
+ "palace-intrigue-cold": "宫斗权谋冷峻",
+ "domestic-suspense-cold": "国产悬疑冷调",
+ "ancient-romance-soft": "古偶唯美柔光",
+ "ancient-chinese-mythology": "中国古代神话史诗",
+ "japanese-youth-film": "日式青春胶片",
+ "japanese-daily-natural": "日式生活自然",
+ "korean-urban-soft": "韩剧都市柔光",
+ "chinese-urban-realistic": "国产都市写实",
+ "wuxia-realistic-photo": "武侠江湖写实摄影",
+ "90s-realistic-film": "90年代写实电影",
+ "retro-narrative-film": "复古叙事电影",
+ "american-retro-hollywood": "美式复古好莱坞",
+ "neon-cyberpunk-film": "霓虹赛博电影",
+ "90s-rural-china-film": "90年代中国农村电影",
+ "tezuka-era-cartoon": "手冢治虫时代卡通画风",
+ "shanghai-animation": "上美画风",
+ "pixel-art": "像素风",
+ "shadow-puppet-illustration": "皮影戏插画",
+}
+
+
+# 根据风格 ID 返回展示名称
+def get_image_style_label(style_id: str) -> str:
+ return IMAGE_STYLE_LABELS.get(style_id, style_id)
+
+
+# 根据风格 ID 返回生图提示词片段,无效 ID 返回空字符串
+def resolve_image_style_prompt(style_id: str | None = None) -> str:
+ if not style_id:
+ return ""
+ return IMAGE_STYLE_PROMPTS.get(style_id, "")
diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.py
new file mode 100644
index 0000000..9d9aa2b
--- /dev/null
+++ b/backend/app/services/drama/jobs.py
@@ -0,0 +1,542 @@
+"""Drama long-running jobs: Celery dispatch + in-process fallback."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import Any
+
+from sqlalchemy.orm import selectinload
+
+from app.config import get_settings
+from app.database import AsyncSessionLocal
+from app.models import User
+from app.models_drama import (
+ DramaAsset,
+ DramaEpisode,
+ DramaEpisodeFragment,
+ DramaFragmentAssetRef,
+ DramaProject,
+)
+from app.services.billing import record_usage
+from app.services.drama.agents import (
+ count_completed_episodes,
+ ensure_episode_outline,
+ format_summary_text,
+ merge_episode_bodies,
+ resolve_episode_target,
+ run_episode_script_batch,
+ run_script_summary,
+)
+from app.services.drama.generation import generate_asset_image, generate_fragment_video
+
+logger = logging.getLogger(__name__)
+
+# in-process fallback handles
+_running: dict[str, asyncio.Task] = {}
+
+
+def _redis_ok() -> bool:
+ try:
+ import redis
+
+ r = redis.Redis.from_url(get_settings().redis_url, socket_connect_timeout=0.4)
+ r.ping()
+ return True
+ except Exception: # noqa: BLE001
+ return False
+
+
+def _use_celery() -> bool:
+ return bool(get_settings().use_celery) and _redis_ok()
+
+
+def _job_key(kind: str, entity_id: int) -> str:
+ return f"{kind}:{entity_id}"
+
+
+# ---------- script summary ----------
+
+
+def dispatch_script_summary_job(project_id: int) -> str:
+ """Enqueue script summary; returns celery / in-process id.
+
+ Caller should mark summary_status=generating before calling.
+ """
+ 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")
+ logger.info("dispatch 剧本摘要 → Celery project_id=%s task_id=%s", project_id, result.id)
+ return str(result.id)
+
+ key = _job_key("summary", project_id)
+ if key in _running and not _running[key].done():
+ logger.info("dispatch 剧本摘要 → 进程内已在跑 project_id=%s", project_id)
+ return "in-process"
+ _running[key] = asyncio.create_task(run_script_summary_job(project_id))
+ logger.info("dispatch 剧本摘要 → 进程内新建 project_id=%s", project_id)
+ return "in-process"
+
+
+async def run_script_summary_job(project_id: int) -> dict[str, Any]:
+ # Worker:生成剧本摘要并写库
+ logger.info("开始生成剧本摘要 project_id=%s", project_id)
+ async with AsyncSessionLocal() as db:
+ project = await db.get(
+ DramaProject,
+ project_id,
+ options=[selectinload(DramaProject.script)],
+ )
+ if not project or not project.script:
+ logger.warning("剧本摘要失败:缺少剧本 project_id=%s", project_id)
+ return {"ok": False, "error": "missing_script"}
+ script = project.script
+ creative = (script.source or "").strip()
+ episode_count = (project.params or {}).get("episode_count")
+ image_style_id = (project.params or {}).get("image_style_id")
+ try:
+ summary = await run_script_summary(
+ creative,
+ episode_count=int(episode_count) if episode_count else None,
+ image_style_id=str(image_style_id) if image_style_id else None,
+ )
+ except Exception as exc: # noqa: BLE001
+ params = dict(script.params or {})
+ params["summary_status"] = "failed"
+ params["summary_error"] = str(exc)[:500]
+ script.params = params
+ await db.commit()
+ logger.exception("剧本摘要失败 project_id=%s err=%s", project_id, exc)
+ return {"ok": False, "error": str(exc)[:500]}
+
+ script.summary = summary
+ params = dict(script.params or {})
+ params["summary_text"] = format_summary_text(summary)
+ params["summary_status"] = "completed"
+ params["summary_error"] = None
+ params["episode_content_status"] = params.get("episode_content_status") or "pending"
+ script.params = params
+ one_line = str(summary.get("oneLineStory") or "").strip()
+ if one_line:
+ project.description = one_line[:500]
+ if len(project.title) > 36 or project.title.startswith(creative[:20]):
+ project.title = one_line[:40] + ("…" if len(one_line) > 40 else "")
+ script.name = project.title
+ user = await db.get(User, project.user_id)
+ if user:
+ await record_usage(
+ db,
+ user_id=user.id,
+ project_id=None,
+ drama_project_id=project.id,
+ billing_key="llm_chat",
+ model=get_settings().model_llm,
+ estimated=True,
+ )
+ await db.commit()
+ logger.info(
+ "剧本摘要完成 project_id=%s episode_count=%s one_line=%s",
+ project_id,
+ summary.get("episodeCount"),
+ (one_line[:40] + "…") if len(one_line) > 40 else one_line,
+ )
+ return {"ok": True, "project_id": project_id}
+
+
+# ---------- episode scripts ----------
+
+
+def dispatch_episode_scripts_job(project_id: int, force: bool = False) -> str:
+ """Enqueue full episode-script generation for a project.
+
+ Caller should mark episode_content_status=generating before calling.
+ """
+ if _use_celery():
+ from app.workers.drama_tasks import drama_episode_scripts_task
+
+ result = drama_episode_scripts_task.apply_async(
+ args=[project_id, force],
+ queue="pipeline",
+ )
+ logger.info(
+ "dispatch 分集剧本 → Celery project_id=%s force=%s task_id=%s",
+ project_id,
+ force,
+ result.id,
+ )
+ return str(result.id)
+
+ key = _job_key("episodes", project_id)
+ if key in _running and not _running[key].done():
+ logger.info("dispatch 分集剧本 → 进程内已在跑 project_id=%s", project_id)
+ return "in-process"
+ _running[key] = asyncio.create_task(run_episode_scripts_job(project_id, force=force))
+ logger.info("dispatch 分集剧本 → 进程内新建 project_id=%s force=%s", project_id, force)
+ return "in-process"
+
+
+async def run_episode_scripts_job(project_id: int, force: bool = False) -> dict[str, Any]:
+ # Worker:大纲 + 循环逐集直到完成
+ logger.info("开始生成分集剧本 project_id=%s force=%s", project_id, force)
+ async with AsyncSessionLocal() as db:
+ project = await db.get(
+ DramaProject,
+ project_id,
+ options=[selectinload(DramaProject.script)],
+ )
+ if not project or not project.script or not project.script.summary:
+ logger.warning("分集剧本失败:缺少摘要 project_id=%s", project_id)
+ return {"ok": False, "error": "missing_summary"}
+
+ script = project.script
+ summary = script.summary if isinstance(script.summary, dict) else {}
+ existing: list = []
+ content = script.episode_content
+ if isinstance(content, dict) and isinstance(content.get("episodes"), list):
+ existing = list(content["episodes"])
+ elif isinstance(content, list):
+ existing = list(content)
+
+ total = resolve_episode_target(summary, project.params, script.params)
+ if summary.get("episodeCount") != total:
+ summary = {**summary, "episodeCount": total}
+ script.summary = summary
+
+ creative = (script.source or "").strip()
+ try:
+ if force and existing:
+ existing = [
+ {
+ "episodeNumber": int(item.get("episodeNumber") or 0),
+ "title": str(item.get("title") or f"第 {item.get('episodeNumber')} 集"),
+ "body": "",
+ }
+ for item in existing
+ if isinstance(item, dict) and int(item.get("episodeNumber") or 0) >= 1
+ ]
+ script.episode_content = {"episodes": existing}
+ await db.flush()
+ logger.info("已清空分集正文准备重写 project_id=%s total=%s", project_id, total)
+
+ existing = await ensure_episode_outline(creative, summary, existing, total)
+ script.episode_content = {"episodes": existing}
+ await db.flush()
+ logger.info("分集大纲就绪 project_id=%s titles=%s", project_id, len(existing))
+
+ guard = 0
+ while True:
+ generated = count_completed_episodes(existing, total)
+ if generated >= total:
+ break
+ logger.info(
+ "生成下一集 project_id=%s progress=%s/%s",
+ project_id,
+ generated,
+ total,
+ )
+ batch = await run_episode_script_batch(
+ summary,
+ existing,
+ batch_size=1,
+ total=total,
+ creative=creative,
+ )
+ existing = merge_episode_bodies(existing, batch)
+ script.episode_content = {"episodes": existing}
+ params = dict(script.params or {})
+ params["episode_content_status"] = "generating"
+ params["episode_count"] = total
+ params["episode_content_progress"] = {
+ "done": count_completed_episodes(existing, total),
+ "total": total,
+ }
+ script.params = params
+ await db.commit()
+ await db.refresh(script)
+ content = script.episode_content
+ if isinstance(content, dict) and isinstance(content.get("episodes"), list):
+ existing = list(content["episodes"])
+ done_now = count_completed_episodes(existing, total)
+ logger.info(
+ "分集进度更新 project_id=%s progress=%s/%s",
+ project_id,
+ done_now,
+ total,
+ )
+ guard += 1
+ if guard > max(total * 2, 24):
+ raise RuntimeError(
+ f"分集生成未完成({count_completed_episodes(existing, total)}/{total})"
+ )
+ if not batch:
+ raise RuntimeError("分集生成无进度")
+
+ params = dict(script.params or {})
+ params["episode_content_status"] = "completed"
+ params["episode_content_error"] = None
+ params["episode_count"] = total
+ params["episode_content_progress"] = {"done": total, "total": total}
+ script.params = params
+ user = await db.get(User, project.user_id)
+ if user:
+ await record_usage(
+ db,
+ user_id=user.id,
+ project_id=None,
+ drama_project_id=project.id,
+ billing_key="llm_chat",
+ model=get_settings().model_llm,
+ estimated=True,
+ )
+ await db.commit()
+ logger.info("分集剧本全部完成 project_id=%s total=%s", project_id, total)
+ return {"ok": True, "project_id": project_id, "total": total}
+ except Exception as exc: # noqa: BLE001
+ params = dict(script.params or {})
+ params["episode_content_status"] = "failed"
+ params["episode_content_error"] = str(exc)[:500]
+ script.params = params
+ await db.commit()
+ logger.exception("分集剧本失败 project_id=%s err=%s", project_id, exc)
+ return {"ok": False, "error": str(exc)[:500]}
+
+
+# ---------- episode video ----------
+
+
+def dispatch_episode_generate_job(
+ episode_id: int,
+ user_id: int,
+ fragment_ids: list[int],
+) -> str:
+ if _use_celery():
+ from app.workers.drama_tasks import drama_episode_generate_task
+
+ result = drama_episode_generate_task.apply_async(
+ args=[episode_id, user_id, fragment_ids],
+ queue="pipeline",
+ )
+ logger.info(
+ "dispatch 分集视频 → Celery episode_id=%s fragments=%s task_id=%s",
+ episode_id,
+ len(fragment_ids),
+ result.id,
+ )
+ return str(result.id)
+
+ key = _job_key("epgen", episode_id)
+ if key in _running and not _running[key].done():
+ logger.info("dispatch 分集视频 → 进程内已在跑 episode_id=%s", episode_id)
+ return "in-process"
+ _running[key] = asyncio.create_task(
+ run_episode_generate_job(episode_id, user_id, fragment_ids)
+ )
+ logger.info(
+ "dispatch 分集视频 → 进程内新建 episode_id=%s fragments=%s",
+ episode_id,
+ len(fragment_ids),
+ )
+ return "in-process"
+
+
+async def run_episode_generate_job(
+ episode_id: int,
+ user_id: int,
+ fragment_ids: list[int],
+) -> dict[str, Any]:
+ logger.info(
+ "开始生成分集视频 episode_id=%s fragments=%s",
+ episode_id,
+ len(fragment_ids),
+ )
+ async with AsyncSessionLocal() as db:
+ ep = await db.get(
+ DramaEpisode,
+ episode_id,
+ options=[selectinload(DramaEpisode.project)],
+ )
+ if not ep:
+ logger.warning("分集视频失败:分集不存在 episode_id=%s", episode_id)
+ return {"ok": False, "error": "missing_episode"}
+ project = ep.project
+ user = await db.get(User, user_id)
+ if not project or not user:
+ return {"ok": False, "error": "missing_project_or_user"}
+
+ ok_count = 0
+ fail_count = 0
+ for fid in fragment_ids:
+ frag = await db.get(
+ DramaEpisodeFragment,
+ fid,
+ options=[
+ selectinload(DramaEpisodeFragment.asset_references).selectinload(
+ DramaFragmentAssetRef.asset
+ )
+ ],
+ )
+ if not frag or frag.episode_id != episode_id:
+ continue
+ try:
+ logger.info("生成分镜视频 fragment_id=%s episode_id=%s", fid, episode_id)
+ await generate_fragment_video(db, user, project, frag)
+ ok_count += 1
+ except Exception: # noqa: BLE001
+ fail_count += 1
+ logger.exception("分镜视频失败 fragment_id=%s", fid)
+ continue
+ logger.info(
+ "分集视频结束 episode_id=%s ok=%s fail=%s",
+ episode_id,
+ ok_count,
+ fail_count,
+ )
+ return {"ok": True, "episode_id": episode_id}
+
+
+# ---------- asset image ----------
+
+
+def dispatch_asset_image_job(
+ project_id: int,
+ user_id: int,
+ prompt: str,
+ asset_id: int | None = None,
+ name: str | None = None,
+ kind: str = "character",
+ *,
+ image_style_id: str | None = None,
+ model_id: str | None = None,
+ aspect_ratio: str | None = None,
+ resolution: str | None = None,
+) -> str:
+ """Enqueue asset image generation. Caller marks asset generating when possible."""
+ if _use_celery():
+ from app.workers.drama_tasks import drama_asset_image_task
+
+ result = drama_asset_image_task.apply_async(
+ kwargs={
+ "project_id": project_id,
+ "user_id": user_id,
+ "prompt": prompt,
+ "asset_id": asset_id,
+ "name": name,
+ "kind": kind,
+ "image_style_id": image_style_id,
+ "model_id": model_id,
+ "aspect_ratio": aspect_ratio,
+ "resolution": resolution,
+ },
+ queue="pipeline",
+ )
+ logger.info(
+ "dispatch 资产生图 → Celery project_id=%s asset_id=%s kind=%s task_id=%s",
+ project_id,
+ asset_id,
+ kind,
+ result.id,
+ )
+ return str(result.id)
+
+ key = _job_key("img", asset_id or project_id)
+ if key in _running and not _running[key].done():
+ logger.info("dispatch 资产生图 → 进程内已在跑 asset_id=%s", asset_id)
+ return "in-process"
+ _running[key] = asyncio.create_task(
+ run_asset_image_job(
+ project_id,
+ user_id,
+ prompt,
+ asset_id,
+ name,
+ kind,
+ image_style_id=image_style_id,
+ model_id=model_id,
+ aspect_ratio=aspect_ratio,
+ resolution=resolution,
+ )
+ )
+ logger.info(
+ "dispatch 资产生图 → 进程内新建 project_id=%s asset_id=%s kind=%s",
+ project_id,
+ asset_id,
+ kind,
+ )
+ return "in-process"
+
+
+async def run_asset_image_job(
+ project_id: int,
+ user_id: int,
+ prompt: str,
+ asset_id: int | None = None,
+ name: str | None = None,
+ kind: str = "character",
+ *,
+ image_style_id: str | None = None,
+ model_id: str | None = None,
+ aspect_ratio: str | None = None,
+ resolution: str | None = None,
+) -> dict[str, Any]:
+ logger.info(
+ "开始资产生图 project_id=%s asset_id=%s kind=%s name=%s style=%s model=%s",
+ project_id,
+ asset_id,
+ kind,
+ name,
+ image_style_id,
+ model_id,
+ )
+ async with AsyncSessionLocal() as db:
+ project = await db.get(DramaProject, project_id)
+ user = await db.get(User, user_id)
+ if not project or not user:
+ return {"ok": False, "error": "missing"}
+ asset = None
+ if asset_id:
+ asset = await db.get(DramaAsset, asset_id)
+ if not asset or asset.project_id != project_id:
+ return {"ok": False, "error": "asset_not_found"}
+ try:
+ asset = await generate_asset_image(
+ db,
+ user,
+ project,
+ prompt,
+ asset=asset,
+ name=name,
+ kind=kind,
+ image_style_id=image_style_id,
+ model_id=model_id,
+ aspect_ratio=aspect_ratio,
+ resolution=resolution,
+ )
+ params = dict(asset.params or {})
+ gen = dict(params.get("generation") or {})
+ gen["status"] = "done"
+ params["generation"] = gen
+ asset.params = params
+ await db.commit()
+ logger.info(
+ "资产生图完成 project_id=%s asset_id=%s url=%s",
+ project_id,
+ asset.id,
+ (asset.url or asset.cover or "")[:80],
+ )
+ return {"ok": True, "asset_id": asset.id}
+ except Exception as exc: # noqa: BLE001
+ if asset_id:
+ asset = await db.get(DramaAsset, asset_id)
+ if asset:
+ params = dict(asset.params or {})
+ params["generation"] = {"status": "failed", "error": str(exc)[:400]}
+ asset.params = params
+ await db.commit()
+ logger.exception(
+ "资产生图失败 project_id=%s asset_id=%s err=%s",
+ project_id,
+ asset_id,
+ exc,
+ )
+ return {"ok": False, "error": str(exc)[:500]}
diff --git a/backend/app/services/drama/llm.py b/backend/app/services/drama/llm.py
new file mode 100644
index 0000000..dcd57f3
--- /dev/null
+++ b/backend/app/services/drama/llm.py
@@ -0,0 +1,105 @@
+"""Drama LLM helpers via Ark chat/completions."""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+from typing import Any
+
+import httpx
+
+from app.config import get_settings
+from app.services.ark import get_ark
+
+logger = logging.getLogger(__name__)
+
+
+def _extract_json(text: str) -> Any:
+ # Parse JSON object/array from model output (strip fences if present)
+ 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))
+
+
+async def drama_chat_json(
+ system: str,
+ user: str,
+ *,
+ temperature: float = 0.6,
+ max_tokens: int = 32768,
+) -> Any:
+ """Call Ark LLM and parse JSON from the reply."""
+ settings = get_settings()
+ ark = get_ark()
+ if ark.mock:
+ logger.info("LLM JSON(mock)")
+ return {"mock": True, "note": "ARK_MOCK=true"}
+
+ logger.info(
+ "调用 LLM JSON model=%s user_len=%s max_tokens=%s",
+ settings.model_llm,
+ len(user or ""),
+ max_tokens,
+ )
+ payload: dict[str, Any] = {
+ "model": settings.model_llm,
+ "temperature": temperature,
+ "max_tokens": max_tokens,
+ "messages": [
+ {"role": "system", "content": system},
+ {"role": "user", "content": user},
+ ],
+ }
+ async with httpx.AsyncClient(timeout=300.0) as client:
+ res = await client.post(
+ ark._url("/chat/completions"),
+ headers={"Authorization": f"Bearer {settings.ark_api_key}"},
+ json=payload,
+ )
+ res.raise_for_status()
+ data = res.json()
+ content = data["choices"][0]["message"]["content"]
+ logger.info("LLM JSON 返回 content_len=%s", len(content or ""))
+ return _extract_json(content)
+
+
+async def drama_chat_text(
+ system: str,
+ user: str,
+ *,
+ temperature: float = 0.7,
+ max_tokens: int = 8192,
+) -> str:
+ """Call Ark LLM and return plain text."""
+ settings = get_settings()
+ ark = get_ark()
+ if ark.mock:
+ return f"[mock] {user[:200]}"
+
+ payload: dict[str, Any] = {
+ "model": settings.model_llm,
+ "temperature": temperature,
+ "max_tokens": max_tokens,
+ "messages": [
+ {"role": "system", "content": system},
+ {"role": "user", "content": user},
+ ],
+ }
+ async with httpx.AsyncClient(timeout=180.0) as client:
+ res = await client.post(
+ ark._url("/chat/completions"),
+ headers={"Authorization": f"Bearer {settings.ark_api_key}"},
+ json=payload,
+ )
+ res.raise_for_status()
+ data = res.json()
+ return str(data["choices"][0]["message"]["content"] or "")
diff --git a/backend/app/services/drama/seed.py b/backend/app/services/drama/seed.py
new file mode 100644
index 0000000..f1f22f0
--- /dev/null
+++ b/backend/app/services/drama/seed.py
@@ -0,0 +1,284 @@
+"""Seed drama assets / episodes from script."""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import selectinload
+
+from app.models_drama import (
+ DramaAsset,
+ DramaEpisode,
+ DramaEpisodeFragment,
+ DramaFragmentAssetRef,
+ DramaProject,
+)
+from app.services.drama.build_fragments import (
+ build_fragments_from_episode_body,
+ is_raw_screenplay_fragment,
+ split_episode_content_into_scenes,
+)
+
+
+async def seed_assets_from_script(db: AsyncSession, project: DramaProject) -> list[DramaAsset]:
+ # Create character/scene assets from script summary if missing
+ script = project.script
+ if not script or not script.summary:
+ raise ValueError("请先生成剧本摘要")
+
+ summary = script.summary if isinstance(script.summary, dict) else {}
+ existing = (
+ await db.execute(select(DramaAsset).where(DramaAsset.project_id == project.id))
+ ).scalars().all()
+ existing_names = {(a.name or "").strip() for a in existing if a.type in {"character", "scene"}}
+
+ created: list[DramaAsset] = []
+ for ch in summary.get("characters") or []:
+ if not isinstance(ch, dict):
+ continue
+ name = str(ch.get("name") or "").strip()
+ if not name or name in existing_names:
+ continue
+ asset = DramaAsset(
+ project_id=project.id,
+ type="character",
+ asset_type="image",
+ name=name,
+ params={
+ "visualImage": ch.get("visualImage"),
+ "roleType": ch.get("roleType"),
+ "title": ch.get("title"),
+ "coreTags": ch.get("coreTags"),
+ },
+ )
+ db.add(asset)
+ created.append(asset)
+ existing_names.add(name)
+
+ # Extract scene names from episode bodies
+ bodies = _episode_bodies(script.episode_content)
+ scene_names: list[str] = []
+ for body in bodies:
+ for m in re.finditer(
+ r"^(?:日|夜|晨|黄昏|傍晚|凌晨|清晨|午|晚)?[ \t]*(?:内|外|内外)[ \t]+(.+)$",
+ body,
+ re.M,
+ ):
+ scene = m.group(1).strip().split("/")[0].split("/")[0].strip()
+ if scene and scene not in scene_names:
+ scene_names.append(scene)
+
+ for scene in scene_names[:40]:
+ if scene in existing_names:
+ continue
+ asset = DramaAsset(
+ project_id=project.id,
+ type="scene",
+ asset_type="image",
+ name=scene,
+ params={"kind": "scene"},
+ )
+ db.add(asset)
+ created.append(asset)
+ existing_names.add(scene)
+
+ await db.commit()
+ for a in created:
+ await db.refresh(a)
+ return created
+
+
+async def seed_episodes_from_script(
+ db: AsyncSession,
+ project: DramaProject,
+ *,
+ force: bool = False,
+) -> list[DramaEpisode]:
+ # Create / 重切分镜:按 ### 场次拆分并生成视频向分镜文案
+ script = project.script
+ if not script:
+ raise ValueError("缺少剧本")
+ bodies = _normalize_episode_list(script.episode_content)
+ if not bodies:
+ raise ValueError("请先生成分集剧本")
+
+ assets = list(
+ (
+ await db.execute(select(DramaAsset).where(DramaAsset.project_id == project.id))
+ ).scalars().all()
+ )
+
+ existing = list(
+ (
+ await db.execute(
+ select(DramaEpisode)
+ .where(DramaEpisode.project_id == project.id)
+ .options(
+ selectinload(DramaEpisode.fragments).selectinload(
+ DramaEpisodeFragment.asset_references
+ )
+ )
+ .order_by(DramaEpisode.id.asc())
+ )
+ ).scalars().all()
+ )
+
+ should_rebuild = force or _should_auto_replan(existing, bodies)
+ if existing and not should_rebuild:
+ return existing
+
+ body_by_number = {
+ int(item.get("episodeNumber") or 0): item
+ for item in bodies
+ if isinstance(item, dict) and int(item.get("episodeNumber") or 0) >= 1
+ }
+
+ if not existing:
+ created: list[DramaEpisode] = []
+ for item in bodies:
+ ep_no = int(item.get("episodeNumber") or len(created) + 1)
+ title = str(item.get("title") or f"第{ep_no}集")
+ body = str(item.get("body") or item.get("content") or "")
+ episode = DramaEpisode(
+ project_id=project.id,
+ name=title,
+ params={"episodeNumber": ep_no},
+ )
+ db.add(episode)
+ await db.flush()
+ await _replace_episode_fragments(db, episode, body, assets)
+ created.append(episode)
+ await db.commit()
+ return await _reload_episodes(db, project.id)
+
+ # 已有分集:按集号同步名称与分镜(已生成视频的分镜默认保留,除非 force)
+ for episode in existing:
+ params = episode.params if isinstance(episode.params, dict) else {}
+ ep_no = int(params.get("episodeNumber") or 0)
+ item = body_by_number.get(ep_no)
+ if item is None:
+ continue
+ title = str(item.get("title") or episode.name)
+ body = str(item.get("body") or item.get("content") or "")
+ episode.name = title
+ has_video = any((f.video or "").strip() for f in (episode.fragments or []))
+ if force or not has_video or _episode_needs_replan(episode):
+ await _replace_episode_fragments(db, episode, body, assets)
+
+ # 补建剧本里有、库中没有的集
+ existing_numbers = {
+ int((ep.params or {}).get("episodeNumber") or 0)
+ for ep in existing
+ if isinstance(ep.params, dict)
+ }
+ for ep_no, item in sorted(body_by_number.items()):
+ if ep_no in existing_numbers:
+ continue
+ title = str(item.get("title") or f"第{ep_no}集")
+ body = str(item.get("body") or item.get("content") or "")
+ episode = DramaEpisode(
+ project_id=project.id,
+ name=title,
+ params={"episodeNumber": ep_no},
+ )
+ db.add(episode)
+ await db.flush()
+ await _replace_episode_fragments(db, episode, body, assets)
+
+ await db.commit()
+ return await _reload_episodes(db, project.id)
+
+
+async def _replace_episode_fragments(
+ db: AsyncSession,
+ episode: DramaEpisode,
+ body: str,
+ assets: list[DramaAsset],
+) -> None:
+ # 删除旧分镜并按场次重建
+ for old in list(episode.fragments or []):
+ await db.delete(old)
+ await db.flush()
+
+ drafts = build_fragments_from_episode_body(body, assets)
+ for i, frag in enumerate(drafts):
+ row = DramaEpisodeFragment(
+ episode_id=episode.id,
+ sort_order=i,
+ content=str(frag.get("content") or ""),
+ duration_sec=int(frag.get("duration_sec") or 8),
+ params={
+ "sceneName": frag.get("scene_name"),
+ "characterNames": frag.get("character_names") or [],
+ },
+ )
+ db.add(row)
+ await db.flush()
+ for asset_id in frag.get("asset_ids") or []:
+ db.add(DramaFragmentAssetRef(fragment_id=row.id, asset_id=int(asset_id)))
+
+
+def _should_auto_replan(existing: list[DramaEpisode], bodies: list[dict[str, Any]]) -> bool:
+ # 无分集、分镜为空、仍是场记原文、场次数与正文不符、或剧本集数更多时自动重切
+ if not existing:
+ return True
+ if any(_episode_needs_replan(ep) for ep in existing):
+ return True
+ body_by_number = {
+ int(item.get("episodeNumber") or 0): item
+ for item in bodies
+ if isinstance(item, dict) and int(item.get("episodeNumber") or 0) >= 1
+ }
+ for episode in existing:
+ params = episode.params if isinstance(episode.params, dict) else {}
+ ep_no = int(params.get("episodeNumber") or 0)
+ item = body_by_number.get(ep_no)
+ if not item:
+ continue
+ script_body = str(item.get("body") or item.get("content") or "")
+ scene_count = len(split_episode_content_into_scenes(script_body))
+ frag_count = len(episode.fragments or [])
+ if scene_count > 0 and frag_count != scene_count:
+ return True
+ if len(bodies) > len(existing):
+ return True
+ return False
+
+
+def _episode_needs_replan(episode: DramaEpisode) -> bool:
+ frags = list(episode.fragments or [])
+ if not frags:
+ return True
+ if any(is_raw_screenplay_fragment(f.content or "") for f in frags):
+ return True
+ return False
+
+
+async def _reload_episodes(db: AsyncSession, project_id: int) -> list[DramaEpisode]:
+ result = await db.execute(
+ select(DramaEpisode)
+ .where(DramaEpisode.project_id == project_id)
+ .options(
+ selectinload(DramaEpisode.fragments).selectinload(
+ DramaEpisodeFragment.asset_references
+ )
+ )
+ .order_by(DramaEpisode.id.asc())
+ )
+ return list(result.scalars().all())
+
+
+def _episode_bodies(episode_content: Any) -> list[str]:
+ items = _normalize_episode_list(episode_content)
+ return [str(x.get("body") or x.get("content") or "") for x in items]
+
+
+def _normalize_episode_list(episode_content: Any) -> list[dict[str, Any]]:
+ if isinstance(episode_content, dict) and isinstance(episode_content.get("episodes"), list):
+ return [x for x in episode_content["episodes"] if isinstance(x, dict)]
+ if isinstance(episode_content, list):
+ return [x for x in episode_content if isinstance(x, dict)]
+ return []
diff --git a/backend/app/services/drama/seedream_options.py b/backend/app/services/drama/seedream_options.py
new file mode 100644
index 0000000..130826b
--- /dev/null
+++ b/backend/app/services/drama/seedream_options.py
@@ -0,0 +1,61 @@
+"""Seedream 前端选项 → 方舟 model / size 解析。"""
+
+from __future__ import annotations
+
+from app.config import get_settings
+
+# SeedreamAspectRatio 支持的比例
+SeedreamAspectRatio = str
+# SeedreamResolution 清晰度
+SeedreamResolution = str
+
+# SEEDREAM_SIZE_MAP 清晰度 + 比例 → Ark size
+SEEDREAM_SIZE_MAP: dict[str, dict[str, str]] = {
+ "3K": {
+ "auto": "3K",
+ "1:1": "3072x3072",
+ "16:9": "4096x2304",
+ "21:9": "4704x2016",
+ "9:16": "2304x4096",
+ "4:3": "3456x2592",
+ "3:4": "2592x3456",
+ },
+ "4K": {
+ "auto": "4K",
+ "1:1": "4096x4096",
+ "16:9": "5404x3040",
+ "21:9": "6198x2656",
+ "9:16": "3040x5404",
+ "4:3": "4694x3520",
+ "3:4": "3520x4694",
+ },
+}
+
+
+# 将前端模型 ID 解析为方舟推理接入点
+def resolve_seedream_model_endpoint(model_id: str | None) -> str:
+ settings = get_settings()
+ mid = (model_id or "").strip().lower()
+ if mid in {"", "seedream-5.0", "seedream-5", "5.0"}:
+ return settings.model_image
+ if mid in {"seedream-4.5", "seedream-4", "4.5"}:
+ return (settings.model_image_45 or "").strip() or settings.model_image
+ # 已是 endpoint / 其它模型名则原样使用
+ return model_id or settings.model_image
+
+
+# 将清晰度 + 比例解析为 Ark size 参数
+def resolve_seedream_size(
+ *,
+ aspect_ratio: str | None = None,
+ resolution: str | None = None,
+) -> str:
+ settings = get_settings()
+ res = (resolution or "3K").strip().upper()
+ if res not in SEEDREAM_SIZE_MAP:
+ res = "3K"
+ ratio = (aspect_ratio or "3:4").strip() or "3:4"
+ mapped = SEEDREAM_SIZE_MAP[res].get(ratio)
+ if mapped:
+ return mapped
+ return settings.ark_image_size or "2k"
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.py
index b10a401..6144342 100644
--- a/backend/app/services/pipeline.py
+++ b/backend/app/services/pipeline.py
@@ -1407,6 +1407,10 @@ async def _compose_stage(project_id: int) -> None:
project.progress = 100
await db.commit()
await _settle_billing(project_id)
+
+
+async def regen_shot_image(project_id: int, shot_id: int) -> None:
+ """重绘单镜首帧图,并清掉该镜视频以便后续重生。"""
ark = get_ark()
async with AsyncSessionLocal() as db:
result = await db.execute(
diff --git a/backend/app/services/seedance_segments.py b/backend/app/services/seedance_segments.py
index 63caa24..91bccd2 100644
--- a/backend/app/services/seedance_segments.py
+++ b/backend/app/services/seedance_segments.py
@@ -19,6 +19,7 @@ DURATION_TOKEN_RE = re.compile(r"@duration:(\d+)")
NARRATION_PREFIX = "【旁白·慢速清晰·同步字幕】"
SUBTITLE_CUE = "【字幕:全程简体中文字幕,旁白逐句同步烧录】"
DEFAULT_BGM_MOOD = "贴合内容的轻量配乐,情绪平稳,不抢旁白"
+SEEDANCE_PRODUCTION_SECTION_HEADER = "【强制约束:音频、字幕与配乐】"
BGM_MOOD_KEYWORDS: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"紧张|危机|压迫|悬疑"), "低沉紧张、鼓点渐强,烘托压迫感,音量低于人声"),
@@ -84,6 +85,62 @@ def build_production_cues(bgm_mood: str) -> list[str]:
return [SUBTITLE_CUE, f"【BGM:{mood}】"]
+def script_has_narration_cue(content: str) -> bool:
+ """检测脚本是否含旁白 cue / 旁白前缀。"""
+ for raw in (content or "").replace("\r\n", "\n").split("\n"):
+ line = raw.strip()
+ if not line or line.startswith("@duration:"):
+ continue
+ if NARRATION_PREFIX in line or line.startswith("【旁白"):
+ return True
+ if "旁白" in line[:24]:
+ return True
+ return False
+
+
+def build_seedance_production_section(segment_script: str) -> str:
+ """组装科普版 Seedance 音频/字幕/BGM 强制约束(对齐漫剧子集,无人物介绍/@asset)。"""
+ # has_vo 脚本是否含旁白
+ has_vo = script_has_narration_cue(segment_script)
+ # bgm_mood 从脚本 BGM cue 或正文推断
+ bgm_mood = DEFAULT_BGM_MOOD
+ for raw in (segment_script or "").replace("\r\n", "\n").split("\n"):
+ line = raw.strip()
+ if line.startswith("【BGM:"):
+ mood = line.removeprefix("【BGM:").removesuffix("】").strip()
+ if mood:
+ bgm_mood = mood
+ break
+ else:
+ bgm_mood = infer_bgm_mood(segment_script)
+
+ if "音量低于人声" not in bgm_mood:
+ bgm_mood = f"{bgm_mood},音量低于人声"
+
+ # lines 约束条目
+ lines = [
+ "1. 语速:旁白语速自然偏慢,吐字清晰,留有呼吸与停顿;严禁加速赶词、压缩台词或提高播放倍速。",
+ "2. 字幕:全程烧录简体中文字幕,位置底部居中,字号清晰可读;旁白须逐句同步显示,字幕与口播一致。",
+ ]
+ if has_vo:
+ lines.append(
+ "3. 旁白:脚本含旁白段落时以第三人称旁白配音,沉稳清晰、语速偏慢;"
+ "视频内不要自行添加嘈杂对白;旁白出现时字幕同步显示全文。"
+ )
+ else:
+ lines.append(
+ "3. 旁白:若脚本含旁白标记,按第三人称旁白慢速清晰配音,并同步烧录字幕;"
+ "视频内不要自行添加嘈杂对白。"
+ )
+ lines.append(
+ f"4. 背景音乐:{bgm_mood};BGM 音量低于人声约 30%,不得盖过旁白与关键音效。"
+ )
+ lines.append(
+ "5. 音效:环境音与动作音效与画面同步,层次低于人声。"
+ )
+ return f"{SEEDANCE_PRODUCTION_SECTION_HEADER}\n" + "\n".join(lines)
+
+
def format_segment_line(kind: str, text: str) -> str:
clean = (text or "").strip()
if not clean:
@@ -217,9 +274,14 @@ def parse_beats_from_llm_shot(item: dict[str, Any], narration_fallback: str = ""
raw_dur = seg.get("duration")
if kind in {"narration", "vo", "旁白"}:
dur = int(raw_dur) if raw_dur else estimate_narration_duration(text)
+ if raw_dur:
+ # 旁白时长再按字数下限钳制,避免 LLM 给过短 duration
+ dur = max(dur, estimate_narration_duration(text))
else:
dur = int(raw_dur) if raw_dur else estimate_visual_duration(text)
- beats.append(SegmentBeat(duration=dur, kind=kind, text=text))
+ beats.append(
+ SegmentBeat(duration=clamp_segment_duration(dur), kind=kind, text=text)
+ )
return beats
img = str(item.get("img_prompt") or item.get("visual") or "").strip()
@@ -248,7 +310,7 @@ def build_seedance_prompt(
motion_bias: str = "",
camera: str = "",
) -> str:
- """Assemble final Seedance text: style lock + production note + timed body."""
+ """Assemble final Seedance text: style lock + production constraints + timed body."""
parts: list[str] = []
style = (style_prefix or "").strip()
if style:
@@ -256,9 +318,9 @@ def build_seedance_prompt(
"【强制约束:视频画面风格】全片画面必须严格遵循以下风格描述,"
f"严禁偏离或混用其他画风:{style}"
)
+ parts.append(build_seedance_production_section(segment_script))
parts.append(
- "【强制约束:节奏与叠字】严格按时间轴段落演绎画面;"
- "旁白由后期配音,视频内不要自行添加嘈杂对白;"
+ "【强制约束:节奏与画面】严格按时间轴段落演绎画面;"
"保持主体外形与首帧一致,动作自然。"
)
if motion_bias or camera:
diff --git a/backend/app/workers/autoscale.py b/backend/app/workers/autoscale.py
index 8f896b9..45ddc5f 100644
--- a/backend/app/workers/autoscale.py
+++ b/backend/app/workers/autoscale.py
@@ -24,13 +24,13 @@ from pathlib import Path
import redis
from app.config import get_settings, reload_settings
+from app.logging_setup import configure_logging
-logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s [%(levelname)s] autoscale: %(message)s",
- datefmt="%H:%M:%S",
-)
+_settings = get_settings()
+configure_logging(level="INFO", sql_echo=_settings.sql_echo)
+# autoscale 自己的格式已由 configure_logging 覆盖;保留 logger 名
logger = logging.getLogger("autoscale")
+logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
BACKEND_ROOT = Path(__file__).resolve().parents[2]
STATE_DIR = BACKEND_ROOT / ".celery_autoscale"
diff --git a/backend/app/workers/celery_app.py b/backend/app/workers/celery_app.py
index 85167a3..003a872 100644
--- a/backend/app/workers/celery_app.py
+++ b/backend/app/workers/celery_app.py
@@ -8,7 +8,7 @@ celery_app = Celery(
"framecut",
broker=settings.redis_url,
backend=settings.redis_url,
- include=["app.workers.tasks"],
+ include=["app.workers.tasks", "app.workers.drama_tasks"],
)
celery_app.conf.update(
@@ -34,5 +34,9 @@ celery_app.conf.update(
"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"},
+ "drama.episode_generate": {"queue": "pipeline"},
+ "drama.asset_image": {"queue": "pipeline"},
},
)
diff --git a/backend/app/workers/drama_tasks.py b/backend/app/workers/drama_tasks.py
new file mode 100644
index 0000000..10ce693
--- /dev/null
+++ b/backend/app/workers/drama_tasks.py
@@ -0,0 +1,110 @@
+"""Celery tasks for drama long-running jobs."""
+
+from __future__ import annotations
+
+import logging
+
+from app.config import get_settings
+from app.logging_setup import configure_logging
+from app.workers.celery_app import celery_app
+from app.workers.tasks import _run
+
+_settings = get_settings()
+configure_logging(level="INFO", sql_echo=_settings.sql_echo)
+logger = logging.getLogger("app.drama.worker")
+
+
+@celery_app.task(name="drama.script_summary", bind=True, max_retries=1)
+def drama_script_summary_task(self, project_id: int) -> dict:
+ # Celery:剧本摘要
+ from app.services.drama.jobs import run_script_summary_job
+
+ logger.info("[Celery] 领取剧本摘要任务 project_id=%s task_id=%s", project_id, self.request.id)
+ result = _run(run_script_summary_job(project_id))
+ logger.info("[Celery] 剧本摘要任务结束 project_id=%s result=%s", project_id, result)
+ return result
+
+
+@celery_app.task(name="drama.episode_scripts", bind=True, max_retries=1)
+def drama_episode_scripts_task(self, project_id: int, force: bool = False) -> dict:
+ # Celery:分集剧本(完整循环)
+ from app.services.drama.jobs import run_episode_scripts_job
+
+ logger.info(
+ "[Celery] 领取分集剧本任务 project_id=%s force=%s task_id=%s",
+ project_id,
+ force,
+ self.request.id,
+ )
+ result = _run(run_episode_scripts_job(project_id, force=force))
+ logger.info("[Celery] 分集剧本任务结束 project_id=%s result=%s", project_id, result)
+ return result
+
+
+@celery_app.task(name="drama.episode_generate", bind=True, max_retries=1)
+def drama_episode_generate_task(
+ self,
+ episode_id: int,
+ user_id: int,
+ fragment_ids: list[int],
+) -> dict:
+ # Celery:分集视频生成
+ from app.services.drama.jobs import run_episode_generate_job
+
+ logger.info(
+ "[Celery] 领取分集视频任务 episode_id=%s fragments=%s task_id=%s",
+ episode_id,
+ len(fragment_ids),
+ self.request.id,
+ )
+ result = _run(run_episode_generate_job(episode_id, user_id, fragment_ids))
+ logger.info("[Celery] 分集视频任务结束 episode_id=%s result=%s", episode_id, result)
+ return result
+
+
+@celery_app.task(name="drama.asset_image", bind=True, max_retries=1)
+def drama_asset_image_task(
+ self,
+ project_id: int,
+ user_id: int,
+ prompt: str,
+ asset_id: int | None = None,
+ name: str | None = None,
+ kind: str = "character",
+ image_style_id: str | None = None,
+ model_id: str | None = None,
+ aspect_ratio: str | None = None,
+ resolution: str | None = None,
+) -> dict:
+ # Celery:资产生图
+ from app.services.drama.jobs import run_asset_image_job
+
+ logger.info(
+ "[Celery] 领取资产生图任务 project_id=%s asset_id=%s kind=%s style=%s task_id=%s",
+ project_id,
+ asset_id,
+ kind,
+ image_style_id,
+ self.request.id,
+ )
+ result = _run(
+ run_asset_image_job(
+ project_id,
+ user_id,
+ prompt,
+ asset_id,
+ name,
+ kind,
+ image_style_id=image_style_id,
+ model_id=model_id,
+ aspect_ratio=aspect_ratio,
+ resolution=resolution,
+ )
+ )
+ logger.info(
+ "[Celery] 资产生图任务结束 project_id=%s asset_id=%s result=%s",
+ project_id,
+ asset_id,
+ result,
+ )
+ return result
diff --git a/backend/tests/test_seedance_segments.py b/backend/tests/test_seedance_segments.py
index 1f8b734..8b6f75d 100644
--- a/backend/tests/test_seedance_segments.py
+++ b/backend/tests/test_seedance_segments.py
@@ -1,11 +1,15 @@
"""Unit tests for manju-style segment planning."""
from app.services.seedance_segments import (
+ NARRATION_PREFIX,
+ SEEDANCE_PRODUCTION_SECTION_HEADER,
SegmentBeat,
apply_segment_script_edit,
build_segment_script,
+ build_seedance_production_section,
build_seedance_prompt,
narration_from_script,
+ parse_beats_from_llm_shot,
replace_duration_with_time_ranges,
resolve_api_duration,
sum_duration,
@@ -33,15 +37,58 @@ def test_build_segment_script_and_time_ranges():
assert "很多人找开源工具" in narration_from_script(script)
-def test_build_seedance_prompt_includes_style():
+def test_build_seedance_prompt_includes_style_and_production():
script = build_segment_script(
- [SegmentBeat(duration=5, kind="visual", text="手部点击配置")],
+ [
+ SegmentBeat(duration=5, kind="visual", text="手部点击配置"),
+ SegmentBeat(duration=6, kind="narration", text="一键接入即可开始监控"),
+ ],
bgm_mood="轻快专业",
)
- prompt = build_seedance_prompt(script, style_prefix="真人写实工位", motion_bias="轻推", camera="缓慢推近")
+ prompt = build_seedance_prompt(
+ script, style_prefix="真人写实工位", motion_bias="轻推", camera="缓慢推近"
+ )
assert "强制约束:视频画面风格" in prompt
assert "真人写实工位" in prompt
+ assert SEEDANCE_PRODUCTION_SECTION_HEADER in prompt
+ assert "语速" in prompt
+ assert "字幕" in prompt
+ assert "背景音乐" in prompt
assert "00:00-00:05" in prompt
+ assert NARRATION_PREFIX in prompt or "旁白" in prompt
+
+
+def test_build_seedance_production_section_detects_vo():
+ script = (
+ "【字幕:全程简体中文字幕,旁白逐句同步烧录】\n"
+ "【BGM:轻快专业,音量低于人声】\n"
+ "@duration:4\n过肩演示\n"
+ f"@duration:8\n{NARRATION_PREFIX}口播一句"
+ )
+ section = build_seedance_production_section(script)
+ assert section.startswith(SEEDANCE_PRODUCTION_SECTION_HEADER)
+ assert "第三人称旁白配音" in section
+ assert "轻快专业" in section
+
+
+def test_parse_beats_clamps_short_narration_duration():
+ beats = parse_beats_from_llm_shot(
+ {
+ "segments": [
+ {"kind": "visual", "duration": 4, "text": "过肩景,程序员点击触控板"},
+ {
+ "kind": "narration",
+ "duration": 3,
+ "text": "还在被网站加载慢、用户流失、性能问题反复出现困扰吗?",
+ },
+ ]
+ }
+ )
+ assert len(beats) == 2
+ assert beats[0].duration == 4
+ # 旁白按字数估时应大于等于 LLM 给的 3 秒
+ assert beats[1].duration >= 3
+ assert beats[1].duration <= 12
def test_apply_segment_script_edit_fills_cues():
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 982f5ce..8b22062 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -8,7 +8,9 @@
"name": "frontend",
"version": "0.0.0",
"dependencies": {
+ "@xyflow/react": "^12.11.2",
"jszip": "^3.10.1",
+ "lucide-react": "^1.31.0",
"qrcode": "^1.5.4",
"react": "^19.2.8",
"react-dom": "^19.2.8",
@@ -646,6 +648,55 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/d3-color": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmmirror.com/@types/d3-color/-/d3-color-3.1.3.tgz",
+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-drag": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmmirror.com/@types/d3-drag/-/d3-drag-3.0.7.tgz",
+ "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-interpolate": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmmirror.com/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-color": "*"
+ }
+ },
+ "node_modules/@types/d3-selection": {
+ "version": "3.0.11",
+ "resolved": "https://registry.npmmirror.com/@types/d3-selection/-/d3-selection-3.0.11.tgz",
+ "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-transition": {
+ "version": "3.0.9",
+ "resolved": "https://registry.npmmirror.com/@types/d3-transition/-/d3-transition-3.0.9.tgz",
+ "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-zoom": {
+ "version": "3.0.8",
+ "resolved": "https://registry.npmmirror.com/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",
+ "integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-interpolate": "*",
+ "@types/d3-selection": "*"
+ }
+ },
"node_modules/@types/jszip": {
"version": "3.4.0",
"resolved": "https://registry.npmmirror.com/@types/jszip/-/jszip-3.4.0.tgz",
@@ -680,7 +731,7 @@
"version": "19.2.18",
"resolved": "https://registry.npmmirror.com/@types/react/-/react-19.2.18.tgz",
"integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==",
- "dev": true,
+ "devOptional": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
@@ -690,7 +741,7 @@
"version": "19.2.4",
"resolved": "https://registry.npmmirror.com/@types/react-dom/-/react-dom-19.2.4.tgz",
"integrity": "sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw==",
- "dev": true,
+ "devOptional": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^19.2.0"
@@ -722,6 +773,48 @@
}
}
},
+ "node_modules/@xyflow/react": {
+ "version": "12.11.2",
+ "resolved": "https://registry.npmmirror.com/@xyflow/react/-/react-12.11.2.tgz",
+ "integrity": "sha512-eLAlDWJfWnQEhJwGMjlWdAXO9eYllKpliUmPQlAmOLxz6mExXuzMVDUKLMquixgkrtmMFFtug3jGKmYYld12cA==",
+ "license": "MIT",
+ "dependencies": {
+ "@xyflow/system": "0.0.79",
+ "classcat": "^5.0.3",
+ "zustand": "^4.4.0"
+ },
+ "peerDependencies": {
+ "@types/react": ">=17",
+ "@types/react-dom": ">=17",
+ "react": ">=17",
+ "react-dom": ">=17"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@xyflow/system": {
+ "version": "0.0.79",
+ "resolved": "https://registry.npmmirror.com/@xyflow/system/-/system-0.0.79.tgz",
+ "integrity": "sha512-czLyOh91NF0hIzbNzwi8I6GlqG23BHh2435OddfI6uiaLH3xdrdygO93gqgH1Bv9mhy8XPFQJOBn1FTq4LvEWA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-drag": "^3.0.7",
+ "@types/d3-interpolate": "^3.0.4",
+ "@types/d3-selection": "^3.0.10",
+ "@types/d3-transition": "^3.0.8",
+ "@types/d3-zoom": "^3.0.8",
+ "d3-drag": "^3.0.0",
+ "d3-interpolate": "^3.0.1",
+ "d3-selection": "^3.0.0",
+ "d3-zoom": "^3.0.0"
+ }
+ },
"node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz",
@@ -755,6 +848,12 @@
"node": ">=6"
}
},
+ "node_modules/classcat": {
+ "version": "5.0.5",
+ "resolved": "https://registry.npmmirror.com/classcat/-/classcat-5.0.5.tgz",
+ "integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==",
+ "license": "MIT"
+ },
"node_modules/cliui": {
"version": "6.0.0",
"resolved": "https://registry.npmmirror.com/cliui/-/cliui-6.0.0.tgz",
@@ -807,9 +906,114 @@
"version": "3.2.3",
"resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
- "dev": true,
+ "devOptional": true,
"license": "MIT"
},
+ "node_modules/d3-color": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmmirror.com/d3-color/-/d3-color-3.1.0.tgz",
+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-dispatch": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmmirror.com/d3-dispatch/-/d3-dispatch-3.0.1.tgz",
+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-drag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/d3-drag/-/d3-drag-3.0.0.tgz",
+ "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-selection": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-ease": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmmirror.com/d3-ease/-/d3-ease-3.0.1.tgz",
+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-interpolate": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmmirror.com/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-selection": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/d3-selection/-/d3-selection-3.0.0.tgz",
+ "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-timer": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmmirror.com/d3-timer/-/d3-timer-3.0.1.tgz",
+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-transition": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmmirror.com/d3-transition/-/d3-transition-3.0.1.tgz",
+ "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3",
+ "d3-dispatch": "1 - 3",
+ "d3-ease": "1 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-timer": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "peerDependencies": {
+ "d3-selection": "2 - 3"
+ }
+ },
+ "node_modules/d3-zoom": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/d3-zoom/-/d3-zoom-3.0.0.tgz",
+ "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-drag": "2 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-selection": "2 - 3",
+ "d3-transition": "2 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/decamelize": {
"version": "1.2.0",
"resolved": "https://registry.npmmirror.com/decamelize/-/decamelize-1.2.0.tgz",
@@ -1229,6 +1433,15 @@
"node": ">=8"
}
},
+ "node_modules/lucide-react": {
+ "version": "1.31.0",
+ "resolved": "https://registry.npmmirror.com/lucide-react/-/lucide-react-1.31.0.tgz",
+ "integrity": "sha512-G8u2eEtoHUnUa9f8lbvqDhCiORMnYLdUEo06EEG9MQvHQrInKcX3Pa2TH39MM5qyzRcWETxB0+aOwAPI1g1kEg==",
+ "license": "ISC",
+ "peerDependencies": {
+ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
"node_modules/nanoid": {
"version": "3.3.17",
"resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.17.tgz",
@@ -1664,6 +1877,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/use-sync-external-store": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmmirror.com/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
+ "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
+ "license": "MIT",
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz",
@@ -1808,6 +2030,34 @@
"engines": {
"node": ">=6"
}
+ },
+ "node_modules/zustand": {
+ "version": "4.5.7",
+ "resolved": "https://registry.npmmirror.com/zustand/-/zustand-4.5.7.tgz",
+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",
+ "license": "MIT",
+ "dependencies": {
+ "use-sync-external-store": "^1.2.2"
+ },
+ "engines": {
+ "node": ">=12.7.0"
+ },
+ "peerDependencies": {
+ "@types/react": ">=16.8",
+ "immer": ">=9.0.6",
+ "react": ">=16.8"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "immer": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ }
+ }
}
}
}
diff --git a/frontend/package.json b/frontend/package.json
index bff90eb..d42c586 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -10,7 +10,9 @@
"preview": "vite preview"
},
"dependencies": {
+ "@xyflow/react": "^12.11.2",
"jszip": "^3.10.1",
+ "lucide-react": "^1.31.0",
"qrcode": "^1.5.4",
"react": "^19.2.8",
"react-dom": "^19.2.8",
diff --git a/frontend/public/image-styles/90s-realistic-film.svg b/frontend/public/image-styles/90s-realistic-film.svg
new file mode 100644
index 0000000..2b1ff0c
--- /dev/null
+++ b/frontend/public/image-styles/90s-realistic-film.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#2c3e50"/>
+ <stop offset="100%" stop-color="#e67e22" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">90年代写实电影</text>
+</svg>
diff --git a/frontend/public/image-styles/90s-rural-china-film.svg b/frontend/public/image-styles/90s-rural-china-film.svg
new file mode 100644
index 0000000..a982b8d
--- /dev/null
+++ b/frontend/public/image-styles/90s-rural-china-film.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#3e2723"/>
+ <stop offset="100%" stop-color="#a5d6a7" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">90年代中国农村</text>
+</svg>
diff --git a/frontend/public/image-styles/american-retro-hollywood.svg b/frontend/public/image-styles/american-retro-hollywood.svg
new file mode 100644
index 0000000..3e9e478
--- /dev/null
+++ b/frontend/public/image-styles/american-retro-hollywood.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#1a1423"/>
+ <stop offset="100%" stop-color="#f5cd79" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">美式复古好莱坞</text>
+</svg>
diff --git a/frontend/public/image-styles/ancient-chinese-mythology.svg b/frontend/public/image-styles/ancient-chinese-mythology.svg
new file mode 100644
index 0000000..9723e9e
--- /dev/null
+++ b/frontend/public/image-styles/ancient-chinese-mythology.svg
@@ -0,0 +1,14 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="480" height="360" viewBox="0 0 480 360" fill="none">
+ <defs>
+ <linearGradient id="bg" x1="0" y1="0" x2="480" y2="360" gradientUnits="userSpaceOnUse">
+ <stop stop-color="#1a2f28"/>
+ <stop offset="0.45" stop-color="#3d5c4a"/>
+ <stop offset="1" stop-color="#c4a574"/>
+ </linearGradient>
+ </defs>
+ <rect width="480" height="360" fill="url(#bg)"/>
+ <path d="M0 250 C80 210 140 270 220 230 C300 190 360 250 480 210 L480 360 L0 360 Z" fill="#0f1f1a" opacity="0.55"/>
+ <path d="M40 180 C120 140 180 200 260 150 C340 100 400 160 460 120" stroke="#e8d5a8" stroke-width="2" opacity="0.35"/>
+ <circle cx="360" cy="88" r="28" fill="#f0e2b8" opacity="0.45"/>
+ <text x="240" y="300" text-anchor="middle" fill="#f7f0df" font-family="serif" font-size="22">古代神话史诗</text>
+</svg>
diff --git a/frontend/public/image-styles/ancient-romance-soft.svg b/frontend/public/image-styles/ancient-romance-soft.svg
new file mode 100644
index 0000000..0d4ae3d
--- /dev/null
+++ b/frontend/public/image-styles/ancient-romance-soft.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#3d2c29"/>
+ <stop offset="100%" stop-color="#e8b4bc" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">古偶唯美柔光</text>
+</svg>
diff --git a/frontend/public/image-styles/chinese-urban-realistic.svg b/frontend/public/image-styles/chinese-urban-realistic.svg
new file mode 100644
index 0000000..793fa0b
--- /dev/null
+++ b/frontend/public/image-styles/chinese-urban-realistic.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#1e272e"/>
+ <stop offset="100%" stop-color="#d2dae2" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">国产都市写实</text>
+</svg>
diff --git a/frontend/public/image-styles/domestic-suspense-cold.svg b/frontend/public/image-styles/domestic-suspense-cold.svg
new file mode 100644
index 0000000..dc85426
--- /dev/null
+++ b/frontend/public/image-styles/domestic-suspense-cold.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#1c2331"/>
+ <stop offset="100%" stop-color="#7f8c9b" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">国产悬疑冷调</text>
+</svg>
diff --git a/frontend/public/image-styles/japanese-daily-natural.svg b/frontend/public/image-styles/japanese-daily-natural.svg
new file mode 100644
index 0000000..12e6264
--- /dev/null
+++ b/frontend/public/image-styles/japanese-daily-natural.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#2f3640"/>
+ <stop offset="100%" stop-color="#7bed9f" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">日式生活自然</text>
+</svg>
diff --git a/frontend/public/image-styles/japanese-youth-film.svg b/frontend/public/image-styles/japanese-youth-film.svg
new file mode 100644
index 0000000..6064abd
--- /dev/null
+++ b/frontend/public/image-styles/japanese-youth-film.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#2d3436"/>
+ <stop offset="100%" stop-color="#fdcb6e" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">日式青春胶片</text>
+</svg>
diff --git a/frontend/public/image-styles/korean-urban-soft.svg b/frontend/public/image-styles/korean-urban-soft.svg
new file mode 100644
index 0000000..7d7cd45
--- /dev/null
+++ b/frontend/public/image-styles/korean-urban-soft.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#2c2c54"/>
+ <stop offset="100%" stop-color="#f8a5c2" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">韩剧都市柔光</text>
+</svg>
diff --git a/frontend/public/image-styles/neon-cyberpunk-film.svg b/frontend/public/image-styles/neon-cyberpunk-film.svg
new file mode 100644
index 0000000..042d8d5
--- /dev/null
+++ b/frontend/public/image-styles/neon-cyberpunk-film.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#0f0f23"/>
+ <stop offset="100%" stop-color="#00f5d4" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">霓虹赛博电影</text>
+</svg>
diff --git a/frontend/public/image-styles/palace-intrigue-cold.svg b/frontend/public/image-styles/palace-intrigue-cold.svg
new file mode 100644
index 0000000..bf4d87e
--- /dev/null
+++ b/frontend/public/image-styles/palace-intrigue-cold.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#2c1810"/>
+ <stop offset="100%" stop-color="#c4a574" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">宫斗权谋冷峻</text>
+</svg>
diff --git a/frontend/public/image-styles/pixel-art.svg b/frontend/public/image-styles/pixel-art.svg
new file mode 100644
index 0000000..485456b
--- /dev/null
+++ b/frontend/public/image-styles/pixel-art.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#2d3436"/>
+ <stop offset="100%" stop-color="#6c5ce7" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">像素风</text>
+</svg>
diff --git a/frontend/public/image-styles/retro-narrative-film.svg b/frontend/public/image-styles/retro-narrative-film.svg
new file mode 100644
index 0000000..f496b3e
--- /dev/null
+++ b/frontend/public/image-styles/retro-narrative-film.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#3b2f2f"/>
+ <stop offset="100%" stop-color="#d4a574" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">复古叙事电影</text>
+</svg>
diff --git a/frontend/public/image-styles/retro-sci-fi-atompunk.svg b/frontend/public/image-styles/retro-sci-fi-atompunk.svg
new file mode 100644
index 0000000..ae7d797
--- /dev/null
+++ b/frontend/public/image-styles/retro-sci-fi-atompunk.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#1a1a2e"/>
+ <stop offset="100%" stop-color="#e94560" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">复古科幻原子朋克</text>
+</svg>
diff --git a/frontend/public/image-styles/shadow-puppet-illustration.svg b/frontend/public/image-styles/shadow-puppet-illustration.svg
new file mode 100644
index 0000000..4f9f06f
--- /dev/null
+++ b/frontend/public/image-styles/shadow-puppet-illustration.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#1a120b"/>
+ <stop offset="100%" stop-color="#e17055" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">皮影戏插画</text>
+</svg>
diff --git a/frontend/public/image-styles/shanghai-animation.svg b/frontend/public/image-styles/shanghai-animation.svg
new file mode 100644
index 0000000..6d8d950
--- /dev/null
+++ b/frontend/public/image-styles/shanghai-animation.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#fff8e7"/>
+ <stop offset="100%" stop-color="#c0392b" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">上美画风</text>
+</svg>
diff --git a/frontend/public/image-styles/tezuka-era-cartoon.svg b/frontend/public/image-styles/tezuka-era-cartoon.svg
new file mode 100644
index 0000000..109e867
--- /dev/null
+++ b/frontend/public/image-styles/tezuka-era-cartoon.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#ffffff"/>
+ <stop offset="100%" stop-color="#e74c3c" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">手冢治虫卡通</text>
+</svg>
diff --git a/frontend/public/image-styles/wuxia-realistic-photo.svg b/frontend/public/image-styles/wuxia-realistic-photo.svg
new file mode 100644
index 0000000..fce6ee2
--- /dev/null
+++ b/frontend/public/image-styles/wuxia-realistic-photo.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#1b1464"/>
+ <stop offset="100%" stop-color="#c7ecee" stop-opacity="0.55"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#g)"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(0,0,0,0.35)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">武侠江湖写实</text>
+</svg>
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index ebf1a48..e776e49 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -10,6 +10,11 @@ import CreateProjectPage from './pages/studio/CreateProjectPage'
import StyleConfigPage from './pages/studio/StyleConfigPage'
import StoryboardPage from './pages/studio/StoryboardPage'
import EditorPage from './pages/studio/EditorPage'
+import DramaListPage from './pages/drama/DramaListPage'
+import AssetLibraryPage from './pages/drama/AssetLibraryPage'
+import ProjectWorkspacePage from './pages/drama/ProjectWorkspacePage'
+import EpisodeEditPage from './pages/drama/EpisodeEditPage'
+import CanvasPage from './pages/drama/canvas/CanvasPage'
import './styles/printfilm.css'
import './App.css'
@@ -27,6 +32,13 @@ export default function App() {
<Route path="/studio/:id/editor" element={<EditorPage />} />
<Route path="/studio/:id" element={<StoryboardPage />} />
<Route path="/studio" element={<StudioPage />} />
+ {/* Agent home (mirrors novel agent entry) */}
+ <Route path="/drama" element={<DramaListPage />} />
+ <Route path="/drama/dramas" element={<DramaListPage />} />
+ <Route path="/drama/assets" element={<AssetLibraryPage />} />
+ <Route path="/drama/projects/:projectId" element={<ProjectWorkspacePage />} />
+ <Route path="/drama/projects/:projectId/episodes/:episodeId" element={<EpisodeEditPage />} />
+ <Route path="/drama/projects/:projectId/canvas" element={<CanvasPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
<DialogHost />
diff --git a/frontend/src/api/drama.ts b/frontend/src/api/drama.ts
new file mode 100644
index 0000000..1f77ef7
--- /dev/null
+++ b/frontend/src/api/drama.ts
@@ -0,0 +1,306 @@
+/** Drama module API client (/api/drama/*). */
+
+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 _viteApiBase = import.meta.env.VITE_API_BASE
+const API_BASE =
+ _viteApiBase === undefined || _viteApiBase === null ? defaultApiBase() : String(_viteApiBase)
+
+/** 导出 API 根地址,供静态资源 URL 拼接 */
+export function getDramaApiBase() {
+ return API_BASE
+}
+
+/** 将 /static 相对路径补全为可访问的绝对 URL */
+export function resolveDramaMediaUrl(url?: string | null): string {
+ if (!url) return ''
+ if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('data:')) {
+ return url
+ }
+ if (url.startsWith('/')) return `${API_BASE}${url}`
+ return url
+}
+
+function authHeaders(): HeadersInit {
+ const token = localStorage.getItem('token')
+ return token
+ ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }
+ : { 'Content-Type': 'application/json' }
+}
+
+async function request<T>(path: string, init?: RequestInit): Promise<T> {
+ const res = await fetch(`${API_BASE}${path}`, {
+ ...init,
+ headers: { ...authHeaders(), ...(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()
+}
+
+export type DramaScript = {
+ id: number
+ name: string
+ source?: string | null
+ summary?: Record<string, unknown> | null
+ episode_content?: { episodes?: DramaEpisodeBody[] } | DramaEpisodeBody[] | null
+ params?: Record<string, unknown> | null
+ project_id: number
+}
+
+export type DramaEpisodeBody = {
+ episodeNumber?: number
+ title?: string
+ body?: string
+}
+
+export type DramaProject = {
+ id: number
+ user_id: number
+ title: string
+ description?: string | null
+ content?: Record<string, unknown> | null
+ params?: Record<string, unknown> | null
+ created_at?: string
+ updated_at?: string
+ script?: DramaScript | null
+ asset_count: number
+ episode_count: number
+}
+
+export type DramaProjectListItem = {
+ id: number
+ title: string
+ description?: string | null
+ created_at?: string
+ updated_at?: string
+ episode_count: number
+ asset_count: number
+ has_script: boolean
+}
+
+export type DramaAsset = {
+ id: number
+ type: string
+ asset_type: string
+ name?: string | null
+ cover?: string | null
+ url?: string | null
+ params?: Record<string, unknown> | null
+ project_id: number
+}
+
+export type DramaFragment = {
+ id: number
+ episode_id: number
+ sort_order: number
+ content: string
+ cover: string
+ video: string
+ duration_sec?: number | null
+ params?: Record<string, unknown> | null
+ asset_ids: number[]
+}
+
+export type DramaEpisode = {
+ id: number
+ name: string
+ params?: Record<string, unknown> | null
+ project_id: number
+ fragments: DramaFragment[]
+}
+
+export type DramaScriptSummaryResult = {
+ ok?: boolean
+ queued?: boolean
+ status?: string
+ task_id?: string | null
+ summary?: Record<string, unknown>
+ text?: string
+ script: DramaScript
+ projectTitle?: string
+}
+
+export type DramaEpisodeScriptResult = {
+ ok?: boolean
+ queued?: boolean
+ status?: string
+ task_id?: string | null
+ episodes: DramaEpisodeBody[]
+ total_generated: number
+ total_target: number
+ done: boolean
+ script: DramaScript
+}
+
+export type DramaImageGenerateResult = {
+ ok: boolean
+ queued: boolean
+ status: string
+ task_id?: string | null
+ asset_id?: number | null
+ asset?: DramaAsset | null
+}
+
+export const dramaApi = {
+ listProjects: () => request<DramaProjectListItem[]>('/api/drama/projects'),
+ createProject: (body: {
+ title?: string
+ description?: string
+ source?: string
+ episode_count?: number
+ image_style_id?: string
+ }) =>
+ request<DramaProject>('/api/drama/projects', { method: 'POST', body: JSON.stringify(body) }),
+ getProject: (id: number) => request<DramaProject>(`/api/drama/projects/${id}`),
+ updateProject: (id: number, body: { title?: string; description?: string }) =>
+ request<DramaProject>(`/api/drama/projects/${id}`, { method: 'PATCH', body: JSON.stringify(body) }),
+ deleteProject: (id: number) =>
+ request<{ ok: boolean }>(`/api/drama/projects/${id}`, { method: 'DELETE' }),
+
+ getScript: (projectId: number) => request<DramaScript>(`/api/drama/scripts/${projectId}`),
+ updateScript: (projectId: number, body: { image_style_id?: string; [key: string]: unknown }) =>
+ request<DramaScript>(`/api/drama/scripts/${projectId}`, {
+ method: 'PATCH',
+ body: JSON.stringify(body),
+ }),
+
+ scriptSummary: (body: {
+ project_id: number
+ creative?: string
+ episode_count?: number
+ image_style_id?: string
+ }) =>
+ request<DramaScriptSummaryResult>('/api/drama/agents/script_summary', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ }),
+ episodeScript: (body: { project_id: number; batch_size?: number; force?: boolean }) =>
+ request<DramaEpisodeScriptResult>('/api/drama/agents/episode_script', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ }),
+ route: (message: string) =>
+ request<{ agent: string; action: string }>('/api/drama/agents/route', {
+ method: 'POST',
+ body: JSON.stringify({ message }),
+ }),
+ chat: (message: string, project_id?: number) =>
+ request<{ reply: string }>('/api/drama/ai/chat', {
+ method: 'POST',
+ body: JSON.stringify({ message, project_id }),
+ }),
+
+ listAssets: (projectId?: number) =>
+ request<DramaAsset[]>(
+ projectId != null ? `/api/drama/assets?project_id=${projectId}` : '/api/drama/assets',
+ ),
+ createAsset: (body: Partial<DramaAsset> & { project_id: number }) =>
+ request<DramaAsset>('/api/drama/assets', { method: 'POST', body: JSON.stringify(body) }),
+ updateAsset: (id: number, body: Partial<DramaAsset>) =>
+ request<DramaAsset>(`/api/drama/assets/${id}`, { method: 'PATCH', body: JSON.stringify(body) }),
+ uploadAssetMedia: async (assetId: number, file: File) => {
+ const token = localStorage.getItem('token')
+ const form = new FormData()
+ form.append('file', file)
+ const res = await fetch(`${API_BASE}/api/drama/assets/${assetId}/upload`, {
+ 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<DramaAsset>
+ },
+ deleteAsset: (id: number) =>
+ request<{ ok: boolean }>(`/api/drama/assets/${id}`, { method: 'DELETE' }),
+ seedAssets: (projectId: number) =>
+ request<DramaAsset[]>(`/api/drama/assets/seed_from_script?project_id=${projectId}`, {
+ method: 'POST',
+ }),
+
+ listEpisodes: (projectId: number) =>
+ request<DramaEpisode[]>(`/api/drama/episodes?project_id=${projectId}`),
+ getEpisode: (id: number) => request<DramaEpisode>(`/api/drama/episodes/${id}`),
+ seedEpisodes: (projectId: number, force = false) =>
+ request<DramaEpisode[]>(
+ `/api/drama/episodes/seed_from_script?project_id=${projectId}${force ? '&force=true' : ''}`,
+ { method: 'POST' },
+ ),
+ saveFragments: (
+ episodeId: number,
+ fragments: Array<{
+ sort_order: number
+ content: string
+ cover?: string
+ video?: string
+ duration_sec?: number | null
+ asset_ids?: number[]
+ }>,
+ ) =>
+ request<DramaEpisode>(`/api/drama/episodes/${episodeId}/fragments`, {
+ method: 'POST',
+ body: JSON.stringify({ fragments }),
+ }),
+ generateEpisode: (episodeId: number, fragment_ids?: number[]) =>
+ request<{ ok: boolean; fragment_ids: number[]; status: string }>(
+ `/api/drama/episodes/${episodeId}/generate`,
+ { method: 'POST', body: JSON.stringify({ fragment_ids }) },
+ ),
+ generateStatus: (episodeId: number) =>
+ request<{
+ episode_id: number
+ done: number
+ failed: number
+ running: number
+ total: number
+ fragments: Array<{ fragment_id: number; status: string; video?: string }>
+ }>(`/api/drama/episodes/${episodeId}/generate_status`),
+
+ generateImage: (body: {
+ project_id: number
+ asset_id?: number
+ prompt: string
+ name?: string
+ asset_type_kind?: string
+ image_style_id?: string
+ model_id?: string
+ aspect_ratio?: string
+ resolution?: string
+ }) =>
+ request<DramaImageGenerateResult>('/api/drama/generation/image', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ }),
+
+ getCanvas: (projectId: number) =>
+ request<{ project_id: number; nodes: unknown[]; edges: unknown[] }>(
+ `/api/drama/canvas/${projectId}`,
+ ),
+ saveCanvas: (body: { project_id: number; nodes: unknown[]; edges: unknown[] }) =>
+ request<{ ok: boolean }>('/api/drama/canvas', { method: 'POST', body: JSON.stringify(body) }),
+}
diff --git a/frontend/src/components/layout/AppShell.tsx b/frontend/src/components/layout/AppShell.tsx
index 6ebdb13..5e95440 100644
--- a/frontend/src/components/layout/AppShell.tsx
+++ b/frontend/src/components/layout/AppShell.tsx
@@ -3,7 +3,7 @@ import SiteNav from './SiteNav'
type Props = {
children: ReactNode
- active?: 'home' | 'templates' | 'studio' | 'history' | 'pricing'
+ active?: 'home' | 'templates' | 'studio' | 'history' | 'pricing' | 'drama'
wide?: boolean
flush?: boolean
}
diff --git a/frontend/src/components/layout/SiteNav.tsx b/frontend/src/components/layout/SiteNav.tsx
index 1c742b9..c118531 100644
--- a/frontend/src/components/layout/SiteNav.tsx
+++ b/frontend/src/components/layout/SiteNav.tsx
@@ -7,7 +7,7 @@ import HelpCenter from '../ui/HelpCenter'
import { IconBell, IconGift, IconHelp } from '../ui/Icons'
type Props = {
- active?: 'home' | 'templates' | 'studio' | 'history' | 'pricing'
+ active?: 'home' | 'templates' | 'studio' | 'history' | 'pricing' | 'drama'
}
export default function SiteNav({ active }: Props) {
diff --git a/frontend/src/lib/dramaGenerationOptions.ts b/frontend/src/lib/dramaGenerationOptions.ts
new file mode 100644
index 0000000..61141b7
--- /dev/null
+++ b/frontend/src/lib/dramaGenerationOptions.ts
@@ -0,0 +1,86 @@
+/** 漫剧生图:模型 / 比例 / 清晰度选项(对齐 manju generationOptions) */
+
+export type ImageGenerationModelId = 'seedream-5.0' | 'seedream-4.5'
+
+export type GenerationAspectRatioId =
+ | 'auto'
+ | '16:9'
+ | '21:9'
+ | '9:16'
+ | '4:3'
+ | '3:4'
+ | '1:1'
+
+export type GenerationResolution = '3K' | '4K'
+
+export type ImageGenerationOptions = {
+ image_style_id?: string
+ model_id: ImageGenerationModelId
+ aspect_ratio: GenerationAspectRatioId
+ resolution: GenerationResolution
+}
+
+/** 图片清晰度列表 */
+export const GENERATION_RESOLUTION_OPTIONS: GenerationResolution[] = ['3K', '4K']
+
+/** 比例列表 */
+export const GENERATION_ASPECT_RATIO_OPTIONS: Array<{
+ id: GenerationAspectRatioId
+ label: string
+}> = [
+ { id: 'auto', label: '自动' },
+ { id: '16:9', label: '16:9' },
+ { id: '21:9', label: '21:9' },
+ { id: '9:16', label: '9:16' },
+ { id: '4:3', label: '4:3' },
+ { id: '3:4', label: '3:4' },
+ { id: '1:1', label: '1:1' },
+]
+
+/** Seedream 生图模型 */
+export const IMAGE_GENERATION_MODELS: Array<{
+ id: ImageGenerationModelId
+ label: string
+ description: string
+}> = [
+ {
+ id: 'seedream-5.0',
+ label: 'Seedream 5.0',
+ description: '更智能的理解与推理,支持多图融合。',
+ },
+ {
+ id: 'seedream-4.5',
+ label: 'Seedream 4.5',
+ description: '擅长图片编辑与复杂场景还原。',
+ },
+]
+
+/** 默认生图选项(角色偏竖构图) */
+export const DEFAULT_IMAGE_GENERATION_OPTIONS: ImageGenerationOptions = {
+ model_id: 'seedream-5.0',
+ aspect_ratio: '3:4',
+ resolution: '3K',
+}
+
+/** 场景默认横构图 */
+export function defaultOptionsForAssetKind(kind: string | undefined | null): ImageGenerationOptions {
+ const k = String(kind || '').toLowerCase()
+ if (k === 'scene') {
+ return { model_id: 'seedream-5.0', aspect_ratio: '16:9', resolution: '3K' }
+ }
+ return { ...DEFAULT_IMAGE_GENERATION_OPTIONS }
+}
+
+/** 格式化比例·清晰度触发文案 */
+export function formatOutputSettingsLabel(
+ aspectRatio: GenerationAspectRatioId,
+ resolution: GenerationResolution,
+): string {
+ if (aspectRatio === 'auto') return `自动 · ${resolution}`
+ return `${aspectRatio} · ${resolution}`
+}
+
+/** 解析模型展示名 */
+export function getImageModelLabel(modelId: string | undefined | null): string {
+ return IMAGE_GENERATION_MODELS.find((m) => m.id === modelId)?.label ?? 'Seedream 5.0'
+}
diff --git a/frontend/src/lib/dramaImageStyles.ts b/frontend/src/lib/dramaImageStyles.ts
new file mode 100644
index 0000000..41e3406
--- /dev/null
+++ b/frontend/src/lib/dramaImageStyles.ts
@@ -0,0 +1,54 @@
+/** Drama image style options (aligned with manju imageStyles). */
+
+export const IMAGE_STYLE_IDS = [
+ 'retro-sci-fi-atompunk',
+ 'palace-intrigue-cold',
+ 'domestic-suspense-cold',
+ 'ancient-romance-soft',
+ 'ancient-chinese-mythology',
+ 'japanese-youth-film',
+ 'japanese-daily-natural',
+ 'korean-urban-soft',
+ 'chinese-urban-realistic',
+ 'wuxia-realistic-photo',
+ '90s-realistic-film',
+ 'retro-narrative-film',
+ 'american-retro-hollywood',
+ 'neon-cyberpunk-film',
+ '90s-rural-china-film',
+ 'tezuka-era-cartoon',
+ 'shanghai-animation',
+ 'pixel-art',
+ 'shadow-puppet-illustration',
+] as const
+
+export type ImageStyleId = (typeof IMAGE_STYLE_IDS)[number]
+
+export const IMAGE_STYLE_OPTIONS: Array<{ id: ImageStyleId; label: string }> = [
+ { id: 'retro-sci-fi-atompunk', label: '复古科幻原子朋克' },
+ { id: 'palace-intrigue-cold', label: '宫斗权谋冷峻' },
+ { id: 'domestic-suspense-cold', label: '国产悬疑冷调' },
+ { id: 'ancient-romance-soft', label: '古偶唯美柔光' },
+ { id: 'ancient-chinese-mythology', label: '中国古代神话史诗' },
+ { id: 'japanese-youth-film', label: '日式青春胶片' },
+ { id: 'japanese-daily-natural', label: '日式生活自然' },
+ { id: 'korean-urban-soft', label: '韩剧都市柔光' },
+ { id: 'chinese-urban-realistic', label: '国产都市写实' },
+ { id: 'wuxia-realistic-photo', label: '武侠江湖写实摄影' },
+ { id: '90s-realistic-film', label: '90年代写实电影' },
+ { id: 'retro-narrative-film', label: '复古叙事电影' },
+ { id: 'american-retro-hollywood', label: '美式复古好莱坞' },
+ { id: 'neon-cyberpunk-film', label: '霓虹赛博电影' },
+ { id: '90s-rural-china-film', label: '90年代中国农村电影' },
+ { id: 'tezuka-era-cartoon', label: '手冢治虫时代卡通画风' },
+ { id: 'shanghai-animation', label: '上美画风' },
+ { id: 'pixel-art', label: '像素风' },
+ { id: 'shadow-puppet-illustration', label: '皮影戏插画' },
+]
+
+export const EPISODE_COUNT_PRESETS = [1, 12, 24, 36, 48] as const
+
+export function getImageStyleLabel(styleId: string | undefined | null): string | null {
+ if (!styleId) return null
+ return IMAGE_STYLE_OPTIONS.find((o) => o.id === styleId)?.label ?? null
+}
diff --git a/frontend/src/lib/dramaProjectSteps.ts b/frontend/src/lib/dramaProjectSteps.ts
new file mode 100644
index 0000000..829abca
--- /dev/null
+++ b/frontend/src/lib/dramaProjectSteps.ts
@@ -0,0 +1,36 @@
+/** Drama project workflow steps (aligned with manju projectSteps). */
+
+export type ProjectStepKey = 'outline' | 'assets' | 'episodes'
+
+export type ProjectStepItem = {
+ key: ProjectStepKey
+ label: string
+ order: number
+}
+
+export function buildProjectSteps(hasScript: boolean): ProjectStepItem[] {
+ const steps: Array<{ key: ProjectStepKey; label: string }> = hasScript
+ ? [
+ { key: 'outline', label: '剧情大纲' },
+ { key: 'assets', label: '资产库' },
+ { key: 'episodes', label: '分集视频' },
+ ]
+ : [
+ { key: 'assets', label: '资产库' },
+ { key: 'episodes', label: '分集视频' },
+ ]
+ return steps.map((step, index) => ({ ...step, order: index + 1 }))
+}
+
+export function getInitialProjectStep(hasScript: boolean): ProjectStepKey {
+ return hasScript ? 'outline' : 'assets'
+}
+
+export function getNextProjectStep(
+ steps: ProjectStepItem[],
+ currentStep: ProjectStepKey,
+): ProjectStepKey | null {
+ const currentIndex = steps.findIndex((step) => step.key === currentStep)
+ if (currentIndex < 0 || currentIndex >= steps.length - 1) return null
+ return steps[currentIndex + 1].key
+}
diff --git a/frontend/src/lib/segmentDuration.ts b/frontend/src/lib/segmentDuration.ts
new file mode 100644
index 0000000..61ce61e
--- /dev/null
+++ b/frontend/src/lib/segmentDuration.ts
@@ -0,0 +1,146 @@
+/**
+ * 科普分镜脚本内 @duration 解析、校验与分段预览
+ * 常量与后端 seedance_segments 对齐(单段 3–12s,镜合计 ≤30s)
+ */
+
+/** 单段时长下限(秒) */
+export const SEGMENT_DURATION_MIN = 3
+
+/** 单段时长上限(秒) */
+export const SEGMENT_DURATION_MAX = 12
+
+/** 单镜脚本内 @duration 合计上限(秒) */
+export const SHOT_DURATION_MAX = 30
+
+/** 时长快捷选项(秒) */
+export const SEGMENT_DURATION_PRESETS = [4, 6, 8, 10, 12] as const
+
+/** 与后端一致的字幕 cue */
+export const SUBTITLE_CUE = '【字幕:全程简体中文字幕,旁白逐句同步烧录】'
+
+/** 与后端一致的旁白前缀 */
+export const NARRATION_PREFIX = '【旁白·慢速清晰·同步字幕】'
+
+/** 脚本编辑区 placeholder */
+export const SEGMENT_SCRIPT_PLACEHOLDER = `${SUBTITLE_CUE}\n【BGM:轻快专业,音量低于人声】\n@duration:4\n过肩工位操作画面…\n@duration:8\n${NARRATION_PREFIX}口播内容…`
+
+const DURATION_TOKEN_PATTERN = /@duration:(\d+)/g
+
+export type SegmentBeatView = { duration: number; text: string }
+
+/**
+ * 从脚本中提取全部 @duration 秒数(保留顺序)
+ * @param content 逐段分镜脚本文本
+ */
+export function extractDurations(content: string): number[] {
+ const durations: number[] = []
+ for (const match of content.matchAll(DURATION_TOKEN_PATTERN)) {
+ const seconds = Number(match[1])
+ if (Number.isFinite(seconds) && seconds > 0) {
+ durations.push(seconds)
+ }
+ }
+ return durations
+}
+
+/**
+ * 合计脚本内 @duration 秒数
+ * @param content 逐段分镜脚本文本
+ */
+export function sumDuration(content: string): number {
+ return extractDurations(content).reduce((sum, value) => sum + value, 0)
+}
+
+/**
+ * 校验单个时长是否在科普单段合法区间
+ * @param seconds 时长秒数
+ */
+export function isValidSegmentDuration(seconds: number): boolean {
+ return (
+ Number.isFinite(seconds) &&
+ seconds >= SEGMENT_DURATION_MIN &&
+ seconds <= SEGMENT_DURATION_MAX
+ )
+}
+
+/**
+ * 校验脚本内时长标签:单段范围 + 合计 ≤ 镜上限
+ * @param content 逐段分镜脚本文本
+ */
+export function validateSegmentScriptDuration(content: string): {
+ valid: boolean
+ total: number
+ durations: number[]
+ message?: string
+} {
+ const durations = extractDurations(content)
+ const total = durations.reduce((sum, value) => sum + value, 0)
+
+ if (durations.length === 0) {
+ return { valid: true, total: 0, durations }
+ }
+
+ if (durations.some((value) => !isValidSegmentDuration(value))) {
+ return {
+ valid: false,
+ total,
+ durations,
+ message: `单个 @duration 需在 ${SEGMENT_DURATION_MIN}–${SEGMENT_DURATION_MAX} 秒之间`,
+ }
+ }
+
+ if (total > SHOT_DURATION_MAX) {
+ return {
+ valid: false,
+ total,
+ durations,
+ message: `镜头时长合计不能超过 ${SHOT_DURATION_MAX} 秒(当前 ${total}s)`,
+ }
+ }
+
+ return { valid: true, total, durations }
+}
+
+/**
+ * 解析脚本为字幕/BGM cues 与带时长的正文段(列表预览用)
+ * @param script 逐段分镜脚本
+ */
+export function parseSegmentScript(script: string | undefined | null): {
+ cues: string[]
+ beats: SegmentBeatView[]
+} {
+ /*
+ * cues 字幕/BGM 行
+ * beats 带 duration 的正文段
+ * pendingDur 上一段 @duration 值
+ */
+ const cues: string[] = []
+ const beats: SegmentBeatView[] = []
+ let pendingDur = 0
+
+ const lines = String(script || '')
+ .replace(/\r\n/g, '\n')
+ .split('\n')
+ .map((l) => l.trim())
+ .filter(Boolean)
+
+ for (const line of lines) {
+ if (line.startsWith('【字幕') || line.startsWith('【BGM')) {
+ cues.push(line)
+ continue
+ }
+ const m = line.match(/^@duration:(\d+)/)
+ if (m) {
+ pendingDur = Number(m[1]) || 0
+ continue
+ }
+ if (pendingDur > 0 || beats.length === 0) {
+ beats.push({ duration: pendingDur || 0, text: line })
+ pendingDur = 0
+ } else {
+ beats.push({ duration: 0, text: line })
+ }
+ }
+
+ return { cues, beats }
+}
diff --git a/frontend/src/pages/HistoryPage.tsx b/frontend/src/pages/HistoryPage.tsx
index 5eb381d..c32b350 100644
--- a/frontend/src/pages/HistoryPage.tsx
+++ b/frontend/src/pages/HistoryPage.tsx
@@ -265,6 +265,9 @@ export default function HistoryPage() {
<IconPlus size={16} />
新建项目
</button>
+ <Link to="/studio/new" className="pf-btn pf-btn-sm" style={{ marginLeft: 8 }}>
+ 新建科普
+ </Link>
</div>
<div className="pf-stats">
diff --git a/frontend/src/pages/drama/AssetLibraryPage.tsx b/frontend/src/pages/drama/AssetLibraryPage.tsx
new file mode 100644
index 0000000..1d5a915
--- /dev/null
+++ b/frontend/src/pages/drama/AssetLibraryPage.tsx
@@ -0,0 +1,119 @@
+/** 全局漫剧资产库:角色 / 场景 / 道具 / 素材 */
+import { useEffect, useMemo, useState } from 'react'
+import { Link } from 'react-router-dom'
+import AppShell from '../../components/layout/AppShell'
+import { dramaApi, type DramaAsset } from '../../api/drama'
+import RequireAuth from './RequireAuth'
+import './drama.css'
+
+type AssetTabKey = 'character' | 'scene' | 'prop' | 'material'
+
+const TABS: Array<{ key: AssetTabKey; label: string }> = [
+ { key: 'character', label: '角色' },
+ { key: 'scene', label: '场景' },
+ { key: 'prop', label: '道具' },
+ { key: 'material', label: '素材' },
+]
+
+export default function AssetLibraryPage() {
+ return (
+ <RequireAuth>
+ <AssetLibraryInner />
+ </RequireAuth>
+ )
+}
+
+// 匹配资产到 Tab(type=none 归入素材)
+function matchTab(asset: DramaAsset, tab: AssetTabKey): boolean {
+ const t = (asset.type || '').toLowerCase()
+ if (tab === 'material') return t === 'material' || t === 'none' || !t
+ return t === tab
+}
+
+// 渲染资产库内容
+function AssetLibraryInner() {
+ /*
+ * assets 全部资产
+ * tab 当前分类
+ * query 搜索关键词
+ * error 错误文案
+ */
+ const [assets, setAssets] = useState<DramaAsset[]>([])
+ const [tab, setTab] = useState<AssetTabKey>('character')
+ const [query, setQuery] = useState('')
+ const [error, setError] = useState('')
+
+ useEffect(() => {
+ dramaApi
+ .listAssets()
+ .then(setAssets)
+ .catch((err) => setError(err instanceof Error ? err.message : '加载失败'))
+ }, [])
+
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase()
+ return assets.filter((asset) => {
+ if (!matchTab(asset, tab)) return false
+ if (!q) return true
+ const name = (asset.name || '').toLowerCase()
+ const type = (asset.type || '').toLowerCase()
+ return name.includes(q) || type.includes(q) || String(asset.project_id).includes(q)
+ })
+ }, [assets, tab, query])
+
+ return (
+ <AppShell active="drama">
+ <div className="drama-page">
+ <header className="drama-header">
+ <div>
+ <h1>资产库</h1>
+ <p className="drama-muted">跨项目角色 / 场景 / 道具 / 素材</p>
+ </div>
+ </header>
+
+ <div className="drama-library-toolbar">
+ <div className="drama-asset-tabs">
+ {TABS.map((t) => (
+ <button
+ key={t.key}
+ type="button"
+ className={tab === t.key ? 'active' : ''}
+ onClick={() => setTab(t.key)}
+ >
+ {t.label}
+ </button>
+ ))}
+ </div>
+ <input
+ className="drama-search-input"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="搜索名称、类型或项目 ID"
+ />
+ </div>
+
+ {error ? <p className="drama-error">{error}</p> : null}
+
+ <div className="drama-asset-grid">
+ {filtered.map((asset) => (
+ <article key={asset.id} className="drama-asset-card">
+ {asset.cover || asset.url ? (
+ <img src={asset.cover || asset.url || ''} alt={asset.name || ''} />
+ ) : (
+ <div className="drama-asset-placeholder">{asset.type || 'asset'}</div>
+ )}
+ <h3>{asset.name || '未命名'}</h3>
+ <p>
+ {asset.type === 'none' ? '素材' : asset.type} · 项目 #{asset.project_id}
+ </p>
+ <Link className="pf-link" to={`/drama/projects/${asset.project_id}`}>
+ 打开项目
+ </Link>
+ </article>
+ ))}
+ </div>
+ {filtered.length === 0 ? <p className="drama-muted">暂无匹配资产</p> : null}
+ </div>
+ </AppShell>
+ )
+}
diff --git a/frontend/src/pages/drama/AssetsStep.tsx b/frontend/src/pages/drama/AssetsStep.tsx
new file mode 100644
index 0000000..2b10b85
--- /dev/null
+++ b/frontend/src/pages/drama/AssetsStep.tsx
@@ -0,0 +1,226 @@
+/** 资产库步骤:进入时 seed,分类 Tab + 生图(含风格/模型/画幅) */
+import { useEffect, useRef, useState } from 'react'
+import { Link } from 'react-router-dom'
+import { dramaApi, type DramaAsset } from '../../api/drama'
+import {
+ defaultOptionsForAssetKind,
+ type ImageGenerationOptions,
+} from '../../lib/dramaGenerationOptions'
+import { getImageStyleId } from './dramaWorkspaceUtils'
+import { DramaImageGenOptionsBar } from './canvas/nodes/DramaImageGenOptionsBar'
+
+type AssetTabKey = 'character' | 'scene' | 'prop' | 'material'
+
+const ASSET_TABS: Array<{ key: AssetTabKey; label: string }> = [
+ { key: 'character', label: '角色' },
+ { key: 'scene', label: '场景' },
+ { key: 'prop', label: '道具' },
+ { key: 'material', label: '素材' },
+]
+
+type AssetsStepProps = {
+ projectId: number
+ onError: (m: string) => void
+}
+
+// 渲染资产库步骤
+export function AssetsStep({ projectId, onError }: AssetsStepProps) {
+ const [assets, setAssets] = useState<DramaAsset[]>([])
+ const [tab, setTab] = useState<AssetTabKey>('character')
+ const [loading, setLoading] = useState(true)
+ const [busyId, setBusyId] = useState<number | null>(null)
+ const [batchBusy, setBatchBusy] = useState(false)
+ // genOptions 工具栏生图选项
+ const [genOptions, setGenOptions] = useState<ImageGenerationOptions>(() =>
+ defaultOptionsForAssetKind('character'),
+ )
+ const seeded = useRef(false)
+
+ useEffect(() => {
+ async function enter() {
+ setLoading(true)
+ try {
+ const project = await dramaApi.getProject(projectId).catch(() => null)
+ const styleId = project ? getImageStyleId(project.script, project) : ''
+ setGenOptions((prev) => ({
+ ...defaultOptionsForAssetKind(tab),
+ image_style_id: styleId || prev.image_style_id,
+ model_id: prev.model_id,
+ resolution: prev.resolution,
+ }))
+ if (!seeded.current) {
+ seeded.current = true
+ const seededAssets = await dramaApi.seedAssets(projectId)
+ setAssets(seededAssets)
+ } else {
+ setAssets(await dramaApi.listAssets(projectId))
+ }
+ } catch (err) {
+ onError(err instanceof Error ? err.message : '资产加载失败')
+ try {
+ setAssets(await dramaApi.listAssets(projectId))
+ } catch {
+ /* ignore */
+ }
+ } finally {
+ setLoading(false)
+ }
+ }
+ void enter()
+ }, [projectId, onError])
+
+ useEffect(() => {
+ setGenOptions((prev) => ({
+ ...defaultOptionsForAssetKind(tab),
+ image_style_id: prev.image_style_id,
+ model_id: prev.model_id,
+ resolution: prev.resolution,
+ }))
+ }, [tab])
+
+ const filtered = assets.filter((a) => {
+ const t = (a.type || '').toLowerCase()
+ if (tab === 'material') return t === 'material' || t === 'none' || !t
+ return t === tab
+ })
+ const pending = filtered.filter((a) => !(a.url || a.cover))
+
+ // 持久化项目画面风格
+ async function persistStyle(styleId: string) {
+ try {
+ await dramaApi.updateScript(projectId, { image_style_id: styleId })
+ } catch (err) {
+ onError(err instanceof Error ? err.message : '保存风格失败')
+ }
+ }
+
+ // 生成单个资产形象(入队 worker 后轮询)
+ async function genOne(asset: DramaAsset, options = genOptions) {
+ setBusyId(asset.id)
+ try {
+ const prompt =
+ String((asset.params as { visualImage?: string } | null)?.visualImage || '') ||
+ `${asset.type} ${asset.name || ''}`
+ await dramaApi.generateImage({
+ project_id: projectId,
+ asset_id: asset.id,
+ prompt,
+ name: asset.name || undefined,
+ asset_type_kind: asset.type,
+ image_style_id: options.image_style_id,
+ model_id: options.model_id,
+ aspect_ratio: options.aspect_ratio,
+ resolution: options.resolution,
+ })
+ const started = Date.now()
+ while (Date.now() - started < 10 * 60 * 1000) {
+ const list = await dramaApi.listAssets(projectId)
+ setAssets(list)
+ const latest = list.find((a) => a.id === asset.id)
+ const gen = (latest?.params || {}).generation as
+ | { status?: string; error?: string }
+ | undefined
+ const status = String(gen?.status || '')
+ if (latest && (latest.url || latest.cover) && status !== 'generating') {
+ return
+ }
+ if (status === 'failed') {
+ throw new Error(String(gen?.error || '生图失败'))
+ }
+ if (status === 'done' && (latest?.url || latest?.cover)) {
+ return
+ }
+ await new Promise((r) => setTimeout(r, 2000))
+ }
+ throw new Error('生图超时,请刷新后重试')
+ } catch (err) {
+ onError(err instanceof Error ? err.message : '生图失败')
+ } finally {
+ setBusyId(null)
+ }
+ }
+
+ // 一键生成无封面资产
+ async function batchGenerate() {
+ setBatchBusy(true)
+ try {
+ for (const asset of pending) {
+ await genOne(asset, {
+ ...genOptions,
+ ...defaultOptionsForAssetKind(asset.type),
+ image_style_id: genOptions.image_style_id,
+ model_id: genOptions.model_id,
+ resolution: genOptions.resolution,
+ })
+ }
+ } finally {
+ setBatchBusy(false)
+ }
+ }
+
+ return (
+ <div className="drama-assets-step">
+ <div className="drama-assets-toolbar">
+ <div className="drama-asset-tabs">
+ {ASSET_TABS.map((t) => (
+ <button
+ key={t.key}
+ type="button"
+ className={tab === t.key ? 'active' : ''}
+ onClick={() => setTab(t.key)}
+ >
+ {t.label}
+ </button>
+ ))}
+ </div>
+ <div className="drama-actions">
+ <button
+ type="button"
+ className="drama-btn-primary"
+ disabled={batchBusy || pending.length === 0}
+ onClick={() => void batchGenerate()}
+ >
+ {batchBusy ? '生成中…' : '一键生成'}
+ </button>
+ <Link className="pf-btn" to={`/drama/projects/${projectId}/canvas`}>
+ 打开画布
+ </Link>
+ </div>
+ </div>
+
+ <div className="drama-assets-gen-opts">
+ <DramaImageGenOptionsBar
+ value={genOptions}
+ onChange={setGenOptions}
+ disabled={batchBusy || busyId != null}
+ onStylePersist={persistStyle}
+ />
+ </div>
+
+ {loading ? <p className="drama-muted">正在从剧本抽取资产…</p> : null}
+
+ <div className="drama-asset-grid">
+ {filtered.map((asset) => (
+ <article key={asset.id} className="drama-asset-card">
+ {asset.cover || asset.url ? (
+ <img src={asset.cover || asset.url || ''} alt={asset.name || ''} />
+ ) : (
+ <div className="drama-asset-placeholder">{asset.type || 'asset'}</div>
+ )}
+ <h3>{asset.name || '未命名'}</h3>
+ <p>{asset.type}</p>
+ <button
+ type="button"
+ className="pf-btn pf-btn-sm"
+ disabled={busyId === asset.id || batchBusy}
+ onClick={() => void genOne(asset)}
+ >
+ {busyId === asset.id ? '生成中…' : '生成形象'}
+ </button>
+ </article>
+ ))}
+ </div>
+ {!loading && filtered.length === 0 ? <p className="drama-muted">该分类暂无资产</p> : null}
+ </div>
+ )
+}
diff --git a/frontend/src/pages/drama/CanvasPage.tsx b/frontend/src/pages/drama/CanvasPage.tsx
new file mode 100644
index 0000000..1d578e6
--- /dev/null
+++ b/frontend/src/pages/drama/CanvasPage.tsx
@@ -0,0 +1,2 @@
+/** 兼容旧路径:转发到全屏自由画布页 */
+export { default } from './canvas/CanvasPage'
diff --git a/frontend/src/pages/drama/DramaHomePage.tsx b/frontend/src/pages/drama/DramaHomePage.tsx
new file mode 100644
index 0000000..1558999
--- /dev/null
+++ b/frontend/src/pages/drama/DramaHomePage.tsx
@@ -0,0 +1,7 @@
+/** Legacy drama home — redirect to Agent entry. */
+import { Navigate } from 'react-router-dom'
+
+// Soft entry: /drama now serves DramaListPage via App routes; keep this for old imports
+export default function DramaHomePage() {
+ return <Navigate to="/drama" replace />
+}
diff --git a/frontend/src/pages/drama/DramaListPage.tsx b/frontend/src/pages/drama/DramaListPage.tsx
new file mode 100644
index 0000000..6a97fe1
--- /dev/null
+++ b/frontend/src/pages/drama/DramaListPage.tsx
@@ -0,0 +1,225 @@
+/** 漫剧 Agent 首页:AI 生剧本 / 自由画布 + 我的项目 */
+import { useEffect, useState } from 'react'
+import { useNavigate } from 'react-router-dom'
+import AppShell from '../../components/layout/AppShell'
+import { dramaApi, type DramaProjectListItem } from '../../api/drama'
+import {
+ EPISODE_COUNT_PRESETS,
+ IMAGE_STYLE_OPTIONS,
+ type ImageStyleId,
+} from '../../lib/dramaImageStyles'
+import RequireAuth from './RequireAuth'
+import './drama.css'
+
+const CREATIVE_MIN_LENGTH = 20
+const CANVAS_PLACEHOLDER =
+ '自由画布创作项目,稍后在画布中完善故事与资产。'
+
+type AgentTab = 'ai' | 'canvas'
+
+export default function DramaListPage() {
+ return (
+ <RequireAuth>
+ <DramaListInner />
+ </RequireAuth>
+ )
+}
+
+// 渲染 Agent 首页内容
+function DramaListInner() {
+ const navigate = useNavigate()
+ /*
+ * tab 当前面板 Tab
+ * storyText AI 创意输入
+ * episodeCount 目标集数
+ * imageStyleId 画面风格
+ * items 我的项目列表
+ * busy 创建中
+ * canvasBusy 画布创建中
+ * error 错误文案
+ */
+ const [tab, setTab] = useState<AgentTab>('ai')
+ const [storyText, setStoryText] = useState('')
+ const [episodeCount, setEpisodeCount] = useState(12)
+ const [imageStyleId, setImageStyleId] = useState<ImageStyleId | ''>('')
+ const [items, setItems] = useState<DramaProjectListItem[]>([])
+ const [busy, setBusy] = useState(false)
+ const [canvasBusy, setCanvasBusy] = useState(false)
+ const [error, setError] = useState('')
+
+ // 加载项目列表
+ async function loadProjects() {
+ const rows = await dramaApi.listProjects()
+ setItems(rows)
+ }
+
+ useEffect(() => {
+ loadProjects().catch((err) => setError(err instanceof Error ? err.message : '加载失败'))
+ }, [])
+
+ // AI 立即生成:创建项目并进入大纲步骤
+ async function handleGenerate() {
+ const source = storyText.trim()
+ if (source.length < CREATIVE_MIN_LENGTH) {
+ setError(`故事内容至少 ${CREATIVE_MIN_LENGTH} 字`)
+ return
+ }
+ setBusy(true)
+ setError('')
+ try {
+ const project = await dramaApi.createProject({
+ source,
+ episode_count: episodeCount,
+ image_style_id: imageStyleId || undefined,
+ title: source.slice(0, 40),
+ })
+ navigate(`/drama/projects/${project.id}`, { state: { activeStep: 'outline' } })
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '创建失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ // 自由画布:创建占位创意项目并进入画布
+ async function handleEnterCanvas() {
+ if (canvasBusy) return
+ setCanvasBusy(true)
+ setError('')
+ try {
+ const project = await dramaApi.createProject({
+ source: CANVAS_PLACEHOLDER,
+ episode_count: 1,
+ title: '自由画布项目',
+ })
+ navigate(`/drama/projects/${project.id}/canvas`)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '创建画布项目失败')
+ } finally {
+ setCanvasBusy(false)
+ }
+ }
+
+ // 切换 Tab;画布 Tab 直接创建并跳转
+ function handleTabClick(next: AgentTab) {
+ if (next === 'canvas') {
+ void handleEnterCanvas()
+ return
+ }
+ setTab('ai')
+ }
+
+ const canGenerate = storyText.trim().length >= CREATIVE_MIN_LENGTH && !busy
+
+ return (
+ <AppShell active="drama">
+ <div className="drama-page drama-agent-page">
+ <header className="drama-agent-hero">
+ <h1>漫剧 Agent</h1>
+ </header>
+
+ <section className="drama-agent-panel">
+ <div className="drama-agent-tabs" role="tablist">
+ <button
+ type="button"
+ role="tab"
+ aria-selected={tab === 'ai'}
+ className={tab === 'ai' ? 'active' : ''}
+ onClick={() => handleTabClick('ai')}
+ >
+ AI 生剧本
+ </button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={false}
+ className=""
+ disabled={canvasBusy}
+ onClick={() => handleTabClick('canvas')}
+ >
+ {canvasBusy ? '创建中…' : '自由画布'}
+ </button>
+ </div>
+
+ {tab === 'ai' ? (
+ <div className="drama-agent-ai">
+ <textarea
+ value={storyText}
+ onChange={(e) => setStoryText(e.target.value)}
+ disabled={busy}
+ placeholder="在此输入你构想的故事内容。可以尝试输入这些要素:故事设定、主角特征、剧情脉络、最终结局等等"
+ rows={6}
+ />
+ <div className="drama-agent-ai-footer">
+ <div className="drama-agent-ai-options">
+ <label>
+ 风格
+ <select
+ value={imageStyleId}
+ onChange={(e) => setImageStyleId((e.target.value || '') as ImageStyleId | '')}
+ disabled={busy}
+ >
+ <option value="">风格库</option>
+ {IMAGE_STYLE_OPTIONS.map((opt) => (
+ <option key={opt.id} value={opt.id}>
+ {opt.label}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label>
+ 集数
+ <select
+ value={episodeCount}
+ onChange={(e) => setEpisodeCount(Number(e.target.value) || 12)}
+ disabled={busy}
+ >
+ {EPISODE_COUNT_PRESETS.map((n) => (
+ <option key={n} value={n}>
+ {n} 集
+ </option>
+ ))}
+ </select>
+ </label>
+ </div>
+ <button
+ type="button"
+ className="drama-btn-primary"
+ disabled={!canGenerate}
+ onClick={() => void handleGenerate()}
+ >
+ {busy ? '创建中…' : '立即生成'}
+ </button>
+ </div>
+ </div>
+ ) : null}
+ </section>
+
+ {error ? <p className="drama-error drama-agent-error">{error}</p> : null}
+
+ <section className="drama-project-section">
+ <h2>我的项目</h2>
+ {items.length === 0 ? <p className="drama-muted">暂无项目,先用上方面板生成一部吧</p> : null}
+ <div className="drama-project-grid">
+ {items.map((item) => (
+ <button
+ key={item.id}
+ type="button"
+ className="drama-project-card"
+ onClick={() => navigate(`/drama/projects/${item.id}`)}
+ >
+ <div className="drama-project-card-cover" aria-hidden>
+ <span className="drama-project-card-icon">▶</span>
+ </div>
+ <div className="drama-project-card-body">
+ <strong>{item.title}</strong>
+ <span className="drama-badge">{item.episode_count || 0} 集</span>
+ </div>
+ </button>
+ ))}
+ </div>
+ </section>
+ </div>
+ </AppShell>
+ )
+}
diff --git a/frontend/src/pages/drama/EpisodeEditAssetPanel.tsx b/frontend/src/pages/drama/EpisodeEditAssetPanel.tsx
new file mode 100644
index 0000000..a73cb41
--- /dev/null
+++ b/frontend/src/pages/drama/EpisodeEditAssetPanel.tsx
@@ -0,0 +1,100 @@
+/** 分集编辑:左侧资产栏(本集/全集 + 分类卡片) */
+import type { DramaAsset } from '../../api/drama'
+import {
+ ASSET_TABS,
+ normalizeAssetTab,
+ type AssetScope,
+ type AssetTab,
+} from './dramaEpisodeEditUtils'
+
+type Props = {
+ scope: AssetScope
+ tab: AssetTab | null
+ assets: DramaAsset[]
+ onScopeChange: (scope: AssetScope) => void
+ onTabChange: (tab: AssetTab | null) => void
+ onOpenCanvas: () => void
+ onMention: (asset: DramaAsset) => void
+}
+
+// 渲染分集编辑左侧资产栏
+export function EpisodeEditAssetPanel({
+ scope,
+ tab,
+ assets,
+ onScopeChange,
+ onTabChange,
+ onOpenCanvas,
+ onMention,
+}: Props) {
+ return (
+ <aside className="drama-ep-assets">
+ <div className="drama-ep-assets-top">
+ <div className="drama-ep-scope">
+ <button
+ type="button"
+ className={scope === 'episode' ? 'active' : ''}
+ onClick={() => onScopeChange('episode')}
+ >
+ 本集
+ </button>
+ <button
+ type="button"
+ className={scope === 'series' ? 'active' : ''}
+ onClick={() => onScopeChange('series')}
+ >
+ 全集
+ </button>
+ </div>
+ <button
+ type="button"
+ className="drama-ep-icon-btn solid"
+ aria-label="去画布添加素材"
+ onClick={onOpenCanvas}
+ >
+ +
+ </button>
+ </div>
+ <div className="drama-ep-asset-tabs">
+ {ASSET_TABS.map((item) => (
+ <button
+ key={item.key}
+ type="button"
+ className={tab === item.key ? 'active' : ''}
+ onClick={() => onTabChange(tab === item.key ? null : item.key)}
+ >
+ {item.label}
+ </button>
+ ))}
+ </div>
+ <div className="drama-ep-asset-grid">
+ {assets.length === 0 ? (
+ <p className="drama-ep-empty">
+ {scope === 'episode'
+ ? '本集暂无引用素材,可切换「全集」或点击资产插入脚本'
+ : '暂无素材,点击右上角前往画布添加'}
+ </p>
+ ) : (
+ assets.map((asset) => {
+ const cover = asset.cover || asset.url
+ const isScene = normalizeAssetTab(asset.type) === 'scene'
+ return (
+ <button
+ key={asset.id}
+ type="button"
+ className={`drama-ep-asset-card ${isScene ? 'scene' : ''}`}
+ onClick={() => onMention(asset)}
+ title="点击插入到当前分镜"
+ >
+ <div className="drama-ep-asset-thumb">
+ {cover ? <img src={cover} alt="" /> : <span>{(asset.name || '?')[0]}</span>}
+ </div>
+ <span className="drama-ep-asset-name">{asset.name || `资产 ${asset.id}`}</span>
+ </button>
+ )
+ })
+ )}
+ </div>
+ </aside>
+ )
+}
diff --git a/frontend/src/pages/drama/EpisodeEditPage.tsx b/frontend/src/pages/drama/EpisodeEditPage.tsx
new file mode 100644
index 0000000..532077c
--- /dev/null
+++ b/frontend/src/pages/drama/EpisodeEditPage.tsx
@@ -0,0 +1,492 @@
+/** 分集编辑:复刻原项目四栏布局(资产 / 脚本 / 预览 / 故事板) */
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useNavigate, useParams } from 'react-router-dom'
+import {
+ dramaApi,
+ type DramaAsset,
+ type DramaEpisode,
+ type DramaFragment,
+} from '../../api/drama'
+import { IMAGE_STYLE_OPTIONS, type ImageStyleId } from '../../lib/dramaImageStyles'
+import {
+ MODEL_OPTIONS,
+ RATIO_OPTIONS,
+ RES_OPTIONS,
+ extractAssetIds,
+ filterEpisodeAssets,
+ formatFragLabel,
+ type AssetScope,
+ type AssetTab,
+} from './dramaEpisodeEditUtils'
+import { EpisodeEditAssetPanel } from './EpisodeEditAssetPanel'
+import RequireAuth from './RequireAuth'
+import './drama.css'
+
+export default function EpisodeEditPage() {
+ return (
+ <RequireAuth>
+ <EpisodeEditInner />
+ </RequireAuth>
+ )
+}
+
+// 分集编辑页主体
+function EpisodeEditInner() {
+ const { projectId, episodeId } = useParams()
+ const pid = Number(projectId)
+ const eid = Number(episodeId)
+ const navigate = useNavigate()
+ /*
+ * episode 分集
+ * fragments 分镜
+ * assets 资产
+ * selectedIndex 当前分镜
+ * assetScope / assetTab 侧栏筛选
+ * editing 是否编辑模式
+ * videoStyleId / modelId / aspectRatio / resolution 生成参数(UI)
+ * busy / status / error 状态
+ */
+ const [episode, setEpisode] = useState<DramaEpisode | null>(null)
+ const [fragments, setFragments] = useState<DramaFragment[]>([])
+ const [assets, setAssets] = useState<DramaAsset[]>([])
+ const [selectedIndex, setSelectedIndex] = useState(0)
+ const [assetScope, setAssetScope] = useState<AssetScope>('episode')
+ const [assetTab, setAssetTab] = useState<AssetTab | null>('character')
+ const [editing, setEditing] = useState(false)
+ const [videoStyleId, setVideoStyleId] = useState<ImageStyleId | ''>('')
+ const [modelId, setModelId] = useState('seedance-2.5')
+ const [aspectRatio, setAspectRatio] = useState<(typeof RATIO_OPTIONS)[number]>('9:16')
+ const [resolution, setResolution] = useState<(typeof RES_OPTIONS)[number]>('480p')
+ const [busy, setBusy] = useState(false)
+ const [status, setStatus] = useState('')
+ const [error, setError] = useState('')
+ const pollRef = useRef<number | null>(null)
+ const videoRef = useRef<HTMLVideoElement | null>(null)
+
+ const selected = fragments[selectedIndex] || null
+ const selectedDuration = selected?.duration_sec ?? 8
+
+ const referencedIds = useMemo(() => {
+ const set = new Set<number>()
+ for (const f of fragments) {
+ for (const id of extractAssetIds(f.content || '')) set.add(id)
+ for (const id of f.asset_ids || []) set.add(id)
+ }
+ return set
+ }, [fragments])
+
+ const filteredAssets = useMemo(
+ () => filterEpisodeAssets(assets, assetScope, assetTab, referencedIds),
+ [assets, assetScope, assetTab, referencedIds],
+ )
+
+ // 重新加载分集
+ async function reload() {
+ const ep = await dramaApi.getEpisode(eid)
+ setEpisode(ep)
+ setFragments(ep.fragments || [])
+ if ((ep.fragments || []).length === 0) {
+ setFragments([
+ {
+ id: 0,
+ episode_id: eid,
+ sort_order: 0,
+ content: '',
+ cover: '',
+ video: '',
+ duration_sec: 8,
+ asset_ids: [],
+ },
+ ])
+ }
+ }
+
+ useEffect(() => {
+ if (!eid || !pid) return
+ reload().catch((err) => setError(err instanceof Error ? err.message : '加载失败'))
+ dramaApi
+ .listAssets(pid)
+ .then(setAssets)
+ .catch(() => setAssets([]))
+ return () => {
+ if (pollRef.current) window.clearInterval(pollRef.current)
+ }
+ }, [eid, pid])
+
+ // 更新当前分镜
+ function updateSelected(patch: Partial<DramaFragment>) {
+ setFragments((prev) =>
+ prev.map((f, i) => (i === selectedIndex ? { ...f, ...patch } : f)),
+ )
+ }
+
+ // 插入空白分镜
+ function insertFrag(at: number) {
+ setFragments((prev) => {
+ const next = [...prev]
+ next.splice(at, 0, {
+ id: 0,
+ episode_id: eid,
+ sort_order: at,
+ content: '',
+ cover: '',
+ video: '',
+ duration_sec: 8,
+ asset_ids: [],
+ })
+ return next
+ })
+ setSelectedIndex(at)
+ setEditing(true)
+ }
+
+ // 复制分镜
+ function duplicateFrag(index: number) {
+ const source = fragments[index]
+ if (!source) return
+ setFragments((prev) => {
+ const next = [...prev]
+ next.splice(index + 1, 0, {
+ ...source,
+ id: 0,
+ sort_order: index + 1,
+ })
+ return next
+ })
+ setSelectedIndex(index + 1)
+ }
+
+ // 删除分镜
+ function deleteFrag(index: number) {
+ if (fragments.length <= 1) return
+ setFragments((prev) => prev.filter((_, i) => i !== index))
+ setSelectedIndex((cur) => {
+ if (cur === index) return Math.max(0, index - 1)
+ if (cur > index) return cur - 1
+ return cur
+ })
+ }
+
+ // 保存全部分镜
+ async function save() {
+ setBusy(true)
+ setError('')
+ try {
+ const ep = await dramaApi.saveFragments(
+ eid,
+ fragments.map((f, i) => ({
+ sort_order: i,
+ content: f.content,
+ cover: f.cover,
+ video: f.video,
+ duration_sec: f.duration_sec,
+ asset_ids: f.asset_ids || [],
+ })),
+ )
+ setEpisode(ep)
+ setFragments(ep.fragments || [])
+ setStatus('已保存')
+ setEditing(false)
+ return ep
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '保存失败')
+ throw err
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ // 保存后生成并轮询
+ async function generate() {
+ if (!window.confirm('将基于当前分镜脚本生成视频,是否继续?')) return
+ setBusy(true)
+ setError('')
+ setStatus('保存并排队生成…')
+ try {
+ await save()
+ setBusy(true)
+ await dramaApi.generateEpisode(eid)
+ if (pollRef.current) window.clearInterval(pollRef.current)
+ pollRef.current = window.setInterval(async () => {
+ try {
+ const st = await dramaApi.generateStatus(eid)
+ setStatus(`完成 ${st.done}/${st.total} · 进行中 ${st.running} · 失败 ${st.failed}`)
+ if (st.running === 0 && st.done + st.failed >= st.total) {
+ if (pollRef.current) window.clearInterval(pollRef.current)
+ pollRef.current = null
+ await reload()
+ setBusy(false)
+ }
+ } catch {
+ if (pollRef.current) window.clearInterval(pollRef.current)
+ pollRef.current = null
+ setBusy(false)
+ }
+ }, 3000)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '生成失败')
+ setBusy(false)
+ }
+ }
+
+ // 返回分集步骤
+ function handleBack() {
+ navigate(`/drama/projects/${pid}`, { state: { returnStep: 'episodes' } })
+ }
+
+ // 点击资产插入 @ 引用
+ function mentionAsset(asset: DramaAsset) {
+ if (!selected) return
+ const mention = `@asset:${asset.id}`
+ const content = selected.content ? `${selected.content} ${mention}` : mention
+ const ids = Array.from(new Set([...(selected.asset_ids || []), asset.id]))
+ updateSelected({ content, asset_ids: ids })
+ setEditing(true)
+ }
+
+ if (!episode) {
+ return (
+ <div className="drama-ep-fullscreen drama-ep-center">
+ {error || '加载中…'}
+ </div>
+ )
+ }
+
+ const previewUrl = selected?.video || ''
+ const previewCover = selected?.cover || ''
+
+ return (
+ <div className="drama-ep-fullscreen">
+ <header className="drama-ep-header">
+ <div className="drama-ep-header-left">
+ <button type="button" className="drama-ep-icon-btn" aria-label="返回" onClick={handleBack}>
+ ‹
+ </button>
+ <h1>{episode.name}</h1>
+ </div>
+ <div className="drama-ep-header-controls">
+ <label className="drama-ep-select">
+ <span>风格</span>
+ <select
+ value={videoStyleId}
+ onChange={(e) => setVideoStyleId(e.target.value as ImageStyleId | '')}
+ >
+ <option value="">视频风格</option>
+ {IMAGE_STYLE_OPTIONS.map((opt) => (
+ <option key={opt.id} value={opt.id}>
+ {opt.label}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="drama-ep-select">
+ <span>模型</span>
+ <select value={modelId} onChange={(e) => setModelId(e.target.value)}>
+ {MODEL_OPTIONS.map((opt) => (
+ <option key={opt.id} value={opt.id}>
+ {opt.label}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="drama-ep-select">
+ <span>比例</span>
+ <select
+ value={aspectRatio}
+ onChange={(e) => setAspectRatio(e.target.value as (typeof RATIO_OPTIONS)[number])}
+ >
+ {RATIO_OPTIONS.map((r) => (
+ <option key={r} value={r}>
+ {r}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="drama-ep-select">
+ <span>分辨率</span>
+ <select
+ value={resolution}
+ onChange={(e) => setResolution(e.target.value as (typeof RES_OPTIONS)[number])}
+ >
+ {RES_OPTIONS.map((r) => (
+ <option key={r} value={r}>
+ {r}
+ </option>
+ ))}
+ </select>
+ </label>
+ </div>
+ </header>
+
+ {(status || error) && (
+ <div className="drama-ep-banner">
+ {error ? <span className="drama-ep-banner-error">{error}</span> : null}
+ {!error && status ? <span>{status}</span> : null}
+ </div>
+ )}
+
+ <div className="drama-ep-body">
+ <EpisodeEditAssetPanel
+ scope={assetScope}
+ tab={assetTab}
+ assets={filteredAssets}
+ onScopeChange={setAssetScope}
+ onTabChange={setAssetTab}
+ onOpenCanvas={() => navigate(`/drama/projects/${pid}/canvas`)}
+ onMention={mentionAsset}
+ />
+
+ <section className="drama-ep-editor">
+ <div className="drama-ep-editor-head">
+ <div>
+ <strong>{formatFragLabel(selectedIndex, selectedDuration)}</strong>
+ <p>键入 @asset:id 可引用资产;脚本可含旁白、字幕与 BGM 说明</p>
+ </div>
+ <label className="drama-ep-duration">
+ 时长
+ <input
+ type="number"
+ min={4}
+ max={30}
+ value={selectedDuration}
+ disabled={!editing && !selected}
+ onChange={(e) =>
+ updateSelected({ duration_sec: Number(e.target.value) || 8 })
+ }
+ />
+ s
+ </label>
+ </div>
+
+ <div className={`drama-ep-editor-box ${editing ? 'editing' : ''}`}>
+ <textarea
+ value={selected?.content || ''}
+ readOnly={!editing}
+ rows={16}
+ placeholder="输入画面描述、对白、旁白或背景音乐提示…"
+ onChange={(e) => updateSelected({ content: e.target.value })}
+ />
+ </div>
+
+ <div className="drama-ep-editor-actions">
+ {editing ? (
+ <>
+ <button
+ type="button"
+ className="drama-ep-btn-ghost"
+ disabled={busy}
+ onClick={() => {
+ setEditing(false)
+ void reload()
+ }}
+ >
+ 取消
+ </button>
+ <button
+ type="button"
+ className="drama-ep-btn-dark"
+ disabled={busy}
+ onClick={() => void save()}
+ >
+ {busy ? '保存中…' : '保存'}
+ </button>
+ </>
+ ) : (
+ <>
+ <button
+ type="button"
+ className="drama-ep-btn-ghost"
+ disabled={!selected}
+ onClick={() => setEditing(true)}
+ >
+ 编辑
+ </button>
+ <button
+ type="button"
+ className="drama-ep-btn-dark"
+ disabled={busy || !selected}
+ onClick={() => void generate()}
+ >
+ {busy ? '处理中…' : '生成'}
+ </button>
+ </>
+ )}
+ </div>
+ </section>
+
+ <aside className="drama-ep-preview">
+ {!selected ? (
+ <p className="drama-ep-empty">请选择底部分镜</p>
+ ) : (
+ <div className={`drama-ep-player ratio-${aspectRatio.replace(':', 'x')}`}>
+ {previewUrl ? (
+ <video
+ ref={videoRef}
+ key={previewUrl}
+ src={previewUrl}
+ poster={previewCover || undefined}
+ controls
+ playsInline
+ />
+ ) : previewCover ? (
+ <img src={previewCover} alt="" />
+ ) : (
+ <div className="drama-ep-player-placeholder">
+ <span>暂无预览</span>
+ <small>生成后将在此播放</small>
+ </div>
+ )}
+ </div>
+ )}
+ </aside>
+ </div>
+
+ <footer className="drama-ep-storyboard">
+ <div className="drama-ep-storyboard-row">
+ <button
+ type="button"
+ className="drama-ep-insert"
+ aria-label="在开头插入分镜"
+ onClick={() => insertFrag(0)}
+ >
+ +
+ </button>
+ {fragments.map((frag, index) => (
+ <div key={`${frag.id}-${index}`} className="drama-ep-clip-wrap">
+ <button
+ type="button"
+ className={`drama-ep-clip ${selectedIndex === index ? 'active' : ''}`}
+ onClick={() => setSelectedIndex(index)}
+ >
+ {frag.cover ? (
+ <img src={frag.cover} alt="" />
+ ) : frag.video ? (
+ <video src={frag.video} muted />
+ ) : (
+ <span className="drama-ep-clip-empty">+</span>
+ )}
+ <em>{formatFragLabel(index, frag.duration_sec)}</em>
+ </button>
+ <div className="drama-ep-clip-ops">
+ <button type="button" aria-label="插入" onClick={() => insertFrag(index + 1)}>
+ +
+ </button>
+ <button type="button" aria-label="复制" onClick={() => duplicateFrag(index)}>
+ ⧉
+ </button>
+ <button
+ type="button"
+ aria-label="删除"
+ disabled={fragments.length <= 1}
+ onClick={() => deleteFrag(index)}
+ >
+ ⌫
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ </footer>
+ </div>
+ )
+}
diff --git a/frontend/src/pages/drama/EpisodesStep.tsx b/frontend/src/pages/drama/EpisodesStep.tsx
new file mode 100644
index 0000000..89ad4ee
--- /dev/null
+++ b/frontend/src/pages/drama/EpisodesStep.tsx
@@ -0,0 +1,112 @@
+/** 分集视频步骤:进入时按剧本切分镜,支持强制重切 */
+import { useEffect, useRef, useState } from 'react'
+import { useNavigate } from 'react-router-dom'
+import { dramaApi, type DramaEpisode } from '../../api/drama'
+
+type EpisodesStepProps = {
+ projectId: number
+ onError: (m: string) => void
+}
+
+// 渲染分集视频步骤
+export function EpisodesStep({ projectId, onError }: EpisodesStepProps) {
+ const navigate = useNavigate()
+ /*
+ * episodes 分集列表
+ * loading 加载中
+ * reseeding 强制重切中
+ * seeded 是否已执行过进页 seed
+ */
+ const [episodes, setEpisodes] = useState<DramaEpisode[]>([])
+ const [loading, setLoading] = useState(true)
+ const [reseeding, setReseeding] = useState(false)
+ const seeded = useRef(false)
+
+ // 拉取 / 切分分镜
+ async function loadEpisodes(force = false) {
+ const rows = await dramaApi.seedEpisodes(projectId, force)
+ setEpisodes(rows)
+ return rows
+ }
+
+ useEffect(() => {
+ async function enter() {
+ setLoading(true)
+ try {
+ if (!seeded.current) {
+ seeded.current = true
+ // 进页自动检测旧场记分镜并重切(后端 force=false 时也会 auto-replan)
+ await loadEpisodes(false)
+ } else {
+ setEpisodes(await dramaApi.listEpisodes(projectId))
+ }
+ } catch (err) {
+ onError(err instanceof Error ? err.message : '分集加载失败')
+ try {
+ setEpisodes(await dramaApi.listEpisodes(projectId))
+ } catch {
+ /* ignore */
+ }
+ } finally {
+ setLoading(false)
+ }
+ }
+ void enter()
+ }, [projectId, onError])
+
+ // 按最新分集剧本强制重切全部分镜
+ async function handleReseed() {
+ if (reseeding) return
+ if (!window.confirm('将按最新分集剧本重新切分镜(已生成视频的分集也会重写),是否继续?')) {
+ return
+ }
+ setReseeding(true)
+ try {
+ await loadEpisodes(true)
+ } catch (err) {
+ onError(err instanceof Error ? err.message : '重新切分失败')
+ } finally {
+ setReseeding(false)
+ }
+ }
+
+ return (
+ <div className="drama-episodes-step">
+ <div className="drama-episodes-head">
+ <div>
+ <h2>分集视频</h2>
+ <p className="drama-muted">共 {episodes.length} 集</p>
+ </div>
+ <button
+ type="button"
+ className="drama-btn-primary"
+ disabled={loading || reseeding}
+ onClick={() => void handleReseed()}
+ >
+ {reseeding ? '切分中…' : '按剧本重切分镜'}
+ </button>
+ </div>
+ {loading ? <p className="drama-muted">正在创建分集与分镜…</p> : null}
+ <div className="drama-episode-cards">
+ {episodes.map((ep) => (
+ <article key={ep.id} className="drama-episode-card">
+ <div className="drama-episode-card-thumb" aria-hidden>
+ ▶
+ </div>
+ <div className="drama-episode-card-body">
+ <strong>{ep.name}</strong>
+ <span>{ep.fragments?.length || 0} 个分镜</span>
+ </div>
+ <button
+ type="button"
+ className="drama-btn-primary"
+ onClick={() => navigate(`/drama/projects/${projectId}/episodes/${ep.id}`)}
+ >
+ 编辑
+ </button>
+ </article>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/pages/drama/OutlineStep.tsx b/frontend/src/pages/drama/OutlineStep.tsx
new file mode 100644
index 0000000..8778e83
--- /dev/null
+++ b/frontend/src/pages/drama/OutlineStep.tsx
@@ -0,0 +1,547 @@
+/** 剧情大纲步骤:自动摘要 + 分集剧本流水线 */
+import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
+import {
+ dramaApi,
+ type DramaProject,
+ type DramaScript,
+} from '../../api/drama'
+import { IMAGE_STYLE_OPTIONS, type ImageStyleId } from '../../lib/dramaImageStyles'
+import {
+ getEpisodeContentStatus,
+ getImageStyleId,
+ getSummaryStatus,
+ parseEpisodeBodies,
+} from './dramaWorkspaceUtils'
+
+type OutlineSectionKey = 'source' | 'summary' | 'episodes'
+
+export type OutlineStepProps = {
+ projectId: number
+ project: DramaProject
+ onProjectChange: (p: DramaProject) => void
+ onOutlineReadyChange: (ready: boolean) => void
+ onError: (msg: string) => void
+}
+
+// 渲染剧情大纲步骤
+export function OutlineStep({
+ projectId,
+ project,
+ onProjectChange,
+ onOutlineReadyChange,
+ onError,
+}: OutlineStepProps) {
+ const [script, setScript] = useState<DramaScript | null>(project.script || null)
+ const [expanded, setExpanded] = useState<Set<OutlineSectionKey>>(() => new Set())
+ const [expandedEpisodes, setExpandedEpisodes] = useState<Set<number>>(() => new Set())
+ const [activeEpisodeNumber, setActiveEpisodeNumber] = useState<number | undefined>()
+ const [summaryGenerating, setSummaryGenerating] = useState(false)
+ const [episodeGenerating, setEpisodeGenerating] = useState(false)
+ const [summaryError, setSummaryError] = useState('')
+ const [episodeError, setEpisodeError] = useState('')
+ const [progress, setProgress] = useState({ done: 0, total: 0 })
+ const pipelineRef = useRef(0)
+
+ const summary = (script?.summary || null) as Record<string, unknown> | null
+ const summaryStatus = getSummaryStatus(script)
+ const episodeStatus = getEpisodeContentStatus(script)
+ const episodeBodies = parseEpisodeBodies(script)
+ const episodeCount =
+ Number(
+ summary?.episodeCount ||
+ (script?.params || {}).episode_count ||
+ project.params?.episode_count,
+ ) || 0
+ const imageStyleId = getImageStyleId(script, project)
+
+ const directoryEpisodes = useMemo(() => {
+ // 按目标集数铺满目录;已生成的用正文标题,未生成的显示占位
+ const byNumber = new Map(
+ episodeBodies.map((ep, i) => {
+ const num = ep.episodeNumber || i + 1
+ return [num, ep.title || `第 ${num} 集`] as const
+ }),
+ )
+ const total = Math.max(episodeCount, episodeBodies.length, 0)
+ if (total <= 0) return []
+ return Array.from({ length: total }, (_, i) => {
+ const episodeNumber = i + 1
+ return {
+ episodeNumber,
+ title: byNumber.get(episodeNumber) || `第 ${episodeNumber} 集`,
+ }
+ })
+ }, [episodeBodies, episodeCount])
+
+ // 切换折叠区块
+ function toggleSection(key: OutlineSectionKey) {
+ setExpanded((prev) => {
+ const next = new Set(prev)
+ if (next.has(key)) next.delete(key)
+ else next.add(key)
+ return next
+ })
+ }
+
+ // 目录点击:展开分集剧本并滚动
+ function selectEpisode(episodeNumber: number) {
+ setExpanded((prev) => new Set(prev).add('episodes'))
+ setExpandedEpisodes((prev) => new Set(prev).add(episodeNumber))
+ setActiveEpisodeNumber(episodeNumber)
+ window.requestAnimationFrame(() => {
+ document.getElementById(`outline-episode-${episodeNumber}`)?.scrollIntoView({
+ behavior: 'smooth',
+ block: 'start',
+ })
+ })
+ }
+
+ // 轮询剧本直到条件满足(worker 异步任务)
+ async function pollScriptUntil(
+ predicate: (s: DramaScript) => boolean,
+ runToken?: number,
+ ): Promise<DramaScript | null> {
+ const started = Date.now()
+ while (Date.now() - started < 45 * 60 * 1000) {
+ if (runToken !== undefined && runToken !== pipelineRef.current) return null
+ const s = await dramaApi.getScript(projectId)
+ setScript(s)
+ const prog = (s.params || {}).episode_content_progress as
+ | { done?: number; total?: number }
+ | undefined
+ if (prog && (prog.total || prog.done)) {
+ setProgress({
+ done: Number(prog.done) || 0,
+ total: Number(prog.total) || 0,
+ })
+ }
+ if (predicate(s)) return s
+ await new Promise((r) => setTimeout(r, 2000))
+ }
+ throw new Error('等待生成超时,请刷新后重试')
+ }
+
+ // 入队并等待剧本摘要完成
+ async function runSummary(runToken?: number) {
+ setSummaryGenerating(true)
+ setSummaryError('')
+ try {
+ const res = await dramaApi.scriptSummary({ project_id: projectId })
+ setScript(res.script)
+ const finished = await pollScriptUntil((s) => {
+ const st = getSummaryStatus(s)
+ return st === 'completed' || st === 'failed'
+ }, runToken)
+ if (!finished) return null
+ if (getSummaryStatus(finished) === 'failed') {
+ const msg =
+ String((finished.params || {}).summary_error || '') || '剧本摘要生成失败'
+ setSummaryError(msg)
+ onError(msg)
+ throw new Error(msg)
+ }
+ const p = await dramaApi.getProject(projectId)
+ onProjectChange(p)
+ return finished
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : '剧本摘要生成失败'
+ setSummaryError(msg)
+ onError(msg)
+ throw err
+ } finally {
+ setSummaryGenerating(false)
+ }
+ }
+
+ // 入队并轮询分集剧本直到完成
+ async function runEpisodeScripts(runToken?: number, force = false) {
+ setEpisodeGenerating(true)
+ setEpisodeError('')
+ try {
+ const res = await dramaApi.episodeScript({
+ project_id: projectId,
+ batch_size: 1,
+ force,
+ })
+ setScript(res.script)
+ setProgress({ done: res.total_generated, total: res.total_target })
+ const finished = await pollScriptUntil((s) => {
+ const st = getEpisodeContentStatus(s)
+ return st === 'completed' || st === 'failed'
+ }, runToken)
+ if (!finished) return
+ if (getEpisodeContentStatus(finished) === 'failed') {
+ const msg =
+ String((finished.params || {}).episode_content_error || '') ||
+ '分集剧本生成失败'
+ setEpisodeError(msg)
+ onError(msg)
+ onOutlineReadyChange(false)
+ return
+ }
+ onOutlineReadyChange(true)
+ const p = await dramaApi.getProject(projectId)
+ onProjectChange(p)
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : '分集剧本生成失败'
+ setEpisodeError(msg)
+ onError(msg)
+ onOutlineReadyChange(false)
+ } finally {
+ setEpisodeGenerating(false)
+ }
+ }
+
+ // 手动强制重写全部分集正文
+ async function handleRegenerateEpisodes() {
+ if (episodeGenerating) return
+ if (!window.confirm('将清空当前分集正文并按新提示词重新生成,是否继续?')) return
+ onOutlineReadyChange(false)
+ await runEpisodeScripts(undefined, true)
+ }
+
+ // 挂载自动流水线:无摘要 → 摘要 → 分集(未满目标集数会续跑;已在 worker 中则只轮询)
+ useEffect(() => {
+ const token = ++pipelineRef.current
+ async function pipeline() {
+ let current = script
+ const status = getSummaryStatus(current)
+ if (!current?.summary && status !== 'completed') {
+ try {
+ if (status === 'generating') {
+ setSummaryGenerating(true)
+ current = await pollScriptUntil((s) => {
+ const st = getSummaryStatus(s)
+ return st === 'completed' || st === 'failed'
+ }, token)
+ setSummaryGenerating(false)
+ if (!current || getSummaryStatus(current) === 'failed') {
+ const msg =
+ String((current?.params || {}).summary_error || '') || '剧本摘要生成失败'
+ setSummaryError(msg)
+ onError(msg)
+ return
+ }
+ } else {
+ current = await runSummary(token)
+ }
+ } catch {
+ return
+ }
+ if (!current || token !== pipelineRef.current) return
+ }
+ const target =
+ Number(
+ (current?.summary as Record<string, unknown> | null)?.episodeCount ||
+ (current?.params || {}).episode_count ||
+ project.params?.episode_count,
+ ) || 0
+ const bodies = parseEpisodeBodies(current)
+ const epStatus = getEpisodeContentStatus(current)
+ // 与后端阈值对齐:过短正文视为未完成,刷新后会续写/重写
+ const substantial = bodies.filter(
+ (b) => (b.body || '').replace(/\s/g, '').length >= 500,
+ ).length
+ const complete =
+ epStatus === 'completed' && target > 0 && substantial >= target
+ if (complete) {
+ onOutlineReadyChange(true)
+ return
+ }
+ if (current?.summary || getSummaryStatus(current) === 'completed') {
+ if (epStatus === 'generating') {
+ setEpisodeGenerating(true)
+ const finished = await pollScriptUntil((s) => {
+ const st = getEpisodeContentStatus(s)
+ return st === 'completed' || st === 'failed'
+ }, token)
+ setEpisodeGenerating(false)
+ if (!finished) return
+ if (getEpisodeContentStatus(finished) === 'failed') {
+ const msg =
+ String((finished.params || {}).episode_content_error || '') ||
+ '分集剧本生成失败'
+ setEpisodeError(msg)
+ onError(msg)
+ onOutlineReadyChange(false)
+ return
+ }
+ onOutlineReadyChange(true)
+ const p = await dramaApi.getProject(projectId)
+ onProjectChange(p)
+ return
+ }
+ await runEpisodeScripts(token)
+ }
+ }
+ void pipeline()
+ return () => {
+ pipelineRef.current += 1
+ onOutlineReadyChange(false)
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [projectId])
+
+ // 更新画面风格
+ async function handleStyleChange(styleId: string) {
+ try {
+ const updated = await dramaApi.updateScript(projectId, {
+ image_style_id: styleId || undefined,
+ })
+ setScript(updated)
+ const p = await dramaApi.getProject(projectId)
+ onProjectChange(p)
+ } catch (err) {
+ onError(err instanceof Error ? err.message : '风格更新失败')
+ }
+ }
+
+ const characters = Array.isArray(summary?.characters)
+ ? (summary.characters as Array<Record<string, unknown>>)
+ : []
+
+ return (
+ <div className="drama-outline">
+ {directoryEpisodes.length > 0 ? (
+ <aside className="drama-episode-dir">
+ <h3>分集目录</h3>
+ <ul>
+ {directoryEpisodes.map((ep) => (
+ <li key={ep.episodeNumber}>
+ <button
+ type="button"
+ className={activeEpisodeNumber === ep.episodeNumber ? 'active' : ''}
+ onClick={() => selectEpisode(ep.episodeNumber)}
+ >
+ <span>第 {ep.episodeNumber} 集</span>
+ <small>{ep.title}</small>
+ </button>
+ </li>
+ ))}
+ </ul>
+ </aside>
+ ) : null}
+
+ <div className="drama-outline-main">
+ <div className="drama-outline-toolbar">
+ <h2>{episodeCount ? `共 ${episodeCount} 集` : '共 — 集'}</h2>
+ <label className="drama-style-select">
+ 项目风格
+ <select
+ value={imageStyleId}
+ onChange={(e) => void handleStyleChange(e.target.value as ImageStyleId | '')}
+ >
+ <option value="">未选择</option>
+ {IMAGE_STYLE_OPTIONS.map((opt) => (
+ <option key={opt.id} value={opt.id}>
+ {opt.label}
+ </option>
+ ))}
+ </select>
+ </label>
+ </div>
+
+ <div className="drama-accordions">
+ <Accordion
+ title="原始创意"
+ open={expanded.has('source')}
+ onToggle={() => toggleSection('source')}
+ >
+ <p className="drama-pre">{script?.source?.trim() || '暂无原始创意'}</p>
+ </Accordion>
+
+ <Accordion
+ title="剧本摘要"
+ open={expanded.has('summary')}
+ onToggle={() => toggleSection('summary')}
+ >
+ {summaryGenerating || summaryStatus === 'generating' ? (
+ <p className="drama-loader">剧本摘要生成中,请稍候…</p>
+ ) : null}
+ {summaryError || summaryStatus === 'failed' ? (
+ <div className="drama-retry-block">
+ <p className="drama-error">{summaryError || '剧本摘要生成失败'}</p>
+ <button type="button" className="drama-btn-primary" onClick={() => void runSummary()}>
+ 重新生成
+ </button>
+ </div>
+ ) : null}
+ {summary && summaryStatus === 'completed' ? (
+ <div className="drama-summary-structured">
+ <SummaryField label="自定义集数" value={String(summary.episodeCount ?? '')} />
+ <SummaryField label="故事类型" value={String(summary.storyType || '')} />
+ <SummaryField label="目标受众" value={String(summary.targetAudience || '')} />
+ <SummaryField label="核心梗" value={String(summary.coreHook || '')} />
+ <SummaryField label="一句话故事" value={String(summary.oneLineStory || '')} />
+ <section>
+ <h4>人物小传</h4>
+ <div className="drama-character-list">
+ {characters.map((ch, i) => (
+ <article key={`${ch.name}-${i}`} className="drama-character-card">
+ <h5>
+ {String(ch.name || '角色')}
+ {ch.title ? `,${String(ch.title)}` : ''}
+ </h5>
+ {(
+ [
+ ['角色类型', 'roleType'],
+ ['视觉形象', 'visualImage'],
+ ['核心标签', 'coreTags'],
+ ['身份背景', 'identityBackground'],
+ ['性格特点', 'personality'],
+ ] as const
+ ).map(([label, key]) =>
+ ch[key] ? (
+ <div key={key} className="drama-character-field">
+ <span>{label}</span>
+ <p>{String(ch[key])}</p>
+ </div>
+ ) : null,
+ )}
+ </article>
+ ))}
+ </div>
+ </section>
+ <SummaryField label="故事梗概" value={String(summary.synopsis || '')} />
+ </div>
+ ) : null}
+ {!summaryGenerating && summaryStatus !== 'completed' && summaryStatus !== 'failed' ? (
+ <p className="drama-muted">等待生成剧本摘要…</p>
+ ) : null}
+ </Accordion>
+
+ <Accordion
+ title="分集剧本"
+ open={expanded.has('episodes')}
+ onToggle={() => toggleSection('episodes')}
+ action={
+ summaryStatus === 'completed' || summary ? (
+ <button
+ type="button"
+ className="drama-regen-btn"
+ disabled={episodeGenerating || summaryGenerating}
+ onClick={(e) => {
+ e.stopPropagation()
+ void handleRegenerateEpisodes()
+ }}
+ >
+ {episodeGenerating ? '生成中…' : '重新生成'}
+ </button>
+ ) : null
+ }
+ >
+ {summaryStatus !== 'completed' && !summary ? (
+ <p className="drama-muted">请先完成剧本摘要</p>
+ ) : null}
+ {episodeGenerating || episodeStatus === 'generating' ? (
+ <p className="drama-loader">
+ 分集剧本生成中
+ {progress.total > 0 ? `(${progress.done}/${progress.total} 集)` : '…'}
+ </p>
+ ) : null}
+ {episodeError || episodeStatus === 'failed' ? (
+ <div className="drama-retry-block">
+ <p className="drama-error">{episodeError || '分集剧本生成失败'}</p>
+ <button
+ type="button"
+ className="drama-btn-primary"
+ disabled={episodeGenerating}
+ onClick={() => void handleRegenerateEpisodes()}
+ >
+ 重新生成
+ </button>
+ </div>
+ ) : null}
+ {!episodeGenerating &&
+ episodeStatus !== 'failed' &&
+ (summaryStatus === 'completed' || summary) &&
+ episodeBodies.length > 0 ? (
+ <div className="drama-regen-inline">
+ <button
+ type="button"
+ className="drama-btn-primary"
+ onClick={() => void handleRegenerateEpisodes()}
+ >
+ 重新生成分集剧本
+ </button>
+ <span className="drama-muted">正文过短或不满意时,可清空后按新提示词重写</span>
+ </div>
+ ) : null}
+ {episodeBodies.length > 0 ? (
+ <div className="drama-episode-bodies">
+ {episodeBodies
+ .slice()
+ .sort((a, b) => (a.episodeNumber || 0) - (b.episodeNumber || 0))
+ .map((ep) => {
+ const num = ep.episodeNumber || 0
+ const open = expandedEpisodes.has(num)
+ return (
+ <div key={num} id={`outline-episode-${num}`} className="drama-episode-body-item">
+ <button
+ type="button"
+ className="drama-episode-body-toggle"
+ onClick={() =>
+ setExpandedEpisodes((prev) => {
+ const next = new Set(prev)
+ if (next.has(num)) next.delete(num)
+ else next.add(num)
+ return next
+ })
+ }
+ >
+ <span>
+ 第 {num} 集 · {ep.title || ''}
+ </span>
+ <span>{open ? '▾' : '▸'}</span>
+ </button>
+ {open ? <pre className="drama-pre">{ep.body || ''}</pre> : null}
+ </div>
+ )
+ })}
+ </div>
+ ) : null}
+ </Accordion>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+// 折叠面板
+function Accordion({
+ title,
+ open,
+ onToggle,
+ action,
+ children,
+}: {
+ title: string
+ open: boolean
+ onToggle: () => void
+ action?: ReactNode
+ children: ReactNode
+}) {
+ return (
+ <div className={`drama-accordion ${open ? 'open' : ''}`}>
+ <div className="drama-accordion-head-row">
+ <button type="button" className="drama-accordion-head" onClick={onToggle}>
+ <span>{title}</span>
+ <span aria-hidden>{open ? '▾' : '▸'}</span>
+ </button>
+ {action}
+ </div>
+ {open ? <div className="drama-accordion-body">{children}</div> : null}
+ </div>
+ )
+}
+
+// 摘要字段块
+function SummaryField({ label, value }: { label: string; value: string }) {
+ if (!value) return null
+ return (
+ <section className="drama-summary-field">
+ <h4>{label}</h4>
+ <p className="drama-pre">{value}</p>
+ </section>
+ )
+}
diff --git a/frontend/src/pages/drama/ProjectWorkspacePage.tsx b/frontend/src/pages/drama/ProjectWorkspacePage.tsx
new file mode 100644
index 0000000..a94321a
--- /dev/null
+++ b/frontend/src/pages/drama/ProjectWorkspacePage.tsx
@@ -0,0 +1,232 @@
+/** 漫剧项目工作流:剧情大纲 / 资产库 / 分集视频 */
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useLocation, useNavigate, useParams } from 'react-router-dom'
+import AppShell from '../../components/layout/AppShell'
+import { dramaApi, type DramaProject } from '../../api/drama'
+import {
+ buildProjectSteps,
+ getInitialProjectStep,
+ getNextProjectStep,
+ type ProjectStepKey,
+} from '../../lib/dramaProjectSteps'
+import { AssetsStep } from './AssetsStep'
+import { EpisodesStep } from './EpisodesStep'
+import { OutlineStep } from './OutlineStep'
+import RequireAuth from './RequireAuth'
+import './drama.css'
+
+export default function ProjectWorkspacePage() {
+ return (
+ <RequireAuth>
+ <WorkspaceInner />
+ </RequireAuth>
+ )
+}
+
+// 项目工作台主体
+function WorkspaceInner() {
+ const { projectId } = useParams()
+ const id = Number(projectId)
+ const navigate = useNavigate()
+ const location = useLocation()
+ /*
+ * project 项目详情
+ * activeStep 当前步骤
+ * outlineReady 大纲是否完成
+ * titleDraft 可编辑标题
+ * editingTitle 是否在编辑标题
+ * loading / error 加载态
+ */
+ const [project, setProject] = useState<DramaProject | null>(null)
+ const [activeStep, setActiveStep] = useState<ProjectStepKey>('outline')
+ const [outlineReady, setOutlineReady] = useState(false)
+ const [titleDraft, setTitleDraft] = useState('')
+ const [editingTitle, setEditingTitle] = useState(false)
+ const [loading, setLoading] = useState(true)
+ const [error, setError] = useState('')
+ const locationApplied = useRef(false)
+
+ const hasScript = Boolean(project?.script)
+ const steps = useMemo(() => buildProjectSteps(hasScript), [hasScript])
+ const nextStep = useMemo(() => getNextProjectStep(steps, activeStep), [steps, activeStep])
+ const canGoNext =
+ nextStep !== null && (activeStep === 'outline' ? outlineReady : activeStep === 'assets')
+
+ // 加载项目
+ async function reload() {
+ const p = await dramaApi.getProject(id)
+ setProject(p)
+ setTitleDraft(p.title)
+ return p
+ }
+
+ useEffect(() => {
+ if (!Number.isFinite(id) || id <= 0) return
+ setLoading(true)
+ reload()
+ .then((p) => {
+ if (!locationApplied.current) {
+ const state = location.state as
+ | { activeStep?: ProjectStepKey; returnStep?: ProjectStepKey }
+ | null
+ if (state?.activeStep) setActiveStep(state.activeStep)
+ else if (state?.returnStep) setActiveStep(state.returnStep)
+ else setActiveStep(getInitialProjectStep(Boolean(p.script)))
+ locationApplied.current = true
+ }
+ })
+ .catch((err) => setError(err instanceof Error ? err.message : '加载失败'))
+ .finally(() => setLoading(false))
+ }, [id])
+
+ useEffect(() => {
+ const state = location.state as
+ | { activeStep?: ProjectStepKey; returnStep?: ProjectStepKey }
+ | null
+ if (state?.activeStep) setActiveStep(state.activeStep)
+ else if (state?.returnStep) setActiveStep(state.returnStep)
+ }, [location.state])
+
+ // 保存标题
+ async function saveTitle() {
+ const next = titleDraft.trim()
+ if (!next || !project) {
+ setEditingTitle(false)
+ setTitleDraft(project?.title || '')
+ return
+ }
+ try {
+ const updated = await dramaApi.updateProject(id, { title: next })
+ setProject(updated)
+ setTitleDraft(updated.title)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '标题保存失败')
+ } finally {
+ setEditingTitle(false)
+ }
+ }
+
+ if (!Number.isFinite(id) || id <= 0) {
+ return (
+ <AppShell active="drama" flush>
+ <div className="drama-workspace-status">项目 ID 无效</div>
+ </AppShell>
+ )
+ }
+
+ if (loading) {
+ return (
+ <AppShell active="drama" flush>
+ <div className="drama-workspace-status">加载中…</div>
+ </AppShell>
+ )
+ }
+
+ if (error && !project) {
+ return (
+ <AppShell active="drama" flush>
+ <div className="drama-workspace-status drama-error">{error}</div>
+ </AppShell>
+ )
+ }
+
+ if (!project) {
+ return (
+ <AppShell active="drama" flush>
+ <div className="drama-workspace-status">项目不存在</div>
+ </AppShell>
+ )
+ }
+
+ return (
+ <AppShell active="drama" flush wide>
+ <div className="drama-workspace">
+ <header className="drama-workspace-top">
+ <div className="drama-workspace-top-left">
+ <button
+ type="button"
+ className="drama-icon-btn"
+ aria-label="返回"
+ onClick={() => navigate('/drama/dramas')}
+ >
+ ←
+ </button>
+ {editingTitle ? (
+ <input
+ className="drama-title-input"
+ value={titleDraft}
+ autoFocus
+ onChange={(e) => setTitleDraft(e.target.value)}
+ onBlur={() => void saveTitle()}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') void saveTitle()
+ if (e.key === 'Escape') {
+ setTitleDraft(project.title)
+ setEditingTitle(false)
+ }
+ }}
+ />
+ ) : (
+ <button type="button" className="drama-title-display" onClick={() => setEditingTitle(true)}>
+ {project.title}
+ </button>
+ )}
+ </div>
+
+ <nav className="drama-step-bar" aria-label="项目步骤">
+ {steps.map((step, index) => {
+ const isActive = step.key === activeStep
+ const activeIndex = steps.findIndex((s) => s.key === activeStep)
+ const isCompleted = activeIndex > index
+ return (
+ <div key={step.key} className="drama-step-bar-item">
+ <button
+ type="button"
+ className={isActive ? 'active' : isCompleted ? 'done' : ''}
+ onClick={() => setActiveStep(step.key)}
+ >
+ <span className="drama-step-num">{step.order}</span>
+ <span>{step.label}</span>
+ </button>
+ {index < steps.length - 1 ? <span className="drama-step-sep">›</span> : null}
+ </div>
+ )
+ })}
+ </nav>
+
+ <div className="drama-workspace-top-right">
+ {nextStep ? (
+ <button
+ type="button"
+ className="drama-next-btn"
+ disabled={!canGoNext}
+ onClick={() => setActiveStep(nextStep)}
+ >
+ 下一步
+ </button>
+ ) : null}
+ </div>
+ </header>
+
+ {error ? <p className="drama-error drama-workspace-banner">{error}</p> : null}
+
+ <main className="drama-workspace-main">
+ {activeStep === 'outline' ? (
+ <OutlineStep
+ projectId={id}
+ project={project}
+ onProjectChange={(p) => {
+ setProject(p)
+ setTitleDraft(p.title)
+ }}
+ onOutlineReadyChange={setOutlineReady}
+ onError={setError}
+ />
+ ) : null}
+ {activeStep === 'assets' ? <AssetsStep projectId={id} onError={setError} /> : null}
+ {activeStep === 'episodes' ? <EpisodesStep projectId={id} onError={setError} /> : null}
+ </main>
+ </div>
+ </AppShell>
+ )
+}
diff --git a/frontend/src/pages/drama/RequireAuth.tsx b/frontend/src/pages/drama/RequireAuth.tsx
new file mode 100644
index 0000000..7c24e0f
--- /dev/null
+++ b/frontend/src/pages/drama/RequireAuth.tsx
@@ -0,0 +1,12 @@
+/** Require login for drama routes; redirect to /auth when missing token. */
+import { Navigate, useLocation } from 'react-router-dom'
+import type { ReactNode } from 'react'
+
+export default function RequireAuth({ children }: { children: ReactNode }) {
+ const location = useLocation()
+ const token = localStorage.getItem('token')
+ if (!token) {
+ return <Navigate to="/auth" replace state={{ from: location.pathname }} />
+ }
+ return children
+}
diff --git a/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx b/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx
new file mode 100644
index 0000000..48a0409
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx
@@ -0,0 +1,110 @@
+/** 画布资产自定义节点:类型图标 + 媒体卡片 + 选中工具栏 */
+import { memo, useCallback, type ChangeEvent } from 'react'
+import { Handle, NodeToolbar, Position, type Node, type NodeProps } from '@xyflow/react'
+import { AudioLines, Image as ImageIcon, Landmark, Loader2, Play, UserRound } from 'lucide-react'
+import { resolveDramaMediaUrl } from '../../../api/drama'
+import { useCanvasStore } from './CanvasStore'
+import {
+ CANVAS_GENERATABLE_KINDS,
+ CANVAS_NODE_OPTION_BY_KIND,
+ CANVAS_UPLOADABLE_KINDS,
+ type CanvasAssetNodeData,
+} from './canvasTypes'
+import { CanvasNodeGeneratePanel } from './nodes/CanvasNodeGeneratePanel'
+import { CanvasNodeUploadBar } from './nodes/CanvasNodeUploadBar'
+
+/** 按类型返回占位图标 */
+function PlaceholderIcon({ kind }: { kind: CanvasAssetNodeData['kind'] }) {
+ const className = 'fc-placeholder-icon'
+ if (kind === 'character') return <UserRound className={className} size={40} strokeWidth={1.4} />
+ if (kind === 'scene') return <Landmark className={className} size={40} strokeWidth={1.4} />
+ if (kind === 'video') return <Play className={className} size={40} strokeWidth={1.4} />
+ if (kind === 'audio') return <AudioLines className={className} size={32} strokeWidth={1.4} />
+ if (kind === 'text') return null
+ return <ImageIcon className={className} size={40} strokeWidth={1.4} />
+}
+
+/** 渲染单个画布资产节点 */
+function CanvasAssetNodeComponent({ id, data, selected }: NodeProps<Node<CanvasAssetNodeData>>) {
+ const { updateNodeTextContent } = useCanvasStore()
+ const option = CANVAS_NODE_OPTION_BY_KIND[data.kind]
+ const Icon = option.icon
+ const isText = data.kind === 'text'
+ const mediaSrc = resolveDramaMediaUrl(data.mediaUrl)
+ const showUpload = selected && CANVAS_UPLOADABLE_KINDS.has(data.kind)
+ const showGenerate = selected && CANVAS_GENERATABLE_KINDS.has(data.kind)
+ const footerLabel =
+ data.kind === 'character' ? '基础形象' : data.kind === 'scene' ? data.label : null
+
+ const handleTextChange = useCallback(
+ (event: ChangeEvent<HTMLTextAreaElement>) => {
+ updateNodeTextContent(id, event.target.value)
+ },
+ [id, updateNodeTextContent],
+ )
+
+ return (
+ <div className={`fc-asset-node${selected ? ' is-selected' : ''}${data.generating ? ' is-generating' : ''}`}>
+ {showUpload ? (
+ <NodeToolbar nodeId={id} position={Position.Top} align="center" offset={10}>
+ <CanvasNodeUploadBar nodeId={id} kind={data.kind} />
+ </NodeToolbar>
+ ) : null}
+
+ <div className="fc-asset-node-header">
+ <Icon size={14} strokeWidth={1.8} />
+ <span>
+ {data.kind === 'character'
+ ? typeof data.characterName === 'string' && data.characterName
+ ? data.characterName
+ : option.label
+ : data.label}
+ </span>
+ </div>
+
+ <div className="fc-asset-card">
+ <div className={`fc-asset-body is-${data.kind}`}>
+ {isText ? (
+ selected ? (
+ <textarea
+ className="fc-text-editor nodrag nowheel"
+ value={data.textContent || ''}
+ onChange={handleTextChange}
+ placeholder="输入文本…"
+ rows={4}
+ />
+ ) : (
+ <span>{data.textContent || data.label || '文本'}</span>
+ )
+ ) : data.generating ? (
+ <div className="fc-generating">
+ <Loader2 size={28} className="fc-spin" />
+ <span>生成中…</span>
+ </div>
+ ) : mediaSrc ? (
+ <img className="fc-asset-media" src={mediaSrc} alt={data.label} draggable={false} />
+ ) : (
+ <PlaceholderIcon kind={data.kind} />
+ )}
+ </div>
+ {footerLabel ? <div className="fc-asset-footer">{footerLabel}</div> : null}
+ </div>
+
+ {showGenerate ? (
+ <NodeToolbar nodeId={id} position={Position.Bottom} align="center" offset={14}>
+ <CanvasNodeGeneratePanel
+ nodeId={id}
+ kind={data.kind}
+ generating={Boolean(data.generating)}
+ defaultPrompt={typeof data.promptHint === 'string' ? data.promptHint : ''}
+ />
+ </NodeToolbar>
+ ) : null}
+
+ <Handle className="fc-handle" type="target" position={Position.Left} />
+ <Handle className="fc-handle" type="source" position={Position.Right} />
+ </div>
+ )
+}
+
+export const CanvasAssetNode = memo(CanvasAssetNodeComponent)
diff --git a/frontend/src/pages/drama/canvas/CanvasBottomControls.tsx b/frontend/src/pages/drama/canvas/CanvasBottomControls.tsx
new file mode 100644
index 0000000..d776710
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/CanvasBottomControls.tsx
@@ -0,0 +1,133 @@
+/** 画布左下角缩放与撤销控制条 */
+import { useCallback, useState } from 'react'
+import { LocateFixed, Magnet, Map, Minus, Plus, Redo2, Scan, Undo2 } from 'lucide-react'
+import { useOnViewportChange, useReactFlow } from '@xyflow/react'
+import { useCanvasStore } from './CanvasStore'
+
+/** 渲染画布左下角控制条 */
+export function CanvasBottomControls() {
+ const {
+ snapToGrid,
+ showMinimap,
+ canUndo,
+ canRedo,
+ toggleSnapToGrid,
+ toggleMinimap,
+ undo,
+ redo,
+ } = useCanvasStore()
+ const { zoomIn, zoomOut, fitView, setViewport, getViewport } = useReactFlow()
+ const [zoomPercent, setZoomPercent] = useState(100)
+
+ useOnViewportChange({
+ onChange: (viewport) => {
+ setZoomPercent(Math.round(viewport.zoom * 100))
+ },
+ })
+
+ const handleResetZoom = useCallback(() => {
+ const viewport = getViewport()
+ void setViewport({ ...viewport, zoom: 1 }, { duration: 200 })
+ }, [getViewport, setViewport])
+
+ return (
+ <div className="fc-overlay fc-bottom-controls">
+ <div className="fc-bottom-bar">
+ <button
+ type="button"
+ className="fc-icon-btn is-sm"
+ aria-label="撤销"
+ title="撤销"
+ disabled={!canUndo}
+ onClick={undo}
+ >
+ <Undo2 size={16} strokeWidth={1.8} />
+ </button>
+ <button
+ type="button"
+ className="fc-icon-btn is-sm"
+ aria-label="重做"
+ title="重做"
+ disabled={!canRedo}
+ onClick={redo}
+ >
+ <Redo2 size={16} strokeWidth={1.8} />
+ </button>
+
+ <span className="fc-bottom-sep" />
+
+ <button
+ type="button"
+ className="fc-icon-btn is-sm"
+ aria-label="定位到内容"
+ title="定位到内容"
+ onClick={() => void fitView({ duration: 200 })}
+ >
+ <LocateFixed size={16} strokeWidth={1.8} />
+ </button>
+ <button
+ type="button"
+ className="fc-icon-btn is-sm"
+ aria-label="适应画布"
+ title="适应画布"
+ onClick={() => void fitView({ duration: 200, padding: 0.2 })}
+ >
+ <Scan size={16} strokeWidth={1.8} />
+ </button>
+
+ <span className="fc-bottom-sep" />
+
+ <button
+ type="button"
+ className={`fc-icon-btn is-sm${snapToGrid ? ' is-active' : ''}`}
+ aria-label={snapToGrid ? '关闭网格吸附' : '开启网格吸附'}
+ title={snapToGrid ? '关闭网格吸附' : '开启网格吸附'}
+ aria-pressed={snapToGrid}
+ onClick={toggleSnapToGrid}
+ >
+ <Magnet size={16} strokeWidth={1.8} />
+ </button>
+ <button
+ type="button"
+ className={`fc-icon-btn is-sm${showMinimap ? ' is-active' : ''}`}
+ aria-label={showMinimap ? '关闭小地图' : '开启小地图'}
+ title={showMinimap ? '关闭小地图' : '开启小地图'}
+ aria-pressed={showMinimap}
+ onClick={toggleMinimap}
+ >
+ <Map size={16} strokeWidth={1.8} />
+ </button>
+
+ <span className="fc-bottom-sep" />
+
+ <button
+ type="button"
+ className="fc-icon-btn is-sm"
+ aria-label="缩小"
+ title="缩小"
+ onClick={() => zoomOut({ duration: 150 })}
+ >
+ <Minus size={16} strokeWidth={1.8} />
+ </button>
+ <button
+ type="button"
+ className="fc-zoom-label"
+ aria-label="重置缩放"
+ title="重置缩放"
+ onClick={handleResetZoom}
+ >
+ {zoomPercent}%
+ </button>
+ <button
+ type="button"
+ className="fc-icon-btn is-sm"
+ aria-label="放大"
+ title="放大"
+ onClick={() => zoomIn({ duration: 150 })}
+ >
+ <Plus size={16} strokeWidth={1.8} />
+ </button>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/pages/drama/canvas/CanvasLeftToolbar.tsx b/frontend/src/pages/drama/canvas/CanvasLeftToolbar.tsx
new file mode 100644
index 0000000..a57d0d2
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/CanvasLeftToolbar.tsx
@@ -0,0 +1,102 @@
+/** 画布左侧垂直居中工具栏与添加节点面板 */
+import { useState } from 'react'
+import { FolderOpen, Plus, X } from 'lucide-react'
+import { useCanvasStore } from './CanvasStore'
+import { ADD_NODE_OPTIONS, CANVAS_NODE_OPTION_BY_KIND, type CanvasNodeKind } from './canvasTypes'
+
+type CanvasLeftToolbarProps = {
+ onSelectNode: (kind: CanvasNodeKind) => void
+}
+
+/** 渲染画布左侧浮动工具栏 */
+export function CanvasLeftToolbar({ onSelectNode }: CanvasLeftToolbarProps) {
+ const { nodes, requestFocusNode } = useCanvasStore()
+ const [panelOpen, setPanelOpen] = useState(false)
+ const [folderOpen, setFolderOpen] = useState(false)
+
+ return (
+ <div className="fc-overlay fc-left-toolbar">
+ <div className="fc-left-stack">
+ <div
+ style={{ position: 'relative' }}
+ onMouseEnter={() => setPanelOpen(true)}
+ onMouseLeave={() => setPanelOpen(false)}
+ >
+ <button
+ type="button"
+ className="fc-icon-btn is-primary"
+ aria-label={panelOpen ? '关闭添加节点' : '添加节点'}
+ aria-expanded={panelOpen}
+ title="添加节点"
+ >
+ {panelOpen ? <X size={18} strokeWidth={2} /> : <Plus size={18} strokeWidth={2} />}
+ </button>
+
+ {panelOpen ? (
+ <div className="fc-add-panel">
+ {ADD_NODE_OPTIONS.map((option) => {
+ const Icon = option.icon
+ return (
+ <button
+ key={option.id}
+ type="button"
+ onClick={() => {
+ onSelectNode(option.id)
+ setPanelOpen(false)
+ }}
+ >
+ <span className="fc-add-panel-icon">
+ <Icon size={14} strokeWidth={1.8} />
+ </span>
+ {option.label}
+ </button>
+ )
+ })}
+ </div>
+ ) : null}
+ </div>
+
+ <button
+ type="button"
+ className={`fc-icon-btn${folderOpen ? ' is-active' : ''}`}
+ aria-label="资产文件夹"
+ title="资产文件夹"
+ aria-expanded={folderOpen}
+ onClick={() => setFolderOpen((v) => !v)}
+ >
+ <FolderOpen size={18} strokeWidth={1.8} />
+ </button>
+
+ {folderOpen ? (
+ <div className="fc-folder-panel" role="dialog" aria-label="画布节点列表">
+ <h4>画布节点</h4>
+ {nodes.length === 0 ? (
+ <p className="fc-folder-empty">暂无节点,点击 + 添加</p>
+ ) : (
+ nodes.map((node) => {
+ const option = CANVAS_NODE_OPTION_BY_KIND[node.data.kind]
+ const Icon = option.icon
+ return (
+ <button
+ key={node.id}
+ type="button"
+ className="fc-folder-item"
+ onClick={() => {
+ requestFocusNode(node.id)
+ setFolderOpen(false)
+ }}
+ >
+ <Icon size={14} strokeWidth={1.8} />
+ <span>
+ {option.label} · {node.data.label}
+ </span>
+ </button>
+ )
+ })
+ )}
+ </div>
+ ) : null}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/pages/drama/canvas/CanvasNodeSelector.tsx b/frontend/src/pages/drama/canvas/CanvasNodeSelector.tsx
new file mode 100644
index 0000000..f43335a
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/CanvasNodeSelector.tsx
@@ -0,0 +1,39 @@
+/** 空画布居中展示的默认节点选择器 */
+import { MousePointer2 } from 'lucide-react'
+import { CANVAS_NODE_OPTIONS, type CanvasNodeKind } from './canvasTypes'
+
+type CanvasNodeSelectorProps = {
+ onSelect: (kind: CanvasNodeKind) => void
+}
+
+/** 渲染快速新建节点类型选择器 */
+export function CanvasNodeSelector({ onSelect }: CanvasNodeSelectorProps) {
+ return (
+ <div className="fc-overlay fc-node-selector">
+ <div className="fc-node-selector-inner">
+ <div className="fc-node-selector-row">
+ {CANVAS_NODE_OPTIONS.map((option) => {
+ const Icon = option.icon
+ return (
+ <button
+ key={option.id}
+ type="button"
+ className="fc-node-chip"
+ onClick={() => onSelect(option.id)}
+ >
+ <span className="fc-node-chip-icon">
+ <Icon size={16} strokeWidth={1.8} />
+ </span>
+ <span>{option.label}</span>
+ </button>
+ )
+ })}
+ </div>
+ <p className="fc-node-hint">
+ <MousePointer2 size={16} strokeWidth={1.8} />
+ 点击快速添加
+ </p>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/pages/drama/canvas/CanvasPage.tsx b/frontend/src/pages/drama/canvas/CanvasPage.tsx
new file mode 100644
index 0000000..109948b
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/CanvasPage.tsx
@@ -0,0 +1,29 @@
+/** 自由画布页:全屏 React Flow 无限画布(无应用壳布局) */
+import { useParams } from 'react-router-dom'
+import RequireAuth from '../RequireAuth'
+import { CanvasWorkspace } from './CanvasWorkspace'
+
+/** 鉴权后渲染全屏自由画布 */
+export default function CanvasPage() {
+ return (
+ <RequireAuth>
+ <CanvasPageInner />
+ </RequireAuth>
+ )
+}
+
+/** 从路由读取 projectId 并挂载工作区 */
+function CanvasPageInner() {
+ const { projectId } = useParams()
+ const id = Number(projectId)
+
+ if (!Number.isFinite(id) || id <= 0) {
+ return (
+ <div className="free-canvas-page" style={{ display: 'grid', placeItems: 'center' }}>
+ <p style={{ color: '#64748b' }}>无效的项目 ID</p>
+ </div>
+ )
+ }
+
+ return <CanvasWorkspace projectId={id} />
+}
diff --git a/frontend/src/pages/drama/canvas/CanvasStore.tsx b/frontend/src/pages/drama/canvas/CanvasStore.tsx
new file mode 100644
index 0000000..e67255a
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/CanvasStore.tsx
@@ -0,0 +1,514 @@
+/** 画布状态上下文:节点/边、历史、UI 开关与增删操作 */
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react'
+import {
+ addEdge,
+ applyEdgeChanges,
+ applyNodeChanges,
+ type Connection,
+ type Edge,
+ type EdgeChange,
+ type Node,
+ type NodeChange,
+ type OnConnect,
+ type OnEdgesChange,
+ type OnNodesChange,
+} from '@xyflow/react'
+import { dramaApi } from '../../../api/drama'
+import type { ImageGenerationOptions } from '../../../lib/dramaGenerationOptions'
+import { getImageStyleId } from '../dramaWorkspaceUtils'
+import {
+ createEmptyCanvasHistory,
+ pushHistory,
+ redoHistory,
+ undoHistory,
+ type CanvasHistoryState,
+} from './canvasHistory'
+import { mergeAssetsWithCanvasLayout } from './assetsToCanvasNodes'
+import {
+ CANVAS_NODE_DEFAULT_LABEL,
+ canvasKindToAssetType,
+ type CanvasAssetNodeData,
+ type CanvasNodeKind,
+} from './canvasTypes'
+import { useCanvasAutoSave } from './useCanvasAutoSave'
+
+type CanvasStoreValue = {
+ projectId: number
+ nodes: Node<CanvasAssetNodeData>[]
+ edges: Edge[]
+ loading: boolean
+ errorMessage: string
+ saveStatusVisible: boolean
+ snapToGrid: boolean
+ showMinimap: boolean
+ canUndo: boolean
+ canRedo: boolean
+ showNodeSelector: boolean
+ setErrorMessage: (msg: string) => void
+ toggleSnapToGrid: () => void
+ toggleMinimap: () => void
+ onNodesChange: OnNodesChange
+ onEdgesChange: OnEdgesChange
+ onConnect: OnConnect
+ addNodeOfKind: (kind: CanvasNodeKind, position: { x: number; y: number }) => Promise<void>
+ undo: () => void
+ redo: () => void
+ pushSnapshot: () => void
+ focusNodeId: string | null
+ requestFocusNode: (id: string) => void
+ clearFocusNode: () => void
+ ensureNodeAsset: (nodeId: string) => Promise<number>
+ uploadNodeMedia: (nodeId: string, file: File) => Promise<void>
+ generateNodeImage: (
+ nodeId: string,
+ prompt: string,
+ options?: Partial<ImageGenerationOptions>,
+ ) => Promise<void>
+ updateNodeTextContent: (nodeId: string, textContent: string) => void
+ /** 项目级内置画面风格 ID */
+ projectImageStyleId: string
+}
+
+const CanvasStoreContext = createContext<CanvasStoreValue | null>(null)
+
+type CanvasStoreProviderProps = {
+ projectId: number
+ children: ReactNode
+}
+
+/** 提供画布受控状态与历史操作 */
+export function CanvasStoreProvider({ projectId, children }: CanvasStoreProviderProps) {
+ const [nodes, setNodes] = useState<Node<CanvasAssetNodeData>[]>([])
+ const [edges, setEdges] = useState<Edge[]>([])
+ const [history, setHistory] = useState<CanvasHistoryState>(createEmptyCanvasHistory)
+ const [loading, setLoading] = useState(true)
+ const [errorMessage, setErrorMessage] = useState('')
+ const [dirty, setDirty] = useState(false)
+ const [saveStatusVisible, setSaveStatusVisible] = useState(false)
+ const [snapToGrid, setSnapToGrid] = useState(false)
+ const [showMinimap, setShowMinimap] = useState(false)
+ const [focusNodeId, setFocusNodeId] = useState<string | null>(null)
+ // projectImageStyleId 项目内置画面风格
+ const [projectImageStyleId, setProjectImageStyleId] = useState('')
+ const readyRef = useRef(false)
+ const nodesRef = useRef(nodes)
+ const edgesRef = useRef(edges)
+ const historyRef = useRef(history)
+ nodesRef.current = nodes
+ edgesRef.current = edges
+ historyRef.current = history
+
+ useEffect(() => {
+ let cancelled = false
+ readyRef.current = false
+ setLoading(true)
+ setDirty(false)
+ setSaveStatusVisible(false)
+ setErrorMessage('')
+
+ Promise.all([
+ dramaApi.getCanvas(projectId),
+ dramaApi.listAssets(projectId),
+ dramaApi.getProject(projectId).catch(() => null),
+ ])
+ .then(([canvas, assets, project]) => {
+ if (cancelled) return
+ const { nodes: mergedNodes, edges: mergedEdges } = mergeAssetsWithCanvasLayout(
+ assets,
+ canvas.nodes,
+ canvas.edges,
+ )
+ setNodes(mergedNodes)
+ setEdges(mergedEdges)
+ setHistory(createEmptyCanvasHistory())
+ setDirty(false)
+ if (project) {
+ setProjectImageStyleId(getImageStyleId(project.script, project))
+ }
+ readyRef.current = true
+ })
+ .catch((err) => {
+ if (cancelled) return
+ setErrorMessage(err instanceof Error ? err.message : '加载画布失败')
+ readyRef.current = true
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false)
+ })
+
+ return () => {
+ cancelled = true
+ readyRef.current = false
+ }
+ }, [projectId])
+
+ const markDirty = useCallback(() => {
+ if (!readyRef.current) return
+ setDirty(true)
+ setSaveStatusVisible(false)
+ }, [])
+
+ const pushSnapshot = useCallback(() => {
+ setHistory((prev) =>
+ pushHistory(prev, {
+ nodes: nodesRef.current,
+ edges: edgesRef.current,
+ }),
+ )
+ }, [])
+
+ const onNodesChange: OnNodesChange = useCallback(
+ (changes: NodeChange[]) => {
+ const hasRemove = changes.some((c) => c.type === 'remove')
+ if (hasRemove) {
+ setHistory((prev) =>
+ pushHistory(prev, {
+ nodes: nodesRef.current,
+ edges: edgesRef.current,
+ }),
+ )
+ }
+ setNodes((current) => applyNodeChanges(changes, current) as Node<CanvasAssetNodeData>[])
+ const structural = changes.some(
+ (c) => c.type === 'remove' || c.type === 'add' || c.type === 'replace' || c.type === 'position',
+ )
+ if (structural) markDirty()
+ },
+ [markDirty],
+ )
+
+ const onEdgesChange: OnEdgesChange = useCallback(
+ (changes: EdgeChange[]) => {
+ const hasRemove = changes.some((c) => c.type === 'remove')
+ if (hasRemove) {
+ setHistory((prev) =>
+ pushHistory(prev, {
+ nodes: nodesRef.current,
+ edges: edgesRef.current,
+ }),
+ )
+ }
+ setEdges((current) => applyEdgeChanges(changes, current))
+ if (changes.some((c) => c.type === 'remove' || c.type === 'add' || c.type === 'replace')) {
+ markDirty()
+ }
+ },
+ [markDirty],
+ )
+
+ const onConnect: OnConnect = useCallback(
+ (connection: Connection) => {
+ if (!connection.source || !connection.target || connection.source === connection.target) {
+ return
+ }
+ setHistory((prev) =>
+ pushHistory(prev, {
+ nodes: nodesRef.current,
+ edges: edgesRef.current,
+ }),
+ )
+ setEdges((current) => addEdge({ ...connection, id: `e-${Date.now()}` }, current))
+ markDirty()
+ },
+ [markDirty],
+ )
+
+ const addNodeOfKind = useCallback(
+ async (kind: CanvasNodeKind, position: { x: number; y: number }) => {
+ const label = CANVAS_NODE_DEFAULT_LABEL[kind]
+ let assetId: number | undefined
+ try {
+ const asset = await dramaApi.createAsset({
+ project_id: projectId,
+ type: kind,
+ asset_type: canvasKindToAssetType(kind),
+ name: label,
+ params: {},
+ })
+ assetId = asset.id
+ } catch (err) {
+ setErrorMessage(err instanceof Error ? err.message : '创建资产失败')
+ return
+ }
+
+ const id = `asset-${assetId}`
+ const node: Node<CanvasAssetNodeData> = {
+ id,
+ type: 'asset',
+ position,
+ data: {
+ kind,
+ label,
+ assetId,
+ textContent: kind === 'text' ? '' : undefined,
+ mediaUrl: null,
+ },
+ }
+ /* 回写 canvas_node_id 便于后端关联 */
+ void dramaApi
+ .updateAsset(assetId, { params: { canvas_node_id: id } })
+ .catch(() => undefined)
+
+ setHistory((prev) =>
+ pushHistory(prev, {
+ nodes: nodesRef.current,
+ edges: edgesRef.current,
+ }),
+ )
+ setNodes((current) => [...current, node])
+ markDirty()
+ },
+ [markDirty, projectId],
+ )
+
+ /** 确保节点已绑定后端资产,返回 assetId */
+ const ensureNodeAsset = useCallback(
+ async (nodeId: string) => {
+ const node = nodesRef.current.find((n) => n.id === nodeId)
+ if (!node) throw new Error('节点不存在')
+ if (typeof node.data.assetId === 'number' && node.data.assetId > 0) {
+ return node.data.assetId
+ }
+ const asset = await dramaApi.createAsset({
+ project_id: projectId,
+ type: node.data.kind,
+ asset_type: canvasKindToAssetType(node.data.kind),
+ name: node.data.label,
+ cover: node.data.mediaUrl || undefined,
+ url: node.data.mediaUrl || undefined,
+ params: { canvas_node_id: nodeId },
+ })
+ setNodes((current) =>
+ current.map((n) =>
+ n.id === nodeId ? { ...n, data: { ...n.data, assetId: asset.id } } : n,
+ ),
+ )
+ markDirty()
+ return asset.id
+ },
+ [markDirty, projectId],
+ )
+
+ /** 本地上传图片到节点 */
+ const uploadNodeMedia = useCallback(
+ async (nodeId: string, file: File) => {
+ pushSnapshot()
+ const assetId = await ensureNodeAsset(nodeId)
+ const asset = await dramaApi.uploadAssetMedia(assetId, file)
+ const mediaUrl = asset.url || asset.cover || ''
+ setNodes((current) =>
+ current.map((n) =>
+ n.id === nodeId
+ ? { ...n, data: { ...n.data, assetId, mediaUrl, generating: false } }
+ : n,
+ ),
+ )
+ markDirty()
+ },
+ [ensureNodeAsset, markDirty, pushSnapshot],
+ )
+
+ /** AI 生图并写回节点 */
+ const generateNodeImage = useCallback(
+ async (nodeId: string, prompt: string, options?: Partial<ImageGenerationOptions>) => {
+ const trimmed = prompt.trim()
+ if (!trimmed) throw new Error('请输入提示词')
+ pushSnapshot()
+ const node = nodesRef.current.find((n) => n.id === nodeId)
+ if (!node) throw new Error('节点不存在')
+
+ setNodes((current) =>
+ current.map((n) =>
+ n.id === nodeId ? { ...n, data: { ...n.data, generating: true } } : n,
+ ),
+ )
+
+ try {
+ const assetId = await ensureNodeAsset(nodeId)
+ await dramaApi.generateImage({
+ project_id: projectId,
+ asset_id: assetId,
+ prompt: trimmed,
+ name: node.data.label,
+ asset_type_kind: node.data.kind,
+ image_style_id: options?.image_style_id || projectImageStyleId || undefined,
+ model_id: options?.model_id,
+ aspect_ratio: options?.aspect_ratio,
+ resolution: options?.resolution,
+ })
+ const started = Date.now()
+ let mediaUrl = ''
+ while (Date.now() - started < 10 * 60 * 1000) {
+ const list = await dramaApi.listAssets(projectId)
+ const latest = list.find((a) => a.id === assetId)
+ const gen = (latest?.params || {}).generation as
+ | { status?: string; error?: string }
+ | undefined
+ const status = String(gen?.status || '')
+ mediaUrl = latest?.url || latest?.cover || ''
+ if (mediaUrl && status !== 'generating') break
+ if (status === 'failed') {
+ throw new Error(String(gen?.error || '生图失败'))
+ }
+ if (status === 'done' && mediaUrl) break
+ await new Promise((r) => setTimeout(r, 2000))
+ }
+ if (!mediaUrl) throw new Error('生图超时,请重试')
+ setNodes((current) =>
+ current.map((n) =>
+ n.id === nodeId
+ ? { ...n, data: { ...n.data, assetId, mediaUrl, generating: false } }
+ : n,
+ ),
+ )
+ markDirty()
+ } catch (err) {
+ setNodes((current) =>
+ current.map((n) =>
+ n.id === nodeId ? { ...n, data: { ...n.data, generating: false } } : n,
+ ),
+ )
+ throw err
+ }
+ },
+ [ensureNodeAsset, markDirty, projectId, projectImageStyleId, pushSnapshot],
+ )
+
+ /** 更新文本节点内容 */
+ const updateNodeTextContent = useCallback(
+ (nodeId: string, textContent: string) => {
+ setNodes((current) =>
+ current.map((n) =>
+ n.id === nodeId
+ ? { ...n, data: { ...n.data, textContent, label: textContent.slice(0, 24) || n.data.label } }
+ : n,
+ ),
+ )
+ markDirty()
+ },
+ [markDirty],
+ )
+
+ const undo = useCallback(() => {
+ const result = undoHistory(
+ { nodes: nodesRef.current, edges: edgesRef.current },
+ historyRef.current,
+ )
+ if (!result) return
+ setNodes(result.snapshot.nodes)
+ setEdges(result.snapshot.edges)
+ setHistory(result.history)
+ markDirty()
+ }, [markDirty])
+
+ const redo = useCallback(() => {
+ const result = redoHistory(
+ { nodes: nodesRef.current, edges: edgesRef.current },
+ historyRef.current,
+ )
+ if (!result) return
+ setNodes(result.snapshot.nodes)
+ setEdges(result.snapshot.edges)
+ setHistory(result.history)
+ markDirty()
+ }, [markDirty])
+
+ const { flush } = useCanvasAutoSave({
+ projectId,
+ nodes,
+ edges,
+ dirty,
+ enabled: !loading,
+ onSaved: () => {
+ setDirty(false)
+ setSaveStatusVisible(true)
+ },
+ onError: (msg) => setErrorMessage(msg),
+ })
+
+ /* 页面关闭前尽量刷一次保存 */
+ useEffect(() => {
+ const onBeforeUnload = () => {
+ if (dirty) void flush()
+ }
+ window.addEventListener('beforeunload', onBeforeUnload)
+ return () => window.removeEventListener('beforeunload', onBeforeUnload)
+ }, [dirty, flush])
+
+ const value = useMemo<CanvasStoreValue>(
+ () => ({
+ projectId,
+ nodes,
+ edges,
+ loading,
+ errorMessage,
+ saveStatusVisible,
+ snapToGrid,
+ showMinimap,
+ canUndo: history.past.length > 0,
+ canRedo: history.future.length > 0,
+ showNodeSelector: !loading && nodes.length === 0,
+ setErrorMessage,
+ toggleSnapToGrid: () => setSnapToGrid((v) => !v),
+ toggleMinimap: () => setShowMinimap((v) => !v),
+ onNodesChange,
+ onEdgesChange,
+ onConnect,
+ addNodeOfKind,
+ undo,
+ redo,
+ pushSnapshot,
+ focusNodeId,
+ requestFocusNode: (id: string) => setFocusNodeId(id),
+ clearFocusNode: () => setFocusNodeId(null),
+ ensureNodeAsset,
+ uploadNodeMedia,
+ generateNodeImage,
+ updateNodeTextContent,
+ projectImageStyleId,
+ }),
+ [
+ projectId,
+ nodes,
+ edges,
+ loading,
+ errorMessage,
+ saveStatusVisible,
+ snapToGrid,
+ showMinimap,
+ history.past.length,
+ history.future.length,
+ onNodesChange,
+ onEdgesChange,
+ onConnect,
+ addNodeOfKind,
+ undo,
+ redo,
+ pushSnapshot,
+ focusNodeId,
+ ensureNodeAsset,
+ uploadNodeMedia,
+ generateNodeImage,
+ updateNodeTextContent,
+ projectImageStyleId,
+ ],
+ )
+
+ return <CanvasStoreContext.Provider value={value}>{children}</CanvasStoreContext.Provider>
+}
+
+/** 读取画布状态上下文 */
+export function useCanvasStore() {
+ const ctx = useContext(CanvasStoreContext)
+ if (!ctx) throw new Error('useCanvasStore must be used within CanvasStoreProvider')
+ return ctx
+}
diff --git a/frontend/src/pages/drama/canvas/CanvasTopBar.tsx b/frontend/src/pages/drama/canvas/CanvasTopBar.tsx
new file mode 100644
index 0000000..86bcfd4
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/CanvasTopBar.tsx
@@ -0,0 +1,68 @@
+/** 画布顶栏:返回、标题、已保存指示、设置占位 */
+import { useState } from 'react'
+import { ChevronLeft, Settings } from 'lucide-react'
+import { useNavigate } from 'react-router-dom'
+import { useCanvasStore } from './CanvasStore'
+
+/** 渲染画布页顶部工具栏 */
+export function CanvasTopBar() {
+ const navigate = useNavigate()
+ const { saveStatusVisible, projectId } = useCanvasStore()
+ const [settingsOpen, setSettingsOpen] = useState(false)
+
+ return (
+ <>
+ <div className="fc-overlay fc-topbar">
+ <div className="fc-topbar-left">
+ <button
+ type="button"
+ className="fc-icon-btn"
+ aria-label="返回"
+ title="返回"
+ onClick={() => {
+ if (window.history.length > 1) navigate(-1)
+ else navigate(`/drama/projects/${projectId}`)
+ }}
+ >
+ <ChevronLeft size={20} strokeWidth={1.8} />
+ </button>
+ <span className="fc-topbar-title">资产库编排</span>
+ {saveStatusVisible ? (
+ <span className="fc-save-pill">
+ <span className="fc-save-dot" />
+ 已保存
+ </span>
+ ) : null}
+ </div>
+
+ <button
+ type="button"
+ className="fc-icon-btn"
+ aria-label="设置"
+ title="设置"
+ aria-expanded={settingsOpen}
+ onClick={() => setSettingsOpen((v) => !v)}
+ >
+ <Settings size={18} strokeWidth={1.8} />
+ </button>
+ </div>
+
+ {settingsOpen ? (
+ <div className="fc-settings-pop" role="dialog" aria-label="画布设置">
+ <strong>画布设置</strong>
+ 布局与项目资产会自动同步保存。上传走 OSS;合成时按需拉本地缓存。
+ <div style={{ marginTop: 10 }}>
+ <button
+ type="button"
+ className="fc-icon-btn is-sm"
+ style={{ width: 'auto', padding: '0 12px', borderRadius: 10 }}
+ onClick={() => setSettingsOpen(false)}
+ >
+ 关闭
+ </button>
+ </div>
+ </div>
+ ) : null}
+ </>
+ )
+}
diff --git a/frontend/src/pages/drama/canvas/CanvasWorkspace.tsx b/frontend/src/pages/drama/canvas/CanvasWorkspace.tsx
new file mode 100644
index 0000000..9d54482
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/CanvasWorkspace.tsx
@@ -0,0 +1,88 @@
+/** 画布工作区:React Flow 与 overlay UI 组合 */
+import { useCallback, useEffect } from 'react'
+import { ReactFlowProvider, useReactFlow } from '@xyflow/react'
+import { CanvasBottomControls } from './CanvasBottomControls'
+import { CanvasLeftToolbar } from './CanvasLeftToolbar'
+import { CanvasNodeSelector } from './CanvasNodeSelector'
+import { CanvasStoreProvider, useCanvasStore } from './CanvasStore'
+import { CanvasTopBar } from './CanvasTopBar'
+import { getViewportCenterNodePosition } from './canvasNormalize'
+import { CANVAS_NODE_SIZE, type CanvasNodeKind } from './canvasTypes'
+import { FreeCanvasFlow } from './FreeCanvasFlow'
+import './canvas.css'
+
+type CanvasWorkspaceProps = {
+ projectId: number
+}
+
+/** 渲染画布主体与各区域 overlay */
+function CanvasWorkspaceContent({ projectId }: CanvasWorkspaceProps) {
+ const {
+ showNodeSelector,
+ errorMessage,
+ setErrorMessage,
+ addNodeOfKind,
+ undo,
+ redo,
+ loading,
+ } = useCanvasStore()
+ const { screenToFlowPosition } = useReactFlow()
+
+ const handleSelectNode = useCallback(
+ (kind: CanvasNodeKind) => {
+ const size = CANVAS_NODE_SIZE[kind]
+ const position = getViewportCenterNodePosition(screenToFlowPosition, size)
+ void addNodeOfKind(kind, position)
+ },
+ [addNodeOfKind, screenToFlowPosition],
+ )
+
+ /* Ctrl/Cmd+Z / Ctrl+Shift+Z / Ctrl+Y */
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ const meta = event.metaKey || event.ctrlKey
+ if (!meta) return
+ const key = event.key.toLowerCase()
+ if (key === 'z' && !event.shiftKey) {
+ event.preventDefault()
+ undo()
+ } else if ((key === 'z' && event.shiftKey) || key === 'y') {
+ event.preventDefault()
+ redo()
+ }
+ }
+ window.addEventListener('keydown', onKeyDown)
+ return () => window.removeEventListener('keydown', onKeyDown)
+ }, [undo, redo])
+
+ return (
+ <div className="free-canvas-page">
+ <FreeCanvasFlow projectId={projectId} />
+ <CanvasTopBar />
+ <CanvasLeftToolbar onSelectNode={handleSelectNode} />
+ <CanvasBottomControls />
+ {showNodeSelector ? <CanvasNodeSelector onSelect={handleSelectNode} /> : null}
+ {errorMessage ? (
+ <p className="fc-error-toast" role="alert" onAnimationEnd={() => setErrorMessage('')}>
+ {errorMessage}
+ </p>
+ ) : null}
+ {loading ? (
+ <p className="fc-error-toast" style={{ background: '#fff', color: '#64748b' }}>
+ 加载画布…
+ </p>
+ ) : null}
+ </div>
+ )
+}
+
+/** 提供 React Flow 与画布状态上下文 */
+export function CanvasWorkspace({ projectId }: CanvasWorkspaceProps) {
+ return (
+ <ReactFlowProvider>
+ <CanvasStoreProvider projectId={projectId}>
+ <CanvasWorkspaceContent projectId={projectId} />
+ </CanvasStoreProvider>
+ </ReactFlowProvider>
+ )
+}
diff --git a/frontend/src/pages/drama/canvas/FreeCanvasFlow.tsx b/frontend/src/pages/drama/canvas/FreeCanvasFlow.tsx
new file mode 100644
index 0000000..ebbdbd5
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/FreeCanvasFlow.tsx
@@ -0,0 +1,131 @@
+/** React Flow 无限画布核心 */
+import { useCallback, useEffect, useRef } from 'react'
+import {
+ Background,
+ MiniMap,
+ ReactFlow,
+ useReactFlow,
+ type Connection,
+ type Edge,
+} from '@xyflow/react'
+import '@xyflow/react/dist/style.css'
+import { CanvasAssetNode } from './CanvasAssetNode'
+import { useCanvasStore } from './CanvasStore'
+import { CANVAS_SNAP_GRID } from './canvasTypes'
+
+const nodeTypes = { asset: CanvasAssetNode }
+
+type FreeCanvasFlowProps = {
+ projectId: number
+}
+
+/** 渲染 React Flow 无限画布 */
+export function FreeCanvasFlow({ projectId }: FreeCanvasFlowProps) {
+ const {
+ nodes,
+ edges,
+ snapToGrid,
+ showMinimap,
+ onNodesChange,
+ onEdgesChange,
+ onConnect,
+ pushSnapshot,
+ focusNodeId,
+ clearFocusNode,
+ } = useCanvasStore()
+ const { fitView, setCenter, getNode } = useReactFlow()
+ const wrapperRef = useRef<HTMLDivElement>(null)
+ const dragSnapshotPushed = useRef(false)
+
+ /* 聚焦文件夹选中的节点 */
+ useEffect(() => {
+ if (!focusNodeId) return
+ const node = getNode(focusNodeId)
+ if (!node) {
+ clearFocusNode()
+ return
+ }
+ const w = 200
+ const h = 240
+ void setCenter(node.position.x + w / 2, node.position.y + h / 2, {
+ zoom: 1,
+ duration: 280,
+ })
+ clearFocusNode()
+ }, [focusNodeId, getNode, setCenter, clearFocusNode])
+
+ const isValidConnection = useCallback((connection: Connection | Edge) => {
+ return connection.source !== connection.target
+ }, [])
+
+ const handlePaneClick = useCallback(() => {
+ wrapperRef.current?.focus()
+ }, [])
+
+ /* 拖拽开始时压入历史快照(同一拖拽只压一次) */
+ const handleNodeDragStart = useCallback(() => {
+ if (!dragSnapshotPushed.current) {
+ pushSnapshot()
+ dragSnapshotPushed.current = true
+ }
+ }, [pushSnapshot])
+
+ const handleNodeDragStop = useCallback(() => {
+ dragSnapshotPushed.current = false
+ }, [])
+
+ /* 保证容器可聚焦;加载后有节点时适应视图 */
+ useEffect(() => {
+ wrapperRef.current?.focus()
+ }, [projectId])
+
+ const fittedRef = useRef(false)
+ useEffect(() => {
+ fittedRef.current = false
+ }, [projectId])
+
+ useEffect(() => {
+ if (fittedRef.current || nodes.length === 0) return
+ fittedRef.current = true
+ void fitView({ padding: 0.2 })
+ }, [nodes.length, fitView])
+
+ return (
+ <div
+ ref={wrapperRef}
+ tabIndex={0}
+ className="free-canvas-flow"
+ style={{ width: '100%', height: '100%', outline: 'none' }}
+ data-project-id={projectId}
+ >
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={nodeTypes}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ onConnect={onConnect}
+ onNodeDragStart={handleNodeDragStart}
+ onNodeDragStop={handleNodeDragStop}
+ isValidConnection={isValidConnection}
+ onPaneClick={handlePaneClick}
+ deleteKeyCode={['Backspace', 'Delete']}
+ snapToGrid={snapToGrid}
+ snapGrid={CANVAS_SNAP_GRID}
+ minZoom={0.2}
+ maxZoom={2}
+ proOptions={{ hideAttribution: true }}
+ defaultEdgeOptions={{ type: 'default' }}
+ >
+ <Background gap={CANVAS_SNAP_GRID[0]} size={1.2} color="#cbd5e1" />
+ {showMinimap ? (
+ <MiniMap
+ pannable
+ zoomable
+ style={{ bottom: 20, right: 20, borderRadius: 12, overflow: 'hidden' }}
+ />
+ ) : null}
+ </ReactFlow>
+ </div>
+ )
+}
diff --git a/frontend/src/pages/drama/canvas/assetsToCanvasNodes.ts b/frontend/src/pages/drama/canvas/assetsToCanvasNodes.ts
new file mode 100644
index 0000000..970a597
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/assetsToCanvasNodes.ts
@@ -0,0 +1,153 @@
+/** 将项目资产与已保存画布布局合并为 React Flow 节点/边 */
+import type { Edge, Node } from '@xyflow/react'
+import type { DramaAsset } from '../../../api/drama'
+import {
+ CANVAS_NODE_DEFAULT_LABEL,
+ CANVAS_NODE_SIZE,
+ type CanvasAssetNodeData,
+ type CanvasNodeKind,
+} from './canvasTypes'
+import { normalizeCanvasEdges, normalizeCanvasNodes } from './canvasNormalize'
+
+/** Drama 资产 type → 画布节点 kind */
+export function dramaAssetTypeToKind(type: string | null | undefined): CanvasNodeKind {
+ const t = String(type || '').toLowerCase()
+ if (t === 'character') return 'character'
+ if (t === 'scene') return 'scene'
+ if (t === 'video') return 'video'
+ if (t === 'audio') return 'audio'
+ if (t === 'text') return 'text'
+ /* prop / material / none / 其他 → 图片卡片 */
+ return 'image'
+}
+
+/** 根据资产 ID 生成稳定节点 ID */
+export function getCanvasNodeId(assetId: number) {
+ return `asset-${assetId}`
+}
+
+/** 从资产构建节点 data */
+export function buildNodeDataFromAsset(asset: DramaAsset): CanvasAssetNodeData {
+ const kind = dramaAssetTypeToKind(asset.type)
+ const params = (asset.params || {}) as Record<string, unknown>
+ const promptHint =
+ (typeof params.visualImage === 'string' && params.visualImage) ||
+ (typeof params.prompt === 'string' && params.prompt) ||
+ ''
+ const label =
+ (typeof asset.name === 'string' && asset.name.trim()) || CANVAS_NODE_DEFAULT_LABEL[kind]
+
+ return {
+ kind,
+ label,
+ assetId: asset.id,
+ mediaUrl: asset.url || asset.cover || null,
+ textContent: kind === 'text' ? String(params.textContent || '') : undefined,
+ promptHint,
+ characterName: kind === 'character' ? label : undefined,
+ }
+}
+
+type SavedLayoutIndex = {
+ byAssetId: Map<number, Node<CanvasAssetNodeData>>
+ orphanNodes: Node<CanvasAssetNodeData>[]
+ edges: Edge[]
+}
+
+/** 索引已保存画布节点(按 assetId) */
+function indexSavedLayout(rawNodes: unknown, rawEdges: unknown): SavedLayoutIndex {
+ const nodes = normalizeCanvasNodes(rawNodes)
+ const edges = normalizeCanvasEdges(rawEdges)
+ const byAssetId = new Map<number, Node<CanvasAssetNodeData>>()
+ const orphanNodes: Node<CanvasAssetNodeData>[] = []
+
+ for (const node of nodes) {
+ const assetId = node.data.assetId
+ if (typeof assetId === 'number' && assetId > 0) {
+ byAssetId.set(assetId, node)
+ } else {
+ orphanNodes.push(node)
+ }
+ }
+
+ return { byAssetId, orphanNodes, edges }
+}
+
+/**
+ * 合并项目资产与已保存布局:
+ * - 资产列表决定「有哪些节点」与媒体/文案
+ * - 已保存布局提供位置与连线
+ * - 尚无布局的资产按横向网格自动摆放(对齐参考「资产库编排」)
+ */
+export function mergeAssetsWithCanvasLayout(
+ assets: DramaAsset[],
+ savedNodes: unknown,
+ savedEdges: unknown,
+): { nodes: Node<CanvasAssetNodeData>[]; edges: Edge[] } {
+ const saved = indexSavedLayout(savedNodes, savedEdges)
+ const nodes: Node<CanvasAssetNodeData>[] = []
+ let maxRight = 0
+
+ for (const asset of assets) {
+ const data = buildNodeDataFromAsset(asset)
+ const kind = data.kind
+ const size = CANVAS_NODE_SIZE[kind]
+ const savedNode = saved.byAssetId.get(asset.id)
+
+ if (savedNode) {
+ nodes.push({
+ ...savedNode,
+ id: getCanvasNodeId(asset.id),
+ type: 'asset',
+ data: {
+ ...savedNode.data,
+ ...data,
+ textContent:
+ kind === 'text'
+ ? savedNode.data.textContent ?? data.textContent
+ : data.textContent,
+ },
+ })
+ maxRight = Math.max(maxRight, savedNode.position.x + size.width + 40)
+ } else {
+ nodes.push({
+ id: getCanvasNodeId(asset.id),
+ type: 'asset',
+ position: {
+ x: maxRight,
+ y: 80,
+ },
+ data,
+ })
+ maxRight += size.width + 40
+ }
+ }
+
+ /* 无 assetId 的旧自由节点仍保留,排在资产行下方 */
+ for (const orphan of saved.orphanNodes) {
+ nodes.push({
+ ...orphan,
+ position: {
+ x: orphan.position.x,
+ y: Math.max(orphan.position.y, 420),
+ },
+ })
+ }
+
+ /* 首次进入(无任何已保存位置)时整行横向排布 */
+ if (saved.byAssetId.size === 0 && assets.length > 0) {
+ let i = 0
+ for (const node of nodes) {
+ if (typeof node.data.assetId !== 'number') continue
+ const size = CANVAS_NODE_SIZE[node.data.kind]
+ node.position = { x: i * (size.width + 40), y: 80 }
+ i += 1
+ }
+ }
+
+ /* 过滤掉指向已删除资产的边 */
+ const nodeIds = new Set(nodes.map((n) => n.id))
+ const edges = saved.edges.filter((e) => nodeIds.has(e.source) && nodeIds.has(e.target))
+
+ return { nodes, edges }
+}
diff --git a/frontend/src/pages/drama/canvas/canvas.css b/frontend/src/pages/drama/canvas/canvas.css
new file mode 100644
index 0000000..95f3a9a
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/canvas.css
@@ -0,0 +1,828 @@
+/* 自由画布:全屏浮动工具栏与节点卡片 */
+
+.free-canvas-page {
+ --fc-bg: #eef1f4;
+ --fc-ink: #0f172a;
+ --fc-muted: #94a3b8;
+ --fc-line: rgba(0, 0, 0, 0.05);
+ --fc-panel: rgba(255, 255, 255, 0.95);
+ --fc-shadow: 0 1px 3px rgba(15, 23, 42, 0.08), 0 4px 16px rgba(15, 23, 42, 0.04);
+ position: fixed;
+ inset: 0;
+ width: 100vw;
+ height: 100svh;
+ overflow: hidden;
+ background: var(--fc-bg);
+ color: var(--fc-ink);
+ font-family: inherit;
+ z-index: 50;
+}
+
+.free-canvas-page .react-flow {
+ background: var(--fc-bg);
+}
+
+.free-canvas-page .react-flow__node {
+ font-size: 13px;
+}
+
+.free-canvas-page .react-flow__edge-path {
+ stroke: #94a3b8;
+ stroke-width: 2;
+}
+
+.free-canvas-page .react-flow__attribution {
+ display: none;
+}
+
+/* —— Overlays —— */
+.fc-overlay {
+ pointer-events: none;
+ position: absolute;
+ z-index: 30;
+}
+
+.fc-overlay > * {
+ pointer-events: auto;
+}
+
+.fc-topbar {
+ inset: 0 0 auto;
+ padding: 20px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.fc-topbar-left {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ min-width: 0;
+}
+
+.fc-topbar-title {
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--fc-ink);
+}
+
+.fc-save-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ color: #64748b;
+}
+
+.fc-save-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: #22c55e;
+}
+
+.fc-icon-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 40px;
+ height: 40px;
+ border: 1px solid var(--fc-line);
+ border-radius: 999px;
+ background: var(--fc-panel);
+ color: #334155;
+ box-shadow: var(--fc-shadow);
+ cursor: pointer;
+ backdrop-filter: blur(8px);
+ transition: background 0.15s ease, color 0.15s ease;
+}
+
+.fc-icon-btn:hover:not(:disabled) {
+ background: #fff;
+}
+
+.fc-icon-btn:disabled {
+ opacity: 0.35;
+ cursor: not-allowed;
+}
+
+.fc-icon-btn.is-active {
+ background: #f1f5f9;
+ color: var(--fc-ink);
+}
+
+.fc-icon-btn.is-primary {
+ background: #0f172a;
+ color: #fff;
+ border-color: transparent;
+}
+
+.fc-icon-btn.is-primary:hover:not(:disabled) {
+ background: #1e293b;
+}
+
+.fc-icon-btn.is-sm {
+ width: 32px;
+ height: 32px;
+}
+
+.fc-left-toolbar {
+ top: 50%;
+ left: 20px;
+ transform: translateY(-50%);
+}
+
+.fc-left-stack {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ padding: 8px;
+ border: 1px solid var(--fc-line);
+ border-radius: 999px;
+ background: var(--fc-panel);
+ box-shadow: var(--fc-shadow);
+ backdrop-filter: blur(8px);
+}
+
+.fc-add-panel {
+ position: absolute;
+ top: 0;
+ left: calc(100% + 12px);
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-width: 148px;
+ padding: 8px;
+ border: 1px solid var(--fc-line);
+ border-radius: 16px;
+ background: #fff;
+ box-shadow: var(--fc-shadow);
+}
+
+.fc-add-panel button {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ padding: 8px 10px;
+ border: none;
+ border-radius: 10px;
+ background: transparent;
+ color: var(--fc-ink);
+ font: inherit;
+ font-size: 13px;
+ cursor: pointer;
+ text-align: left;
+}
+
+.fc-add-panel button:hover {
+ background: #f8fafc;
+}
+
+.fc-add-panel-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ border-radius: 999px;
+ background: #f0f0f2;
+ color: #334155;
+}
+
+.fc-folder-panel {
+ position: absolute;
+ top: 0;
+ left: calc(100% + 12px);
+ width: 240px;
+ max-height: 360px;
+ overflow: auto;
+ padding: 12px;
+ border: 1px solid var(--fc-line);
+ border-radius: 16px;
+ background: #fff;
+ box-shadow: var(--fc-shadow);
+}
+
+.fc-folder-panel h4 {
+ margin: 0 0 8px;
+ font-size: 13px;
+ font-weight: 600;
+}
+
+.fc-folder-empty {
+ margin: 0;
+ font-size: 12px;
+ color: var(--fc-muted);
+}
+
+.fc-folder-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 8px;
+ border: none;
+ border-radius: 10px;
+ background: transparent;
+ color: var(--fc-ink);
+ font: inherit;
+ font-size: 13px;
+ cursor: pointer;
+ text-align: left;
+}
+
+.fc-folder-item:hover {
+ background: #f8fafc;
+}
+
+.fc-node-selector {
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 20;
+}
+
+.fc-node-selector-inner {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 16px;
+ width: min(1326px, calc(100vw - 48px));
+}
+
+.fc-node-selector-row {
+ display: flex;
+ flex-wrap: nowrap;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ width: 100%;
+}
+
+.fc-node-chip {
+ display: flex;
+ flex: 1 1 160px;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ max-width: 211px;
+ height: 64px;
+ padding: 0 12px;
+ border: 1px solid var(--fc-line);
+ border-radius: 12px;
+ background: #fff;
+ box-shadow: var(--fc-shadow);
+ color: var(--fc-ink);
+ font: inherit;
+ font-size: 14px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: transform 0.2s ease, box-shadow 0.2s ease;
+}
+
+.fc-node-chip:hover {
+ transform: translateY(-4px);
+ box-shadow: 0 8px 24px rgba(15, 23, 42, 0.1);
+}
+
+.fc-node-chip-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 32px;
+ border-radius: 999px;
+ background: #f0f0f2;
+ color: #334155;
+ flex-shrink: 0;
+}
+
+.fc-node-hint {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin: 0;
+ font-size: 14px;
+ color: var(--fc-muted);
+}
+
+.fc-bottom-controls {
+ bottom: 20px;
+ left: 20px;
+}
+
+.fc-bottom-bar {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 6px 8px;
+ border: 1px solid var(--fc-line);
+ border-radius: 999px;
+ background: var(--fc-panel);
+ box-shadow: var(--fc-shadow);
+ backdrop-filter: blur(8px);
+}
+
+.fc-bottom-sep {
+ width: 1px;
+ height: 20px;
+ margin: 0 4px;
+ background: #e2e8f0;
+}
+
+.fc-zoom-label {
+ min-width: 48px;
+ padding: 0 4px;
+ border: none;
+ background: transparent;
+ color: #334155;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ text-align: center;
+}
+
+.fc-error-toast {
+ position: absolute;
+ top: 88px;
+ left: 50%;
+ z-index: 40;
+ transform: translateX(-50%);
+ padding: 8px 16px;
+ border-radius: 999px;
+ background: #fef2f2;
+ color: #dc2626;
+ font-size: 13px;
+ pointer-events: none;
+}
+
+/* —— Asset node —— */
+.fc-asset-node {
+ position: relative;
+}
+
+.fc-asset-node-header {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 8px;
+ padding: 0 2px;
+ color: var(--fc-muted);
+ font-size: 12px;
+}
+
+.fc-asset-card {
+ display: flex;
+ flex-direction: column;
+ border-radius: 18px;
+ background: #fff;
+ border: 1px solid #e2e8f0;
+ overflow: hidden;
+ transition: box-shadow 0.2s ease;
+}
+
+.fc-asset-node.is-selected .fc-asset-card {
+ box-shadow: 0 8px 24px rgba(15, 23, 42, 0.12);
+ border-radius: 22px;
+}
+
+.fc-asset-body {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: #f8fafc;
+ color: #cbd5e1;
+}
+
+.fc-asset-body.is-character,
+.fc-asset-body.is-scene {
+ width: 200px;
+ height: 240px;
+}
+
+.fc-asset-body.is-image,
+.fc-asset-body.is-video {
+ width: 160px;
+ height: 220px;
+}
+
+.fc-asset-body.is-audio {
+ width: 200px;
+ height: 72px;
+}
+
+.fc-asset-body.is-text {
+ width: 280px;
+ min-height: 100px;
+ padding: 14px;
+ align-items: flex-start;
+ justify-content: flex-start;
+ color: var(--fc-ink);
+ font-size: 13px;
+ line-height: 1.5;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+.fc-asset-footer {
+ padding: 10px 12px;
+ border-top: 1px solid #f1f5f9;
+ font-size: 12px;
+ color: #64748b;
+}
+
+.fc-asset-media {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
+.fc-handle {
+ width: 10px !important;
+ height: 10px !important;
+ border: 2px solid #fff !important;
+ background: #64748b !important;
+ opacity: 0;
+}
+
+.fc-asset-node.is-selected .fc-handle,
+.fc-asset-node:hover .fc-handle {
+ opacity: 1;
+}
+
+.fc-settings-pop {
+ position: absolute;
+ top: 64px;
+ right: 20px;
+ z-index: 40;
+ width: 260px;
+ padding: 14px 16px;
+ border: 1px solid var(--fc-line);
+ border-radius: 16px;
+ background: #fff;
+ box-shadow: var(--fc-shadow);
+ font-size: 13px;
+ color: #64748b;
+ line-height: 1.5;
+}
+
+.fc-settings-pop strong {
+ display: block;
+ margin-bottom: 6px;
+ color: var(--fc-ink);
+ font-size: 14px;
+}
+
+/* —— Node toolbars / generate —— */
+.fc-hidden-input {
+ display: none;
+}
+
+.fc-node-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px;
+ border: 1px solid var(--fc-line);
+ border-radius: 999px;
+ background: #fff;
+ box-shadow: var(--fc-shadow);
+}
+
+.fc-toolbar-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 12px;
+ border: none;
+ border-radius: 999px;
+ background: transparent;
+ color: #334155;
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+ white-space: nowrap;
+}
+
+.fc-toolbar-chip:hover:not(:disabled) {
+ background: #f8fafc;
+}
+
+.fc-toolbar-chip:disabled {
+ opacity: 0.55;
+ cursor: wait;
+}
+
+.fc-generate-panel {
+ width: min(420px, calc(100vw - 48px));
+ padding: 12px;
+ border: 1px solid var(--fc-line);
+ border-radius: 16px;
+ background: #fff;
+ box-shadow: 0 8px 28px rgba(15, 23, 42, 0.12);
+}
+
+.fc-generate-head {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 8px;
+ color: #64748b;
+ font-size: 12px;
+ font-weight: 500;
+}
+
+.fc-generate-input {
+ width: 100%;
+ box-sizing: border-box;
+ min-height: 72px;
+ padding: 10px 12px;
+ border: 1px solid #e2e8f0;
+ border-radius: 12px;
+ resize: vertical;
+ font: inherit;
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--fc-ink);
+ background: #f8fafc;
+}
+
+.fc-generate-input:focus {
+ outline: none;
+ border-color: #94a3b8;
+ background: #fff;
+}
+
+.fc-generate-actions {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ margin-top: 8px;
+}
+
+.fc-generate-hint {
+ font-size: 11px;
+ color: var(--fc-muted);
+}
+
+.fc-generate-submit {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 32px;
+ border: none;
+ border-radius: 999px;
+ background: #0f172a;
+ color: #fff;
+ cursor: pointer;
+}
+
+.fc-generate-submit:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+
+.fc-generate-submit:hover:not(:disabled) {
+ background: #1e293b;
+}
+
+.fc-gen-opts {
+ position: relative;
+ margin-top: 8px;
+}
+
+.fc-gen-opts-triggers {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.fc-gen-opt-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ max-width: 148px;
+ height: 30px;
+ padding: 0 10px;
+ border: none;
+ border-radius: 999px;
+ background: transparent;
+ color: #475569;
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.fc-gen-opt-btn:hover:not(:disabled) {
+ background: #f1f5f9;
+}
+
+.fc-gen-opt-btn.active {
+ background: #f5f3ff;
+ color: #6d28d9;
+}
+
+.fc-gen-opt-btn:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+.fc-gen-opt-label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.fc-gen-opt-panel {
+ position: absolute;
+ left: 0;
+ bottom: calc(100% + 8px);
+ z-index: 30;
+ width: min(360px, calc(100vw - 64px));
+ max-height: 320px;
+ overflow: auto;
+ padding: 12px;
+ border: 1px solid #e2e8f0;
+ border-radius: 14px;
+ background: #fff;
+ box-shadow: 0 12px 32px rgba(15, 23, 42, 0.14);
+}
+
+.fc-gen-style-panel {
+ width: min(420px, calc(100vw - 48px));
+ max-height: 360px;
+}
+
+.fc-gen-opt-panel-title {
+ margin-bottom: 8px;
+ color: #0f172a;
+ font-size: 13px;
+ font-weight: 600;
+}
+
+.fc-gen-style-grid {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 8px;
+}
+
+.fc-gen-style-card {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 0;
+ border: 1px solid #e2e8f0;
+ border-radius: 10px;
+ overflow: hidden;
+ background: #fff;
+ cursor: pointer;
+ text-align: left;
+}
+
+.fc-gen-style-card img {
+ display: block;
+ width: 100%;
+ aspect-ratio: 16 / 10;
+ object-fit: cover;
+ background: #f8fafc;
+}
+
+.fc-gen-style-card span {
+ padding: 4px 6px 6px;
+ color: #334155;
+ font-size: 11px;
+ line-height: 1.3;
+}
+
+.fc-gen-style-card.selected {
+ border-color: #7c3aed;
+ box-shadow: 0 0 0 1px #7c3aed;
+}
+
+.fc-gen-model-list {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.fc-gen-model-item {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 10px 12px;
+ border: 1px solid #e2e8f0;
+ border-radius: 10px;
+ background: #fff;
+ text-align: left;
+ cursor: pointer;
+}
+
+.fc-gen-model-item strong {
+ color: #0f172a;
+ font-size: 13px;
+}
+
+.fc-gen-model-item span {
+ color: #64748b;
+ font-size: 11px;
+ line-height: 1.4;
+}
+
+.fc-gen-model-item.selected {
+ border-color: #7c3aed;
+ background: #faf5ff;
+}
+
+.fc-gen-chip-row {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.fc-gen-chip {
+ height: 28px;
+ padding: 0 10px;
+ border: 1px solid #e2e8f0;
+ border-radius: 999px;
+ background: #fff;
+ color: #475569;
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.fc-gen-chip.selected {
+ border-color: #7c3aed;
+ background: #f5f3ff;
+ color: #6d28d9;
+}
+
+.fc-text-editor {
+ width: 100%;
+ height: 100%;
+ min-height: 88px;
+ border: none;
+ resize: none;
+ background: transparent;
+ font: inherit;
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--fc-ink);
+ outline: none;
+}
+
+.fc-generating {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ color: #94a3b8;
+ font-size: 12px;
+}
+
+.fc-spin {
+ animation: fc-spin 0.8s linear infinite;
+}
+
+@keyframes fc-spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+.fc-asset-node.is-generating .fc-asset-card {
+ opacity: 0.92;
+}
+
+@media (max-width: 720px) {
+ .fc-node-selector-row {
+ flex-wrap: wrap;
+ }
+
+ .fc-node-chip {
+ flex: 1 1 calc(50% - 12px);
+ max-width: none;
+ }
+
+ .fc-left-toolbar {
+ left: 12px;
+ }
+
+ .fc-bottom-controls {
+ left: 12px;
+ right: 12px;
+ bottom: 12px;
+ }
+
+ .fc-bottom-bar {
+ flex-wrap: wrap;
+ border-radius: 20px;
+ }
+}
diff --git a/frontend/src/pages/drama/canvas/canvasHistory.ts b/frontend/src/pages/drama/canvas/canvasHistory.ts
new file mode 100644
index 0000000..4491e6d
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/canvasHistory.ts
@@ -0,0 +1,74 @@
+/** 画布撤销/重做历史栈纯函数 */
+import type { Edge, Node } from '@xyflow/react'
+import { MAX_CANVAS_HISTORY, type CanvasAssetNodeData } from './canvasTypes'
+
+export type CanvasSnapshot = {
+ nodes: Node<CanvasAssetNodeData>[]
+ edges: Edge[]
+}
+
+export type CanvasHistoryState = {
+ past: CanvasSnapshot[]
+ future: CanvasSnapshot[]
+}
+
+/** 创建空历史栈 */
+export function createEmptyCanvasHistory(): CanvasHistoryState {
+ return { past: [], future: [] }
+}
+
+/** 深拷贝画布快照 */
+export function cloneCanvasSnapshot(snapshot: CanvasSnapshot): CanvasSnapshot {
+ return JSON.parse(JSON.stringify(snapshot)) as CanvasSnapshot
+}
+
+/** 将快照压入 past 并清空 future */
+export function pushHistory(
+ history: CanvasHistoryState,
+ snapshot: CanvasSnapshot,
+): CanvasHistoryState {
+ const nextPast = [...history.past, cloneCanvasSnapshot(snapshot)]
+ const trimmedPast =
+ nextPast.length > MAX_CANVAS_HISTORY
+ ? nextPast.slice(nextPast.length - MAX_CANVAS_HISTORY)
+ : nextPast
+
+ return {
+ past: trimmedPast,
+ future: [],
+ }
+}
+
+/** 从 past 弹出上一快照并恢复 */
+export function undoHistory(
+ current: CanvasSnapshot,
+ history: CanvasHistoryState,
+): { snapshot: CanvasSnapshot; history: CanvasHistoryState } | null {
+ if (history.past.length === 0) return null
+
+ const previous = history.past[history.past.length - 1]
+ return {
+ snapshot: previous,
+ history: {
+ past: history.past.slice(0, -1),
+ future: [cloneCanvasSnapshot(current), ...history.future],
+ },
+ }
+}
+
+/** 从 future 弹出下一快照并恢复 */
+export function redoHistory(
+ current: CanvasSnapshot,
+ history: CanvasHistoryState,
+): { snapshot: CanvasSnapshot; history: CanvasHistoryState } | null {
+ if (history.future.length === 0) return null
+
+ const next = history.future[0]
+ return {
+ snapshot: next,
+ history: {
+ past: [...history.past, cloneCanvasSnapshot(current)],
+ future: history.future.slice(1),
+ },
+ }
+}
diff --git a/frontend/src/pages/drama/canvas/canvasNormalize.ts b/frontend/src/pages/drama/canvas/canvasNormalize.ts
new file mode 100644
index 0000000..769cae4
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/canvasNormalize.ts
@@ -0,0 +1,142 @@
+/** 将后端/旧版画布数据规范化为 xyflow 节点与边 */
+import type { Edge, Node } from '@xyflow/react'
+import {
+ CANVAS_NODE_DEFAULT_LABEL,
+ type CanvasAssetNodeData,
+ type CanvasNodeKind,
+} from './canvasTypes'
+
+const KIND_SET = new Set<CanvasNodeKind>([
+ 'character',
+ 'scene',
+ 'video',
+ 'image',
+ 'text',
+ 'audio',
+])
+
+/** 判断是否为合法节点类型 */
+function isCanvasNodeKind(value: unknown): value is CanvasNodeKind {
+ return typeof value === 'string' && KIND_SET.has(value as CanvasNodeKind)
+}
+
+/** 规范化单个节点(兼容旧 { id, label, x, y }) */
+export function normalizeCanvasNode(raw: unknown, index: number): Node<CanvasAssetNodeData> | null {
+ if (!raw || typeof raw !== 'object') return null
+ const item = raw as Record<string, unknown>
+ const id = String(item.id || `n-${index}`)
+
+ /* 新版 xyflow:position + data */
+ if (item.position && typeof item.position === 'object') {
+ const pos = item.position as { x?: unknown; y?: unknown }
+ const dataRaw = (item.data && typeof item.data === 'object' ? item.data : {}) as Record<
+ string,
+ unknown
+ >
+ const kind = isCanvasNodeKind(dataRaw.kind)
+ ? dataRaw.kind
+ : isCanvasNodeKind(item.type)
+ ? item.type
+ : 'image'
+ const label =
+ typeof dataRaw.label === 'string' && dataRaw.label
+ ? dataRaw.label
+ : CANVAS_NODE_DEFAULT_LABEL[kind]
+
+ return {
+ id,
+ type: 'asset',
+ position: {
+ x: Number(pos.x) || 0,
+ y: Number(pos.y) || 0,
+ },
+ data: {
+ kind,
+ label,
+ assetId: typeof dataRaw.assetId === 'number' ? dataRaw.assetId : undefined,
+ mediaUrl:
+ typeof dataRaw.mediaUrl === 'string'
+ ? dataRaw.mediaUrl
+ : typeof dataRaw.url === 'string'
+ ? dataRaw.url
+ : null,
+ textContent: typeof dataRaw.textContent === 'string' ? dataRaw.textContent : undefined,
+ },
+ }
+ }
+
+ /* 旧版绝对定位:x / y / label */
+ if ('x' in item || 'y' in item || 'label' in item) {
+ const label =
+ typeof item.label === 'string' && item.label
+ ? item.label
+ : CANVAS_NODE_DEFAULT_LABEL.image
+ return {
+ id,
+ type: 'asset',
+ position: {
+ x: Number(item.x) || 40 + (index % 5) * 180,
+ y: Number(item.y) || 40 + Math.floor(index / 5) * 120,
+ },
+ data: {
+ kind: 'image',
+ label,
+ },
+ }
+ }
+
+ return null
+}
+
+/** 规范化边列表 */
+export function normalizeCanvasEdges(raw: unknown): Edge[] {
+ if (!Array.isArray(raw)) return []
+ const edges: Edge[] = []
+ for (let i = 0; i < raw.length; i++) {
+ const item = raw[i]
+ if (!item || typeof item !== 'object') continue
+ const e = item as Record<string, unknown>
+ const source = String(e.source || '')
+ const target = String(e.target || '')
+ if (!source || !target || source === target) continue
+ edges.push({
+ id: String(e.id || `e-${source}-${target}-${i}`),
+ source,
+ target,
+ })
+ }
+ return edges
+}
+
+/** 规范化节点列表 */
+export function normalizeCanvasNodes(raw: unknown): Node<CanvasAssetNodeData>[] {
+ if (!Array.isArray(raw)) return []
+ const nodes: Node<CanvasAssetNodeData>[] = []
+ for (let i = 0; i < raw.length; i++) {
+ const node = normalizeCanvasNode(raw[i], i)
+ if (node) nodes.push(node)
+ }
+ return nodes
+}
+
+/** 计算新节点落在视口中心的坐标 */
+export function getViewportCenterNodePosition(
+ screenToFlowPosition: (p: { x: number; y: number }) => { x: number; y: number },
+ size: { width: number; height: number },
+) {
+ const pane = document.querySelector('.react-flow')
+ const bounds = pane?.getBoundingClientRect() ?? {
+ left: 0,
+ top: 0,
+ width: window.innerWidth,
+ height: window.innerHeight,
+ }
+ const center = screenToFlowPosition({
+ x: bounds.left + bounds.width / 2,
+ y: bounds.top + bounds.height / 2,
+ })
+ return {
+ x: center.x - size.width / 2,
+ y: center.y - size.height / 2,
+ }
+}
diff --git a/frontend/src/pages/drama/canvas/canvasTypes.ts b/frontend/src/pages/drama/canvas/canvasTypes.ts
new file mode 100644
index 0000000..97c47da
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/canvasTypes.ts
@@ -0,0 +1,104 @@
+/** 画布节点类型与选择器选项定义 */
+import type { LucideIcon } from 'lucide-react'
+import {
+ AudioLines,
+ Image as ImageIcon,
+ Landmark,
+ PlaySquare,
+ Text,
+ UserRound,
+} from 'lucide-react'
+
+export type CanvasNodeKind = 'character' | 'scene' | 'video' | 'image' | 'text' | 'audio'
+
+export type CanvasNodeOption = {
+ id: CanvasNodeKind
+ label: string
+ icon: LucideIcon
+}
+
+export type CanvasAssetNodeData = {
+ kind: CanvasNodeKind
+ label: string
+ assetId?: number
+ mediaUrl?: string | null
+ textContent?: string
+ generating?: boolean
+ [key: string]: unknown
+}
+
+/** 支持本地图片上传的节点类型 */
+export const CANVAS_UPLOADABLE_KINDS = new Set<CanvasNodeKind>([
+ 'character',
+ 'scene',
+ 'image',
+ 'video',
+])
+
+/** 支持 AI 生图的节点类型 */
+export const CANVAS_GENERATABLE_KINDS = new Set<CanvasNodeKind>([
+ 'character',
+ 'scene',
+ 'image',
+])
+
+/** 节点类型对应的 Drama asset_type */
+export function canvasKindToAssetType(kind: CanvasNodeKind): string {
+ if (kind === 'video') return 'video'
+ if (kind === 'audio') return 'audio'
+ if (kind === 'text') return 'text'
+ return 'image'
+}
+
+/** 空画布居中快速新建选项(顺序与设计稿一致) */
+export const CANVAS_NODE_OPTIONS: CanvasNodeOption[] = [
+ { id: 'character', label: '角色', icon: UserRound },
+ { id: 'scene', label: '场景', icon: Landmark },
+ { id: 'video', label: '视频', icon: PlaySquare },
+ { id: 'image', label: '图片', icon: ImageIcon },
+ { id: 'text', label: '文本', icon: Text },
+ { id: 'audio', label: '音频', icon: AudioLines },
+]
+
+/** 左侧添加面板选项 */
+export const ADD_NODE_OPTIONS: CanvasNodeOption[] = [
+ { id: 'character', label: '角色', icon: UserRound },
+ { id: 'scene', label: '场景', icon: Landmark },
+ { id: 'text', label: '文本', icon: Text },
+ { id: 'image', label: '图片', icon: ImageIcon },
+ { id: 'video', label: '视频', icon: PlaySquare },
+ { id: 'audio', label: '音频', icon: AudioLines },
+]
+
+export const CANVAS_NODE_OPTION_BY_KIND = Object.fromEntries(
+ CANVAS_NODE_OPTIONS.map((option) => [option.id, option]),
+) as Record<CanvasNodeKind, CanvasNodeOption>
+
+/** 各类型默认展示名 */
+export const CANVAS_NODE_DEFAULT_LABEL: Record<CanvasNodeKind, string> = {
+ character: '新角色',
+ scene: '新场景',
+ video: '新视频',
+ image: '新图片',
+ text: '文本',
+ audio: '新音频',
+}
+
+/** 节点卡片尺寸(宽 × 高,用于落点居中) */
+export const CANVAS_NODE_SIZE: Record<CanvasNodeKind, { width: number; height: number }> = {
+ character: { width: 200, height: 280 },
+ scene: { width: 200, height: 280 },
+ video: { width: 160, height: 240 },
+ image: { width: 160, height: 240 },
+ text: { width: 280, height: 140 },
+ audio: { width: 200, height: 100 },
+}
+
+/** 网格吸附步长 */
+export const CANVAS_SNAP_GRID: [number, number] = [20, 20]
+
+/** 自动保存防抖毫秒 */
+export const CANVAS_AUTO_SAVE_MS = 2000
+
+/** 历史栈最大深度 */
+export const MAX_CANVAS_HISTORY = 50
diff --git a/frontend/src/pages/drama/canvas/nodes/CanvasNodeGeneratePanel.tsx b/frontend/src/pages/drama/canvas/nodes/CanvasNodeGeneratePanel.tsx
new file mode 100644
index 0000000..14b1a96
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/nodes/CanvasNodeGeneratePanel.tsx
@@ -0,0 +1,112 @@
+/** 选中节点底部:AI 生图提示词面板(含风格/模型/画幅) */
+import { useEffect, useState, type FormEvent, type KeyboardEvent, type MouseEvent } from 'react'
+import { ArrowUp, Loader2, Sparkles } from 'lucide-react'
+import { useCanvasStore } from '../CanvasStore'
+import { CANVAS_GENERATABLE_KINDS, type CanvasNodeKind } from '../canvasTypes'
+import {
+ defaultOptionsForAssetKind,
+ type ImageGenerationOptions,
+} from '../../../../lib/dramaGenerationOptions'
+import { DramaImageGenOptionsBar } from './DramaImageGenOptionsBar'
+
+type CanvasNodeGeneratePanelProps = {
+ nodeId: string
+ kind: CanvasNodeKind
+ generating?: boolean
+ defaultPrompt?: string
+}
+
+/** 渲染 AI 生图编辑面板 */
+export function CanvasNodeGeneratePanel({
+ nodeId,
+ kind,
+ generating = false,
+ defaultPrompt = '',
+}: CanvasNodeGeneratePanelProps) {
+ const { generateNodeImage, setErrorMessage, projectImageStyleId } = useCanvasStore()
+ const [prompt, setPrompt] = useState(defaultPrompt)
+ const [busy, setBusy] = useState(false)
+ // options 生图风格/模型/画幅
+ const [options, setOptions] = useState<ImageGenerationOptions>(() => ({
+ ...defaultOptionsForAssetKind(kind),
+ image_style_id: projectImageStyleId || undefined,
+ }))
+
+ /* 切换节点或资产带入 visualImage 时同步提示词 */
+ useEffect(() => {
+ setPrompt(defaultPrompt)
+ }, [defaultPrompt, nodeId])
+
+ /* 节点类型或项目风格变化时同步默认选项 */
+ useEffect(() => {
+ setOptions((prev) => ({
+ ...defaultOptionsForAssetKind(kind),
+ image_style_id: prev.image_style_id || projectImageStyleId || undefined,
+ model_id: prev.model_id,
+ resolution: prev.resolution,
+ }))
+ }, [kind, nodeId, projectImageStyleId])
+
+ const isBusy = busy || generating
+ const canSubmit = prompt.trim().length > 0 && !isBusy
+
+ if (!CANVAS_GENERATABLE_KINDS.has(kind)) return null
+
+ const stopFlowEvent = (event: MouseEvent) => {
+ event.stopPropagation()
+ }
+
+ const submit = async () => {
+ if (!canSubmit) return
+ setBusy(true)
+ try {
+ await generateNodeImage(nodeId, prompt, options)
+ } catch (err) {
+ setErrorMessage(err instanceof Error ? err.message : '生图失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ const handleSubmit = (event: FormEvent) => {
+ event.preventDefault()
+ void submit()
+ }
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (event.key === 'Enter' && !event.shiftKey) {
+ event.preventDefault()
+ void submit()
+ }
+ }
+
+ return (
+ <form
+ className="fc-generate-panel nodrag nopan nowheel"
+ onMouseDown={stopFlowEvent}
+ onPointerDown={stopFlowEvent}
+ onSubmit={handleSubmit}
+ >
+ <div className="fc-generate-head">
+ <Sparkles size={14} strokeWidth={1.8} />
+ <span>AI 生图</span>
+ </div>
+ <textarea
+ className="fc-generate-input"
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ onKeyDown={handleKeyDown}
+ placeholder="描述你想要生成的画面内容…"
+ rows={3}
+ disabled={isBusy}
+ />
+ <DramaImageGenOptionsBar value={options} onChange={setOptions} disabled={isBusy} />
+ <div className="fc-generate-actions">
+ <span className="fc-generate-hint">Enter 生成 · Shift+Enter 换行</span>
+ <button type="submit" className="fc-generate-submit" disabled={!canSubmit} aria-label="生成">
+ {isBusy ? <Loader2 size={16} className="fc-spin" /> : <ArrowUp size={16} strokeWidth={2} />}
+ </button>
+ </div>
+ </form>
+ )
+}
diff --git a/frontend/src/pages/drama/canvas/nodes/CanvasNodeUploadBar.tsx b/frontend/src/pages/drama/canvas/nodes/CanvasNodeUploadBar.tsx
new file mode 100644
index 0000000..bbd39c6
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/nodes/CanvasNodeUploadBar.tsx
@@ -0,0 +1,64 @@
+/** 选中节点顶部:本地上传图片操作条 */
+import { useCallback, useRef, useState, type ChangeEvent, type MouseEvent } from 'react'
+import { Loader2, Upload } from 'lucide-react'
+import { useCanvasStore } from '../CanvasStore'
+import { CANVAS_UPLOADABLE_KINDS, type CanvasNodeKind } from '../canvasTypes'
+
+type CanvasNodeUploadBarProps = {
+ nodeId: string
+ kind: CanvasNodeKind
+}
+
+/** 渲染选中节点的上传操作条 */
+export function CanvasNodeUploadBar({ nodeId, kind }: CanvasNodeUploadBarProps) {
+ const { uploadNodeMedia, setErrorMessage } = useCanvasStore()
+ const fileInputRef = useRef<HTMLInputElement>(null)
+ const [uploading, setUploading] = useState(false)
+
+ if (!CANVAS_UPLOADABLE_KINDS.has(kind)) return null
+
+ const stopFlowEvent = useCallback((event: MouseEvent) => {
+ event.stopPropagation()
+ }, [])
+
+ const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0]
+ event.target.value = ''
+ if (!file) return
+
+ if (!file.type.startsWith('image/')) {
+ setErrorMessage('请选择图片文件')
+ return
+ }
+ if (file.size > 20 * 1024 * 1024) {
+ setErrorMessage('图片不能超过 20MB')
+ return
+ }
+
+ setUploading(true)
+ void uploadNodeMedia(nodeId, file)
+ .catch((err) => setErrorMessage(err instanceof Error ? err.message : '上传失败'))
+ .finally(() => setUploading(false))
+ }
+
+ return (
+ <div className="fc-node-toolbar nodrag nopan" onMouseDown={stopFlowEvent} onPointerDown={stopFlowEvent}>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/jpeg,image/png,image/webp,image/gif"
+ className="fc-hidden-input"
+ onChange={handleFileChange}
+ />
+ <button
+ type="button"
+ className="fc-toolbar-chip"
+ disabled={uploading}
+ onClick={() => fileInputRef.current?.click()}
+ >
+ {uploading ? <Loader2 size={14} className="fc-spin" /> : <Upload size={14} strokeWidth={1.8} />}
+ {uploading ? '上传中…' : '上传图片'}
+ </button>
+ </div>
+ )
+}
diff --git a/frontend/src/pages/drama/canvas/nodes/DramaImageGenOptionsBar.tsx b/frontend/src/pages/drama/canvas/nodes/DramaImageGenOptionsBar.tsx
new file mode 100644
index 0000000..b03bfd2
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/nodes/DramaImageGenOptionsBar.tsx
@@ -0,0 +1,195 @@
+/** 漫剧生图:风格 / 模型 / 画幅选择条(内置风格,无手填) */
+import { useEffect, useRef, useState, type MouseEvent } from 'react'
+import { BarChart3, ChevronDown, RectangleVertical, Smile } from 'lucide-react'
+import {
+ getImageStyleLabel,
+ IMAGE_STYLE_OPTIONS,
+ type ImageStyleId,
+} from '../../../../lib/dramaImageStyles'
+import {
+ formatOutputSettingsLabel,
+ GENERATION_ASPECT_RATIO_OPTIONS,
+ GENERATION_RESOLUTION_OPTIONS,
+ getImageModelLabel,
+ IMAGE_GENERATION_MODELS,
+ type GenerationAspectRatioId,
+ type GenerationResolution,
+ type ImageGenerationModelId,
+ type ImageGenerationOptions,
+} from '../../../../lib/dramaGenerationOptions'
+import './dramaImageGenOptions.css'
+
+type DramaImageGenOptionsBarProps = {
+ value: ImageGenerationOptions
+ onChange: (next: ImageGenerationOptions) => void
+ disabled?: boolean
+ /** 是否持久化风格到项目(Assets 步骤用) */
+ onStylePersist?: (styleId: string) => void | Promise<void>
+}
+
+type OpenPanel = 'style' | 'model' | 'output' | null
+
+/** 风格预览图 URL */
+function stylePreviewUrl(styleId: string): string {
+ const base = import.meta.env.BASE_URL.endsWith('/')
+ ? import.meta.env.BASE_URL
+ : `${import.meta.env.BASE_URL}/`
+ return `${base}image-styles/${styleId}.svg`
+}
+
+/** 渲染生图选项条:风格 · 模型 · 比例清晰度 */
+export function DramaImageGenOptionsBar({
+ value,
+ onChange,
+ disabled = false,
+ onStylePersist,
+}: DramaImageGenOptionsBarProps) {
+ const rootRef = useRef<HTMLDivElement>(null)
+ const [open, setOpen] = useState<OpenPanel>(null)
+
+ useEffect(() => {
+ if (!open) return
+ // 点击外部关闭弹层
+ function onDoc(e: Event) {
+ const target = e.target as Node | null
+ if (rootRef.current && target && !rootRef.current.contains(target)) {
+ setOpen(null)
+ }
+ }
+ document.addEventListener('mousedown', onDoc)
+ return () => document.removeEventListener('mousedown', onDoc)
+ }, [open])
+
+ const stop = (e: MouseEvent) => {
+ e.stopPropagation()
+ }
+
+ const styleLabel = getImageStyleLabel(value.image_style_id) || '风格'
+ const modelLabel = getImageModelLabel(value.model_id)
+ const outputLabel = formatOutputSettingsLabel(value.aspect_ratio, value.resolution)
+
+ return (
+ <div ref={rootRef} className="fc-gen-opts" onMouseDown={stop} onPointerDown={stop}>
+ <div className="fc-gen-opts-triggers">
+ <button
+ type="button"
+ className={`fc-gen-opt-btn${open === 'style' || value.image_style_id ? ' active' : ''}`}
+ disabled={disabled}
+ onClick={() => setOpen((c) => (c === 'style' ? null : 'style'))}
+ >
+ <Smile size={14} strokeWidth={1.8} />
+ <span className="fc-gen-opt-label">{styleLabel}</span>
+ <ChevronDown size={12} />
+ </button>
+ <button
+ type="button"
+ className={`fc-gen-opt-btn${open === 'model' ? ' active' : ''}`}
+ disabled={disabled}
+ onClick={() => setOpen((c) => (c === 'model' ? null : 'model'))}
+ >
+ <BarChart3 size={14} strokeWidth={1.8} />
+ <span className="fc-gen-opt-label">{modelLabel}</span>
+ <ChevronDown size={12} />
+ </button>
+ <button
+ type="button"
+ className={`fc-gen-opt-btn${open === 'output' ? ' active' : ''}`}
+ disabled={disabled}
+ onClick={() => setOpen((c) => (c === 'output' ? null : 'output'))}
+ >
+ <RectangleVertical size={14} strokeWidth={1.8} />
+ <span className="fc-gen-opt-label">{outputLabel}</span>
+ <ChevronDown size={12} />
+ </button>
+ </div>
+
+ {open === 'style' ? (
+ <div className="fc-gen-opt-panel fc-gen-style-panel" role="dialog" aria-label="图片风格">
+ <div className="fc-gen-opt-panel-title">图片风格</div>
+ <div className="fc-gen-style-grid">
+ {IMAGE_STYLE_OPTIONS.map((opt) => {
+ const selected = value.image_style_id === opt.id
+ return (
+ <button
+ key={opt.id}
+ type="button"
+ className={`fc-gen-style-card${selected ? ' selected' : ''}`}
+ onClick={() => {
+ onChange({ ...value, image_style_id: opt.id })
+ void onStylePersist?.(opt.id)
+ setOpen(null)
+ }}
+ >
+ <img src={stylePreviewUrl(opt.id)} alt="" loading="lazy" />
+ <span>{opt.label}</span>
+ </button>
+ )
+ })}
+ </div>
+ </div>
+ ) : null}
+
+ {open === 'model' ? (
+ <div className="fc-gen-opt-panel" role="dialog" aria-label="生图模型">
+ <div className="fc-gen-opt-panel-title">模型</div>
+ <div className="fc-gen-model-list">
+ {IMAGE_GENERATION_MODELS.map((m) => (
+ <button
+ key={m.id}
+ type="button"
+ className={`fc-gen-model-item${value.model_id === m.id ? ' selected' : ''}`}
+ onClick={() => {
+ onChange({ ...value, model_id: m.id as ImageGenerationModelId })
+ setOpen(null)
+ }}
+ >
+ <strong>{m.label}</strong>
+ <span>{m.description}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ ) : null}
+
+ {open === 'output' ? (
+ <div className="fc-gen-opt-panel" role="dialog" aria-label="输出设置">
+ <div className="fc-gen-opt-panel-title">比例</div>
+ <div className="fc-gen-chip-row">
+ {GENERATION_ASPECT_RATIO_OPTIONS.map((opt) => (
+ <button
+ key={opt.id}
+ type="button"
+ className={`fc-gen-chip${value.aspect_ratio === opt.id ? ' selected' : ''}`}
+ onClick={() =>
+ onChange({ ...value, aspect_ratio: opt.id as GenerationAspectRatioId })
+ }
+ >
+ {opt.label}
+ </button>
+ ))}
+ </div>
+ <div className="fc-gen-opt-panel-title" style={{ marginTop: 10 }}>
+ 清晰度
+ </div>
+ <div className="fc-gen-chip-row">
+ {GENERATION_RESOLUTION_OPTIONS.map((res) => (
+ <button
+ key={res}
+ type="button"
+ className={`fc-gen-chip${value.resolution === res ? ' selected' : ''}`}
+ onClick={() => {
+ onChange({ ...value, resolution: res as GenerationResolution })
+ setOpen(null)
+ }}
+ >
+ {res}
+ </button>
+ ))}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ )
+}
+
+export type { ImageStyleId }
diff --git a/frontend/src/pages/drama/canvas/nodes/dramaImageGenOptions.css b/frontend/src/pages/drama/canvas/nodes/dramaImageGenOptions.css
new file mode 100644
index 0000000..9a9536b
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/nodes/dramaImageGenOptions.css
@@ -0,0 +1,187 @@
+/* 漫剧生图选项条:风格 / 模型 / 画幅 */
+
+.fc-gen-opts {
+ position: relative;
+ margin-top: 8px;
+}
+
+.fc-gen-opts-triggers {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.fc-gen-opt-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ max-width: 148px;
+ height: 30px;
+ padding: 0 10px;
+ border: none;
+ border-radius: 999px;
+ background: transparent;
+ color: #475569;
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.fc-gen-opt-btn:hover:not(:disabled) {
+ background: #f1f5f9;
+}
+
+.fc-gen-opt-btn.active {
+ background: #f5f3ff;
+ color: #6d28d9;
+}
+
+.fc-gen-opt-btn:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+.fc-gen-opt-label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.fc-gen-opt-panel {
+ position: absolute;
+ left: 0;
+ bottom: calc(100% + 8px);
+ z-index: 30;
+ width: min(360px, calc(100vw - 64px));
+ max-height: 320px;
+ overflow: auto;
+ padding: 12px;
+ border: 1px solid #e2e8f0;
+ border-radius: 14px;
+ background: #fff;
+ box-shadow: 0 12px 32px rgba(15, 23, 42, 0.14);
+}
+
+.drama-assets-gen-opts .fc-gen-opt-panel {
+ bottom: auto;
+ top: calc(100% + 8px);
+}
+
+.fc-gen-style-panel {
+ width: min(420px, calc(100vw - 48px));
+ max-height: 360px;
+}
+
+.fc-gen-opt-panel-title {
+ margin-bottom: 8px;
+ color: #0f172a;
+ font-size: 13px;
+ font-weight: 600;
+}
+
+.fc-gen-style-grid {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 8px;
+}
+
+.fc-gen-style-card {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 0;
+ border: 1px solid #e2e8f0;
+ border-radius: 10px;
+ overflow: hidden;
+ background: #fff;
+ cursor: pointer;
+ text-align: left;
+}
+
+.fc-gen-style-card img {
+ display: block;
+ width: 100%;
+ aspect-ratio: 16 / 10;
+ object-fit: cover;
+ background: #f8fafc;
+}
+
+.fc-gen-style-card span {
+ padding: 4px 6px 6px;
+ color: #334155;
+ font-size: 11px;
+ line-height: 1.3;
+}
+
+.fc-gen-style-card.selected {
+ border-color: #7c3aed;
+ box-shadow: 0 0 0 1px #7c3aed;
+}
+
+.fc-gen-model-list {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.fc-gen-model-item {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 10px 12px;
+ border: 1px solid #e2e8f0;
+ border-radius: 10px;
+ background: #fff;
+ text-align: left;
+ cursor: pointer;
+}
+
+.fc-gen-model-item strong {
+ color: #0f172a;
+ font-size: 13px;
+}
+
+.fc-gen-model-item span {
+ color: #64748b;
+ font-size: 11px;
+ line-height: 1.4;
+}
+
+.fc-gen-model-item.selected {
+ border-color: #7c3aed;
+ background: #faf5ff;
+}
+
+.fc-gen-chip-row {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.fc-gen-chip {
+ height: 28px;
+ padding: 0 10px;
+ border: 1px solid #e2e8f0;
+ border-radius: 999px;
+ background: #fff;
+ color: #475569;
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.fc-gen-chip.selected {
+ border-color: #7c3aed;
+ background: #f5f3ff;
+ color: #6d28d9;
+}
+
+.drama-assets-gen-opts {
+ margin: 0 0 1rem;
+ padding: 10px 12px;
+ border: 1px solid #e2e8f0;
+ border-radius: 12px;
+ background: #fff;
+}
+
+.drama-assets-gen-opts .fc-gen-opts {
+ margin-top: 0;
+}
diff --git a/frontend/src/pages/drama/canvas/useCanvasAutoSave.ts b/frontend/src/pages/drama/canvas/useCanvasAutoSave.ts
new file mode 100644
index 0000000..ef468fd
--- /dev/null
+++ b/frontend/src/pages/drama/canvas/useCanvasAutoSave.ts
@@ -0,0 +1,73 @@
+/** 画布布局脏标记 → 防抖自动保存 */
+import { useCallback, useEffect, useRef } from 'react'
+import type { Edge, Node } from '@xyflow/react'
+import { dramaApi } from '../../../api/drama'
+import { CANVAS_AUTO_SAVE_MS, type CanvasAssetNodeData } from './canvasTypes'
+
+type UseCanvasAutoSaveArgs = {
+ projectId: number
+ nodes: Node<CanvasAssetNodeData>[]
+ edges: Edge[]
+ dirty: boolean
+ enabled: boolean
+ onSaved: () => void
+ onError: (message: string) => void
+}
+
+/** 脏数据防抖保存到 drama canvas API */
+export function useCanvasAutoSave({
+ projectId,
+ nodes,
+ edges,
+ dirty,
+ enabled,
+ onSaved,
+ onError,
+}: UseCanvasAutoSaveArgs) {
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const savingRef = useRef(false)
+ const latestRef = useRef({ nodes, edges, projectId })
+ latestRef.current = { nodes, edges, projectId }
+
+ const flush = useCallback(async () => {
+ if (savingRef.current) return
+ const payload = latestRef.current
+ savingRef.current = true
+ try {
+ await dramaApi.saveCanvas({
+ project_id: payload.projectId,
+ nodes: payload.nodes.map((n) => ({
+ id: n.id,
+ type: n.type,
+ position: n.position,
+ data: n.data,
+ })),
+ edges: payload.edges.map((e) => ({
+ id: e.id,
+ source: e.source,
+ target: e.target,
+ })),
+ })
+ onSaved()
+ } catch (err) {
+ onError(err instanceof Error ? err.message : '自动保存失败')
+ } finally {
+ savingRef.current = false
+ }
+ }, [onError, onSaved])
+
+ useEffect(() => {
+ if (!enabled || !dirty) return
+
+ if (timerRef.current) clearTimeout(timerRef.current)
+ timerRef.current = setTimeout(() => {
+ void flush()
+ }, CANVAS_AUTO_SAVE_MS)
+
+ return () => {
+ if (timerRef.current) clearTimeout(timerRef.current)
+ }
+ }, [dirty, enabled, nodes, edges, flush])
+
+ return { flush }
+}
diff --git a/frontend/src/pages/drama/drama.css b/frontend/src/pages/drama/drama.css
new file mode 100644
index 0000000..7f50993
--- /dev/null
+++ b/frontend/src/pages/drama/drama.css
@@ -0,0 +1,1691 @@
+/* Drama module styles — PRINTFILM tokens (lime #b6ff00, white cards, 14px radius) */
+
+.drama-page {
+ --drama-lime: #b6ff00;
+ --drama-card: #ffffff;
+ --drama-radius: 14px;
+ --drama-ink: var(--pf-ink, #111);
+ --drama-muted: var(--pf-muted, #6b7280);
+ --drama-line: var(--pf-line, #e5e7eb);
+ --drama-bg: var(--pf-bg, #f7f7f5);
+ max-width: 1100px;
+ margin: 0 auto;
+ padding: 28px 20px 64px;
+}
+
+.drama-agent-page {
+ max-width: 920px;
+}
+
+.drama-agent-hero {
+ text-align: center;
+ padding: 28px 0 8px;
+}
+
+.drama-agent-hero h1 {
+ margin: 0;
+ font-size: clamp(2rem, 4vw, 2.75rem);
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ color: var(--drama-ink);
+}
+
+.drama-agent-panel {
+ background: var(--drama-card);
+ border: 1px solid var(--drama-line);
+ border-radius: var(--drama-radius);
+ overflow: hidden;
+ margin: 20px 0 28px;
+ box-shadow: 0 1px 0 rgba(15, 23, 42, 0.04);
+}
+
+.drama-agent-tabs {
+ display: flex;
+ background: #e8e8ec;
+}
+
+.drama-agent-tabs button {
+ flex: 1;
+ height: 42px;
+ border: none;
+ background: transparent;
+ font: inherit;
+ font-weight: 600;
+ color: var(--drama-muted);
+ cursor: pointer;
+}
+
+.drama-agent-tabs button.active {
+ background: var(--drama-card);
+ color: var(--drama-ink);
+ border-radius: var(--drama-radius) var(--drama-radius) 0 0;
+}
+
+.drama-agent-tabs button:disabled {
+ opacity: 0.6;
+ cursor: wait;
+}
+
+.drama-agent-ai {
+ padding: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.drama-agent-ai textarea {
+ width: 100%;
+ box-sizing: border-box;
+ min-height: 144px;
+ border: 1px solid var(--drama-line);
+ border-radius: 12px;
+ padding: 12px 14px;
+ font: inherit;
+ resize: vertical;
+ background: #fff;
+}
+
+.drama-agent-ai textarea:focus {
+ outline: 2px solid color-mix(in srgb, var(--drama-lime) 55%, transparent);
+ border-color: var(--drama-lime);
+}
+
+.drama-agent-ai-footer {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.drama-agent-ai-options {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 10px;
+}
+
+.drama-agent-ai-options label,
+.drama-style-select {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 13px;
+ color: var(--drama-muted);
+ font-weight: 600;
+}
+
+.drama-agent-ai-options select,
+.drama-style-select select,
+.drama-search-input,
+.drama-title-input {
+ border: 1px solid var(--drama-line);
+ border-radius: 999px;
+ padding: 6px 12px;
+ font: inherit;
+ background: #fff;
+ color: var(--drama-ink);
+}
+
+.drama-btn-primary {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ height: 36px;
+ padding: 0 20px;
+ border: none;
+ border-radius: 999px;
+ background: var(--drama-lime);
+ color: var(--drama-ink);
+ font: inherit;
+ font-weight: 600;
+ cursor: pointer;
+}
+
+.drama-btn-primary:disabled {
+ background: #e8e8ec;
+ color: #9ca3af;
+ cursor: not-allowed;
+}
+
+.drama-btn-primary:not(:disabled):hover {
+ filter: brightness(0.97);
+}
+
+.drama-agent-error {
+ text-align: center;
+}
+
+.drama-project-section h2 {
+ margin: 0 0 14px;
+ font-size: 18px;
+}
+
+.drama-project-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
+ gap: 14px;
+}
+
+.drama-project-card {
+ display: flex;
+ flex-direction: column;
+ border: 1px solid var(--drama-line);
+ border-radius: var(--drama-radius);
+ background: var(--drama-card);
+ overflow: hidden;
+ text-align: left;
+ cursor: pointer;
+ padding: 0;
+ font: inherit;
+ color: inherit;
+ transition: transform 0.15s ease, box-shadow 0.15s ease;
+}
+
+.drama-project-card:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 8px 20px rgba(0, 0, 0, 0.06);
+ border-color: color-mix(in srgb, var(--drama-lime) 50%, var(--drama-line));
+}
+
+.drama-project-card-cover {
+ aspect-ratio: 16 / 10;
+ background: #ececef;
+ display: grid;
+ place-items: center;
+}
+
+.drama-project-card-icon {
+ width: 40px;
+ height: 40px;
+ border-radius: 50%;
+ background: #fff;
+ display: grid;
+ place-items: center;
+ color: var(--drama-muted);
+ font-size: 12px;
+}
+
+.drama-project-card-body {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 12px 14px;
+}
+
+.drama-project-card-body strong {
+ font-size: 14px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.drama-badge {
+ flex-shrink: 0;
+ font-size: 12px;
+ padding: 2px 8px;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--drama-lime) 35%, #fff);
+ color: var(--drama-ink);
+ font-weight: 600;
+}
+
+.drama-hero {
+ background: linear-gradient(135deg, #f4ffe6 0%, #ffffff 55%, #f7f7f5 100%);
+ border: 1px solid var(--drama-line);
+ border-radius: var(--drama-radius);
+ padding: 36px 32px;
+ margin-bottom: 24px;
+}
+
+.drama-eyebrow {
+ margin: 0 0 8px;
+ font-size: 12px;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--drama-muted);
+ font-weight: 600;
+}
+
+.drama-hero h1,
+.drama-header h1,
+.drama-panel h2,
+.drama-create h2,
+.drama-list h2 {
+ margin: 0 0 8px;
+ color: var(--drama-ink);
+ font-weight: 700;
+}
+
+.drama-lead {
+ margin: 0 0 20px;
+ font-size: 16px;
+ line-height: 1.6;
+ color: var(--drama-ink);
+ max-width: 36em;
+}
+
+.drama-muted {
+ color: var(--drama-muted);
+ font-size: 14px;
+ line-height: 1.5;
+}
+
+.drama-cta-row,
+.drama-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 10px;
+ align-items: center;
+}
+
+.drama-chat,
+.drama-create,
+.drama-panel {
+ background: var(--drama-card);
+ border: 1px solid var(--drama-line);
+ border-radius: var(--drama-radius);
+ padding: 20px 22px;
+ margin-bottom: 20px;
+}
+
+.drama-chat label,
+.drama-create label {
+ display: block;
+ margin-bottom: 8px;
+ font-weight: 600;
+ font-size: 14px;
+}
+
+.drama-chat textarea,
+.drama-create textarea,
+.drama-create input,
+.drama-frag-card textarea {
+ width: 100%;
+ box-sizing: border-box;
+ border: 1px solid var(--drama-line);
+ border-radius: 10px;
+ padding: 10px 12px;
+ font: inherit;
+ margin-bottom: 12px;
+ background: #fff;
+ color: var(--drama-ink);
+ resize: vertical;
+}
+
+.drama-chat textarea:focus,
+.drama-create textarea:focus,
+.drama-create input:focus,
+.drama-frag-card textarea:focus {
+ outline: 2px solid color-mix(in srgb, var(--drama-lime) 55%, transparent);
+ border-color: var(--drama-lime);
+}
+
+.drama-reply {
+ margin-top: 14px;
+ padding: 14px;
+ background: #fafafa;
+ border: 1px solid var(--drama-line);
+ border-radius: 10px;
+ white-space: pre-wrap;
+ font-size: 13px;
+ line-height: 1.55;
+ overflow: auto;
+}
+
+.drama-error {
+ color: #b91c1c;
+ font-size: 14px;
+ margin: 10px 0 0;
+}
+
+.drama-header {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: space-between;
+ align-items: flex-start;
+ gap: 16px;
+ margin-bottom: 20px;
+}
+
+.drama-back {
+ display: inline-block;
+ margin-bottom: 8px;
+ color: var(--drama-muted);
+ text-decoration: none;
+ font-size: 13px;
+}
+
+.drama-back:hover {
+ color: var(--drama-ink);
+}
+
+.drama-list ul,
+.drama-episode-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.drama-list li a,
+.drama-episode-list li {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 12px;
+ padding: 14px 16px;
+ background: var(--drama-card);
+ border: 1px solid var(--drama-line);
+ border-radius: var(--drama-radius);
+ text-decoration: none;
+ color: var(--drama-ink);
+}
+
+.drama-list li a:hover,
+.drama-episode-list li:hover {
+ border-color: color-mix(in srgb, var(--drama-lime) 70%, var(--drama-line));
+}
+
+.drama-list li span,
+.drama-episode-list li span {
+ color: var(--drama-muted);
+ font-size: 13px;
+}
+
+.drama-steps {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-bottom: 18px;
+}
+
+.drama-steps button {
+ border: 1px solid var(--drama-line);
+ background: var(--drama-card);
+ border-radius: 999px;
+ padding: 8px 16px;
+ font: inherit;
+ cursor: pointer;
+ color: var(--drama-muted);
+}
+
+.drama-steps button.active,
+.drama-steps button:hover {
+ background: var(--drama-lime);
+ border-color: var(--drama-lime);
+ color: var(--drama-ink);
+ font-weight: 600;
+}
+
+.drama-asset-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
+ gap: 14px;
+ margin-top: 14px;
+}
+
+.drama-asset-card {
+ background: #fafafa;
+ border: 1px solid var(--drama-line);
+ border-radius: var(--drama-radius);
+ padding: 12px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.drama-asset-card img,
+.drama-asset-placeholder {
+ width: 100%;
+ aspect-ratio: 1;
+ object-fit: cover;
+ border-radius: 10px;
+ background: #eee;
+}
+
+.drama-asset-placeholder {
+ display: grid;
+ place-items: center;
+ color: var(--drama-muted);
+ font-size: 12px;
+ text-transform: uppercase;
+}
+
+.drama-asset-card h3 {
+ margin: 0;
+ font-size: 14px;
+}
+
+.drama-asset-card p {
+ margin: 0;
+ font-size: 12px;
+ color: var(--drama-muted);
+}
+
+.drama-asset-tabs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.drama-asset-tabs button {
+ border: 1px solid var(--drama-line);
+ background: var(--drama-card);
+ border-radius: 999px;
+ padding: 7px 14px;
+ font: inherit;
+ cursor: pointer;
+ color: var(--drama-muted);
+}
+
+.drama-asset-tabs button.active {
+ background: var(--drama-lime);
+ border-color: var(--drama-lime);
+ color: var(--drama-ink);
+ font-weight: 600;
+}
+
+.drama-library-toolbar {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin-bottom: 16px;
+}
+
+.drama-search-input {
+ min-width: 220px;
+ border-radius: 10px;
+ padding: 8px 12px;
+}
+
+.drama-frag-list {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ margin-top: 14px;
+}
+
+.drama-frag-card {
+ background: var(--drama-card);
+ border: 1px solid var(--drama-line);
+ border-radius: var(--drama-radius);
+ padding: 16px;
+}
+
+.drama-frag-card.selected {
+ border-color: var(--drama-lime);
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--drama-lime) 40%, transparent);
+}
+
+.drama-frag-card header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 8px;
+ font-weight: 600;
+}
+
+.drama-video {
+ width: 100%;
+ max-height: 280px;
+ border-radius: 10px;
+ background: #111;
+ margin-top: 8px;
+}
+
+/* —— Workspace —— */
+.drama-workspace {
+ --drama-lime: #b6ff00;
+ --drama-card: #ffffff;
+ --drama-radius: 14px;
+ --drama-ink: #111;
+ --drama-muted: #6b7280;
+ --drama-line: #e5e7eb;
+ min-height: calc(100vh - 64px);
+ background: #f5f5f5;
+}
+
+.drama-workspace-status {
+ display: flex;
+ min-height: 40vh;
+ align-items: center;
+ justify-content: center;
+ color: var(--drama-muted, #6b7280);
+ font-size: 14px;
+}
+
+.drama-workspace-top {
+ position: sticky;
+ top: 0;
+ z-index: 20;
+ display: grid;
+ grid-template-columns: 1fr auto 1fr;
+ align-items: center;
+ gap: 12px;
+ height: 64px;
+ padding: 0 16px;
+ border-bottom: 1px solid rgba(0, 0, 0, 0.05);
+ background: rgba(245, 245, 245, 0.95);
+ backdrop-filter: blur(8px);
+}
+
+.drama-workspace-top-left,
+.drama-workspace-top-right {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+}
+
+.drama-workspace-top-right {
+ justify-content: flex-end;
+}
+
+.drama-icon-btn {
+ width: 36px;
+ height: 36px;
+ border: none;
+ border-radius: 50%;
+ background: transparent;
+ cursor: pointer;
+ font-size: 18px;
+ color: #64748b;
+}
+
+.drama-icon-btn:hover {
+ background: rgba(0, 0, 0, 0.05);
+}
+
+.drama-title-display {
+ border: none;
+ background: transparent;
+ font: inherit;
+ font-weight: 600;
+ font-size: 15px;
+ cursor: pointer;
+ padding: 4px 8px;
+ border-radius: 8px;
+ max-width: 280px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.drama-title-display:hover {
+ background: rgba(0, 0, 0, 0.04);
+}
+
+.drama-title-input {
+ min-width: 180px;
+ max-width: 280px;
+ border-radius: 8px;
+ padding: 6px 10px;
+}
+
+.drama-step-bar {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.drama-step-bar-item {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.drama-step-bar button {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ border: none;
+ background: transparent;
+ cursor: pointer;
+ font: inherit;
+ color: #94a3b8;
+ padding: 4px;
+}
+
+.drama-step-bar button.active {
+ color: #0f172a;
+ font-weight: 600;
+}
+
+.drama-step-bar button.done {
+ color: #64748b;
+}
+
+.drama-step-num {
+ width: 24px;
+ height: 24px;
+ border-radius: 50%;
+ display: grid;
+ place-items: center;
+ font-size: 12px;
+ font-weight: 700;
+ background: #f1f5f9;
+ color: #94a3b8;
+}
+
+.drama-step-bar button.active .drama-step-num {
+ background: #111;
+ color: #fff;
+}
+
+.drama-step-bar button.done .drama-step-num {
+ background: #e2e8f0;
+ color: #475569;
+}
+
+.drama-step-sep {
+ color: #cbd5e1;
+ font-size: 14px;
+ margin: 0 2px;
+}
+
+.drama-next-btn {
+ height: 36px;
+ padding: 0 20px;
+ border: none;
+ border-radius: 999px;
+ background: #111;
+ color: #fff;
+ font: inherit;
+ font-weight: 600;
+ cursor: pointer;
+}
+
+.drama-next-btn:disabled {
+ background: #e2e8f0;
+ color: #94a3b8;
+ cursor: not-allowed;
+}
+
+.drama-workspace-banner {
+ max-width: 920px;
+ margin: 12px auto 0;
+ padding: 0 16px;
+}
+
+.drama-workspace-main {
+ padding-bottom: 48px;
+}
+
+/* Outline */
+.drama-outline {
+ display: flex;
+ gap: 0;
+ max-width: 1200px;
+ margin: 0 auto;
+ padding: 0 12px;
+}
+
+.drama-episode-dir {
+ position: sticky;
+ top: 80px;
+ align-self: flex-start;
+ width: 180px;
+ flex-shrink: 0;
+ padding: 24px 8px;
+}
+
+.drama-episode-dir h3 {
+ margin: 0 0 10px;
+ font-size: 13px;
+ color: var(--drama-muted);
+}
+
+.drama-episode-dir ul {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ max-height: calc(100vh - 140px);
+ overflow: auto;
+}
+
+.drama-episode-dir button {
+ width: 100%;
+ text-align: left;
+ border: none;
+ background: transparent;
+ border-radius: 10px;
+ padding: 8px 10px;
+ cursor: pointer;
+ font: inherit;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.drama-episode-dir button span {
+ font-size: 13px;
+ font-weight: 600;
+ color: #334155;
+}
+
+.drama-episode-dir button small {
+ font-size: 11px;
+ color: var(--drama-muted);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.drama-episode-dir button.active,
+.drama-episode-dir button:hover {
+ background: #fff;
+}
+
+.drama-outline-main {
+ flex: 1;
+ min-width: 0;
+ max-width: 920px;
+ padding: 24px 12px 48px;
+}
+
+.drama-outline-toolbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin-bottom: 12px;
+}
+
+.drama-outline-toolbar h2 {
+ margin: 0;
+ font-size: 15px;
+ font-weight: 600;
+}
+
+.drama-accordions {
+ background: var(--drama-card);
+ border-radius: var(--drama-radius) var(--drama-radius) 0 0;
+ overflow: hidden;
+ box-shadow: 0 1px 0 rgba(15, 23, 42, 0.04);
+}
+
+.drama-accordion {
+ border-bottom: 1px solid var(--drama-line);
+}
+
+.drama-accordion-head {
+ flex: 1;
+ width: 100%;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 16px 18px;
+ border: none;
+ background: #fff;
+ font: inherit;
+ font-weight: 600;
+ cursor: pointer;
+ text-align: left;
+}
+
+.drama-accordion-head-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding-right: 12px;
+ background: #fff;
+}
+
+.drama-accordion-head-row .drama-accordion-head {
+ padding-right: 8px;
+}
+
+.drama-accordion-head:hover {
+ background: #fafafa;
+}
+
+.drama-regen-btn {
+ flex-shrink: 0;
+ border: none;
+ border-radius: 999px;
+ padding: 6px 14px;
+ font: inherit;
+ font-size: 12px;
+ font-weight: 600;
+ background: #0f172a;
+ color: #fff;
+ cursor: pointer;
+}
+
+.drama-regen-btn:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.drama-regen-inline {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 10px;
+ margin-bottom: 12px;
+}
+
+.drama-accordion-body {
+ padding: 0 18px 18px;
+}
+
+.drama-pre {
+ margin: 0;
+ white-space: pre-wrap;
+ font-family: inherit;
+ font-size: 14px;
+ line-height: 1.7;
+ color: #475569;
+}
+
+.drama-loader {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: var(--drama-muted);
+ font-size: 14px;
+}
+
+.drama-retry-block {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ align-items: flex-start;
+}
+
+.drama-summary-structured {
+ display: flex;
+ flex-direction: column;
+ gap: 18px;
+}
+
+.drama-summary-field h4,
+.drama-summary-structured h4 {
+ margin: 0 0 6px;
+ font-size: 14px;
+ font-weight: 600;
+ color: #1e293b;
+}
+
+.drama-character-list {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.drama-character-card {
+ background: #f8fafc;
+ border-radius: 12px;
+ padding: 14px;
+}
+
+.drama-character-card h5 {
+ margin: 0 0 10px;
+ font-size: 14px;
+}
+
+.drama-character-field {
+ margin-bottom: 8px;
+}
+
+.drama-character-field span {
+ display: block;
+ font-size: 11px;
+ color: #94a3b8;
+ margin-bottom: 2px;
+}
+
+.drama-character-field p {
+ margin: 0;
+ font-size: 13px;
+ line-height: 1.55;
+ color: #475569;
+ white-space: pre-wrap;
+}
+
+.drama-episode-bodies {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.drama-episode-body-item {
+ border: 1px solid var(--drama-line);
+ border-radius: 10px;
+ overflow: hidden;
+}
+
+.drama-episode-body-toggle {
+ width: 100%;
+ display: flex;
+ justify-content: space-between;
+ padding: 10px 12px;
+ border: none;
+ background: #fafafa;
+ font: inherit;
+ font-weight: 600;
+ cursor: pointer;
+}
+
+.drama-episode-body-item .drama-pre {
+ padding: 12px;
+}
+
+/* Assets / Episodes steps */
+.drama-assets-step,
+.drama-episodes-step {
+ max-width: 920px;
+ margin: 0 auto;
+ padding: 28px 16px 64px;
+}
+
+.drama-assets-toolbar {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin-bottom: 8px;
+}
+
+.drama-episodes-head {
+ margin-bottom: 20px;
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.drama-episodes-head h2 {
+ margin: 0 0 4px;
+ font-size: 26px;
+}
+
+.drama-episode-cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
+ gap: 14px;
+}
+
+.drama-episode-card {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ background: var(--drama-card);
+ border-radius: var(--drama-radius);
+ padding: 14px;
+ border: 1px solid var(--drama-line);
+}
+
+.drama-episode-card-thumb {
+ width: 72px;
+ height: 72px;
+ border-radius: 12px;
+ background: #efeff4;
+ display: grid;
+ place-items: center;
+ color: var(--drama-muted);
+ flex-shrink: 0;
+}
+
+.drama-episode-card-body {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.drama-episode-card-body span {
+ font-size: 13px;
+ color: var(--drama-muted);
+}
+
+/* Episode edit — manju-style fullscreen workspace */
+.drama-ep-fullscreen {
+ --ep-bg: #f5f5f5;
+ --ep-panel: #ffffff;
+ --ep-muted: #6b7280;
+ --ep-ink: #0f172a;
+ --ep-line: rgba(0, 0, 0, 0.05);
+ --ep-soft: #efeff4;
+ height: 100svh;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ background: var(--ep-bg);
+ color: var(--ep-ink);
+ font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
+}
+
+.drama-ep-center {
+ align-items: center;
+ justify-content: center;
+ color: var(--ep-muted);
+ font-size: 14px;
+}
+
+.drama-ep-header {
+ height: 56px;
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ padding: 0 16px;
+ border-bottom: 1px solid var(--ep-line);
+ background: rgba(245, 245, 245, 0.95);
+ backdrop-filter: blur(8px);
+}
+
+.drama-ep-header-left {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+}
+
+.drama-ep-header-left h1 {
+ margin: 0;
+ font-size: 16px;
+ font-weight: 600;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.drama-ep-header-controls {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ justify-content: flex-end;
+}
+
+.drama-ep-select {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ color: var(--ep-muted);
+}
+
+.drama-ep-select span {
+ display: none;
+}
+
+.drama-ep-select select {
+ border: none;
+ background: #fff;
+ border-radius: 999px;
+ padding: 6px 12px;
+ font: inherit;
+ color: var(--ep-ink);
+ box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.04);
+ cursor: pointer;
+}
+
+.drama-ep-icon-btn {
+ width: 36px;
+ height: 36px;
+ border: none;
+ border-radius: 999px;
+ background: transparent;
+ color: #475569;
+ font-size: 22px;
+ line-height: 1;
+ cursor: pointer;
+}
+
+.drama-ep-icon-btn:hover {
+ background: rgba(0, 0, 0, 0.05);
+}
+
+.drama-ep-icon-btn.solid {
+ background: #fff;
+ font-size: 18px;
+}
+
+.drama-ep-banner {
+ padding: 6px 16px;
+ font-size: 12px;
+ color: var(--ep-muted);
+ border-bottom: 1px solid var(--ep-line);
+}
+
+.drama-ep-banner-error {
+ color: #dc2626;
+}
+
+.drama-ep-body {
+ flex: 1;
+ min-height: 0;
+ display: grid;
+ grid-template-columns: 300px minmax(0, 1fr) 420px;
+}
+
+.drama-ep-assets {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ border-right: 1px solid var(--ep-line);
+ background: #f7f7f8;
+}
+
+.drama-ep-assets-top {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 12px;
+ border-bottom: 1px solid var(--ep-line);
+}
+
+.drama-ep-scope {
+ display: inline-flex;
+ padding: 2px;
+ border-radius: 999px;
+ background: #fff;
+}
+
+.drama-ep-scope button {
+ border: none;
+ background: transparent;
+ border-radius: 999px;
+ padding: 4px 12px;
+ font-size: 12px;
+ color: #64748b;
+ cursor: pointer;
+}
+
+.drama-ep-scope button.active {
+ background: #0f172a;
+ color: #fff;
+}
+
+.drama-ep-asset-tabs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ padding: 8px 12px;
+}
+
+.drama-ep-asset-tabs button {
+ border: none;
+ border-radius: 999px;
+ padding: 4px 10px;
+ font-size: 12px;
+ background: #fff;
+ color: #475569;
+ cursor: pointer;
+}
+
+.drama-ep-asset-tabs button.active {
+ background: #0f172a;
+ color: #fff;
+}
+
+.drama-ep-asset-grid {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ padding: 0 12px 16px;
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 8px;
+ align-content: start;
+}
+
+.drama-ep-asset-card {
+ border: none;
+ border-radius: 12px;
+ background: #fff;
+ padding: 0;
+ overflow: hidden;
+ cursor: pointer;
+ text-align: left;
+ transition: box-shadow 0.15s ease;
+}
+
+.drama-ep-asset-card:hover {
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
+}
+
+.drama-ep-asset-card.scene {
+ grid-column: 1 / -1;
+}
+
+.drama-ep-asset-thumb {
+ aspect-ratio: 3 / 4;
+ background: var(--ep-soft);
+ display: grid;
+ place-items: center;
+ overflow: hidden;
+ color: #cbd5e1;
+ font-weight: 700;
+}
+
+.drama-ep-asset-card.scene .drama-ep-asset-thumb {
+ aspect-ratio: 4 / 3;
+}
+
+.drama-ep-asset-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
+.drama-ep-asset-name {
+ display: block;
+ padding: 8px 6px;
+ font-size: 12px;
+ color: #475569;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.drama-ep-empty {
+ grid-column: 1 / -1;
+ margin: 24px 0;
+ text-align: center;
+ font-size: 12px;
+ color: #94a3b8;
+ line-height: 1.5;
+}
+
+.drama-ep-editor {
+ min-width: 0;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ padding: 20px 24px 16px;
+ background: transparent;
+}
+
+.drama-ep-editor-head {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 12px;
+ margin-bottom: 12px;
+}
+
+.drama-ep-editor-head strong {
+ display: block;
+ font-size: 15px;
+}
+
+.drama-ep-editor-head p {
+ margin: 4px 0 0;
+ font-size: 12px;
+ color: var(--ep-muted);
+}
+
+.drama-ep-duration {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ color: var(--ep-muted);
+ white-space: nowrap;
+}
+
+.drama-ep-duration input {
+ width: 56px;
+ border: 1px solid #e5e7eb;
+ border-radius: 8px;
+ padding: 4px 8px;
+ font: inherit;
+}
+
+.drama-ep-editor-box {
+ flex: 1;
+ min-height: 0;
+ border-radius: 16px;
+ background: rgba(255, 255, 255, 0.72);
+ border: 1px solid transparent;
+ padding: 16px;
+ box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
+}
+
+.drama-ep-editor-box.editing {
+ background: #fff;
+ border-color: rgba(0, 0, 0, 0.08);
+}
+
+.drama-ep-editor-box textarea {
+ width: 100%;
+ height: 100%;
+ min-height: 280px;
+ border: none;
+ resize: none;
+ outline: none;
+ background: transparent;
+ font: inherit;
+ font-size: 14px;
+ line-height: 1.7;
+ color: var(--ep-ink);
+}
+
+.drama-ep-editor-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 10px;
+ margin-top: 14px;
+}
+
+.drama-ep-btn-ghost,
+.drama-ep-btn-dark {
+ border: none;
+ border-radius: 999px;
+ padding: 8px 18px;
+ font: inherit;
+ font-size: 13px;
+ cursor: pointer;
+}
+
+.drama-ep-btn-ghost {
+ background: #fff;
+ color: var(--ep-ink);
+ box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.06);
+}
+
+.drama-ep-btn-dark {
+ background: #0f172a;
+ color: #fff;
+}
+
+.drama-ep-btn-ghost:disabled,
+.drama-ep-btn-dark:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.drama-ep-preview {
+ min-height: 0;
+ border-left: 1px solid var(--ep-line);
+ background: #fff;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 20px 30px;
+}
+
+.drama-ep-player {
+ width: 100%;
+ max-width: 320px;
+ border-radius: 16px;
+ overflow: hidden;
+ background: #111;
+ aspect-ratio: 9 / 16;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.drama-ep-player.ratio-16x9 {
+ max-width: 100%;
+ aspect-ratio: 16 / 9;
+}
+
+.drama-ep-player.ratio-1x1 {
+ max-width: 320px;
+ aspect-ratio: 1 / 1;
+}
+
+.drama-ep-player video,
+.drama-ep-player img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+}
+
+.drama-ep-player-placeholder {
+ color: #94a3b8;
+ text-align: center;
+ display: grid;
+ gap: 6px;
+ font-size: 13px;
+}
+
+.drama-ep-player-placeholder small {
+ font-size: 11px;
+ opacity: 0.8;
+}
+
+.drama-ep-storyboard {
+ flex-shrink: 0;
+ border-top: 1px solid var(--ep-line);
+ background: #fff;
+ padding: 12px 16px 16px;
+}
+
+.drama-ep-storyboard-row {
+ display: flex;
+ align-items: flex-start;
+ gap: 4px;
+ overflow-x: auto;
+ padding-bottom: 4px;
+}
+
+.drama-ep-insert {
+ width: 28px;
+ height: 28px;
+ margin-top: 36px;
+ flex-shrink: 0;
+ border: none;
+ border-radius: 999px;
+ background: var(--ep-soft);
+ color: #64748b;
+ cursor: pointer;
+}
+
+.drama-ep-clip-wrap {
+ position: relative;
+ flex-shrink: 0;
+ padding-right: 28px;
+}
+
+.drama-ep-clip {
+ width: 112px;
+ border: 2px solid transparent;
+ border-radius: 14px;
+ background: transparent;
+ padding: 0;
+ cursor: pointer;
+ text-align: left;
+}
+
+.drama-ep-clip.active {
+ border-color: #fff;
+ box-shadow: 0 0 0 2px #0f172a;
+}
+
+.drama-ep-clip img,
+.drama-ep-clip video,
+.drama-ep-clip-empty {
+ width: 112px;
+ height: 72px;
+ border-radius: 12px;
+ object-fit: cover;
+ background: var(--ep-soft);
+ display: grid;
+ place-items: center;
+ color: #94a3b8;
+ font-size: 18px;
+}
+
+.drama-ep-clip em {
+ display: block;
+ margin-top: 6px;
+ font-style: normal;
+ font-size: 11px;
+ color: #64748b;
+ white-space: nowrap;
+}
+
+.drama-ep-clip-ops {
+ position: absolute;
+ top: 16px;
+ right: 0;
+ display: none;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.drama-ep-clip-wrap:hover .drama-ep-clip-ops {
+ display: flex;
+}
+
+.drama-ep-clip-ops button {
+ width: 24px;
+ height: 24px;
+ border: none;
+ border-radius: 8px;
+ background: var(--ep-soft);
+ color: #64748b;
+ cursor: pointer;
+ font-size: 12px;
+}
+
+.drama-ep-clip-ops button:disabled {
+ opacity: 0.35;
+ cursor: not-allowed;
+}
+
+@media (max-width: 1100px) {
+ .drama-ep-body {
+ grid-template-columns: 240px minmax(0, 1fr) 300px;
+ }
+}
+
+@media (max-width: 860px) {
+ .drama-ep-body {
+ grid-template-columns: 1fr;
+ overflow: auto;
+ }
+
+ .drama-ep-assets,
+ .drama-ep-preview {
+ border: none;
+ max-height: 280px;
+ }
+
+ .drama-ep-preview {
+ order: -1;
+ }
+}
+
+/* legacy episode edit hooks kept for other pages */
+.drama-episode-edit {
+ --drama-lime: #b6ff00;
+ --drama-card: #ffffff;
+ --drama-radius: 14px;
+ --drama-ink: #111;
+ --drama-muted: #6b7280;
+ --drama-line: #e5e7eb;
+ min-height: calc(100vh - 64px);
+ background: #f5f5f5;
+ display: flex;
+ flex-direction: column;
+}
+
+.drama-episode-edit-top {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 12px 16px;
+ border-bottom: 1px solid rgba(0, 0, 0, 0.05);
+ background: rgba(245, 245, 245, 0.95);
+}
+
+.drama-episode-edit-top h1 {
+ margin: 0;
+ font-size: 16px;
+ font-weight: 600;
+}
+
+.drama-episode-edit-layout {
+ display: grid;
+ grid-template-columns: 220px 1fr;
+ gap: 16px;
+ padding: 16px;
+ flex: 1;
+ min-height: 0;
+}
+
+.drama-episode-assets {
+ background: var(--drama-card);
+ border: 1px solid var(--drama-line);
+ border-radius: var(--drama-radius);
+ padding: 12px;
+}
+
+.drama-episode-assets h3 {
+ margin: 0 0 10px;
+ font-size: 13px;
+ color: var(--drama-muted);
+}
+
+.drama-storyboard-thumbs {
+ border-top: 1px solid var(--drama-line);
+ background: #fff;
+ padding: 12px 16px 20px;
+}
+
+.drama-storyboard-thumbs h3 {
+ margin: 0 0 10px;
+ font-size: 13px;
+ color: var(--drama-muted);
+}
+
+.drama-storyboard-row {
+ display: flex;
+ gap: 8px;
+ overflow-x: auto;
+}
+
+@media (max-width: 860px) {
+ .drama-workspace-top {
+ grid-template-columns: 1fr;
+ height: auto;
+ padding: 10px 12px;
+ }
+
+ .drama-outline {
+ flex-direction: column;
+ }
+
+ .drama-episode-dir {
+ position: static;
+ width: 100%;
+ padding: 12px 0 0;
+ }
+
+ .drama-episode-dir ul {
+ flex-direction: row;
+ overflow-x: auto;
+ max-height: none;
+ }
+
+ .drama-episode-dir button {
+ min-width: 110px;
+ }
+
+ .drama-episode-edit-layout {
+ grid-template-columns: 1fr;
+ }
+}
+
diff --git a/frontend/src/pages/drama/dramaEpisodeEditUtils.ts b/frontend/src/pages/drama/dramaEpisodeEditUtils.ts
new file mode 100644
index 0000000..ec1e6cd
--- /dev/null
+++ b/frontend/src/pages/drama/dramaEpisodeEditUtils.ts
@@ -0,0 +1,65 @@
+/** 分集编辑页辅助:资产分类、引用解析、标签文案 */
+import type { DramaAsset } from '../../api/drama'
+
+export type AssetScope = 'episode' | 'series'
+export type AssetTab = 'character' | 'scene' | 'prop' | 'material'
+
+export const ASSET_TABS: Array<{ key: AssetTab; label: string }> = [
+ { key: 'character', label: '角色' },
+ { key: 'scene', label: '场景' },
+ { key: 'material', label: '素材' },
+ { key: 'prop', label: '道具' },
+]
+
+export const MODEL_OPTIONS = [
+ { id: 'seedance-2.5', label: 'Seedance 2.5' },
+ { id: 'seedance-1.5', label: 'Seedance 1.5' },
+]
+
+export const RATIO_OPTIONS = ['9:16', '16:9', '1:1'] as const
+export const RES_OPTIONS = ['480p', '720p', '1080p'] as const
+
+// 从分镜正文提取 @asset:id
+export function extractAssetIds(content: string): number[] {
+ const ids: number[] = []
+ const re = /@asset:(\d+)/g
+ let m: RegExpExecArray | null
+ while ((m = re.exec(content))) {
+ ids.push(Number(m[1]))
+ }
+ return ids
+}
+
+// 规范化资产分类
+export function normalizeAssetTab(type: string): AssetTab | null {
+ const t = (type || '').toLowerCase()
+ if (t === 'character' || t === '角色') return 'character'
+ if (t === 'scene' || t === '场景') return 'scene'
+ if (t === 'prop' || t === '道具') return 'prop'
+ if (t === 'material' || t === '素材') return 'material'
+ return null
+}
+
+// 格式化片段标签
+export function formatFragLabel(index: number, durationSec: number | null | undefined) {
+ const n = String(index + 1).padStart(2, '0')
+ const sec = durationSec && durationSec > 0 ? durationSec : 8
+ return `片段 ${n} · ${sec}s`
+}
+
+// 按本集/全集与分类筛选资产
+export function filterEpisodeAssets(
+ assets: DramaAsset[],
+ scope: AssetScope,
+ tab: AssetTab | null,
+ referencedIds: Set<number>,
+): DramaAsset[] {
+ let list = assets.filter((a) => normalizeAssetTab(a.type))
+ if (scope === 'episode') {
+ list = list.filter((a) => referencedIds.has(a.id))
+ }
+ if (tab) {
+ list = list.filter((a) => normalizeAssetTab(a.type) === tab)
+ }
+ return list
+}
diff --git a/frontend/src/pages/drama/dramaWorkspaceUtils.ts b/frontend/src/pages/drama/dramaWorkspaceUtils.ts
new file mode 100644
index 0000000..8a2c003
--- /dev/null
+++ b/frontend/src/pages/drama/dramaWorkspaceUtils.ts
@@ -0,0 +1,31 @@
+/** Shared helpers for drama project workspace steps. */
+import type { DramaEpisodeBody, DramaProject, DramaScript } from '../../api/drama'
+
+// 解析 episode_content 为分集数组
+export function parseEpisodeBodies(script: DramaScript | null | undefined): DramaEpisodeBody[] {
+ const raw = script?.episode_content
+ if (!raw) return []
+ if (Array.isArray(raw)) return raw
+ if (Array.isArray(raw.episodes)) return raw.episodes
+ return []
+}
+
+// 读取摘要状态
+export function getSummaryStatus(script: DramaScript | null | undefined): string {
+ return String((script?.params || {}).summary_status || (script?.summary ? 'completed' : 'pending'))
+}
+
+// 读取分集剧本状态
+export function getEpisodeContentStatus(script: DramaScript | null | undefined): string {
+ return String((script?.params || {}).episode_content_status || 'pending')
+}
+
+// 读取画面风格 ID
+export function getImageStyleId(
+ script: DramaScript | null | undefined,
+ project: DramaProject | null,
+): string {
+ const fromScript = (script?.params || {}).image_style_id
+ const fromProject = (project?.params || {}).image_style_id
+ return String(fromScript || fromProject || '')
+}
diff --git a/frontend/src/pages/studio/StoryboardPage.tsx b/frontend/src/pages/studio/StoryboardPage.tsx
index 456eb90..b3a660b 100644
--- a/frontend/src/pages/studio/StoryboardPage.tsx
+++ b/frontend/src/pages/studio/StoryboardPage.tsx
@@ -28,40 +28,12 @@ import {
shotStatusLabel,
statusLabel,
} from '../../lib/status'
-
-type SegmentBeatView = { duration: number; text: string; isCue?: boolean }
-
-function parseSegmentScript(script: string | undefined | null): {
- cues: string[]
- beats: SegmentBeatView[]
-} {
- const cues: string[] = []
- const beats: SegmentBeatView[] = []
- const lines = String(script || '')
- .replace(/\r\n/g, '\n')
- .split('\n')
- .map((l) => l.trim())
- .filter(Boolean)
- let pendingDur = 0
- for (const line of lines) {
- if (line.startsWith('【字幕') || line.startsWith('【BGM')) {
- cues.push(line)
- continue
- }
- const m = line.match(/^@duration:(\d+)/)
- if (m) {
- pendingDur = Number(m[1]) || 0
- continue
- }
- if (pendingDur > 0 || beats.length === 0) {
- beats.push({ duration: pendingDur || 0, text: line })
- pendingDur = 0
- } else {
- beats.push({ duration: 0, text: line })
- }
- }
- return { cues, beats }
-}
+import {
+ SEGMENT_SCRIPT_PLACEHOLDER,
+ SHOT_DURATION_MAX,
+ parseSegmentScript,
+ validateSegmentScriptDuration,
+} from '../../lib/segmentDuration'
function csvEscape(value: string | number | null | undefined) {
const s = String(value ?? '')
@@ -208,6 +180,14 @@ export default function StoryboardPage() {
[project?.shots],
)
+ // editScriptText 弹窗中当前编辑的逐段脚本
+ const editScriptText = editing?.segment_script || editing?.video_prompt || ''
+ // editDurationCheck 弹窗脚本时长校验
+ const editDurationCheck = useMemo(
+ () => validateSegmentScriptDuration(editScriptText),
+ [editScriptText],
+ )
+
const shots = project?.shots || []
/** 项目字段为空时回显模板默认(与后端 _effective_* 一致) */
const promptDefaults = useMemo(
@@ -525,6 +505,14 @@ export default function StoryboardPage() {
async function saveShot() {
if (!project || !editing) return
+ // scriptText 当前编辑中的逐段脚本
+ const scriptText = editing.segment_script || editing.video_prompt || ''
+ // durationCheck 时长校验结果
+ const durationCheck = validateSegmentScriptDuration(scriptText)
+ if (!durationCheck.valid) {
+ setError(durationCheck.message || '分镜时长不合法')
+ return
+ }
setBusy(true)
try {
await api.updateShot(project.id, editing.id, {
@@ -1288,6 +1276,9 @@ export default function StoryboardPage() {
onChange={(e) => setEditing({ ...editing, narration: e.target.value })}
rows={3}
/>
+ <span className="pf-muted" style={{ fontSize: '0.75rem', marginTop: 4, display: 'block' }}>
+ 保存后将按脚本中旁白段回写
+ </span>
</label>
<label>
画面提示词(首帧)
@@ -1297,6 +1288,9 @@ export default function StoryboardPage() {
onChange={(e) => setEditing({ ...editing, img_prompt: e.target.value })}
rows={3}
/>
+ <span className="pf-muted" style={{ fontSize: '0.75rem', marginTop: 4, display: 'block' }}>
+ 保存后将按脚本首段画面回写
+ </span>
</label>
<label>
逐段分镜脚本(@duration + 字幕/BGM)
@@ -1311,11 +1305,40 @@ export default function StoryboardPage() {
})
}
rows={10}
- placeholder={
- '【字幕:全程简体中文字幕,旁白逐句同步烧录】\n【BGM:轻快专业,音量低于人声】\n@duration:4\n过肩工位操作画面…\n@duration:8\n【旁白·慢速清晰·同步字幕】口播内容…'
- }
+ placeholder={SEGMENT_SCRIPT_PLACEHOLDER}
/>
</label>
+ <div
+ className="pf-chips"
+ style={{ marginTop: '-0.35rem', marginBottom: '0.75rem', flexWrap: 'wrap' }}
+ >
+ {editDurationCheck.durations.length > 0 ? (
+ editDurationCheck.durations.map((sec, i) => (
+ <span key={`${sec}-${i}`} className="pf-chip" style={{ cursor: 'default' }}>
+ {sec}s
+ </span>
+ ))
+ ) : (
+ <span className="pf-muted" style={{ fontSize: '0.8rem' }}>
+ 暂无 @duration 标签
+ </span>
+ )}
+ <span
+ className="pf-muted"
+ style={{
+ fontSize: '0.8rem',
+ marginLeft: 'auto',
+ color: editDurationCheck.valid ? undefined : 'var(--pf-danger, #c0392b)',
+ }}
+ >
+ 合计 {editDurationCheck.total}s / {SHOT_DURATION_MAX}s
+ </span>
+ </div>
+ {!editDurationCheck.valid && editDurationCheck.message ? (
+ <p className="pf-error" style={{ margin: '0 0 0.75rem', fontSize: '0.85rem' }}>
+ {editDurationCheck.message}
+ </p>
+ ) : null}
<label>
运镜备注
<input
@@ -1334,7 +1357,12 @@ export default function StoryboardPage() {
</label>
</div>
<div style={{ display: 'flex', gap: '0.5rem' }}>
- <button type="button" className="pf-btn pf-btn-lime" disabled={busy} onClick={saveShot}>
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime"
+ disabled={busy || !editDurationCheck.valid}
+ onClick={saveShot}
+ >
保存
</button>
<button