🎬 火宝短剧 - 基于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
refactor: 提取 3 个核心 composable (useProfessionalEditor, useFrameImageGeneration, useVideoGenerationPro)
Connoraf5b99c76a51
diff --git a/web/src/composables/useFrameImageGeneration.ts b/web/src/composables/useFrameImageGeneration.tsnew file mode 100644index 0000000..ecef8dc--- /dev/null+++ b/web/src/composables/useFrameImageGeneration.ts@@ -0,0 +1,582 @@+import { ref, watch, type Ref } from 'vue'+import { ElMessage, ElMessageBox } from 'element-plus'+import { generateFramePrompt, type FrameType } from '@/api/frame'+import { imageAPI } from '@/api/image'+import { taskAPI } from '@/api/task'+import type { ImageGeneration } from '@/types/image'+import type { Storyboard } from '@/types/drama'+import { getImageUrl } from '@/utils/image'++export function useFrameImageGeneration(+ currentStoryboard: Ref<Storyboard | null>,+ dramaId: number,+) {+ // 状态+ const selectedFrameType = ref<FrameType>('first')+ const panelCount = ref(3)+ const generatingPromptStates = ref<Record<string, boolean>>({})+ const framePrompts = ref<Record<string, string>>({+ key: '',+ first: '',+ last: '',+ panel: '',+ })+ const currentFramePrompt = ref('')+ const generatingImage = ref(false)+ const generatedImages = ref<ImageGeneration[]>([])+ const isSwitchingFrameType = ref(false)+ const loadingImages = ref(false)+ let pollingTimer: any = null+ let pollingFrameType: FrameType | null = null++ // 宫格 / 裁剪+ const showGridEditor = ref(false)+ const allGeneratedImages = ref<ImageGeneration[]>([])+ const showCropDialog = ref(false)+ const cropImageUrl = ref<string>('')+ const cropImageData = ref<ImageGeneration | null>(null)++ // 视频参考图(供视频生成共享)+ const videoReferenceImages = ref<ImageGeneration[]>([])++ // 帧提示词存储 key+ const getPromptStorageKey = (+ storyboardId: string | number | undefined,+ frameType: FrameType,+ ) => {+ if (!storyboardId) return null+ return `frame_prompt_${storyboardId}_${frameType}`+ }++ // watch: 帧类型切换+ watch(selectedFrameType, (newType) => {+ stopPolling()++ if (!currentStoryboard.value) {+ currentFramePrompt.value = ''+ generatedImages.value = []+ return+ }++ isSwitchingFrameType.value = true++ const storageKey = `frame_prompt_${currentStoryboard.value.id}_${newType}`+ const stored = sessionStorage.getItem(storageKey)++ if (stored) {+ currentFramePrompt.value = stored+ framePrompts.value[newType] = stored+ } else {+ currentFramePrompt.value = framePrompts.value[newType] || ''+ }++ loadStoryboardImages(currentStoryboard.value.id, newType)++ setTimeout(() => {+ isSwitchingFrameType.value = false+ }, 0)+ })++ // watch: 分镜切换+ watch(currentStoryboard, async (newStoryboard) => {+ if (!newStoryboard) {+ currentFramePrompt.value = ''+ generatedImages.value = []+ videoReferenceImages.value = []+ return+ }++ isSwitchingFrameType.value = true++ framePrompts.value = { key: '', first: '', last: '', panel: '' }++ const storageKey = getPromptStorageKey(+ newStoryboard.id,+ selectedFrameType.value,+ )+ if (storageKey) {+ const stored = sessionStorage.getItem(storageKey)+ currentFramePrompt.value = stored || ''+ if (stored) {+ framePrompts.value[selectedFrameType.value] = stored+ }+ } else {+ currentFramePrompt.value = ''+ }++ setTimeout(() => {+ isSwitchingFrameType.value = false+ }, 0)++ await loadStoryboardImages(newStoryboard.id, selectedFrameType.value)+ await loadAllGeneratedImages()+ await loadVideoReferenceImages(newStoryboard.id)+ })++ // watch: 提示词变化 -> sessionStorage+ watch(currentFramePrompt, (newPrompt) => {+ if (isSwitchingFrameType.value) return+ if (!currentStoryboard.value) return++ const storageKey = getPromptStorageKey(+ currentStoryboard.value.id,+ selectedFrameType.value,+ )+ if (storageKey) {+ if (newPrompt) {+ sessionStorage.setItem(storageKey, newPrompt)+ } else {+ sessionStorage.removeItem(storageKey)+ }+ }+ })++ // 提取帧提示词+ const extractFramePrompt = async () => {+ if (!currentStoryboard.value) return++ const storyboardId = currentStoryboard.value.id+ const targetFrameType = selectedFrameType.value+ const stateKey = `${storyboardId}_${targetFrameType}`+ generatingPromptStates.value[stateKey] = true++ try {+ const params: any = { frame_type: targetFrameType }+ if (targetFrameType === 'panel') {+ params.panel_count = panelCount.value+ }++ const { task_id } = await generateFramePrompt(Number(storyboardId), params)++ const pollTask = async () => {+ while (true) {+ const task = await taskAPI.getStatus(task_id)+ if (task.status === 'completed') {+ let result = task.result+ if (typeof result === 'string') {+ try {+ result = JSON.parse(result)+ } catch (e) {+ console.error('Failed to parse task result', e)+ throw new Error('解析任务结果失败')+ }+ }+ return (result as any).response+ } else if (task.status === 'failed') {+ throw new Error(task.message || task.error || '生成失败')+ }+ await new Promise((resolve) => setTimeout(resolve, 1000))+ }+ }++ const result: any = await pollTask()++ let extractedPrompt = ''+ if (result.single_frame) {+ extractedPrompt = result.single_frame.prompt+ } else if (result.multi_frame && result.multi_frame.frames) {+ extractedPrompt = result.multi_frame.frames+ .map((frame: any) => frame.prompt)+ .join('\n\n')+ }++ const storageKey = getPromptStorageKey(storyboardId, targetFrameType)+ if (storageKey) {+ sessionStorage.setItem(storageKey, extractedPrompt)+ }++ if (+ currentStoryboard.value &&+ currentStoryboard.value.id === storyboardId &&+ selectedFrameType.value === targetFrameType+ ) {+ currentFramePrompt.value = extractedPrompt+ framePrompts.value[targetFrameType] = extractedPrompt+ }++ ElMessage.success(`${getFrameTypeLabel(targetFrameType)}提示词提取成功`)+ } catch (error: any) {+ ElMessage.error('提取失败: ' + (error.message || '未知错误'))+ } finally {+ const stateKey2 = `${storyboardId}_${targetFrameType}`+ if (generatingPromptStates.value[stateKey2]) {+ generatingPromptStates.value[stateKey2] = false+ }+ }+ }++ const isGeneratingPrompt = (+ storyboardId: string | number | undefined,+ frameType: string,+ ) => {+ if (!storyboardId) return false+ return !!generatingPromptStates.value[`${storyboardId}_${frameType}`]+ }++ const getFrameTypeLabel = (frameType: string): string => {+ const labels: Record<string, string> = {+ key: '关键帧',+ first: '首帧',+ last: '尾帧',+ panel: '分镜版',+ }+ return labels[frameType] || frameType+ }++ // 加载图片列表+ const loadStoryboardImages = async (+ storyboardId: string | number,+ frameType?: string,+ ) => {+ loadingImages.value = true+ try {+ const params: any = {+ storyboard_id: Number(storyboardId),+ page: 1,+ page_size: 50,+ }+ if (frameType) {+ params.frame_type = frameType+ }+ const result = await imageAPI.listImages(params)+ generatedImages.value = result.items || []++ const hasPendingOrProcessing = generatedImages.value.some(+ (img) => img.status === 'pending' || img.status === 'processing',+ )+ if (hasPendingOrProcessing) {+ startPolling()+ }+ } catch (error: any) {+ console.error('加载图片列表失败:', error)+ } finally {+ loadingImages.value = false+ }+ }++ // 轮询+ const startPolling = () => {+ if (pollingTimer) return+ pollingFrameType = selectedFrameType.value++ pollingTimer = setInterval(async () => {+ if (!currentStoryboard.value) {+ stopPolling()+ return+ }+ if (selectedFrameType.value !== pollingFrameType) {+ stopPolling()+ return+ }++ try {+ const params: any = {+ storyboard_id: Number(currentStoryboard.value.id),+ page: 1,+ page_size: 50,+ }+ if (pollingFrameType) {+ params.frame_type = pollingFrameType+ }+ const result = await imageAPI.listImages(params)++ if (selectedFrameType.value === pollingFrameType) {+ generatedImages.value = result.items || []+ }++ const hasPendingOrProcessing = (result.items || []).some(+ (img: any) => img.status === 'pending' || img.status === 'processing',+ )+ if (!hasPendingOrProcessing) {+ stopPolling()+ if (currentStoryboard.value) {+ loadVideoReferenceImages(currentStoryboard.value.id)+ }+ }+ } catch (error) {+ console.error('轮询图片状态失败:', error)+ }+ }, 3000)+ }++ const stopPolling = () => {+ if (pollingTimer) {+ clearInterval(pollingTimer)+ pollingTimer = null+ }+ pollingFrameType = null+ }++ // 生成图片+ const generateFrameImage = async (currentStoryboardCharacters: any[]) => {+ if (!currentStoryboard.value || !currentFramePrompt.value) return++ generatingImage.value = true+ try {+ const referenceImages: string[] = []++ if (currentStoryboard.value.background?.local_path) {+ referenceImages.push(currentStoryboard.value.background.local_path)+ }++ if (currentStoryboardCharacters && currentStoryboardCharacters.length > 0) {+ currentStoryboardCharacters.forEach((char: any) => {+ if (char.local_path) {+ referenceImages.push(char.local_path)+ }+ })+ }++ const result = await imageAPI.generateImage({+ drama_id: dramaId.toString(),+ prompt: currentFramePrompt.value,+ storyboard_id: Number(currentStoryboard.value.id),+ image_type: 'storyboard',+ frame_type: selectedFrameType.value,+ reference_images:+ referenceImages.length > 0 ? referenceImages : undefined,+ })++ generatedImages.value.unshift(result)++ const refMsg =+ referenceImages.length > 0+ ? ` (已添加${referenceImages.length}张参考图)`+ : ''+ ElMessage.success(`图片生成任务已提交${refMsg}`)++ startPolling()+ } catch (error: any) {+ ElMessage.error('生成失败: ' + (error.message || '未知错误'))+ } finally {+ generatingImage.value = false+ }+ }++ // 上传图片+ const uploadImage = async () => {+ if (!currentStoryboard.value) {+ ElMessage.warning('请先选择镜头')+ return+ }++ const input = document.createElement('input')+ input.type = 'file'+ input.accept = 'image/*'+ input.onchange = async (e: Event) => {+ const target = e.target as HTMLInputElement+ const file = target.files?.[0]+ if (!file) return++ if (file.size > 10 * 1024 * 1024) {+ ElMessage.error('图片大小不能超过 10MB')+ return+ }++ try {+ const formData = new FormData()+ formData.append('file', file)++ const response = await fetch('/api/v1/upload/image', {+ method: 'POST',+ body: formData,+ })++ if (!response.ok) {+ throw new Error('上传失败')+ }++ const result = await response.json()+ const imageUrl = result.data?.url++ if (imageUrl && currentStoryboard.value) {+ await imageAPI.uploadImage({+ storyboard_id: Number(currentStoryboard.value.id),+ drama_id: Number(dramaId),+ frame_type: selectedFrameType.value || 'first',+ image_url: imageUrl,+ prompt: currentFramePrompt.value || '用户上传图片',+ })++ await loadStoryboardImages(+ currentStoryboard.value.id,+ selectedFrameType.value,+ )++ ElMessage.success('图片上传成功')+ }+ } catch (error: any) {+ console.error('上传图片失败:', error)+ ElMessage.error(error.message || '上传失败')+ }+ }+ input.click()+ }++ // 删除图片+ const handleDeleteImage = async (img: ImageGeneration) => {+ if (!currentStoryboard.value) return++ try {+ await ElMessageBox.confirm('确定要删除这张图片吗?', '确认删除', {+ confirmButtonText: '确定',+ cancelButtonText: '取消',+ type: 'warning',+ })++ await imageAPI.deleteImage(img.id)+ ElMessage.success('删除成功')++ await loadStoryboardImages(+ currentStoryboard.value.id,+ selectedFrameType.value,+ )+ } catch (error: any) {+ if (error !== 'cancel') {+ console.error('删除图片失败:', error)+ ElMessage.error(error.message || '删除失败')+ }+ }+ }++ // 加载所有图片+ const loadAllGeneratedImages = async () => {+ if (!currentStoryboard.value) return++ try {+ const result = await imageAPI.listImages({+ storyboard_id: Number(currentStoryboard.value.id),+ page: 1,+ page_size: 100,+ })+ allGeneratedImages.value = result.items || []+ } catch (error: any) {+ console.error('加载所有图片失败:', error)+ }+ }++ // 加载视频参考图+ const loadVideoReferenceImages = async (storyboardId: string | number) => {+ try {+ const result = await imageAPI.listImages({+ storyboard_id: Number(storyboardId),+ page: 1,+ page_size: 100,+ })+ videoReferenceImages.value = result.items || []+ } catch (error: any) {+ console.error('加载视频参考图片失败:', error)+ }+ }++ // 宫格成功回调+ const handleGridImageSuccess = async () => {+ if (currentStoryboard.value) {+ await loadStoryboardImages(currentStoryboard.value.id, 'action')+ await loadAllGeneratedImages()+ }+ }++ // 裁剪对话框+ const openCropDialog = (img: ImageGeneration) => {+ cropImageData.value = img+ cropImageUrl.value = getImageUrl(img) || ''+ showCropDialog.value = true+ }++ const handleCropSave = async (images: { blob: Blob; frameType: string }[]) => {+ if (!currentStoryboard.value || !cropImageData.value) return++ try {+ const convertBlobToBase64 = (blob: Blob): Promise<string> => {+ return new Promise((resolve, reject) => {+ const reader = new FileReader()+ reader.onloadend = () => resolve(reader.result as string)+ reader.onerror = reject+ reader.readAsDataURL(blob)+ })+ }++ for (const img of images) {+ const imageUrl = await convertBlobToBase64(img.blob)++ await imageAPI.uploadImage({+ storyboard_id: Number(currentStoryboard.value.id),+ drama_id: Number(dramaId),+ frame_type: img.frameType,+ image_url: imageUrl,+ prompt: cropImageData.value.prompt || '',+ })+ }++ ElMessage.success('裁剪图片保存成功')++ if (currentStoryboard.value) {+ await loadStoryboardImages(currentStoryboard.value.id)+ await loadAllGeneratedImages()+ }+ } catch (error) {+ console.error('Failed to save cropped images:', error)+ ElMessage.error('保存裁剪图片失败')+ }+ }++ // 辅助+ const getStatusText = (status: string) => {+ const statusTextMap: Record<string, string> = {+ pending: '等待中',+ processing: '生成中',+ completed: '已完成',+ failed: '失败',+ }+ return statusTextMap[status] || status+ }++ const getStatusType = (status: string) => {+ const statusMap: Record<string, any> = {+ pending: 'info',+ processing: 'warning',+ completed: 'success',+ failed: 'danger',+ }+ return statusMap[status] || 'info'+ }++ const getStoryboardThumbnail = (storyboard: any) => {+ if (storyboard.composed_image) return storyboard.composed_image+ if (storyboard.image_url) return storyboard.image_url+ return null+ }++ return {+ selectedFrameType,+ currentFramePrompt,+ generatingImage,+ generatedImages,+ allGeneratedImages,+ videoReferenceImages,+ loadingImages,+ extractFramePrompt,+ generateFrameImage,+ uploadImage,+ handleDeleteImage,+ loadStoryboardImages,+ loadAllGeneratedImages,+ loadVideoReferenceImages,+ isGeneratingPrompt,+ getFrameTypeLabel,+ getStatusText,+ getStatusType,+ getStoryboardThumbnail,+ // 宫格/裁剪+ showGridEditor,+ showCropDialog,+ cropImageUrl,+ cropImageData,+ openCropDialog,+ handleCropSave,+ handleGridImageSuccess,+ // 轮询+ stopPolling,+ }+}diff --git a/web/src/composables/useProfessionalEditor.ts b/web/src/composables/useProfessionalEditor.tsnew file mode 100644index 0000000..e06eac3--- /dev/null+++ b/web/src/composables/useProfessionalEditor.ts@@ -0,0 +1,374 @@+import { ref, computed } from 'vue'+import { useRoute, useRouter } from 'vue-router'+import { useI18n } from 'vue-i18n'+import { ElMessage, ElMessageBox } from 'element-plus'+import { dramaAPI } from '@/api/drama'+import { propAPI } from '@/api/prop'+import type { Drama, Episode, Storyboard } from '@/types/drama'++export function useProfessionalEditor() {+ const route = useRoute()+ const router = useRouter()+ const { t: $t } = useI18n()++ // 路由参数+ const dramaId = Number(route.params.dramaId)+ const episodeNumber = Number(route.params.episodeNumber)+ const episodeId = ref<string | number>(0)++ // 核心数据+ const drama = ref<Drama | null>(null)+ const episode = ref<Episode | null>(null)+ const storyboards = ref<Storyboard[]>([])+ const characters = ref<any[]>([])+ const availableScenes = ref<any[]>([])+ const props = ref<any[]>([])++ // 当前选中+ const currentStoryboardId = ref<string | null>(null)++ // 弹窗状态+ const showSceneSelector = ref(false)+ const showCharacterSelector = ref(false)+ const showPropSelector = ref(false)+ const showCharacterImagePreview = ref(false)+ const previewCharacter = ref<any>(null)+ const showSceneImagePreview = ref(false)++ // computed+ const currentStoryboard = computed(() => {+ if (!currentStoryboardId.value) return null+ return storyboards.value.find(+ (s) => String(s.id) === String(currentStoryboardId.value),+ ) || null+ })++ const previousStoryboard = computed(() => {+ if (!currentStoryboardId.value || storyboards.value.length < 2) return null+ const currentIndex = storyboards.value.findIndex(+ (s) => String(s.id) === String(currentStoryboardId.value),+ )+ if (currentIndex <= 0) return null+ return storyboards.value[currentIndex - 1]+ })++ const currentStoryboardCharacters = computed(() => {+ if (!currentStoryboard.value?.characters) return []++ if (+ Array.isArray(currentStoryboard.value.characters) &&+ currentStoryboard.value.characters.length > 0+ ) {+ const firstItem = currentStoryboard.value.characters[0]+ if (typeof firstItem === 'object' && (firstItem as any).id) {+ return currentStoryboard.value.characters+ }+ if (typeof firstItem === 'number') {+ return characters.value.filter((c) =>+ currentStoryboard.value!.characters!.includes(c.id as any),+ )+ }+ }++ return []+ })++ const availableCharacters = computed(() => characters.value || [])++ const availableProps = computed(() => props.value || [])++ const currentStoryboardProps = computed(() => {+ if (!currentStoryboard.value?.props) return []+ return currentStoryboard.value.props+ })++ // 方法+ const loadData = async () => {+ try {+ const dramaRes = await dramaAPI.get(dramaId.toString())+ drama.value = dramaRes++ const ep = dramaRes.episodes?.find(+ (e) => e.episode_number === episodeNumber,+ )+ if (!ep) {+ ElMessage.error('章节不存在')+ router.back()+ return+ }++ episode.value = ep+ episodeId.value = ep.id++ const storyboardsRes = await dramaAPI.getStoryboards(ep.id.toString())+ storyboards.value = (storyboardsRes as any)?.storyboards || []++ if (storyboards.value.length > 0 && !currentStoryboardId.value) {+ currentStoryboardId.value = storyboards.value[0].id+ }++ characters.value = dramaRes.characters || []+ availableScenes.value = dramaRes.scenes || []+ props.value = dramaRes.props || []+ } catch (error: any) {+ ElMessage.error('加载数据失败: ' + (error.message || '未知错误'))+ }+ }++ const selectStoryboard = (id: string) => {+ currentStoryboardId.value = id+ }++ const goBack = () => {+ router.replace({+ name: 'EpisodeWorkflowNew',+ params: { id: dramaId, episodeNumber },+ })+ }++ const handleAddStoryboard = async () => {+ if (!episodeId.value) return++ try {+ const nextShotNumber =+ storyboards.value.length > 0+ ? Math.max(...storyboards.value.map((s) => s.storyboard_number)) + 1+ : 1++ await dramaAPI.createStoryboard({+ episode_id: Number(episodeId.value),+ storyboard_number: nextShotNumber,+ title: `镜头 ${nextShotNumber}`,+ description: '新镜头描述',+ action: '动作描述',+ dialogue: '',+ duration: 5,+ scene_id:+ storyboards.value.length > 0+ ? Number(storyboards.value[storyboards.value.length - 1].scene_id)+ : undefined,+ })++ ElMessage.success('添加分镜成功')+ await loadData()++ if (storyboards.value.length > 0) {+ selectStoryboard(storyboards.value[storyboards.value.length - 1].id)+ }+ } catch (error: any) {+ console.error('添加分镜失败:', error)+ ElMessage.error(error.message || '添加分镜失败')+ }+ }++ const handleDeleteStoryboard = async (storyboard: any) => {+ try {+ await ElMessageBox.confirm(+ `确定要删除镜头 ${storyboard.storyboard_number} 吗?此操作不可恢复。`,+ '删除确认',+ {+ confirmButtonText: '确定',+ cancelButtonText: '取消',+ type: 'warning',+ },+ )++ await dramaAPI.deleteStoryboard(storyboard.id)+ ElMessage.success('删除分镜成功')++ if (currentStoryboardId.value === storyboard.id) {+ currentStoryboardId.value = null+ }++ await loadData()+ } catch (error: any) {+ if (error !== 'cancel') {+ console.error('删除分镜失败:', error)+ ElMessage.error(error.message || '删除分镜失败')+ }+ }+ }++ const saveStoryboardField = async (fieldName: string) => {+ if (!currentStoryboard.value) return+ try {+ const updateData: any = {}+ updateData[fieldName] = (currentStoryboard.value as any)[fieldName]++ await dramaAPI.updateStoryboard(+ currentStoryboard.value.id.toString(),+ updateData,+ )+ } catch (error: any) {+ ElMessage.error('保存失败: ' + (error.message || '未知错误'))+ }+ }++ const toggleCharacterInShot = async (charId: number) => {+ if (!currentStoryboard.value) return++ if (!currentStoryboard.value.characters) {+ currentStoryboard.value.characters = []+ }++ const char = characters.value.find((c) => c.id === charId)+ if (!char) return++ const existIndex = currentStoryboard.value.characters.findIndex((c) =>+ typeof c === 'object' ? (c as any).id === charId : Number(c) === charId,+ )++ if (existIndex > -1) {+ currentStoryboard.value.characters.splice(existIndex, 1)+ } else {+ currentStoryboard.value.characters.push(char)+ }++ try {+ const characterIds = currentStoryboard.value.characters.map((c) =>+ typeof c === 'object' ? (c as any).id : Number(c),+ )++ await dramaAPI.updateStoryboard(currentStoryboard.value.id.toString(), {+ character_ids: characterIds,+ })++ if (existIndex > -1) {+ ElMessage.success(`已移除角色: ${char.name}`)+ } else {+ ElMessage.success(`已添加角色: ${char.name}`)+ }+ } catch (error: any) {+ ElMessage.error('保存失败: ' + (error.message || '未知错误'))+ if (existIndex > -1) {+ currentStoryboard.value.characters.push(char)+ } else {+ currentStoryboard.value.characters.splice(+ currentStoryboard.value.characters.length - 1,+ 1,+ )+ }+ }+ }++ const isCharacterInCurrentShot = (charId: number) => {+ if (!currentStoryboard.value?.characters) return false++ if (+ Array.isArray(currentStoryboard.value.characters) &&+ currentStoryboard.value.characters.length > 0+ ) {+ const firstItem = currentStoryboard.value.characters[0]+ if (typeof firstItem === 'object' && (firstItem as any).id) {+ return currentStoryboard.value.characters.some((c: any) => c.id === charId)+ }+ if (typeof firstItem === 'number') {+ return (currentStoryboard.value.characters as any[]).includes(charId)+ }+ }++ return false+ }++ const togglePropInShot = async (propId: number) => {+ if (!currentStoryboard.value) return++ let newProps = [...(currentStoryboard.value.props || [])]+ if (isPropInCurrentShot(propId)) {+ newProps = newProps.filter((p: any) => p.id !== propId)+ } else {+ const prop = props.value.find((p) => p.id === propId)+ if (prop) {+ newProps.push(prop)+ }+ }++ currentStoryboard.value.props = newProps++ try {+ const propIds = newProps.map((p: any) => p.id)+ await propAPI.associateWithStoryboard(+ Number(currentStoryboard.value.id),+ propIds,+ )+ } catch (error) {+ ElMessage.error($t('editor.updatePropFailed'))+ }+ }++ const isPropInCurrentShot = (propId: number) => {+ if (!currentStoryboard.value?.props) return false+ return currentStoryboard.value.props.some((p: any) => p.id === propId)+ }++ const selectScene = async (sceneId: number) => {+ if (!currentStoryboard.value) return++ try {+ await dramaAPI.updateStoryboard(currentStoryboard.value.id.toString(), {+ scene_id: String(sceneId),+ })++ await loadData()+ showSceneSelector.value = false+ ElMessage.success('场景关联成功')+ } catch (error: any) {+ ElMessage.error(error.message || '场景关联失败')+ }+ }++ const showCharacterImage = (char: any) => {+ previewCharacter.value = char+ showCharacterImagePreview.value = true+ }++ const showSceneImage = () => {+ if (currentStoryboard.value?.background?.image_url) {+ showSceneImagePreview.value = true+ }+ }++ return {+ // 路由+ dramaId,+ episodeNumber,+ episodeId,+ // 核心数据+ drama,+ episode,+ storyboards,+ characters,+ availableScenes,+ props,+ // 选中状态+ currentStoryboardId,+ currentStoryboard,+ previousStoryboard,+ // computed+ currentStoryboardCharacters,+ currentStoryboardProps,+ availableCharacters,+ availableProps,+ // 弹窗状态+ showSceneSelector,+ showCharacterSelector,+ showPropSelector,+ showCharacterImagePreview,+ previewCharacter,+ showSceneImagePreview,+ // 方法+ loadData,+ selectStoryboard,+ goBack,+ handleAddStoryboard,+ handleDeleteStoryboard,+ saveStoryboardField,+ toggleCharacterInShot,+ isCharacterInCurrentShot,+ togglePropInShot,+ isPropInCurrentShot,+ selectScene,+ showCharacterImage,+ showSceneImage,+ }+}diff --git a/web/src/composables/useVideoGenerationPro.ts b/web/src/composables/useVideoGenerationPro.tsnew file mode 100644index 0000000..7548d19--- /dev/null+++ b/web/src/composables/useVideoGenerationPro.ts@@ -0,0 +1,746 @@+import { ref, computed, watch, type Ref } from 'vue'+import { ElMessage, ElMessageBox } from 'element-plus'+import { dramaAPI } from '@/api/drama'+import { imageAPI } from '@/api/image'+import { videoAPI } from '@/api/video'+import { assetAPI } from '@/api/asset'+import { aiAPI } from '@/api/ai'+import type { FrameType } from '@/api/frame'+import type { ImageGeneration } from '@/types/image'+import type { VideoGeneration } from '@/types/video'+import type { Asset } from '@/types/asset'+import type { Storyboard } from '@/types/drama'+import { getVideoUrl } from '@/utils/image'++// 视频模型能力配置+export interface VideoModelCapability {+ id: string+ name: string+ supportMultipleImages: boolean+ supportFirstLastFrame: boolean+ supportSingleImage: boolean+ supportTextOnly: boolean+ maxImages: number+}++// 模型能力默认配置(作为后备)+const defaultModelCapabilities: Record<+ string,+ Omit<VideoModelCapability, 'id' | 'name'>+> = {+ kling: {+ supportSingleImage: true,+ supportMultipleImages: false,+ supportFirstLastFrame: false,+ supportTextOnly: true,+ maxImages: 1,+ },+ runway: {+ supportSingleImage: true,+ supportMultipleImages: false,+ supportFirstLastFrame: true,+ supportTextOnly: true,+ maxImages: 2,+ },+ pika: {+ supportSingleImage: true,+ supportMultipleImages: true,+ supportFirstLastFrame: false,+ supportTextOnly: true,+ maxImages: 6,+ },+ 'doubao-seedance-1-5-pro-251215': {+ supportSingleImage: true,+ supportMultipleImages: false,+ supportFirstLastFrame: true,+ supportTextOnly: true,+ maxImages: 2,+ },+ 'doubao-seedance-1-0-lite-i2v-250428': {+ supportSingleImage: true,+ supportMultipleImages: true,+ supportFirstLastFrame: true,+ supportTextOnly: false,+ maxImages: 6,+ },+ 'doubao-seedance-1-0-lite-t2v-250428': {+ supportSingleImage: false,+ supportMultipleImages: false,+ supportFirstLastFrame: false,+ supportTextOnly: true,+ maxImages: 0,+ },+ 'doubao-seedance-1-0-pro-250528': {+ supportSingleImage: true,+ supportMultipleImages: false,+ supportFirstLastFrame: true,+ supportTextOnly: true,+ maxImages: 2,+ },+ 'doubao-seedance-1-0-pro-fast-251015': {+ supportSingleImage: true,+ supportMultipleImages: false,+ supportFirstLastFrame: false,+ supportTextOnly: true,+ maxImages: 1,+ },+ 'sora-2': {+ supportSingleImage: true,+ supportMultipleImages: false,+ supportFirstLastFrame: false,+ supportTextOnly: true,+ maxImages: 1,+ },+ 'sora-2-pro': {+ supportSingleImage: true,+ supportMultipleImages: false,+ supportFirstLastFrame: true,+ supportTextOnly: true,+ maxImages: 2,+ },+ 'MiniMax-Hailuo-2.3': {+ supportSingleImage: true,+ supportMultipleImages: false,+ supportFirstLastFrame: false,+ supportTextOnly: true,+ maxImages: 1,+ },+ 'MiniMax-Hailuo-2.3-Fast': {+ supportSingleImage: true,+ supportMultipleImages: false,+ supportFirstLastFrame: false,+ supportTextOnly: true,+ maxImages: 1,+ },+ 'MiniMax-Hailuo-02': {+ supportSingleImage: true,+ supportMultipleImages: false,+ supportFirstLastFrame: false,+ supportTextOnly: true,+ maxImages: 1,+ },+}++const extractProviderFromModel = (modelName: string): string => {+ if (modelName.startsWith('doubao-') || modelName.startsWith('seedance'))+ return 'doubao'+ if (modelName.startsWith('runway')) return 'runway'+ if (modelName.startsWith('pika')) return 'pika'+ if (+ modelName.startsWith('MiniMax-') ||+ modelName.toLowerCase().startsWith('minimax') ||+ modelName.startsWith('hailuo')+ )+ return 'minimax'+ if (modelName.startsWith('sora')) return 'openai'+ if (modelName.startsWith('kling')) return 'kling'+ return 'doubao'+}++export function useVideoGenerationPro(+ currentStoryboard: Ref<Storyboard | null>,+ dramaId: number,+ episodeId: Ref<string | number>,+ storyboards: Ref<Storyboard[]>,+ videoReferenceImages: Ref<ImageGeneration[]>,+ timelineEditorRef: Ref<any>,+) {+ // 状态+ const videoDuration = ref(5)+ const selectedVideoFrameType = ref<FrameType>('first')+ const selectedImagesForVideo = ref<number[]>([])+ const selectedLastImageForVideo = ref<number | null>(null)+ const generatingVideo = ref(false)+ const generatedVideos = ref<VideoGeneration[]>([])+ const videoAssets = ref<Asset[]>([])+ const loadingVideos = ref(false)+ const selectedVideoModel = ref<string>('')+ const selectedReferenceMode = ref<string>('')+ const videoModelCapabilities = ref<VideoModelCapability[]>([])+ const showVideoPreview = ref(false)+ const previewVideo = ref<VideoGeneration | null>(null)+ const addingToAssets = ref<Set<number>>(new Set())+ let videoPollingTimer: any = null++ // 上一镜头尾帧+ const previousStoryboardLastFrames = ref<any[]>([])++ // computed+ const currentModelCapability = computed(() => {+ return videoModelCapabilities.value.find(+ (m) => m.id === selectedVideoModel.value,+ )+ })++ const availableReferenceModes = computed(() => {+ const capability = currentModelCapability.value+ if (!capability) return []++ const modes: Array<{ value: string; label: string; description?: string }> = []++ if (capability.supportTextOnly) {+ modes.push({ value: 'none', label: '纯文本', description: '不使用参考图' })+ }+ if (capability.supportSingleImage) {+ modes.push({ value: 'single', label: '单图', description: '使用单张参考图' })+ }+ if (capability.supportFirstLastFrame) {+ modes.push({+ value: 'first_last',+ label: '首尾帧',+ description: '使用首帧和尾帧',+ })+ }+ if (capability.supportMultipleImages) {+ modes.push({+ value: 'multiple',+ label: '多图',+ description: `最多${capability.maxImages}张`,+ })+ }++ return modes+ })++ const firstFrameSlotImage = computed(() => {+ if (selectedImagesForVideo.value.length === 0) return null+ const firstImageId = selectedImagesForVideo.value[0]+ return (+ videoReferenceImages.value.find((img) => img.id === firstImageId) ||+ previousStoryboardLastFrames.value.find((img) => img.id === firstImageId)+ )+ })++ const lastFrameSlotImage = computed(() => {+ if (!selectedLastImageForVideo.value) return null+ return (+ videoReferenceImages.value.find(+ (img) => img.id === selectedLastImageForVideo.value,+ ) ||+ previousStoryboardLastFrames.value.find(+ (img) => img.id === selectedLastImageForVideo.value,+ )+ )+ })++ // watch+ watch(selectedVideoModel, () => {+ selectedImagesForVideo.value = []+ selectedLastImageForVideo.value = null+ selectedReferenceMode.value = ''+ })++ watch(currentStoryboard, (newStoryboard) => {+ if (newStoryboard?.duration) {+ videoDuration.value = Math.round(newStoryboard.duration)+ } else {+ videoDuration.value = 5+ }+ generatedVideos.value = []+ previousStoryboardLastFrames.value = []++ if (newStoryboard) {+ loadStoryboardVideos(newStoryboard.id)+ loadPreviousStoryboardLastFrame()+ }+ })++ watch(selectedReferenceMode, () => {+ selectedImagesForVideo.value = []+ selectedLastImageForVideo.value = null+ })++ // 方法+ const loadVideoModels = async () => {+ try {+ const configs = await aiAPI.list('video')+ const activeConfigs = configs.filter((c) => c.is_active)++ const allModels = activeConfigs+ .flatMap((config) => {+ const models = Array.isArray(config.model)+ ? config.model+ : [config.model]+ return models.map((modelName) => ({+ modelName,+ configName: config.name,+ priority: config.priority || 0,+ }))+ })+ .sort((a, b) => b.priority - a.priority)++ const modelMap = new Map<string, { configName: string; priority: number }>()+ allModels.forEach((model) => {+ if (!modelMap.has(model.modelName)) {+ modelMap.set(model.modelName, {+ configName: model.configName,+ priority: model.priority,+ })+ }+ })++ videoModelCapabilities.value = Array.from(modelMap.keys()).map(+ (modelName) => {+ const capability = defaultModelCapabilities[modelName] || {+ supportSingleImage: true,+ supportMultipleImages: false,+ supportFirstLastFrame: false,+ supportTextOnly: true,+ maxImages: 1,+ }++ return {+ id: modelName,+ name: modelName,+ ...capability,+ }+ },+ )+ } catch (error: any) {+ console.error('加载视频模型配置失败:', error)+ ElMessage.error('加载视频模型失败')+ }+ }++ const loadVideoAssets = async () => {+ try {+ const result = await assetAPI.listAssets({+ drama_id: dramaId.toString(),+ episode_id: Number(episodeId.value) || undefined,+ type: 'video',+ page: 1,+ page_size: 100,+ })+ videoAssets.value = result.items || []+ } catch (error: any) {+ console.error('加载视频素材库失败:', error)+ }+ }++ const loadPreviousStoryboardLastFrame = async () => {+ if (!currentStoryboard.value || storyboards.value.length < 2) {+ previousStoryboardLastFrames.value = []+ return+ }+ const currentIndex = storyboards.value.findIndex(+ (s) => String(s.id) === String(currentStoryboard.value!.id),+ )+ if (currentIndex <= 0) {+ previousStoryboardLastFrames.value = []+ return+ }+ const prevStoryboard = storyboards.value[currentIndex - 1]+ try {+ const result = await imageAPI.listImages({+ storyboard_id: Number(prevStoryboard.id),+ frame_type: 'last',+ page: 1,+ page_size: 10,+ })+ const images = result.items || []+ previousStoryboardLastFrames.value = images.filter(+ (img: any) => img.status === 'completed' && img.image_url,+ )+ } catch (error) {+ console.error('加载上一镜头尾帧失败:', error)+ previousStoryboardLastFrames.value = []+ }+ }++ const handleImageSelect = (imageId: number) => {+ if (!selectedReferenceMode.value) {+ ElMessage.warning('请先选择参考图模式')+ return+ }+ if (!currentModelCapability.value) {+ ElMessage.warning('请先选择视频生成模型')+ return+ }++ const capability = currentModelCapability.value+ const currentIndex = selectedImagesForVideo.value.indexOf(imageId)++ if (currentIndex > -1) {+ selectedImagesForVideo.value.splice(currentIndex, 1)+ return+ }++ const clickedImage = videoReferenceImages.value.find(+ (img) => img.id === imageId,+ )+ if (!clickedImage) return++ switch (selectedReferenceMode.value) {+ case 'single':+ selectedImagesForVideo.value = [imageId]+ break+ case 'first_last': {+ const frameType = clickedImage.frame_type+ if (+ frameType === 'first' ||+ frameType === 'panel' ||+ frameType === 'key'+ ) {+ selectedImagesForVideo.value = [imageId]+ } else if (frameType === 'last') {+ selectedLastImageForVideo.value = imageId+ } else {+ ElMessage.warning('首尾帧模式下,请选择首帧或尾帧类型的图片')+ }+ break+ }+ case 'multiple':+ if (selectedImagesForVideo.value.length >= capability.maxImages) {+ ElMessage.warning(`最多只能选择${capability.maxImages}张图片`)+ return+ }+ selectedImagesForVideo.value.push(imageId)+ break+ default:+ ElMessage.warning('未知的参考图模式')+ }+ }++ const removeSelectedImage = (imageId: number) => {+ if (selectedLastImageForVideo.value === imageId) {+ selectedLastImageForVideo.value = null+ return+ }+ const index = selectedImagesForVideo.value.indexOf(imageId)+ if (index > -1) {+ selectedImagesForVideo.value.splice(index, 1)+ }+ }++ const selectPreviousLastFrame = (img: any) => {+ const currentIndex = selectedImagesForVideo.value.indexOf(img.id)+ if (currentIndex > -1) {+ selectedImagesForVideo.value.splice(currentIndex, 1)+ ElMessage.success('已取消首帧参考')+ return+ }++ if (+ !selectedReferenceMode.value ||+ selectedReferenceMode.value === 'single'+ ) {+ selectedImagesForVideo.value = [img.id]+ } else if (selectedReferenceMode.value === 'first_last') {+ selectedImagesForVideo.value = [img.id]+ } else if (selectedReferenceMode.value === 'multiple') {+ const capability = currentModelCapability.value+ if (+ capability &&+ selectedImagesForVideo.value.length >= capability.maxImages+ ) {+ ElMessage.warning(`最多只能选择${capability.maxImages}张图片`)+ return+ }+ selectedImagesForVideo.value.push(img.id)+ }+ ElMessage.success('已添加为首帧参考')+ }++ const generateVideo = async () => {+ if (!selectedVideoModel.value) {+ ElMessage.warning('请先选择视频生成模型')+ return+ }+ if (!currentStoryboard.value) {+ ElMessage.warning('请先选择分镜')+ return+ }+ if (+ selectedReferenceMode.value !== 'none' &&+ selectedImagesForVideo.value.length === 0+ ) {+ ElMessage.warning('请选择参考图片')+ return+ }++ let selectedImage: any = null+ if (+ selectedReferenceMode.value !== 'none' &&+ selectedImagesForVideo.value.length > 0+ ) {+ selectedImage =+ videoReferenceImages.value.find(+ (img) => img.id === selectedImagesForVideo.value[0],+ ) ||+ previousStoryboardLastFrames.value.find(+ (img) => img.id === selectedImagesForVideo.value[0],+ )+ if (!selectedImage || !selectedImage.image_url) {+ ElMessage.error('请选择有效的参考图片')+ return+ }+ }++ generatingVideo.value = true+ try {+ const provider = extractProviderFromModel(selectedVideoModel.value)++ const requestParams: any = {+ drama_id: dramaId.toString(),+ storyboard_id: Number(currentStoryboard.value.id),+ prompt:+ currentStoryboard.value.video_prompt ||+ currentStoryboard.value.action ||+ currentStoryboard.value.description ||+ '',+ duration: videoDuration.value,+ provider: provider,+ model: selectedVideoModel.value,+ reference_mode: selectedReferenceMode.value,+ }++ switch (selectedReferenceMode.value) {+ case 'single':+ if (selectedImage.local_path) {+ requestParams.image_local_path = selectedImage.local_path+ } else if (selectedImage.image_url) {+ requestParams.image_url = selectedImage.image_url+ }+ requestParams.image_gen_id = selectedImage.id+ break++ case 'first_last': {+ const firstImage =+ videoReferenceImages.value.find(+ (img) => img.id === selectedImagesForVideo.value[0],+ ) ||+ previousStoryboardLastFrames.value.find(+ (img) => img.id === selectedImagesForVideo.value[0],+ )+ const lastImage =+ videoReferenceImages.value.find(+ (img) => img.id === selectedLastImageForVideo.value,+ ) ||+ previousStoryboardLastFrames.value.find(+ (img) => img.id === selectedLastImageForVideo.value,+ )++ if (firstImage?.local_path) {+ requestParams.first_frame_local_path = firstImage.local_path+ } else if (firstImage?.image_url) {+ requestParams.first_frame_url = firstImage.image_url+ }+ if (lastImage?.local_path) {+ requestParams.last_frame_local_path = lastImage.local_path+ } else if (lastImage?.image_url) {+ requestParams.last_frame_url = lastImage.image_url+ }+ break+ }++ case 'multiple': {+ const selectedImages = selectedImagesForVideo.value+ .map((id) => videoReferenceImages.value.find((img) => img.id === id))+ .filter((img) => img?.local_path || img?.image_url)+ .map((img) => img!.local_path || img!.image_url)+ requestParams.reference_image_urls = selectedImages+ break+ }++ case 'none':+ break+ }++ const result = await videoAPI.generateVideo(requestParams)+ generatedVideos.value.unshift(result)+ ElMessage.success('视频生成任务已提交')+ startVideoPolling()+ } catch (error: any) {+ ElMessage.error('生成失败: ' + (error.message || '未知错误'))+ } finally {+ generatingVideo.value = false+ }+ }++ const loadStoryboardVideos = async (storyboardId: string | number) => {+ loadingVideos.value = true+ try {+ const result = await videoAPI.listVideos({+ storyboard_id: storyboardId.toString(),+ page: 1,+ page_size: 50,+ })+ generatedVideos.value = result.items || []++ const hasPendingOrProcessing = generatedVideos.value.some(+ (v) => v.status === 'pending' || v.status === 'processing',+ )+ if (hasPendingOrProcessing) {+ startVideoPolling()+ }+ } catch (error: any) {+ console.error('加载视频列表失败:', error)+ } finally {+ loadingVideos.value = false+ }+ }++ const startVideoPolling = () => {+ if (videoPollingTimer) return++ videoPollingTimer = setInterval(async () => {+ if (!currentStoryboard.value) {+ stopVideoPolling()+ return+ }++ try {+ const oldVideos = [...generatedVideos.value]++ const result = await videoAPI.listVideos({+ storyboard_id: currentStoryboard.value.id.toString(),+ page: 1,+ page_size: 50,+ })+ generatedVideos.value = result.items || []++ const hasNewlyCompleted = generatedVideos.value.some((newVideo) => {+ const oldVideo = oldVideos.find((v) => v.id === newVideo.id)+ return (+ oldVideo &&+ (oldVideo.status === 'pending' || oldVideo.status === 'processing') &&+ newVideo.status === 'completed'+ )+ })++ if (hasNewlyCompleted && episodeId.value) {+ try {+ const storyboardsRes = await dramaAPI.getStoryboards(+ episodeId.value.toString(),+ )+ storyboards.value = (storyboardsRes as any)?.storyboards || []+ } catch (error) {+ console.error('重新加载分镜列表失败:', error)+ }+ }++ const hasPendingOrProcessing = generatedVideos.value.some(+ (v) => v.status === 'pending' || v.status === 'processing',+ )+ if (!hasPendingOrProcessing) {+ stopVideoPolling()+ }+ } catch (error) {+ console.error('轮询视频状态失败:', error)+ }+ }, 5000)+ }++ const stopVideoPolling = () => {+ if (videoPollingTimer) {+ clearInterval(videoPollingTimer)+ videoPollingTimer = null+ }+ }++ const playVideo = (video: VideoGeneration) => {+ previewVideo.value = video+ showVideoPreview.value = true+ }++ const addVideoToAssets = async (video: VideoGeneration) => {+ if (video.status !== 'completed' || !video.video_url) {+ ElMessage.warning('只能添加已完成的视频到素材库')+ return+ }++ addingToAssets.value.add(video.id)++ try {+ let isReplacing = false+ if (video.storyboard_id) {+ const existingAsset = videoAssets.value.find(+ (asset: any) => asset.storyboard_id === video.storyboard_id,+ )++ if (existingAsset) {+ isReplacing = true+ try {+ await assetAPI.deleteAsset(existingAsset.id)+ } catch (error) {+ console.error('删除旧素材失败:', error)+ }+ }+ }++ await assetAPI.importFromVideo(video.id)+ ElMessage.success('已添加到素材库')++ await loadVideoAssets()++ if (isReplacing && video.storyboard_id && video.video_url) {+ if (timelineEditorRef.value) {+ timelineEditorRef.value.updateClipsByStoryboardId(+ video.storyboard_id,+ video.video_url,+ )+ }+ }+ } catch (error: any) {+ ElMessage.error(error.message || '添加失败')+ } finally {+ addingToAssets.value.delete(video.id)+ }+ }++ const handleDeleteVideo = async (video: VideoGeneration) => {+ if (!currentStoryboard.value) return++ try {+ await ElMessageBox.confirm(+ '确定要删除这个视频吗?删除后无法恢复。',+ '确认删除',+ {+ confirmButtonText: '确定',+ cancelButtonText: '取消',+ type: 'warning',+ },+ )++ await videoAPI.deleteVideo(video.id)+ ElMessage.success('删除成功')++ await loadStoryboardVideos(Number(currentStoryboard.value.id))+ } catch (error: any) {+ if (error !== 'cancel') {+ console.error('删除视频失败:', error)+ ElMessage.error(error.message || '删除失败')+ }+ }+ }++ return {+ videoDuration,+ selectedVideoFrameType,+ selectedImagesForVideo,+ selectedVideoModel,+ selectedReferenceMode,+ generatingVideo,+ generatedVideos,+ videoModelCapabilities,+ videoAssets,+ currentModelCapability,+ availableReferenceModes,+ firstFrameSlotImage,+ lastFrameSlotImage,+ previousStoryboardLastFrames,+ showVideoPreview,+ previewVideo,+ loadVideoModels,+ loadVideoAssets,+ generateVideo,+ loadStoryboardVideos,+ handleImageSelect,+ removeSelectedImage,+ selectPreviousLastFrame,+ playVideo,+ addVideoToAssets,+ handleDeleteVideo,+ stopVideoPolling,+ }+}