Skip to content

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

feat(kepu): TokenFree 官方价 1:1 计费并收紧管理端与成片

yi3c211cba69c4
diff --git a/admin/src/components/admin/UserDetailDrawer.tsx b/admin/src/components/admin/UserDetailDrawer.tsx
index 6422ed9..9250e03 100644
--- a/admin/src/components/admin/UserDetailDrawer.tsx
+++ b/admin/src/components/admin/UserDetailDrawer.tsx
@@ -91,7 +91,6 @@ export function UserDetailDrawer({ userId, open, onOpenChange, initialUser }: Us
items={[
{ label: "昵称", value: user.nickname || "—" },
{ label: "手机", value: user.phone || "—" },
- { label: "套餐", value: user.plan },
{ label: "角色", value: user.role },
{ label: "余额", value: `¥${fenToYuan(user.balance_fen)}` },
{ label: "冻结", value: `¥${fenToYuan(user.frozen_fen)}` },
diff --git a/admin/src/components/settings/OssSettingsPanel.tsx b/admin/src/components/settings/OssSettingsPanel.tsx
index 8d10182..80678c5 100644
--- a/admin/src/components/settings/OssSettingsPanel.tsx
+++ b/admin/src/components/settings/OssSettingsPanel.tsx
@@ -10,17 +10,13 @@ import { SecretField } from "@/components/settings/SecretField";
import { Switch } from "@/components/ui/switch";
import { useAdminModelSettings } from "@/hooks/useAdminModelSettings";
-// OSS / TOS / CDN 存储配置
+// 阿里云 OSS 存储配置
export function OssSettingsPanel() {
const { form, loading, saving, patchField, save } = useAdminModelSettings();
const [ossKeyIdInput, setOssKeyIdInput] = useState("");
const [ossKeySecretInput, setOssKeySecretInput] = useState("");
- const [tosKeyInput, setTosKeyInput] = useState("");
- const [tosSecretInput, setTosSecretInput] = useState("");
const [clearOssId, setClearOssId] = useState(false);
const [clearOssSecret, setClearOssSecret] = useState(false);
- const [clearTosKey, setClearTosKey] = useState(false);
- const [clearTosSecret, setClearTosSecret] = useState(false);
const ossReady = useMemo(() => {
if (!form?.oss_enabled) return false;
@@ -31,13 +27,6 @@ export function OssSettingsPanel() {
return Boolean(form.oss_bucket && hasCreds && hasSecret);
}, [form, clearOssId, clearOssSecret, ossKeyIdInput, ossKeySecretInput]);
- const tosConfigured = useMemo(() => {
- if (!form) return false;
- const hasKey = (form.has_tos_access_key && !clearTosKey) || tosKeyInput.trim().length > 0;
- const hasSecret = (form.has_tos_secret_key && !clearTosSecret) || tosSecretInput.trim().length > 0;
- return Boolean(form.tos_bucket && hasKey && hasSecret);
- }, [form, clearTosKey, clearTosSecret, tosKeyInput, tosSecretInput]);
-
async function handleSave() {
if (!form) return;
await save(
@@ -54,24 +43,13 @@ export function OssSettingsPanel() {
oss_access_key_secret: ossKeySecretInput.trim() || undefined,
clear_oss_access_key_id: clearOssId,
clear_oss_access_key_secret: clearOssSecret,
- tos_endpoint: form.tos_endpoint,
- tos_bucket: form.tos_bucket,
- tos_access_key: tosKeyInput.trim() || undefined,
- tos_secret_key: tosSecretInput.trim() || undefined,
- clear_tos_access_key: clearTosKey,
- clear_tos_secret_key: clearTosSecret,
- cdn_base: form.cdn_base,
},
"存储配置已保存",
);
setOssKeyIdInput("");
setOssKeySecretInput("");
- setTosKeyInput("");
- setTosSecretInput("");
setClearOssId(false);
setClearOssSecret(false);
- setClearTosKey(false);
- setClearTosSecret(false);
}
if (loading || !form) {
@@ -97,13 +75,6 @@ export function OssSettingsPanel() {
readyText: "已开启",
pendingText: "已关闭",
},
- {
- id: "tos",
- label: "火山 TOS",
- ready: tosConfigured,
- readyText: "已配置",
- pendingText: "可选",
- },
]}
extra={
<span className="settings-status-extra">
@@ -157,7 +128,11 @@ export function OssSettingsPanel() {
onChange={(e) => patchField("oss_folder", e.target.value)}
/>
</LabeledControl>
- <LabeledControl label="公网访问基址" hint="留空则自动拼 https://{bucket}.{endpoint}" className="settings-field-span-full">
+ <LabeledControl
+ label="公网访问基址"
+ hint="留空则自动拼 https://{bucket}.{endpoint}"
+ className="settings-field-span-full"
+ >
<input
className="settings-input"
placeholder="https://cdn.example.com"
@@ -201,57 +176,6 @@ export function OssSettingsPanel() {
<Switch checked={form.oss_upload_async} onCheckedChange={(v) => patchField("oss_upload_async", v)} />
</div>
</SettingsPanel>
-
- <SettingsPanel
- className="settings-panel--compact"
- title="2. 火山 TOS(可选)"
- description="历史存储方案,新项目可只配 OSS"
- >
- <div className="settings-field-grid">
- <LabeledControl label="Endpoint">
- <input
- className="settings-input"
- value={form.tos_endpoint}
- onChange={(e) => patchField("tos_endpoint", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl label="Bucket">
- <input
- className="settings-input"
- value={form.tos_bucket}
- onChange={(e) => patchField("tos_bucket", e.target.value)}
- />
- </LabeledControl>
- <LabeledControl label="CDN 基址" className="settings-field-span-full">
- <input
- className="settings-input"
- placeholder="http://localhost:8000/static"
- value={form.cdn_base}
- onChange={(e) => patchField("cdn_base", e.target.value)}
- />
- </LabeledControl>
- <SecretField
- label="TOS Access Key"
- value={tosKeyInput}
- configured={form.has_tos_access_key && !clearTosKey}
- onChange={setTosKeyInput}
- onClear={() => {
- setTosKeyInput("");
- setClearTosKey(true);
- }}
- />
- <SecretField
- label="TOS Secret Key"
- value={tosSecretInput}
- configured={form.has_tos_secret_key && !clearTosSecret}
- onChange={setTosSecretInput}
- onClear={() => {
- setTosSecretInput("");
- setClearTosSecret(true);
- }}
- />
- </div>
- </SettingsPanel>
</div>
</SettingsTabShell>
);
diff --git a/admin/src/components/settings/PaymentSettingsPanel.tsx b/admin/src/components/settings/PaymentSettingsPanel.tsx
index c3e15eb..541ad7b 100644
--- a/admin/src/components/settings/PaymentSettingsPanel.tsx
+++ b/admin/src/components/settings/PaymentSettingsPanel.tsx
@@ -34,6 +34,11 @@ export function PaymentSettingsPanel() {
basis: string;
rate_label: string;
markup: number;
+ recommended?: boolean;
+ note?: string;
+ official_cost_yuan?: number;
+ user_charge_yuan?: number;
+ verify_url?: string;
}>
>([]);
const [modelRatesBusy, setModelRatesBusy] = useState(false);
@@ -63,7 +68,7 @@ export function PaymentSettingsPanel() {
epay_notify_url: form.epay_notify_url,
epay_return_url: form.epay_return_url,
billing_enabled: form.billing_enabled,
- billing_markup: form.billing_markup,
+ billing_markup: 1.0,
billing_estimate_buffer: form.billing_estimate_buffer,
billing_seedance_video0: form.billing_seedance_video0,
billing_seedance_video1: form.billing_seedance_video1,
@@ -76,8 +81,6 @@ export function PaymentSettingsPanel() {
billing_est_tts_tokens: form.billing_est_tts_tokens,
billing_est_seedance_tokens_per_sec: form.billing_est_seedance_tokens_per_sec,
billing_signup_grant_fen: form.billing_signup_grant_fen,
- quota_enabled: form.quota_enabled,
- new_user_quota: form.new_user_quota,
billing_user_alert_enabled: form.billing_user_alert_enabled,
billing_user_alert_interval_fen: form.billing_user_alert_interval_fen,
billing_admin_cost_alert_enabled: form.billing_admin_cost_alert_enabled,
@@ -233,7 +236,7 @@ export function PaymentSettingsPanel() {
<SettingsPanel
className="settings-panel--compact"
title="2. Token 计费"
- description="按上游成本 × markup 扣费"
+ description="按 TokenFree 官方成本 1:1 扣费,不再加价"
>
<div className="settings-toggle-row">
<div>
@@ -243,16 +246,6 @@ export function PaymentSettingsPanel() {
<Switch checked={form.billing_enabled} onCheckedChange={(v) => patchField("billing_enabled", v)} />
</div>
<div className="settings-field-grid mt-3">
- <LabeledControl label="加价系数 markup">
- <input
- className="settings-input"
- type="number"
- step="0.1"
- min={1}
- value={form.billing_markup}
- onChange={(e) => patchField("billing_markup", Number(e.target.value))}
- />
- </LabeledControl>
<LabeledControl label="预估缓冲系数">
<input
className="settings-input"
@@ -341,7 +334,7 @@ export function PaymentSettingsPanel() {
disabled={modelRatesBusy}
onClick={() => void loadModelRates()}
>
- {modelRatesBusy ? "加载中…" : "查看各模型计费口径"}
+ {modelRatesBusy ? "加载中…" : "查看 TokenFree 官方价目"}
</Button>
</div>
{tokenfreeInfo ? <p className="text-sm text-muted-foreground mt-2">{tokenfreeInfo}</p> : null}
@@ -351,23 +344,38 @@ export function PaymentSettingsPanel() {
<thead>
<tr className="border-b bg-muted/40 text-left">
<th className="p-2">模型</th>
- <th className="p-2">渠道</th>
- <th className="p-2">依据</th>
- <th className="p-2">费率</th>
- <th className="p-2">markup</th>
+ <th className="p-2">能力</th>
+ <th className="p-2">官方成本</th>
+ <th className="p-2">用户价</th>
+ <th className="p-2">口径</th>
</tr>
</thead>
<tbody>
{modelRates.map((row) => (
<tr key={row.id} className="border-b last:border-0">
<td className="p-2">
- <div className="font-medium">{row.label}</div>
+ <div className="font-medium">
+ {row.label}
+ {row.recommended ? <span className="ml-1 text-xs text-[#409eff]">推荐</span> : null}
+ </div>
<div className="text-xs text-muted-foreground font-mono">{row.id}</div>
+ {row.note ? <div className="text-xs text-muted-foreground">{row.note}</div> : null}
+ </td>
+ <td className="p-2">{row.capability}</td>
+ <td className="p-2">
+ {row.official_cost_yuan ? `¥${row.official_cost_yuan}` : "—"}
+ </td>
+ <td className="p-2">
+ {row.user_charge_yuan ? `¥${row.user_charge_yuan}` : "—"}
+ </td>
+ <td className="p-2">
+ <div>{row.rate_label}</div>
+ {row.verify_url ? (
+ <a className="text-xs text-[#409eff] hover:underline" href={row.verify_url} target="_blank" rel="noreferrer">
+ 去 TokenFree 核对
+ </a>
+ ) : null}
</td>
- <td className="p-2">{row.provider}</td>
- <td className="p-2">{row.basis}</td>
- <td className="p-2">{row.rate_label}</td>
- <td className="p-2">{row.markup}</td>
</tr>
))}
</tbody>
@@ -410,25 +418,6 @@ export function PaymentSettingsPanel() {
/>
</LabeledControl>
</div>
-
- <div className="settings-toggle-row mt-3">
- <div>
- <strong>旧版次数配额</strong>
- <span>与 Token 计费并存时以 billing_enabled 为准</span>
- </div>
- <Switch checked={form.quota_enabled} onCheckedChange={(v) => patchField("quota_enabled", v)} />
- </div>
- <div className="settings-field-grid mt-2">
- <LabeledControl label="新用户默认次数">
- <input
- className="settings-input"
- type="number"
- min={0}
- value={form.new_user_quota}
- onChange={(e) => patchField("new_user_quota", Number(e.target.value))}
- />
- </LabeledControl>
- </div>
</SettingsPanel>
</div>
@@ -559,16 +548,6 @@ export function PaymentSettingsPanel() {
</LabeledControl>
</div>
</SettingsPanel>
-
- <SettingsPanel
- className="settings-panel--compact"
- title="4. 上游成本监控"
- description="TokenFree New API 用量,与「模型」页同一把 Key"
- >
- <p className="text-sm text-muted-foreground">
- 无需火山 Access Key。填写 TokenFree Key 后,仪表盘与财务列表可同步官方日消耗(quota,500000 ≈ 1 USD)。
- </p>
- </SettingsPanel>
</div>
</SettingsTabShell>
);
diff --git a/admin/src/components/settings/RoutingSettingsPanel.tsx b/admin/src/components/settings/RoutingSettingsPanel.tsx
index fb56c88..0ddc5c7 100644
--- a/admin/src/components/settings/RoutingSettingsPanel.tsx
+++ b/admin/src/components/settings/RoutingSettingsPanel.tsx
@@ -9,22 +9,22 @@ import {
SettingsSurface,
SettingsTabShell,
} from "@/components/settings/SettingsPanel";
+import {
+ canonicalChannelModelId,
+ canonicalizeChannelModels,
+ collapseCatalogModels,
+ mergeRecommendedSelection,
+ pickRecommendedDefaults,
+ pickRecommendedModelIds,
+ type UpstreamModelOption,
+} from "@/lib/tokenfreeRecommendedModels";
import { cn } from "@/lib/utils";
type Capability = "text" | "image" | "video" | "audio";
type CapabilityFilter = Capability | "all";
-type UpstreamModelOption = { id: string; label: string; capability: string };
const CAPABILITY_ORDER: Capability[] = ["text", "image", "video", "audio"];
-/** 拉取上游后优先勾选的模型(按能力各取首个命中) */
-const RECOMMENDED_PATTERNS: Record<Capability, RegExp[]> = {
- text: [/^grok-4-6$/i, /^grok-4-5$/i, /grok-4/i, /^gpt-4/i],
- image: [/gpt-image-2\.5/i, /seedream-5/i, /seedream/i, /gpt-image-2/i, /grok-imagine-image/i],
- video: [/seedance-2-5/i, /seedance-2-0/i, /doubao-seedance-2-5/i, /seedance/i],
- audio: [/seed-tts-2/i, /seed-tts/i, /tts-2/i],
-};
-
const TOKENFREE_CHANNEL_ID = "tokenfree";
const TOKENFREE_BASE_URL = "https://www.tokenfree.com/v1";
const TOKENFREE_CONSOLE_URL = "https://www.tokenfree.com/channels";
@@ -61,6 +61,7 @@ function inferCapability(model: string): Capability {
return "text";
}
+// 优先用上游声明的能力,否则按模型 id 推断
function modelCapability(model: UpstreamModelOption): Capability {
const cap = (model.capability || "").trim().toLowerCase();
if (cap === "text" || cap === "image" || cap === "video" || cap === "audio") {
@@ -69,30 +70,16 @@ function modelCapability(model: UpstreamModelOption): Capability {
return inferCapability(model.id);
}
-function pickRecommendedByCapability(models: UpstreamModelOption[]): Record<Capability, string> {
- const byCap: Record<Capability, UpstreamModelOption[]> = {
- text: [],
- image: [],
- video: [],
- audio: [],
+// 渠道已选模型收到规范 id,避免 Seedance 2.0 三档并存
+function canonicalizeRoutingSettings(settings: AdminRoutingSettings): AdminRoutingSettings {
+ return {
+ ...settings,
+ system_channels: settings.system_channels.map((item) =>
+ item.id === TOKENFREE_CHANNEL_ID
+ ? { ...item, models: canonicalizeChannelModels(item.models || []) }
+ : item,
+ ),
};
- for (const model of models) {
- byCap[modelCapability(model)].push(model);
- }
- const out: Record<Capability, string> = { text: "", image: "", video: "", audio: "" };
- for (const cap of CAPABILITY_ORDER) {
- for (const pattern of RECOMMENDED_PATTERNS[cap]) {
- const hit = byCap[cap].find((m) => pattern.test(m.id));
- if (hit) {
- out[cap] = hit.id;
- break;
- }
- }
- if (!out[cap] && byCap[cap][0]) {
- out[cap] = byCap[cap][0].id;
- }
- }
- return out;
}
function buildReadiness(data: AdminRoutingSettings | null, hasKey: boolean) {
@@ -126,7 +113,7 @@ export function RoutingSettingsPanel() {
setLoading(true);
try {
const res = await api<AdminRoutingSettings>("/api/admin/settings/routing");
- setData(res);
+ setData(canonicalizeRoutingSettings(res));
setApiKeyInput("");
setUpstreamModels([]);
} catch (err) {
@@ -142,14 +129,19 @@ export function RoutingSettingsPanel() {
const selectedModels = channel?.models ?? [];
const catalogModels = useMemo(() => {
- const map = new Map<string, UpstreamModelOption>();
- for (const m of upstreamModels) map.set(m.id, m);
+ const raw: UpstreamModelOption[] = [];
+ const seen = new Set<string>();
+ for (const model of upstreamModels) {
+ raw.push(model);
+ seen.add(canonicalChannelModelId(model.id));
+ }
for (const id of selectedModels) {
- if (!map.has(id)) {
- map.set(id, { id, label: id, capability: inferCapability(id) });
- }
+ const cid = canonicalChannelModelId(id);
+ if (!cid || seen.has(cid)) continue;
+ raw.push({ id: cid, label: cid, capability: inferCapability(cid) });
+ seen.add(cid);
}
- return Array.from(map.values()).sort((a, b) => a.id.localeCompare(b.id));
+ return collapseCatalogModels(raw);
}, [selectedModels, upstreamModels]);
const capCounts = useMemo(() => {
@@ -181,17 +173,10 @@ export function RoutingSettingsPanel() {
const readiness = buildReadiness(data, hasKey);
- function applyRecommendedSelection(
- models: UpstreamModelOption[],
- opts: { mergeSelected: boolean },
- ) {
- const { mergeSelected } = opts;
- const picks = pickRecommendedByCapability(models);
- const pickIds = CAPABILITY_ORDER.map((cap) => picks[cap]).filter(Boolean);
- const nextSelected = mergeSelected
- ? [...new Set([...selectedModels, ...pickIds])]
- : [...new Set([...pickIds])];
- setSelectedModels(nextSelected);
+ // 勾选短名单,并把 Seedance 2.0 三档别名收成 2.5 / 2.0 Mini
+ function applyRecommendedSelection(models: UpstreamModelOption[]) {
+ const picks = pickRecommendedDefaults(models);
+ setSelectedModels(mergeRecommendedSelection(selectedModels, models));
setData((prev) => {
if (!prev) return prev;
const nextDefaults = { ...prev.default_models };
@@ -207,11 +192,12 @@ export function RoutingSettingsPanel() {
}
function setSelectedModels(models: string[]) {
+ const nextModels = canonicalizeChannelModels(models);
setData((prev) => {
if (!prev) return prev;
const channels = prev.system_channels.length
? prev.system_channels.map((item) =>
- item.id === (channel?.id || TOKENFREE_CHANNEL_ID) ? { ...item, models } : item,
+ item.id === (channel?.id || TOKENFREE_CHANNEL_ID) ? { ...item, models: nextModels } : item,
)
: [
{
@@ -222,7 +208,7 @@ export function RoutingSettingsPanel() {
has_api_key: hasSavedKey,
api_format: "openai" as const,
protocol: "auto" as const,
- models,
+ models: nextModels,
enabled: true,
sort_order: 0,
},
@@ -248,9 +234,14 @@ export function RoutingSettingsPanel() {
capability: "all",
}),
});
- setUpstreamModels(res.models);
+ const catalog = collapseCatalogModels(res.models);
+ setUpstreamModels(catalog);
const shouldAutoPick = selectedModels.length === 0;
- applyRecommendedSelection(res.models, { mergeSelected: true });
+ if (shouldAutoPick) {
+ applyRecommendedSelection(catalog);
+ } else {
+ setSelectedModels([...selectedModels, ...pickRecommendedModelIds(catalog)]);
+ }
toast.success(
shouldAutoPick
? `已拉取 ${res.models.length} 个模型,并已勾选推荐默认项`
@@ -271,7 +262,7 @@ export function RoutingSettingsPanel() {
}
function addManualModel() {
- const id = manualModel.trim();
+ const id = canonicalChannelModelId(manualModel.trim());
if (!id) return;
if (!selectedModels.includes(id)) setSelectedModels([...selectedModels, id]);
setManualModel("");
@@ -300,7 +291,7 @@ export function RoutingSettingsPanel() {
default_models: data.default_models,
}),
});
- setData(res.settings);
+ setData(canonicalizeRoutingSettings(res.settings));
setApiKeyInput("");
toast.success("模型配置已保存");
} catch (err) {
@@ -382,7 +373,7 @@ export function RoutingSettingsPanel() {
<LabeledControl
className="settings-field-span-full"
label="可用模型"
- hint="按类型筛选、搜索 ID;拉取后会自动勾选各能力推荐模型(未设置默认项时写入下方默认)"
+ hint="按类型筛选、搜索 ID。Seedance 2.0 的短名/方舟接入点会合并成一条;勾选推荐默认 2.5 与 2.0 Mini。"
>
<div className="settings-model-toolbar">
<button
@@ -398,7 +389,7 @@ export function RoutingSettingsPanel() {
type="button"
className="admin-btn admin-btn-secondary settings-mini-btn"
disabled={upstreamModels.length === 0}
- onClick={() => applyRecommendedSelection(upstreamModels, { mergeSelected: true })}
+ onClick={() => applyRecommendedSelection(upstreamModels)}
>
勾选推荐
</button>
diff --git a/admin/src/lib/tokenfreeRecommendedModels.ts b/admin/src/lib/tokenfreeRecommendedModels.ts
new file mode 100644
index 0000000..9beaaac
--- /dev/null
+++ b/admin/src/lib/tokenfreeRecommendedModels.ts
@@ -0,0 +1,97 @@
+export type ModelCapability = "text" | "image" | "video" | "audio";
+
+export type UpstreamModelOption = { id: string; label: string; capability: string };
+
+/** 勾选推荐时留下的 TokenFree id;视频只留 2.5 与 2.0 Mini */
+export const RECOMMENDED_MODEL_IDS: Record<ModelCapability, string[]> = {
+ text: ["kimi-k2.6"],
+ image: ["gpt-image-2-5"],
+ video: ["seedance-2-5", "seedance-2-0-mini"],
+ audio: ["seed-tts-2.0"],
+};
+
+const CAPABILITY_ORDER: ModelCapability[] = ["text", "image", "video", "audio"];
+
+// 把 Seedance 接入点/短名收到 TokenFree 目录 id
+export function canonicalChannelModelId(model: string): string {
+ const mid = (model || "").trim();
+ if (!mid) return "";
+ const low = mid.toLowerCase();
+ if (!low.includes("seedance")) return mid;
+ if (low.includes("mini")) return "seedance-2-0-mini";
+ if (/(?:2-5|2\.5|260628)/.test(low)) return "seedance-2-5";
+ if (/(?:2-0|2\.0|260128)/.test(low)) return "seedance-2-0";
+ const compact = low.replace(/_/g, "-");
+ if (compact === "seedance-2" || compact === "seedance2" || compact.endsWith("seedance-2")) {
+ return "seedance-2-0";
+ }
+ return mid;
+}
+
+// 合并 Seedance 2.0 三档别名,保持原顺序
+export function canonicalizeChannelModels(models: string[]): string[] {
+ const out: string[] = [];
+ const seen = new Set<string>();
+ for (const raw of models) {
+ const id = canonicalChannelModelId(raw);
+ if (!id || seen.has(id)) continue;
+ seen.add(id);
+ out.push(id);
+ }
+ return out;
+}
+
+// 目录里同款 Seedance 只留一条,优先展示规范 id
+export function collapseCatalogModels(models: UpstreamModelOption[]): UpstreamModelOption[] {
+ const map = new Map<string, UpstreamModelOption>();
+ for (const model of models) {
+ const id = canonicalChannelModelId(model.id);
+ if (!id) continue;
+ const prev = map.get(id);
+ if (!prev || model.id === id) {
+ map.set(id, {
+ ...model,
+ id,
+ label: model.id === id ? model.label || id : id,
+ });
+ }
+ }
+ return Array.from(map.values()).sort((a, b) => a.id.localeCompare(b.id));
+}
+
+// 上游目录里实际存在的推荐 id
+export function pickRecommendedModelIds(models: UpstreamModelOption[]): string[] {
+ const ids = new Set(models.map((item) => canonicalChannelModelId(item.id)));
+ const out: string[] = [];
+ for (const cap of CAPABILITY_ORDER) {
+ for (const want of RECOMMENDED_MODEL_IDS[cap]) {
+ if (ids.has(want) && !out.includes(want)) out.push(want);
+ }
+ }
+ return out;
+}
+
+// 各能力默认项;视频写逻辑 id seedance-2.5,与下拉选项对齐
+export function pickRecommendedDefaults(models: UpstreamModelOption[]): Record<ModelCapability, string> {
+ const ids = new Set(models.map((item) => canonicalChannelModelId(item.id)));
+ const out: Record<ModelCapability, string> = { text: "", image: "", video: "", audio: "" };
+ for (const cap of CAPABILITY_ORDER) {
+ if (cap === "video" && (ids.has("seedance-2-5") || ids.has("seedance-2.5"))) {
+ out.video = "seedance-2.5";
+ continue;
+ }
+ out[cap] = RECOMMENDED_MODEL_IDS[cap].find((id) => ids.has(id)) || "";
+ }
+ return out;
+}
+
+// 勾选推荐:补上短名单,Seedance 只留 2.5 / 2.0 Mini
+export function mergeRecommendedSelection(selected: string[], catalog: UpstreamModelOption[]): string[] {
+ const recommended = pickRecommendedModelIds(catalog);
+ const preferredVideo = new Set(RECOMMENDED_MODEL_IDS.video);
+ const kept = canonicalizeChannelModels(selected).filter((id) => {
+ if (!id.toLowerCase().includes("seedance")) return true;
+ return preferredVideo.has(id);
+ });
+ return canonicalizeChannelModels([...kept, ...recommended]);
+}
diff --git a/admin/src/pages/OrdersPage.tsx b/admin/src/pages/OrdersPage.tsx
index 0e63a33..abb413a 100644
--- a/admin/src/pages/OrdersPage.tsx
+++ b/admin/src/pages/OrdersPage.tsx
@@ -471,9 +471,9 @@ export function OrdersPage() {
}
title={
row.billing_basis === "upstream_cost"
- ? "按火山返回的实际费用 × markup"
+ ? "按 TokenFree 返回的实际费用扣费"
: row.billing_basis === "upstream_usage"
- ? "按火山返回的 usage token × 配置单价 × markup"
+ ? "按 TokenFree usage token × 官方单价扣费"
: "上游未返回 usage,按配置估算 token 扣费"
}
>
diff --git a/admin/src/pages/UsersPage.tsx b/admin/src/pages/UsersPage.tsx
index 1c4dc10..2d9d735 100644
--- a/admin/src/pages/UsersPage.tsx
+++ b/admin/src/pages/UsersPage.tsx
@@ -24,7 +24,6 @@ type ListRes = { items: AdminUserRow[]; meta: PageMeta };
// 用户管理:搜索、筛选、只读明细与编辑
export function UsersPage() {
const [q, setQ] = useState("");
- const [planFilter, setPlanFilter] = useState("");
const [roleFilter, setRoleFilter] = useState("");
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);
@@ -34,7 +33,6 @@ export function UsersPage() {
const [editing, setEditing] = useState<AdminUserRow | null>(null);
const [detailUser, setDetailUser] = useState<AdminUserRow | null>(null);
const [form, setForm] = useState({
- plan: "free",
role: "user",
balance_yuan: "0",
balance_note: "",
@@ -50,7 +48,6 @@ export function UsersPage() {
page_size: String(nextSize),
});
if (nextQ.trim()) params.set("q", nextQ.trim());
- if (planFilter) params.set("plan", planFilter);
if (roleFilter) params.set("role", roleFilter);
const res = await api<ListRes>(`/api/admin/users?${params}`);
setData(res);
@@ -84,7 +81,6 @@ export function UsersPage() {
function openEdit(user: AdminUserRow) {
setEditing(user);
setForm({
- plan: user.plan || "free",
role: user.role || "user",
balance_yuan: fenToYuan(user.balance_fen),
balance_note: "",
@@ -100,7 +96,6 @@ export function UsersPage() {
await api(`/api/admin/users/${editing.id}`, {
method: "PATCH",
body: JSON.stringify({
- plan: form.plan,
role: form.role,
balance_fen: balanceFen,
balance_note: form.balance_note || undefined,
@@ -123,7 +118,7 @@ export function UsersPage() {
return (
<div className="admin-list-page">
- <PageHeader description="搜索用户,调整套餐与余额" />
+ <PageHeader description="搜索用户,调整角色与余额" />
<AdminFilterBar>
<AdminSearchInput
@@ -134,12 +129,6 @@ export function UsersPage() {
if (e.key === "Enter") applyFilters();
}}
/>
- <Select value={planFilter} onChange={(e) => setPlanFilter(e.target.value)}>
- <option value="">全部套餐</option>
- <option value="free">free</option>
- <option value="pro">pro</option>
- <option value="team">team</option>
- </Select>
<Select value={roleFilter} onChange={(e) => setRoleFilter(e.target.value)}>
<option value="">全部角色</option>
<option value="user">user</option>
@@ -173,7 +162,6 @@ export function UsersPage() {
<TableHead>邮箱</TableHead>
<TableHead>昵称</TableHead>
<TableHead>手机</TableHead>
- <TableHead>套餐</TableHead>
<TableHead>余额</TableHead>
<TableHead>冻结</TableHead>
<TableHead>角色</TableHead>
@@ -188,9 +176,6 @@ export function UsersPage() {
<TableCell className="font-medium">{u.email}</TableCell>
<TableCell>{u.nickname || "—"}</TableCell>
<TableCell className="text-xs">{u.phone || "—"}</TableCell>
- <TableCell>
- <Badge variant="info">{u.plan}</Badge>
- </TableCell>
<TableCell className="tabular-nums">¥{fenToYuan(u.balance_fen)}</TableCell>
<TableCell className="tabular-nums">¥{fenToYuan(u.frozen_fen)}</TableCell>
<TableCell>
@@ -220,7 +205,7 @@ export function UsersPage() {
))}
{!loading && (data?.items.length ?? 0) === 0 && (
<TableRow>
- <TableCell colSpan={10} className="p-0">
+ <TableCell colSpan={9} className="p-0">
<EmptyState title="暂无用户" description="试试换个关键词搜索" />
</TableCell>
</TableRow>
@@ -264,13 +249,6 @@ export function UsersPage() {
}
>
<div className="admin-form-grid admin-form-grid--2">
- <AdminField label="套餐">
- <Select value={form.plan} onChange={(e) => setForm((f) => ({ ...f, plan: e.target.value }))}>
- <option value="free">free</option>
- <option value="pro">pro</option>
- <option value="team">team</option>
- </Select>
- </AdminField>
<AdminField label="角色">
<Select value={form.role} onChange={(e) => setForm((f) => ({ ...f, role: e.target.value }))}>
<option value="user">user</option>
diff --git a/backend/.env.example b/backend/.env.example
index 9d23fd0..2473a61 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -28,9 +28,9 @@ MODEL_LLM=
USE_CELERY=false
QUOTA_ENABLED=false
-# Token 计费(用户价 = 成本 × markup)
+# Token 计费(用户价 = TokenFree 官方成本,不再加价)
BILLING_ENABLED=false
-BILLING_MARKUP=1.5
+BILLING_MARKUP=1.0
# TokenFree / New API:500000 quota = 1 USD,按此汇率折人民币分
BILLING_USD_CNY=7.0
BILLING_SIGNUP_GRANT_FEN=500
@@ -79,6 +79,7 @@ ARK_VIDEO_RATIO=16:9
ARK_VIDEO_POLL_INTERVAL=8
ARK_VIDEO_POLL_TIMEOUT=900
PIPELINE_IMAGE_CONCURRENCY=3
+TOKENFREE_IMAGE_CONCURRENCY=1
PIPELINE_VIDEO_CONCURRENCY=10
PIPELINE_AUDIO_CONCURRENCY=4
diff --git a/backend/app/api/admin/settings.py b/backend/app/api/admin/settings.py
index a612344..a2cd7fa 100644
--- a/backend/app/api/admin/settings.py
+++ b/backend/app/api/admin/settings.py
@@ -142,10 +142,11 @@ async def admin_list_upstream_models(
async def admin_billing_model_rates(
_admin: User = Depends(get_current_admin),
) -> dict:
- """各模型计费口径一览(按比例 markup)。"""
- from app.services.billing.pricing import billing_model_rate_rows
+ """拉取 TokenFree 官方价目,返回推荐文字/图/视频模型费率。"""
+ from app.services.tokenfree_pricing import billing_official_rate_rows, tokenfree_pricing_url
- return {"items": billing_model_rate_rows()}
+ items = await billing_official_rate_rows()
+ return {"items": items, "source": tokenfree_pricing_url()}
@router.get("/settings/tokenfree/quota")
diff --git a/backend/app/api/drama/episodes.py b/backend/app/api/drama/episodes.py
index 6ba2501..5b7c0a4 100644
--- a/backend/app/api/drama/episodes.py
+++ b/backend/app/api/drama/episodes.py
@@ -17,7 +17,6 @@ from app.models import User
from app.models_drama import (
DramaEpisode,
DramaEpisodeFragment,
- DramaFragmentAssetRef,
DramaProject,
)
from app.schemas_drama import (
@@ -43,6 +42,7 @@ from app.services.drama.access import (
get_owned_drama_project,
get_owned_episode,
load_episode_fragments,
+ replace_fragment_asset_refs,
match_fragments_for_generate,
)
from app.services.drama.generation import (
@@ -516,7 +516,9 @@ async def save_fragments(
item_id = int(item.id) if item.id else 0
frag = existing.get(item_id) if item_id > 0 else None
if frag is None:
+ # 先挂上空集合,flush 后不要再 lazy load asset_references
frag = DramaEpisodeFragment(episode_id=ep.id)
+ frag.asset_references = []
ep.fragments.append(frag)
await db.flush()
frag.sort_order = item.sort_order
@@ -527,15 +529,12 @@ async def save_fragments(
frag.params = item.params
keep_ids.add(int(frag.id))
- frag.asset_references.clear()
- await db.flush()
asset_ids = await filter_valid_project_asset_ids(
db,
ep.project_id,
list(item.asset_ids or []),
)
- for aid in asset_ids:
- db.add(DramaFragmentAssetRef(fragment_id=frag.id, asset_id=aid))
+ await replace_fragment_asset_refs(db, frag, asset_ids)
stale_ids = [fid for fid in existing if fid not in keep_ids]
if stale_ids:
diff --git a/backend/app/api/projects.py b/backend/app/api/projects.py
index 1a3dc42..9ba252e 100644
--- a/backend/app/api/projects.py
+++ b/backend/app/api/projects.py
@@ -16,7 +16,7 @@ from sse_starlette.sse import EventSourceResponse
from app.database import get_db
from app.deps import get_current_user
-from app.models import Project, ProjectStatus, Shot, UsageEvent, User, Work
+from app.models import Project, ProjectStatus, Shot, ShotStatus, UsageEvent, User, Work
from app.models_tasks import TaskRun
from app.schemas import (
ContentExpandOut,
@@ -30,6 +30,7 @@ from app.schemas import (
ProjectOut,
ProjectUpdate,
ShotOut,
+ ShotReorderIn,
ShotUpdate,
VoicePreviewOut,
VoicePreviewRequest,
@@ -37,20 +38,46 @@ from app.schemas import (
)
from app.schemas_tasks import TaskCreateRequest, TaskTargetBind
from app.services import pipeline, storage
+from app.services.bgm import clip_shot_bgm
from app.services.ark import get_ark
from app.services.progress import redis_bridge, subscribe, unsubscribe
from app.services.billing import record_llm_chat_line, run_billed_ephemeral
from app.services.billing.http import http_exception_for_value_error
from app.services.tasks.service import (
+ ACTIVE_TASK_STATUSES,
cancel_tasks_for_scope,
create_task,
list_active_tasks_for_owner,
)
from app.services.voices import ensure_voice_preview, list_voices
+from app.services.kepu_stages import resolve_kepu_billing_phase
router = APIRouter(tags=["projects"])
+def _demote_after_edit(project: Project) -> None:
+ """改镜头/配乐后作废成片,并按素材把终态打回 script/assets/videos/compose。"""
+ project.final_video_url = None
+ if project.status not in {
+ ProjectStatus.DONE,
+ ProjectStatus.AUDITING,
+ ProjectStatus.COMPOSING,
+ ProjectStatus.VIDEO_READY,
+ ProjectStatus.FAILED,
+ ProjectStatus.CANCELLED,
+ }:
+ return
+ phase = resolve_kepu_billing_phase(project)
+ if phase == "script":
+ project.status = ProjectStatus.SCRIPT_READY if project.shots else ProjectStatus.DRAFT
+ elif phase == "assets":
+ project.status = ProjectStatus.SCRIPT_READY
+ elif phase == "videos":
+ project.status = ProjectStatus.IMAGE_READY
+ else:
+ project.status = ProjectStatus.VIDEO_READY
+
+
@router.get("/voices")
async def get_voices() -> list[dict]:
return list_voices()
@@ -137,18 +164,35 @@ async def _get_owned_project(db: AsyncSession, project_id: int, user: User) -> P
return project
+def _image_ext_from_magic(raw: bytes) -> str:
+ """按文件头识别图片后缀;无法识别则返回空。"""
+ if raw.startswith(b"\xff\xd8\xff"):
+ return ".jpg"
+ if raw.startswith(b"\x89PNG\r\n\x1a\n"):
+ return ".png"
+ if raw.startswith(b"GIF87a") or raw.startswith(b"GIF89a"):
+ return ".gif"
+ if len(raw) >= 12 and raw.startswith(b"RIFF") and raw[8:12] == b"WEBP":
+ return ".webp"
+ return ""
+
+
+# 整片级任务占用项目时,禁止再开侧任务(含 cancel_requested,流水线可能仍在写)
+_PROJECT_WIDE_TASK_TYPES = {
+ "project_pipeline",
+ "project_compose_only",
+ "project_regen_audio",
+ "shot_regen_audio",
+}
+
+
def _ensure_side_task_allowed(project: Project) -> None:
- """重绘/重生/合成侧任务:流水线进行中时拒绝,避免与进行中任务冲突。"""
- running = {
- ProjectStatus.SCRIPTING,
- ProjectStatus.IMAGING,
- ProjectStatus.VIDEOING,
- ProjectStatus.AUDIOING,
- ProjectStatus.COMPOSING,
- ProjectStatus.AUDITING,
- }
- if project.status in running:
- raise HTTPException(status_code=409, detail="生成进行中,请稍后")
+ """整片任务未终态前拒绝侧任务;单镜重绘可并行,不因残留 IMAGING 卡住。"""
+ for task in getattr(project, "active_tasks", []) or []:
+ if str(getattr(task, "status", "") or "") not in ACTIVE_TASK_STATUSES:
+ continue
+ if str(getattr(task, "task_type", "") or "") in _PROJECT_WIDE_TASK_TYPES:
+ raise HTTPException(status_code=409, detail="整片生成进行中,请稍后")
# COMPOSING 且无进行中任务时视为拼接已失败卡住,允许重新发起
@@ -567,6 +611,12 @@ async def update_project(
if not is_valid_project_media_model(data["video_model"], "video"):
raise HTTPException(status_code=400, detail="无效视频模型")
+ if "bgm_lock" in data:
+ data["bgm_lock"] = str(data["bgm_lock"] or "").strip()
+ if "subtitle_preset" in data:
+ data["subtitle_preset"] = str(data["subtitle_preset"] or "").strip()
+ if "bgm_lock" in data or "subtitle_preset" in data:
+ _demote_after_edit(project)
for k, v in data.items():
setattr(project, k, v)
await db.commit()
@@ -792,6 +842,118 @@ async def project_events(
return EventSourceResponse(event_generator())
[email protected]("/projects/{project_id}/shots", response_model=ShotOut)
+async def create_shot(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Shot:
+ """在片尾追加一镜空白分镜。"""
+ project = await _get_owned_project(db, project_id, user)
+ _ensure_side_task_allowed(project)
+ shots = sorted(project.shots, key=lambda s: s.shot_no)
+ next_no = (shots[-1].shot_no + 1) if shots else 1
+ from app.services.seedance_segments import SegmentBeat, build_segment_script
+
+ bgm = clip_shot_bgm(getattr(project, "bgm_lock", None))
+ visual = "画面轻微动态,保持主体稳定"
+ script = build_segment_script(
+ [SegmentBeat(duration=4, kind="visual", text=visual)],
+ bgm_mood=bgm,
+ )
+ shot = Shot(
+ project_id=project.id,
+ shot_no=next_no,
+ duration=4,
+ narration="",
+ overlay_title=f"场景 {next_no:02d}",
+ overlay_subtitle="",
+ img_prompt=visual,
+ video_prompt=script,
+ segment_script=script,
+ camera="slow pan",
+ bgm_mood=bgm,
+ status=ShotStatus.PENDING,
+ )
+ db.add(shot)
+ await db.flush()
+ await db.refresh(project, attribute_names=["shots"])
+ _demote_after_edit(project)
+ await db.commit()
+ await db.refresh(shot)
+ return shot
+
+
[email protected]("/projects/{project_id}/shots/reorder", response_model=ProjectOut)
+async def reorder_shots(
+ project_id: int,
+ body: ShotReorderIn,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Project:
+ """按 shot_ids 重排镜号。"""
+ project = await _get_owned_project(db, project_id, user)
+ _ensure_side_task_allowed(project)
+ existing = {s.id: s for s in project.shots}
+ if set(body.shot_ids) != set(existing.keys()):
+ raise HTTPException(status_code=400, detail="镜头列表不完整")
+ for i, sid in enumerate(body.shot_ids, start=1):
+ existing[sid].shot_no = i
+ _demote_after_edit(project)
+ await db.commit()
+ return await _get_owned_project(db, project_id, user)
+
+
[email protected]("/projects/{project_id}/shots/{shot_id}/image", response_model=ProjectOut)
+async def upload_shot_image(
+ project_id: int,
+ shot_id: int,
+ file: UploadFile = File(...),
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Project:
+ """上传替换本镜画面。"""
+ project = await _get_owned_project(db, project_id, user)
+ _ensure_side_task_allowed(project)
+ shot = next((s for s in project.shots if s.id == shot_id), None)
+ if not shot:
+ raise HTTPException(status_code=404, detail="分镜不存在")
+ 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()
+ ext = ".jpg" if suffix == ".jpeg" else suffix if suffix in {".jpg", ".png", ".webp", ".gif"} else ""
+ if not ext:
+ raise HTTPException(status_code=400, detail="仅支持 JPG / PNG / WebP / GIF")
+ raw = await file.read(8 * 1024 * 1024 + 1)
+ if not raw:
+ raise HTTPException(status_code=400, detail="空文件")
+ if len(raw) > 8 * 1024 * 1024:
+ raise HTTPException(status_code=400, detail="画面不能超过 8MB")
+ sniffed = _image_ext_from_magic(raw)
+ if not sniffed:
+ raise HTTPException(status_code=400, detail="文件不是有效图片")
+ ext = sniffed
+ dest = storage.project_dir(project_id) / f"shot_{shot.id}_upload{ext}"
+ dest.write_bytes(raw)
+ shot.image_url = storage.publish_local(dest)
+ shot.image_ark_url = None
+ shot.video_url = None
+ shot.last_frame_url = None
+ shot.status = ShotStatus.IMAGE_READY
+ shot.version += 1
+ _demote_after_edit(project)
+ await db.commit()
+ return await _get_owned_project(db, project_id, user)
+
+
@router.patch("/projects/{project_id}/shots/{shot_id}", response_model=ShotOut)
async def update_shot(
project_id: int,
@@ -815,7 +977,7 @@ async def update_shot(
replace_narration_in_script,
)
- bgm = (getattr(project, "bgm_lock", None) or shot.bgm_mood or "").strip()
+ bgm = clip_shot_bgm(getattr(project, "bgm_lock", None) or shot.bgm_mood)
script = str(data["segment_script"])
# 弹窗旁白/首帧优先写回脚本,避免保存时被旧脚本盖掉
if "narration" in data and data["narration"] is not None:
@@ -838,12 +1000,15 @@ async def update_shot(
tpl_min=tpl.shot_duration_min if tpl else 2,
tpl_max=tpl.shot_duration_max if tpl else 8,
)
+ if "bgm_mood" in data and data["bgm_mood"] is not None:
+ data["bgm_mood"] = clip_shot_bgm(str(data["bgm_mood"]))
for k, v in data.items():
setattr(shot, k, v)
# Invalidate downstream if visual prompts changed
if "img_prompt" in data:
shot.image_url = None
shot.video_url = None
+ shot.last_frame_url = None
shot.status = "PENDING"
project.final_video_url = None
elif (
@@ -853,6 +1018,7 @@ async def update_shot(
or "camera" in data
):
shot.video_url = None
+ shot.last_frame_url = None
project.final_video_url = None
shot.version += 1
await db.commit()
diff --git a/backend/app/config.py b/backend/app/config.py
index 31983f6..a59be37 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -69,6 +69,8 @@ class Settings(BaseSettings):
ark_video_poll_timeout: float = 900.0
# Parallel generation concurrency (per project)
pipeline_image_concurrency: int = 3
+ # TokenFree / New API 同时观察的生图任务上限(超出会 429)
+ tokenfree_image_concurrency: int = 1
# Seedance 2.5 官方并发上限约 10
pipeline_video_concurrency: int = 10
pipeline_audio_concurrency: int = 4
@@ -103,9 +105,9 @@ class Settings(BaseSettings):
# Legacy flag; prefer billing_enabled
quota_enabled: bool = False
- # Token billing (charge = provider_cost * markup)
+ # Token 计费:用户扣费 = TokenFree 官方成本(billing_markup 保留兼容,不再乘)
billing_enabled: bool = False
- billing_markup: float = 1.5
+ billing_markup: float = 1.0
billing_estimate_buffer: float = 1.2
# Yuan per million tokens (provider cost)
billing_seedance_video0: float = 46.0
@@ -113,7 +115,7 @@ class Settings(BaseSettings):
billing_llm_per_m: float = 5.0
billing_seedream_per_m: float = 8.0
billing_tts_per_m: float = 2.0
- # Kie:1 credit 折合人民币分(约 $0.005 ≈ ¥0.035 → 3.5);用户扣费再 × markup
+ # Kie:1 credit 折合人民币分(约 $0.005 ≈ ¥0.035 → 3.5)
billing_kie_fen_per_credit: float = 3.5
# TokenFree / New API:quota→USD→人民币(500000 quota = 1 USD)
billing_usd_cny: float = 7.0
diff --git a/backend/app/main.py b/backend/app/main.py
index 18b286a..81407a1 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -140,6 +140,8 @@ async def _apply_schema_patches() -> None:
scols = await _pg_columns(conn, "shots")
if "segment_script" not in scols:
await conn.execute(text("ALTER TABLE shots ADD COLUMN segment_script TEXT DEFAULT ''"))
+ if "last_frame_url" not in scols:
+ await conn.execute(text("ALTER TABLE shots ADD COLUMN last_frame_url VARCHAR(1024)"))
pcols = await _pg_columns(conn, "projects")
if "pipeline_mode" not in pcols:
@@ -152,6 +154,8 @@ async def _apply_schema_patches() -> None:
await conn.execute(text("ALTER TABLE projects ADD COLUMN character_bible TEXT DEFAULT ''"))
if "bgm_lock" not in pcols:
await conn.execute(text("ALTER TABLE projects ADD COLUMN bgm_lock TEXT DEFAULT ''"))
+ if "subtitle_preset" not in pcols:
+ await conn.execute(text("ALTER TABLE projects ADD COLUMN subtitle_preset VARCHAR(32) DEFAULT ''"))
if "style_prompt" not in pcols:
await conn.execute(text("ALTER TABLE projects ADD COLUMN style_prompt TEXT DEFAULT ''"))
if "character_prompt" not in pcols:
diff --git a/backend/app/models.py b/backend/app/models.py
index c8b4305..16f8be9 100644
--- a/backend/app/models.py
+++ b/backend/app/models.py
@@ -120,6 +120,8 @@ class Project(Base):
character_bible: Mapped[str] = mapped_column(Text, default="")
# Project-level BGM mood lock (same across shots)
bgm_lock: Mapped[str] = mapped_column(Text, default="")
+ # 科普成片字幕预设:standard | large | split
+ subtitle_preset: Mapped[str] = mapped_column(String(32), default="")
# User overrides from studio (optional)
style_prompt: Mapped[str] = mapped_column(Text, default="")
character_prompt: Mapped[str] = mapped_column(Text, default="")
@@ -135,7 +137,11 @@ class Project(Base):
owner: Mapped["User"] = relationship(back_populates="projects")
template: Mapped["Template"] = relationship()
- shots: Mapped[list["Shot"]] = relationship(back_populates="project", cascade="all, delete-orphan")
+ shots: Mapped[list["Shot"]] = relationship(
+ back_populates="project",
+ cascade="all, delete-orphan",
+ order_by="Shot.shot_no",
+ )
jobs: Mapped[list["PipelineJob"]] = relationship(back_populates="project", cascade="all, delete-orphan")
@@ -158,6 +164,7 @@ class Shot(Base):
image_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
image_ark_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
video_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
+ last_frame_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
audio_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
status: Mapped[str] = mapped_column(String(32), default=ShotStatus.PENDING)
version: Mapped[int] = mapped_column(Integer, default=1)
diff --git a/backend/app/schemas.py b/backend/app/schemas.py
index df13f78..8c1c0de 100644
--- a/backend/app/schemas.py
+++ b/backend/app/schemas.py
@@ -112,6 +112,12 @@ class ShotOut(BaseModel):
model_config = {"from_attributes": True}
+class ShotReorderIn(BaseModel):
+ """按 id 顺序重排分镜号。"""
+
+ shot_ids: list[int] = Field(min_length=1)
+
+
class ShotUpdate(BaseModel):
narration: str | None = None
overlay_title: str | None = None
@@ -163,6 +169,8 @@ class ProjectUpdate(BaseModel):
extra_prompt: str | None = Field(default=None, max_length=2000)
image_model: str | None = Field(default=None, max_length=64)
video_model: str | None = Field(default=None, max_length=64)
+ bgm_lock: str | None = Field(default=None, max_length=200)
+ subtitle_preset: str | None = Field(default=None, max_length=32)
ref_image_url: str | None = None
cover_url: str | None = Field(default=None, max_length=1024)
@@ -184,6 +192,7 @@ class ProjectOut(BaseModel):
voice_id: str = ""
character_bible: str = ""
bgm_lock: str = ""
+ subtitle_preset: str = ""
style_prompt: str = ""
character_prompt: str = ""
extra_prompt: str = ""
diff --git a/backend/app/schemas_settings.py b/backend/app/schemas_settings.py
index 0a3740f..ba673a3 100644
--- a/backend/app/schemas_settings.py
+++ b/backend/app/schemas_settings.py
@@ -98,7 +98,7 @@ class AdminModelSettingsOut(BaseModel):
# Token 计费
billing_enabled: bool = False
- billing_markup: float = 1.5
+ billing_markup: float = 1.0
billing_estimate_buffer: float = 1.2
billing_seedance_video0: float = 46.0
billing_seedance_video1: float = 28.0
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
index 3f525ec..adceae6 100644
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@ -25,6 +25,18 @@ from app.services.logical_model_router import (
resolve_upstream_model,
)
from app.services.tokenfree_audio import uses_tokenfree_audio
+from app.services.tokenfree_image import (
+ build_tokenfree_image_body,
+ extract_tokenfree_image_url,
+ is_tokenfree_image_url,
+ is_tokenfree_retryable_image_error,
+ post_until_not_rate_limited,
+ tokenfree_image_channel_dead,
+ tokenfree_image_slot,
+ tokenfree_image_user_error,
+ tokenfree_working_image_model,
+ uses_tokenfree_image,
+)
from app.services.voices import edge_tts_voice_for_speaker
from app.services.tokenfree_video import (
extract_video_result_url,
@@ -48,14 +60,29 @@ from app.services import seedance_segments as segplan
logger = logging.getLogger(__name__)
-def _raise_seedream_http_error(status_code: int, body: str) -> None:
- """将 Seedream HTTP 错误转为可读 RuntimeError(含上游账户欠费)。"""
+def _raise_seedream_http_error(
+ status_code: int,
+ body: str,
+ *,
+ model: str = "",
+ tokenfree: bool = False,
+) -> None:
+ """将出图 HTTP 错误转为可读 RuntimeError;TokenFree 文案与官方方舟分开。"""
snippet = (body or "")[:800]
if status_code == 403 and "AccountOverdueError" in snippet:
logger.error("Seedream AccountOverdueError — upstream Ark account overdue: %s", snippet[:200])
raise RuntimeError(
"上游 Seedream 账户欠费(AccountOverdueError),生图暂不可用,请联系管理员充值火山方舟账户"
)
+ logger.warning(
+ "出图上游失败 model=%s tokenfree=%s status=%s body=%s",
+ (model or "").strip() or "-",
+ tokenfree,
+ status_code,
+ snippet[:200],
+ )
+ if tokenfree:
+ raise RuntimeError(tokenfree_image_user_error(model=model, status_code=status_code, body=snippet))
raise RuntimeError(f"Seedream error {status_code}: {snippet}")
@@ -470,8 +497,9 @@ class ArkGateway:
)
else:
person_rule = (
- "character_bible:填「无固定人物,各镜为独立系统/场景界面」。"
- "每镜 img_prompt 必须写清该镜独特的界面类型、布局分区、主色与信息层级,不要粘贴人物锁定。"
+ "character_bible:根据主题与模板系统规则决定是否出人物,不要默认全片必须有人或必须无人。"
+ "模板要求人在场则写清操作者类型(可不锁同一张脸);主题以界面/场景/示意图为主则可写「无固定人物」。"
+ "img_prompt 写清本镜主体与构图,禁止与模板系统附加规则对着干。"
)
consistency = (
"必须输出严格 JSON 对象(不要数组、不要 markdown、不要代码围栏):"
@@ -514,7 +542,8 @@ class ArkGateway:
# segment_rules 科普逐段脚本生产约束(对齐漫剧 cue,无 @asset)
segment_rules = (
"【segments 生产规范】"
- "segments 必填;系统会落成 @duration +【字幕】/【BGM】/【旁白·自然语速·同步字幕】生产脚本,"
+ "segments 必填;系统会落成 @duration +【字幕:后期叠旁白字幕】/【BGM:后期混音】/"
+ "【旁白·自然语速·同步字幕】生产脚本,成片字幕与配乐由后期合成,不由视频模型烧录。"
"因此 kind/text/duration 必须可直接消费。"
"段序优先「画面→旁白」交替,首段尽量 kind=visual(保证首帧有料);"
"visual/action 的 text 必须含景别+主体动作+场景/界面类型,禁止空镜与模糊氛围词堆砌;"
@@ -646,15 +675,18 @@ class ArkGateway:
size: str | None = None,
model: str | None = None,
aspect_ratio: str | None = None,
+ style_ref_urls: list[str] | None = None,
) -> ImageResult:
# Kie 主流图模型(前台 image_model=kie-*);不走 ARK_MOCK
from app.services.kie_catalog import get_media_model, resolve_image_model_id
from app.services.kie_client import get_kie
+ from app.services.style_lock import split_seedream_subject_style_refs
resolved = resolve_image_model_id(model)
kie_spec = get_media_model(resolved)
if kie_spec and kie_spec.provider == "kie" and kie_spec.capability == "image":
full_prompt = f"{prompt}。避免:{negative}" if negative else prompt
+ subject_refs, style_refs = split_seedream_subject_style_refs(ref_urls, style_ref_urls)
return await get_kie().gen_image(
full_prompt,
spec=kie_spec,
@@ -662,7 +694,7 @@ class ArkGateway:
shot_no=shot_no,
aspect_ratio=aspect_ratio,
size=size,
- ref_urls=ref_urls,
+ ref_urls=[*subject_refs, *style_refs] or None,
)
if self.mock:
@@ -706,6 +738,8 @@ class ArkGateway:
size=size,
model=ark_model,
prompt_hash_src=prompt,
+ aspect_ratio=aspect_ratio,
+ style_ref_urls=style_ref_urls,
)
except Exception as exc: # noqa: BLE001
last_err = exc
@@ -731,6 +765,37 @@ class ArkGateway:
)
raise RuntimeError(str(last_err) if last_err else "Seedream failed")
+ async def _kie_image_fallback(
+ self,
+ prompt: str,
+ *,
+ project_id: int | None,
+ shot_no: int | None,
+ size: str | None,
+ aspect_ratio: str | None,
+ ref_urls: list[str] | None,
+ ) -> ImageResult | None:
+ """TokenFree 出图挂了且已配 Kie Key 时,改走已验证可用的 nano-banana-2。"""
+ from app.services.kie_catalog import get_media_model
+ from app.services.kie_client import get_kie, resolve_kie_credentials
+
+ key, _ = resolve_kie_credentials()
+ if not key:
+ return None
+ spec = get_media_model("kie-nano-banana-2")
+ if spec is None:
+ return None
+ logger.warning("TokenFree 生图不可用,回退 Kie %s shot=%s", spec.id, shot_no)
+ return await get_kie().gen_image(
+ prompt,
+ spec=spec,
+ project_id=project_id,
+ shot_no=shot_no,
+ aspect_ratio=aspect_ratio,
+ size=size,
+ ref_urls=ref_urls,
+ )
+
async def _seedream_once(
self,
full_prompt: str,
@@ -741,6 +806,8 @@ class ArkGateway:
size: str | None,
prompt_hash_src: str,
model: str | None = None,
+ aspect_ratio: str | None = None,
+ style_ref_urls: list[str] | None = None,
) -> ImageResult:
route = self._resolve_ark_route("image", model)
upstream_model = route.upstream_model if route else ((model or "").strip() or self.settings.model_image)
@@ -757,27 +824,77 @@ class ArkGateway:
resolved_size = "2K"
else:
resolved_size = clamp_seedream_pixel_size(str(resolved_size))
- body: dict[str, Any] = {
- "model": upstream_model,
- "prompt": full_prompt,
- "size": resolved_size,
- "response_format": "url",
- "watermark": False,
- }
- from app.services.style_lock import seedream_ref_urls
+ from app.services.style_lock import split_seedream_subject_style_refs
- refs = seedream_ref_urls(*(ref_urls or []))
- if refs:
- body["image"] = refs if len(refs) > 1 else refs[0]
+ subject_refs, style_refs = split_seedream_subject_style_refs(ref_urls, style_ref_urls)
+ refs = [*subject_refs, *style_refs]
+ channel_id = (route.channel_id if route else "") or ""
+ base = (route.base_url if route and route.base_url else self.settings.ark_base_url) or ""
+ on_tokenfree = uses_tokenfree_image(base_url=base, channel_id=channel_id)
+ chosen = tokenfree_working_image_model(upstream_model) if on_tokenfree else upstream_model
+ if on_tokenfree:
+ if chosen != (upstream_model or "").strip():
+ logger.warning("TokenFree 将 %s 改走 %s,避免 Seedream task_protocol_error", upstream_model, chosen)
+ path = "/responses"
+ body = build_tokenfree_image_body(
+ model=chosen,
+ prompt=full_prompt,
+ size=str(resolved_size or ""),
+ ref_urls=subject_refs,
+ style_ref_urls=style_refs,
+ )
+ else:
+ path = "/images/generations"
+ body = {
+ "model": upstream_model,
+ "prompt": full_prompt,
+ "size": resolved_size,
+ "response_format": "url",
+ "watermark": False,
+ }
+ if refs:
+ body["image"] = refs if len(refs) > 1 else refs[0]
async with httpx.AsyncClient(timeout=180.0) as client:
- resp = await client.post(
- self._route_url("/images/generations", route),
- headers=self._route_headers(route),
- json=body,
- )
- if resp.status_code >= 400:
- _raise_seedream_http_error(resp.status_code, resp.text)
+ async def _post():
+ # 单次上游 POST,限流重试由外层包住
+ return await client.post(
+ self._route_url(path, route),
+ headers=self._route_headers(route),
+ json=body,
+ )
+
+ if on_tokenfree:
+ async with tokenfree_image_slot():
+ resp = await post_until_not_rate_limited(_post)
+ else:
+ resp = await _post()
+ if resp.status_code >= 400 or is_tokenfree_retryable_image_error(
+ status_code=resp.status_code, body=resp.text
+ ):
+ if on_tokenfree and tokenfree_image_channel_dead(
+ status_code=resp.status_code, body=resp.text
+ ):
+ try:
+ fallback = await self._kie_image_fallback(
+ full_prompt,
+ project_id=project_id,
+ shot_no=shot_no,
+ size=str(resolved_size or ""),
+ aspect_ratio=aspect_ratio,
+ ref_urls=refs,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Kie 出图回退失败 shot=%s: %s", shot_no, exc)
+ fallback = None
+ if fallback is not None:
+ return fallback
+ _raise_seedream_http_error(
+ resp.status_code,
+ resp.text,
+ model=chosen,
+ tokenfree=on_tokenfree,
+ )
data = resp.json()
usage_parsed = parse_usage_dict(data)
@@ -791,7 +908,9 @@ class ArkGateway:
if upstream_cost_fen is None and raw_usage:
upstream_cost_fen = parse_upstream_cost_fen({"usage": raw_usage})
- remote = self._extract_image_url(data)
+ remote = extract_tokenfree_image_url(data) if on_tokenfree else self._extract_image_url(data)
+ if not remote:
+ remote = self._extract_image_url(data) or extract_tokenfree_image_url(data)
if not remote:
raise RuntimeError(f"Seedream missing url: {json.dumps(data)[:500]}")
@@ -803,7 +922,10 @@ class ArkGateway:
f"{int(time.time() * 1000) % 10_000_000:07d}.png"
)
dest = dest_dir / name
- await storage.download_to(remote, dest)
+ dl_headers = None
+ if is_tokenfree_image_url(remote) or is_tokenfree_content_url(remote):
+ dl_headers = {"Authorization": f"Bearer {self._ark_api_key()}"}
+ await storage.download_to(remote, dest, headers=dl_headers)
return ImageResult(
local_url=storage.publish_local(dest, sync=True),
remote_url=remote,
@@ -998,6 +1120,7 @@ class ArkGateway:
prompt_as_json: bool = True,
return_last_frame: bool = True,
generate_audio: bool = False,
+ extra_image_urls: list[str] | None = None,
) -> str:
if self.mock:
digest = hashlib.md5(f"{image_url}:{prompt}".encode()).hexdigest()[:10]
@@ -1015,6 +1138,20 @@ class ArkGateway:
# 有目标画幅时用 reference_image + ratio(可强制 9:16)。
# 纯 first_frame 禁止传 ratio,且实测即使静帧竖屏也可能吐横屏。
image_role, target_ratio = resolve_seedance_i2v_image_role(ratio)
+ extra_refs: list[str] = []
+ for raw in extra_image_urls or []:
+ text_url = str(raw or "").strip()
+ if not text_url:
+ continue
+ try:
+ extra_refs.append(await self._resolve_image_ref(text_url, prefer_https=True))
+ except Exception: # noqa: BLE001
+ logger.warning("Seedance extra ref resolve failed url=%s", text_url[:120])
+ if extra_refs:
+ # 多图只能走 reference_image,不能与 first_frame 混用
+ image_role = "reference_image"
+ if not target_ratio:
+ target_ratio = (ratio or "").strip() or "16:9"
content: list[dict[str, Any]] = [
{"type": "text", "text": text},
{
@@ -1023,6 +1160,14 @@ class ArkGateway:
"role": image_role,
},
]
+ for extra in extra_refs[:2]:
+ content.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": extra},
+ "role": "reference_image",
+ }
+ )
route = self._resolve_ark_route("video", self.settings.model_video)
video_model = route.upstream_model if route else self.settings.model_video
body: dict[str, Any] = {
@@ -1391,9 +1536,12 @@ class ArkGateway:
project_id: int,
shot_no: int,
) -> tuple[str, TaskResult]:
- video_local, _last, result = await self.wait_video_assets(
+ """等待成片并优先把已落盘尾帧写回 result,供下一镜参考。"""
+ video_local, last_local, result = await self.wait_video_assets(
task_id, project_id=project_id, shot_no=shot_no
)
+ if last_local:
+ result.last_frame_url = last_local
return video_local, result
async def gen_and_wait_video(
@@ -1410,6 +1558,7 @@ class ArkGateway:
max_attempts: int = 3,
generate_audio: bool = False,
model: str | None = None,
+ extra_image_urls: list[str] | None = None,
) -> tuple[str, TaskResult]:
"""Create i2v task and wait; Kie 或 Seedance;后者在 summary_caption / transient BodyFormat 时重试。"""
from app.services.kie_catalog import get_media_model, resolve_video_model_id
@@ -1418,6 +1567,18 @@ class ArkGateway:
resolved = resolve_video_model_id(model)
kie_spec = get_media_model(resolved)
if kie_spec and kie_spec.provider == "kie" and kie_spec.capability == "video":
+ kie_refs: list[str] | None = None
+ extras = [str(u).strip() for u in (extra_image_urls or []) if str(u).strip()]
+ if extras:
+ extra_resolved: list[str] = []
+ for raw in extras[:2]:
+ try:
+ extra_resolved.append(await self._resolve_image_ref(raw, prefer_https=True))
+ except Exception: # noqa: BLE001
+ logger.warning("Kie extra ref resolve failed url=%s", raw[:120])
+ if extra_resolved:
+ primary = await self._resolve_image_ref(image_url, prefer_https=True)
+ kie_refs = [primary, *extra_resolved]
return await get_kie().gen_and_wait_video(
image_url,
prompt,
@@ -1428,6 +1589,7 @@ class ArkGateway:
resolution=resolution,
ratio=ratio,
generate_audio=generate_audio,
+ reference_image_urls=kie_refs,
)
last_err: Exception | None = None
@@ -1443,6 +1605,7 @@ class ArkGateway:
ratio=ratio,
prompt_as_json=use_json,
generate_audio=generate_audio,
+ extra_image_urls=extra_image_urls,
)
return await self.wait_video(
task_id,
diff --git a/backend/app/services/bgm.py b/backend/app/services/bgm.py
index cc9e2d1..75579a0 100644
--- a/backend/app/services/bgm.py
+++ b/backend/app/services/bgm.py
@@ -3,12 +3,15 @@
from __future__ import annotations
import logging
+import os
import re
+import tempfile
from pathlib import Path
logger = logging.getLogger(__name__)
_STATIC_ROOT = Path(__file__).resolve().parents[2] / "static"
+SHOT_BGM_MAX = 64
# Map mood keywords → filename stems under static/bgm/
_BGM_FILES: list[tuple[re.Pattern[str], str]] = [
@@ -21,11 +24,54 @@ _BGM_FILES: list[tuple[re.Pattern[str], str]] = [
]
+def clip_shot_bgm(mood: str | None) -> str:
+ """Shot.bgm_mood 列上限 64,写入前截断。"""
+ text = (mood or "").strip()
+ return (text[:SHOT_BGM_MAX] if text else "neutral") or "neutral"
+
+
+def _ensure_default_bed() -> Path | None:
+ """无曲库时在系统临时目录生成轻垫乐;失败则跳过 BGM,不成片失败。"""
+ dest = Path(tempfile.gettempdir()) / "printfilm_bgm" / "default.wav"
+ try:
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ if dest.is_file() and dest.stat().st_size > 1000:
+ return dest
+ import math
+ import struct
+ import wave
+
+ fd, tmp_name = tempfile.mkstemp(suffix=".wav", dir=str(dest.parent))
+ os.close(fd)
+ tmp = Path(tmp_name)
+ rate = 22050
+ seconds = 8
+ amp = 1800
+ with wave.open(str(tmp), "w") as wf:
+ wf.setnchannels(1)
+ wf.setsampwidth(2)
+ wf.setframerate(rate)
+ frames = bytearray()
+ for i in range(rate * seconds):
+ t = i / rate
+ fade = min(1.0, t * 4, (seconds - t) * 4)
+ sample = int(
+ amp
+ * fade
+ * (0.55 * math.sin(2 * math.pi * 196 * t) + 0.45 * math.sin(2 * math.pi * 247 * t))
+ )
+ frames.extend(struct.pack("<h", max(-32767, min(32767, sample))))
+ wf.writeframes(bytes(frames))
+ os.replace(tmp, dest)
+ return dest if dest.is_file() else None
+ except OSError:
+ logger.warning("Failed to write fallback BGM bed; compose will skip BGM", exc_info=True)
+ return None
+
+
def resolve_bgm_path(mood: str | None) -> Path | None:
- """Return a local BGM file if present; otherwise None (compose skips)."""
+ """Return a local BGM file if present; otherwise a generated quiet bed."""
root = _STATIC_ROOT / "bgm"
- if not root.is_dir():
- return None
blob = (mood or "").strip()
stem = "default"
for pattern, name in _BGM_FILES:
@@ -46,5 +92,5 @@ def resolve_bgm_path(mood: str | None) -> Path | None:
found = sorted(root.glob(ext))
if found:
return found[0]
- logger.debug("No BGM file under %s for mood=%s", root, mood)
- return None
+ logger.debug("No BGM file under %s for mood=%s; using generated bed", root, mood)
+ return _ensure_default_bed()
diff --git a/backend/app/services/billing/estimates.py b/backend/app/services/billing/estimates.py
index caf58ad..35c3882 100644
--- a/backend/app/services/billing/estimates.py
+++ b/backend/app/services/billing/estimates.py
@@ -12,6 +12,12 @@ from app.config import Settings, get_settings
from app.models import Project
from app.models_tasks import TaskRun
from app.services.billing.pricing import charge_fen_for_tokens
+from app.services.tokenfree_pricing import (
+ charge_fen_official_image,
+ charge_fen_official_llm,
+ charge_fen_official_video,
+ ensure_official_rates,
+)
from app.services.kepu_stages import (
normalize_kepu_pipeline_phase,
project_audio_ready,
@@ -38,8 +44,7 @@ def _estimate_assets_fen(project: Project, settings: Settings) -> int:
return 1
total = 0
for _ in range(max(need_img, 0)):
- _, c_img = charge_fen_for_tokens(settings.billing_est_seedream_tokens, "seedream", settings=settings)
- total += c_img
+ total += charge_fen_official_image(settings)
if need_tts > 0:
n = max(len(shots), 1)
_, c_tts = charge_fen_for_tokens(
@@ -60,9 +65,7 @@ def _estimate_videos_fen(project: Project, settings: Settings) -> int:
total = 0
for sh in shots:
secs = max(float(sh.duration or 4), 2.0)
- tok = int(secs * settings.billing_est_seedance_tokens_per_sec)
- _, c_vid = charge_fen_for_tokens(tok, "seedance2:video0", settings=settings)
- total += c_vid
+ total += charge_fen_official_video(secs, settings)
return max(math.ceil(total * buf), 1)
@@ -73,7 +76,7 @@ def estimate_phase_fen(project: Project, phase: str, settings: Settings | None =
raw = normalize_kepu_pipeline_phase(phase, project)
if raw == "script":
- _, charge = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)
+ charge = charge_fen_official_llm(s.billing_est_llm_tokens, s)
return max(1, math.ceil(charge * buf))
if raw == "assets":
@@ -91,6 +94,7 @@ def estimate_phase_fen(project: Project, phase: str, settings: Settings | None =
async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings | None = None) -> int:
"""按 domain + task_type 估算单任务预扣(分)。"""
s = settings or get_settings()
+ await ensure_official_rates(s)
buf = float(s.billing_estimate_buffer or 1.2)
domain = (task.domain or "").strip()
task_type = (task.task_type or "").strip()
@@ -99,26 +103,25 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings
if domain == "kepu" and task_type == "project_pipeline":
project_id = task.project_id or payload.get("project_id")
if not project_id:
- _, charge = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)
+ charge = charge_fen_official_llm(s.billing_est_llm_tokens, s)
return max(1, math.ceil(charge * buf))
result = await db.execute(
select(Project).where(Project.id == int(project_id)).options(selectinload(Project.shots))
)
project = result.scalar_one_or_none()
if not project:
- _, charge = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)
+ charge = charge_fen_official_llm(s.billing_est_llm_tokens, s)
return max(1, math.ceil(charge * buf))
phase = str(payload.get("phase") or "script")
return estimate_phase_fen(project, phase, settings=s)
if domain == "kepu":
if task_type in {"shot_regen_image"}:
- _, c = charge_fen_for_tokens(s.billing_est_seedream_tokens, "seedream", settings=s)
+ c = charge_fen_official_image(s)
return max(1, math.ceil(c * buf))
if task_type in {"shot_regen_video"}:
dur = float(payload.get("duration") or 5)
- tok = int(max(dur, 2.0) * s.billing_est_seedance_tokens_per_sec)
- _, c = charge_fen_for_tokens(tok, "seedance2:video0", settings=s)
+ c = charge_fen_official_video(max(dur, 2.0), s)
return max(1, math.ceil(c * buf))
if task_type in {"shot_regen_audio", "project_regen_audio"}:
_, c = charge_fen_for_tokens(s.billing_est_tts_tokens * 3, "tts", settings=s)
@@ -128,17 +131,17 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings
if domain == "drama":
if task_type in {"script_summary", "fragment_plan", "agent_chat"}:
- _, c = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)
+ c = charge_fen_official_llm(s.billing_est_llm_tokens, s)
return max(1, math.ceil(c * buf))
if task_type == "episode_script":
total_eps = int(payload.get("total") or payload.get("episode_count") or 1)
- _, c = charge_fen_for_tokens(s.billing_est_llm_tokens * max(total_eps, 1), "llm_chat", settings=s)
+ c = charge_fen_official_llm(s.billing_est_llm_tokens * max(total_eps, 1), s)
return max(1, math.ceil(c * buf))
if task_type in {"asset_image", "seed_assets"}:
if task_type == "seed_assets":
- _, c = charge_fen_for_tokens(s.billing_est_llm_tokens * 3, "llm_chat", settings=s)
+ c = charge_fen_official_llm(s.billing_est_llm_tokens * 3, s)
return max(1, math.ceil(c * buf))
- _, c = charge_fen_for_tokens(s.billing_est_seedream_tokens, "seedream", settings=s)
+ c = charge_fen_official_image(s)
return max(1, math.ceil(c * buf))
if task_type in {"asset_video", "fragment_video"}:
dur = float(payload.get("duration_sec") or payload.get("duration") or 0)
@@ -166,32 +169,29 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings
)
if dur <= 0:
dur = 8.0
- tok = int(max(dur, 2.0) * s.billing_est_seedance_tokens_per_sec)
- _, c = charge_fen_for_tokens(tok, "seedance2:video0", settings=s)
+ c = charge_fen_official_video(max(dur, 2.0), s)
if task_type == "fragment_video":
- _, c_img = charge_fen_for_tokens(s.billing_est_seedream_tokens, "seedream", settings=s)
- c += max(1, c_img // 2)
+ c += max(1, charge_fen_official_image(s) // 2)
return max(1, math.ceil(c * buf))
if task_type == "voice_synthesis":
_, c = charge_fen_for_tokens(s.billing_est_tts_tokens, "tts", settings=s)
return max(1, math.ceil(c * buf))
if task_type in {"skill_optimize", "voice_prompt"}:
- _, c = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)
+ c = charge_fen_official_llm(s.billing_est_llm_tokens, s)
return max(1, math.ceil(c * buf))
if domain == "kepu" and task_type == "content_expand":
- _, c = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)
+ c = charge_fen_official_llm(s.billing_est_llm_tokens, s)
return max(1, math.ceil(c * buf))
if domain in {"api", "studio"}:
if task_type in {"v1_image", "tool_image"}:
- _, c = charge_fen_for_tokens(s.billing_est_seedream_tokens, "seedream", settings=s)
+ c = charge_fen_official_image(s)
return max(1, math.ceil(c * buf))
if task_type in {"v1_video", "v1_seedance", "tool_video"}:
dur = float(payload.get("duration") or 5)
- tok = int(max(dur, 2.0) * s.billing_est_seedance_tokens_per_sec)
- _, c = charge_fen_for_tokens(tok, "seedance2:video0", settings=s)
+ c = charge_fen_official_video(max(dur, 2.0), s)
return max(1, math.ceil(c * buf))
- _, c = charge_fen_for_tokens(s.billing_est_llm_tokens, "llm_chat", settings=s)
+ c = charge_fen_official_llm(s.billing_est_llm_tokens, s)
return max(1, math.ceil(c * buf))
diff --git a/backend/app/services/billing/pricing.py b/backend/app/services/billing/pricing.py
index 996474f..e5c051f 100644
--- a/backend/app/services/billing/pricing.py
+++ b/backend/app/services/billing/pricing.py
@@ -56,18 +56,25 @@ def kie_credits_to_cost_fen(
return max(1, int(math.ceil(amount * kie_fen_per_credit(settings))))
+def user_charge_fen(cost_fen: int, settings: Settings | None = None) -> int:
+ """用户扣费 = TokenFree / 上游成本,不再乘 markup。"""
+ if cost_fen <= 0:
+ return 0
+ return max(1, int(cost_fen))
+
+
def charge_fen_for_tokens(
tokens: int,
billing_key: str,
*,
settings: Settings | None = None,
) -> tuple[int, int]:
- """Return (cost_fen, charge_fen) with markup."""
+ """Return (cost_fen, charge_fen);charge 与成本相同。"""
s = settings or get_settings()
t = max(0, int(tokens))
yuan_per_m = provider_yuan_per_m(billing_key, s)
cost = math.ceil(t / 1_000_000 * yuan_per_m * 100) if t else 0
- charge = math.ceil(cost * float(s.billing_markup)) if cost else 0
+ charge = user_charge_fen(cost, s)
if t > 0 and charge < 1:
charge = 1
cost = max(cost, 1)
@@ -144,15 +151,13 @@ def charge_fen_for_usage(
) -> tuple[int, int, bool]:
"""按上游实际成本或 token 用量计算 (cost_fen, charge_fen, used_upstream_cost)。
- 有上游成本时:charge = ceil(cost × markup)(按比例加价)。
+ 用户扣费与 TokenFree / 上游成本相同,不再加价。
"""
s = settings or get_settings()
upstream_cost = parse_upstream_cost_fen(raw_usage, settings=s)
if upstream_cost is not None and upstream_cost > 0:
cost = upstream_cost
- charge = math.ceil(cost * float(s.billing_markup))
- if charge < 1:
- charge = 1
+ charge = user_charge_fen(cost, s)
return cost, charge, True
cost, charge = charge_fen_for_tokens(tokens, billing_key, settings=s)
return cost, charge, False
@@ -195,50 +200,10 @@ def billing_key_label(billing_key: str) -> str:
def billing_model_rate_rows(settings: Settings | None = None) -> list[dict[str, Any]]:
- """管理端展示:TokenFree 上游优先按 New API quota,缺省回退 token 单价。"""
- s = settings or get_settings()
- markup = float(s.billing_markup)
- return [
- {
- "id": "llm_chat",
- "label": "LLM 对话",
- "provider": "tokenfree",
- "capability": "llm",
- "basis": "quota/token",
- "rate_label": f"New API quota 优先;缺省 {s.billing_llm_per_m} 元/百万 tokens",
- "markup": markup,
- },
- {
- "id": "seedream",
- "label": "图片生成",
- "provider": "tokenfree",
- "capability": "image",
- "basis": "quota/token",
- "rate_label": f"New API quota 优先;缺省 {s.billing_seedream_per_m} 元/百万 tokens",
- "markup": markup,
- },
- {
- "id": "seedance",
- "label": "视频生成",
- "provider": "tokenfree",
- "capability": "video",
- "basis": "quota/token",
- "rate_label": (
- f"New API quota 优先;缺省 video0 {s.billing_seedance_video0} / "
- f"video1 {s.billing_seedance_video1} 元/百万 tokens"
- ),
- "markup": markup,
- },
- {
- "id": "tts",
- "label": "TTS 语音",
- "provider": "tokenfree",
- "capability": "tts",
- "basis": "quota/token",
- "rate_label": f"New API quota 优先;缺省 {s.billing_tts_per_m} 元/百万 tokens",
- "markup": markup,
- },
- ]
+ """管理端展示:推荐模型走 TokenFree /api/pricing;无缓存时仍列出短名单。"""
+ from app.services.tokenfree_pricing import build_official_rate_rows, cached_rates
+
+ return build_official_rate_rows(cached_rates(), settings)
def sku_by_id(sku_id: str) -> dict[str, Any] | None:
diff --git a/backend/app/services/drama/access.py b/backend/app/services/drama/access.py
index 3183192..e80eeca 100644
--- a/backend/app/services/drama/access.py
+++ b/backend/app/services/drama/access.py
@@ -3,9 +3,9 @@
from __future__ import annotations
from fastapi import HTTPException
-from sqlalchemy import func, or_, select, update
+from sqlalchemy import delete, func, inspect, or_, select, update
from sqlalchemy.ext.asyncio import AsyncSession
-from sqlalchemy.orm import selectinload
+from sqlalchemy.orm import attributes, selectinload
from app.models import User
from app.models_drama import (
@@ -87,6 +87,47 @@ async def detach_task_fragment_refs(
)
+async def replace_fragment_asset_refs(
+ db: AsyncSession,
+ fragment: DramaEpisodeFragment,
+ asset_ids: list[int],
+) -> None:
+ """按目标 id 对齐分镜资产引用:只删多余、只补缺失,避免同键先 INSERT 后 DELETE。"""
+ fragment_id = int(fragment.id)
+ unique_ids: list[int] = []
+ seen: set[int] = set()
+ for raw_id in asset_ids:
+ asset_id = int(raw_id)
+ if asset_id <= 0 or asset_id in seen:
+ continue
+ seen.add(asset_id)
+ unique_ids.append(asset_id)
+ desired = set(unique_ids)
+
+ if "asset_references" in inspect(fragment).unloaded:
+ # 未加载:SQL 清库后写入内存集合,避免 async lazy load
+ await db.execute(
+ delete(DramaFragmentAssetRef)
+ .where(DramaFragmentAssetRef.fragment_id == fragment_id)
+ .execution_options(synchronize_session=False)
+ )
+ await db.flush()
+ attributes.set_committed_value(fragment, "asset_references", [])
+ else:
+ for ref in list(fragment.asset_references):
+ if int(ref.asset_id) not in desired:
+ fragment.asset_references.remove(ref)
+
+ existing = {int(ref.asset_id) for ref in fragment.asset_references}
+ for asset_id in unique_ids:
+ if asset_id in existing:
+ continue
+ fragment.asset_references.append(
+ DramaFragmentAssetRef(fragment_id=fragment_id, asset_id=asset_id)
+ )
+ await db.flush()
+
+
async def filter_valid_project_asset_ids(
db: AsyncSession,
project_id: int,
@@ -115,6 +156,7 @@ async def load_episode_fragments(
select(DramaEpisodeFragment)
.where(DramaEpisodeFragment.episode_id == episode_id)
.options(selectinload(DramaEpisodeFragment.asset_references))
+ .execution_options(populate_existing=True)
.order_by(DramaEpisodeFragment.sort_order.asc(), DramaEpisodeFragment.id.asc())
)
return list(result.scalars().all())
diff --git a/backend/app/services/drama/asset_video.py b/backend/app/services/drama/asset_video.py
index aad575f..cf7c727 100644
--- a/backend/app/services/drama/asset_video.py
+++ b/backend/app/services/drama/asset_video.py
@@ -15,12 +15,17 @@ from app.services.ark import get_ark
from app.services.drama.billing_util import record_seedance_video_usage, seedance_billing_key
from app.services.drama.build_seedance_generate_body import (
build_seedance_generate_body,
+ build_seedance_reference_catalog,
drama_asset_to_payload,
)
from app.services.drama.generation import (
ensure_reference_assets_public_urls,
extract_asset_ids_from_content,
)
+from app.services.drama.image_styles import (
+ append_style_board_url,
+ resolve_image_style_board_url,
+)
logger = logging.getLogger(__name__)
@@ -94,6 +99,10 @@ async def generate_asset_video(
ref_assets = await load_reference_assets(db, project.id, ref_ids)
ref_assets = await ensure_reference_assets_public_urls(db, ref_assets)
ref_payloads = [drama_asset_to_payload(item) for item in ref_assets]
+ # catalog 参考资产;video_board_url 仅在已有角色/场景图时挂画风板
+ catalog = build_seedance_reference_catalog(ref_payloads)
+ board_url = resolve_image_style_board_url(style_id)
+ video_board_url = board_url if catalog.images else ""
t0 = time.time()
from app.services.kie_catalog import get_media_model
@@ -104,7 +113,6 @@ async def generate_asset_video(
from app.services import storage as storage_svc
from app.services.drama.build_seedance_generate_body import (
build_seedance_prompt_text,
- build_seedance_reference_catalog,
resolve_reference_image_url,
)
@@ -116,9 +124,9 @@ async def generate_asset_video(
text = str(published).strip()
return text if text.startswith("https://") else raw
- catalog = build_seedance_reference_catalog(ref_payloads)
ref_image_urls: list[str] = []
- for item in catalog.images[:30]:
+ image_budget = 29 if video_board_url else 30
+ for item in catalog.images[:image_budget]:
https_url = _https(item.url)
if https_url.startswith("https://"):
ref_image_urls.append(https_url)
@@ -138,9 +146,17 @@ async def generate_asset_video(
image_url = resolve_reference_image_url(drama_asset_to_payload(asset)) or ""
if not image_url:
raise RuntimeError("Kie 图生视频需要参考图或资产封面")
+ elif video_board_url:
+ ref_image_urls = append_style_board_url(ref_image_urls, video_board_url)
kie_prompt = (
- build_seedance_prompt_text(content, ref_payloads, catalog, style_id)
+ build_seedance_prompt_text(
+ content,
+ ref_payloads,
+ catalog,
+ style_id,
+ has_style_board=bool(video_board_url),
+ )
if ref_image_urls
else content
)
@@ -172,6 +188,7 @@ async def generate_asset_video(
"aspect_ratio": ratio,
"resolution": res,
"duration_fallback": duration,
+ "style_board_url": video_board_url or None,
}
)
local_video, local_last_frame, task_result = await ark.gen_and_wait_seedance_body(
diff --git a/backend/app/services/drama/build_fragments.py b/backend/app/services/drama/build_fragments.py
index cdc6318..fdbfebe 100644
--- a/backend/app/services/drama/build_fragments.py
+++ b/backend/app/services/drama/build_fragments.py
@@ -1159,16 +1159,18 @@ def plan_fragment_content_from_scene(
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
+ for raw in trimmed.replace("\r\n", "\n").split("\n"):
+ line = raw.strip()
+ if not line:
+ continue
+ if SCENE_HEADER_RE.match(line) or SCENE_HEADER_LOOSE_RE.match(line):
+ return True
+ if CAST_LINE_RE.match(line) or line.startswith("出场人物"):
+ return True
return False
diff --git a/backend/app/services/drama/build_seedance_generate_body.py b/backend/app/services/drama/build_seedance_generate_body.py
index db345e9..df7ee6a 100644
--- a/backend/app/services/drama/build_seedance_generate_body.py
+++ b/backend/app/services/drama/build_seedance_generate_body.py
@@ -14,7 +14,10 @@ from app.services.drama.fragment_content_duration import (
replace_duration_mentions_with_time_ranges,
resolve_seedance_duration_from_content,
)
-from app.services.drama.image_styles import resolve_image_style_prompt
+from app.services.drama.image_styles import (
+ STYLE_BOARD_PROMPT_HINT,
+ resolve_image_style_prompt,
+)
from app.services.seedance_segments import (
build_seedance_production_section,
rewrite_misclassified_visual_voice_lines,
@@ -58,6 +61,8 @@ class BuildSeedanceGenerateBodyInput(TypedDict, total=False):
duration_fallback: int | None
# 上一镜尾帧公网/本地 URL;有参考媒体时作 reference_image(不可与 first_frame 混用)
continuity_first_frame_url: str | None
+ # 画风板公网 URL(角色/场景图之后、衔接尾帧之前)
+ style_board_url: str | None
# True=模型烧录字幕;False=后期叠字(禁止画面内字幕)
burn_subtitles: bool
# True=角色身旁人物介绍叠字;False=禁止人物介绍字卡
@@ -247,6 +252,7 @@ def describe_seedance_content_slots(
continuity_first_frame_url: str | None = None,
*,
has_text: bool = True,
+ style_board_url: str | None = None,
) -> list[str]:
catalog = build_seedance_reference_catalog(reference)
asset_by_id = {
@@ -263,6 +269,9 @@ def describe_seedance_content_slots(
kind_zh = _KIND_ZH.get(kind, "参考图")
name = str(asset.get("name") or "").strip() or f"资产#{image.asset_id}"
labels.append(f"{kind_zh}「{name}」")
+ board = (style_board_url or "").strip() if catalog.images else ""
+ if board:
+ labels.append("画风板")
for audio in catalog.audios:
asset = asset_by_id.get(audio.asset_id) or {}
kind = str(asset.get("type") or "").lower()
@@ -300,12 +309,17 @@ def replace_asset_mention_token(
return format_body_asset_mention(resolve_other_asset_prompt_name(asset), image_index)
-# 组装画面风格声明块
-def build_visual_style_section(video_style_id: str | None) -> str | None:
+# 组装画面风格声明块;有画风板时强调只借气质、禁止抄主体
+def build_visual_style_section(
+ video_style_id: str | None,
+ *,
+ has_style_board: bool = False,
+) -> str | None:
style_prompt = resolve_image_style_prompt(video_style_id)
if not style_prompt:
return None
- return f"{SEEDANCE_VISUAL_STYLE_SECTION_INTRO}\n{style_prompt}"
+ extra = f"\n{STYLE_BOARD_PROMPT_HINT}" if has_style_board else ""
+ return f"{SEEDANCE_VISUAL_STYLE_SECTION_INTRO}\n{style_prompt}{extra}"
def build_reference_index_section(
@@ -368,6 +382,7 @@ def build_seedance_prompt_text(
*,
burn_subtitles: bool = True,
character_intro: bool = True,
+ has_style_board: bool = False,
) -> str:
# 提交前拆分对白舞台指示并纠正空镜误标,保证强制约束与正文一致
normalized = rewrite_dialogue_action_lines(content or "")
@@ -379,7 +394,7 @@ def build_seedance_prompt_text(
normalized = strip_character_intro_cues(normalized)
resolved_catalog = catalog or build_seedance_reference_catalog(reference)
sections = [
- build_visual_style_section(video_style_id),
+ build_visual_style_section(video_style_id, has_style_board=has_style_board),
build_seedance_production_section(
normalized,
burn_subtitles=burn_subtitles,
@@ -431,8 +446,11 @@ def build_seedance_content_items(
*,
burn_subtitles: bool = True,
character_intro: bool = True,
+ style_board_url: str | None = None,
) -> list[dict[str, Any]]:
catalog = build_seedance_reference_catalog(reference)
+ # 无角色/场景图时不挂画风板,避免板子变成唯一画面参考
+ board = (style_board_url or "").strip() if catalog.images else ""
prompt_text = build_seedance_prompt_text(
content,
reference,
@@ -440,6 +458,7 @@ def build_seedance_content_items(
video_style_id,
burn_subtitles=burn_subtitles,
character_intro=character_intro,
+ has_style_board=bool(board),
)
items: list[dict[str, Any]] = []
@@ -469,6 +488,11 @@ def build_seedance_content_items(
{"type": "image_url", "image_url": {"url": image.url}, "role": "reference_image"}
)
+ if board:
+ items.append(
+ {"type": "image_url", "image_url": {"url": board}, "role": "reference_image"}
+ )
+
for audio in catalog.audios:
items.append(
{"type": "audio_url", "audio_url": {"url": audio.url}, "role": "reference_audio"}
@@ -530,6 +554,9 @@ def build_seedance_generate_body(input_params: BuildSeedanceGenerateBodyInput) -
reference = input_params.get("reference")
catalog = build_seedance_reference_catalog(reference)
# 仅「纯首帧、无参考媒体」时省略 ratio;混用参考时必须保留 ratio、且尾帧用 reference_image
+ style_board_url = (input_params.get("style_board_url") or "").strip() or None
+ if not catalog.images:
+ style_board_url = None
use_first_frame_mode = bool(continuity) and not (catalog.images or catalog.audios)
burn_subtitles = input_params.get("burn_subtitles")
if burn_subtitles is None:
@@ -547,6 +574,7 @@ def build_seedance_generate_body(input_params: BuildSeedanceGenerateBodyInput) -
continuity_first_frame_url=continuity,
burn_subtitles=bool(burn_subtitles),
character_intro=bool(character_intro),
+ style_board_url=style_board_url,
),
"duration": resolve_seedance_duration_from_content(content, fallback=fallback),
"resolution": resolve_seedance_resolution(input_params.get("resolution")),
diff --git a/backend/app/services/drama/generation.py b/backend/app/services/drama/generation.py
index 5929971..b8f5da0 100644
--- a/backend/app/services/drama/generation.py
+++ b/backend/app/services/drama/generation.py
@@ -35,7 +35,11 @@ from app.services.drama.build_seedance_generate_body import (
resolve_episode_burn_subtitles,
resolve_episode_character_intro,
)
-from app.services.drama.generation_prompt import build_generation_prompt
+from app.services.drama.generation_prompt import append_style_prompt, build_generation_prompt
+from app.services.drama.image_styles import (
+ append_style_board_url,
+ resolve_image_style_board_url,
+)
from app.services.drama.seedream_options import resolve_seedream_model_endpoint, resolve_seedream_size
from app.services.drama.visual_prompt import resolve_visual_prompt_for_asset
from app.services.drama.voice_synthesis import build_voice_sample_text, synthesize_voice_asset
@@ -1283,10 +1287,14 @@ async def generate_asset_image(
res = (resolution or "").strip() or "2K"
model = resolve_seedream_model_endpoint(model_id)
size = resolve_seedream_size(aspect_ratio=ratio, resolution=res, model_id=model)
- full_prompt = build_generation_prompt(prompt, asset_type=kind, style_id=style_id)
+ # board 风格封面的公网 URL;没有栅格图时仍只靠提示词
+ board = resolve_image_style_board_url(style_id)
+ full_prompt = build_generation_prompt(
+ prompt, asset_type=kind, style_id=style_id, has_style_board=bool(board)
+ )
logger.info(
- "调用 Seedream 生图 project_id=%s asset_id=%s kind=%s style=%s model=%s size=%s prompt_len=%s",
+ "调用 Seedream 生图 project_id=%s asset_id=%s kind=%s style=%s model=%s size=%s prompt_len=%s board=%s",
project.id,
asset.id if asset else None,
kind,
@@ -1294,6 +1302,7 @@ async def generate_asset_image(
model,
size,
len(full_prompt or ""),
+ bool(board),
)
result = await ark.gen_image(
full_prompt.strip(),
@@ -1301,6 +1310,7 @@ async def generate_asset_image(
size=size,
model=model,
aspect_ratio=ratio,
+ style_ref_urls=[board] if board else None,
)
# 生图结果实时同步 OSS(禁止异步排队),Seedance 参考图需要公网 https
from datetime import datetime, timezone
@@ -1558,6 +1568,9 @@ async def prepare_fragment_video_for_submit(
ref_payloads = build_fragment_ref_payloads(project, ref_assets)
style_id = str((project.params or {}).get("image_style_id") or "").strip() or None
catalog = build_seedance_reference_catalog(ref_payloads)
+ # board 始终可用于静帧;视频参考图只在已有角色/场景图时挂上,避免封面被当成主体
+ board_url = resolve_image_style_board_url(style_id)
+ video_board_url = board_url if catalog.images else ""
continuity_url: str | None = None
if project_link_last_frame_enabled(project):
@@ -1576,7 +1589,8 @@ async def prepare_fragment_video_for_submit(
ark = get_ark()
ref_image_urls: list[str] = []
unsupported_images: list[str] = []
- for item in catalog.images[:30]:
+ image_budget = 29 if video_board_url else 30
+ for item in catalog.images[:image_budget]:
https_url = _publish_https_media_url(item.url)
if not https_url.startswith("https://"):
continue
@@ -1597,8 +1611,13 @@ async def prepare_fragment_video_for_submit(
ref_audio_urls.append(https_url)
if not ref_image_urls:
+ still_prompt = append_style_prompt(
+ (prompt or "").strip()[:500] or "短剧分镜",
+ style_id,
+ has_style_board=False,
+ )
still = await ark.gen_image(
- prompt[:500],
+ still_prompt,
project_id=project.id,
shot_no=fragment.id,
size=seedream_still_size_for_video_ratio(ratio),
@@ -1617,6 +1636,8 @@ async def prepare_fragment_video_for_submit(
)
# 多参考:把 @asset:id 改写成「参考图N」,与 reference_image_urls 顺序对齐
+ if video_board_url:
+ ref_image_urls = append_style_board_url(ref_image_urls, video_board_url)
kie_prompt = build_seedance_prompt_text(
prompt,
ref_payloads,
@@ -1628,6 +1649,7 @@ async def prepare_fragment_video_for_submit(
character_intro=resolve_episode_character_intro(
episode.params if episode else None
),
+ has_style_board=bool(video_board_url),
)
return FragmentVideoPrepared(
submit_mode="kie",
@@ -1644,6 +1666,7 @@ async def prepare_fragment_video_for_submit(
ref_payloads,
None,
has_text=bool((prompt or "").strip()),
+ style_board_url=video_board_url or None,
),
model_id=mid,
kie_api_kind=kie_spec.api_kind if kie_spec else "jobs",
@@ -1660,6 +1683,7 @@ async def prepare_fragment_video_for_submit(
"resolution": resolution,
"duration_fallback": duration,
"continuity_first_frame_url": continuity_url,
+ "style_board_url": video_board_url or None,
"burn_subtitles": resolve_episode_burn_subtitles(
episode.params if episode else None
),
@@ -1679,6 +1703,7 @@ async def prepare_fragment_video_for_submit(
ref_payloads,
continuity_url,
has_text=bool((prompt or "").strip()),
+ style_board_url=video_board_url or None,
),
model_id=mid,
)
@@ -1686,8 +1711,14 @@ async def prepare_fragment_video_for_submit(
ark = get_ark()
if not image_url:
# Seedance i2v 禁止传 ratio,输出跟首帧;静帧必须先按目标画幅生成
+ # 无主体参考时不把画风板当唯一 image,只靠风格文案
+ still_prompt = append_style_prompt(
+ (prompt or "").strip()[:500] or "短剧分镜",
+ style_id,
+ has_style_board=False,
+ )
still = await ark.gen_image(
- prompt[:500],
+ still_prompt,
project_id=project.id,
shot_no=fragment.id,
size=seedream_still_size_for_video_ratio(ratio),
diff --git a/backend/app/services/drama/generation_prompt.py b/backend/app/services/drama/generation_prompt.py
index 10aabfb..5431e90 100644
--- a/backend/app/services/drama/generation_prompt.py
+++ b/backend/app/services/drama/generation_prompt.py
@@ -7,7 +7,7 @@ ai_movie 扩展:prop/material 增加静物/空镜前缀(manju 无此前缀
from __future__ import annotations
-from app.services.drama.image_styles import resolve_image_style_prompt
+from app.services.drama.image_styles import STYLE_BOARD_PROMPT_HINT, resolve_image_style_prompt
# CHARACTER_PROMPT_PREFIX 角色设定板结构要求(无风格词)
CHARACTER_PROMPT_PREFIX = (
@@ -64,21 +64,24 @@ MATERIAL_PROMPT_PREFIX = (
# 将内置风格提示词追加到正文后;设定板类资产强调构图优先于风格场景
+# has_style_board 为真时补一句:只借画风板气质,禁止抄主体
def append_style_prompt(
prompt: str,
style_id: str | None = None,
*,
structure_locked: bool = False,
+ has_style_board: bool = False,
) -> str:
style_prompt = resolve_image_style_prompt(style_id)
if not style_prompt:
return prompt
+ board_hint = f"。{STYLE_BOARD_PROMPT_HINT}" if has_style_board else ""
if structure_locked:
return (
- f"{prompt}。外观材质与画风参考:{style_prompt}"
+ f"{prompt}。外观材质与画风参考:{style_prompt}{board_hint}"
"(须服从上文白底设定板构图与排版,禁止改成复杂场景或替换纯白背景)"
)
- return f"{prompt}。画面风格要求:{style_prompt}"
+ return f"{prompt}。画面风格要求:{style_prompt}{board_hint}"
# 按资产类型与风格 ID 组装完整 Seedream 提示词
@@ -86,6 +89,8 @@ def build_generation_prompt(
user_prompt: str,
asset_type: str | None = None,
style_id: str | None = None,
+ *,
+ has_style_board: bool = False,
) -> str:
trimmed = (user_prompt or "").strip()
prompt = trimmed
@@ -101,4 +106,6 @@ def build_generation_prompt(
structure_locked = True
elif kind in {"material", "none"}:
prompt = f"{MATERIAL_PROMPT_PREFIX}{trimmed}"
- return append_style_prompt(prompt, style_id, structure_locked=structure_locked)
+ return append_style_prompt(
+ prompt, style_id, structure_locked=structure_locked, has_style_board=has_style_board
+ )
diff --git a/backend/app/services/drama/image_styles.py b/backend/app/services/drama/image_styles.py
index 147c255..3086ffd 100644
--- a/backend/app/services/drama/image_styles.py
+++ b/backend/app/services/drama/image_styles.py
@@ -2,6 +2,23 @@
from __future__ import annotations
+import logging
+import time
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+# 画风板只借鉴气质,禁止抄参考图里的人物与构图
+STYLE_BOARD_PROMPT_HINT = (
+ "另附画风参考图:只借鉴其色调、笔触、光影与整体气质,"
+ "禁止复制该图的人物、场景主体与构图。"
+)
+
+_STYLE_BOARD_EXTS = (".png", ".jpg", ".jpeg", ".webp")
+_board_url_cache: dict[tuple[str, int, int], str] = {}
+_board_fail_cache: dict[tuple[str, int, int], float] = {}
+_BOARD_FAIL_TTL_SEC = 60.0
+
# IMAGE_STYLE_IDS 内置风格 ID(与前端 dramaImageStyles 对齐)
IMAGE_STYLE_IDS = (
"retro-sci-fi-atompunk",
@@ -20,6 +37,7 @@ IMAGE_STYLE_IDS = (
"neon-cyberpunk-film",
"90s-rural-china-film",
"cgi-3d-animation",
+ "ghibli-handdrawn-anime",
"tezuka-era-cartoon",
"shanghai-animation",
"pixel-art",
@@ -79,6 +97,12 @@ IMAGE_STYLE_PROMPTS: dict[str, str] = {
"柔和体积光与次表面散射,干净材质与饱和配色,浅景深,"
"非写实摄影、非日系赛璐璐平面、非剪纸扁平"
),
+ "ghibli-handdrawn-anime": (
+ "手绘二维动画电影气质,水彩与水粉背景,柔和自然光与金色黄昏,"
+ "写实人体比例与朴素五官(非大眼睛赛璐璐美少女),生活化服饰,"
+ "茂盛草木、风吹草地与流动云层,温暖土黄与青绿,空气透视与电影构图,"
+ "非写实摄影、非3D CGI、非像素风、非剪纸扁平"
+ ),
"tezuka-era-cartoon": "手冢治虫时代经典日式卡通画风,简洁线条,复古动画平涂着色,怀旧动画质感",
"shanghai-animation": (
"上海美术电影制片厂经典动画画风,中国民族绘画韵味,水彩与工笔结合,诗意唯美,传统色彩"
@@ -107,6 +131,7 @@ IMAGE_STYLE_LABELS: dict[str, str] = {
"neon-cyberpunk-film": "霓虹赛博电影",
"90s-rural-china-film": "90年代中国农村电影",
"cgi-3d-animation": "3D 动画",
+ "ghibli-handdrawn-anime": "宫崎骏气质手绘",
"tezuka-era-cartoon": "手冢治虫时代卡通画风",
"shanghai-animation": "上美画风",
"pixel-art": "像素风",
@@ -124,3 +149,102 @@ def resolve_image_style_prompt(style_id: str | None = None) -> str:
if not style_id:
return ""
return IMAGE_STYLE_PROMPTS.get(style_id, "")
+
+
+def _first_raster(directory: Path, style_id: str) -> Path | None:
+ """目录下按常见栅格后缀找风格板,跳过 svg 占位。"""
+ if not directory.is_dir():
+ return None
+ for ext in _STYLE_BOARD_EXTS:
+ path = directory / f"{style_id}{ext}"
+ if path.is_file() and path.stat().st_size > 1024:
+ return path
+ return None
+
+
+# 延迟导入,避免与 storage 循环依赖
+def _static_root() -> Path:
+ from app.services.storage import STATIC_ROOT
+
+ return STATIC_ROOT
+
+
+def _safe_image_style_id(style_id: str | None) -> str | None:
+ """只接受内置风格 ID,拒绝路径穿越。"""
+ sid = (style_id or "").strip()
+ if not sid or sid not in IMAGE_STYLE_IDS:
+ return None
+ if any(part in sid for part in ("/", "\\", "..")):
+ return None
+ return sid
+
+
+def style_board_local_path(style_id: str | None) -> Path | None:
+ """风格板本地文件:优先 backend/static,其次前端 public 封面。"""
+ sid = _safe_image_style_id(style_id)
+ if not sid:
+ return None
+ backend_dir = _static_root() / "drama" / "image-styles"
+ found = _first_raster(backend_dir, sid)
+ if found:
+ return found
+ repo_root = Path(__file__).resolve().parents[4]
+ return _first_raster(repo_root / "frontend" / "public" / "image-styles", sid)
+
+
+def resolve_image_style_board_url(style_id: str | None = None) -> str:
+ """把风格板发到公网 https,供 Seedream / Seedance 拉图;失败则空串(仍走提示词)。"""
+ path = style_board_local_path(style_id)
+ if path is None:
+ return ""
+ cache_key = (str(path.resolve()), int(path.stat().st_mtime_ns), int(path.stat().st_size))
+ cached = _board_url_cache.get(cache_key)
+ if cached:
+ return cached
+ failed_at = _board_fail_cache.get(cache_key)
+ if failed_at is not None and (time.monotonic() - failed_at) < _BOARD_FAIL_TTL_SEC:
+ return ""
+ from app.services import storage
+ from app.services.style_lock import seedream_ref_urls
+
+ dest = path
+ static_root = _static_root()
+ try:
+ resolved = path.resolve()
+ if static_root not in resolved.parents and static_root != resolved.parent:
+ dest_dir = static_root / "drama" / "image-styles"
+ dest_dir.mkdir(parents=True, exist_ok=True)
+ dest = dest_dir / path.name
+ if not dest.exists() or dest.stat().st_mtime < path.stat().st_mtime:
+ dest.write_bytes(path.read_bytes())
+ published = storage.publish_local(dest, sync=True)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("风格板未能发布为公网 URL style=%s: %s", style_id, exc)
+ _board_fail_cache[cache_key] = time.monotonic()
+ return ""
+ urls = seedream_ref_urls(published, limit=1)
+ url = urls[0] if urls else ""
+ if not url:
+ logger.warning("风格板 URL 不是上游可拉取的 https style=%s published=%s", style_id, published)
+ _board_fail_cache[cache_key] = time.monotonic()
+ return ""
+ _board_fail_cache.pop(cache_key, None)
+ _board_url_cache[cache_key] = url
+ return url
+
+
+def append_style_board_url(
+ urls: list[str],
+ board_url: str | None,
+ *,
+ max_total: int = 30,
+) -> list[str]:
+ """画风板接到角色/场景图之后,去重,并为板子预留最后一个名额。"""
+ board = (board_url or "").strip()
+ out = [u.strip() for u in urls if (u or "").strip()]
+ cap = max(1, int(max_total))
+ if board:
+ out = [u for u in out if u != board][: cap - 1]
+ out.append(board)
+ return out
+ return out[:cap]
diff --git a/backend/app/services/drama/seed.py b/backend/app/services/drama/seed.py
index f9a11d3..561c3c7 100644
--- a/backend/app/services/drama/seed.py
+++ b/backend/app/services/drama/seed.py
@@ -1369,8 +1369,8 @@ def _episode_should_replace_fragments(episode: DramaEpisode, script_body: str) -
return True
if _episode_has_protected_fragments(episode):
return False
- if any(is_raw_screenplay_fragment(f.content or "") for f in frags):
- # 场记原文须重切,但已有成片/手改时不覆盖
+ if all(is_raw_screenplay_fragment(f.content or "") for f in frags):
+ # 整集仍是场记原文才重切;夹一手写镜或空镜不要整集覆盖
return True
params = episode.params if isinstance(episode.params, dict) else {}
stored_fp = str(params.get("fragment_source_fp") or "")
diff --git a/backend/app/services/kepu_continuity.py b/backend/app/services/kepu_continuity.py
new file mode 100644
index 0000000..8b61d2d
--- /dev/null
+++ b/backend/app/services/kepu_continuity.py
@@ -0,0 +1,131 @@
+"""科普镜间衔接:后镜出图参考上一镜静帧,出视频参考上一镜尾帧。"""
+
+from __future__ import annotations
+
+import time
+from typing import Any
+
+from app.services.style_lock import seedream_ref_urls
+
+
+def previous_shot(shots: list[Any], shot_no: int) -> Any | None:
+ """按 shot_no 取上一镜(不含本镜)。"""
+ prev = None
+ for shot in sorted(shots, key=lambda item: int(getattr(item, "shot_no", 0) or 0)):
+ no = int(getattr(shot, "shot_no", 0) or 0)
+ if no >= int(shot_no):
+ break
+ prev = shot
+ return prev
+
+
+def previous_usable_shot(shots: list[Any], shot_no: int) -> Any | None:
+ """向前找到最近一镜有静帧或尾帧的镜头。"""
+ prev = None
+ for shot in sorted(shots, key=lambda item: int(getattr(item, "shot_no", 0) or 0)):
+ no = int(getattr(shot, "shot_no", 0) or 0)
+ if no >= int(shot_no):
+ break
+ if shot_image_ref(shot) or shot_last_frame_ref(shot):
+ prev = shot
+ return prev
+
+
+def _usable_seedream_url(raw: str | None, *, allow_republish: bool = False) -> str | None:
+ """只返回 Seedream 能拉的公网地址;TokenFree 产物地址不可作参考。"""
+ url = str(raw or "").strip()
+ if not url:
+ return None
+ from app.services.tokenfree_image import is_tokenfree_image_url
+
+ if is_tokenfree_image_url(url):
+ return None
+ if allow_republish and not (url.startswith("http://") or url.startswith("https://")):
+ from app.services import storage
+
+ url = str(storage.republish_url(url, sync=True) or "").strip()
+ if is_tokenfree_image_url(url):
+ return None
+ ok = seedream_ref_urls(url)
+ return ok[0] if ok else None
+
+
+def shot_image_ref(shot: Any | None) -> str | None:
+ """优先已是公网的 image_url,其次 ark CDN;本地 /static 尝试同步上 OSS。"""
+ if shot is None:
+ return None
+ candidates = (getattr(shot, "image_url", None), getattr(shot, "image_ark_url", None))
+ for raw in candidates:
+ url = _usable_seedream_url(raw, allow_republish=False)
+ if url:
+ return url
+ for raw in candidates:
+ url = _usable_seedream_url(raw, allow_republish=True)
+ if url:
+ return url
+ return None
+
+
+def _any_shot_image(shot: Any) -> str | None:
+ """静帧任意可用地址(含本地 /static,交给下游 resolve)。"""
+ for raw in (getattr(shot, "image_ark_url", None), getattr(shot, "image_url", None)):
+ url = str(raw or "").strip()
+ if url:
+ return url
+ return None
+
+
+def shot_last_frame_ref(shot: Any | None) -> str | None:
+ """上一镜尾帧;没有则退回该镜静帧。本地路径由 Seedance resolve 再上公网。"""
+ if shot is None:
+ return None
+ last = str(getattr(shot, "last_frame_url", None) or "").strip()
+ if last:
+ return last
+ return shot_image_ref(shot) or _any_shot_image(shot)
+
+
+def image_refs_for_shot(prev: Any | None, base_refs: list[str] | None = None) -> list[str]:
+ """本镜 Seedream 参考:上一镜静帧 + 模板底图。"""
+ bases = list(base_refs or [])
+ prev_url = shot_image_ref(prev)
+ if prev_url:
+ return seedream_ref_urls(prev_url, *bases)
+ return seedream_ref_urls(*bases)
+
+
+def video_extra_refs_for_shot(prev: Any | None) -> list[str]:
+ """本镜视频额外参考:上一镜尾帧(或静帧)。"""
+ url = shot_last_frame_ref(prev)
+ return [url] if url else []
+
+
+def persist_last_frame_from_video(
+ project_id: int,
+ shot_no: int,
+ video_url: str,
+ preferred_url: str | None = None,
+) -> str | None:
+ """优先落盘/公网尾帧;没有再用 ffmpeg 从成片抽。"""
+ from app.services import storage
+ from app.services.ffmpeg_compose import extract_video_last_frame
+
+ pref = str(preferred_url or "").strip()
+ if pref:
+ from app.services.tokenfree_image import is_tokenfree_image_url
+
+ if (pref.startswith("http://") or pref.startswith("https://")) and not is_tokenfree_image_url(pref):
+ return pref
+ https = storage.republish_url(pref, sync=True)
+ if https and str(https).startswith("http") and not is_tokenfree_image_url(str(https)):
+ return str(https)
+ if pref.startswith("/static/"):
+ return pref
+ path = storage.local_path_from_url(video_url)
+ if path and path.exists():
+ dest = storage.project_dir(int(project_id)) / f"shot_{int(shot_no):03d}_{int(time.time())}_last.jpg"
+ if extract_video_last_frame(path, dest):
+ published = storage.publish_local(dest, sync=True)
+ https = storage.republish_url(published, sync=True)
+ return https or published
+ return None
diff --git a/backend/app/services/logical_model_router.py b/backend/app/services/logical_model_router.py
index 73c0ed0..13a9973 100644
--- a/backend/app/services/logical_model_router.py
+++ b/backend/app/services/logical_model_router.py
@@ -7,7 +7,6 @@ from app.services.model_routing_config import (
channel_connection_ready,
channel_supports_model,
infer_model_capability,
- resolve_channel_model_capability,
)
from app.services.model_settings import get_routing_snapshot
@@ -76,6 +75,17 @@ def resolve_logical_model_candidates(
if routes:
return routes
+ # 用户点名的上游模型在渠道清单里时,不要静默换成同能力的另一个逻辑模型
+ if requested:
+ direct = _direct_channel_routes(
+ capability,
+ requested,
+ snapshot.channels,
+ preferred_channel_id=preferred_channel_id,
+ )
+ if direct:
+ return direct
+
# 默认/请求模型失效时,回落到同能力第一个可解析模型(DeepSeek / Kimi / 其它兼容均可)
for model in snapshot.logical_models:
if not model.enabled or model.capability != capability:
@@ -96,19 +106,36 @@ def resolve_logical_model_candidates(
if not requested:
return []
- ordered = snapshot.channels
+ return _direct_channel_routes(
+ capability,
+ requested,
+ snapshot.channels,
+ preferred_channel_id=preferred_channel_id,
+ )
+
+
+def _direct_channel_routes(
+ capability: LogicalModelCapability,
+ requested: str,
+ channels: list[SystemModelChannel],
+ *,
+ preferred_channel_id: str = "",
+) -> list[ResolvedModelRoute]:
+ """按渠道 models 清单精确匹配用户点名的上游模型。"""
+ ordered = list(channels)
if preferred_channel_id:
ordered = [
- *([item for item in snapshot.channels if item.id == preferred_channel_id]),
- *[item for item in snapshot.channels if item.id != preferred_channel_id],
+ *([item for item in channels if item.id == preferred_channel_id]),
+ *[item for item in channels if item.id != preferred_channel_id],
]
- routes = []
+ routes: list[ResolvedModelRoute] = []
for channel in ordered:
if not channel.enabled or not channel_connection_ready(channel):
continue
if not channel_supports_model(channel, requested):
continue
- if resolve_channel_model_capability(channel, requested) != capability:
+ # TokenFree 渠道 protocol=openai,resolve_channel_model_capability 会把所有模型判成 text
+ if infer_model_capability(requested) != capability:
continue
route = _build_route(capability, requested, requested, channel)
if route:
diff --git a/backend/app/services/model_routing_config.py b/backend/app/services/model_routing_config.py
index d71aff0..1125266 100644
--- a/backend/app/services/model_routing_config.py
+++ b/backend/app/services/model_routing_config.py
@@ -69,10 +69,16 @@ def channel_connection_ready(channel: SystemModelChannel) -> bool:
# 判断渠道是否包含指定上游模型
def channel_supports_model(channel: SystemModelChannel, upstream_model: str) -> bool:
+ from app.services.tokenfree_pricing import canonicalize_channel_model_id
+
target = normalize_model_name(upstream_model)
if not target:
return False
- return any(normalize_model_name(item) == target for item in channel.models)
+ target_c = canonicalize_channel_model_id(target)
+ return any(
+ normalize_model_name(item) == target or canonicalize_channel_model_id(item) == target_c
+ for item in channel.models
+ )
# 解析渠道下单模型的能力
diff --git a/backend/app/services/model_settings.py b/backend/app/services/model_settings.py
index 6e42936..c7d9bca 100644
--- a/backend/app/services/model_settings.py
+++ b/backend/app/services/model_settings.py
@@ -118,12 +118,12 @@ def _refresh_routing_snapshot(
# 从 env 构建默认渠道(开源版仅 TokenFree)
def _bootstrap_channels_from_env(settings: Settings | None = None) -> list[SystemModelChannel]:
from app.services.tokenfree_gateway import locked_tokenfree_channel
+ from app.services.tokenfree_pricing import canonicalize_channel_models
src = settings or get_settings()
key = (src.openai_api_key or src.ark_api_key or "").strip()
- models = [
- m
- for m in [
+ models = canonicalize_channel_models(
+ [
src.model_llm,
src.model_image,
src.model_image_45,
@@ -131,14 +131,15 @@ def _bootstrap_channels_from_env(settings: Settings | None = None) -> list[Syste
src.model_video_2,
src.model_audio,
]
- if m
- ]
+ )
return [locked_tokenfree_channel(api_key=key, models=models, enabled=True)]
def _seedance_logical_meta(upstream: str) -> tuple[str, str]:
- """按接入点 ID 推断 Seedance 逻辑模型(2.0 vs 2.5)。"""
+ """按接入点 ID 推断 Seedance 逻辑模型(2.0 vs 2.5 vs Mini)。"""
mid = (upstream or "").strip().lower()
+ if "mini" in mid:
+ return "seedance-2-0-mini", "Seedance 2.0 Mini"
if any(token in mid for token in ("2-5", "2.5", "260628")):
return "seedance-2.5", "Seedance 2.5"
if any(token in mid for token in ("2-0", "2.0", "260128", "seedance-2")):
@@ -218,11 +219,15 @@ def _bootstrap_logical_from_channels(channels: list[SystemModelChannel]) -> tupl
def _bindings_for_upstream(upstream: str) -> list:
from app.schemas_routing import LogicalModelBinding
+ from app.services.tokenfree_pricing import canonicalize_channel_model_id
+ wanted = {(upstream or "").strip(), canonicalize_channel_model_id(upstream)}
+ wanted.discard("")
result = []
for model in logical_models:
for binding in model.bindings:
- if binding.upstream_model == upstream:
+ raw = (binding.upstream_model or "").strip()
+ if raw in wanted or canonicalize_channel_model_id(raw) in wanted:
result.append(binding.model_copy())
return result
@@ -260,11 +265,12 @@ def _bootstrap_logical_from_channels(channels: list[SystemModelChannel]) -> tupl
bindings_for_upstream=_bindings_for_upstream,
)
if settings.model_video_2:
+ logical_id_2, name_2 = _seedance_logical_meta(settings.model_video_2)
_append_seedance_alias(
alias_models,
upstream=settings.model_video_2,
- logical_id="seedance-2",
- name="Seedance 2",
+ logical_id=logical_id_2,
+ name=name_2,
bindings_for_upstream=_bindings_for_upstream,
)
default_video = ""
@@ -373,6 +379,7 @@ async def _ensure_tokenfree_channel(db: AsyncSession, existing: list[SystemModel
TOKENFREE_CHANNEL_NAME,
pick_migratable_api_key,
)
+ from app.services.tokenfree_pricing import canonicalize_channel_models
runtime = [_channel_row_to_runtime(row) for row in existing]
migrated_key = pick_migratable_api_key(runtime)
@@ -392,9 +399,8 @@ async def _ensure_tokenfree_channel(db: AsyncSession, existing: list[SystemModel
token_row.api_key_ciphertext = _encrypt_secret(migrated_key)
current_key = migrated_key
src = get_settings()
- env_models = [
- m
- for m in [
+ env_models = canonicalize_channel_models(
+ [
src.model_llm,
src.model_image,
src.model_image_45,
@@ -402,19 +408,13 @@ async def _ensure_tokenfree_channel(db: AsyncSession, existing: list[SystemModel
src.model_video_2,
src.model_audio,
]
- if m
- ]
+ )
if not token_row.models:
token_row.models = env_models
- elif env_models:
- # 已有 DB 配置时,把 .env 新增的接入点(如 MODEL_VIDEO_2)补进渠道 models
- merged = list(token_row.models or [])
- changed = False
- for model in env_models:
- if model not in merged:
- merged.append(model)
- changed = True
- if changed:
+ else:
+ # 已有 DB 清单只折叠别名,不再把 .env 模型并回去
+ merged = canonicalize_channel_models(token_row.models)
+ if merged != list(token_row.models or []):
token_row.models = merged
for row in existing:
if row.id != TOKENFREE_CHANNEL_ID:
@@ -679,6 +679,7 @@ async def patch_admin_routing_settings(
TOKENFREE_CHANNEL_NAME,
locked_tokenfree_channel,
)
+ from app.services.tokenfree_pricing import canonicalize_channel_models
incoming = next(
(item for item in body.system_channels if (item.id or "").strip() == TOKENFREE_CHANNEL_ID),
@@ -692,7 +693,9 @@ async def patch_admin_routing_settings(
api_key = ""
elif incoming.api_key is not None and str(incoming.api_key).strip():
api_key = str(incoming.api_key).strip()
- models = list(incoming.models) if incoming is not None else (list(prev.models or []) if prev else [])
+ models = canonicalize_channel_models(
+ list(incoming.models) if incoming is not None else (list(prev.models or []) if prev else [])
+ )
locked = locked_tokenfree_channel(api_key=api_key, models=models, enabled=True)
row = prev or SystemModelChannelRow(id=TOKENFREE_CHANNEL_ID)
row.name = TOKENFREE_CHANNEL_NAME
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.py
index 969e9df..d6e1ccf 100644
--- a/backend/app/services/pipeline.py
+++ b/backend/app/services/pipeline.py
@@ -6,6 +6,7 @@ import asyncio
import logging
import shutil
from pathlib import Path
+from types import SimpleNamespace
from sqlalchemy import select
from sqlalchemy.orm import selectinload
@@ -35,9 +36,15 @@ from app.services.style_lock import (
template_consistency_mode,
template_is_photoreal,
)
+from app.services.kepu_continuity import (
+ image_refs_for_shot,
+ persist_last_frame_from_video,
+ previous_usable_shot,
+ video_extra_refs_for_shot,
+)
from app.services.voices import resolve_speaker
from app.services import seedance_segments as segplan
-from app.services.bgm import resolve_bgm_path
+from app.services.bgm import clip_shot_bgm, resolve_bgm_path
logger = logging.getLogger(__name__)
@@ -318,6 +325,39 @@ def clamp_shot_duration(duration: float, *, pipeline_mode: str, tpl_min: int, tp
return float(max(lo, min(float(duration), hi)))
+def _merge_subtitle_preset(sub_cfg: dict, preset: str) -> dict:
+ """科普字幕预设覆盖模板 subtitle_config。"""
+ out = dict(sub_cfg or {})
+ key = (preset or "").strip().lower()
+ if key == "large":
+ out["caption_scale"] = 1.55
+ elif key == "split":
+ out["position"] = "split"
+ elif key == "standard":
+ out["caption_scale"] = 1.25
+ out["position"] = "top"
+ return out
+
+
+def _kepu_video_prompt(
+ script: str,
+ *,
+ style_prefix: str,
+ motion_bias: str,
+ camera: str,
+ ambient_only: bool,
+) -> str:
+ """科普提交 Seedance:后期叠字,禁止模型烧录字幕。"""
+ return segplan.build_seedance_prompt(
+ segplan.normalize_kepu_subtitle_cue(script or ""),
+ style_prefix=style_prefix,
+ motion_bias=motion_bias,
+ camera=camera,
+ ambient_only=ambient_only,
+ burn_subtitles=False,
+ )
+
+
async def _ensure_not_cancelled(project_id: int) -> None:
if is_cancelled(project_id):
raise PipelineCancelled(f"project {project_id} cancelled")
@@ -752,25 +792,25 @@ async def _script_stage(project_id: int) -> None:
duration_max=d_max,
max_shot_duration=d_max,
pipeline_mode=mode,
- # 用户角色限制在 diverse/style 下也必须进分镜,否则出镜人物会被模板默认成「过肩无脸」
+ # 仅用户显式覆盖才当强制人设;模板角色交给 llm_system_addon 与主题由 AI 决定
character_hint=char_hint,
extra_requirements=extra,
consistency_mode=consist,
output_ratio=_project_output_ratio(project),
)
plans = plans_result.shots
- if consist == "character":
- project.character_bible = _effective_character_bible(project, plans_result.character_bible)
- elif char_hint:
- # 多样人物:保留用户角色限制,不锁成同一张脸
- project.character_bible = char_hint
- else:
- project.character_bible = "无固定人物,各镜独立场景"
+ project.character_bible = resolve_script_character_bible(
+ char_hint,
+ plans_result.character_bible,
+ )
tpl_bgm = ""
if tpl and isinstance(tpl.audio_config, dict):
tpl_bgm = str(tpl.audio_config.get("bgm_mood") or "").strip()
+ # 风格页用户选曲优先,其次 LLM / 模板推断
+ user_bgm = (getattr(project, "bgm_lock", None) or "").strip()
project.bgm_lock = (
- (plans_result.bgm_lock or "").strip()
+ user_bgm
+ or (plans_result.bgm_lock or "").strip()
or tpl_bgm
or (plans[0].bgm if plans else "")
or "轻快专业"
@@ -808,7 +848,7 @@ async def _script_stage(project_id: int) -> None:
video_prompt=segment_script or plan.video_prompt,
segment_script=segment_script,
camera=plan.camera,
- bgm_mood=project.bgm_lock or plan.bgm,
+ bgm_mood=clip_shot_bgm(project.bgm_lock or plan.bgm),
status=ShotStatus.PENDING,
)
)
@@ -843,8 +883,16 @@ def _template_seedream_field(project: Project, key: str) -> str:
def _effective_character_prompt(project: Project) -> str:
- user = (getattr(project, "character_prompt", None) or "").strip()
- return user or _template_seedream_field(project, "character_prompt")
+ """仅用户在项目里写的角色覆盖;模板角色不当作用户强制约束。"""
+ return (getattr(project, "character_prompt", None) or "").strip()
+
+
+def resolve_script_character_bible(user_character_prompt: str, llm_bible: str = "") -> str:
+ """用户覆盖优先,否则用分镜 LLM 的 character_bible。"""
+ user = (user_character_prompt or "").strip()
+ if user:
+ return user
+ return (llm_bible or "").strip() or "无固定人物,各镜独立场景"
def _effective_extra(project: Project) -> str:
@@ -852,11 +900,6 @@ def _effective_extra(project: Project) -> str:
return user or _template_seedream_field(project, "extra_prompt")
-def _effective_character_bible(project: Project, llm_bible: str = "") -> str:
- user = _effective_character_prompt(project)
- return user or (llm_bible or "").strip()
-
-
def _image_size_for(project: Project) -> str | None:
ratio = _project_output_ratio(project)
return _IMAGE_SIZE_BY_RATIO.get(ratio)
@@ -891,18 +934,6 @@ def _locked_shot_prompt(project: Project, img_prompt: str) -> str:
)
-def _consistency_ref_from_shots(shots: list) -> str | None:
- """Prefer first finished shot's Ark CDN URL, else local static."""
- ordered = sorted(shots, key=lambda s: s.shot_no)
- for s in ordered:
- if s.image_ark_url and str(s.image_ark_url).startswith("http"):
- return s.image_ark_url
- for s in ordered:
- if s.image_url:
- return s.image_url
- return None
-
-
_db_write_locks: dict[int, asyncio.Lock] = {}
@@ -918,7 +949,7 @@ def _db_write_lock() -> asyncio.Lock:
async def _parallel_image_and_audio(project_id: int) -> None:
- """Generate storyboard images and continuous TTS (full 再并行图生视频)。"""
+ """逐镜出图(后镜参考上一镜静帧),同时整片连贯配音。"""
await _set_status(project_id, ProjectStatus.IMAGING, 18, "PARALLEL_ASSETS")
cfg = get_settings()
ark = get_ark()
@@ -942,6 +973,8 @@ async def _parallel_image_and_audio(project_id: int) -> None:
"img_prompt": s.img_prompt,
"narration": s.narration,
"duration": float(s.duration),
+ "image_url": s.image_url,
+ "image_ark_url": s.image_ark_url,
"has_image": bool(s.image_url or s.image_ark_url),
"has_audio": bool(
s.audio_url
@@ -958,8 +991,6 @@ async def _parallel_image_and_audio(project_id: int) -> None:
consist = template_consistency_mode(tpl)
lock_character = consist == "character"
base_refs = _project_base_refs(project)
- # Only character mode chains shot-to-shot refs; diverse/style keep scenes independent
- existing_anchor = _consistency_ref_from_shots(shot_rows) if lock_character else None
image_size = _image_size_for(project)
negative = _project_image_negative(project)
voice = _project_voice(project)
@@ -1026,8 +1057,8 @@ async def _parallel_image_and_audio(project_id: int) -> None:
await db.commit()
await bump_images()
- async def one_image(meta: dict, ref_urls: list[str]) -> str | None:
- """Generate one shot; return remote/local URL for consistency chaining."""
+ async def one_image(meta: dict, ref_urls: list[str]) -> SimpleNamespace | None:
+ """生成一镜;返回静帧代理供下一镜参考。"""
await _ensure_not_cancelled(project_id)
if meta.get("has_image"):
await bump_images()
@@ -1060,47 +1091,23 @@ async def _parallel_image_and_audio(project_id: int) -> None:
shot_id=meta["id"],
)
await persist_image(meta, img)
- return img.remote_url or img.local_url
+ return SimpleNamespace(image_ark_url=img.remote_url, image_url=img.local_url)
async def run_images() -> None:
- """Character mode: anchor first shot then parallelize. Diverse/style: all independent."""
- need = [m for m in shot_meta if not m.get("has_image")]
- already = [m for m in shot_meta if m.get("has_image")]
- for _m in already:
- await bump_images()
-
- if not need:
- return
-
- if not lock_character:
- # Content-driven: each shot uses only template base refs (if any)
- results = await asyncio.gather(
- *(one_image(m, list(base_refs)) for m in need),
- return_exceptions=True,
- )
- for r in results:
- if isinstance(r, Exception):
- raise r
- return
-
- anchor = existing_anchor
- first, rest = need[0], need[1:]
- first_refs = seedream_ref_urls(anchor, *base_refs) if anchor else list(base_refs)
- first_url = await one_image(first, first_refs)
- if first_url:
- anchor = first_url
-
- if not rest:
- return
- rest_refs = seedream_ref_urls(anchor, *base_refs) if anchor else list(base_refs)
-
- results = await asyncio.gather(
- *(one_image(m, rest_refs) for m in rest),
- return_exceptions=True,
- )
- for r in results:
- if isinstance(r, Exception):
- raise r
+ """逐镜出图:后镜 Seedream 参考上一镜静帧。"""
+ prev_proxy = None
+ for meta in shot_meta:
+ if meta.get("has_image"):
+ prev_proxy = SimpleNamespace(
+ image_ark_url=meta.get("image_ark_url"),
+ image_url=meta.get("image_url"),
+ )
+ await bump_images()
+ continue
+ refs = image_refs_for_shot(prev_proxy, base_refs)
+ proxy = await one_image(meta, refs)
+ if proxy:
+ prev_proxy = proxy
async def run_continuous_audio() -> None:
await _ensure_not_cancelled(project_id)
@@ -1177,7 +1184,7 @@ async def _parallel_image_and_audio(project_id: int) -> None:
async def _parallel_videos(project_id: int) -> None:
- """Run Seedance i2v for all shots concurrently (after images exist)."""
+ """按镜序逐个出视频;后镜参考上一镜尾帧。"""
await _set_status(project_id, ProjectStatus.VIDEOING, 55, "VIDEOING")
cfg = get_settings()
ark = get_ark()
@@ -1210,6 +1217,10 @@ async def _parallel_videos(project_id: int) -> None:
"segment_script": getattr(s, "segment_script", "") or s.video_prompt or "",
"camera": s.camera,
"image_ref": s.image_ark_url or s.image_url or "",
+ "image_ark_url": s.image_ark_url,
+ "image_url": s.image_url,
+ "last_frame_url": getattr(s, "last_frame_url", None),
+ "video_url": s.video_url,
"has_video": bool(s.video_url),
}
for s in sorted(project.shots, key=lambda s: s.shot_no)
@@ -1221,17 +1232,31 @@ async def _parallel_videos(project_id: int) -> None:
if not shot_meta:
return
- sem = asyncio.Semaphore(max(1, cfg.pipeline_video_concurrency))
done = 0
- progress_lock = asyncio.Lock()
- async def one_video(meta: dict) -> None:
+ async def one_video(meta: dict, extra_refs: list[str]) -> SimpleNamespace:
nonlocal done
await _ensure_not_cancelled(project_id)
+ proxy = SimpleNamespace(
+ image_ark_url=meta.get("image_ark_url"),
+ image_url=meta.get("image_url"),
+ last_frame_url=meta.get("last_frame_url"),
+ )
if meta.get("has_video"):
- async with progress_lock:
- done += 1
- pct = 55 + int(30 * done / max(total, 1))
+ done += 1
+ pct = 55 + int(30 * done / max(total, 1))
+ if not proxy.last_frame_url and meta.get("video_url"):
+ last = persist_last_frame_from_video(
+ project_id, int(meta["shot_no"]), str(meta["video_url"])
+ )
+ if last:
+ proxy.last_frame_url = last
+ async with _db_write_lock():
+ async with AsyncSessionLocal() as db:
+ shot = await db.get(Shot, meta["id"])
+ if shot:
+ shot.last_frame_url = last
+ await db.commit()
await publish_progress(
project_id,
{
@@ -1242,72 +1267,78 @@ async def _parallel_videos(project_id: int) -> None:
"message": f"沿用已有视频 {done}/{total}",
},
)
- return
- async with sem:
- await _ensure_not_cancelled(project_id)
- script = (meta.get("segment_script") or meta.get("video_prompt") or "").strip()
- prompt = segplan.build_seedance_prompt(
- script,
- style_prefix=style_prefix,
- motion_bias=motion,
- camera=str(meta.get("camera") or ""),
- ambient_only=ambient_only,
- )
- dur = segplan.resolve_api_duration(
- script,
- fallback=meta["duration"],
- lo=cfg.seedance_duration_min,
- hi=cfg.seedance_duration_max,
+ return proxy
+ await _ensure_not_cancelled(project_id)
+ script = (meta.get("segment_script") or meta.get("video_prompt") or "").strip()
+ prompt = _kepu_video_prompt(
+ script,
+ style_prefix=style_prefix,
+ motion_bias=motion,
+ camera=str(meta.get("camera") or ""),
+ ambient_only=ambient_only,
+ )
+ dur = segplan.resolve_api_duration(
+ script,
+ fallback=meta["duration"],
+ lo=cfg.seedance_duration_min,
+ hi=cfg.seedance_duration_max,
+ )
+ try:
+ local_video, task_result = await ark.gen_and_wait_video(
+ meta["image_ref"],
+ prompt,
+ int(dur),
+ project_id=project_id,
+ shot_no=meta["shot_no"],
+ character_consistency=consistency,
+ resolution=resolution,
+ ratio=ratio,
+ generate_audio=generate_audio,
+ model=video_model,
+ extra_image_urls=extra_refs or None,
)
- try:
- local_video, task_result = await ark.gen_and_wait_video(
- meta["image_ref"],
- prompt,
- int(dur),
- project_id=project_id,
- shot_no=meta["shot_no"],
- character_consistency=consistency,
- resolution=resolution,
- ratio=ratio,
- generate_audio=generate_audio,
- model=video_model,
+ except Exception as exc: # noqa: BLE001
+ msg = str(exc)
+ # Real-person privacy blocks — skip AI video; compose will use still image
+ if any(
+ k in msg
+ for k in (
+ "PrivacyInformation",
+ "InputImageSensitive",
+ "SensitiveContentDetected",
)
- except Exception as exc: # noqa: BLE001
- msg = str(exc)
- # Real-person privacy blocks — skip AI video; compose will use still image
- if any(
- k in msg
- for k in (
- "PrivacyInformation",
- "InputImageSensitive",
- "SensitiveContentDetected",
- )
- ):
- logger.warning(
- "Seedance privacy skip project=%s shot=%s: %s",
- project_id,
- meta["shot_no"],
- msg[:240],
- )
- async with progress_lock:
- done += 1
- pct = 55 + int(30 * done / max(total, 1))
- await publish_progress(
- project_id,
- {
- "event": "progress",
- "stage": "VIDEOING",
- "shot": meta["shot_no"],
- "total": total,
- "percent": pct,
- "message": (
- f"镜头 {meta['shot_no']} 含真人已跳过 AI 视频"
- + ("(成片将缺该镜)" if generate_audio else ",将用静图合成")
- ),
- },
- )
- return
- raise
+ ):
+ logger.warning(
+ "Seedance privacy skip project=%s shot=%s: %s",
+ project_id,
+ meta["shot_no"],
+ msg[:240],
+ )
+ done += 1
+ pct = 55 + int(30 * done / max(total, 1))
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "VIDEOING",
+ "shot": meta["shot_no"],
+ "total": total,
+ "percent": pct,
+ "message": (
+ f"镜头 {meta['shot_no']} 含真人已跳过 AI 视频"
+ + ("(成片将缺该镜)" if generate_audio else ",将用静图合成")
+ ),
+ },
+ )
+ return proxy
+ raise
+ last = persist_last_frame_from_video(
+ project_id,
+ int(meta["shot_no"]),
+ local_video,
+ preferred_url=getattr(task_result, "last_frame_url", None),
+ )
+ proxy.last_frame_url = last
s = get_settings()
dur = max(float(dur), 2.0)
billing_key = "seedance2:video0" if generate_audio else "seedance2:video1"
@@ -1323,43 +1354,45 @@ async def _parallel_videos(project_id: int) -> None:
async with AsyncSessionLocal() as db:
shot = await db.get(Shot, meta["id"])
if not shot:
- return
+ return proxy
shot.video_url = local_video
+ shot.last_frame_url = last
shot.status = ShotStatus.VIDEO_READY
await db.commit()
- async with progress_lock:
- done += 1
- pct = 55 + int(30 * done / max(total, 1))
- async with _db_write_lock():
- async with AsyncSessionLocal() as db:
- project = await db.get(Project, project_id)
- if project:
- project.progress = pct
- project.status = ProjectStatus.VIDEOING
- await db.commit()
- await publish_progress(
- project_id,
- {
- "event": "progress",
- "stage": "VIDEOING",
- "shot": meta["shot_no"],
- "total": total,
- "percent": pct,
- "message": (
+ done += 1
+ pct = 55 + int(30 * done / max(total, 1))
+ async with _db_write_lock():
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if project:
+ project.progress = pct
+ project.status = ProjectStatus.VIDEOING
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "VIDEOING",
+ "shot": meta["shot_no"],
+ "total": total,
+ "percent": pct,
+ "message": (
+ f"逐镜 AI 视频 {done}/{total}(参考上一镜)"
+ if extra_refs
+ else (
f"AI 视频(含操作音效){done}/{total}"
if generate_audio
else f"AI 视频 {done}/{total}"
- ),
- },
- )
+ )
+ ),
+ },
+ )
+ return proxy
- results = await asyncio.gather(*(one_video(m) for m in shot_meta), return_exceptions=True)
- errors = [r for r in results if isinstance(r, Exception)]
- if errors:
- for err in errors:
- if isinstance(err, (PipelineCancelled, asyncio.CancelledError)):
- raise err
- raise RuntimeError(str(errors[0]))
+ prev_proxy: SimpleNamespace | None = None
+ for meta in shot_meta:
+ extra = video_extra_refs_for_shot(prev_proxy)
+ prev_proxy = await one_video(meta, extra)
async with _db_write_lock():
async with AsyncSessionLocal() as db:
@@ -1375,6 +1408,7 @@ async def _parallel_videos(project_id: int) -> None:
async def _image_stage(project_id: int) -> None:
+ """逐镜出图;后镜 Seedream 参考上一镜静帧。"""
await _set_status(project_id, ProjectStatus.IMAGING, 20, "IMAGING")
ark = get_ark()
async with AsyncSessionLocal() as db:
@@ -1394,20 +1428,16 @@ async def _image_stage(project_id: int) -> None:
photoreal = template_is_photoreal(tpl)
consist = template_consistency_mode(tpl)
lock_character = consist == "character"
- anchor: str | None = None
+ prev_shot = None
image_model = (getattr(project, "image_model", None) or "").strip()
output_ratio = _project_output_ratio(project) or ""
for idx, shot in enumerate(sorted(project.shots, key=lambda s: s.shot_no)):
await _ensure_not_cancelled(project_id)
if shot.image_url or shot.image_ark_url:
- if lock_character and not anchor:
- anchor = shot.image_ark_url or shot.image_url
+ prev_shot = shot
continue
- if lock_character:
- refs = seedream_ref_urls(anchor, *ref_urls) if anchor else list(ref_urls)
- else:
- refs = list(ref_urls)
+ refs = image_refs_for_shot(prev_shot, ref_urls)
prompt = build_locked_image_prompt(
style_prefix,
strip_lock_blocks(shot.img_prompt),
@@ -1429,8 +1459,7 @@ async def _image_stage(project_id: int) -> None:
shot.image_url = img.local_url
shot.image_ark_url = img.remote_url
shot.status = ShotStatus.IMAGE_READY
- if lock_character and not anchor:
- anchor = img.remote_url or img.local_url
+ prev_shot = shot
span = 55 if _is_image_text(project) else 25
pct = 20 + int(span * (idx + 1) / max(total, 1))
project.progress = pct
@@ -1453,6 +1482,7 @@ async def _image_stage(project_id: int) -> None:
async def _video_stage(project_id: int) -> None:
+ """逐镜出视频;后镜参考上一镜尾帧(无尾帧则用静帧)。"""
await _set_status(project_id, ProjectStatus.VIDEOING, 50, "VIDEOING")
ark = get_ark()
async with AsyncSessionLocal() as db:
@@ -1479,8 +1509,15 @@ async def _video_stage(project_id: int) -> None:
video_model = (getattr(project, "video_model", None) or "").strip()
for idx, shot in enumerate(sorted(project.shots, key=lambda s: s.shot_no)):
await _ensure_not_cancelled(project_id)
+ if shot.video_url:
+ if not shot.last_frame_url:
+ shot.last_frame_url = persist_last_frame_from_video(
+ project_id, int(shot.shot_no), str(shot.video_url)
+ )
+ await db.commit()
+ continue
script = (getattr(shot, "segment_script", "") or shot.video_prompt or "").strip()
- prompt = segplan.build_seedance_prompt(
+ prompt = _kepu_video_prompt(
script,
style_prefix=style_prefix,
motion_bias=motion,
@@ -1494,6 +1531,7 @@ async def _video_stage(project_id: int) -> None:
hi=cfg.seedance_duration_max,
)
image_ref = shot.image_ark_url or shot.image_url or ""
+ extra_refs = video_extra_refs_for_shot(previous_usable_shot(list(project.shots), shot.shot_no))
local_video, task_result = await ark.gen_and_wait_video(
image_ref,
prompt,
@@ -1505,8 +1543,15 @@ async def _video_stage(project_id: int) -> None:
ratio=ratio,
generate_audio=generate_audio,
model=video_model,
+ extra_image_urls=extra_refs or None,
)
shot.video_url = local_video
+ shot.last_frame_url = persist_last_frame_from_video(
+ project_id,
+ int(shot.shot_no),
+ local_video,
+ preferred_url=getattr(task_result, "last_frame_url", None),
+ )
shot.status = ShotStatus.VIDEO_READY
billing_key = "seedance2:video0" if generate_audio else "seedance2:video1"
await _record_seedance_usage(
@@ -1644,7 +1689,10 @@ async def _compose_stage(project_id: int) -> None:
if not full_audio.exists():
full_audio = None
- sub_cfg = (project.template.subtitle_config if project.template else None) or {}
+ sub_cfg = _merge_subtitle_preset(
+ (project.template.subtitle_config if project.template else None) or {},
+ getattr(project, "subtitle_preset", "") or "",
+ )
layout = str(sub_cfg.get("position") or "top")
if layout not in {"top", "split", "bottom", "center"}:
layout = "top"
@@ -1662,8 +1710,7 @@ async def _compose_stage(project_id: int) -> None:
bgm_mood = (project.shots[0].bgm_mood or "").strip()
if not bgm_mood and project.template and isinstance(project.template.audio_config, dict):
bgm_mood = str(project.template.audio_config.get("bgm_mood") or "").strip()
- # 科普 full:不要后期 BGM;静图成片仍可叠配乐
- bgm_path = None if mode != "image_text" else resolve_bgm_path(bgm_mood)
+ bgm_path = resolve_bgm_path(bgm_mood)
keep_video_sfx = _kepu_seedance_sfx_audio(project)
await _run_ffmpeg_compose_with_retry(
@@ -1765,28 +1812,33 @@ async def regen_shot_image(project_id: int, shot_id: int) -> None:
shot = next((s for s in project.shots if s.id == shot_id), None)
if not shot:
raise ValueError("shot not found")
- base_refs = _project_base_refs(project)
- lock_character = template_consistency_mode(project.template) == "character"
- if lock_character:
- anchor = _consistency_ref_from_shots([s for s in project.shots if s.id != shot.id])
- ref_urls = seedream_ref_urls(anchor, *base_refs) if anchor else list(base_refs)
- else:
- ref_urls = list(base_refs)
+ # 生成前先备好参考,避免长等待占着同一条 DB 连接
+ shot_no = shot.shot_no
+ ref_urls = image_refs_for_shot(previous_usable_shot(list(project.shots), shot_no), _project_base_refs(project))
negative = _project_image_negative(project)
prompt = _locked_shot_prompt(project, shot.img_prompt)
- img = await ark.gen_image(
- prompt,
- negative,
- ref_urls,
- project_id=project_id,
- shot_no=shot.shot_no,
- size=_image_size_for(project),
- model=(getattr(project, "image_model", None) or "").strip(),
- aspect_ratio=_project_output_ratio(project) or None,
- )
+ image_size = _image_size_for(project)
+ image_model = (getattr(project, "image_model", None) or "").strip()
+ aspect_ratio = _project_output_ratio(project) or None
+ img = await ark.gen_image(
+ prompt,
+ negative,
+ ref_urls,
+ project_id=project_id,
+ shot_no=shot_no,
+ size=image_size,
+ model=image_model,
+ aspect_ratio=aspect_ratio,
+ )
+ async with AsyncSessionLocal() as db:
+ shot = await db.get(Shot, shot_id)
+ project = await db.get(Project, project_id)
+ if not shot or not project:
+ raise ValueError("shot not found")
shot.image_url = img.local_url
shot.image_ark_url = img.remote_url
shot.video_url = None
+ shot.last_frame_url = None
shot.status = ShotStatus.IMAGE_READY
shot.version += 1
project.status = ProjectStatus.IMAGE_READY
@@ -1803,7 +1855,9 @@ async def regen_shot_image(project_id: int, shot_id: int) -> None:
@storage.without_intermediate_oss
async def regen_shot_video(project_id: int, shot_id: int) -> None:
+ """重绘单镜视频;后镜参考上一镜尾帧。"""
ark = get_ark()
+ cfg = get_settings()
async with AsyncSessionLocal() as db:
result = await db.execute(
select(Project)
@@ -1821,12 +1875,11 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
consistency = template_consistency_mode(project.template) == "character" and bool(
project.template.seedance_config.get("character_consistency", True)
)
- cfg = get_settings()
resolution = cfg.ark_video_resolution
if project.resolution_mode == "hd" and resolution == "480p":
resolution = "720p"
script = (getattr(shot, "segment_script", "") or shot.video_prompt or "").strip()
- prompt = segplan.build_seedance_prompt(
+ prompt = _kepu_video_prompt(
script,
style_prefix=_effective_style(project),
motion_bias=motion,
@@ -1839,34 +1892,51 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
lo=cfg.seedance_duration_min,
hi=cfg.seedance_duration_max,
)
+ shot_no = shot.shot_no
image_ref = shot.image_ark_url or shot.image_url or ""
- local_video, task_result = await ark.gen_and_wait_video(
- image_ref,
- prompt,
- int(dur),
- project_id=project_id,
- shot_no=shot.shot_no,
- character_consistency=consistency,
- resolution=resolution,
- ratio=_project_output_ratio(project) or cfg.ark_video_ratio,
- generate_audio=generate_audio,
- model=(getattr(project, "video_model", None) or "").strip(),
- )
+ extra_refs = video_extra_refs_for_shot(previous_usable_shot(list(project.shots), shot_no))
+ video_model = (getattr(project, "video_model", None) or "").strip()
+ ratio = _project_output_ratio(project) or cfg.ark_video_ratio
+ local_video, task_result = await ark.gen_and_wait_video(
+ image_ref,
+ prompt,
+ int(dur),
+ project_id=project_id,
+ shot_no=shot_no,
+ character_consistency=consistency,
+ resolution=resolution,
+ ratio=ratio,
+ generate_audio=generate_audio,
+ model=video_model,
+ extra_image_urls=extra_refs or None,
+ )
+ last = persist_last_frame_from_video(
+ project_id,
+ int(shot_no),
+ local_video,
+ preferred_url=getattr(task_result, "last_frame_url", None),
+ )
+ async with AsyncSessionLocal() as db:
+ shot = await db.get(Shot, shot_id)
+ project = await db.get(Project, project_id)
+ if not shot or not project:
+ raise ValueError("shot not found")
shot.video_url = local_video
+ shot.last_frame_url = last
shot.status = ShotStatus.VIDEO_READY
shot.version += 1
project.final_video_url = None
project.status = ProjectStatus.VIDEO_READY
- billing_key = "seedance2:video0" if generate_audio else "seedance2:video1"
- await _record_seedance_usage(
- project_id,
- billing_key=billing_key,
- model=cfg.model_video,
- task_result=task_result,
- fallback_duration_sec=max(float(dur), 2.0),
- shot_id=shot_id,
- )
await db.commit()
+ billing_key = "seedance2:video0" if generate_audio else "seedance2:video1"
+ await _record_seedance_usage(
+ project_id,
+ billing_key=billing_key,
+ model=cfg.model_video,
+ task_result=task_result,
+ fallback_duration_sec=max(float(dur), 2.0),
+ shot_id=shot_id,
+ )
@storage.without_intermediate_oss
diff --git a/backend/app/services/seedance_segments.py b/backend/app/services/seedance_segments.py
index 21cc66d..8bed124 100644
--- a/backend/app/services/seedance_segments.py
+++ b/backend/app/services/seedance_segments.py
@@ -24,9 +24,12 @@ LEGACY_NARRATION_PREFIX = "【旁白·慢速清晰·同步字幕】"
DIALOGUE_PREFIX = "【对白·慢速清晰·同步字幕】"
VISUAL_PREFIX = "【画面·无配音仅环境音】"
EMPTY_SHOT_PREFIX = "【空镜·可仅环境音与 BGM】"
-SUBTITLE_CUE = "【字幕:全程简体中文字幕,旁白逐句同步烧录】"
+SUBTITLE_CUE = "【字幕:后期叠旁白字幕,简体中文逐句同步】"
DRAMA_SUBTITLE_CUE = "【字幕:底部居中·简体中文·逐句轮换·与口播同步】"
# 历史 cue,提交前统一替换为现行文案
+LEGACY_KEPU_SUBTITLE_CUES = (
+ "【字幕:全程简体中文字幕,旁白逐句同步烧录】",
+)
LEGACY_DRAMA_SUBTITLE_CUES = (
"【字幕:底部居中·简体中文·仅标记段落同步】",
"【字幕:底部居中·简体中文】",
@@ -79,6 +82,15 @@ def is_visual_description_body(text: str) -> bool:
return False
+def normalize_kepu_subtitle_cue(content: str) -> str:
+ """将科普历史字幕 cue 统一为「后期叠旁白字幕」。"""
+ text = content or ""
+ for old in LEGACY_KEPU_SUBTITLE_CUES:
+ if old in text:
+ text = text.replace(old, SUBTITLE_CUE)
+ return text
+
+
def normalize_drama_subtitle_cue(content: str) -> str:
"""将历史字幕 cue 统一为现行「逐句轮换」文案。"""
text = content or ""
@@ -258,7 +270,7 @@ def build_production_cues(bgm_mood: str) -> list[str]:
mood = (bgm_mood or "").strip() or DEFAULT_BGM_MOOD
if "音量低于人声" not in mood:
mood = f"{mood},音量低于人声"
- return [SUBTITLE_CUE, f"【BGM:{mood}】"]
+ return [SUBTITLE_CUE, f"【BGM:后期混音 · {mood}】"]
# 后期字幕模式:提交前去掉烧录 cue /「同步字幕」前缀,避免模型仍按字烧屏。
@@ -752,23 +764,20 @@ def resolve_api_duration(
def apply_segment_script_edit(script: str, *, bgm_mood: str | None = None) -> dict[str, Any]:
"""Normalize an edited script: ensure cues, recompute duration/narration/img."""
- content = (script or "").strip()
+ content = normalize_kepu_subtitle_cue((script or "").strip())
if not content:
content = build_segment_script(
[SegmentBeat(duration=4, kind="visual", text="画面轻微动态,保持主体稳定")],
bgm_mood=bgm_mood or DEFAULT_BGM_MOOD,
)
else:
- has_sub = any(line.strip().startswith("【字幕") for line in content.splitlines())
- has_bgm = any(line.strip().startswith("【BGM") for line in content.splitlines())
- if not has_sub or not has_bgm:
- cues = build_production_cues(bgm_mood or infer_bgm_mood(content))
- body_lines = [
- ln
- for ln in content.splitlines()
- if not ln.strip().startswith("【字幕") and not ln.strip().startswith("【BGM")
- ]
- content = "\n".join(cues + body_lines).strip()
+ cues = build_production_cues(bgm_mood or infer_bgm_mood(content))
+ body_lines = [
+ ln
+ for ln in content.splitlines()
+ if not ln.strip().startswith("【字幕") and not ln.strip().startswith("【BGM")
+ ]
+ content = "\n".join(cues + body_lines).strip()
if not extract_durations(content):
body = "\n".join(
ln
diff --git a/backend/app/services/style_lock.py b/backend/app/services/style_lock.py
index bf7cca1..51beecb 100644
--- a/backend/app/services/style_lock.py
+++ b/backend/app/services/style_lock.py
@@ -180,11 +180,12 @@ def template_prompt_defaults(tpl) -> dict[str, str]:
}
-def seedream_ref_urls(*candidates: str | None) -> list[str]:
+def seedream_ref_urls(*candidates: str | None, limit: int = 2) -> list[str]:
"""Normalize refs for Seedream — **public https only**.
Skip data: URIs (multi‑MB base64 often hangs Seedream) and LAN/localhost URLs
(Ark cloud cannot fetch them). Prefer prior shot `image_ark_url` CDN links.
+ limit 默认 2(科普锚点镜);漫剧主体+画风板走 split_seedream_subject_style_refs。
"""
out: list[str] = []
seen: set[str] = set()
@@ -205,4 +206,19 @@ def seedream_ref_urls(*candidates: str | None) -> list[str]:
continue
out.append(u)
seen.add(u)
- return out[:2]
+ cap = max(0, int(limit))
+ return out[:cap]
+
+
+def split_seedream_subject_style_refs(
+ subject_urls: list[str] | None,
+ style_urls: list[str] | None,
+ *,
+ max_total: int = 6,
+) -> tuple[list[str], list[str]]:
+ """主体参考优先,但为画风板预留 1 个名额。"""
+ cap = max(1, int(max_total))
+ style_refs = seedream_ref_urls(*(style_urls or []), limit=1)
+ budget = cap - len(style_refs)
+ subject_refs = seedream_ref_urls(*(subject_urls or []), limit=budget)
+ return subject_refs, style_refs
diff --git a/backend/app/services/tasks/service.py b/backend/app/services/tasks/service.py
index 4c3b836..436ae1a 100644
--- a/backend/app/services/tasks/service.py
+++ b/backend/app/services/tasks/service.py
@@ -423,7 +423,78 @@ async def reconcile_stale_pending_tasks(db: AsyncSession) -> int:
return changed
+# 连续点各镜「生成」会各建一个 sequential batch,且 batch_index 都是 0。
+# 这种分镜视频不能按 batch 首镜激活,必须按分集镜序走 rebalance。
+def sequential_fragment_video_needs_episode_rebalance(
+ task_type: str | None,
+ payload: dict | None,
+) -> bool:
+ if str(task_type or "") != "fragment_video":
+ return False
+ data = payload if isinstance(payload, dict) else {}
+ return bool(data.get("sequential"))
+
+
+# 开启衔接时,每集只允许镜序最前的未完成任务占槽(在跑优先于排队)。
+def pick_sequential_episode_head(
+ ep_tasks: list[TaskRun],
+ sort_by_frag: dict[int, int],
+) -> TaskRun | None:
+ ordered = sorted(
+ [task for task in ep_tasks if task.fragment_id is not None],
+ key=lambda task: (
+ sort_by_frag.get(int(task.fragment_id or 0), 10**9),
+ int(getattr(task, "id", 0) or 0),
+ ),
+ )
+ for task in ordered:
+ if task.status in {"leased", "running", "awaiting_poll"}:
+ return task
+ if task.status == "pending":
+ return task
+ return None
+
+
+# 上一镜没有成片或尾帧时,后镜不能当队首(失败任务已离开队列)。
+def sequential_task_blocked_by_previous_fragment(
+ task: TaskRun,
+ episode_frags: list[DramaEpisodeFragment],
+) -> bool:
+ if task.fragment_id is None or not episode_frags:
+ return False
+ ordered = sorted(
+ [frag for frag in episode_frags if frag.id is not None],
+ key=lambda frag: (int(frag.sort_order or 0), int(frag.id or 0)),
+ )
+ idx = next(
+ (i for i, frag in enumerate(ordered) if int(frag.id) == int(task.fragment_id)),
+ None,
+ )
+ if idx is None or idx <= 0:
+ return False
+ prev = ordered[idx - 1]
+ if (prev.video or "").strip():
+ return False
+ from app.services.drama.generation import read_fragment_last_frame_url
+
+ return not bool(read_fragment_last_frame_url(prev))
+
+
+# 从任务列或 payload 取出漫剧项目 id,供衔接重排按项目收口。
+def _sequential_fragment_video_project_id(task: TaskRun, payload: dict) -> int | None:
+ raw = getattr(task, "drama_project_id", None)
+ if raw is None:
+ raw = payload.get("project_id")
+ if raw is None or raw == "":
+ return None
+ try:
+ return int(raw)
+ except (TypeError, ValueError):
+ return None
+
+
# 修复串行 batch 中 next_action_at 为空导致永远排队的任务;并行 batch 按用户并发上限逐步激活。
+# 分镜视频开启尾帧衔接时,不把各点击的 batch_index=0 当成独立首镜。
async def reconcile_sequential_batches(db: AsyncSession) -> int:
from app.config import get_settings
from app.services.drama.access import count_user_inflight_fragment_video_tasks
@@ -442,6 +513,8 @@ async def reconcile_sequential_batches(db: AsyncSession) -> int:
limit = max(1, int(get_settings().drama_user_video_job_limit or 12))
# 同一 tick 内跨 batch 共享用户空位,避免重复超发
user_slots: dict[int, int] = {}
+ # 开启衔接的分镜视频:按项目收集后统一重排,避免连续点击并发开跑
+ frag_video_projects: dict[int, int] = {}
for batch_key in batch_keys:
tasks = list(
(
@@ -488,6 +561,20 @@ async def reconcile_sequential_batches(db: AsyncSession) -> int:
payload = task.payload if isinstance(task.payload, dict) else {}
by_index[int(payload.get("batch_index", -1))] = task
+ uses_episode_rebalance = sequential_fragment_video_needs_episode_rebalance(
+ tasks[0].task_type,
+ sample,
+ )
+ pid = _sequential_fragment_video_project_id(tasks[0], sample)
+ if uses_episode_rebalance and pid:
+ frag_video_projects[pid] = int(tasks[0].requested_by)
+ elif uses_episode_rebalance:
+ logger.warning(
+ "sequential fragment_video missing project_id batch_key=%s task_id=%s",
+ batch_key,
+ tasks[0].id,
+ )
+
failed_indices = [
int((t.payload or {}).get("batch_index", -1))
for t in tasks
@@ -512,6 +599,10 @@ async def reconcile_sequential_batches(db: AsyncSession) -> int:
changed += 1
continue
+ if uses_episode_rebalance:
+ # 无论能否登记项目,都不要把连续点击当成独立首镜点亮
+ continue
+
first = by_index.get(0)
if first and first.status == "pending" and first.next_action_at is None:
user_id = int(first.requested_by)
@@ -531,6 +622,14 @@ async def reconcile_sequential_batches(db: AsyncSession) -> int:
message="串行批次首镜激活",
)
changed += 1
+ for pid, uid in frag_video_projects.items():
+ stats = await rebalance_project_fragment_video_queue(
+ db,
+ pid,
+ sequential=True,
+ user_id=uid,
+ )
+ changed += int(stats.get("activated") or 0) + int(stats.get("deferred") or 0)
if changed:
await db.commit()
return changed
@@ -629,22 +728,34 @@ async def rebalance_project_fragment_video_queue(
ep_id = episode_by_frag.get(int(task.fragment_id)) or int(task.episode_id or 0)
by_episode.setdefault(ep_id, []).append(task)
+ # 补齐同集全部分镜:上一镜失败后任务已不在队列,仍需挡住后镜
+ siblings_by_ep: dict[int, list[DramaEpisodeFragment]] = {}
+ episode_ids = [eid for eid in by_episode.keys() if eid]
+ if episode_ids:
+ sibling_rows = list(
+ (
+ await db.execute(
+ select(DramaEpisodeFragment).where(
+ DramaEpisodeFragment.episode_id.in_(sorted(episode_ids))
+ )
+ )
+ ).scalars().all()
+ )
+ for frag in sibling_rows:
+ siblings_by_ep.setdefault(int(frag.episode_id), []).append(frag)
+ sort_by_frag[int(frag.id)] = int(frag.sort_order or 0)
+
heads_to_activate: list[TaskRun] = []
for ep_id, ep_tasks in by_episode.items():
- ep_tasks.sort(
- key=lambda task: (
- sort_by_frag.get(int(task.fragment_id or 0), 10**9),
- int(task.id),
+ head = pick_sequential_episode_head(ep_tasks, sort_by_frag)
+ if (
+ head is not None
+ and head.status == "pending"
+ and sequential_task_blocked_by_previous_fragment(
+ head, siblings_by_ep.get(ep_id, [])
)
- )
- head: TaskRun | None = None
- for task in ep_tasks:
- if task.status in {"leased", "running", "awaiting_poll"}:
- head = task
- break
- if task.status == "pending":
- head = task
- break
+ ):
+ head = None
for task in ep_tasks:
if task.status != "pending":
continue
diff --git a/backend/app/services/tokenfree_image.py b/backend/app/services/tokenfree_image.py
new file mode 100644
index 0000000..e6695e1
--- /dev/null
+++ b/backend/app/services/tokenfree_image.py
@@ -0,0 +1,202 @@
+"""TokenFree / New API 生图:KIE 渠道走 POST /v1/responses,不是方舟 /images/generations。"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import re
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+from app.services.tokenfree_gateway import TOKENFREE_CHANNEL_ID
+from app.services.tokenfree_video import uses_tokenfree_video
+
+logger = logging.getLogger(__name__)
+
+# 全进程只留一个观察位,避免 New API「Too many active task observations」
+_image_slot: asyncio.Semaphore | None = None
+# 429 后等待秒数(槽位不释放,避免其它镜继续撞限)
+TOKENFREE_IMAGE_RETRY_DELAYS = (3.0, 6.0, 12.0, 20.0)
+
+_IMG_SRC_RE = re.compile(r'<img[^>]+src=["\']([^"\']+)["\']', re.IGNORECASE)
+_URL_RE = re.compile(r"https?://[^\s\"'<>]+", re.IGNORECASE)
+
+
+def uses_tokenfree_image(*, base_url: str = "", channel_id: str = "") -> bool:
+ """与视频相同:TokenFree 主机或 tokenfree 渠道。"""
+ return uses_tokenfree_video(base_url=base_url, channel_id=channel_id)
+
+
+def is_seedream_family(model: str) -> bool:
+ """TokenFree 上 Seedream 走 /responses 会 task_protocol_error。"""
+ mid = (model or "").strip().lower()
+ return "seedream" in mid
+
+
+def tokenfree_working_image_model(model: str) -> str:
+ """Seedream 在 TokenFree KIE 上不可用,改走实测成功的 gpt-image-2-5。"""
+ raw = (model or "").strip()
+ if is_seedream_family(raw):
+ return "gpt-image-2-5"
+ return raw
+
+
+def build_tokenfree_image_body(
+ *,
+ model: str,
+ prompt: str,
+ size: str = "",
+ ref_urls: list[str] | None = None,
+ style_ref_urls: list[str] | None = None,
+) -> dict[str, Any]:
+ """线上成功体只要 model + 自然语言 input,不要 size: 这种协议字段。"""
+ text = (prompt or "").strip() or "画面清晰,主体稳定"
+ size_s = (size or "").strip()
+ if size_s:
+ text = f"{text}。输出清晰度{size_s}"
+ refs = [u.strip() for u in (ref_urls or []) if (u or "").strip()]
+ style_refs = [u.strip() for u in (style_ref_urls or []) if (u or "").strip()]
+ if style_refs:
+ text = f"{text}。画风参考图(只借色调、笔触、光影,禁止抄主体与构图):{' '.join(style_refs)}"
+ if refs:
+ text = f"{text}。构图与主体参考:{' '.join(refs)}"
+ return {"model": tokenfree_working_image_model(model), "input": text}
+
+
+def extract_tokenfree_image_url(data: dict[str, Any]) -> str | None:
+ """从 /v1/responses 或兼容包里抽出图片 URL。"""
+ if not isinstance(data, dict):
+ return None
+ for item in data.get("output") or []:
+ if not isinstance(item, dict):
+ continue
+ for block in item.get("content") or []:
+ if not isinstance(block, dict):
+ continue
+ url = block.get("url")
+ image_url = block.get("image_url")
+ if not url and isinstance(image_url, dict):
+ url = image_url.get("url")
+ if isinstance(url, str) and url.startswith("http"):
+ return url.strip()
+ text = str(block.get("text") or "")
+ found = _IMG_SRC_RE.search(text) or _URL_RE.search(text)
+ if found:
+ return found.group(1).strip()
+ if data.get("data"):
+ first = data["data"][0]
+ if isinstance(first, dict):
+ raw = first.get("url")
+ if isinstance(raw, str) and raw.startswith("http"):
+ return raw.strip()
+ return None
+
+
+def is_tokenfree_rate_limit(*, status_code: int = 0, body: str = "") -> bool:
+ """429,或明确的观察位/限流错误体;2xx 成功体里的 rate_limit 字段不算。"""
+ if int(status_code or 0) == 429:
+ return True
+ text = body or ""
+ if "too many active task observations" in text.lower():
+ return True
+ try:
+ payload = json.loads(text) if text.strip().startswith("{") else None
+ except json.JSONDecodeError:
+ payload = None
+ err = payload.get("error") if isinstance(payload, dict) else None
+ code = ""
+ if isinstance(err, dict):
+ code = str(err.get("code") or "")
+ elif isinstance(payload, dict):
+ code = str(payload.get("code") or "")
+ return code.lower() == "rate_limit_exceeded"
+
+
+def is_tokenfree_protocol_error(*, status_code: int = 0, body: str = "") -> bool:
+ """KIE / New API 任务协议失败(常见于 Seedream 或瞬时 502)。"""
+ text = (body or "").lower()
+ if "task_protocol_error" in text or "task protocol request failed" in text:
+ return True
+ try:
+ payload = json.loads(body) if (body or "").strip().startswith("{") else None
+ except json.JSONDecodeError:
+ payload = None
+ err = payload.get("error") if isinstance(payload, dict) else None
+ code = str((err or {}).get("code") or "") if isinstance(err, dict) else ""
+ return int(status_code or 0) == 502 and code.lower() == "task_protocol_error"
+
+
+def is_tokenfree_no_distributor(*, status_code: int = 0, body: str = "") -> bool:
+ """New API 分组下没有可用 distributor(须 404/502/503 且 model_not_found + 无线路)。"""
+ if int(status_code or 0) not in {404, 502, 503}:
+ return False
+ text = body or ""
+ lowered = text.lower()
+ if "model_not_found" not in lowered:
+ return False
+ return "distributor" in lowered or "无可用" in text
+
+
+def is_tokenfree_retryable_image_error(*, status_code: int = 0, body: str = "") -> bool:
+ """仅限流退避;协议/无线路对同一 Key 会连跪,应立刻换通道或报错。"""
+ return is_tokenfree_rate_limit(status_code=status_code, body=body)
+
+
+def tokenfree_image_channel_dead(*, status_code: int = 0, body: str = "") -> bool:
+ """TokenFree 出图通道当前不可用(协议失败或无 distributor)。"""
+ return is_tokenfree_protocol_error(status_code=status_code, body=body) or is_tokenfree_no_distributor(
+ status_code=status_code, body=body
+ )
+
+
+def tokenfree_image_user_error(*, model: str = "", status_code: int = 0, body: str = "") -> str:
+ """用户可见的 TokenFree 出图失败文案;通道挂了不再误导改模型。"""
+ if is_tokenfree_rate_limit(status_code=status_code, body=body):
+ return "出图通道繁忙,同时进行的任务过多,请稍后再点「生成画面」"
+ if tokenfree_image_channel_dead(status_code=status_code, body=body):
+ # TokenFree 上已会把 Seedream 改走 gpt-image,再提示「请改用」会误导
+ return "出图通道暂时失败,请稍后再点「生成画面」"
+ snippet = (body or "")[:800]
+ return f"出图失败 {status_code}: {snippet}"
+
+
+def tokenfree_image_slot() -> asyncio.Semaphore:
+ """全进程 TokenFree 生图互斥(默认 1 路)。"""
+ global _image_slot
+ if _image_slot is None:
+ from app.config import get_settings
+
+ n = max(1, int(getattr(get_settings(), "tokenfree_image_concurrency", 1) or 1))
+ _image_slot = asyncio.Semaphore(n)
+ return _image_slot
+
+
+async def post_until_not_rate_limited(
+ post: Callable[[], Awaitable[Any]],
+ *,
+ delays: tuple[float, ...] = TOKENFREE_IMAGE_RETRY_DELAYS,
+ sleep: Callable[[float], Awaitable[Any]] = asyncio.sleep,
+) -> Any:
+ """POST 遇观察位限流则退避重试;仍失败则返回最后一次响应。"""
+ last: Any = None
+ for attempt in range(len(delays) + 1):
+ last = await post()
+ status = int(getattr(last, "status_code", 0) or 0)
+ body = str(getattr(last, "text", "") or "")
+ if not is_tokenfree_retryable_image_error(status_code=status, body=body):
+ return last
+ if attempt >= len(delays):
+ break
+ wait = delays[attempt]
+ logger.warning("TokenFree 生图暂不可用,%.0fs 后重试(%s/%s)", wait, attempt + 1, len(delays))
+ await sleep(wait)
+ return last
+
+
+def is_tokenfree_image_url(url: str) -> bool:
+ """TokenFree 任务产物地址,下载建议带 Bearer。"""
+ raw = (url or "").strip().lower()
+ if "tokenfree.com" not in raw:
+ return False
+ return "/tasks/" in raw or "/responses/" in raw or "/artifacts/" in raw
diff --git a/backend/app/services/tokenfree_pricing.py b/backend/app/services/tokenfree_pricing.py
new file mode 100644
index 0000000..d1cd6f5
--- /dev/null
+++ b/backend/app/services/tokenfree_pricing.py
@@ -0,0 +1,409 @@
+"""TokenFree 公开 /api/pricing:推荐模型官方价与预估。"""
+
+from __future__ import annotations
+
+import logging
+import math
+import time
+from dataclasses import dataclass
+from typing import Any
+
+import httpx
+
+from app.config import Settings, get_settings
+from app.services.tokenfree_gateway import TOKENFREE_CONSOLE_URL, tokenfree_site_origin
+from app.services.tokenfree_usage import usd_cny_rate
+
+logger = logging.getLogger(__name__)
+
+# New API:model_ratio=1 → $2 / 百万 tokens
+NEWAPI_USD_PER_1M_AT_RATIO_1 = 2.0
+# 视频价目常见占位倍率,不能当秒价
+PLACEHOLDER_MODEL_RATIO = 37.5
+_CACHE_TTL_SEC = 3600.0
+_FAIL_TTL_SEC = 60.0
+TOKENFREE_PRICING_PATH = "/api/pricing"
+# LLM 预估按输入/输出拆分
+LLM_PROMPT_SHARE = 0.7
+# 费率表视频展示用的对照时长
+VIDEO_RATE_SAMPLE_SECONDS = 5.0
+
+# 火山 480P 5 秒官价折秒价(TokenFree 视频表不可信时预估用)
+VENDOR_VIDEO_YUAN_PER_SEC_480P = {
+ "seedance-2-5": 3.36 / 5.0,
+ "seedance-2-0": 2.31 / 5.0,
+ "seedance-2-0-mini": 2.31 / 5.0,
+}
+
+# 产品里好用、目录有、方便去 TokenFree 核对的短名单
+RECOMMENDED_MODELS: tuple[dict[str, Any], ...] = (
+ {
+ "id": "kimi-k2.6",
+ "capability": "text",
+ "label": "Kimi K2.6",
+ "note": "默认剧本/分镜,中文长上下文",
+ "recommended": True,
+ },
+ {
+ "id": "deepseek-v3.2",
+ "capability": "text",
+ "label": "DeepSeek V3.2",
+ "note": "便宜备选,扩写与闲聊",
+ "recommended": False,
+ },
+ {
+ "id": "qwen3.5-plus",
+ "capability": "text",
+ "label": "Qwen 3.5 Plus",
+ "note": "便宜中文日常对话",
+ "recommended": False,
+ },
+ {
+ "id": "gpt-image-2-5",
+ "capability": "image",
+ "label": "GPT Image 2.5",
+ "note": "TokenFree 实测可通;Seedream 会改走此模型",
+ "recommended": True,
+ },
+ {
+ "id": "seedream-5-0-pro",
+ "capability": "image",
+ "label": "Seedream 5.0 Pro",
+ "note": "便宜,但 TokenFree /responses 可能不通",
+ "recommended": False,
+ },
+ {
+ "id": "nano-banana-2",
+ "capability": "image",
+ "label": "Nano Banana 2",
+ "note": "极便宜闪图,草稿/批量",
+ "recommended": False,
+ },
+ {
+ "id": "seedance-2-5",
+ "capability": "video",
+ "label": "Seedance 2.5",
+ "note": "默认成片,最长约 30 秒",
+ "recommended": True,
+ },
+ {
+ "id": "seedance-2-0-mini",
+ "capability": "video",
+ "label": "Seedance 2.0 Mini",
+ "note": "更快更便宜的备选",
+ "recommended": False,
+ },
+)
+
+_cache: dict[str, "OfficialRate"] | None = None
+_cache_at: float = 0.0
+_cache_failed: bool = False
+
+
+@dataclass(frozen=True)
+class OfficialRate:
+ """一条 TokenFree 官方价。"""
+
+ model: str
+ billing: str
+ usd_per_call: float
+ cny_per_call: float
+ cny_in_per_1m: float
+ cny_out_per_1m: float
+ model_ratio: float
+ placeholder: bool
+ tags: str
+
+
+def tokenfree_pricing_url() -> str:
+ """公开价目接口,无需 Key。"""
+ return f"{tokenfree_site_origin()}{TOKENFREE_PRICING_PATH}"
+
+
+def cached_rates() -> dict[str, OfficialRate]:
+ """内存缓存;未拉过返回空。"""
+ return dict(_cache or {})
+
+
+def set_cached_rates(rates: dict[str, OfficialRate] | None) -> None:
+ """写入缓存;None 表示测试清空,空 dict 表示负缓存。"""
+ global _cache, _cache_at, _cache_failed
+ if rates is None:
+ _cache = None
+ _cache_at = 0.0
+ _cache_failed = False
+ return
+ _cache = dict(rates)
+ _cache_at = time.monotonic()
+ _cache_failed = False
+
+
+def _mark_fetch_failed() -> None:
+ """拉取失败:保留旧表,刷新时间戳,避免预扣每次打外网。"""
+ global _cache, _cache_at, _cache_failed
+ if _cache is None:
+ _cache = {}
+ _cache_at = time.monotonic()
+ _cache_failed = True
+
+
+def parse_pricing_item(item: dict[str, Any], *, usd_cny: float) -> OfficialRate | None:
+ """把 /api/pricing 一行折成人民币。"""
+ name = str(item.get("model_name") or "").strip()
+ if not name:
+ return None
+ try:
+ qt = int(item.get("quota_type") or 0)
+ mr = float(item.get("model_ratio") or 0)
+ cr = float(item.get("completion_ratio") or 0)
+ mp = float(item.get("model_price") or 0)
+ rate = max(0.01, float(usd_cny))
+ except (TypeError, ValueError):
+ return None
+ if qt == 1:
+ return OfficialRate(
+ model=name,
+ billing="per_call",
+ usd_per_call=mp,
+ cny_per_call=round(mp * rate, 4),
+ cny_in_per_1m=0.0,
+ cny_out_per_1m=0.0,
+ model_ratio=0.0,
+ placeholder=False,
+ tags=str(item.get("tags") or ""),
+ )
+ return OfficialRate(
+ model=name,
+ billing="token",
+ usd_per_call=0.0,
+ cny_per_call=0.0,
+ cny_in_per_1m=round(mr * NEWAPI_USD_PER_1M_AT_RATIO_1 * rate, 4),
+ cny_out_per_1m=round(mr * cr * NEWAPI_USD_PER_1M_AT_RATIO_1 * rate, 4),
+ model_ratio=mr,
+ placeholder=abs(mr - PLACEHOLDER_MODEL_RATIO) < 0.01,
+ tags=str(item.get("tags") or ""),
+ )
+
+
+def parse_pricing_payload(payload: dict[str, Any], settings: Settings | None = None) -> dict[str, OfficialRate]:
+ """解析 TokenFree 价目 JSON。"""
+ items = payload.get("data") if isinstance(payload, dict) else None
+ if not isinstance(items, list):
+ return {}
+ rate = usd_cny_rate(settings)
+ out: dict[str, OfficialRate] = {}
+ for raw in items:
+ if not isinstance(raw, dict):
+ continue
+ parsed = parse_pricing_item(raw, usd_cny=rate)
+ if parsed:
+ out[parsed.model] = parsed
+ return out
+
+
+def lookup_rate(model: str, rates: dict[str, OfficialRate] | None = None) -> OfficialRate | None:
+ """按模型 id 精确或忽略大小写查找。"""
+ mid = (model or "").strip()
+ table = rates if rates is not None else cached_rates()
+ if not mid or not table:
+ return None
+ hit = table.get(mid)
+ if hit:
+ return hit
+ key = mid.lower()
+ for name, row in table.items():
+ if name.lower() == key:
+ return row
+ return None
+
+
+def video_catalog_id(model: str) -> str:
+ """计费预估用:已知别名映射,未知 Seedance 回退 2.5。"""
+ mapped = canonicalize_channel_model_id(model)
+ if _is_canonical_seedance(mapped):
+ return mapped
+ return "seedance-2-5"
+
+
+def _is_canonical_seedance(model: str) -> bool:
+ """是否为 TokenFree 目录里的三档 Seedance id。"""
+ return model in {"seedance-2-5", "seedance-2-0", "seedance-2-0-mini"}
+
+
+def canonicalize_channel_model_id(model: str) -> str:
+ """已知 Seedance 别名收到 TokenFree 目录 id;对不上则原样返回。"""
+ mid = (model or "").strip()
+ if "seedance" not in mid.lower():
+ return mid
+ low = mid.lower()
+ if "mini" in low:
+ return "seedance-2-0-mini"
+ if any(token in low for token in ("2-5", "2.5", "260628")):
+ return "seedance-2-5"
+ if any(token in low for token in ("2-0", "2.0", "260128")):
+ return "seedance-2-0"
+ compact = low.replace("_", "-")
+ if compact in {"seedance-2", "seedance2"} or compact.endswith("seedance-2"):
+ return "seedance-2-0"
+ return mid
+
+
+def canonicalize_channel_models(models: list[str] | None) -> list[str]:
+ """合并 Seedance 2.0 三档别名,保持原顺序。"""
+ out: list[str] = []
+ seen: set[str] = set()
+ for raw in models or []:
+ mid = canonicalize_channel_model_id(raw)
+ if not mid or mid in seen:
+ continue
+ seen.add(mid)
+ out.append(mid)
+ return out
+
+
+def _markup_charge(cost_fen: int, settings: Settings) -> int:
+ """用户预扣金额 = 官方成本,不再乘倍率。"""
+ from app.services.billing.pricing import user_charge_fen
+
+ return user_charge_fen(cost_fen, settings)
+
+
+def charge_fen_official_image(settings: Settings, *, model: str = "") -> int:
+ """生图预估:按 TokenFree 按张价;Seedream 按实际工作模型。"""
+ from app.services.billing.pricing import charge_fen_for_tokens
+ from app.services.tokenfree_image import tokenfree_working_image_model
+
+ mid = tokenfree_working_image_model(model or "gpt-image-2-5")
+ rate = lookup_rate(mid)
+ if rate and rate.billing == "per_call" and rate.cny_per_call > 0:
+ return _markup_charge(max(1, int(math.ceil(rate.cny_per_call * 100))), settings)
+ _, charge = charge_fen_for_tokens(settings.billing_est_seedream_tokens, "seedream", settings=settings)
+ return charge
+
+
+def charge_fen_official_llm(tokens: int, settings: Settings, *, model: str = "") -> int:
+ """LLM 预估:官方 in/out,按 70% 输入 / 30% 输出拆。"""
+ from app.services.billing.pricing import charge_fen_for_tokens
+
+ t = max(0, int(tokens))
+ mid = (model or getattr(settings, "model_llm", "") or "kimi-k2.6").strip()
+ rate = lookup_rate(mid)
+ if t and rate and rate.billing == "token" and (rate.cny_in_per_1m or rate.cny_out_per_1m):
+ prompt = int(t * LLM_PROMPT_SHARE)
+ completion = t - prompt
+ yuan = prompt / 1_000_000 * rate.cny_in_per_1m + completion / 1_000_000 * rate.cny_out_per_1m
+ return _markup_charge(max(1, int(math.ceil(yuan * 100))), settings)
+ _, charge = charge_fen_for_tokens(t, "llm_chat", settings=settings)
+ return charge
+
+
+def charge_fen_official_video(seconds: float, settings: Settings, *, model: str = "") -> int:
+ """视频预估:用火山 480P 秒价,不用 TokenFree 占位 37.5。"""
+ from app.services.billing.pricing import charge_fen_for_tokens
+
+ secs = max(float(seconds or 0), 2.0)
+ mid = video_catalog_id(model or getattr(settings, "model_video", "") or "seedance-2-5")
+ vendor = VENDOR_VIDEO_YUAN_PER_SEC_480P.get(mid)
+ if vendor:
+ return _markup_charge(max(1, int(math.ceil(secs * vendor * 100))), settings)
+ tok = int(secs * settings.billing_est_seedance_tokens_per_sec)
+ _, charge = charge_fen_for_tokens(tok, "seedance2:video0", settings=settings)
+ return charge
+
+
+def build_official_rate_rows(
+ rates: dict[str, OfficialRate],
+ settings: Settings | None = None,
+) -> list[dict[str, Any]]:
+ """管理端推荐模型费率表(含用户价)。"""
+ s = settings or get_settings()
+ usd_cny = usd_cny_rate(s)
+ items: list[dict[str, Any]] = []
+ for spec in RECOMMENDED_MODELS:
+ rate = lookup_rate(str(spec["id"]), rates)
+ official_yuan = 0.0
+ basis = "missing"
+ rate_label = "TokenFree 价目未收录,请到控制台核对"
+ if spec["capability"] == "video":
+ vendor = VENDOR_VIDEO_YUAN_PER_SEC_480P.get(str(spec["id"]))
+ if vendor:
+ official_yuan = round(vendor * VIDEO_RATE_SAMPLE_SECONDS, 4)
+ basis = "vendor_sec"
+ listed = ""
+ if rate and rate.placeholder:
+ listed = f";TokenFree 表 model_ratio={rate.model_ratio} 疑似占位"
+ rate_label = (
+ f"预估按火山 480P 约 {vendor:.3f} 元/秒"
+ f"({VIDEO_RATE_SAMPLE_SECONDS:g}秒 ¥{official_yuan:.2f}){listed}"
+ )
+ elif rate and rate.billing == "per_call":
+ official_yuan = rate.cny_per_call
+ basis = "per_call"
+ rate_label = f"TokenFree ${rate.usd_per_call:.4f}/次 ≈ ¥{official_yuan:.4f}"
+ elif rate and rate.billing == "token":
+ official_yuan = rate.cny_out_per_1m
+ basis = "token"
+ rate_label = f"TokenFree 输入 ¥{rate.cny_in_per_1m:.4f} / 输出 ¥{rate.cny_out_per_1m:.4f} 每百万"
+ items.append(
+ {
+ "id": spec["id"],
+ "label": spec["label"],
+ "provider": "tokenfree",
+ "capability": spec["capability"],
+ "recommended": bool(spec["recommended"]),
+ "note": spec["note"],
+ "basis": basis,
+ "rate_label": rate_label,
+ "official_cost_yuan": official_yuan,
+ "user_charge_yuan": official_yuan,
+ "placeholder": bool(rate.placeholder) if rate else False,
+ "markup": 1.0,
+ "usd_cny": usd_cny,
+ "verify_url": TOKENFREE_CONSOLE_URL,
+ }
+ )
+ return items
+
+
+async def fetch_tokenfree_pricing() -> dict[str, Any]:
+ """GET TokenFree 公开价目,无需 API Key。"""
+ url = tokenfree_pricing_url()
+ try:
+ async with httpx.AsyncClient(timeout=8.0) as client:
+ resp = await client.get(url)
+ except httpx.HTTPError as exc:
+ raise RuntimeError(f"TokenFree pricing 网络失败: {exc}") from exc
+ if resp.status_code >= 400:
+ raise RuntimeError(f"TokenFree pricing HTTP {resp.status_code}: {resp.text[:300]}")
+ try:
+ payload = resp.json()
+ except ValueError as exc:
+ raise RuntimeError("TokenFree 价目返回非 JSON") from exc
+ if not isinstance(payload, dict):
+ raise RuntimeError("TokenFree 价目格式异常")
+ return payload
+
+
+async def ensure_official_rates(settings: Settings | None = None) -> dict[str, OfficialRate]:
+ """有缓存且未过期则复用;失败写短 TTL,预扣不因外网挂掉。"""
+ ttl = _FAIL_TTL_SEC if _cache_failed else _CACHE_TTL_SEC
+ if _cache is not None and _cache_at and (time.monotonic() - _cache_at) < ttl:
+ return _cache
+ try:
+ payload = await fetch_tokenfree_pricing()
+ parsed = parse_pricing_payload(payload, settings)
+ if parsed:
+ set_cached_rates(parsed)
+ return parsed
+ _mark_fetch_failed()
+ except (RuntimeError, ValueError, TypeError) as exc:
+ logger.info("tokenfree pricing skipped: %s", exc)
+ _mark_fetch_failed()
+ return cached_rates()
+
+
+async def billing_official_rate_rows(settings: Settings | None = None) -> list[dict[str, Any]]:
+ """拉取(或复用)官方价后生成推荐模型费率表。"""
+ s = settings or get_settings()
+ rates = await ensure_official_rates(s)
+ return build_official_rate_rows(rates, s)
diff --git a/backend/static/drama/image-styles/ghibli-handdrawn-anime.png b/backend/static/drama/image-styles/ghibli-handdrawn-anime.png
new file mode 100644
index 0000000..76b749e
Binary files /dev/null and b/backend/static/drama/image-styles/ghibli-handdrawn-anime.png differ
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 3557734..f6696f2 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -14,6 +14,21 @@ from app.models import User
from app.models_tasks import TaskRun
[email protected](autouse=True)
+def skip_tokenfree_pricing_network(monkeypatch: pytest.MonkeyPatch) -> None:
+ """单测不打 TokenFree 公开价目,避免预估被外网拖慢或改数。"""
+
+ async def _empty(_settings=None):
+ """返回空价目,预估走本地回退。"""
+ return {}
+
+ monkeypatch.setattr("app.services.tokenfree_pricing.ensure_official_rates", _empty)
+ monkeypatch.setattr("app.services.billing.estimates.ensure_official_rates", _empty)
+ from app.services.tokenfree_pricing import set_cached_rates
+
+ set_cached_rates(None)
+
+
@pytest.fixture
def billing_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
"""测试环境强制开启计费,buffer=1 便于断言。"""
diff --git a/backend/tests/test_build_fragments.py b/backend/tests/test_build_fragments.py
index db8f8b6..810dd34 100644
--- a/backend/tests/test_build_fragments.py
+++ b/backend/tests/test_build_fragments.py
@@ -9,10 +9,24 @@ from app.services.drama.build_fragments import (
_resolve_character_intro_text,
build_character_binding,
build_fragments_from_episode_body,
+ is_raw_screenplay_fragment,
plan_fragments_from_scene,
)
+def test_is_raw_screenplay_fragment_detects_scene_heading():
+ assert is_raw_screenplay_fragment("") is True
+ assert is_raw_screenplay_fragment("### 场1-1\n日外 大河\n出场人物:无") is True
+ assert is_raw_screenplay_fragment("###场1-1") is True
+ assert is_raw_screenplay_fragment("出场人物:苏轼\n△ 抬头。") is True
+
+
+def test_is_raw_screenplay_fragment_keeps_cinematic_shots():
+ # 手写分镜常无【字幕:】/@duration:,不能当场记原文
+ shot = "【转入|无|片头直接黑起】\n【BGM|低频太鼓】\n【场景】夜 · 内 · 大牢"
+ assert is_raw_screenplay_fragment(shot) is False
+
+
def test_long_scene_splits_into_multiple_fragments():
# 构造足够多的对白行,使合计时长超过软上限
lines = ["日外 羽山刑场", "出场人物:禹"]
diff --git a/backend/tests/test_confirm_episode.py b/backend/tests/test_confirm_episode.py
index 66e1612..fca7b3b 100644
--- a/backend/tests/test_confirm_episode.py
+++ b/backend/tests/test_confirm_episode.py
@@ -49,3 +49,42 @@ def test_protected_video_fragments_are_not_replaced():
)
episode = SimpleNamespace(fragments=[frag], params={})
assert _episode_should_replace_fragments(episode, "甲" * MIN_EPISODE_CONTENT_CHARS) is False
+
+
+# 手写电影感分镜没有【字幕:】/@duration:,不能当成场记原文整集重切
+def test_protected_cinematic_fragments_are_not_replaced_as_raw():
+ frag = SimpleNamespace(
+ video="https://cdn.example/a.mp4",
+ content="【转入|无|片头直接黑起】\n【BGM|低频太鼓】\n【场景】夜 · 内 · 大牢",
+ params={"user_edited": True},
+ )
+ episode = SimpleNamespace(fragments=[frag], params={})
+ assert _episode_should_replace_fragments(episode, "甲" * MIN_EPISODE_CONTENT_CHARS) is False
+
+
+# 未打 user_edited、也无成片的手写分镜,只要不是场记原文就不要自动重切
+def test_unprotected_cinematic_fragments_are_not_auto_replaced():
+ frags = [
+ SimpleNamespace(
+ video="",
+ content="【转入|无|片头直接黑起】\n【BGM|低频太鼓】",
+ params={},
+ ),
+ SimpleNamespace(
+ video="",
+ content="【场景】夜 · 内 · 御史台大牢\n苏轼环顾。",
+ params={},
+ ),
+ ]
+ episode = SimpleNamespace(fragments=frags, params={})
+ assert _episode_should_replace_fragments(episode, "甲" * MIN_EPISODE_CONTENT_CHARS) is False
+
+
+# 手写分镜旁夹一条空镜,不能 any() 一条原文就整集重切
+def test_mixed_cinematic_and_empty_fragment_is_not_auto_replaced():
+ frags = [
+ SimpleNamespace(video="", content="【场景】夜 · 内 · 大牢", params={}),
+ SimpleNamespace(video="", content="", params={}),
+ ]
+ episode = SimpleNamespace(fragments=frags, params={})
+ assert _episode_should_replace_fragments(episode, "甲" * MIN_EPISODE_CONTENT_CHARS) is False
diff --git a/backend/tests/test_image_styles.py b/backend/tests/test_image_styles.py
new file mode 100644
index 0000000..34d1520
--- /dev/null
+++ b/backend/tests/test_image_styles.py
@@ -0,0 +1,95 @@
+"""内置漫剧画面风格 ID / 文案保持对齐。"""
+
+from app.services.drama.generation_prompt import append_style_prompt, build_generation_prompt
+from app.services.drama.image_styles import (
+ IMAGE_STYLE_IDS,
+ IMAGE_STYLE_LABELS,
+ IMAGE_STYLE_PROMPTS,
+ STYLE_BOARD_PROMPT_HINT,
+ _board_fail_cache,
+ _board_url_cache,
+ append_style_board_url,
+ resolve_image_style_board_url,
+ resolve_image_style_prompt,
+ style_board_local_path,
+)
+from app.services.style_lock import seedream_ref_urls, split_seedream_subject_style_refs
+
+
+def test_image_style_catalog_is_aligned():
+ assert set(IMAGE_STYLE_IDS) == set(IMAGE_STYLE_LABELS)
+ assert set(IMAGE_STYLE_IDS) == set(IMAGE_STYLE_PROMPTS)
+
+
+def test_ghibli_handdrawn_style_resolves():
+ prompt = resolve_image_style_prompt("ghibli-handdrawn-anime")
+ assert "水彩" in prompt
+ assert "赛璐璐" in prompt
+ assert IMAGE_STYLE_LABELS["ghibli-handdrawn-anime"] == "宫崎骏气质手绘"
+
+
+def test_style_board_prefers_backend_raster_and_skips_svg():
+ path = style_board_local_path("palace-intrigue-cold")
+ assert path is not None
+ assert path.suffix.lower() in {".png", ".jpg", ".jpeg", ".webp"}
+ ghibli = style_board_local_path("ghibli-handdrawn-anime")
+ if ghibli is not None:
+ assert ghibli.suffix.lower() != ".svg"
+
+
+def test_style_board_rejects_unknown_and_path_traversal():
+ assert style_board_local_path("../generated/p355") is None
+ assert style_board_local_path("..\\generated") is None
+ assert style_board_local_path("/etc/passwd") is None
+ assert style_board_local_path("palace-intrigue-cold/../../secret") is None
+ assert style_board_local_path("not-a-real-style") is None
+
+
+def test_resolve_image_style_board_url_publishes_https(monkeypatch):
+ _board_url_cache.clear()
+ _board_fail_cache.clear()
+ monkeypatch.setattr(
+ "app.services.storage.publish_local",
+ lambda path, sync=True: "https://cdn.example.com/style-board.png",
+ )
+ url = resolve_image_style_board_url("palace-intrigue-cold")
+ assert url == "https://cdn.example.com/style-board.png"
+
+
+def test_resolve_image_style_board_url_skips_localhost(monkeypatch):
+ _board_url_cache.clear()
+ _board_fail_cache.clear()
+ monkeypatch.setattr(
+ "app.services.storage.publish_local",
+ lambda path, sync=True: "http://127.0.0.1:8000/static/board.png",
+ )
+ assert resolve_image_style_board_url("palace-intrigue-cold") == ""
+
+
+def test_append_style_prompt_mentions_style_board():
+ text = append_style_prompt("少女站在窗边", "ghibli-handdrawn-anime", has_style_board=True)
+ assert STYLE_BOARD_PROMPT_HINT in text
+ assert "禁止复制该图的人物" in text
+ locked = build_generation_prompt(
+ "黑发少女",
+ asset_type="character",
+ style_id="ghibli-handdrawn-anime",
+ has_style_board=True,
+ )
+ assert STYLE_BOARD_PROMPT_HINT in locked
+ plain = append_style_prompt("少女站在窗边", "ghibli-handdrawn-anime", has_style_board=False)
+ assert STYLE_BOARD_PROMPT_HINT not in plain
+
+
+def test_seedream_ref_urls_default_two_drama_split_reserves_style():
+ subjects = [f"https://cdn.example.com/c{i}.png" for i in range(8)]
+ styles = ["https://cdn.example.com/style.png"]
+ assert len(seedream_ref_urls(*subjects)) == 2
+ assert len(seedream_ref_urls(*subjects, limit=6)) == 6
+ subject_refs, style_refs = split_seedream_subject_style_refs(subjects, styles)
+ assert len(subject_refs) == 5
+ assert style_refs == styles
+ merged = append_style_board_url(subjects, styles[0], max_total=30)
+ assert merged[-1] == styles[0]
+ assert len(merged) == 9
+
diff --git a/backend/tests/test_kepu_character_bible.py b/backend/tests/test_kepu_character_bible.py
new file mode 100644
index 0000000..173020b
--- /dev/null
+++ b/backend/tests/test_kepu_character_bible.py
@@ -0,0 +1,22 @@
+"""科普分镜:模板角色不当作用户强制;是否出人由 LLM 按模板与主题决定。"""
+
+from types import SimpleNamespace
+
+from app.services.pipeline import _effective_character_prompt, resolve_script_character_bible
+
+
+def test_effective_character_prompt_ignores_template_fallback():
+ tpl = SimpleNamespace(seedream_config={"character_prompt": "模板操作员必须出镜"})
+ project = SimpleNamespace(character_prompt="", template=tpl)
+ assert _effective_character_prompt(project) == ""
+
+
+def test_effective_character_prompt_keeps_user_override():
+ project = SimpleNamespace(character_prompt=" 只出剪影人物 ", template=None)
+ assert _effective_character_prompt(project) == "只出剪影人物"
+
+
+def test_script_bible_prefers_user_then_llm():
+ assert resolve_script_character_bible("用户人设", "LLM 人设") == "用户人设"
+ assert resolve_script_character_bible("", "侧脸操作员,不锁同一张脸") == "侧脸操作员,不锁同一张脸"
+ assert resolve_script_character_bible("", "") == "无固定人物,各镜独立场景"
diff --git a/backend/tests/test_kepu_continuity.py b/backend/tests/test_kepu_continuity.py
new file mode 100644
index 0000000..02b66d9
--- /dev/null
+++ b/backend/tests/test_kepu_continuity.py
@@ -0,0 +1,85 @@
+"""科普逐镜衔接:后镜出图参考上一镜静帧,出视频参考上一镜尾帧。"""
+
+from types import SimpleNamespace
+
+from app.services.kepu_continuity import (
+ image_refs_for_shot,
+ previous_shot,
+ previous_usable_shot,
+ shot_image_ref,
+ shot_last_frame_ref,
+ video_extra_refs_for_shot,
+)
+
+
+def _shot(**kwargs):
+ """构造带默认镜号的分镜代理。"""
+ data = {"shot_no": 1, "image_ark_url": None, "image_url": None, "last_frame_url": None}
+ data.update(kwargs)
+ return SimpleNamespace(**data)
+
+
+def test_previous_shot_picks_immediate_predecessor():
+ """乱序分镜列表仍取 shot_no 紧邻的上一镜。"""
+ shots = [_shot(shot_no=1), _shot(shot_no=3), _shot(shot_no=2)]
+ prev = previous_shot(shots, 3)
+ assert prev is not None
+ assert prev.shot_no == 2
+ assert previous_shot(shots, 1) is None
+
+
+def test_image_refs_for_shot_puts_prev_still_first():
+ """后镜出图把上一镜 CDN 静帧放在参考列表最前。"""
+ prev = _shot(image_ark_url="https://cdn.example.com/shot1.png")
+ refs = image_refs_for_shot(prev, ["https://cdn.example.com/style.png"])
+ assert refs[0] == "https://cdn.example.com/shot1.png"
+ assert "https://cdn.example.com/style.png" in refs
+
+
+def test_image_refs_skip_local_static_and_keep_template():
+ """Seedream 丢弃本地 /static,仍保留模板公网底图。"""
+ prev = _shot(image_url="/static/generated/p1/shot_001.png")
+ refs = image_refs_for_shot(prev, ["https://cdn.example.com/style.png"])
+ assert refs == ["https://cdn.example.com/style.png"]
+ assert shot_image_ref(prev) is None
+
+
+def test_video_extra_refs_prefer_last_frame_even_if_local():
+ """出视频优先用上一镜尾帧,本地路径留给 Seedance resolve。"""
+ prev = _shot(
+ last_frame_url="/static/generated/p1/shot_001_last.jpg",
+ image_ark_url="https://cdn.example.com/shot1.png",
+ )
+ assert video_extra_refs_for_shot(prev) == ["/static/generated/p1/shot_001_last.jpg"]
+ assert shot_last_frame_ref(prev) == "/static/generated/p1/shot_001_last.jpg"
+
+
+def test_video_extra_refs_fall_back_to_prev_still():
+ """没有尾帧时退回上一镜静帧;首镜无额外参考。"""
+ prev = _shot(image_ark_url="https://cdn.example.com/shot1.png")
+ assert video_extra_refs_for_shot(prev) == ["https://cdn.example.com/shot1.png"]
+ assert video_extra_refs_for_shot(None) == []
+
+
+def test_shot_image_ref_skips_tokenfree_and_uses_oss():
+ """TokenFree 产物地址不能给上游当参考,改用已发布的公网图。"""
+ prev = _shot(
+ image_ark_url="https://www.tokenfree.com/v1/tasks/t1/artifacts/image-0/content",
+ image_url="https://cdn.example.com/shot1.png",
+ )
+ assert shot_image_ref(prev) == "https://cdn.example.com/shot1.png"
+ refs = image_refs_for_shot(prev, [])
+ assert refs == ["https://cdn.example.com/shot1.png"]
+
+
+def test_previous_usable_shot_skips_empty_middle():
+ """中间镜被清空时,后镜参考再往前一镜。"""
+ shots = [
+ _shot(shot_no=1, image_ark_url="https://cdn.example.com/s1.png"),
+ _shot(shot_no=2),
+ _shot(shot_no=3, image_ark_url="https://cdn.example.com/s3.png"),
+ ]
+ prev = previous_usable_shot(shots, 3)
+ assert prev is not None
+ assert prev.shot_no == 1
+ assert previous_shot(shots, 3).shot_no == 2
diff --git a/backend/tests/test_kepu_phase_billing.py b/backend/tests/test_kepu_phase_billing.py
index 25af424..181cfbb 100644
--- a/backend/tests/test_kepu_phase_billing.py
+++ b/backend/tests/test_kepu_phase_billing.py
@@ -108,7 +108,8 @@ def test_videos_estimate_only_remaining_shots() -> None:
settings=settings,
)
two = estimate_phase_fen(_project(shots), "videos", settings=settings)
- assert two == one * 2
+ # 每镜 ceil 后再乘 buffer,两镜合计可能差 1 分
+ assert abs(two - one * 2) <= 1
def test_normalize_produce_maps_to_current_phase(monkeypatch) -> None:
diff --git a/backend/tests/test_kepu_subtitle_preset.py b/backend/tests/test_kepu_subtitle_preset.py
new file mode 100644
index 0000000..972917d
--- /dev/null
+++ b/backend/tests/test_kepu_subtitle_preset.py
@@ -0,0 +1,59 @@
+"""科普成片字幕预设与后期 BGM 解析。"""
+
+from app.services.bgm import clip_shot_bgm, resolve_bgm_path
+from app.services.pipeline import _kepu_video_prompt, _merge_subtitle_preset
+from app.services.seedance_segments import build_segment_script, SegmentBeat
+
+
+def test_merge_subtitle_preset_standard_overrides_template():
+ out = _merge_subtitle_preset({"caption_scale": 1.4, "position": "split"}, "standard")
+ assert out["caption_scale"] == 1.25
+ assert out["position"] == "top"
+
+
+def test_merge_subtitle_preset_large_bumps_caption():
+ out = _merge_subtitle_preset({"caption_scale": 1.1}, "large")
+ assert out["caption_scale"] == 1.55
+
+
+def test_merge_subtitle_preset_split_sets_position():
+ out = _merge_subtitle_preset({"position": "top"}, "split")
+ assert out["position"] == "split"
+
+
+def test_merge_subtitle_preset_unknown_is_noop():
+ src = {"caption_scale": 1.1, "position": "top"}
+ assert _merge_subtitle_preset(src, "") == src
+ assert _merge_subtitle_preset(src, "unknown") == src
+
+
+def test_clip_shot_bgm_truncates_to_column():
+ assert len(clip_shot_bgm("轻快专业,音量低于人声,还带一段超长补充说明" * 4)) == 64
+ assert clip_shot_bgm("") == "neutral"
+
+
+def test_kepu_video_prompt_forbids_burn_when_sfx_off():
+ script = build_segment_script(
+ [
+ SegmentBeat(duration=4, kind="visual", text="过肩工位"),
+ SegmentBeat(duration=6, kind="narration", text="恒星燃料耗尽就会坍缩"),
+ ],
+ bgm_mood="轻快专业",
+ )
+ prompt = _kepu_video_prompt(
+ "【字幕:全程简体中文字幕,旁白逐句同步烧录】\n" + script,
+ style_prefix="写实",
+ motion_bias="",
+ camera="",
+ ambient_only=False,
+ )
+ assert "烧录简体中文字幕" not in prompt
+ assert "禁止在画面内烧录字幕" in prompt
+ assert "后期叠旁白字幕" in prompt or "后期完成" in prompt
+
+
+def test_resolve_bgm_path_uses_temp_fallback():
+ path = resolve_bgm_path("轻快专业")
+ assert path is not None
+ assert path.is_file()
+ assert "printfilm_bgm" in str(path)
diff --git a/backend/tests/test_logical_image_route.py b/backend/tests/test_logical_image_route.py
new file mode 100644
index 0000000..3fd79e6
--- /dev/null
+++ b/backend/tests/test_logical_image_route.py
@@ -0,0 +1,40 @@
+"""用户点名的图模型不要被静默换成同能力的 Seedream。"""
+
+from app.schemas_routing import (
+ DefaultModels,
+ LogicalModel,
+ LogicalModelBinding,
+ SystemModelChannel,
+)
+from app.services.logical_model_router import resolve_logical_model
+from app.services.model_settings import _refresh_routing_snapshot, get_routing_snapshot
+
+
+def test_requested_gpt_image_keeps_upstream():
+ prev = get_routing_snapshot()
+ channel = SystemModelChannel(
+ id="tokenfree",
+ name="TokenFree",
+ base_url="https://www.tokenfree.com/v1",
+ api_key="sk-test",
+ has_api_key=True,
+ protocol="openai",
+ models=["gpt-image-2-5", "seedream-5-0-pro"],
+ enabled=True,
+ )
+ # gpt-image 逻辑模型绑定坏了时,仍应按渠道清单直连
+ seedream = LogicalModel(
+ id="seedream-5.0",
+ capability="image",
+ enabled=True,
+ bindings=[
+ LogicalModelBinding(channel_id="tokenfree", upstream_model="seedream-5-0-pro", enabled=True)
+ ],
+ )
+ try:
+ _refresh_routing_snapshot([channel], [seedream], DefaultModels(image_model="seedream-5.0"))
+ route = resolve_logical_model("image", "gpt-image-2-5")
+ assert route is not None
+ assert route.upstream_model == "gpt-image-2-5"
+ finally:
+ _refresh_routing_snapshot(prev.channels, prev.logical_models, prev.default_models)
diff --git a/backend/tests/test_record_seedream_image_usage.py b/backend/tests/test_record_seedream_image_usage.py
index d529939..25b7315 100644
--- a/backend/tests/test_record_seedream_image_usage.py
+++ b/backend/tests/test_record_seedream_image_usage.py
@@ -53,4 +53,4 @@ async def test_record_seedream_with_upstream_cost_fen(db_session: AsyncSession,
await db_session.commit()
assert ev.estimated is False
assert ev.cost_fen == 500
- assert ev.charge_fen == 1000
+ assert ev.charge_fen == 500
diff --git a/backend/tests/test_replace_fragment_asset_refs.py b/backend/tests/test_replace_fragment_asset_refs.py
new file mode 100644
index 0000000..8b07396
--- /dev/null
+++ b/backend/tests/test_replace_fragment_asset_refs.py
@@ -0,0 +1,37 @@
+"""保存分镜时对齐资产引用:只补缺、只删多余。"""
+
+from unittest.mock import AsyncMock
+
+import pytest
+
+from app.models_drama import DramaEpisodeFragment, DramaFragmentAssetRef
+from app.services.drama.access import replace_fragment_asset_refs
+
+
+async def test_replace_keeps_existing_refs_without_reinsert():
+ db = AsyncMock()
+ frag = DramaEpisodeFragment(episode_id=1)
+ frag.id = 18275
+ keep = DramaFragmentAssetRef(fragment_id=18275, asset_id=4657)
+ drop = DramaFragmentAssetRef(fragment_id=18275, asset_id=1)
+ frag.asset_references = [keep, drop]
+
+ await replace_fragment_asset_refs(db, frag, [4657, 4665, 4657])
+
+ db.execute.assert_not_awaited()
+ assert [row.asset_id for row in frag.asset_references] == [4657, 4665]
+ assert frag.asset_references[0] is keep
+
+
+async def test_replace_empty_collection_only_appends():
+ db = AsyncMock()
+ frag = DramaEpisodeFragment(episode_id=1)
+ frag.id = 99
+ frag.asset_references = []
+
+ await replace_fragment_asset_refs(db, frag, [5, 5, 7, 0, -1])
+
+ db.execute.assert_not_awaited()
+ assert [row.asset_id for row in frag.asset_references] == [5, 7]
diff --git a/backend/tests/test_seedance_content_labels.py b/backend/tests/test_seedance_content_labels.py
index 4b5835e..981c99f 100644
--- a/backend/tests/test_seedance_content_labels.py
+++ b/backend/tests/test_seedance_content_labels.py
@@ -44,3 +44,67 @@ def test_content_slot_labels_match_content_indices():
assert "羽山" in labels[1]
assert "相柳" in labels[2]
assert "流民群演" in labels[3]
+
+
+def test_style_board_sits_after_assets_before_continuity():
+ reference = [
+ {
+ "id": 1,
+ "type": "character",
+ "name": "相柳",
+ "cover": "https://example.com/a.jpg",
+ "url": "",
+ "params": {},
+ }
+ ]
+ board = "https://cdn.example.com/ghibli-board.png"
+ continuity = "https://cdn.example.com/prev_last.jpg"
+ items = build_seedance_content_items(
+ "文案",
+ reference,
+ video_style_id="ghibli-handdrawn-anime",
+ continuity_first_frame_url=continuity,
+ style_board_url=board,
+ )
+ labels = describe_seedance_content_slots(
+ reference,
+ continuity,
+ has_text=True,
+ style_board_url=board,
+ )
+ assert len(labels) == len(items)
+ urls = [
+ item["image_url"]["url"]
+ for item in items
+ if item.get("type") == "image_url"
+ ]
+ assert urls == ["https://example.com/a.jpg", board, continuity]
+ assert labels == ["分镜文案", "角色「相柳」", "画风板", "上一镜尾帧"]
+ assert "只借鉴其色调、笔触、光影" in items[0]["text"]
+ assert all(item.get("role") == "reference_image" for item in items if item.get("type") == "image_url")
+
+
+def test_style_board_ignored_without_catalog_images():
+ continuity = "https://cdn.example.com/prev_last.jpg"
+ board = "https://cdn.example.com/ghibli-board.png"
+ items = build_seedance_content_items(
+ "文案",
+ [],
+ continuity_first_frame_url=continuity,
+ style_board_url=board,
+ )
+ labels = describe_seedance_content_slots(
+ [],
+ continuity,
+ has_text=True,
+ style_board_url=board,
+ )
+ urls = [
+ item["image_url"]["url"]
+ for item in items
+ if item.get("type") == "image_url"
+ ]
+ assert urls == [continuity]
+ assert items[-1].get("role") == "first_frame"
+ assert labels == ["分镜文案", "上一镜尾帧"]
+ assert "画风板" not in labels
diff --git a/backend/tests/test_seedance_model_routing.py b/backend/tests/test_seedance_model_routing.py
index 9db0fe5..5243b13 100644
--- a/backend/tests/test_seedance_model_routing.py
+++ b/backend/tests/test_seedance_model_routing.py
@@ -9,10 +9,37 @@ from app.services.tokenfree_gateway import locked_tokenfree_channel
def test_seedance_logical_meta_detects_versions():
assert _seedance_logical_meta("doubao-seedance-2-5-260628") == ("seedance-2.5", "Seedance 2.5")
assert _seedance_logical_meta("doubao-seedance-2-0-260128") == ("seedance-2", "Seedance 2")
+ assert _seedance_logical_meta("seedance-2-0-mini") == ("seedance-2-0-mini", "Seedance 2.0 Mini")
+
+
+def test_bootstrap_aliases_match_tokenfree_catalog_ids(monkeypatch):
+ """渠道已是 TokenFree 目录 id 时,仍能挂上 seedance-2.5 / seedance-2 别名。"""
+ from app.config import Settings
+
+ settings = Settings(
+ model_llm="kimi-k2.6",
+ model_video="doubao-seedance-2-5-260628",
+ model_video_2="doubao-seedance-2-0-260128",
+ openai_api_key="test-key",
+ )
+ monkeypatch.setattr("app.services.model_settings.get_settings", lambda: settings)
+ monkeypatch.setattr("app.config.get_settings", lambda: settings)
+
+ channels = [
+ locked_tokenfree_channel(
+ api_key="test-key",
+ models=["kimi-k2.6", "seedance-2-5", "seedance-2-0"],
+ enabled=True,
+ )
+ ]
+ logical_models, defaults = _bootstrap_logical_from_channels(channels)
+ ids = {model.id for model in logical_models if model.capability == "video"}
+ assert ids == {"seedance-2.5", "seedance-2"}
+ assert defaults.video_model == "seedance-2.5"
def test_bootstrap_registers_seedance_2_and_25(monkeypatch):
- from app.config import Settings, get_settings
+ from app.config import Settings
settings = Settings(
model_llm="kimi-k2.6",
diff --git a/backend/tests/test_seedance_segments.py b/backend/tests/test_seedance_segments.py
index 4b9e26e..fc33bc0 100644
--- a/backend/tests/test_seedance_segments.py
+++ b/backend/tests/test_seedance_segments.py
@@ -29,8 +29,8 @@ def test_build_segment_script_and_time_ranges():
],
bgm_mood="轻快专业",
)
- assert "【字幕:" in script
- assert "【BGM:" in script
+ assert "【字幕:后期叠旁白字幕" in script
+ assert "【BGM:后期混音" in script
assert "@duration:4" in script
assert "@duration:8" in script
assert "【旁白·自然语速·同步字幕】" in script
@@ -240,3 +240,24 @@ def test_build_seedance_prompt_ambient_only_rewrites_narration():
assert "一键接入即可开始监控" not in prompt
assert "00:00-00:05" in prompt
assert NARRATION_PREFIX not in prompt
+
+
+def test_normalize_kepu_subtitle_cue_rewrites_legacy_burn():
+ from app.services.seedance_segments import SUBTITLE_CUE, normalize_kepu_subtitle_cue
+
+ legacy = "【字幕:全程简体中文字幕,旁白逐句同步烧录】\n@duration:4\n过肩工位"
+ assert normalize_kepu_subtitle_cue(legacy).startswith(SUBTITLE_CUE)
+ assert "烧录" not in normalize_kepu_subtitle_cue(legacy)
+
+
+def test_apply_segment_script_edit_normalizes_legacy_kepu_cue():
+ edited = apply_segment_script_edit(
+ "【字幕:全程简体中文字幕,旁白逐句同步烧录】\n"
+ "【BGM:轻快专业,音量低于人声】\n"
+ "@duration:4\n过肩演示\n"
+ f"@duration:8\n{NARRATION_PREFIX}口播一句"
+ )
+ assert "后期叠旁白字幕" in edited["segment_script"]
+ assert "烧录" not in edited["segment_script"]
+ assert "后期混音" in edited["segment_script"]
+ assert edited["narration"]
diff --git a/backend/tests/test_seedream_billing_usage.py b/backend/tests/test_seedream_billing_usage.py
index d980f1e..88cdbb5 100644
--- a/backend/tests/test_seedream_billing_usage.py
+++ b/backend/tests/test_seedream_billing_usage.py
@@ -22,7 +22,7 @@ def test_parse_upstream_cost_fen_from_kie_credits():
assert parse_upstream_cost_fen({"creditsConsumed": 10}, settings) == 35
-def test_charge_fen_for_usage_kie_credits_with_markup():
+def test_charge_fen_for_usage_kie_credits_no_markup():
settings = get_settings()
settings.billing_markup = 1.5
settings.billing_kie_fen_per_credit = 3.5
@@ -34,7 +34,7 @@ def test_charge_fen_for_usage_kie_credits_with_markup():
)
assert used is True
assert cost == 35
- assert charge == 53 # ceil(35 * 1.5)
+ assert charge == 35
def test_charge_fen_for_usage_prefers_upstream_cost():
@@ -48,7 +48,7 @@ def test_charge_fen_for_usage_prefers_upstream_cost():
)
assert used is True
assert cost == 1000
- assert charge == 1500
+ assert charge == 1000
def test_charge_fen_for_usage_falls_back_to_tokens():
@@ -63,7 +63,7 @@ def test_charge_fen_for_usage_falls_back_to_tokens():
)
assert used is False
assert cost == 800
- assert charge == 1200
+ assert charge == 800
def test_build_task_result_includes_usage():
diff --git a/backend/tests/test_sequential_fragment_wait.py b/backend/tests/test_sequential_fragment_wait.py
new file mode 100644
index 0000000..7275459
--- /dev/null
+++ b/backend/tests/test_sequential_fragment_wait.py
@@ -0,0 +1,215 @@
+"""开启尾帧衔接后,连续点各镜生成必须按镜序等待,不能各自当首镜开跑。"""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from app.services.tasks.service import (
+ _sequential_fragment_video_project_id,
+ pick_sequential_episode_head,
+ reconcile_sequential_batches,
+ sequential_fragment_video_needs_episode_rebalance,
+ sequential_task_blocked_by_previous_fragment,
+)
+
+
+def _task(**kwargs):
+ """构造分镜视频任务替身。"""
+ payload = kwargs.pop("payload", {"sequential": True, "batch_index": 0})
+ defaults = {
+ "id": 1,
+ "task_type": "fragment_video",
+ "status": "pending",
+ "next_action_at": None,
+ "requested_by": 9,
+ "drama_project_id": 100,
+ "fragment_id": 1,
+ "episode_id": 7,
+ "payload": payload,
+ "current_step_key": "submit",
+ "cancel_requested": False,
+ }
+ defaults.update(kwargs)
+ return SimpleNamespace(**defaults)
+
+
+def _rows(items):
+ """模拟 SQLAlchemy scalars().all()。"""
+
+ class _Result:
+ def scalars(self):
+ return self
+
+ def all(self):
+ return list(items)
+
+ return _Result()
+
+
+def test_sequential_fragment_video_needs_episode_rebalance():
+ assert sequential_fragment_video_needs_episode_rebalance(
+ "fragment_video", {"sequential": True}
+ )
+ assert not sequential_fragment_video_needs_episode_rebalance(
+ "fragment_video", {"sequential": False}
+ )
+ assert not sequential_fragment_video_needs_episode_rebalance(
+ "asset_image", {"sequential": True}
+ )
+
+
+def test_pick_head_keeps_running_first_shot():
+ shot1 = _task(id=11, fragment_id=1, status="awaiting_poll")
+ shot2 = _task(id=12, fragment_id=2, status="pending")
+ head = pick_sequential_episode_head(
+ [shot2, shot1],
+ {1: 0, 2: 1},
+ )
+ assert head is shot1
+
+
+def test_pick_head_activates_next_after_previous_leaves_queue():
+ shot2 = _task(id=12, fragment_id=2, status="pending")
+ shot3 = _task(id=13, fragment_id=3, status="pending")
+ head = pick_sequential_episode_head(
+ [shot3, shot2],
+ {2: 1, 3: 2},
+ )
+ assert head is shot2
+
+
+def test_project_id_falls_back_to_payload():
+ task = _task(drama_project_id=None, payload={"sequential": True, "project_id": "355"})
+ assert _sequential_fragment_video_project_id(task, task.payload) == 355
+ assert _sequential_fragment_video_project_id(
+ _task(drama_project_id=None, payload={"sequential": True}),
+ {"sequential": True},
+ ) is None
+
+
+def _frag(fid: int, sort_order: int, *, video: str = "", last_frame: str = ""):
+ """构造分镜替身。"""
+ params: dict = {}
+ if last_frame:
+ params["lastFrameUrl"] = last_frame
+ return SimpleNamespace(id=fid, sort_order=sort_order, video=video, params=params)
+
+
+def test_later_shot_waits_when_previous_failed_without_last_frame():
+ shot2 = _task(id=12, fragment_id=2, status="pending")
+ prev = _frag(1, 0)
+ current = _frag(2, 1)
+ assert sequential_task_blocked_by_previous_fragment(shot2, [current, prev])
+
+
+def test_later_shot_unblocked_when_previous_has_last_frame():
+ shot2 = _task(id=12, fragment_id=2, status="pending")
+ prev = _frag(1, 0, last_frame="https://example.com/last.png")
+ current = _frag(2, 1)
+ assert not sequential_task_blocked_by_previous_fragment(shot2, [current, prev])
+
+
+async def test_reconcile_does_not_activate_each_click_as_batch_head():
+ """连续点击会各建 batch_index=0;调和不得把后镜当独立首镜点亮。"""
+ shot1 = _task(id=11, fragment_id=1)
+ shot2 = _task(id=12, fragment_id=2)
+ db = SimpleNamespace(commit=AsyncMock())
+ db.execute = AsyncMock(
+ side_effect=[
+ _rows(["batch-click-1", "batch-click-2"]),
+ _rows([shot1]),
+ _rows([shot2]),
+ ]
+ )
+ rebalance = AsyncMock(return_value={"pending": 2, "activated": 0, "deferred": 1})
+ activate_next = AsyncMock()
+ append_event = AsyncMock()
+
+ with (
+ patch(
+ "app.services.tasks.service.rebalance_project_fragment_video_queue",
+ new=rebalance,
+ ),
+ patch(
+ "app.services.tasks.service.activate_next_sequential_task",
+ new=activate_next,
+ ),
+ patch("app.services.tasks.service.append_task_event", new=append_event),
+ patch(
+ "app.config.get_settings",
+ return_value=SimpleNamespace(drama_user_video_job_limit=12),
+ ),
+ ):
+ await reconcile_sequential_batches(db)
+
+ assert shot1.next_action_at is None
+ assert shot2.next_action_at is None
+ append_event.assert_not_awaited()
+ activate_next.assert_not_awaited()
+ rebalance.assert_awaited_once()
+ assert rebalance.await_args.args[1] == 100
+ assert rebalance.await_args.kwargs["sequential"] is True
+
+
+async def test_reconcile_uses_payload_project_id_when_column_missing():
+ """drama_project_id 为空时仍按 payload.project_id 收口重排。"""
+ shot = _task(
+ id=31,
+ fragment_id=2,
+ drama_project_id=None,
+ payload={"sequential": True, "batch_index": 0, "project_id": 355},
+ )
+ db = SimpleNamespace(commit=AsyncMock())
+ db.execute = AsyncMock(side_effect=[_rows(["batch-no-col"]), _rows([shot])])
+ rebalance = AsyncMock(return_value={"pending": 1, "activated": 0, "deferred": 1})
+
+ with (
+ patch(
+ "app.services.tasks.service.rebalance_project_fragment_video_queue",
+ new=rebalance,
+ ),
+ patch("app.services.tasks.service.append_task_event", new=AsyncMock()),
+ patch(
+ "app.config.get_settings",
+ return_value=SimpleNamespace(drama_user_video_job_limit=12),
+ ),
+ ):
+ await reconcile_sequential_batches(db)
+
+ assert shot.next_action_at is None
+ rebalance.assert_awaited_once()
+ assert rebalance.await_args.args[1] == 355
+
+
+async def test_reconcile_still_activates_non_fragment_sequential_head():
+ """非分镜视频的串行 batch 仍按 batch_index=0 补激活。"""
+ other = _task(id=21, task_type="other_job", fragment_id=None)
+ db = SimpleNamespace(commit=AsyncMock())
+ db.execute = AsyncMock(side_effect=[_rows(["batch-other"]), _rows([other])])
+ rebalance = AsyncMock(return_value={"pending": 0, "activated": 0, "deferred": 0})
+ append_event = AsyncMock()
+
+ with (
+ patch(
+ "app.services.tasks.service.rebalance_project_fragment_video_queue",
+ new=rebalance,
+ ),
+ patch("app.services.tasks.service.append_task_event", new=append_event),
+ patch(
+ "app.services.drama.access.count_user_inflight_fragment_video_tasks",
+ new=AsyncMock(return_value=0),
+ ),
+ patch(
+ "app.config.get_settings",
+ return_value=SimpleNamespace(drama_user_video_job_limit=12),
+ ),
+ ):
+ await reconcile_sequential_batches(db)
+
+ assert other.next_action_at is not None
+ append_event.assert_awaited()
+ rebalance.assert_not_awaited()
diff --git a/backend/tests/test_side_task_gate.py b/backend/tests/test_side_task_gate.py
new file mode 100644
index 0000000..6ac5e7f
--- /dev/null
+++ b/backend/tests/test_side_task_gate.py
@@ -0,0 +1,54 @@
+"""单镜侧任务门禁:整片流水线才拦截,残留 IMAGING / 其它镜任务不拦。"""
+
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+
+from app.api.projects import _ensure_side_task_allowed
+
+
+def _project(*tasks: SimpleNamespace, status: str = "SCRIPT_READY") -> SimpleNamespace:
+ return SimpleNamespace(status=status, active_tasks=list(tasks))
+
+
+def _task(task_type: str, status: str = "running", cancel_requested: bool = False) -> SimpleNamespace:
+ return SimpleNamespace(task_type=task_type, status=status, cancel_requested=cancel_requested)
+
+
+def test_side_task_allows_leftover_imaging_without_tasks():
+ _ensure_side_task_allowed(_project(status="IMAGING"))
+
+
+def test_side_task_allows_parallel_shot_regen():
+ _ensure_side_task_allowed(_project(_task("shot_regen_image"), status="IMAGING"))
+
+
+def test_side_task_blocks_project_pipeline():
+ with pytest.raises(HTTPException) as exc:
+ _ensure_side_task_allowed(_project(_task("project_pipeline"), status="SCRIPTING"))
+ assert exc.value.status_code == 409
+
+
+def test_side_task_blocks_shot_regen_audio():
+ with pytest.raises(HTTPException) as exc:
+ _ensure_side_task_allowed(_project(_task("shot_regen_audio"), status="AUDIOING"))
+ assert exc.value.status_code == 409
+
+
+def test_side_task_blocks_compose():
+ with pytest.raises(HTTPException) as exc:
+ _ensure_side_task_allowed(_project(_task("project_compose_only"), status="COMPOSING"))
+ assert exc.value.status_code == 409
+
+
+def test_side_task_blocks_cancel_requested_pipeline():
+ with pytest.raises(HTTPException) as exc:
+ _ensure_side_task_allowed(
+ _project(_task("project_pipeline", status="cancel_requested", cancel_requested=True))
+ )
+ assert exc.value.status_code == 409
+
+
+def test_side_task_allows_terminal_cancelled_pipeline():
+ _ensure_side_task_allowed(_project(_task("project_pipeline", status="cancelled", cancel_requested=True)))
diff --git a/backend/tests/test_tokenfree_image.py b/backend/tests/test_tokenfree_image.py
new file mode 100644
index 0000000..9af4874
--- /dev/null
+++ b/backend/tests/test_tokenfree_image.py
@@ -0,0 +1,277 @@
+"""TokenFree 生图走 /v1/responses。"""
+
+from types import SimpleNamespace
+
+import pytest
+
+from app.services.tokenfree_image import (
+ build_tokenfree_image_body,
+ extract_tokenfree_image_url,
+ is_tokenfree_no_distributor,
+ is_tokenfree_protocol_error,
+ is_tokenfree_rate_limit,
+ is_tokenfree_retryable_image_error,
+ post_until_not_rate_limited,
+ tokenfree_image_channel_dead,
+ tokenfree_image_user_error,
+ tokenfree_working_image_model,
+ uses_tokenfree_image,
+)
+from app.services.tokenfree_gateway import TOKENFREE_BASE_URL, TOKENFREE_CHANNEL_ID
+
+
+def test_uses_tokenfree_image_on_tokenfree_host():
+ assert uses_tokenfree_image(base_url=TOKENFREE_BASE_URL) is True
+ assert uses_tokenfree_image(channel_id=TOKENFREE_CHANNEL_ID) is True
+ assert uses_tokenfree_image(base_url="https://ark.cn-beijing.volces.com/api/v3") is False
+
+
+def test_build_tokenfree_image_body_matches_live_success():
+ body = build_tokenfree_image_body(model="gpt-image-2-5", prompt="橘猫", size="2K")
+ assert body["model"] == "gpt-image-2-5"
+ assert "橘猫" in body["input"]
+ assert "size:" not in body["input"]
+ assert "prompt" not in body
+ assert "watermark" not in body
+
+
+def test_build_tokenfree_image_body_separates_style_and_subject_refs():
+ body = build_tokenfree_image_body(
+ model="gpt-image-2-5",
+ prompt="少女站在窗边",
+ ref_urls=["https://cdn.example.com/character.png"],
+ style_ref_urls=["https://cdn.example.com/ghibli.png"],
+ )
+ text = body["input"]
+ assert "画风参考图(只借色调、笔触、光影,禁止抄主体与构图):https://cdn.example.com/ghibli.png" in text
+ assert "构图与主体参考:https://cdn.example.com/character.png" in text
+ assert text.index("画风参考图") < text.index("构图与主体参考")
+
+
+def test_tokenfree_working_image_model_remaps_seedream():
+ assert tokenfree_working_image_model("seedream-5-0-pro") == "gpt-image-2-5"
+ assert tokenfree_working_image_model("gpt-image-2-5") == "gpt-image-2-5"
+
+
+def test_extract_tokenfree_image_url_from_img_tag():
+ url = extract_tokenfree_image_url(
+ {
+ "output": [
+ {
+ "content": [
+ {
+ "type": "output_text",
+ "text": '<img src="https://www.tokenfree.com/v1/tasks/t1/artifacts/image-0/content?access=x" />',
+ }
+ ]
+ }
+ ]
+ }
+ )
+ assert url and url.startswith("https://www.tokenfree.com/v1/tasks/")
+
+
+def test_is_tokenfree_rate_limit_detects_observations():
+ body = '{"error":{"code":"rate_limit_exceeded","message":"Too many active task observations"}}'
+ assert is_tokenfree_rate_limit(status_code=429, body="") is True
+ assert is_tokenfree_rate_limit(status_code=200, body=body) is True
+ assert is_tokenfree_rate_limit(status_code=200, body='{"usage":{"rate_limit":{"remaining":1}}}') is False
+ assert is_tokenfree_rate_limit(status_code=503, body="model_not_found") is False
+
+
+def test_is_tokenfree_protocol_error():
+ body = '{"error":{"code":"task_protocol_error","message":"Task protocol request failed"}}'
+ assert is_tokenfree_protocol_error(status_code=502, body=body) is True
+ assert is_tokenfree_protocol_error(status_code=200, body='{"id":"ok"}') is False
+ assert is_tokenfree_retryable_image_error(status_code=502, body=body) is False
+ assert tokenfree_image_channel_dead(status_code=502, body=body) is True
+
+
+def test_is_tokenfree_no_distributor():
+ """503 model_not_found 视为无线路,不再当限流重试。"""
+ body = '{"error":{"code":"model_not_found","message":"分组 default 下模型 gpt-image-2-5 无可用的渠道distributor"}}'
+ assert is_tokenfree_no_distributor(status_code=503, body=body) is True
+ assert tokenfree_image_channel_dead(status_code=503, body=body) is True
+ assert is_tokenfree_retryable_image_error(status_code=503, body=body) is False
+
+
+def test_tokenfree_image_user_error_does_not_nudge_switch_model():
+ """TokenFree 通道挂了不再提示改用 gpt-image-2-5。"""
+ protocol = '{"error":{"code":"task_protocol_error","message":"Task protocol request failed"}}'
+ for mid in ("gpt-image-2-5", "seedream-5-0-pro"):
+ msg = tokenfree_image_user_error(model=mid, status_code=502, body=protocol)
+ assert "请改用 gpt-image-2-5" not in msg
+ assert "暂时失败" in msg
+
+
+def test_raise_seedream_http_error_tokenfree_vs_ark():
+ """TokenFree 走友好文案,官方方舟保持 Seedream error。"""
+ from app.services.ark import _raise_seedream_http_error
+
+ protocol = '{"error":{"code":"task_protocol_error","message":"Task protocol request failed"}}'
+ with pytest.raises(RuntimeError, match="暂时失败"):
+ _raise_seedream_http_error(502, protocol, model="gpt-image-2-5", tokenfree=True)
+ with pytest.raises(RuntimeError, match="Seedream error 502"):
+ _raise_seedream_http_error(502, protocol, model="gpt-image-2-5", tokenfree=False)
+
+
+async def test_post_until_not_rate_limited_retries_then_ok():
+ calls = {"n": 0}
+ sleeps: list[float] = []
+
+ async def post():
+ calls["n"] += 1
+ if calls["n"] < 3:
+ return SimpleNamespace(status_code=429, text="Too many active task observations")
+ return SimpleNamespace(status_code=200, text="ok")
+
+ async def fake_sleep(sec: float):
+ sleeps.append(sec)
+
+ resp = await post_until_not_rate_limited(post, delays=(0.1, 0.2), sleep=fake_sleep)
+ assert resp.status_code == 200
+ assert calls["n"] == 3
+ assert sleeps == [0.1, 0.2]
+
+
+async def test_post_does_not_retry_protocol_error():
+ """协议失败立即返回,避免空等四轮。"""
+ calls = {"n": 0}
+
+ async def post():
+ calls["n"] += 1
+ return SimpleNamespace(
+ status_code=502,
+ text='{"error":{"code":"task_protocol_error","message":"Task protocol request failed"}}',
+ )
+
+ async def fake_sleep(_sec: float):
+ return None
+
+ resp = await post_until_not_rate_limited(post, delays=(0.01,), sleep=fake_sleep)
+ assert resp.status_code == 502
+ assert calls["n"] == 1
+
+
+async def test_kie_image_fallback_skips_without_key(monkeypatch):
+ """没有 Kie Key 时不回退。"""
+ from app.services.ark import ArkGateway
+
+ monkeypatch.setattr(
+ "app.services.kie_client.resolve_kie_credentials",
+ lambda: ("", "https://api.kie.ai"),
+ )
+ out = await ArkGateway()._kie_image_fallback(
+ "湖",
+ project_id=1,
+ shot_no=1,
+ size="2k",
+ aspect_ratio="16:9",
+ ref_urls=None,
+ )
+ assert out is None
+
+
+async def test_seedream_once_falls_back_to_kie_on_protocol_error(monkeypatch):
+ """TokenFree 协议失败且有回退时,返回 Kie 结果。"""
+ from app.config import Settings
+ from app.services.ark import ArkGateway, ImageResult
+
+ settings = Settings(
+ ark_mock=False,
+ ark_api_key="sk-test",
+ ark_base_url="https://www.tokenfree.com/v1",
+ )
+ gw = ArkGateway(settings=settings)
+
+ class _Resp:
+ status_code = 502
+ text = '{"error":{"code":"task_protocol_error","message":"Task protocol request failed"}}'
+
+ def json(self):
+ return {}
+
+ class _FakeClient:
+ def __init__(self, *args, **kwargs):
+ pass
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *args):
+ return False
+
+ async def post(self, *args, **kwargs):
+ return _Resp()
+
+ async def _fake_fallback(*args, **kwargs):
+ return ImageResult(local_url="/static/x.png")
+
+ monkeypatch.setattr("app.services.ark.httpx.AsyncClient", _FakeClient)
+ monkeypatch.setattr(gw, "_resolve_ark_route", lambda *args, **kwargs: None)
+ monkeypatch.setattr(gw, "_kie_image_fallback", _fake_fallback)
+ result = await gw._seedream_once(
+ "湖",
+ None,
+ project_id=1,
+ shot_no=1,
+ size="2k",
+ prompt_hash_src="湖",
+ model="gpt-image-2-5",
+ )
+ assert result.local_url == "/static/x.png"
+
+
+async def test_seedream_once_keeps_tokenfree_error_when_kie_fallback_raises(monkeypatch):
+ """Kie 回退抛错时仍返回 TokenFree 友好文案,不把 Kie 原文抛给用户。"""
+ from app.config import Settings
+ from app.services.ark import ArkGateway
+
+ settings = Settings(
+ ark_mock=False,
+ ark_api_key="sk-test",
+ ark_base_url="https://www.tokenfree.com/v1",
+ )
+ gw = ArkGateway(settings=settings)
+
+ class _Resp:
+ status_code = 502
+ text = '{"error":{"code":"task_protocol_error","message":"Task protocol request failed"}}'
+
+ def json(self):
+ return {}
+
+ class _FakeClient:
+ def __init__(self, *args, **kwargs):
+ pass
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *args):
+ return False
+
+ async def post(self, *args, **kwargs):
+ return _Resp()
+
+ async def _boom(*args, **kwargs):
+ raise RuntimeError("Kie 生图失败")
+
+ monkeypatch.setattr("app.services.ark.httpx.AsyncClient", _FakeClient)
+ monkeypatch.setattr(gw, "_resolve_ark_route", lambda *args, **kwargs: None)
+ monkeypatch.setattr(gw, "_kie_image_fallback", _boom)
+ with pytest.raises(RuntimeError, match="暂时失败"):
+ await gw._seedream_once(
+ "湖",
+ None,
+ project_id=1,
+ shot_no=1,
+ size="2k",
+ prompt_hash_src="湖",
+ model="gpt-image-2-5",
+ )
diff --git a/backend/tests/test_tokenfree_pricing.py b/backend/tests/test_tokenfree_pricing.py
new file mode 100644
index 0000000..668e85f
--- /dev/null
+++ b/backend/tests/test_tokenfree_pricing.py
@@ -0,0 +1,183 @@
+"""TokenFree 官方价目解析、推荐名单与预估。"""
+
+from __future__ import annotations
+
+from app.config import get_settings
+from app.services.tokenfree_pricing import (
+ OfficialRate,
+ RECOMMENDED_MODELS,
+ build_official_rate_rows,
+ charge_fen_official_image,
+ charge_fen_official_llm,
+ charge_fen_official_video,
+ lookup_rate,
+ parse_pricing_payload,
+ set_cached_rates,
+ video_catalog_id,
+)
+
+
+def _sample_payload() -> dict:
+ return {
+ "success": True,
+ "data": [
+ {
+ "model_name": "gpt-image-2-5",
+ "quota_type": 1,
+ "model_price": 0.625,
+ "model_ratio": 0,
+ "completion_ratio": 0,
+ },
+ {
+ "model_name": "kimi-k2.6",
+ "quota_type": 0,
+ "model_price": 0,
+ "model_ratio": 0.727612,
+ "completion_ratio": 4.15385,
+ },
+ {
+ "model_name": "seedance-2-5",
+ "quota_type": 0,
+ "model_price": 0,
+ "model_ratio": 37.5,
+ "completion_ratio": 1,
+ },
+ ],
+ }
+
+
+def test_parse_pricing_payload_per_call_and_token() -> None:
+ """按张价与 token 价按 7 汇率折人民币。"""
+ settings = get_settings()
+ settings.billing_usd_cny = 7.0
+ rates = parse_pricing_payload(_sample_payload(), settings)
+ image = rates["gpt-image-2-5"]
+ assert image.billing == "per_call"
+ assert image.cny_per_call == 4.375
+ llm = rates["kimi-k2.6"]
+ assert llm.billing == "token"
+ assert abs(llm.cny_in_per_1m - 10.1866) < 0.01
+ video = rates["seedance-2-5"]
+ assert video.placeholder is True
+
+
+def test_recommended_models_cover_text_image_video() -> None:
+ """短名单覆盖文字/图/视频,且含默认推荐。"""
+ caps = {row["capability"] for row in RECOMMENDED_MODELS}
+ assert caps == {"text", "image", "video"}
+ ids = {row["id"] for row in RECOMMENDED_MODELS}
+ assert {"kimi-k2.6", "gpt-image-2-5", "seedance-2-5"} <= ids
+ assert any(row["recommended"] and row["id"] == "kimi-k2.6" for row in RECOMMENDED_MODELS)
+
+
+def test_charge_official_image_uses_per_call() -> None:
+ """有官方按张价时,生图预估不再走 8 元/百万 token。"""
+ settings = get_settings()
+ settings.billing_usd_cny = 7.0
+ settings.billing_markup = 1.5
+ settings.billing_seedream_per_m = 8.0
+ settings.billing_est_seedream_tokens = 45_000
+ rates = parse_pricing_payload(_sample_payload(), settings)
+ set_cached_rates(rates)
+ try:
+ charge = charge_fen_official_image(settings, model="seedream-5-0-pro")
+ # ¥4.375 → 438 分
+ assert charge == 438
+ finally:
+ set_cached_rates(None)
+
+
+def test_charge_official_image_falls_back_without_cache() -> None:
+ """无价目缓存时回退旧 token 估价。"""
+ settings = get_settings()
+ settings.billing_markup = 1.5
+ settings.billing_seedream_per_m = 8.0
+ settings.billing_est_seedream_tokens = 45_000
+ set_cached_rates(None)
+ from app.services.billing.pricing import charge_fen_for_tokens
+
+ _, expected = charge_fen_for_tokens(45_000, "seedream", settings=settings)
+ assert charge_fen_official_image(settings) == expected
+
+
+def test_charge_official_video_uses_vendor_sec_not_placeholder() -> None:
+ """视频预估用火山 480P 秒价,不用 37.5 占位倍率。"""
+ settings = get_settings()
+ settings.billing_markup = 1.5
+ settings.billing_usd_cny = 7.0
+ rates = parse_pricing_payload(_sample_payload(), settings)
+ set_cached_rates(rates)
+ try:
+ charge = charge_fen_official_video(5.0, settings, model="seedance-2-5")
+ # 3.36 元 → 336 分
+ assert charge == 336
+ finally:
+ set_cached_rates(None)
+
+
+def test_charge_official_llm_uses_in_out_split() -> None:
+ """LLM 预估按官方 in/out 70/30 拆。"""
+ settings = get_settings()
+ settings.billing_usd_cny = 7.0
+ settings.billing_markup = 1.5
+ settings.model_llm = "kimi-k2.6"
+ rates = parse_pricing_payload(_sample_payload(), settings)
+ set_cached_rates(rates)
+ try:
+ charge = charge_fen_official_llm(10_000, settings)
+ assert charge > 1
+ assert lookup_rate("kimi-k2.6") is not None
+ finally:
+ set_cached_rates(None)
+
+
+def test_build_official_rate_rows_marks_video_vendor() -> None:
+ """费率表视频行标 vendor_sec,方便去 TokenFree 核对。"""
+ settings = get_settings()
+ settings.billing_usd_cny = 7.0
+ settings.billing_markup = 1.5
+ rates = parse_pricing_payload(_sample_payload(), settings)
+ rows = build_official_rate_rows(rates, settings)
+ by_id = {row["id"]: row for row in rows}
+ assert by_id["gpt-image-2-5"]["official_cost_yuan"] == 4.375
+ assert by_id["gpt-image-2-5"]["user_charge_yuan"] == 4.375
+ assert by_id["seedance-2-5"]["basis"] == "vendor_sec"
+ assert by_id["seedance-2-5"]["placeholder"] is True
+
+
+def test_parse_pricing_item_skips_bad_row() -> None:
+ """脏字段跳过,不让整包价目作废。"""
+ from app.services.tokenfree_pricing import parse_pricing_item
+
+ assert parse_pricing_item({"model_name": "x", "quota_type": "nope"}, usd_cny=7.0) is None
+
+
+def test_video_catalog_id_from_endpoint() -> None:
+ """方舟接入点名能收到推荐 Seedance id。"""
+ assert video_catalog_id("doubao-seedance-2-5-260628") == "seedance-2-5"
+ assert video_catalog_id("seedance-2-0-mini") == "seedance-2-0-mini"
+ assert video_catalog_id("doubao-seedance-2-0-260128") == "seedance-2-0"
+ assert video_catalog_id("seedance-2") == "seedance-2-0"
+ assert video_catalog_id("seedance-2-0") == "seedance-2-0"
+
+
+def test_canonicalize_channel_models_merges_seedance_2_aliases() -> None:
+ """2.0 三档别名合并成一条,2.5 / Mini 保留。"""
+ from app.services.tokenfree_pricing import canonicalize_channel_models
+
+ assert canonicalize_channel_models(
+ [
+ "doubao-seedance-2-0-260128",
+ "seedance-2",
+ "seedance-2-0",
+ "seedance-2-0-mini",
+ "seedance-2-5",
+ ]
+ ) == ["seedance-2-0", "seedance-2-0-mini", "seedance-2-5"]
+
+
+def test_canonicalize_keeps_unknown_seedance_id() -> None:
+ """未知 Seedance 名不改写成 2.5。"""
+ from app.services.tokenfree_pricing import canonicalize_channel_model_id
+
+ assert canonicalize_channel_model_id("seedance-1.5") == "seedance-1.5"
diff --git a/deploy/.env.prod.example b/deploy/.env.prod.example
index 0a6e286..de80b72 100644
--- a/deploy/.env.prod.example
+++ b/deploy/.env.prod.example
@@ -32,7 +32,7 @@ USE_CELERY=true
QUOTA_ENABLED=false
BILLING_ENABLED=true
-BILLING_MARKUP=1.5
+BILLING_MARKUP=1.0
BILLING_SIGNUP_GRANT_FEN=500
EPAY_API_URL=https://pay.gitcc.com
EPAY_PID=
diff --git a/docs/BILLING.md b/docs/BILLING.md
index 2cfcb35..f4b5be4 100644
--- a/docs/BILLING.md
+++ b/docs/BILLING.md
@@ -2,8 +2,8 @@
## 原则
-- 按上游 **真实 token 用量**(或无法拿到 usage 时的保守估价)计费。
-- 用户支付价 = 上游成本 × **1.5**(`BILLING_MARKUP`)。
+- 按上游 **真实 TokenFree 成本**(或无法拿到 usage 时的保守估价)计费。
+- 用户支付价 = TokenFree 官方成本,**不再加价**。
- 钱包单位:**分(fen)**。
- 充值:易支付 [pay.gitcc.com](https://pay.gitcc.com/),支付宝 `alipay` / 微信 `wxpay`。
- **所有 AI 调用**均关联 `task_run_id`(单次聊天/API/工具调用创建轻量 TaskRun)。
@@ -13,13 +13,13 @@
**有上游成本时(优先)**:
```
-charge_fen = ceil(cost_fen × markup)
+charge_fen = cost_fen
```
**按 token 估价时**:
```
-charge_fen = ceil(tokens / 1e6 * provider_yuan_per_m * markup * 100)
+charge_fen = ceil(tokens / 1e6 * provider_yuan_per_m * 100)
```
默认成本价(元/百万 tokens,可环境覆盖):
@@ -38,10 +38,12 @@ charge_fen = ceil(tokens / 1e6 * provider_yuan_per_m * markup * 100)
```
cost_fen = ceil(quota / 500000 × BILLING_USD_CNY × 100) # 500000 quota = 1 USD
-charge_fen = ceil(cost_fen × markup)
+charge_fen = cost_fen
```
-未返回 quota 时回退 token 单价。管理端「支付与计费」可「查询 TokenFree 余额」(`GET /v1/dashboard/billing/subscription` + `usage`)。
+未返回 quota 时回退 token 单价。管理端「支付与计费」可「查询 TokenFree 余额」(`GET /v1/dashboard/billing/subscription` + `usage`),并拉取公开价目 `GET https://www.tokenfree.com/api/pricing` 展示推荐模型官方价。
+
+预扣:生图按 TokenFree 按张价(Seedream 实际走 `gpt-image-2-5`);LLM 按官方 in/out(默认 kimi-k2.6,70/30 拆);视频不用价目表占位 `model_ratio=37.5`,按火山 480P 秒价估。结算仍优先单次 `quota`。
管理端「官方用量对照」复用模型页 TokenFree API Key,拉取 New API 日消耗(`/api/data/self` 或 billing usage,日期无效时按累计额度差分记到当天)并与本地成本对照。
@@ -135,7 +137,7 @@ api/studio 轻量视频:`awaiting_poll` 由 Selector 后台轮询;超过 `ar
```
BILLING_ENABLED=true
-BILLING_MARKUP=1.5
+BILLING_MARKUP=1.0
BILLING_KIE_FEN_PER_CREDIT=3.5
EPAY_API_URL=https://pay.gitcc.com
EPAY_PID=your-epay-pid
@@ -158,12 +160,12 @@ EPAY_RETURN_URL=https://your-site.example.com/pricing?paid=1
| GET | `/api/admin/tasks/{id}` | 任务详情含 `usage_lines` 与计费字段 |
| GET | `/api/admin/stats/upstream-usage` | 近 N 日官方/本地成本对照 |
| POST | `/api/admin/stats/upstream-usage/sync` | 手动刷新官方用量快照 |
-| GET | `/api/admin/settings/billing/model-rates` | 各模型计费口径(TokenFree quota / token) |
+| GET | `/api/admin/settings/billing/model-rates` | 推荐模型 TokenFree 官方价(/api/pricing) |
| GET | `/api/admin/settings/tokenfree/quota` | 查询 TokenFree 账户剩余额度 |
## 管理端
-- **设置 → 支付与计费**:各模型单价、markup;可查看模型费率表与查询 TokenFree 余额。
+- **设置 → 支付与计费**:按 TokenFree 官方成本 1:1 扣费;可查看模型费率表与查询 TokenFree 余额。
- **订单与流水** → 「用量明细」Tab:按用户/任务/领域筛选 `usage_events`。
- **任务队列** → 列表「费用」列显示 `billing_charged_fen`(冻结中显示预扣)。
- **任务详情** → 「计费」Tab:预扣/实扣/退回 + 用量行列表。
@@ -177,4 +179,4 @@ EPAY_RETURN_URL=https://your-site.example.com/pricing?paid=1
4. 管理端可按 `task_run_id` 或 `billing_key=llm_chat` 查到每条 LLM/图/视频/TTS 费用。
5. Seedance 视频成功后 `usage_events.estimated=false` 且 `total_tokens` 与官方任务查询一致。
6. 配置 TokenFree API Key 后,管理端可刷新并查看近 30 日官方/本地成本对照。
-7. 单次调用若带 New API `quota` / `quota_consumed`,按额度折人民币后再 × markup 扣费;管理端可查询 TokenFree 余额。
+7. 单次调用若带 New API `quota` / `quota_consumed`,按额度折人民币后按官方成本 1:1 扣费;管理端可查询 TokenFree 余额。
diff --git a/docs/releases/2026-09-12.md b/docs/releases/2026-09-12.md
new file mode 100644
index 0000000..a1ee887
--- /dev/null
+++ b/docs/releases/2026-09-12.md
@@ -0,0 +1,34 @@
+## 2026-09-12 18:55 · 保存分镜新建镜 MissingGreenlet(热修)
+
+- **操作者**:Agent
+- **方式**:SSH 热修(改 `access.py` + `episodes.py` + `systemctl restart ai-movie-api`)
+- **范围**:api
+- **变更摘要**:
+ - `POST /api/drama/episodes/{id}/fragments` 新建无 id 分镜后,不再 `asset_references.clear()` 触发 async lazy load
+ - 改为 `replace_fragment_asset_refs`:已加载集合只删多余/只补缺失(避免 `uq_drama_frag_asset` 同键先插后删);未加载才 SQL 清库;`load_episode_fragments` 加 `populate_existing`
+- **验证**:
+ - [x] 本机 `http://127.0.0.1:8000/api/health` → `ok:true`,task_runtime healthy
+ - [x] 前台首页 200(`www.printfilm.com`)
+ - [x] admin 首页 200(`admin.printfilm.com`)
+ - [x] 远端 `py_compile` 通过;helper 含 `set_committed_value` / `populate_existing`
+ - [ ] 前台分集 `#609` 再点保存(含第 8 镜无 id)应 200
+- **备注 / 回滚**:
+ - `cp -a /opt/ai_movie/backend/app/api/drama/episodes.py.bak-20260912-savefrags /opt/ai_movie/backend/app/api/drama/episodes.py && cp -a /opt/ai_movie/backend/app/services/drama/access.py.bak-20260912-savefrags /opt/ai_movie/backend/app/services/drama/access.py && systemctl restart ai-movie-api`
+
+## 2026-09-12 16:21 · 分镜自动重切保护顺序 + 挂回 #609 成片(热修)
+
+- **操作者**:Agent
+- **方式**:SSH 热修(改 `seed.py` + `systemctl restart ai-movie-api` + 数据挂回)
+- **范围**:api / 数据
+- **变更摘要**:
+ - 线上 `_episode_should_replace_fragments` 先判断成片/手改保护,再判断是否场记原文;避免进分镜页 `seed_from_script` 把电影感手写分镜整集覆盖
+ - 项目 `#424` 分集 `#609`「被贬成仙美食图鉴」第 1 镜(`18274`)挂回旧成片 `18261`(`shot_18261_1789197049.mp4`);原 `18274` 成片写入 `video_versions`
+- **验证**:
+ - [x] `https://www.printfilm.com/api/health` → `ok:true`,task_runtime healthy
+ - [x] 前台首页 200(`www.printfilm.com`)
+ - [x] admin 首页 200(`admin.printfilm.com`)
+ - [x] 线上函数顺序:`_episode_has_protected_fragments` 在 `is_raw_screenplay_fragment` 之前
+ - [x] `18274.video` 指向 OSS `shot_18261_1789197049.mp4`,HEAD 200
+- **备注 / 回滚**:
+ - 代码:`cp -a /opt/ai_movie/backend/app/services/drama/seed.py.bak-20260912 /opt/ai_movie/backend/app/services/drama/seed.py && systemctl restart ai-movie-api`
+ - 成片:在分镜页把第 1 镜切回历史版本(热修时已归档)
diff --git a/docs/releases/README.md b/docs/releases/README.md
index 794a421..9c9db5a 100644
--- a/docs/releases/README.md
+++ b/docs/releases/README.md
@@ -33,6 +33,7 @@
| 日期 | 摘要 | 文件 |
|------|------|------|
+| 2026-09-12 | 保存分镜新建镜 MissingGreenlet;分镜保护顺序 + 挂回 #609 成片;杭州热修 | [2026-09-12.md](./2026-09-12.md) |
| 2026-09-08 | Seedance 视频文案策略 CG 重试;杭州热修 | [2026-09-08.md](./2026-09-08.md) |
| 2026-09-07 | 科普分阶段计费;杭州全量 | [2026-09-07.md](./2026-09-07.md) |
| 2026-09-07 | 分镜重试上限 + Seedream CG 策略重试;杭州全量 | [2026-09-07.md](./2026-09-07.md) |
diff --git a/frontend/public/image-styles/ghibli-handdrawn-anime.jpg b/frontend/public/image-styles/ghibli-handdrawn-anime.jpg
new file mode 100644
index 0000000..76b749e
Binary files /dev/null and b/frontend/public/image-styles/ghibli-handdrawn-anime.jpg differ
diff --git a/frontend/public/image-styles/ghibli-handdrawn-anime.svg b/frontend/public/image-styles/ghibli-handdrawn-anime.svg
new file mode 100644
index 0000000..74cd958
--- /dev/null
+++ b/frontend/public/image-styles/ghibli-handdrawn-anime.svg
@@ -0,0 +1,14 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
+ <defs>
+ <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stop-color="#f4d7a3"/>
+ <stop offset="45%" stop-color="#8ec5c0"/>
+ <stop offset="100%" stop-color="#3d7a4a"/>
+ </linearGradient>
+ </defs>
+ <rect width="640" height="480" fill="url(#sky)"/>
+ <ellipse cx="480" cy="110" rx="90" ry="36" fill="#fff6e8" opacity="0.75"/>
+ <ellipse cx="160" cy="130" rx="70" ry="28" fill="#fff6e8" opacity="0.55"/>
+ <rect x="24" y="360" width="592" height="96" rx="12" fill="rgba(40,28,12,0.42)"/>
+ <text x="320" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="white">��(K�</text>
+</svg>
diff --git a/frontend/src/api.ts b/frontend/src/api.ts
index 45c7469..e2f9852 100644
--- a/frontend/src/api.ts
+++ b/frontend/src/api.ts
@@ -149,6 +149,7 @@ export type Project = {
voice_id?: string
character_bible?: string
bgm_lock?: string
+ subtitle_preset?: string
style_prompt?: string
character_prompt?: string
extra_prompt?: string
@@ -399,6 +400,8 @@ export const api = {
extra_prompt?: string
image_model?: string
video_model?: string
+ bgm_lock?: string
+ subtitle_preset?: string
cover_url?: string | null
},
) {
@@ -518,6 +521,31 @@ export const api = {
body: JSON.stringify(body),
})
},
+ createShot(projectId: number) {
+ return request<Shot>(`/api/projects/${projectId}/shots`, { method: 'POST' })
+ },
+ reorderShots(projectId: number, shotIds: number[]) {
+ return request<Project>(`/api/projects/${projectId}/shots/reorder`, {
+ method: 'POST',
+ body: JSON.stringify({ shot_ids: shotIds }),
+ })
+ },
+ async uploadShotImage(projectId: number, shotId: number, file: File) {
+ const token = localStorage.getItem('token')
+ const form = new FormData()
+ form.append('file', file)
+ const res = await fetch(`${API_BASE}/api/projects/${projectId}/shots/${shotId}/image`, {
+ 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
+ throw new Error(typeof detail === 'string' ? detail : '画面上传失败')
+ }
+ return res.json() as Promise<Project>
+ },
regenImage(projectId: number, shotId: number) {
return request<Project>(`/api/projects/${projectId}/shots/${shotId}/regen-image`, {
method: 'POST',
diff --git a/frontend/src/i18n/locales/en/pages.ts b/frontend/src/i18n/locales/en/pages.ts
index 3f0cb4f..ae4ce2f 100644
--- a/frontend/src/i18n/locales/en/pages.ts
+++ b/frontend/src/i18n/locales/en/pages.ts
@@ -354,7 +354,7 @@ export const enPages = {
ordering: 'Creating order…',
payNow: 'Top up',
billingTitle: 'How billing works',
- billing1: 'Storyboard, stills, voice, and AI video are billed from upstream token use',
+ billing1: 'Storyboard, stills, voice, and AI video are billed at TokenFree official cost (no markup)',
billing2: 'We pre-authorize an estimate, then settle the real usage (refund or top-up the difference)',
billing3: 'Image+narration is cheaper; turning on AI motion video costs more',
whyTitle: 'Why metered billing',
@@ -394,6 +394,7 @@ export const enPages = {
runningNow: 'Generating now',
noTask: 'No active jobs',
statDone: 'Done',
+ statPublished: 'Published',
statDuration: 'This month',
durationSoon: 'Usage stats coming soon',
tabs: {
diff --git a/frontend/src/i18n/locales/en/shell.ts b/frontend/src/i18n/locales/en/shell.ts
index 22adafe..a7bf11b 100644
--- a/frontend/src/i18n/locales/en/shell.ts
+++ b/frontend/src/i18n/locales/en/shell.ts
@@ -200,8 +200,11 @@ export const enShell = {
PENDING: 'Waiting',
IMAGE_READY: 'Image ready',
VIDEO_READY: 'Video ready',
- AUDIO_READY: 'Done',
+ AUDIO_READY: 'Audio ready',
DONE: 'Done',
FAILED: 'Failed',
+ GENERATING: 'Generating',
+ WAIT_IMAGE: 'Need image',
+ WAIT_VIDEO: 'Need clip',
},
} as const
diff --git a/frontend/src/i18n/locales/zh/pages.ts b/frontend/src/i18n/locales/zh/pages.ts
index b0bfa32..2ce0e35 100644
--- a/frontend/src/i18n/locales/zh/pages.ts
+++ b/frontend/src/i18n/locales/zh/pages.ts
@@ -347,7 +347,7 @@ export const zhPages = {
ordering: '下单中…',
payNow: '立即充值',
billingTitle: '计费说明',
- billing1: '拆分镜、出图、配音、AI 视频分别按上游 token 用量计费',
+ billing1: '拆分镜、出图、配音、AI 视频按 TokenFree 官方成本计费(不加价)',
billing2: '开始生成时预扣估算金额,结束后按实际用量结算(多退少补)',
billing3: '图文模式成本更低;开启 AI 动态视频时消耗更高',
whyTitle: '为什么按量计费',
@@ -387,6 +387,7 @@ export const zhPages = {
runningNow: '正在生成中',
noTask: '暂无任务',
statDone: '已完成',
+ statPublished: '已发布',
statDuration: '本月时长',
durationSoon: '额度统计即将推出',
tabs: {
diff --git a/frontend/src/i18n/locales/zh/shell.ts b/frontend/src/i18n/locales/zh/shell.ts
index 9bf4f20..cb5e79a 100644
--- a/frontend/src/i18n/locales/zh/shell.ts
+++ b/frontend/src/i18n/locales/zh/shell.ts
@@ -199,8 +199,11 @@ export const zhShell = {
PENDING: '等待中',
IMAGE_READY: '图已生成',
VIDEO_READY: '视频已生成',
- AUDIO_READY: '已完成',
+ AUDIO_READY: '配音已生成',
DONE: '已完成',
FAILED: '失败',
+ GENERATING: '生成中',
+ WAIT_IMAGE: '待出图',
+ WAIT_VIDEO: '待出视频',
},
} as const
diff --git a/frontend/src/lib/dramaImageStyles.ts b/frontend/src/lib/dramaImageStyles.ts
index f18b88a..bd10552 100644
--- a/frontend/src/lib/dramaImageStyles.ts
+++ b/frontend/src/lib/dramaImageStyles.ts
@@ -17,6 +17,7 @@ export const IMAGE_STYLE_IDS = [
'neon-cyberpunk-film',
'90s-rural-china-film',
'cgi-3d-animation',
+ 'ghibli-handdrawn-anime',
'tezuka-era-cartoon',
'shanghai-animation',
'pixel-art',
@@ -42,6 +43,7 @@ export const IMAGE_STYLE_OPTIONS: Array<{ id: ImageStyleId; label: string }> = [
{ id: 'neon-cyberpunk-film', label: '霓虹赛博电影' },
{ id: '90s-rural-china-film', label: '90年代中国农村电影' },
{ id: 'cgi-3d-animation', label: '3D 动画' },
+ { id: 'ghibli-handdrawn-anime', label: '宫崎骏气质手绘' },
{ id: 'tezuka-era-cartoon', label: '手冢治虫时代卡通画风' },
{ id: 'shanghai-animation', label: '上美画风' },
{ id: 'pixel-art', label: '像素风' },
diff --git a/frontend/src/lib/dramaStoryboardNav.ts b/frontend/src/lib/dramaStoryboardNav.ts
index 311a2d6..8d8a5c0 100644
--- a/frontend/src/lib/dramaStoryboardNav.ts
+++ b/frontend/src/lib/dramaStoryboardNav.ts
@@ -1,12 +1,24 @@
/** 分镜入口:跳过中间分集页,直达首集编辑 */
-import { dramaApi } from '../api/drama'
+import { dramaApi, type DramaEpisode } from '../api/drama'
+
+/** 已有分集只读取;没有分集才按剧本切一次。force 才走重切。 */
+export async function loadDramaEpisodes(
+ projectId: number,
+ force = false,
+): Promise<DramaEpisode[]> {
+ if (!force) {
+ const existing = await dramaApi.listEpisodes(projectId)
+ if (existing.length) return existing
+ }
+ return dramaApi.seedEpisodes(projectId, force)
+}
/** 确保已切分并返回首集(或指定集)编辑路径;无分集则回大纲 */
export async function resolveStoryboardPath(
projectId: number,
preferredEpisodeId?: number | null,
): Promise<string> {
- const rows = await dramaApi.seedEpisodes(projectId, false)
+ const rows = await loadDramaEpisodes(projectId, false)
if (preferredEpisodeId && rows.some((r) => r.id === preferredEpisodeId)) {
return `/drama/projects/${projectId}/episodes/${preferredEpisodeId}`
}
diff --git a/frontend/src/lib/legalContent.ts b/frontend/src/lib/legalContent.ts
index 8d17af8..baa2c81 100644
--- a/frontend/src/lib/legalContent.ts
+++ b/frontend/src/lib/legalContent.ts
@@ -49,7 +49,7 @@ export const LEGAL_DOCS: Record<'terms' | 'privacy', LegalDoc> = {
{
title: '4. 计费与充值',
bullets: [
- '生成类任务按上游 token 或约定单价计费;开始任务时可能预扣估算金额,结束后按实际用量结算(多退少补)。',
+ '生成类任务按 TokenFree 官方成本计费(与上游一致,不再加价);开始任务时可能预扣估算金额,结束后按实际用量结算(多退少补)。',
'充值通过支付宝、微信支付等渠道完成,到账以系统记录为准。',
'除法律法规另有规定或本平台明确约定外,已到账的充值余额一般不予退款。',
'若因系统故障导致重复扣款或未到账,请保留订单号并联系客服核实处理。',
diff --git a/frontend/src/lib/segmentDuration.ts b/frontend/src/lib/segmentDuration.ts
index f1e1a80..a66227b 100644
--- a/frontend/src/lib/segmentDuration.ts
+++ b/frontend/src/lib/segmentDuration.ts
@@ -15,14 +15,14 @@ export const SHOT_DURATION_MAX = 30
/** 时长快捷选项(秒) */
export const SEGMENT_DURATION_PRESETS = [4, 6, 8, 10, 12] as const
-/** 与后端一致的字幕 cue */
-export const SUBTITLE_CUE = '【字幕:全程简体中文字幕,旁白逐句同步烧录】'
+/** 与后端一致的字幕 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}口播内容…`
+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
diff --git a/frontend/src/lib/status.ts b/frontend/src/lib/status.ts
index 5773cab..346b36c 100644
--- a/frontend/src/lib/status.ts
+++ b/frontend/src/lib/status.ts
@@ -90,14 +90,116 @@ export const SHOT_STATUS_CN: Record<string, string> = new Proxy(
},
)
+// 兼容旧调用:直接翻译 shot.status
export function shotStatusLabel(status: string) {
return SHOT_STATUS_CN[status] || STATUS_CN[status] || status
}
+// 旧「镜头终态」判断;分镜表请用 shotDisplayDone
export function shotIsDone(status: string) {
return ['AUDIO_READY', 'VIDEO_READY', 'DONE', 'IMAGE_READY'].includes(status)
}
+/** 分镜表按素材完备度展示,不盲信 shot.status(AUDIO_READY 只代表配音) */
+export type ShotDisplayKind =
+ | 'failed'
+ | 'generating'
+ | 'wait_image'
+ | 'wait_video'
+ | 'image_ready'
+ | 'video_ready'
+
+export type ShotAssetLike = {
+ status?: string | null
+ image_url?: string | null
+ video_url?: string | null
+}
+
+/*
+ * SHOT_TASK_ACTIVE 任务中心进行中状态
+ * PROJECT_WIDE_TASKS 整片占用,单镜生成需避开
+ */
+const SHOT_TASK_ACTIVE = [
+ 'pending',
+ 'leased',
+ 'running',
+ 'awaiting_poll',
+ 'awaiting_review',
+ 'cancel_requested',
+]
+const PROJECT_WIDE_TASKS = new Set([
+ 'project_pipeline',
+ 'project_compose_only',
+ 'project_regen_audio',
+ 'shot_regen_audio',
+])
+
+/** 按图/视频是否齐推断单镜展示态 */
+export function shotDisplayKind(
+ shot: ShotAssetLike,
+ opts?: { pipelineMode?: string | null; generating?: boolean },
+): ShotDisplayKind {
+ if (opts?.generating) return 'generating'
+ if (shot.status === 'FAILED') return 'failed'
+ if (!shot.image_url) return 'wait_image'
+ const full = opts?.pipelineMode !== 'image_text'
+ if (full && !shot.video_url) return 'wait_video'
+ if (full) return 'video_ready'
+ return 'image_ready'
+}
+
+/** 该镜素材是否已齐(静图看图,全流程看视频) */
+export function shotDisplayDone(kind: ShotDisplayKind) {
+ return kind === 'image_ready' || kind === 'video_ready'
+}
+
+/** 分镜表 / CSV 用的素材态文案 */
+export function shotDisplayLabel(kind: ShotDisplayKind) {
+ const key = {
+ failed: 'FAILED',
+ generating: 'GENERATING',
+ wait_image: 'WAIT_IMAGE',
+ wait_video: 'WAIT_VIDEO',
+ image_ready: 'IMAGE_READY',
+ video_ready: 'VIDEO_READY',
+ }[kind]
+ return SHOT_STATUS_CN[key] || key
+}
+
+type TaskLike = {
+ status: string
+ task_type?: string | null
+ shot_id?: number | null
+ cancel_requested?: boolean | null
+}
+
+/** 整片流水线 / 合成 / 整片配音进行中 */
+export function isProjectWideBusy(project: {
+ status?: string
+ active_tasks?: TaskLike[] | null
+}) {
+ const tasks = project.active_tasks
+ if (Array.isArray(tasks)) {
+ return tasks.some(
+ (task) =>
+ SHOT_TASK_ACTIVE.includes(task.status) && PROJECT_WIDE_TASKS.has(task.task_type || ''),
+ )
+ }
+ return isRunning(project.status || '')
+}
+
+/** 该镜是否有进行中的单镜任务 */
+export function isShotGenerating(
+ project: { active_tasks?: TaskLike[] | null } | null | undefined,
+ shotId: number,
+) {
+ return Boolean(
+ project?.active_tasks?.some(
+ (task) => task.shot_id === shotId && SHOT_TASK_ACTIVE.includes(task.status),
+ ),
+ )
+}
+
export function formatMmSs(seconds: number) {
const s = Math.max(0, Math.round(seconds || 0))
const m = Math.floor(s / 60)
@@ -105,17 +207,98 @@ export function formatMmSs(seconds: number) {
return `${String(m).padStart(2, '0')}:${String(r).padStart(2, '0')}`
}
-export const CREATE_STEPS = [
- { key: 'template', label: '选择模板' },
- { key: 'content', label: '输入内容' },
- { key: 'style', label: '风格配置' },
- { key: 'generate', label: '开始生成' },
+/** 科普全链路步骤:建项 / 风格 / 分镜台共用 */
+export const KEPU_STEPS = [
+ { key: 'topic', label: '选题' },
+ { key: 'style', label: '风格' },
+ { key: 'confirm', label: '确认分镜' },
+ { key: 'assets', label: '画面与配音' },
+ { key: 'videos', label: '镜头视频' },
+ { key: 'compose', label: '合成预览' },
]
-export const BOARD_STEPS = [
- { key: 'theme', label: '输入主题' },
- { key: 'smart', label: '智能生成' },
- { key: 'preset', label: '精细画面' },
- { key: 'board', label: '生成分镜' },
- { key: 'compose', label: '成片预览' },
-]
+export const CREATE_STEPS = KEPU_STEPS
+export const BOARD_STEPS = KEPU_STEPS
+
+/** 静图成片跳过「镜头视频」步 */
+export function kepuSteps(pipelineMode?: string | null) {
+ if (pipelineMode === 'image_text') {
+ return KEPU_STEPS.filter((s) => s.key !== 'videos')
+ }
+ return KEPU_STEPS
+}
+
+export type KepuWizardPage = 'create' | 'style' | 'board'
+
+export type KepuBillingPhase = 'script' | 'assets' | 'videos' | 'compose'
+
+/** 与后端 resolve_kepu_billing_phase 对齐(前端不做近静音文件检测)。 */
+export function kepuBillingPhase(project: {
+ pipeline_mode?: string | null
+ shots?: Array<{ image_url?: string | null; audio_url?: string | null; video_url?: string | null }>
+}): KepuBillingPhase {
+ const shots = project.shots || []
+ if (!shots.length) return 'script'
+ const full = project.pipeline_mode !== 'image_text'
+ const needImages = shots.some((s) => !s.image_url)
+ const needAudio = !full && shots.some((s) => !s.audio_url)
+ if (needImages || needAudio) return 'assets'
+ if (full && shots.some((s) => !s.video_url)) return 'videos'
+ return 'compose'
+}
+
+export function shotsByNo<T extends { shot_no: number }>(shots: T[] | null | undefined): T[] {
+ return [...(shots || [])].sort((a, b) => a.shot_no - b.shot_no)
+}
+
+/**
+ * 当前步骤下标;分镜台跟 script / assets / videos / compose 对齐。
+ */
+export function kepuStepIndex(
+ page: KepuWizardPage,
+ project?: {
+ status: string
+ pipeline_mode?: string | null
+ final_video_url?: string | null
+ shots?: Array<{ image_url?: string | null; audio_url?: string | null; video_url?: string | null }>
+ } | null,
+): number {
+ const steps = kepuSteps(project?.pipeline_mode)
+ const idx = (key: string) => {
+ const n = steps.findIndex((s) => s.key === key)
+ return n >= 0 ? n : 0
+ }
+ if (page === 'create') return idx('topic')
+ if (page === 'style') return idx('style')
+ if (!project) return idx('confirm')
+ const status = effectiveStatus(project)
+ const shots = project.shots || []
+ if (isRunning(status)) {
+ if (status === 'VIDEOING') return idx('videos')
+ if (['IMAGING', 'AUDIOING', 'PARALLEL_ASSETS'].includes(status)) return idx('assets')
+ if (['COMPOSING', 'AUDITING'].includes(status)) return idx('compose')
+ }
+ if (project.final_video_url && status === 'DONE') return idx('compose')
+ const phase = kepuBillingPhase(project)
+ if (phase === 'compose') return idx('compose')
+ if (phase === 'videos') return idx('videos')
+ if (phase === 'assets') return idx('assets')
+ if (status === 'DRAFT' && shots.length === 0) return idx('style')
+ return idx('confirm')
+}
+
+/** 分镜台主按钮旁:本步做什么、是否预扣 */
+export function kepuPhaseHint(project: {
+ status: string
+ pipeline_mode?: string | null
+ shots?: Array<{ image_url?: string | null; audio_url?: string | null; video_url?: string | null }>
+}): string {
+ if (isRunning(effectiveStatus(project))) {
+ return '生成进行中,可在右侧查看各阶段进度。'
+ }
+ const phase = kepuBillingPhase(project)
+ if (phase === 'script') return '先在风格页点「生成故事板」,本步只拆分镜脚本(预扣文字模型)。'
+ if (phase === 'assets') return '确认旁白与画面后开始生成:按镜头依次出图(后镜参考上一镜)+ 整片配音。'
+ if (phase === 'videos') return '画面与配音已齐。下一步按镜头依次出视频,后镜参考上一镜尾帧。'
+ return '素材已齐。拼接成片走后期合成(叠旁白字幕与配乐,扣费很少)。'
+}
diff --git a/frontend/src/pages/HistoryPage.tsx b/frontend/src/pages/HistoryPage.tsx
index a0a453a..68f780d 100644
--- a/frontend/src/pages/HistoryPage.tsx
+++ b/frontend/src/pages/HistoryPage.tsx
@@ -10,7 +10,6 @@ import StatCard from '../components/ui/StatCard'
import {
IconClapper,
IconClock,
- IconCopy,
IconDownload,
IconEdit,
IconEye,
@@ -321,9 +320,9 @@ export default function HistoryPage() {
icon={<IconSend size={18} />}
/>
<StatCard
- label={t('history.statDuration')}
- value="—"
- trend={t('history.durationSoon')}
+ label={t('history.statPublished')}
+ value={stats.published}
+ trend="—"
icon={<IconClock size={18} />}
/>
</div>
@@ -466,10 +465,6 @@ export default function HistoryPage() {
<IconDownload size={14} />
{busyId === p.id ? t('common.downloading') : t('common.download')}
</button>
- <button type="button" className="pf-btn-text" disabled title={t('common.comingSoon')}>
- <IconCopy size={14} />
- {t('common.copy')}
- </button>
<button
type="button"
className="pf-icon-btn danger"
diff --git a/frontend/src/pages/drama/DramaImageStyleModal.tsx b/frontend/src/pages/drama/DramaImageStyleModal.tsx
index 1c6f63a..b64cc3b 100644
--- a/frontend/src/pages/drama/DramaImageStyleModal.tsx
+++ b/frontend/src/pages/drama/DramaImageStyleModal.tsx
@@ -79,6 +79,10 @@ export function DramaImageStyleModal({
)}
<Modal open={open} onClose={() => setOpen(false)} title={title} size="md" className="drama-style-modal">
+ {/* 封面即画风参考图,避免用户以为只是缩略预览 */}
+ <p className="drama-style-modal-hint">
+ 封面图会作为画风参考一并提交。模型只借色调、笔触和光影,不会照抄封面里的人物或构图。
+ </p>
<DramaImageStyleCardGrid value={value} onChange={select} noneLabel="无风格" />
</Modal>
</>
diff --git a/frontend/src/pages/drama/EpisodesStep.tsx b/frontend/src/pages/drama/EpisodesStep.tsx
index 08367a2..df91db9 100644
--- a/frontend/src/pages/drama/EpisodesStep.tsx
+++ b/frontend/src/pages/drama/EpisodesStep.tsx
@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom'
import { Clapperboard, Film, Layers, Sparkles, Wand2 } from 'lucide-react'
import { dramaApi, resolveDramaMediaUrl, type DramaEpisode } from '../../api/drama'
import { dialog } from '../../lib/dialog'
+import { loadDramaEpisodes } from '../../lib/dramaStoryboardNav'
import { readEpisodeSubtitleMode, subtitleModeUsesModelOutput } from '../../lib/dramaSubtitleBoard'
import { FragmentPlanSkillModal } from '../../components/drama/FragmentPlanSkillModal'
import { readFragmentGenerationStatus } from './dramaEpisodeEditUtils'
@@ -104,8 +105,9 @@ export function EpisodesStep({ projectId, onError }: EpisodesStepProps) {
seeded.current = false
}, [projectId])
+ // 进页只读已有分集;force 才按剧本重切
async function loadEpisodes(force = false) {
- const rows = await dramaApi.seedEpisodes(projectId, force)
+ const rows = await loadDramaEpisodes(projectId, force)
setEpisodes(rows)
return rows
}
diff --git a/frontend/src/pages/drama/drama.css b/frontend/src/pages/drama/drama.css
index 36bd1f3..a9f6c05 100644
--- a/frontend/src/pages/drama/drama.css
+++ b/frontend/src/pages/drama/drama.css
@@ -384,6 +384,13 @@
padding-top: 0.5rem;
}
+.drama-style-modal-hint {
+ margin: 0 0 12px;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--drama-muted);
+}
+
.drama-style-modal-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
diff --git a/frontend/src/pages/studio/CreateProjectPage.tsx b/frontend/src/pages/studio/CreateProjectPage.tsx
index 0453be5..818ae5d 100644
--- a/frontend/src/pages/studio/CreateProjectPage.tsx
+++ b/frontend/src/pages/studio/CreateProjectPage.tsx
@@ -6,10 +6,9 @@ import BillingErrorNotice from '../../components/billing/BillingErrorNotice'
import AppShell from '../../components/layout/AppShell'
import Stepper from '../../components/ui/Stepper'
import PillTabs from '../../components/ui/PillTabs'
-import ComingSoon from '../../components/ui/ComingSoon'
import { IconChevronLeft, IconRefresh, IconSparkles } from '../../components/ui/Icons'
import { CATEGORY_ORDER } from '../../lib/categories'
-import { CREATE_STEPS } from '../../lib/status'
+import { kepuStepIndex, kepuSteps } from '../../lib/status'
type Inspiration = {
title: string
@@ -198,7 +197,6 @@ export default function CreateProjectPage() {
const selected = templates.find((t) => t.id === templateId)
const sourceType = inputTab === '粘贴完整文案' ? 'script' : 'theme'
- const disabledInput = inputTab === '导入文章链接' || inputTab === '上传文档'
const inspTotal = Math.ceil(INSPIRATION_POOL.length / PAGE_SIZE)
const inspirations = INSPIRATION_POOL.slice(inspPage * PAGE_SIZE, inspPage * PAGE_SIZE + PAGE_SIZE)
@@ -220,10 +218,6 @@ export default function CreateProjectPage() {
}
async function aiExpand() {
- if (disabledInput) {
- setError('该输入方式即将推出,请使用一句话主题或粘贴文案')
- return
- }
const seed = sourceText.trim() || title.trim() || '人工智能如何改变生活'
setAiBusy(true)
setError('')
@@ -246,10 +240,6 @@ export default function CreateProjectPage() {
setError('请选择模板并填写主题内容')
return
}
- if (disabledInput) {
- setError('该输入方式即将推出,请使用一句话主题或粘贴文案')
- return
- }
setBusy(true)
setError('')
try {
@@ -289,7 +279,7 @@ export default function CreateProjectPage() {
</button>
<h1 className="pf-page-title">创建项目</h1>
</div>
- <Stepper steps={CREATE_STEPS} current={1} doneThrough={0} />
+ <Stepper steps={kepuSteps()} current={kepuStepIndex('create')} doneThrough={-1} />
</div>
</header>
@@ -318,15 +308,12 @@ export default function CreateProjectPage() {
</button>
))}
</div>
- <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" style={{ marginTop: '0.75rem' }} disabled>
- 加载更多模板 <ComingSoon />
- </button>
</aside>
<section className="pf-create-col">
<h3>输入内容</h3>
<div className="pf-input-tabs">
- {['一句话主题', '粘贴完整文案', '导入文章链接', '上传文档'].map((tab) => (
+ {['一句话主题', '粘贴完整文案'].map((tab) => (
<button
key={tab}
type="button"
@@ -334,12 +321,6 @@ export default function CreateProjectPage() {
onClick={() => setInputTab(tab)}
>
{tab}
- {(tab === '导入文章链接' || tab === '上传文档') && (
- <>
- {' '}
- <ComingSoon />
- </>
- )}
</button>
))}
</div>
@@ -368,7 +349,7 @@ export default function CreateProjectPage() {
<button
type="button"
className="pf-btn pf-btn-ai pf-btn-sm pf-btn-icon"
- disabled={aiBusy || busy || disabledInput}
+ disabled={aiBusy || busy}
onClick={aiExpand}
>
<IconSparkles size={14} />
@@ -387,13 +368,10 @@ export default function CreateProjectPage() {
setTitle(deriveTitle(next))
}
}}
- disabled={disabledInput}
placeholder={
- disabledInput
- ? '该方式即将推出'
- : sourceType === 'theme'
- ? '例如:黑洞是如何形成的?用通俗方式讲清引力与时空'
- : '粘贴或 AI 生成完整口播文案…'
+ sourceType === 'theme'
+ ? '例如:黑洞是如何形成的?用通俗方式讲清引力与时空'
+ : '粘贴或 AI 生成完整口播文案…'
}
/>
{sourceType === 'theme' ? (
@@ -486,14 +464,14 @@ export default function CreateProjectPage() {
type="button"
className="pf-btn pf-btn-ghost pf-btn-block pf-btn-sm pf-btn-icon"
style={{ marginTop: '0.55rem' }}
- disabled={aiBusy || busy || disabledInput}
+ disabled={aiBusy || busy}
onClick={aiExpand}
>
<IconSparkles size={14} />
{aiBusy ? 'AI 生成中…' : '不够完整?让 AI 帮你写'}
</button>
<p className="pf-muted" style={{ fontSize: '0.78rem', marginTop: '0.5rem' }}>
- 下一步可自定义风格、画面与配音。
+ 画风已随模板带上。下一步确认配音、字幕与成片方式。
</p>
</aside>
</div>
diff --git a/frontend/src/pages/studio/EditorPage.tsx b/frontend/src/pages/studio/EditorPage.tsx
index 454f061..c340007 100644
--- a/frontend/src/pages/studio/EditorPage.tsx
+++ b/frontend/src/pages/studio/EditorPage.tsx
@@ -1,11 +1,12 @@
-import { useEffect, useMemo, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { api } from '../../api'
import type { Project, Shot } from '../../api'
import BillingErrorNotice from '../../components/billing/BillingErrorNotice'
import AppShell from '../../components/layout/AppShell'
import ComingSoon from '../../components/ui/ComingSoon'
-import { STATUS_CN } from '../../lib/status'
+import { STATUS_CN, shotsByNo } from '../../lib/status'
+import { downloadSingleVideo } from '../../lib/clientDownload'
const PANEL_TABS = ['文案', '画面', '配音', '转场'] as const
@@ -19,6 +20,7 @@ export default function EditorPage() {
const [narration, setNarration] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
+ const shotFileRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (!localStorage.getItem('token')) {
@@ -42,10 +44,12 @@ export default function EditorPage() {
.catch((err) => setError(err instanceof Error ? err.message : '加载失败'))
}, [nav, projectId])
+ const orderedShots = useMemo(() => shotsByNo(project?.shots), [project?.shots])
const shot: Shot | undefined = useMemo(
- () => project?.shots.find((s) => s.id === activeShotId),
- [project, activeShotId],
+ () => orderedShots.find((s) => s.id === activeShotId),
+ [orderedShots, activeShotId],
)
+ const shotIndex = shot ? orderedShots.findIndex((s) => s.id === shot.id) : -1
const totalDuration = useMemo(
() => (project?.shots || []).reduce((s, x) => s + (Number(x.duration) || 0), 0),
@@ -84,6 +88,77 @@ export default function EditorPage() {
}
}
+ /** 在片尾追加一镜,并选中新建镜头。 */
+ async function addShot() {
+ if (!project) return
+ setBusy(true)
+ setError('')
+ try {
+ const created = await api.createShot(project.id)
+ const next = await api.getProject(project.id)
+ setProject(next)
+ const s = next.shots.find((x) => x.id === created.id)
+ if (s) selectShot(s)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '添加镜头失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ /** 将当前镜与相邻镜对调顺序。 */
+ async function moveShot(delta: number) {
+ if (!project || !shot) return
+ const ordered = orderedShots
+ const i = ordered.findIndex((s) => s.id === shot.id)
+ const j = i + delta
+ if (i < 0 || j < 0 || j >= ordered.length) return
+ const ids = ordered.map((s) => s.id)
+ ;[ids[i], ids[j]] = [ids[j], ids[i]]
+ setBusy(true)
+ setError('')
+ try {
+ setProject(await api.reorderShots(project.id, ids))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '调序失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ /** 上传本镜静帧,替换后需重出视频。 */
+ async function onShotImageFile(file: File | null) {
+ if (!project || !shot || !file) return
+ setBusy(true)
+ setError('')
+ try {
+ setProject(await api.uploadShotImage(project.id, shot.id, file))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '上传画面失败')
+ } finally {
+ setBusy(false)
+ if (shotFileRef.current) shotFileRef.current.value = ''
+ }
+ }
+
+ /** 下载已合成的成片。 */
+ async function exportFilm() {
+ if (!project?.final_video_url) return
+ setBusy(true)
+ setError('')
+ try {
+ await downloadSingleVideo({
+ projectId: project.id,
+ title: project.title,
+ url: api.assetUrl(project.final_video_url, project.updated_at),
+ })
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '导出失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
async function regenAudio() {
if (!project || !shot) return
setBusy(true)
@@ -170,8 +245,13 @@ export default function EditorPage() {
>
预览播放
</button>
- <button type="button" className="pf-btn pf-btn-lime pf-btn-sm" disabled>
- 导出视频 <ComingSoon />
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime pf-btn-sm"
+ disabled={busy || !project.final_video_url}
+ onClick={() => void exportFilm()}
+ >
+ 导出视频
</button>
</div>
</div>
@@ -184,11 +264,11 @@ export default function EditorPage() {
<aside>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.75rem' }}>
<strong>场景列表</strong>
- <button type="button" className="pf-link" disabled>
- + 添加镜头 <ComingSoon />
+ <button type="button" className="pf-link" disabled={busy} onClick={() => void addShot()}>
+ + 添加镜头
</button>
</div>
- {project.shots.map((s) => (
+ {orderedShots.map((s) => (
<button
key={s.id}
type="button"
@@ -220,9 +300,24 @@ export default function EditorPage() {
.toString()
.padStart(2, '0')}
</p>
- <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm pf-btn-block" disabled>
- 调整顺序 <ComingSoon />
- </button>
+ <div style={{ display: 'flex', gap: 8, marginTop: '0.75rem' }}>
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-sm"
+ disabled={busy || !shot || shotIndex <= 0}
+ onClick={() => void moveShot(-1)}
+ >
+ 上移
+ </button>
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-sm"
+ disabled={busy || !shot || shotIndex < 0 || shotIndex >= orderedShots.length - 1}
+ onClick={() => void moveShot(1)}
+ >
+ 下移
+ </button>
+ </div>
</aside>
<section>
@@ -230,9 +325,26 @@ export default function EditorPage() {
<strong>
{shot ? `镜头 ${shot.shot_no}` : '预览'} · {isPortrait ? '9:16' : '16:9'}
</strong>
- <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled={busy} onClick={regenImage}>
- 替换画面
- </button>
+ <div style={{ display: 'flex', gap: 8 }}>
+ <input
+ ref={shotFileRef}
+ type="file"
+ accept="image/jpeg,image/png,image/webp,image/gif"
+ hidden
+ onChange={(e) => void onShotImageFile(e.target.files?.[0] || null)}
+ />
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-sm"
+ disabled={busy || !shot}
+ onClick={() => shotFileRef.current?.click()}
+ >
+ 上传画面
+ </button>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled={busy} onClick={regenImage}>
+ AI 重绘
+ </button>
+ </div>
</div>
<div className={isPortrait ? 'pf-editor-preview portrait' : 'pf-editor-preview'}>
{shotVideo ? (
@@ -267,7 +379,7 @@ export default function EditorPage() {
paddingBottom: 4,
}}
>
- {project.shots.map((s) => (
+ {orderedShots.map((s) => (
<button
key={s.id}
type="button"
@@ -303,7 +415,7 @@ export default function EditorPage() {
fontSize: '0.9rem',
}}
>
- 拖拽素材到此处替换当前镜头画面 <ComingSoon />
+ 可用「上传画面」替换本镜图,或「AI 重绘」按提示词重生。
</div>
<div style={{ marginTop: '1rem' }}>
@@ -315,7 +427,7 @@ export default function EditorPage() {
))}
</div>
<p className="pf-muted" style={{ fontSize: '0.85rem' }}>
- 素材库与上传能力即将推出,当前可使用「替换画面」触发 AI 重绘。
+ 素材库即将推出。当前可用上方「上传画面」或「AI 重绘」替换本镜图。
</p>
</div>
</section>
@@ -382,7 +494,7 @@ export default function EditorPage() {
{tab === '画面' ? (
<>
<p className="pf-muted" style={{ fontSize: '0.88rem' }}>
- 当前镜头画面可通过 AI 重绘替换。时间线精修即将推出。
+ 可用预览区「上传画面」替换本镜图,或「AI 重绘」按提示词重生。
</p>
<button
type="button"
diff --git a/frontend/src/pages/studio/StoryboardPage.tsx b/frontend/src/pages/studio/StoryboardPage.tsx
index a359735..4d253cf 100644
--- a/frontend/src/pages/studio/StoryboardPage.tsx
+++ b/frontend/src/pages/studio/StoryboardPage.tsx
@@ -20,12 +20,19 @@ import { dialog } from '../../lib/dialog'
import { handleBillingError } from '../../lib/billingError'
import BillingErrorNotice from '../../components/billing/BillingErrorNotice'
import {
- BOARD_STEPS,
effectiveStatus,
formatMmSs,
isRunning,
- shotIsDone,
- shotStatusLabel,
+ kepuBillingPhase,
+ kepuPhaseHint,
+ kepuStepIndex,
+ kepuSteps,
+ isProjectWideBusy,
+ isShotGenerating,
+ shotsByNo,
+ shotDisplayDone,
+ shotDisplayKind,
+ shotDisplayLabel,
statusLabel,
} from '../../lib/status'
import {
@@ -56,7 +63,7 @@ function downloadStoryboardCsv(project: Project) {
s.narration,
scenePromptForDisplay(s.img_prompt || s.video_prompt || ''),
s.duration,
- shotStatusLabel(s.status),
+ shotDisplayLabel(shotDisplayKind(s, { pipelineMode: project.pipeline_mode })),
s.overlay_title || '',
]
.map(csvEscape)
@@ -94,23 +101,6 @@ function shotCaption(shot: Shot) {
return shot.narration
}
-function boardStepIndex(project: Project) {
- const status = project.status
- if (status === 'DRAFT') return 0
- if (status === 'SCRIPTING') return 1
- // 分镜已出,停留在「生成分镜」供确认修改
- if (status === 'SCRIPT_READY') return 3
- // 成片阶段:合成中 / 已完成;或素材已齐、等待合成
- if (['COMPOSING', 'AUDITING', 'DONE'].includes(status)) return 4
- if (status === 'VIDEO_READY') return 4
- if (status === 'IMAGE_READY' && project.pipeline_mode === 'image_text') return 4
- if (status === 'FAILED' || status === 'CANCELLED') {
- return project.final_video_url ? 4 : 3
- }
- // IMAGING / VIDEOING / AUDIOING / IMAGE_READY(full) 等仍在分镜生成
- return 3
-}
-
function hasActiveUnifiedTasks(project: Project | null): boolean {
const activeStatuses = ['pending', 'leased', 'running', 'awaiting_poll', 'awaiting_review']
return Boolean(
@@ -137,6 +127,8 @@ export default function StoryboardPage() {
const [project, setProject] = useState<Project | null>(null)
const [template, setTemplate] = useState<Template | null>(null)
const [busy, setBusy] = useState(false)
+ // busyShotIds 正在提交单镜图/视频的镜号,可并行,finally 只删自己
+ const [busyShotIds, setBusyShotIds] = useState<Set<number>>(() => new Set())
const [error, setError] = useState('')
const [editing, setEditing] = useState<Shot | null>(null)
const [editFocus, setEditFocus] = useState<string>('')
@@ -199,7 +191,7 @@ export default function StoryboardPage() {
}, [menuShotId])
const running = isProjectBusy(project)
- const step = project ? boardStepIndex(project) : 3
+ const step = project ? kepuStepIndex('board', project) : 2
const totalDuration = useMemo(
() => (project?.shots || []).reduce((s, x) => s + (Number(x.duration) || 0), 0),
[project?.shots],
@@ -213,7 +205,7 @@ export default function StoryboardPage() {
[editScriptText],
)
- const shots = project?.shots || []
+ const shots = useMemo(() => shotsByNo(project?.shots), [project?.shots])
/** 项目字段为空时回显模板默认(与后端 _effective_* 一致) */
const promptDefaults = useMemo(
() => (template ? defaultsFromTemplate(template) : null),
@@ -231,34 +223,20 @@ export default function StoryboardPage() {
}
}, [project, promptDefaults])
const isFullPipeline = project?.pipeline_mode !== 'image_text'
- const imgDone = shots.filter((s) => s.image_url).length
- const audDone = shots.filter((s) => s.audio_url).length
- const vidDone = shots.filter((s) => s.video_url).length
- const assetsReady =
- shots.length > 0 &&
- imgDone === shots.length &&
- (isFullPipeline || audDone === shots.length)
/**
* Full pipeline: need AI videos before compose.
* VIDEO_READY+ means video stage finished (incl. privacy skips without video_url).
* image_text skips the video stage entirely.
*/
- const videosReady =
- !isFullPipeline ||
- ['VIDEO_READY', 'COMPOSING', 'AUDITING', 'DONE', 'FAILED'].includes(project?.status || '') ||
- (shots.length > 0 && vidDone === shots.length)
- const readyToCompose = assetsReady && videosReady
- const needsVideos = isFullPipeline && assetsReady && !videosReady
- const needsScriptConfirm =
- Boolean(project) &&
- shots.length > 0 &&
- !assetsReady &&
- ['SCRIPT_READY', 'DRAFT', 'CANCELLED', 'FAILED'].includes(project!.status)
+ const phase = project ? kepuBillingPhase(project) : 'script'
+ const readyToCompose = phase === 'compose'
+ const needsVideos = phase === 'videos'
+ const needsScriptConfirm = phase === 'assets'
const hasFinal = Boolean(project?.final_video_url)
/** Primary CTA: confirm script → generate → (videos) → compose → preview */
const primaryAction: 'generate' | 'compose' | 'preview' | 'busy' = running
? 'busy'
- : hasFinal || project?.status === 'DONE'
+ : hasFinal
? 'preview'
: readyToCompose
? 'compose'
@@ -266,11 +244,13 @@ export default function StoryboardPage() {
const generateLabel = running
? '生成中…'
- : needsScriptConfirm
- ? '确认分镜,开始生成'
- : needsVideos
- ? '继续生成视频'
- : '继续生成'
+ : shots.length === 0
+ ? '去风格页生成分镜'
+ : needsScriptConfirm
+ ? '确认分镜,逐镜出图与配音'
+ : needsVideos
+ ? '逐镜出视频'
+ : '继续生成'
// 工作台进度:完整模式要镜头视频 + 外部 TTS,静图模式只配音合成
const progressItems = useMemo(() => {
@@ -334,6 +314,15 @@ export default function StoryboardPage() {
setProject(await api.generate(project.id))
} catch (err) {
const msg = err instanceof Error ? err.message : '继续生成失败'
+ if (msg.includes('合成成片')) {
+ try {
+ setError('')
+ setProject(await api.compose(project.id))
+ } catch (e2) {
+ setError(e2 instanceof Error ? e2.message : '合成失败')
+ }
+ return
+ }
setError(msg)
await handleBillingError(err, nav)
} finally {
@@ -488,32 +477,47 @@ export default function StoryboardPage() {
}
}
+ // 标记本镜请求进行中,不覆盖其它镜
+ function markShotBusy(shotId: number) {
+ setBusyShotIds((ids) => new Set(ids).add(shotId))
+ }
+
+ // 只清自己,避免并行请求互相冲掉锁
+ function markShotIdle(shotId: number) {
+ setBusyShotIds((ids) => {
+ const next = new Set(ids)
+ next.delete(shotId)
+ return next
+ })
+ }
+
async function regenImage(shot: Shot) {
if (!project) return
- setBusy(true)
+ markShotBusy(shot.id)
try {
setProject(await api.regenImage(project.id, shot.id))
} catch (err) {
- setError(err instanceof Error ? err.message : '重绘失败')
+ setError(err instanceof Error ? err.message : '生成画面失败')
} finally {
- setBusy(false)
+ markShotIdle(shot.id)
}
}
async function regenVideo(shot: Shot) {
if (!project) return
- setBusy(true)
+ markShotBusy(shot.id)
try {
setProject(await api.regenVideo(project.id, shot.id))
} catch (err) {
- setError(err instanceof Error ? err.message : '重生视频失败')
+ setError(err instanceof Error ? err.message : '生成视频失败')
} finally {
- setBusy(false)
+ markShotIdle(shot.id)
}
}
async function regenAudio(shot: Shot) {
if (!project) return
+ // 重配音会重写整片口播,锁整表避免两路抢写
setBusy(true)
try {
setProject(await api.regenAudio(project.id, shot.id))
@@ -708,7 +712,9 @@ export default function StoryboardPage() {
type="button"
className="pf-btn pf-btn-lime pf-btn-sm pf-btn-icon"
disabled={busy || running}
- onClick={continueGenerate}
+ onClick={() =>
+ shots.length === 0 ? nav(`/studio/${project.id}/style`) : void continueGenerate()
+ }
>
<IconPlay size={14} />
{generateLabel}
@@ -769,7 +775,14 @@ title="用当前镜头重新拼接"
</button>
</div>
</div>
- <Stepper steps={BOARD_STEPS} current={step} doneThrough={Math.max(0, step - 1)} />
+ <Stepper
+ steps={kepuSteps(project.pipeline_mode)}
+ current={step}
+ doneThrough={Math.max(0, step - 1)}
+ />
+ <p className="pf-muted" style={{ fontSize: '0.78rem', margin: '0.55rem 0 0' }}>
+ {kepuPhaseHint(project)}
+ </p>
</header>
{error ? <BillingErrorNotice message={error} /> : null}
@@ -885,7 +898,7 @@ title="用当前镜头重新拼接"
<div className="pf-prompt-panel">
<h4>内置提示词</h4>
<p className="pf-muted" style={{ fontSize: '0.72rem', margin: '0 0 0.45rem' }}>
- 默认来自管理后台模板。此处修改只覆盖本项目,后续重生成才生效。
+ 画风来自模板。角色是否出镜由 AI 按模板与主题决定;只有这里改过才覆盖本项目。
</p>
{(
[
@@ -982,7 +995,7 @@ title="用当前镜头重新拼接"
</p>
) : needsScriptConfirm ? (
<p className="pf-muted" style={{ margin: '0 0 1rem' }}>
- 分镜已就绪,请先检查旁白与画面描述。确认后先生成画面与配音,再按需生成镜头视频并合成成片(分阶段扣费)。
+ 分镜已就绪。点表格「旁白」改口播(会同步脚本并影响整片配音),点「逐段分镜」改画面节奏与 @duration。确认后按阶段预扣:画面+配音 → 镜头视频 → 合成。
</p>
) : null}
{project.shots.length === 0 ? null : (
@@ -990,22 +1003,33 @@ title="用当前镜头重新拼接"
<table className="pf-shot-table">
<thead>
<tr>
- <th>场景</th>
- <th>画面</th>
- <th>旁白/台词</th>
- <th>逐段分镜</th>
- <th>时长</th>
- <th>状态</th>
- <th>操作</th>
+ <th className="col-no">场景</th>
+ <th className="col-thumb">画面</th>
+ <th className="col-narr">旁白/台词</th>
+ <th className="col-seg">逐段分镜</th>
+ <th className="col-dur">时长</th>
+ <th className="col-status">状态</th>
+ <th className="col-ops">操作</th>
</tr>
</thead>
<tbody>
- {project.shots.map((shot) => {
- // Full pipeline: shot is "done" only after AI video (or privacy skip left image-only while project advanced)
- const done = isFullPipeline
- ? Boolean(shot.video_url) || shot.status === 'VIDEO_READY'
- : shotIsDone(shot.status) || Boolean(shot.image_url)
- const failed = shot.status === 'FAILED'
+ {shots.map((shot) => {
+ /*
+ * localBusy 本镜请求已发出、任务尚未回写
+ * shotGenerating 本镜任务或本地提交中
+ * pipelineLocked 整片流水线/配音占用
+ * displayKind / done / failed 按素材完备度展示
+ */
+ const localBusy = busyShotIds.has(shot.id)
+ const shotGenerating = isShotGenerating(project, shot.id) || localBusy
+ const pipelineLocked = isProjectWideBusy(project)
+ const rowBusy = busy || pipelineLocked || shotGenerating
+ const displayKind = shotDisplayKind(shot, {
+ pipelineMode: project.pipeline_mode,
+ generating: shotGenerating,
+ })
+ const done = shotDisplayDone(displayKind)
+ const failed = displayKind === 'failed'
const sceneTitle =
shot.overlay_title?.trim() || `场景 ${String(shot.shot_no).padStart(2, '0')}`
const narration = (shot.narration || '').trim()
@@ -1037,15 +1061,17 @@ title="用当前镜头重新拼接"
alt=""
/>
) : (
- <div className="pf-shot-thumb empty">生成中</div>
+ <div className="pf-shot-thumb empty">
+ {shotGenerating ? '生成中' : '待出图'}
+ </div>
)}
</button>
</td>
- <td>
+ <td className="col-narr">
<button
type="button"
className="pf-shot-narration pf-shot-editable"
- disabled={busy || running}
+ disabled={rowBusy}
title="点击编辑旁白与标题"
onClick={() => openShotEdit(shot, 'narration')}
>
@@ -1055,11 +1081,11 @@ title="用当前镜头重新拼接"
</span>
</button>
</td>
- <td>
+ <td className="col-seg">
<button
type="button"
className="pf-shot-desc pf-shot-editable"
- disabled={busy || running}
+ disabled={rowBusy}
title="点击编辑逐段分镜脚本"
onClick={() => openShotEdit(shot, 'segment_script')}
style={{ textAlign: 'left', width: '100%' }}
@@ -1117,7 +1143,7 @@ title="用当前镜头重新拼接"
.join(' ')}
>
{done && !failed ? <span className="mark">✓</span> : null}
- {shotStatusLabel(shot.status)}
+ {shotDisplayLabel(displayKind)}
</span>
</td>
<td className="col-ops">
@@ -1125,7 +1151,7 @@ title="用当前镜头重新拼接"
<button
type="button"
className="op"
- disabled={busy || running}
+ disabled={rowBusy}
onClick={() => openShotEdit(shot)}
>
编辑
@@ -1133,24 +1159,27 @@ title="用当前镜头重新拼接"
<button
type="button"
className="op"
- disabled={busy || running}
+ disabled={rowBusy}
onClick={() => regenImage(shot)}
>
- 重生成
- </button>
- <button
- type="button"
- className="op"
- disabled={busy || running}
- onClick={() => regenImage(shot)}
- >
- 替换画面
+ {shot.image_url ? '重绘画面' : '生成画面'}
</button>
+ {isFullPipeline ? (
+ <button
+ type="button"
+ className="op op-video"
+ disabled={rowBusy || !shot.image_url}
+ title={!shot.image_url ? '请先生成该镜画面' : undefined}
+ onClick={() => regenVideo(shot)}
+ >
+ {shot.video_url ? '重生视频' : '出视频'}
+ </button>
+ ) : null}
<button
type="button"
className="more"
aria-label="更多操作"
- disabled={busy || running}
+ disabled={rowBusy}
onClick={(e) => {
e.stopPropagation()
setMenuShotId((id) => (id === shot.id ? null : shot.id))
@@ -1160,21 +1189,9 @@ title="用当前镜头重新拼接"
</button>
{menuShotId === shot.id ? (
<div className="pf-shot-menu" onClick={(e) => e.stopPropagation()}>
- {project.pipeline_mode !== 'image_text' ? (
- <button
- type="button"
- disabled={busy || running}
- onClick={() => {
- setMenuShotId(null)
- regenVideo(shot)
- }}
- >
- 重生视频
- </button>
- ) : null}
<button
type="button"
- disabled={busy || running}
+ disabled={rowBusy}
onClick={() => {
setMenuShotId(null)
regenAudio(shot)
@@ -1391,7 +1408,7 @@ title="用当前镜头重新拼接"
rows={editMode === 'narration' ? 6 : 3}
/>
<span className="pf-muted pf-prompt-hint">
- 会同步到脚本旁白段,配音与视频按脚本生成
+ 会同步到脚本旁白段,并影响整片配音(改完需重新生成配音/成片)
</span>
</label>
</>
@@ -1413,7 +1430,7 @@ title="用当前镜头重新拼接"
{editMode === 'segment' || editMode === 'full' ? (
<>
<label>
- 逐段分镜脚本(@duration + 字幕/BGM)
+ 逐段分镜脚本(画面节奏与 @duration;字幕/配乐由后期合成)
<textarea
className="pf-prompt-segment"
autoFocus={editFocus === 'segment_script' || editMode === 'segment'}
diff --git a/frontend/src/pages/studio/StyleConfigPage.tsx b/frontend/src/pages/studio/StyleConfigPage.tsx
index 99dd0a0..3e86469 100644
--- a/frontend/src/pages/studio/StyleConfigPage.tsx
+++ b/frontend/src/pages/studio/StyleConfigPage.tsx
@@ -8,38 +8,7 @@ import ComingSoon from '../../components/ui/ComingSoon'
import { IconChevronLeft, IconPlay } from '../../components/ui/Icons'
import BillingErrorNotice from '../../components/billing/BillingErrorNotice'
import { handleBillingError } from '../../lib/billingError'
-import { CREATE_STEPS } from '../../lib/status'
-
-const CHAR_PRESETS = [
- {
- id: 'real',
- label: '写实人物',
- desc: '真实人物质感',
- image: '/char-presets/real.jpg',
- promptHint: '写实人物操作电脑或系统界面,侧脸或过肩视角,手部与屏幕清晰',
- },
- {
- id: 'anime',
- label: '动漫角色',
- desc: '二次元形象',
- image: '/char-presets/anime.jpg',
- promptHint: '动漫风格角色在工位前操作系统,造型简洁统一',
- },
- {
- id: 'sil',
- label: '剪影',
- desc: '抽象剪影表达',
- image: '/char-presets/sil.jpg',
- promptHint: '剪影人物操作系统界面,抽象轮廓,信息层级清晰',
- },
- {
- id: 'none',
- label: '无角色',
- desc: '纯场景解说',
- image: '/char-presets/none.jpg',
- promptHint: '无人物角色,专注产品界面、文档与架构示意',
- },
-]
+import { kepuStepIndex, kepuSteps } from '../../lib/status'
const OUTPUT_MODES: { id: PipelineMode; label: string; desc: string; image: string }[] = [
{ id: 'full', label: 'AI 视频', desc: '图→视频→配音→合成', image: '/mode-presets/full.jpg' },
@@ -51,6 +20,18 @@ const OUTPUT_MODES: { id: PipelineMode; label: string; desc: string; image: stri
},
]
+const BGM_PRESETS = [
+ { id: '轻快专业,音量低于人声', label: '轻快' },
+ { id: '冷静纪实,音量低于人声', label: '冷静' },
+ { id: '温暖人文,音量低于人声', label: '温暖' },
+]
+
+const SUBTITLE_PRESETS = [
+ { id: 'standard', label: '标准', desc: '标题在上,旁白字幕底部' },
+ { id: 'large', label: '大字幕', desc: '旁白字幕加大' },
+ { id: 'split', label: '分栏', desc: '标题与说明分栏叠字' },
+]
+
const RATIOS: { id: string; label: string; w: number; h: number }[] = [
{ id: '16:9', label: '16:9', w: 36, h: 20 },
{ id: '9:16', label: '9:16', w: 18, h: 32 },
@@ -80,14 +61,14 @@ export default function StyleConfigPage() {
const [templates, setTemplates] = useState<Template[]>([])
const [voices, setVoices] = useState<VoicePreset[]>([])
const [stylePrompt, setStylePrompt] = useState('')
- const [characterPrompt, setCharacterPrompt] = useState('')
const [extraPrompt, setExtraPrompt] = useState('')
const [voiceId, setVoiceId] = useState('')
const [pipelineMode, setPipelineMode] = useState<PipelineMode>('full')
const [ratio, setRatio] = useState('16:9')
- const [charPreset, setCharPreset] = useState('real')
const [imageModel, setImageModel] = useState('')
const [videoModel, setVideoModel] = useState('')
+ const [bgmLock, setBgmLock] = useState(BGM_PRESETS[0].id)
+ const [subtitlePreset, setSubtitlePreset] = useState('standard')
const [mediaCatalog, setMediaCatalog] = useState<MediaModelsCatalog | null>(null)
const [busy, setBusy] = useState(false)
const [previewBusy, setPreviewBusy] = useState<string | null>(null)
@@ -118,9 +99,10 @@ export default function StyleConfigPage() {
.then((p) => {
setProject(p)
setStylePrompt(p.style_prompt || '')
- setCharacterPrompt(p.character_prompt || '')
setExtraPrompt(p.extra_prompt || '')
setVoiceId(p.voice_id || '')
+ if (p.bgm_lock) setBgmLock(p.bgm_lock)
+ if (p.subtitle_preset) setSubtitlePreset(p.subtitle_preset)
setPipelineMode(p.pipeline_mode || 'full')
setRatio(p.output_ratio || (p.pipeline_mode === 'image_text' ? '9:16' : '16:9'))
if (p.image_model) setImageModel(p.image_model)
@@ -149,15 +131,13 @@ export default function StyleConfigPage() {
[templates, project?.template_id],
)
- const styleOptions = useMemo(() => templates.slice(0, 8), [templates])
const selectedVoice = voices.find((v) => voiceKey(v) === voiceId || v.id === voiceId)
useEffect(() => {
if (!project || !currentTpl) return
- if (!stylePrompt && !characterPrompt) {
+ if (!stylePrompt) {
const d = defaultsFromTemplate(currentTpl)
setStylePrompt((v) => v || d.style_prompt)
- setCharacterPrompt((v) => v || d.character_prompt)
setExtraPrompt((v) => v || d.extra_prompt)
setVoiceId((v) => v || d.voice_id)
}
@@ -168,30 +148,6 @@ export default function StyleConfigPage() {
setRatio(currentTpl.default_ratio)
}, [project?.id, project?.output_ratio, currentTpl?.default_ratio])
- function pickStyle(t: Template) {
- const d = defaultsFromTemplate(t)
- setStylePrompt(d.style_prompt)
- setCharacterPrompt(d.character_prompt)
- setExtraPrompt(d.extra_prompt)
- setVoiceId(d.voice_id)
- // 风格带默认画幅;用户仍可在下方「输出比例」改
- if (d.output_ratio) setRatio(d.output_ratio)
- if (/无人物|无角色/.test(d.character_prompt)) setCharPreset('none')
- else if (/剪影/.test(d.character_prompt)) setCharPreset('sil')
- else if (/动漫|二次元|3D|三维|CGI/.test(d.character_prompt + d.style_prompt)) setCharPreset('anime')
- else setCharPreset('real')
- if (project) {
- api
- .updateProject(project.id, {
- template_id: t.id,
- voice_id: d.voice_id,
- output_ratio: d.output_ratio || undefined,
- })
- .then(setProject)
- .catch((err) => setError(err instanceof Error ? err.message : '更新失败'))
- }
- }
-
function pickRatio(r: (typeof RATIOS)[0]) {
setRatio(r.id)
}
@@ -247,40 +203,41 @@ export default function StyleConfigPage() {
setBusy(true)
setError('')
try {
- const charNote =
- charPreset === 'none'
- ? '无人物角色,侧重场景与信息图表。'
- : charPreset === 'anime'
- ? '角色偏动漫造型。'
- : charPreset === 'sil'
- ? '角色以剪影呈现。'
- : ''
const d = currentTpl ? defaultsFromTemplate(currentTpl) : null
/*
* styleOut 风格提示词;与模板相同则留空,生成时读后台
* extraOut 额外提示词
- * charText 角色描述原文;与模板相同则不写入覆盖
*/
const styleOut = stylePrompt.trim()
const extraOut = extraPrompt.trim()
- const charText = characterPrompt.trim()
const sameStyle = Boolean(d) && styleOut === d!.style_prompt
- const sameChar = Boolean(d) && charText === d!.character_prompt
const sameExtra = Boolean(d) && extraOut === d!.extra_prompt
await api.updateProject(project.id, {
style_prompt: sameStyle ? '' : styleOut,
- character_prompt: sameChar ? '' : [charText, charNote].filter(Boolean).join('\n'),
+ character_prompt: '',
extra_prompt: sameExtra ? '' : extraOut,
voice_id: voiceId,
pipeline_mode: pipelineMode,
output_ratio: ratio,
image_model: imageModel,
video_model: videoModel,
+ bgm_lock: bgmLock,
+ subtitle_preset: subtitlePreset,
})
const started = await api.generate(project.id)
nav(`/studio/${started.id}`)
} catch (err) {
const msg = err instanceof Error ? err.message : '生成失败'
+ if (msg.includes('合成成片')) {
+ try {
+ const composed = await api.compose(project.id)
+ nav(`/studio/${composed.id}`)
+ return
+ } catch (e2) {
+ setError(e2 instanceof Error ? e2.message : '合成失败')
+ return
+ }
+ }
setError(msg)
await handleBillingError(err, nav)
} finally {
@@ -307,7 +264,11 @@ export default function StyleConfigPage() {
</button>
<h1 className="pf-page-title">{project?.title || '风格配置'}</h1>
</div>
- <Stepper steps={CREATE_STEPS} current={2} doneThrough={1} />
+ <Stepper
+ steps={kepuSteps(pipelineMode)}
+ current={kepuStepIndex('style', { status: 'DRAFT', pipeline_mode: pipelineMode })}
+ doneThrough={0}
+ />
</div>
</header>
@@ -357,41 +318,34 @@ export default function StyleConfigPage() {
<section className="pf-create-col">
<div className="pf-style-block">
- <h3>
- 画面风格
- <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled>
- 更多风格 <ComingSoon />
- </button>
- </h3>
- <div className="pf-style-grid">
- {styleOptions.map((t) => {
- const portrait = isPortraitRatio(t.default_ratio)
- return (
- <button
- key={t.id}
- type="button"
- className={[
- 'pf-style-opt',
- portrait ? 'portrait' : '',
- project?.template_id === t.id ? 'selected' : '',
- ]
- .filter(Boolean)
- .join(' ')}
- onClick={() => pickStyle(t)}
- >
- <span className="pf-style-opt-media">
- <img src={api.assetUrl(t.preview_cover)} alt="" />
- {t.default_ratio ? (
- <span className="pf-style-opt-ratio">{t.default_ratio}</span>
- ) : null}
- </span>
- <div className="cap">{t.name}</div>
- </button>
- )
- })}
- </div>
+ <h3>画面风格</h3>
+ <p className="pf-muted" style={{ fontSize: '0.78rem', margin: '0 0 0.65rem' }}>
+ 已由选题时选择的模板锁定,出图与出视频会自动带上画风。是否出角色由模板规则和主题让 AI
+ 决定,不必再选一套人设。
+ </p>
+ {currentTpl ? (
+ <div
+ className={[
+ 'pf-style-opt',
+ 'selected',
+ isPortraitRatio(currentTpl.default_ratio) ? 'portrait' : '',
+ ]
+ .filter(Boolean)
+ .join(' ')}
+ style={{ maxWidth: 280, textAlign: 'left' }}
+ >
+ <span className="pf-style-opt-media">
+ <img src={api.assetUrl(currentTpl.preview_cover)} alt="" />
+ {currentTpl.default_ratio ? (
+ <span className="pf-style-opt-ratio">{currentTpl.default_ratio}</span>
+ ) : null}
+ </span>
+ <div className="cap">{currentTpl.name}</div>
+ <div className="cap-sub">模板画风</div>
+ </div>
+ ) : null}
<label className="pf-field" style={{ marginTop: '0.75rem' }}>
- <span className="pf-field-label">风格提示词</span>
+ <span className="pf-field-label">风格提示词(可选覆盖)</span>
<textarea
className="pf-field-input"
value={stylePrompt}
@@ -402,37 +356,6 @@ export default function StyleConfigPage() {
</label>
</div>
- <div className="pf-style-block">
- <h3>角色设定</h3>
- <div className="pf-style-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
- {CHAR_PRESETS.map((c) => (
- <button
- key={c.id}
- type="button"
- className={charPreset === c.id ? 'pf-style-opt selected' : 'pf-style-opt'}
- onClick={() => {
- setCharPreset(c.id)
- setCharacterPrompt(c.promptHint)
- }}
- >
- <img src={c.image} alt="" />
- <div className="cap">{c.label}</div>
- <div className="cap-sub">{c.desc}</div>
- </button>
- ))}
- </div>
- <label className="pf-field" style={{ marginTop: '0.75rem' }}>
- <span className="pf-field-label">角色描述</span>
- <textarea
- className="pf-field-input"
- value={characterPrompt}
- onChange={(e) => setCharacterPrompt(e.target.value)}
- rows={2}
- style={{ resize: 'vertical', minHeight: 64 }}
- />
- </label>
- </div>
-
<div className="pf-style-block">
<h3>
配音音色
@@ -493,11 +416,54 @@ export default function StyleConfigPage() {
</div>
{selectedVoice ? (
<p className="pf-muted" style={{ fontSize: '0.78rem', margin: '0.55rem 0 0' }}>
- 当前:{selectedVoice.label} · 点击「试听」可听约 5 秒样例
+ 当前:{selectedVoice.label} · 成片用该音色整片配音;点击「试听」可听约 5 秒样例
</p>
) : null}
</div>
+ <div className="pf-style-block">
+ <h3>后期配乐</h3>
+ <p className="pf-muted" style={{ fontSize: '0.78rem', margin: '0 0 0.65rem' }}>
+ 合成时叠在旁白下方,音量低于人声。
+ </p>
+ <div className="pf-ratio-row">
+ {BGM_PRESETS.map((b) => (
+ <button
+ key={b.id}
+ type="button"
+ className={
+ bgmLock === b.id || (bgmLock && b.id.startsWith(bgmLock.slice(0, 2)))
+ ? 'pf-ratio selected'
+ : 'pf-ratio'
+ }
+ onClick={() => setBgmLock(b.id)}
+ >
+ {b.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="pf-style-block">
+ <h3>字幕预设</h3>
+ <p className="pf-muted" style={{ fontSize: '0.78rem', margin: '0 0 0.65rem' }}>
+ 成片由后期叠旁白字幕,不是视频模型烧录。
+ </p>
+ <div className="pf-ratio-row">
+ {SUBTITLE_PRESETS.map((s) => (
+ <button
+ key={s.id}
+ type="button"
+ className={subtitlePreset === s.id ? 'pf-ratio selected' : 'pf-ratio'}
+ onClick={() => setSubtitlePreset(s.id)}
+ title={s.desc}
+ >
+ {s.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
<div className="pf-style-block">
<h3>成片方式</h3>
<p className="pf-muted" style={{ fontSize: '0.78rem', margin: '0 0 0.65rem' }}>
@@ -617,7 +583,7 @@ export default function StyleConfigPage() {
</li>
<li>
<span>角色</span>
- <span>{CHAR_PRESETS.find((c) => c.id === charPreset)?.label}</span>
+ <span>AI 按模板与主题决定</span>
</li>
<li>
<span>配音</span>
@@ -654,7 +620,7 @@ export default function StyleConfigPage() {
disabled={busy || Boolean(previewBusy)}
onClick={generate}
>
- {busy ? '启动中…' : '生成故事板'}
+ {busy ? '启动中…' : project.shots?.length ? '保存并继续' : '生成故事板'}
{!busy ? <span aria-hidden>→</span> : null}
</button>
<p className="pf-muted" style={{ fontSize: '0.78rem', marginTop: '0.5rem' }}>
diff --git a/frontend/src/styles/printfilm.css b/frontend/src/styles/printfilm.css
index 5c6c828..b450fa9 100644
--- a/frontend/src/styles/printfilm.css
+++ b/frontend/src/styles/printfilm.css
@@ -3874,17 +3874,24 @@
border-radius: 3px;
}
-/* Storyboard */
+/* Storyboard:中间列允许收缩,避免分镜表 min-width 把右侧「生成进度」裁切掉 */
.pf-board {
display: grid;
- grid-template-columns: 260px 1fr 260px;
+ grid-template-columns: minmax(0, 220px) minmax(0, 1fr) minmax(0, 220px);
gap: 1rem;
+ width: 100%;
+ max-width: 100%;
+}
+
+.pf-board > .pf-create-col {
+ min-width: 0;
}
.pf-board-main {
display: flex;
flex-direction: column;
gap: 1rem;
+ min-width: 0;
}
.pf-outline-grid {
@@ -3916,16 +3923,17 @@
}
.pf-shot-table-wrap {
- overflow-x: auto;
- margin: 0 -0.25rem;
+ min-width: 0;
+ overflow-x: hidden;
+ margin: 0;
}
.pf-shot-table {
width: 100%;
+ table-layout: fixed;
border-collapse: separate;
border-spacing: 0;
font-size: 0.88rem;
- min-width: 920px;
}
.pf-shot-table thead th {
@@ -3933,7 +3941,7 @@
font-weight: 600;
font-size: 0.78rem;
text-align: left;
- padding: 0.55rem 0.65rem;
+ padding: 0.55rem 0.45rem;
border-bottom: 1px solid var(--pf-line);
background: #fafbfc;
white-space: nowrap;
@@ -3949,34 +3957,49 @@
.pf-shot-table td {
border-bottom: 1px solid var(--pf-line);
- padding: 0.85rem 0.65rem;
+ padding: 0.75rem 0.45rem;
text-align: left;
vertical-align: top;
}
-.pf-shot-table td.col-no {
- width: 52px;
+/* 固定窄列不换行;旁白 / 分镜按比例吃剩余宽度,避免整表横向滑动 */
+.pf-shot-table .col-no {
+ width: 3rem;
font-weight: 700;
font-variant-numeric: tabular-nums;
color: var(--pf-ink);
font-family: 'Space Grotesk', sans-serif;
+ white-space: nowrap;
}
-.pf-shot-table td.col-thumb {
- width: 140px;
+.pf-shot-table .col-thumb {
+ width: 6.6rem;
}
-.pf-shot-table td.col-dur,
-.pf-shot-table td.col-status {
- width: 88px;
+.pf-shot-table .col-narr {
+ width: 22%;
+ overflow-wrap: break-word;
+}
+
+.pf-shot-table .col-seg {
+ width: 30%;
+ overflow-wrap: break-word;
+}
+
+.pf-shot-table .col-dur {
+ width: 4rem;
white-space: nowrap;
}
-.pf-shot-table td.col-ops {
- width: 200px;
+.pf-shot-table .col-status {
+ width: 5.6rem;
white-space: nowrap;
}
+.pf-shot-table .col-ops {
+ width: 8.4rem;
+}
+
.pf-shot-thumb-btn {
border: 0;
padding: 0;
@@ -3993,8 +4016,8 @@
}
.pf-shot-thumb {
- width: 128px;
- height: 72px;
+ width: 96px;
+ height: 54px;
object-fit: cover;
border-radius: 10px;
background: linear-gradient(135deg, #e5e7eb, #d1d5db);
@@ -4034,7 +4057,7 @@
color: #6b7280;
font-size: 0.84rem;
line-height: 1.55;
- max-width: 280px;
+ max-width: 100%;
}
button.pf-shot-editable {
@@ -4247,9 +4270,10 @@ button.pf-shot-editable:disabled {
}
.pf-shot-ops {
- display: inline-flex;
+ display: flex;
+ flex-wrap: wrap;
align-items: center;
- gap: 0.15rem;
+ gap: 0.1rem 0.05rem;
position: relative;
}
@@ -4264,9 +4288,13 @@ button.pf-shot-editable:disabled {
cursor: pointer;
}
-.pf-shot-ops .op:hover:not(:disabled) {
+.pf-shot-ops .op.op-video {
color: var(--pf-ink);
- background: rgba(182, 255, 0, 0.25);
+ font-weight: 650;
+}
+
+.pf-shot-ops .op.op-video:hover:not(:disabled) {
+ background: rgba(182, 255, 0, 0.45);
}
.pf-shot-ops .op:disabled {