Skip to content

🎬 火宝短剧 - 基于AI的一站式短剧生成平台 《一句话生成完整短剧,从剧本到成片全自动化》 Huobao Drama - An AI-Powered End-to-End Short Drama Generator "One Sentence to Complete Drama: Fully Automated from Script to Final Video"

TypeScript

feat: Phase 3 — AI generation services, file upload, frontend switch

Connor82684227fce7
diff --git a/server/src/index.ts b/server/src/index.ts
index 1c6c54d..5f0e82c 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -13,6 +13,7 @@ import scenes from './routes/scenes.js'
import characters from './routes/characters.js'
import images from './routes/images.js'
import videos from './routes/videos.js'
+import upload from './routes/upload.js'
import aiConfigs, { aiProviders } from './routes/aiConfigs.js'
import agentConfigs from './routes/agentConfigs.js'
import agent from './routes/agent.js'
@@ -41,6 +42,7 @@ api.route('/scenes', scenes)
api.route('/characters', characters)
api.route('/images', images)
api.route('/videos', videos)
+api.route('/upload', upload)
api.route('/ai-configs', aiConfigs)
api.route('/ai-providers', aiProviders)
api.route('/agent-configs', agentConfigs)
diff --git a/server/src/routes/images.ts b/server/src/routes/images.ts
index 3f9a302..5d904fd 100644
--- a/server/src/routes/images.ts
+++ b/server/src/routes/images.ts
@@ -1,45 +1,63 @@
import { Hono } from 'hono'
import { eq } from 'drizzle-orm'
import { db, schema } from '../db/index.js'
-import { success, created, now } from '../utils/response.js'
+import { success, created, now, badRequest } from '../utils/response.js'
+import { generateImage } from '../services/image-generation.js'
const app = new Hono()
-// POST /images — Generate image (placeholder)
+// POST /images — Generate image
app.post('/', async (c) => {
const body = await c.req.json()
- const ts = now()
- const [result] = await db.insert(schema.imageGenerations).values({
- storyboardId: body.storyboard_id,
- dramaId: body.drama_id,
- prompt: body.prompt,
- model: body.model,
- status: 'pending',
- frameType: body.frame_type,
- createdAt: ts,
- updatedAt: ts,
- }).returning()
- return created(c, result)
+ if (!body.prompt) return badRequest(c, 'prompt is required')
+
+ try {
+ const id = await generateImage({
+ storyboardId: body.storyboard_id,
+ dramaId: body.drama_id,
+ sceneId: body.scene_id,
+ characterId: body.character_id,
+ prompt: body.prompt,
+ model: body.model,
+ size: body.size,
+ referenceImages: body.reference_images,
+ frameType: body.frame_type,
+ })
+
+ const [record] = db.select().from(schema.imageGenerations)
+ .where(eq(schema.imageGenerations.id, id))
+ return created(c, record)
+ } catch (err: any) {
+ return badRequest(c, err.message)
+ }
})
// GET /images/:id
app.get('/:id', async (c) => {
const id = Number(c.req.param('id'))
- const [row] = await db.select().from(schema.imageGenerations)
+ const [row] = db.select().from(schema.imageGenerations)
.where(eq(schema.imageGenerations.id, id))
return success(c, row || null)
})
+// GET /images — List by storyboard_id or drama_id
+app.get('/', async (c) => {
+ const storyboardId = c.req.query('storyboard_id')
+ const dramaId = c.req.query('drama_id')
+
+ let rows = db.select().from(schema.imageGenerations).all()
+
+ if (storyboardId) rows = rows.filter(r => r.storyboardId === Number(storyboardId))
+ if (dramaId) rows = rows.filter(r => r.dramaId === Number(dramaId))
+
+ return success(c, rows)
+})
+
// DELETE /images/:id
app.delete('/:id', async (c) => {
const id = Number(c.req.param('id'))
- await db.delete(schema.imageGenerations).where(eq(schema.imageGenerations.id, id))
+ db.delete(schema.imageGenerations).where(eq(schema.imageGenerations.id, id)).run()
return success(c)
})
-// POST /images/episode/:episode_id/batch (placeholder)
-app.post('/episode/:episode_id/batch', async (c) => {
- return success(c, { message: 'Batch generation queued' })
-})
-
export default app
diff --git a/server/src/routes/upload.ts b/server/src/routes/upload.ts
new file mode 100644
index 0000000..fc07218
--- /dev/null
+++ b/server/src/routes/upload.ts
@@ -0,0 +1,21 @@
+import { Hono } from 'hono'
+import { success, badRequest } from '../utils/response.js'
+import { saveUploadedFile } from '../utils/storage.js'
+
+const app = new Hono()
+
+// POST /upload/image
+app.post('/image', async (c) => {
+ const body = await c.req.parseBody()
+ const file = body['file']
+
+ if (!file || !(file instanceof File)) {
+ return badRequest(c, 'file is required')
+ }
+
+ const buffer = await file.arrayBuffer()
+ const path = await saveUploadedFile(buffer, 'uploads', file.name)
+ return success(c, { url: `/${path}`, path })
+})
+
+export default app
diff --git a/server/src/routes/videos.ts b/server/src/routes/videos.ts
index 3b70510..2b42d21 100644
--- a/server/src/routes/videos.ts
+++ b/server/src/routes/videos.ts
@@ -1,40 +1,64 @@
import { Hono } from 'hono'
import { eq } from 'drizzle-orm'
import { db, schema } from '../db/index.js'
-import { success, created, now } from '../utils/response.js'
+import { success, created, badRequest } from '../utils/response.js'
+import { generateVideo } from '../services/video-generation.js'
const app = new Hono()
-// POST /videos — Generate video (placeholder)
+// POST /videos — Generate video
app.post('/', async (c) => {
const body = await c.req.json()
- const ts = now()
- const [result] = await db.insert(schema.videoGenerations).values({
- storyboardId: body.storyboard_id,
- dramaId: body.drama_id,
- prompt: body.prompt,
- model: body.model,
- referenceMode: body.reference_mode,
- imageUrl: body.image_url,
- status: 'pending',
- createdAt: ts,
- updatedAt: ts,
- }).returning()
- return created(c, result)
+ if (!body.prompt) return badRequest(c, 'prompt is required')
+
+ try {
+ const id = await generateVideo({
+ storyboardId: body.storyboard_id,
+ dramaId: body.drama_id,
+ prompt: body.prompt,
+ model: body.model,
+ referenceMode: body.reference_mode,
+ imageUrl: body.image_url,
+ firstFrameUrl: body.first_frame_url,
+ lastFrameUrl: body.last_frame_url,
+ referenceImageUrls: body.reference_image_urls,
+ duration: body.duration,
+ aspectRatio: body.aspect_ratio,
+ })
+
+ const [record] = db.select().from(schema.videoGenerations)
+ .where(eq(schema.videoGenerations.id, id))
+ return created(c, record)
+ } catch (err: any) {
+ return badRequest(c, err.message)
+ }
})
// GET /videos/:id
app.get('/:id', async (c) => {
const id = Number(c.req.param('id'))
- const [row] = await db.select().from(schema.videoGenerations)
+ const [row] = db.select().from(schema.videoGenerations)
.where(eq(schema.videoGenerations.id, id))
return success(c, row || null)
})
+// GET /videos — List by storyboard_id or drama_id
+app.get('/', async (c) => {
+ const storyboardId = c.req.query('storyboard_id')
+ const dramaId = c.req.query('drama_id')
+
+ let rows = db.select().from(schema.videoGenerations).all()
+
+ if (storyboardId) rows = rows.filter(r => r.storyboardId === Number(storyboardId))
+ if (dramaId) rows = rows.filter(r => r.dramaId === Number(dramaId))
+
+ return success(c, rows)
+})
+
// DELETE /videos/:id
app.delete('/:id', async (c) => {
const id = Number(c.req.param('id'))
- await db.delete(schema.videoGenerations).where(eq(schema.videoGenerations.id, id))
+ db.delete(schema.videoGenerations).where(eq(schema.videoGenerations.id, id)).run()
return success(c)
})
diff --git a/server/src/services/image-generation.ts b/server/src/services/image-generation.ts
new file mode 100644
index 0000000..72500d0
--- /dev/null
+++ b/server/src/services/image-generation.ts
@@ -0,0 +1,175 @@
+/**
+ * 图片生成服务 — 调用 OpenAI compatible API 生成图片
+ */
+import { db, schema } from '../db/index.js'
+import { eq } from 'drizzle-orm'
+import { getActiveConfig } from './ai.js'
+import { now } from '../utils/response.js'
+import { downloadFile } from '../utils/storage.js'
+
+interface GenerateImageParams {
+ storyboardId?: number
+ dramaId?: number
+ sceneId?: number
+ characterId?: number
+ prompt: string
+ model?: string
+ size?: string
+ referenceImages?: string[]
+ frameType?: string
+}
+
+export async function generateImage(params: GenerateImageParams): Promise<number> {
+ const ts = now()
+ const config = getActiveConfig('image')
+ if (!config) throw new Error('No active image AI config')
+
+ // 创建记录
+ const [record] = db.insert(schema.imageGenerations).values({
+ storyboardId: params.storyboardId,
+ dramaId: params.dramaId,
+ sceneId: params.sceneId,
+ characterId: params.characterId,
+ prompt: params.prompt,
+ model: params.model || config.model,
+ provider: config.provider,
+ size: params.size || '1920x1080',
+ frameType: params.frameType,
+ referenceImages: params.referenceImages ? JSON.stringify(params.referenceImages) : null,
+ status: 'processing',
+ createdAt: ts,
+ updatedAt: ts,
+ }).returning()
+
+ // 异步处理
+ processImageGeneration(record.id, config).catch(err => {
+ console.error(`Image generation ${record.id} failed:`, err)
+ })
+
+ return record.id
+}
+
+async function processImageGeneration(id: number, config: { baseUrl: string; apiKey: string; model: string }) {
+ try {
+ const [record] = db.select().from(schema.imageGenerations).where(eq(schema.imageGenerations.id, id))
+ if (!record) return
+
+ // 构建请求
+ const body: any = {
+ model: record.model || config.model,
+ prompt: record.prompt,
+ size: record.size || '1920x1080',
+ n: 1,
+ }
+
+ // 参考图
+ if (record.referenceImages) {
+ const refs = JSON.parse(record.referenceImages)
+ if (refs.length > 0) body.image = refs
+ }
+
+ const resp = await fetch(`${config.baseUrl}/images/generations`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${config.apiKey}`,
+ },
+ body: JSON.stringify(body),
+ })
+
+ if (!resp.ok) {
+ const errText = await resp.text()
+ throw new Error(`API error ${resp.status}: ${errText}`)
+ }
+
+ const result = await resp.json() as any
+
+ // 检查是否异步任务
+ if (result.task_id || result.id) {
+ const taskId = result.task_id || result.id
+ db.update(schema.imageGenerations)
+ .set({ taskId, status: 'processing', updatedAt: now() })
+ .where(eq(schema.imageGenerations.id, id))
+ .run()
+
+ // 开始轮询
+ pollImageTask(id, config, taskId)
+ return
+ }
+
+ // 同步结果
+ const imageUrl = result.data?.[0]?.url || result.url
+ if (!imageUrl) throw new Error('No image URL in response')
+
+ const localPath = await downloadFile(imageUrl, 'images')
+
+ db.update(schema.imageGenerations)
+ .set({ imageUrl, localPath, status: 'completed', updatedAt: now() })
+ .where(eq(schema.imageGenerations.id, id))
+ .run()
+
+ // 更新关联的 storyboard
+ if (record.storyboardId) {
+ db.update(schema.storyboards)
+ .set({ composedImage: localPath, updatedAt: now() })
+ .where(eq(schema.storyboards.id, record.storyboardId))
+ .run()
+ }
+ } catch (err: any) {
+ db.update(schema.imageGenerations)
+ .set({ status: 'failed', errorMsg: err.message, updatedAt: now() })
+ .where(eq(schema.imageGenerations.id, id))
+ .run()
+ }
+}
+
+async function pollImageTask(id: number, config: { baseUrl: string; apiKey: string }, taskId: string) {
+ const maxAttempts = 60
+ const interval = 5000
+
+ for (let i = 0; i < maxAttempts; i++) {
+ await new Promise(r => setTimeout(r, interval))
+
+ try {
+ const resp = await fetch(`${config.baseUrl}/images/task/${taskId}`, {
+ headers: { 'Authorization': `Bearer ${config.apiKey}` },
+ })
+ if (!resp.ok) continue
+
+ const result = await resp.json() as any
+ const status = result.status || result.data?.status
+
+ if (status === 'completed' || status === 'succeeded') {
+ const imageUrl = result.image_url || result.data?.image_url || result.url || result.data?.url
+ if (!imageUrl) continue
+
+ const localPath = await downloadFile(imageUrl, 'images')
+ const [record] = db.select().from(schema.imageGenerations).where(eq(schema.imageGenerations.id, id))
+
+ db.update(schema.imageGenerations)
+ .set({ imageUrl, localPath, status: 'completed', updatedAt: now() })
+ .where(eq(schema.imageGenerations.id, id))
+ .run()
+
+ if (record?.storyboardId) {
+ db.update(schema.storyboards)
+ .set({ composedImage: localPath, updatedAt: now() })
+ .where(eq(schema.storyboards.id, record.storyboardId))
+ .run()
+ }
+ return
+ }
+
+ if (status === 'failed' || status === 'error') {
+ throw new Error(result.error_msg || result.message || 'Task failed')
+ }
+ } catch (err: any) {
+ if (i === maxAttempts - 1) {
+ db.update(schema.imageGenerations)
+ .set({ status: 'failed', errorMsg: `Polling timeout: ${err.message}`, updatedAt: now() })
+ .where(eq(schema.imageGenerations.id, id))
+ .run()
+ }
+ }
+ }
+}
diff --git a/server/src/services/video-generation.ts b/server/src/services/video-generation.ts
new file mode 100644
index 0000000..8122993
--- /dev/null
+++ b/server/src/services/video-generation.ts
@@ -0,0 +1,183 @@
+/**
+ * 视频生成服务 — 调用 Chatfire/Doubao compatible API 生成视频
+ */
+import { db, schema } from '../db/index.js'
+import { eq } from 'drizzle-orm'
+import { getActiveConfig } from './ai.js'
+import { now } from '../utils/response.js'
+import { downloadFile } from '../utils/storage.js'
+
+interface GenerateVideoParams {
+ storyboardId?: number
+ dramaId?: number
+ prompt: string
+ model?: string
+ referenceMode?: string
+ imageUrl?: string
+ firstFrameUrl?: string
+ lastFrameUrl?: string
+ referenceImageUrls?: string[]
+ duration?: number
+ aspectRatio?: string
+}
+
+export async function generateVideo(params: GenerateVideoParams): Promise<number> {
+ const ts = now()
+ const config = getActiveConfig('video')
+ if (!config) throw new Error('No active video AI config')
+
+ const [record] = db.insert(schema.videoGenerations).values({
+ storyboardId: params.storyboardId,
+ dramaId: params.dramaId,
+ prompt: params.prompt,
+ model: params.model || config.model,
+ provider: config.provider,
+ referenceMode: params.referenceMode || 'none',
+ imageUrl: params.imageUrl,
+ firstFrameUrl: params.firstFrameUrl,
+ lastFrameUrl: params.lastFrameUrl,
+ referenceImageUrls: params.referenceImageUrls ? JSON.stringify(params.referenceImageUrls) : null,
+ duration: params.duration || 5,
+ aspectRatio: params.aspectRatio || '16:9',
+ status: 'processing',
+ createdAt: ts,
+ updatedAt: ts,
+ }).returning()
+
+ // 异步处理
+ processVideoGeneration(record.id, config).catch(err => {
+ console.error(`Video generation ${record.id} failed:`, err)
+ })
+
+ return record.id
+}
+
+async function processVideoGeneration(id: number, config: { baseUrl: string; apiKey: string; model: string }) {
+ try {
+ const [record] = db.select().from(schema.videoGenerations).where(eq(schema.videoGenerations.id, id))
+ if (!record) return
+
+ // 构建 prompt(拼接参数)
+ let promptText = record.prompt || ''
+ const dur = record.duration || 5
+ const ratio = record.aspectRatio || '16:9'
+ promptText += ` --ratio ${ratio} --dur ${dur}`
+
+ // 构建 content 数组(Doubao/Chatfire 格式)
+ const content: any[] = [{ type: 'text', text: promptText }]
+
+ // 参考图
+ if (record.referenceMode === 'single' && record.imageUrl) {
+ content.push({ type: 'image_url', image_url: { url: record.imageUrl }, role: 'reference_image' })
+ } else if (record.referenceMode === 'first_last') {
+ if (record.firstFrameUrl) content.push({ type: 'image_url', image_url: { url: record.firstFrameUrl }, role: 'first_frame' })
+ if (record.lastFrameUrl) content.push({ type: 'image_url', image_url: { url: record.lastFrameUrl }, role: 'last_frame' })
+ } else if (record.referenceMode === 'multiple' && record.referenceImageUrls) {
+ const urls = JSON.parse(record.referenceImageUrls) as string[]
+ for (const url of urls) {
+ content.push({ type: 'image_url', image_url: { url }, role: 'reference_image' })
+ }
+ }
+
+ const body = { model: record.model || config.model, content }
+
+ const resp = await fetch(`${config.baseUrl}/video/generations`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${config.apiKey}`,
+ },
+ body: JSON.stringify(body),
+ })
+
+ if (!resp.ok) {
+ const errText = await resp.text()
+ throw new Error(`API error ${resp.status}: ${errText}`)
+ }
+
+ const result = await resp.json() as any
+ const taskId = result.task_id || result.id || result.data?.id
+
+ if (!taskId) {
+ // 同步结果
+ const videoUrl = result.video_url || result.data?.video_url || result.content?.video_url
+ if (videoUrl) {
+ const localPath = await downloadFile(videoUrl, 'videos')
+ db.update(schema.videoGenerations)
+ .set({ videoUrl, localPath, status: 'completed', updatedAt: now() })
+ .where(eq(schema.videoGenerations.id, id))
+ .run()
+ updateStoryboardVideo(record.storyboardId, localPath, dur)
+ return
+ }
+ throw new Error('No task_id or video_url in response')
+ }
+
+ // 异步任务 — 开始轮询
+ db.update(schema.videoGenerations)
+ .set({ taskId, status: 'processing', updatedAt: now() })
+ .where(eq(schema.videoGenerations.id, id))
+ .run()
+
+ pollVideoTask(id, config, taskId, record.storyboardId)
+ } catch (err: any) {
+ db.update(schema.videoGenerations)
+ .set({ status: 'failed', errorMsg: err.message, updatedAt: now() })
+ .where(eq(schema.videoGenerations.id, id))
+ .run()
+ }
+}
+
+async function pollVideoTask(id: number, config: { baseUrl: string; apiKey: string }, taskId: string, storyboardId?: number | null) {
+ const maxAttempts = 300
+ const interval = 10000
+
+ for (let i = 0; i < maxAttempts; i++) {
+ await new Promise(r => setTimeout(r, interval))
+
+ try {
+ const resp = await fetch(`${config.baseUrl}/video/task/${taskId}`, {
+ headers: { 'Authorization': `Bearer ${config.apiKey}` },
+ })
+ if (!resp.ok) continue
+
+ const result = await resp.json() as any
+ const status = result.status || result.data?.status
+
+ if (status === 'completed' || status === 'succeeded') {
+ const videoUrl = result.video_url || result.data?.video_url || result.content?.video_url
+ if (!videoUrl) continue
+
+ const localPath = await downloadFile(videoUrl, 'videos')
+ const [record] = db.select().from(schema.videoGenerations).where(eq(schema.videoGenerations.id, id))
+
+ db.update(schema.videoGenerations)
+ .set({ videoUrl, localPath, status: 'completed', completedAt: now(), updatedAt: now() })
+ .where(eq(schema.videoGenerations.id, id))
+ .run()
+
+ updateStoryboardVideo(record?.storyboardId || storyboardId, localPath, record?.duration || 0)
+ return
+ }
+
+ if (status === 'failed' || status === 'error') {
+ throw new Error(result.error_msg || result.message || 'Task failed')
+ }
+ } catch (err: any) {
+ if (i === maxAttempts - 1) {
+ db.update(schema.videoGenerations)
+ .set({ status: 'failed', errorMsg: `Polling timeout: ${err.message}`, updatedAt: now() })
+ .where(eq(schema.videoGenerations.id, id))
+ .run()
+ }
+ }
+ }
+}
+
+function updateStoryboardVideo(storyboardId: number | null | undefined, localPath: string, duration: number | null) {
+ if (!storyboardId) return
+ db.update(schema.storyboards)
+ .set({ videoUrl: localPath, duration: duration || undefined, updatedAt: now() })
+ .where(eq(schema.storyboards.id, storyboardId))
+ .run()
+}
diff --git a/server/src/utils/storage.ts b/server/src/utils/storage.ts
new file mode 100644
index 0000000..92a4830
--- /dev/null
+++ b/server/src/utils/storage.ts
@@ -0,0 +1,65 @@
+/**
+ * 文件存储工具 — 下载远程文件到本地
+ */
+import fs from 'fs'
+import path from 'path'
+import { fileURLToPath } from 'url'
+import { v4 as uuid } from 'uuid'
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url))
+const STORAGE_ROOT = process.env.STORAGE_PATH || path.resolve(__dirname, '../../../data/static')
+
+/**
+ * 下载远程文件到本地存储
+ */
+export async function downloadFile(url: string, subDir: string): Promise<string> {
+ const dir = path.join(STORAGE_ROOT, subDir)
+ fs.mkdirSync(dir, { recursive: true })
+
+ const ext = getExtFromUrl(url)
+ const filename = `${uuid()}${ext}`
+ const filePath = path.join(dir, filename)
+
+ const resp = await fetch(url)
+ if (!resp.ok) throw new Error(`Download failed: ${resp.status}`)
+
+ const buffer = Buffer.from(await resp.arrayBuffer())
+ fs.writeFileSync(filePath, buffer)
+
+ // 返回相对路径(供 API 返回给前端)
+ return `static/${subDir}/${filename}`
+}
+
+/**
+ * 保存上传的文件
+ */
+export async function saveUploadedFile(data: ArrayBuffer, subDir: string, originalName: string): Promise<string> {
+ const dir = path.join(STORAGE_ROOT, subDir)
+ fs.mkdirSync(dir, { recursive: true })
+
+ const ext = path.extname(originalName) || '.bin'
+ const filename = `${uuid()}${ext}`
+ const filePath = path.join(dir, filename)
+
+ fs.writeFileSync(filePath, Buffer.from(data))
+ return `static/${subDir}/${filename}`
+}
+
+function getExtFromUrl(url: string): string {
+ try {
+ const pathname = new URL(url).pathname
+ const ext = path.extname(pathname)
+ if (ext && ext.length <= 5) return ext
+ } catch {}
+ return '.bin'
+}
+
+/**
+ * 获取本地文件的绝对路径
+ */
+export function getAbsolutePath(relativePath: string): string {
+ if (relativePath.startsWith('static/')) {
+ return path.join(STORAGE_ROOT, '..', relativePath)
+ }
+ return path.join(STORAGE_ROOT, relativePath)
+}
diff --git a/web/vite.config.ts b/web/vite.config.ts
index f1872c9..b47be41 100644
--- a/web/vite.config.ts
+++ b/web/vite.config.ts
@@ -4,7 +4,7 @@ import { defineConfig, loadEnv } from 'vite'
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
- const apiTarget = env.VITE_API_BASE_URL || 'http://localhost:5678'
+ const apiTarget = env.VITE_API_BASE_URL || 'http://localhost:5679'
return {
plugins: [vue()],