🎬 火宝短剧 - 基于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:更改图片、视频资源为本地地址
jiangzijun895cb8710e61
diff --git a/api/handlers/drama.go b/api/handlers/drama.goindex f102771..c791652 100644--- a/api/handlers/drama.go+++ b/api/handlers/drama.go@@ -22,7 +22,7 @@ type DramaHandler struct {func NewDramaHandler(db *gorm.DB, cfg *config.Config, log *logger.Logger, transferService *services.ResourceTransferService) *DramaHandler {return &DramaHandler{db: db,- dramaService: services.NewDramaService(db, log),+ dramaService: services.NewDramaService(db, cfg, log),videoMergeService: services.NewVideoMergeService(db, transferService, cfg.Storage.LocalPath, cfg.Storage.BaseURL, log),log: log,}diff --git a/application/services/asset_service.go b/application/services/asset_service.goindex c630c5c..6fb75b8 100644--- a/application/services/asset_service.go+++ b/application/services/asset_service.go@@ -268,6 +268,7 @@ func (s *AssetService) ImportFromVideoGen(videoGenID uint) (*models.Asset, errorName: fmt.Sprintf("Video_%d", videoGen.ID),Type: models.AssetTypeVideo,URL: *videoGen.VideoURL,+ LocalPath: videoGen.LocalPath, // 同步 local_path 到 assets 表DramaID: &dramaID,EpisodeID: episodeID,StoryboardID: videoGen.StoryboardID,diff --git a/application/services/drama_service.go b/application/services/drama_service.goindex 19b251f..276f687 100644--- a/application/services/drama_service.go+++ b/application/services/drama_service.go@@ -8,19 +8,22 @@ import ("time""github.com/drama-generator/backend/domain/models"+ "github.com/drama-generator/backend/pkg/config""github.com/drama-generator/backend/pkg/logger""gorm.io/gorm")type DramaService struct {- db *gorm.DB- log *logger.Logger+ db *gorm.DB+ log *logger.Logger+ baseURL string}-func NewDramaService(db *gorm.DB, log *logger.Logger) *DramaService {+func NewDramaService(db *gorm.DB, cfg *config.Config, log *logger.Logger) *DramaService {return &DramaService{- db: db,- log: log,+ db: db,+ log: log,+ baseURL: cfg.Storage.BaseURL,}}@@ -188,7 +191,8 @@ func (s *DramaService) GetDrama(dramaID string) (*models.Drama, error) {drama.Scenes = append(drama.Scenes, *scene)}- // local_path 已通过 Preload 从 characters 和 scenes 表加载,无需额外查询+ // 为所有场景的 local_path 添加 base_url 前缀+ // s.addBaseURLToScenes(&drama)return &drama, nil}@@ -656,3 +660,24 @@ func (s *DramaService) SaveProgress(dramaID string, req *SaveProgressRequest) ers.log.Infow("Progress saved", "drama_id", dramaID, "step", req.CurrentStep)return nil}++// addBaseURLToScenes 为剧本中所有场景的 local_path 添加 base_url 前缀+func (s *DramaService) addBaseURLToScenes(drama *models.Drama) {+ // 处理 drama.Scenes+ for i := range drama.Scenes {+ if drama.Scenes[i].LocalPath != nil && *drama.Scenes[i].LocalPath != "" {+ fullPath := fmt.Sprintf("%s/%s", s.baseURL, *drama.Scenes[i].LocalPath)+ drama.Scenes[i].LocalPath = &fullPath+ }+ }++ // 处理 drama.Episodes[].Scenes+ for i := range drama.Episodes {+ for j := range drama.Episodes[i].Scenes {+ if drama.Episodes[i].Scenes[j].LocalPath != nil && *drama.Episodes[i].Scenes[j].LocalPath != "" {+ fullPath := fmt.Sprintf("%s/%s", s.baseURL, *drama.Episodes[i].Scenes[j].LocalPath)+ drama.Episodes[i].Scenes[j].LocalPath = &fullPath+ }+ }+ }+}diff --git a/application/services/video_generation_service.go b/application/services/video_generation_service.goindex dee0e9a..a30a2cd 100644--- a/application/services/video_generation_service.go+++ b/application/services/video_generation_service.go@@ -379,22 +379,38 @@ func (s *VideoGenerationService) completeVideoGeneration(videoGenID uint, videoU}// 如果视频已下载到本地,探测真实时长- if localVideoPath != nil && s.ffmpeg != nil {+ // 特别是当 AI 服务返回的 duration 为 0 或 nil 时,必须探测+ shouldProbe := localVideoPath != nil && s.ffmpeg != nil && (duration == nil || *duration == 0)+ if shouldProbe {absPath := s.localStorage.GetAbsolutePath(*localVideoPath)if probedDuration, err := s.ffmpeg.GetVideoDuration(absPath); err == nil {// 转换为整数秒(向上取整)durationInt := int(probedDuration + 0.5)duration = &durationInt- s.log.Infow("Probed video duration",+ s.log.Infow("Probed video duration (was 0 or nil)","id", videoGenID,"duration_seconds", durationInt,"duration_float", probedDuration)} else {- s.log.Warnw("Failed to probe video duration, using provided duration",+ s.log.Errorw("Failed to probe video duration, duration will be 0","error", err,"id", videoGenID,"local_path", *localVideoPath)}+ } else if localVideoPath != nil && s.ffmpeg != nil && duration != nil && *duration > 0 {+ // 即使有 duration,也验证一下(可选)+ absPath := s.localStorage.GetAbsolutePath(*localVideoPath)+ if probedDuration, err := s.ffmpeg.GetVideoDuration(absPath); err == nil {+ durationInt := int(probedDuration + 0.5)+ if durationInt != *duration {+ s.log.Warnw("Probed duration differs from provided duration",+ "id", videoGenID,+ "provided", *duration,+ "probed", durationInt)+ // 使用探测到的时长(更准确)+ duration = &durationInt+ }+ }}// 下载首帧图片到本地存储(仅用于缓存,不更新数据库)diff --git a/application/services/video_merge_service.go b/application/services/video_merge_service.goindex 1a14f2f..8671e21 100644--- a/application/services/video_merge_service.go+++ b/application/services/video_merge_service.go@@ -412,15 +412,23 @@ func (s *VideoMergeService) FinalizeEpisode(episodeID string, timelineData *Finavar sceneID uintif clip.AssetID != "" {- // 从素材库获取视频URL+ // 从素材库获取视频,优先使用 local_pathvar asset models.Assetif err := s.db.Where("id = ? AND type = ?", clip.AssetID, models.AssetTypeVideo).First(&asset).Error; err == nil {- videoURL = asset.URL+ // 优先使用 local_path(本地文件)+ if asset.LocalPath != nil && *asset.LocalPath != "" {+ // 构建完整的本地路径+ videoURL = filepath.Join(s.storagePath, *asset.LocalPath)+ s.log.Infow("Using local video from asset library", "asset_id", clip.AssetID, "local_path", videoURL)+ } else {+ // 回退到远程 URL+ videoURL = asset.URL+ s.log.Infow("Using remote video from asset library", "asset_id", clip.AssetID, "video_url", videoURL)+ }// 如果asset关联了storyboard,使用关联的storyboard_idif asset.StoryboardID != nil {sceneID = *asset.StoryboardID}- s.log.Infow("Using video from asset library", "asset_id", clip.AssetID, "video_url", videoURL)} else {s.log.Warnw("Asset not found, will try storyboard video", "asset_id", clip.AssetID, "error", err)}@@ -434,10 +442,25 @@ func (s *VideoMergeService) FinalizeEpisode(episodeID string, timelineData *Finacontinue}- if scene.VideoURL != nil && *scene.VideoURL != "" {+ // 查找关联的 video_generation 记录以获取 local_path+ var videoGen models.VideoGeneration+ if err := s.db.Where("storyboard_id = ? AND status = ?", scene.ID, "completed").Order("created_at DESC").First(&videoGen).Error; err == nil {+ if videoGen.LocalPath != nil && *videoGen.LocalPath != "" {+ // 使用本地路径+ videoURL = filepath.Join(s.storagePath, *videoGen.LocalPath)+ sceneID = scene.ID+ s.log.Infow("Using local video from video_generation", "storyboard_id", clip.StoryboardID, "local_path", videoURL)+ } else if scene.VideoURL != nil && *scene.VideoURL != "" {+ // 回退到远程 URL+ videoURL = *scene.VideoURL+ sceneID = scene.ID+ s.log.Infow("Using remote video from storyboard", "storyboard_id", clip.StoryboardID, "video_url", videoURL)+ }+ } else if scene.VideoURL != nil && *scene.VideoURL != "" {+ // 如果没有找到 video_generation,直接使用 storyboard 的 video_urlvideoURL = *scene.VideoURLsceneID = scene.ID- s.log.Infow("Using video from storyboard", "storyboard_id", clip.StoryboardID, "video_url", videoURL)+ s.log.Infow("Using video from storyboard (no video_generation found)", "storyboard_id", clip.StoryboardID, "video_url", videoURL)}}@@ -482,17 +505,42 @@ func (s *VideoMergeService) FinalizeEpisode(episodeID string, timelineData *Finascene.ID, models.AssetTypeVideo, episode.ID).Order("created_at DESC").First(&asset).Error; err == nil {- videoURL = asset.URL- s.log.Infow("Using video from asset library for storyboard",- "storyboard_id", scene.ID,- "asset_id", asset.ID,- "video_url", videoURL)- } else if scene.VideoURL != nil && *scene.VideoURL != "" {- // 如果素材库没有,使用storyboard的video_url作为fallback- videoURL = *scene.VideoURL- s.log.Infow("Using fallback video from storyboard",- "storyboard_id", scene.ID,- "video_url", videoURL)+ // 优先使用 local_path+ if asset.LocalPath != nil && *asset.LocalPath != "" {+ videoURL = filepath.Join(s.storagePath, *asset.LocalPath)+ s.log.Infow("Using local video from asset library for storyboard",+ "storyboard_id", scene.ID,+ "asset_id", asset.ID,+ "local_path", videoURL)+ } else {+ videoURL = asset.URL+ s.log.Infow("Using remote video from asset library for storyboard",+ "storyboard_id", scene.ID,+ "asset_id", asset.ID,+ "video_url", videoURL)+ }+ } else {+ // 如果素材库没有,查找 video_generation 记录+ var videoGen models.VideoGeneration+ if err := s.db.Where("storyboard_id = ? AND status = ?", scene.ID, "completed").Order("created_at DESC").First(&videoGen).Error; err == nil {+ if videoGen.LocalPath != nil && *videoGen.LocalPath != "" {+ videoURL = filepath.Join(s.storagePath, *videoGen.LocalPath)+ s.log.Infow("Using local video from video_generation for storyboard",+ "storyboard_id", scene.ID,+ "local_path", videoURL)+ } else if scene.VideoURL != nil && *scene.VideoURL != "" {+ videoURL = *scene.VideoURL+ s.log.Infow("Using remote video from storyboard",+ "storyboard_id", scene.ID,+ "video_url", videoURL)+ }+ } else if scene.VideoURL != nil && *scene.VideoURL != "" {+ // 最后回退到 storyboard 的 video_url+ videoURL = *scene.VideoURL+ s.log.Infow("Using fallback video from storyboard",+ "storyboard_id", scene.ID,+ "video_url", videoURL)+ }}// 跳过没有视频的场景diff --git a/domain/models/asset.go b/domain/models/asset.goindex dc5f5dd..ad07a1b 100644--- a/domain/models/asset.go+++ b/domain/models/asset.go@@ -25,7 +25,7 @@ type Asset struct {Category *string `gorm:"type:varchar(50);index" json:"category,omitempty"`URL string `gorm:"type:varchar(1000);not null" json:"url"`ThumbnailURL *string `gorm:"type:varchar(1000)" json:"thumbnail_url,omitempty"`- LocalPath *string `gorm:"type:varchar(500)" json:"local_path,omitempty"`+ LocalPath *string `gorm:"type:varchar(500)" json:"local_path"`FileSize *int64 `json:"file_size,omitempty"`MimeType *string `gorm:"type:varchar(100)" json:"mime_type,omitempty"`diff --git a/domain/models/drama.go b/domain/models/drama.goindex 37343fd..500b9ff 100644--- a/domain/models/drama.go+++ b/domain/models/drama.go@@ -136,7 +136,7 @@ type Scene struct {Prompt string `gorm:"type:text;not null" json:"prompt"`StoryboardCount int `gorm:"default:1" json:"storyboard_count"`ImageURL *string `gorm:"type:varchar(500)" json:"image_url"`- LocalPath *string `gorm:"type:text" json:"local_path,omitempty"`+ LocalPath *string `gorm:"type:text" json:"local_path"`Status string `gorm:"type:varchar(20);default:'pending'" json:"status"` // pending, generated, failedCreatedAt time.Time `gorm:"not null;autoCreateTime" json:"created_at"`UpdatedAt time.Time `gorm:"not null;autoUpdateTime" json:"updated_at"`diff --git a/infrastructure/external/ffmpeg/ffmpeg.go b/infrastructure/external/ffmpeg/ffmpeg.goindex 9985296..3692dd6 100644--- a/infrastructure/external/ffmpeg/ffmpeg.go+++ b/infrastructure/external/ffmpeg/ffmpeg.go@@ -105,6 +105,18 @@ func (f *FFmpeg) MergeVideos(opts *MergeOptions) (string, error) {}func (f *FFmpeg) downloadVideo(url, destPath string) (string, error) {+ // 检查是否是本地文件路径+ if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {+ // 这是本地文件路径,检查文件是否存在+ if _, err := os.Stat(url); err == nil {+ f.log.Infow("Using local video file", "path", url)+ return url, nil+ } else {+ return "", fmt.Errorf("local file not found: %s", url)+ }+ }++ // 远程 URL,需要下载f.log.Infow("Downloading video", "url", url, "dest", destPath)resp, err := http.Get(url)diff --git a/web/src/components/editor/VideoTimelineEditor.vue b/web/src/components/editor/VideoTimelineEditor.vueindex 368fb4f..efafa08 100644--- a/web/src/components/editor/VideoTimelineEditor.vue+++ b/web/src/components/editor/VideoTimelineEditor.vue@@ -392,6 +392,7 @@ import {} from '@element-plus/icons-vue'import { videoMerger, type MergeProgress } from '@/utils/videoMerger'import { trimAndMergeVideos } from '@/utils/ffmpeg'+import { getVideoUrl } from '@/utils/image'interface Scene {id: string@@ -458,7 +459,7 @@ const availableStoryboards = computed(() => {storyboard_number: a.storyboard_num || a.id,storyboard_num: a.storyboard_num,storyboard_id: a.storyboard_id,- video_url: a.url,+ video_url: getVideoUrl(a), // 优先使用 local_pathduration: a.duration || 0,name: a.name,isAsset: true,diff --git a/web/src/utils/image.ts b/web/src/utils/image.tsindex de4987f..201b299 100644--- a/web/src/utils/image.ts+++ b/web/src/utils/image.ts@@ -6,9 +6,9 @@* 修复图片URL,处理相对路径和绝对路径*/export function fixImageUrl(url: string): string {- if (!url) return '';- if (url.startsWith('http') || url.startsWith('data:')) return url;- return `${import.meta.env.VITE_API_BASE_URL || ''}${url}`;+ if (!url) return "";+ if (url.startsWith("http") || url.startsWith("data:")) return url;+ return `${import.meta.env.VITE_API_BASE_URL || ""}${url}`;}/**@@ -17,20 +17,20 @@ export function fixImageUrl(url: string): string {* @returns 处理后的图片URL*/export function getImageUrl(item: any): string {- if (!item) return '';-+ if (!item) return "";+// 优先使用 local_pathif (item.local_path) {// local_path 是相对路径(如 images/xxx.jpg),需要添加 /static/ 前缀return `/static/${item.local_path}`;}-+// 回退到 image_urlif (item.image_url) {return fixImageUrl(item.image_url);}-- return '';++ return "";}/**@@ -39,3 +39,41 @@ export function getImageUrl(item: any): string {export function hasImage(item: any): boolean {return !!(item?.local_path || item?.image_url);}++/**+ * 获取视频URL,优先使用 local_path+ * @param item 包含 local_path 或 video_url 或 url 的对象+ * @returns 处理后的视频URL+ */+export function getVideoUrl(item: any): string {+ if (!item) return "";++ // 优先使用 local_path+ if (item.local_path) {+ // 如果 local_path 已经是完整 URL,直接返回+ if (item.local_path.startsWith("http")) {+ return item.local_path;+ }+ // 否则添加 /static/ 前缀+ return `/static/${item.local_path}`;+ }++ // 回退到 video_url+ if (item.video_url) {+ return fixImageUrl(item.video_url);+ }++ // 回退到 url(用于 assets)+ if (item.url) {+ return fixImageUrl(item.url);+ }++ return "";+}++/**+ * 检查是否有视频+ */+export function hasVideo(item: any): boolean {+ return !!(item?.local_path || item?.video_url || item?.url);+}diff --git a/web/src/views/drama/ProfessionalEditor.vue b/web/src/views/drama/ProfessionalEditor.vueindex 131f17b..ded7a51 100644--- a/web/src/views/drama/ProfessionalEditor.vue+++ b/web/src/views/drama/ProfessionalEditor.vue@@ -1511,7 +1511,7 @@@click="playVideo(video)"><video- :src="video.video_url"+ :src="getVideoUrl(video)"preload="metadata"style="width: 100%;@@ -1944,8 +1944,8 @@><div class="scene-image"><img- v-if="scene.image_url"- :src="scene.image_url"+ v-if="hasImage(scene)"+ :src="getImageUrl(scene)":alt="scene.location"/><el-icon v-else :size="48" color="#ccc">@@ -1974,7 +1974,7 @@<div class="video-preview-container" v-if="previewVideo"><videov-if="previewVideo.video_url"- :src="previewVideo.video_url"+ :src="getVideoUrl(previewVideo)"controlsautoplaystyle="@@ -2092,7 +2092,7 @@ import type { VideoMerge } from "@/api/videoMerge";import VideoTimelineEditor from "@/components/editor/VideoTimelineEditor.vue";import type { Drama, Episode, Storyboard } from "@/types/drama";import { AppHeader } from "@/components/common";-import { getImageUrl, hasImage } from "@/utils/image";+import { getImageUrl, hasImage, getVideoUrl } from "@/utils/image";const route = useRoute();const router = useRouter();@@ -2548,17 +2548,16 @@ watch(selectedFrameType, (newType) => {// 设置切换标志,防止watch(currentFramePrompt)错误保存isSwitchingFrameType.value = true;- // 从 framePrompts 对象中加载该帧类型的提示词- currentFramePrompt.value = framePrompts.value[newType] || "";-- // 从 sessionStorage 中加载该帧类型之前的提示词(如果framePrompts中没有)- if (!currentFramePrompt.value) {- const storageKey = `frame_prompt_${currentStoryboard.value.id}_${newType}`;- const stored = sessionStorage.getItem(storageKey);- if (stored) {- currentFramePrompt.value = stored;- framePrompts.value[newType] = stored;- }+ // 优先从 sessionStorage 中加载该帧类型的提示词(确保数据准确)+ const storageKey = `frame_prompt_${currentStoryboard.value.id}_${newType}`;+ const stored = sessionStorage.getItem(storageKey);++ if (stored) {+ currentFramePrompt.value = stored;+ framePrompts.value[newType] = stored;+ } else {+ // 如果 sessionStorage 中没有,再尝试从 framePrompts 对象中读取+ currentFramePrompt.value = framePrompts.value[newType] || "";}// 重新加载该帧类型的图片@@ -2584,6 +2583,14 @@ watch(currentStoryboard, async (newStoryboard) => {// 设置切换标志isSwitchingFrameType.value = true;+ // 清空 framePrompts 对象,避免显示上一个镜头的提示词+ framePrompts.value = {+ key: "",+ first: "",+ last: "",+ panel: "",+ };+// 加载当前帧类型的提示词const storageKey = getPromptStorageKey(newStoryboard.id,@@ -2592,6 +2599,10 @@ watch(currentStoryboard, async (newStoryboard) => {if (storageKey) {const stored = sessionStorage.getItem(storageKey);currentFramePrompt.value = stored || "";+ // 同时更新 framePrompts 对象+ if (stored) {+ framePrompts.value[selectedFrameType.value] = stored;+ }} else {currentFramePrompt.value = "";}