feat(*): 生成工作台 - 新增项目画风配置与图片模型能力裁剪

This commit is contained in:
ddCat committed 2026-08-07 11:46:23 +08:00
1 parent 2b0d56f8e3
commit 1973afc356
52 files changed
+3309 -361

No files matched your search

@@ -244,6 +244,7 @@ func migrations() []tableMigration {
migrateTable[model.VoiceProfile]("voice_profiles"),
migrateTable[model.CharacterVoiceBinding]("character_voice_bindings"),
migrateTable[model.Project]("projects"),
migrateTable[model.StyleProfile]("style_profiles"),
migrateTable[model.ProjectUnit]("project_units"),
migrateTable[model.CanvasUnitLink]("canvas_unit_links"),
migrateTable[model.Shot]("shots"),
+1
View File
@@ -39,6 +39,7 @@ func Models() []any {
&model.VoiceProfile{},
&model.CharacterVoiceBinding{},
&model.Project{},
&model.StyleProfile{},
&model.ProjectUnit{},
&model.CanvasUnitLink{},
&model.Shot{},
+1
View File
@@ -9,6 +9,7 @@ import (
)
func RegisterProjectRoutes(r *gin.RouterGroup, svc *service.Service) {
RegisterStyleProfileRoutes(r, svc)
r.GET("/voice-profiles", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
+117
View File
@@ -0,0 +1,117 @@
package handler
import (
"net/http"
"infinite-canvas/backend/internal/service"
"github.com/gin-gonic/gin"
)
func RegisterStyleProfileRoutes(r *gin.RouterGroup, svc *service.Service) {
r.GET("/style-profiles", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
profiles, err := svc.ListStyleProfiles(user.ID)
if err != nil {
failService(c, err)
return
}
ok(c, gin.H{"profiles": profiles})
})
r.POST("/style-profiles", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 320<<10)
var req service.StyleProfileRequest
if err := c.ShouldBindJSON(&req); err != nil {
fail(c, http.StatusBadRequest, err)
return
}
profile, err := svc.CreateStyleProfile(user.ID, req)
if err != nil {
failService(c, err)
return
}
ok(c, gin.H{"profile": profile})
})
r.PATCH("/style-profiles/:id", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 320<<10)
var req service.StyleProfileRequest
if err := c.ShouldBindJSON(&req); err != nil {
fail(c, http.StatusBadRequest, err)
return
}
profile, err := svc.UpdateStyleProfile(user.ID, c.Param("id"), req)
if service.IsProjectNotFound(err) {
fail(c, http.StatusNotFound, err)
return
}
if err != nil {
failService(c, err)
return
}
ok(c, gin.H{"profile": profile})
})
r.PATCH("/style-profiles/:id/favorite", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
var req service.StyleProfileFavoriteRequest
if err := c.ShouldBindJSON(&req); err != nil {
fail(c, http.StatusBadRequest, err)
return
}
if err := svc.SetStyleProfileFavorite(user.ID, c.Param("id"), req.Favorite); service.IsProjectNotFound(err) {
fail(c, http.StatusNotFound, err)
return
} else if err != nil {
failService(c, err)
return
}
ok(c, gin.H{"id": c.Param("id"), "favorite": req.Favorite})
})
r.POST("/style-profiles/:id/use", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
if err := svc.TouchStyleProfile(user.ID, c.Param("id")); service.IsProjectNotFound(err) {
fail(c, http.StatusNotFound, err)
return
} else if err != nil {
failService(c, err)
return
}
ok(c, gin.H{"id": c.Param("id")})
})
r.DELETE("/style-profiles/:id", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
if err := svc.DeleteStyleProfile(user.ID, c.Param("id")); service.IsProjectNotFound(err) {
fail(c, http.StatusNotFound, err)
return
} else if err != nil {
failService(c, err)
return
}
ok(c, gin.H{"id": c.Param("id")})
})
}
+29 -12
View File
@@ -109,18 +109,35 @@ type CharacterVoiceBinding struct {
// Project 是短剧领域聚合根;CanvasProject 仍代表可独立创作的画布文档。
type Project struct {
ID string `json:"id" gorm:"primaryKey;size:36"`
UserID string `json:"userId" gorm:"index;size:36;uniqueIndex:idx_projects_user_name,priority:1"`
Name string `json:"name" gorm:"size:240;uniqueIndex:idx_projects_user_name,priority:2"`
Type string `json:"type" gorm:"size:32;index"`
AspectRatio string `json:"aspectRatio" gorm:"size:16"`
SourceType string `json:"sourceType" gorm:"size:32"`
Description string `json:"description" gorm:"type:text"`
StylePresetID string `json:"stylePresetId" gorm:"size:64"`
Status ProjectStatus `json:"status" gorm:"index;size:24"`
Revision int64 `json:"revision"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt" gorm:"index"`
ID string `json:"id" gorm:"primaryKey;size:36"`
UserID string `json:"userId" gorm:"index;size:36;uniqueIndex:idx_projects_user_name,priority:1"`
Name string `json:"name" gorm:"size:240;uniqueIndex:idx_projects_user_name,priority:2"`
Type string `json:"type" gorm:"size:32;index"`
AspectRatio string `json:"aspectRatio" gorm:"size:16"`
SourceType string `json:"sourceType" gorm:"size:32"`
Description string `json:"description" gorm:"type:text"`
StylePresetID string `json:"stylePresetId" gorm:"size:64"`
StyleProfileJSON string `json:"styleProfileJson" gorm:"type:text"`
Status ProjectStatus `json:"status" gorm:"index;size:24"`
Revision int64 `json:"revision"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt" gorm:"index"`
}
// StyleProfile 是用户可持续编辑的风格源;项目只保存应用当时的 JSON 快照,避免源对象更新污染历史生成。
type StyleProfile struct {
ID string `json:"id" gorm:"primaryKey;size:36"`
UserID string `json:"userId" gorm:"index;size:36;index:idx_style_profiles_user_updated,priority:1"`
Name string `json:"name" gorm:"size:160"`
Description string `json:"description" gorm:"size:500"`
CoverURL string `json:"coverUrl" gorm:"type:text"`
TagsJSON string `json:"tagsJson" gorm:"type:text"`
ProfileJSON string `json:"profileJson" gorm:"type:text"`
Favorite bool `json:"favorite" gorm:"index"`
LastUsedAt *time.Time `json:"lastUsedAt,omitempty" gorm:"index"`
Revision int64 `json:"revision"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt" gorm:"index:idx_style_profiles_user_updated,priority:2"`
}
type ProjectUnit struct {
+1 -1
View File
@@ -934,7 +934,7 @@ func (r *Repository) CreateProject(project *model.Project) error {
func (r *Repository) UpdateProject(project *model.Project) error {
return r.db.Model(&model.Project{}).Where("id = ? AND user_id = ?", project.ID, project.UserID).Updates(map[string]any{
"name": project.Name, "type": project.Type, "aspect_ratio": project.AspectRatio, "source_type": project.SourceType,
"description": project.Description, "style_preset_id": project.StylePresetID,
"description": project.Description, "style_preset_id": project.StylePresetID, "style_profile_json": project.StyleProfileJSON,
"status": project.Status, "revision": project.Revision, "updated_at": project.UpdatedAt,
}).Error
}
@@ -0,0 +1,73 @@
package repository
import (
"time"
"infinite-canvas/backend/internal/model"
"gorm.io/gorm"
)
func (r *Repository) StyleProfiles(userID string) ([]model.StyleProfile, error) {
var profiles []model.StyleProfile
err := r.db.Where("user_id = ?", userID).Order("favorite desc, updated_at desc").Find(&profiles).Error
return profiles, err
}
func (r *Repository) StyleProfileCount(userID string) (int64, error) {
var count int64
err := r.db.Model(&model.StyleProfile{}).Where("user_id = ?", userID).Count(&count).Error
return count, err
}
func (r *Repository) StyleProfileForUser(userID string, id string) (*model.StyleProfile, error) {
var profile model.StyleProfile
if err := r.db.First(&profile, "id = ? AND user_id = ?", id, userID).Error; err != nil {
return nil, err
}
return &profile, nil
}
func (r *Repository) CreateStyleProfile(profile *model.StyleProfile) error {
return r.db.Create(profile).Error
}
func (r *Repository) UpdateStyleProfile(profile *model.StyleProfile) error {
return r.db.Model(&model.StyleProfile{}).Where("id = ? AND user_id = ?", profile.ID, profile.UserID).Updates(map[string]any{
"name": profile.Name, "description": profile.Description, "cover_url": profile.CoverURL,
"tags_json": profile.TagsJSON, "profile_json": profile.ProfileJSON, "revision": profile.Revision, "updated_at": profile.UpdatedAt,
}).Error
}
func (r *Repository) SetStyleProfileFavorite(userID string, id string, favorite bool) error {
result := r.db.Model(&model.StyleProfile{}).Where("id = ? AND user_id = ?", id, userID).Update("favorite", favorite)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
}
func (r *Repository) TouchStyleProfile(userID string, id string, usedAt time.Time) error {
result := r.db.Model(&model.StyleProfile{}).Where("id = ? AND user_id = ?", id, userID).Update("last_used_at", usedAt)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
}
func (r *Repository) DeleteStyleProfile(userID string, id string) error {
result := r.db.Delete(&model.StyleProfile{}, "id = ? AND user_id = ?", id, userID)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
}
+10 -3
View File
@@ -137,7 +137,7 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
if err != nil {
return nil, err
}
if capability == "video" {
if capability == "image" || capability == "video" {
if _, err := NormalizeModelCapabilityConfig(capability, string(protocol), req.CapabilityConfig); err != nil {
return nil, err
}
@@ -193,7 +193,7 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
item.OutputTokenPriceMicrocredits = req.OutputTokenPriceMicrocredits
item.CachedTokenPriceMicrocredits = req.CachedTokenPriceMicrocredits
item.PriceConfigured = req.PriceConfigured
if capability == "video" {
if capability == "image" || capability == "video" {
capabilityConfig, normalizeErr := NormalizeModelCapabilityConfig(capability, string(protocol), req.CapabilityConfig)
if normalizeErr != nil {
return nil, normalizeErr
@@ -234,7 +234,7 @@ func (s *Service) TestAdminChannelModel(ctx context.Context, actor *model.User,
if err != nil {
return nil, err
}
if capability == "video" {
if capability == "image" || capability == "video" {
if _, err := NormalizeModelCapabilityConfig(capability, string(protocol), req.CapabilityConfig); err != nil {
return nil, err
}
@@ -284,6 +284,13 @@ func (s *Service) TestAdminChannelModel(ctx context.Context, actor *model.User,
},
Metadata: map[string]interface{}{},
}
if capability == "image" {
profile, normalizeErr := NormalizeModelCapabilityConfig(capability, string(protocol), req.CapabilityConfig)
if normalizeErr != nil {
return nil, normalizeErr
}
input.ImageCapability = profile.Image
}
// 测试复用真实生成协议、运行时并发和熔断策略,但不创建用户任务或计费订单。
testCtx, cancel := context.WithTimeout(ctx, 10*time.Minute)
+178 -4
View File
@@ -14,9 +14,44 @@ import (
// ModelCapabilityConfig 是模型能力声明,不包含供应商字段名;协议适配器负责把统一参数映射到上游请求。
type ModelCapabilityConfig struct {
Version int `json:"version"`
Image *ImageCapabilityConfig `json:"image,omitempty"`
Video *VideoCapabilityConfig `json:"video,omitempty"`
}
type ImageCapabilityConfig struct {
References ImageReferenceConfig `json:"references"`
Size ImageSizeConfig `json:"size"`
Quality ImageQualityConfig `json:"quality"`
TransparentBackground VideoBooleanConfig `json:"transparentBackground"`
ResponseFormat ParameterSupport `json:"responseFormat"`
OutputFormat ParameterSupport `json:"outputFormat"`
MaxOutputs int `json:"maxOutputs"`
}
type ImageReferenceConfig struct {
PromptMaxChars int `json:"promptMaxChars"`
MaxImages int `json:"maxImages"`
MaxImageBytes int64 `json:"maxImageBytes"`
MaskSupported bool `json:"maskSupported"`
}
type ImageSizeConfig struct {
Parameter string `json:"parameter"`
Values []string `json:"values"`
Default string `json:"default"`
AllowCustom bool `json:"allowCustom"`
}
type ImageQualityConfig struct {
Supported bool `json:"supported"`
Values []string `json:"values"`
Default string `json:"default"`
}
type ParameterSupport struct {
Supported bool `json:"supported"`
}
type VideoCapabilityConfig struct {
References VideoReferenceConfig `json:"references"`
Duration VideoDurationConfig `json:"duration"`
@@ -57,6 +92,48 @@ type VideoBooleanConfig struct {
}
func DefaultModelCapabilityConfig(protocol string) *ModelCapabilityConfig {
return DefaultModelCapabilityConfigForModel(protocol, "")
}
func DefaultImageCapabilityConfig(protocol string, modelName string) *ImageCapabilityConfig {
image := &ImageCapabilityConfig{
References: ImageReferenceConfig{PromptMaxChars: 32000, MaxImages: 16, MaxImageBytes: 30 * 1024 * 1024, MaskSupported: true},
Size: ImageSizeConfig{Parameter: "size", Values: []string{"1:1", "3:2", "2:3", "4:3", "3:4", "16:9", "21:9", "9:16", "2048x2048", "2048x1152", "1152x2048", "3840x2160", "2160x3840"}, Default: "1:1", AllowCustom: true},
Quality: ImageQualityConfig{Supported: true, Values: []string{"auto", "low", "medium", "high"}, Default: "auto"},
TransparentBackground: VideoBooleanConfig{Supported: true, Default: false},
ResponseFormat: ParameterSupport{Supported: true},
OutputFormat: ParameterSupport{Supported: true},
MaxOutputs: 15,
}
switch model.ChannelInterfaceType(protocol) {
case model.ChannelInterfaceVolcengineArkImage:
image.References.MaskSupported = false
image.Quality.Supported = false
image.TransparentBackground.Supported = false
image.ResponseFormat.Supported = false
image.OutputFormat.Supported = false
case model.ChannelInterfaceVolcengineJiMengImage:
image.References.MaxImages = 14
image.References.MaskSupported = false
image.Quality.Supported = false
image.TransparentBackground.Supported = false
image.ResponseFormat.Supported = false
image.OutputFormat.Supported = false
}
if strings.HasPrefix(strings.ToLower(strings.TrimSpace(modelName)), "grok-imagine-image") {
image.References.MaxImages = 0
image.References.MaskSupported = false
image.Size = ImageSizeConfig{Parameter: "none", Values: []string{}, Default: "auto", AllowCustom: false}
image.Quality = ImageQualityConfig{Supported: false, Values: []string{}, Default: "auto"}
image.TransparentBackground = VideoBooleanConfig{Supported: false, Default: false}
image.ResponseFormat = ParameterSupport{Supported: true}
image.OutputFormat = ParameterSupport{Supported: false}
image.MaxOutputs = 1
}
return image
}
func DefaultModelCapabilityConfigForModel(protocol string, modelName string) *ModelCapabilityConfig {
video := &VideoCapabilityConfig{
References: VideoReferenceConfig{PromptMaxChars: 1000, MaxImages: 9, MaxImageBytes: 30 * 1024 * 1024, MaxVideos: 0, MaxVideoBytes: 0, MaxVideoDuration: 0, MaxAudios: 0, MaxAudioBytes: 0, MaxAudioDuration: 0},
Duration: VideoDurationConfig{Selection: "range", Min: 1, Max: 15, Step: 1, Default: 6},
@@ -90,7 +167,7 @@ func DefaultModelCapabilityConfig(protocol string) *ModelCapabilityConfig {
case model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceXAIVideo:
video.GenerateAudio = VideoBooleanConfig{Supported: false, Default: false}
}
return &ModelCapabilityConfig{Version: 1, Video: video}
return &ModelCapabilityConfig{Version: 1, Image: DefaultImageCapabilityConfig(protocol, modelName), Video: video}
}
func DecodeModelCapabilityConfig(raw string) (*ModelCapabilityConfig, error) {
@@ -104,10 +181,20 @@ func DecodeModelCapabilityConfig(raw string) (*ModelCapabilityConfig, error) {
return &value, nil
}
func NormalizeModelCapabilityConfig(capability string, protocol string, input *ModelCapabilityConfig) (*ModelCapabilityConfig, error) {
if capability != "video" {
func NormalizeModelCapabilityConfig(capability string, _ string, input *ModelCapabilityConfig) (*ModelCapabilityConfig, error) {
if capability != "image" && capability != "video" {
return nil, nil
}
if capability == "image" {
if input == nil || input.Image == nil {
return nil, BadAuthRequest("请配置图片模型能力参数")
}
value := &ModelCapabilityConfig{Version: 1, Image: input.Image}
if err := validateImageCapabilityConfig(value.Image); err != nil {
return nil, err
}
return value, nil
}
if input == nil || input.Video == nil {
return nil, BadAuthRequest("请配置视频模型能力参数")
}
@@ -118,6 +205,45 @@ func NormalizeModelCapabilityConfig(capability string, protocol string, input *M
return value, nil
}
func validateImageCapabilityConfig(value *ImageCapabilityConfig) error {
if value.References.PromptMaxChars < 1 || value.References.PromptMaxChars > 1000000 {
return BadAuthRequest("提示词最大字符数必须在 1-1000000 之间")
}
if value.References.MaxImages < 0 || value.References.MaxImages > 100 || value.References.MaxImageBytes < 0 {
return BadAuthRequest("图片引用限制无效")
}
if value.MaxOutputs < 1 || value.MaxOutputs > 100 {
return BadAuthRequest("单次图片数量必须在 1-100 之间")
}
switch value.Size.Parameter {
case "none":
value.Size.Values = []string{}
value.Size.Default = "auto"
value.Size.AllowCustom = false
case "size", "aspect_ratio":
if strings.TrimSpace(value.Size.Default) == "" {
return BadAuthRequest("请配置默认图片尺寸或比例")
}
if !value.Size.AllowCustom && !containsCapabilityString(value.Size.Values, value.Size.Default) {
return BadAuthRequest("默认图片尺寸必须属于支持值")
}
default:
return BadAuthRequest("尺寸参数仅支持不发送、size 或 aspect_ratio")
}
if value.Quality.Supported {
if len(value.Quality.Values) == 0 || strings.TrimSpace(value.Quality.Default) == "" || !containsCapabilityString(value.Quality.Values, value.Quality.Default) {
return BadAuthRequest("请配置图片质量支持值和默认值")
}
} else {
value.Quality.Values = []string{}
value.Quality.Default = "auto"
}
if !value.TransparentBackground.Supported {
value.TransparentBackground.Default = false
}
return nil
}
func validateVideoCapabilityConfig(value *VideoCapabilityConfig) error {
if value.References.PromptMaxChars < 1 || value.References.PromptMaxChars > 1000000 {
return BadAuthRequest("提示词最大字符数必须在 1-1000000 之间")
@@ -177,7 +303,7 @@ func (s *Service) ValidateTaskCapability(input map[string]any) error {
return BadAuthRequest("任务输入格式无效")
}
var taskInput canvasGenerationInput
if err := json.Unmarshal(encoded, &taskInput); err != nil || taskInput.Mode != "video" {
if err := json.Unmarshal(encoded, &taskInput); err != nil || (taskInput.Mode != "image" && taskInput.Mode != "video") {
return nil
}
channelID := strings.TrimSpace(taskInput.Config.ChannelID)
@@ -185,6 +311,13 @@ func (s *Service) ValidateTaskCapability(input map[string]any) error {
channelID = systemChannelIDFromBaseURL(taskInput.Config.BaseURL)
}
if channelID == "" {
if taskInput.Mode == "image" {
profile := DefaultImageCapabilityConfig(taskInput.Config.InterfaceType, taskInput.Config.Model)
if taskInput.Config.CapabilityConfig != nil && taskInput.Config.CapabilityConfig.Image != nil {
profile = taskInput.Config.CapabilityConfig.Image
}
return validateImageTask(profile, taskInput)
}
if taskInput.Config.CapabilityConfig == nil || taskInput.Config.CapabilityConfig.Video == nil {
return nil
}
@@ -195,6 +328,16 @@ func (s *Service) ValidateTaskCapability(input map[string]any) error {
return BadAuthRequest("当前系统渠道模型未配置或已停用")
}
profile, err := DecodeModelCapabilityConfig(item.CapabilityConfigJSON)
if taskInput.Mode == "image" {
if err != nil {
return BadAuthRequest("当前图片模型能力参数无效")
}
imageProfile := DefaultImageCapabilityConfig(string(item.Protocol), item.ModelKey)
if profile != nil && profile.Image != nil {
imageProfile = profile.Image
}
return validateImageTask(imageProfile, taskInput)
}
if err != nil || profile == nil || profile.Video == nil {
return BadAuthRequest("当前视频模型尚未配置能力参数")
}
@@ -253,6 +396,37 @@ func validateVideoTask(profile *VideoCapabilityConfig, input canvasGenerationInp
return nil
}
func validateImageTask(profile *ImageCapabilityConfig, input canvasGenerationInput) error {
if profile == nil {
return nil
}
if utf8.RuneCountInString(input.Prompt) > profile.References.PromptMaxChars {
return BadAuthRequest(fmt.Sprintf("提示词超过当前模型限制(最多 %d 字)", profile.References.PromptMaxChars))
}
if len(input.ReferenceImages) > profile.References.MaxImages {
return BadAuthRequest(fmt.Sprintf("当前图片模型最多支持 %d 张参考图", profile.References.MaxImages))
}
for _, media := range input.ReferenceImages {
if profile.References.MaxImageBytes > 0 && media.Bytes > profile.References.MaxImageBytes {
return BadAuthRequest("参考图片文件超过当前模型大小限制")
}
}
if input.Mask != nil && !profile.References.MaskSupported {
return BadAuthRequest("当前图片模型不支持蒙版编辑")
}
if profile.Size.Parameter != "none" && !profile.Size.AllowCustom && strings.TrimSpace(input.Config.Size) != "" && !containsCapabilityString(profile.Size.Values, input.Config.Size) {
return BadAuthRequest("图片尺寸不在当前模型支持范围内")
}
if profile.Quality.Supported && strings.TrimSpace(input.Config.Quality) != "" && !containsCapabilityString(profile.Quality.Values, input.Config.Quality) {
return BadAuthRequest("图片质量不在当前模型支持范围内")
}
count, err := strconv.Atoi(strings.TrimSpace(input.Config.Count))
if err == nil && count > profile.MaxOutputs {
return BadAuthRequest(fmt.Sprintf("当前图片模型单次最多生成 %d 张", profile.MaxOutputs))
}
return nil
}
func videoDurationAllowed(value VideoDurationConfig, seconds int) bool {
if value.Selection == "enum" {
return containsInt(value.Values, seconds)
+34 -14
View File
@@ -12,22 +12,24 @@ import (
)
type CreateProjectRequest struct {
Name string `json:"name"`
Type string `json:"type"`
AspectRatio string `json:"aspectRatio"`
SourceType string `json:"sourceType"`
Description string `json:"description"`
StylePresetID string `json:"stylePresetId"`
Name string `json:"name"`
Type string `json:"type"`
AspectRatio string `json:"aspectRatio"`
SourceType string `json:"sourceType"`
Description string `json:"description"`
StylePresetID string `json:"stylePresetId"`
StyleProfileJSON string `json:"styleProfileJson"`
}
type UpdateProjectRequest struct {
Name string `json:"name"`
Type string `json:"type"`
AspectRatio string `json:"aspectRatio"`
SourceType string `json:"sourceType"`
Description *string `json:"description"`
StylePresetID *string `json:"stylePresetId"`
Status string `json:"status"`
Name string `json:"name"`
Type string `json:"type"`
AspectRatio string `json:"aspectRatio"`
SourceType string `json:"sourceType"`
Description *string `json:"description"`
StylePresetID *string `json:"stylePresetId"`
StyleProfileJSON *string `json:"styleProfileJson"`
Status string `json:"status"`
}
type CreateProjectUnitRequest struct {
@@ -175,8 +177,16 @@ func (s *Service) CreateProject(userID string, req CreateProjectRequest) (model.
if sourceType == "" {
sourceType = "blank"
}
styleProfileJSON, err := validateStyleProfileJSON(req.StyleProfileJSON)
if err != nil {
return model.Project{}, BadAuthRequest(err.Error())
}
stylePresetID := strings.TrimSpace(req.StylePresetID)
if err := validateStyleProfilePreset(stylePresetID, styleProfileJSON); err != nil {
return model.Project{}, BadAuthRequest(err.Error())
}
now := time.Now()
project := model.Project{ID: newID(), UserID: userID, Name: name, Type: projectType, AspectRatio: aspectRatio, SourceType: sourceType, Description: strings.TrimSpace(req.Description), StylePresetID: strings.TrimSpace(req.StylePresetID), Status: model.ProjectStatusActive, Revision: 1, CreatedAt: now, UpdatedAt: now}
project := model.Project{ID: newID(), UserID: userID, Name: name, Type: projectType, AspectRatio: aspectRatio, SourceType: sourceType, Description: strings.TrimSpace(req.Description), StylePresetID: stylePresetID, StyleProfileJSON: styleProfileJSON, Status: model.ProjectStatusActive, Revision: 1, CreatedAt: now, UpdatedAt: now}
if err := s.repo.CreateProject(&project); err != nil {
return model.Project{}, err
}
@@ -212,6 +222,16 @@ func (s *Service) UpdateProject(userID string, id string, req UpdateProjectReque
if req.StylePresetID != nil {
project.StylePresetID = strings.TrimSpace(*req.StylePresetID)
}
if req.StyleProfileJSON != nil {
styleProfileJSON, profileErr := validateStyleProfileJSON(*req.StyleProfileJSON)
if profileErr != nil {
return model.Project{}, BadAuthRequest(profileErr.Error())
}
project.StyleProfileJSON = styleProfileJSON
}
if err := validateStyleProfilePreset(project.StylePresetID, project.StyleProfileJSON); err != nil {
return model.Project{}, BadAuthRequest(err.Error())
}
if status := model.ProjectStatus(strings.TrimSpace(req.Status)); status != "" {
if status != model.ProjectStatusActive && status != model.ProjectStatusArchived {
return model.Project{}, BadAuthRequest("不支持的项目状态")
+243 -18
View File
@@ -20,6 +20,8 @@ import (
"time"
"infinite-canvas/backend/internal/model"
"gorm.io/gorm"
)
type canvasGenerationInput struct {
@@ -31,6 +33,7 @@ type canvasGenerationInput struct {
ReferenceAudios []providerMedia `json:"referenceAudios"`
Mask *providerMedia `json:"mask"`
Metadata map[string]interface{} `json:"metadata"`
ImageCapability *ImageCapabilityConfig `json:"-"`
VideoCapability *VideoCapabilityConfig `json:"-"`
}
@@ -149,7 +152,7 @@ func (e providerHTTPError) Error() string {
return fmt.Sprintf("接口请求失败:%s %s", e.Status, e.Body)
}
func (s *Service) processCanvasGenerationTask(ctx context.Context, userID string, taskType string, fallbackPrompt string, rawInput string) (map[string]interface{}, error) {
func (s *Service) processCanvasGenerationTask(ctx context.Context, userID string, taskProjectID string, taskType string, fallbackPrompt string, rawInput string) (map[string]interface{}, error) {
var input canvasGenerationInput
if err := json.Unmarshal([]byte(rawInput), &input); err != nil {
return nil, fmt.Errorf("任务输入解析失败:%w", err)
@@ -177,6 +180,11 @@ func (s *Service) processCanvasGenerationTask(ctx context.Context, userID string
return nil, err
}
input.Config = config
if (input.Mode == "image" || input.Mode == "video") && input.Metadata != nil {
if err := s.applyGenerationStyleProfile(userID, taskProjectID, &input); err != nil {
return nil, err
}
}
if input.Config.APIFormat == "gemini" && input.Config.InterfaceType != string(model.ChannelInterfaceGeminiVeo) {
return nil, errors.New("后端任务队列暂不支持 Gemini 调用格式,请使用 OpenAI 兼容渠道")
}
@@ -189,6 +197,11 @@ func (s *Service) processCanvasGenerationTask(ctx context.Context, userID string
if isVolcengineJiMengProtocol(input.Config.InterfaceType) && strings.TrimSpace(input.Config.SecretKey) == "" {
return nil, errors.New("即梦官方 API 缺少 Secret Key")
}
if input.Mode == "image" {
if err := s.validateResolvedImageCapability(&input); err != nil {
return nil, err
}
}
if input.Mode == "video" {
if err := s.validateResolvedVideoCapability(&input); err != nil {
return nil, err
@@ -223,6 +236,180 @@ func (s *Service) processCanvasGenerationTask(ctx context.Context, userID string
}
}
type styleExecutionPlanDocument struct {
SchemaVersion int `json:"schemaVersion"`
ProfilePresetID string `json:"profilePresetId"`
ProfileRevision int `json:"profileRevision"`
Mode string `json:"mode"`
Model string `json:"model"`
InterfaceType string `json:"interfaceType"`
Status string `json:"status"`
Prompt string `json:"prompt"`
}
func (s *Service) applyGenerationStyleProfile(userID string, taskProjectID string, input *canvasGenerationInput) error {
styleProfileJSON := metadataString(input.Metadata, "styleProfileJson")
if strings.TrimSpace(styleProfileJSON) == "" {
return nil
}
if _, err := validateStyleProfileJSON(styleProfileJSON); err != nil {
return fmt.Errorf("项目画风执行配置无效:%w", err)
}
var profile styleProfileDocument
if err := json.Unmarshal([]byte(styleProfileJSON), &profile); err != nil {
return fmt.Errorf("项目画风执行配置解析失败:%w", err)
}
storedProfileJSON, storedPresetID, belongsToProject, err := s.taskProjectStyleProfile(userID, taskProjectID)
if err != nil {
return fmt.Errorf("读取项目画风失败:%w", err)
}
if belongsToProject {
if strings.TrimSpace(storedProfileJSON) == "" {
// 旧项目只有 preset ID,允许画布把该预设编译为结构化快照;仍需锁定同一预设,不能借降级路径换画风。
if strings.TrimSpace(storedPresetID) == "" || strings.TrimSpace(profile.PresetID) != strings.TrimSpace(storedPresetID) {
return errors.New("任务画风预设与项目当前设置不一致,请刷新画布后重试")
}
} else {
matches, compareErr := equivalentStyleProfileJSON(styleProfileJSON, storedProfileJSON)
if compareErr != nil || !matches {
return errors.New("任务画风快照与项目当前设置不一致,请刷新画布后重试")
}
}
}
plan, err := decodeStyleExecutionPlan(input.Metadata["styleExecutionPlan"])
if err != nil {
return err
}
stylePrompt, expectedStatus, warnings := resolveGenerationStyleExecution(profile, input.Config.Model, firstNonEmpty(input.Config.InterfaceType, input.Config.APIFormat))
if plan.SchemaVersion != 1 || plan.ProfilePresetID != profile.PresetID || plan.ProfileRevision != profile.Revision || plan.Mode != input.Mode || !strings.EqualFold(plan.Model, input.Config.Model) || plan.InterfaceType != firstNonEmpty(input.Config.InterfaceType, input.Config.APIFormat) {
return errors.New("项目画风执行计划与当前模型或快照不一致,请刷新配置后重试")
}
if plan.Status != expectedStatus || strings.TrimSpace(plan.Prompt) != stylePrompt {
return errors.New("项目画风执行计划已失效,请重新生成执行计划")
}
if expectedStatus == "blocked" {
return fmt.Errorf("项目画风与当前生成模型不兼容:%s", strings.Join(warnings, ";"))
}
if stylePrompt != "" && !strings.Contains(input.Prompt, stylePrompt) {
input.Prompt = strings.TrimSpace(input.Prompt) + "\n\n【项目画风执行规范】\n" + stylePrompt
}
return nil
}
func (s *Service) taskProjectStyleProfile(userID string, canvasOrProjectID string) (string, string, bool, error) {
id := strings.TrimSpace(canvasOrProjectID)
if id == "" {
return "", "", false, nil
}
if canvas, err := s.repo.CanvasProjectForUser(userID, id); err == nil {
if strings.TrimSpace(canvas.ProjectID) == "" {
return "", "", false, nil
}
project, projectErr := s.repo.ProjectForUser(userID, canvas.ProjectID)
if projectErr != nil {
return "", "", true, projectErr
}
return project.StyleProfileJSON, project.StylePresetID, true, nil
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
return "", "", false, err
}
project, err := s.repo.ProjectForUser(userID, id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return "", "", false, nil
}
return "", "", false, err
}
return project.StyleProfileJSON, project.StylePresetID, true, nil
}
func equivalentStyleProfileJSON(left string, right string) (bool, error) {
var leftValue interface{}
if err := json.Unmarshal([]byte(left), &leftValue); err != nil {
return false, err
}
var rightValue interface{}
if err := json.Unmarshal([]byte(right), &rightValue); err != nil {
return false, err
}
leftCanonical, err := json.Marshal(leftValue)
if err != nil {
return false, err
}
rightCanonical, err := json.Marshal(rightValue)
if err != nil {
return false, err
}
return bytes.Equal(leftCanonical, rightCanonical), nil
}
func decodeStyleExecutionPlan(value interface{}) (styleExecutionPlanDocument, error) {
if value == nil {
return styleExecutionPlanDocument{}, errors.New("项目画风执行计划缺失")
}
raw, err := json.Marshal(value)
if err != nil {
return styleExecutionPlanDocument{}, errors.New("项目画风执行计划格式无效")
}
var plan styleExecutionPlanDocument
if err := json.Unmarshal(raw, &plan); err != nil {
return styleExecutionPlanDocument{}, errors.New("项目画风执行计划格式无效")
}
return plan, nil
}
func resolveGenerationStyleExecution(profile styleProfileDocument, generationModel string, interfaceType string) (string, string, []string) {
fragments := []string{strings.TrimSpace(profile.Prompt)}
if negative := strings.TrimSpace(profile.NegativePrompt); negative != "" {
fragments = append(fragments, "【全局负面 Prompt】\n"+negative)
}
warnings := make([]string, 0)
for _, asset := range profile.Assets {
if asset.Enabled != nil && !*asset.Enabled {
continue
}
if asset.Status != "validated" {
reason := "资产尚未验证"
if asset.Status == "unavailable" {
reason = "资产当前不可用"
}
warnings = append(warnings, asset.Title+":"+reason)
continue
}
if len(asset.BaseModels) > 0 && !styleAssetSupportsModel(asset.BaseModels, generationModel) {
warnings = append(warnings, asset.Title+":仅兼容 "+strings.Join(asset.BaseModels, "、"))
continue
}
switch asset.Kind {
case "prompt", "template":
fragments = append(fragments, strings.TrimSpace(asset.PromptFragment))
fragments = append(fragments, nonEmptyStyleProfileStrings(asset.TriggerWords)...)
case "reference":
warnings = append(warnings, asset.Title+":项目参考图自动注入适配器尚未启用")
case "lora":
warnings = append(warnings, asset.Title+":当前 "+firstNonEmpty(interfaceType, "图片")+" 协议未启用 LoRA 适配器")
}
}
normalizedFragments := nonEmptyStyleProfileStrings(fragments)
status := "ready"
if len(warnings) > 0 {
status = "degraded"
if profile.ExecutionPolicy == "strict-assets" {
status = "blocked"
}
}
return strings.Join(normalizedFragments, "\n"), status, warnings
}
func styleAssetSupportsModel(baseModels []string, generationModel string) bool {
for _, baseModel := range baseModels {
if strings.EqualFold(strings.TrimSpace(baseModel), strings.TrimSpace(generationModel)) {
return true
}
}
return false
}
func (s *Service) validateResolvedVideoCapability(input *canvasGenerationInput) error {
channelID := strings.TrimSpace(input.Config.ChannelID)
if channelID == "" {
@@ -244,6 +431,33 @@ func (s *Service) validateResolvedVideoCapability(input *canvasGenerationInput)
return validateVideoTask(profile.Video, *input)
}
func (s *Service) validateResolvedImageCapability(input *canvasGenerationInput) error {
fallback := DefaultImageCapabilityConfig(input.Config.InterfaceType, input.Config.Model)
channelID := strings.TrimSpace(input.Config.ChannelID)
if channelID == "" {
if input.Config.CapabilityConfig != nil && input.Config.CapabilityConfig.Image != nil {
input.ImageCapability = input.Config.CapabilityConfig.Image
} else {
input.ImageCapability = fallback
}
return validateImageTask(input.ImageCapability, *input)
}
item, err := s.repo.ChannelModelByKey(channelID, strings.TrimPrefix(strings.TrimSpace(input.Config.Model), "models/"))
if err != nil {
return errors.New("当前系统渠道模型未配置或已停用")
}
profile, err := DecodeModelCapabilityConfig(item.CapabilityConfigJSON)
if err != nil {
return errors.New("当前图片模型能力参数无效")
}
if profile != nil && profile.Image != nil {
input.ImageCapability = profile.Image
} else {
input.ImageCapability = fallback
}
return validateImageTask(input.ImageCapability, *input)
}
func metadataStringValues(value any) map[string]string {
values := map[string]string{}
raw, ok := value.(map[string]interface{})
@@ -443,16 +657,20 @@ func runImageTask(ctx context.Context, input canvasGenerationInput) (map[string]
writeField(writer, "model", input.Config.Model)
writeField(writer, "prompt", withSystemPrompt(input.Config, input.Prompt))
writeField(writer, "n", "1")
writeField(writer, "response_format", "b64_json")
writeField(writer, "output_format", "png")
if input.Config.TransparentBackground == "true" {
if imageParameterSupported(input.ImageCapability, "response_format") {
writeField(writer, "response_format", "b64_json")
}
if imageParameterSupported(input.ImageCapability, "output_format") {
writeField(writer, "output_format", "png")
}
if imageTransparentBackgroundSupported(input.ImageCapability) && input.Config.TransparentBackground == "true" {
writeField(writer, "background", "transparent")
}
if input.Config.Quality != "" {
if imageQualitySupported(input.ImageCapability) && input.Config.Quality != "" {
writeField(writer, "quality", normalizeImageQuality(input.Config.Quality))
}
if size := normalizePixelSize(input.Config.Size); size != "" {
writeField(writer, "size", size)
if key, value := imageSizeParameter(input.ImageCapability, input.Config.Size); value != "" {
writeField(writer, key, value)
}
for _, image := range input.ReferenceImages {
if err := writeMediaPart(writer, "image", image); err != nil {
@@ -472,20 +690,24 @@ func runImageTask(ctx context.Context, input canvasGenerationInput) (map[string]
}
} else {
body := map[string]interface{}{
"model": input.Config.Model,
"prompt": withSystemPrompt(input.Config, input.Prompt),
"n": 1,
"response_format": "b64_json",
"output_format": "png",
"model": input.Config.Model,
"prompt": withSystemPrompt(input.Config, input.Prompt),
"n": 1,
}
if input.Config.TransparentBackground == "true" {
if imageParameterSupported(input.ImageCapability, "response_format") {
body["response_format"] = "b64_json"
}
if imageParameterSupported(input.ImageCapability, "output_format") {
body["output_format"] = "png"
}
if imageTransparentBackgroundSupported(input.ImageCapability) && input.Config.TransparentBackground == "true" {
body["background"] = "transparent"
}
if input.Config.Quality != "" {
if imageQualitySupported(input.ImageCapability) && input.Config.Quality != "" {
body["quality"] = normalizeImageQuality(input.Config.Quality)
}
if size := normalizePixelSize(input.Config.Size); size != "" {
body["size"] = size
if key, value := imageSizeParameter(input.ImageCapability, input.Config.Size); value != "" {
body[key] = value
}
if err := postJSON(ctx, input.Config, "/images/generations", body, &payload); err != nil {
return nil, err
@@ -525,8 +747,11 @@ func volcengineArkImageBody(input canvasGenerationInput) (map[string]interface{}
"prompt": withSystemPrompt(input.Config, input.Prompt),
"n": 1,
}
if size := normalizeVolcengineArkImageSize(input.Config.Size); size != "" {
body["size"] = size
if key, value := imageSizeParameter(input.ImageCapability, input.Config.Size); value != "" {
if key == "size" {
value = normalizeVolcengineArkImageSize(value)
}
body[key] = value
}
if len(input.ReferenceImages) == 0 {
return body, nil
+54 -1
View File
@@ -999,8 +999,61 @@ func TestProcessTaskValidatesInterfaceBeforeHydratingMedia(t *testing.T) {
ReferenceImages: []providerMedia{{StorageKey: "resource:missing"}},
}
raw, _ := json.Marshal(input)
_, err := (&Service{}).processCanvasGenerationTask(context.Background(), "user-1", "video_generate", "", string(raw))
_, err := (&Service{}).processCanvasGenerationTask(context.Background(), "user-1", "", "video_generate", "", string(raw))
if err == nil || !strings.Contains(err.Error(), "不支持video生成") {
t.Fatalf("processCanvasGenerationTask() error = %v", err)
}
}
func TestResolveGenerationStyleExecutionUsesValidatedPromptAssets(t *testing.T) {
enabled := true
profile := styleProfileDocument{
Prompt: "base style",
ExecutionPolicy: "compatible-fallback",
Assets: []styleProfileAsset{
{ID: "prompt-1", Kind: "prompt", Title: "色彩约束", Provider: "builtin", Enabled: &enabled, Status: "validated", PromptFragment: "muted palette", TriggerWords: []string{"soft light"}},
{ID: "lora-1", Kind: "lora", Title: "东方角色 LoRA", Provider: "liblib", Enabled: &enabled, Status: "validated", SourceID: "model-1"},
},
}
prompt, status, warnings := resolveGenerationStyleExecution(profile, "image-model", "openai-image")
if prompt != "base style\nmuted palette\nsoft light" {
t.Fatalf("resolveGenerationStyleExecution() prompt = %q", prompt)
}
if status != "degraded" || len(warnings) != 1 || !strings.Contains(warnings[0], "LoRA") {
t.Fatalf("resolveGenerationStyleExecution() status = %q, warnings = %#v", status, warnings)
}
}
func TestResolveGenerationStyleExecutionStrictPolicyBlocksUnsupportedAsset(t *testing.T) {
profile := styleProfileDocument{
Prompt: "base style",
ExecutionPolicy: "strict-assets",
Assets: []styleProfileAsset{{ID: "reference-1", Kind: "reference", Title: "项目参考图", Provider: "project", Status: "validated", ReferenceResourceIDs: []string{"resource-1"}}},
}
_, status, warnings := resolveGenerationStyleExecution(profile, "image-model", "openai-image")
if status != "blocked" || len(warnings) != 1 {
t.Fatalf("resolveGenerationStyleExecution() status = %q, warnings = %#v", status, warnings)
}
}
func TestResolveGenerationStyleExecutionSkipsPromptAssetForOtherModel(t *testing.T) {
profile := styleProfileDocument{
Prompt: "base style",
ExecutionPolicy: "compatible-fallback",
Assets: []styleProfileAsset{{
ID: "template-1", Kind: "template", Title: "专用模板", Provider: "workflow", Status: "validated",
BaseModels: []string{"supported-model"}, PromptFragment: "must not be injected",
}},
}
prompt, status, warnings := resolveGenerationStyleExecution(profile, "other-model", "openai-image")
if prompt != "base style" || status != "degraded" || len(warnings) != 1 {
t.Fatalf("resolveGenerationStyleExecution() prompt = %q, status = %q, warnings = %#v", prompt, status, warnings)
}
}
func TestEquivalentStyleProfileJSONIgnoresObjectKeyOrder(t *testing.T) {
equal, err := equivalentStyleProfileJSON(`{"schemaVersion":1,"presetId":"style-1","assets":[]}`, `{"assets":[],"presetId":"style-1","schemaVersion":1}`)
if err != nil || !equal {
t.Fatalf("equivalentStyleProfileJSON() equal = %v, err = %v", equal, err)
}
}
@@ -38,6 +38,70 @@ func normalizeImageQuality(value string) string {
}
}
func imageParameterSupported(profile *ImageCapabilityConfig, parameter string) bool {
if profile == nil {
return true
}
if parameter == "response_format" {
return profile.ResponseFormat.Supported
}
return profile.OutputFormat.Supported
}
func imageQualitySupported(profile *ImageCapabilityConfig) bool {
return profile == nil || profile.Quality.Supported
}
func imageTransparentBackgroundSupported(profile *ImageCapabilityConfig) bool {
return profile == nil || profile.TransparentBackground.Supported
}
func imageSizeParameter(profile *ImageCapabilityConfig, value string) (string, string) {
if profile == nil {
return "size", normalizePixelSize(value)
}
value = strings.TrimSpace(value)
if value == "" || value == "auto" {
value = strings.TrimSpace(profile.Size.Default)
}
switch profile.Size.Parameter {
case "size":
return "size", normalizePixelSize(value)
case "aspect_ratio":
return "aspect_ratio", normalizeImageAspectRatio(value)
default:
return "", ""
}
}
func normalizeImageAspectRatio(value string) string {
value = strings.TrimSpace(strings.ToLower(strings.ReplaceAll(value, "×", "x")))
if strings.Contains(value, ":") {
return value
}
parts := strings.Split(value, "x")
if len(parts) != 2 {
return ""
}
width, widthErr := strconv.Atoi(parts[0])
height, heightErr := strconv.Atoi(parts[1])
if widthErr != nil || heightErr != nil || width <= 0 || height <= 0 {
return ""
}
divisor := imageDimensionGCD(width, height)
return strconv.Itoa(width/divisor) + ":" + strconv.Itoa(height/divisor)
}
func imageDimensionGCD(left int, right int) int {
for right != 0 {
left, right = right, left%right
}
if left < 1 {
return 1
}
return left
}
func normalizePixelSize(value string) string {
value = strings.TrimSpace(value)
if value == "" || value == "auto" {
+11 -5
View File
@@ -131,9 +131,10 @@ type agentStoryboardInput struct {
}
type storyboardProjectStyle struct {
PresetID string `json:"presetId"`
Title string `json:"title"`
Prompt string `json:"prompt"`
PresetID string `json:"presetId"`
Title string `json:"title"`
Prompt string `json:"prompt"`
ProfileJSON string `json:"profileJson,omitempty"`
}
type storyboardCharacterCard struct {
@@ -1079,7 +1080,7 @@ func (s *Service) processTask(ctx context.Context, task model.Task) (map[string]
return s.processStoryboardRowsTask(ctx, task)
}
if strings.HasPrefix(task.Type, "canvas_") || canRunProviderTask(task) {
result, err := s.processCanvasGenerationTask(ctx, task.UserID, task.Type, task.Prompt, task.InputJSON)
result, err := s.processCanvasGenerationTask(ctx, task.UserID, task.ProjectID, task.Type, task.Prompt, task.InputJSON)
return result, nil, err
}
if task.Type == "agent_storyboard" {
@@ -1341,6 +1342,11 @@ func validateStoryboardContext(projectStyle storyboardProjectStyle, characters [
if strings.TrimSpace(projectStyle.PresetID) == "" || strings.TrimSpace(projectStyle.Title) == "" || strings.TrimSpace(projectStyle.Prompt) == "" {
return errors.New("请先设置项目画风,再生成分镜")
}
if strings.TrimSpace(projectStyle.ProfileJSON) != "" {
if _, err := validateStyleProfileJSON(projectStyle.ProfileJSON); err != nil {
return err
}
}
for _, character := range characters {
if strings.TrimSpace(character.AssetID) == "" || strings.TrimSpace(character.VersionID) == "" || strings.TrimSpace(character.Name) == "" {
return errors.New("角色卡缺少当前资产版本,请刷新角色资产后再生成分镜")
@@ -1505,7 +1511,7 @@ func (s *Service) buildAgentStoryboardResult(task model.Task, plan agentStoryboa
ops := []map[string]any{
nodeOpWithMetadata(scriptID, "text", "剧本 · "+shortTitle(plan.Title, 24), 0, 0, map[string]any{"workflowKind": "script", "workflowTitle": "剧本", "status": "success", "content": strings.Join([]string{plan.Title, "", plan.Logline, "", task.Prompt}, "\n")}),
nodeOpWithMetadata(sceneID, "text", "场景设定", sceneX, 0, map[string]any{"workflowKind": "scene", "workflowTitle": "场景", "status": "success", "content": listContent("场景", plan.Locations)}),
nodeOpWithMetadata(styleID, "text", "项目画风 · "+shortTitle(projectStyle.Title, 24), styleX, 0, map[string]any{"workflowKind": "styleboard", "workflowTitle": "项目画风", "workflowDescription": plan.StyleGuide, "stylePresetId": projectStyle.PresetID, "status": "success", "content": projectStyle.Prompt, "prompt": projectStyle.Prompt}),
nodeOpWithMetadata(styleID, "text", "项目画风 · "+shortTitle(projectStyle.Title, 24), styleX, 0, map[string]any{"workflowKind": "styleboard", "workflowTitle": "项目画风", "workflowDescription": plan.StyleGuide, "stylePresetId": projectStyle.PresetID, "styleProfileJson": projectStyle.ProfileJSON, "status": "success", "content": projectStyle.Prompt, "prompt": projectStyle.Prompt}),
nodeOpWithMetadata(referenceID, "text", "参考素材组", 0, 270, map[string]any{"workflowKind": "reference_set", "workflowTitle": "参考素材组", "status": "success", "content": storyboardAssetsContent(assets)}),
nodeOpWithMetadata(finalID, "video", "成片 · 待生成", styleX, 270, map[string]any{"workflowKind": "final", "workflowTitle": "成片", "status": "idle"}),
connectOp(scriptID, sceneID),
+304
View File
@@ -0,0 +1,304 @@
package service
import (
"encoding/json"
"errors"
"strings"
"time"
"infinite-canvas/backend/internal/model"
)
const maxUserStyleProfiles = 200
type StyleProfileRequest struct {
ProfileJSON string `json:"profileJson"`
}
type StyleProfileFavoriteRequest struct {
Favorite bool `json:"favorite"`
}
type styleProfileDocument struct {
SchemaVersion int `json:"schemaVersion"`
PresetID string `json:"presetId"`
Title string `json:"title"`
Description string `json:"description"`
Tags []string `json:"tags"`
Prompt string `json:"prompt"`
NegativePrompt string `json:"negativePrompt"`
CoverURL string `json:"coverUrl"`
SourceProfileID string `json:"sourceProfileId"`
Selection map[string]string `json:"selection,omitempty"`
Assets []styleProfileAsset `json:"assets"`
ExecutionPolicy string `json:"executionPolicy"`
Source string `json:"source"`
Revision int `json:"revision"`
}
type styleProfileAsset struct {
ID string `json:"id"`
Kind string `json:"kind"`
Provider string `json:"provider"`
Title string `json:"title"`
Enabled *bool `json:"enabled"`
SourceID string `json:"sourceId"`
SourceURL string `json:"sourceUrl"`
Model string `json:"model"`
Version string `json:"version"`
BaseModels []string `json:"baseModels"`
TriggerWords []string `json:"triggerWords"`
PromptFragment string `json:"promptFragment"`
Weight *float64 `json:"weight"`
Parameters *styleProfileAssetParameters `json:"parameters"`
ReferenceURLs []string `json:"referenceUrls"`
ReferenceResourceIDs []string `json:"referenceResourceIds"`
Status string `json:"status"`
License *styleProfileAssetLicense `json:"license,omitempty"`
}
type styleProfileAssetParameters struct {
Sampler string `json:"sampler"`
Steps *int `json:"steps"`
CFG *float64 `json:"cfg"`
Size string `json:"size"`
}
type styleProfileAssetLicense struct {
Commercial *bool `json:"commercial,omitempty"`
Note string `json:"note,omitempty"`
Source string `json:"source,omitempty"`
CapturedAt string `json:"capturedAt,omitempty"`
}
func (s *Service) ListStyleProfiles(userID string) ([]model.StyleProfile, error) {
return s.repo.StyleProfiles(userID)
}
func (s *Service) CreateStyleProfile(userID string, req StyleProfileRequest) (model.StyleProfile, error) {
count, err := s.repo.StyleProfileCount(userID)
if err != nil {
return model.StyleProfile{}, err
}
if count >= maxUserStyleProfiles {
return model.StyleProfile{}, BadAuthRequest("我的风格最多保存 200 个")
}
normalized, document, err := normalizeUserStyleProfileJSON(req.ProfileJSON, "", 1)
if err != nil {
return model.StyleProfile{}, BadAuthRequest(err.Error())
}
now := time.Now()
profile := model.StyleProfile{
ID: newID(), UserID: userID, Name: strings.TrimSpace(document.Title), Description: strings.TrimSpace(document.Description),
CoverURL: strings.TrimSpace(document.CoverURL), TagsJSON: mustStyleProfileJSON(document.Tags), Favorite: false,
Revision: 1, CreatedAt: now, UpdatedAt: now,
}
normalized, document, err = normalizeUserStyleProfileJSON(normalized, profile.ID, profile.Revision)
if err != nil {
return model.StyleProfile{}, BadAuthRequest(err.Error())
}
profile.ProfileJSON = normalized
profile.Name = document.Title
if err := s.repo.CreateStyleProfile(&profile); err != nil {
return model.StyleProfile{}, err
}
return profile, nil
}
func (s *Service) UpdateStyleProfile(userID string, id string, req StyleProfileRequest) (model.StyleProfile, error) {
profile, err := s.repo.StyleProfileForUser(userID, id)
if err != nil {
return model.StyleProfile{}, err
}
normalized, document, err := normalizeUserStyleProfileJSON(req.ProfileJSON, profile.ID, profile.Revision+1)
if err != nil {
return model.StyleProfile{}, BadAuthRequest(err.Error())
}
profile.Name = document.Title
profile.Description = document.Description
profile.CoverURL = document.CoverURL
profile.TagsJSON = mustStyleProfileJSON(document.Tags)
profile.ProfileJSON = normalized
profile.Revision++
profile.UpdatedAt = time.Now()
if err := s.repo.UpdateStyleProfile(profile); err != nil {
return model.StyleProfile{}, err
}
return *profile, nil
}
func (s *Service) SetStyleProfileFavorite(userID string, id string, favorite bool) error {
return s.repo.SetStyleProfileFavorite(userID, id, favorite)
}
func (s *Service) TouchStyleProfile(userID string, id string) error {
return s.repo.TouchStyleProfile(userID, id, time.Now())
}
func (s *Service) DeleteStyleProfile(userID string, id string) error {
return s.repo.DeleteStyleProfile(userID, id)
}
func validateStyleProfileJSON(value string) (string, error) {
trimmed := strings.TrimSpace(value)
if trimmed == "" {
return "", nil
}
if len([]byte(trimmed)) > 256*1024 {
return "", errors.New("项目画风资产配置过大")
}
var profile styleProfileDocument
if err := json.Unmarshal([]byte(trimmed), &profile); err != nil {
return "", errors.New("项目画风资产配置不是合法 JSON")
}
if profile.SchemaVersion != 1 || strings.TrimSpace(profile.PresetID) == "" || strings.TrimSpace(profile.Title) == "" || strings.TrimSpace(profile.Prompt) == "" || profile.Revision < 1 {
return "", errors.New("项目画风资产配置缺少必要字段")
}
if profile.Assets == nil {
return "", errors.New("项目画风资产配置缺少 assets 数组")
}
if len(profile.Assets) > 20 {
return "", errors.New("项目画风执行资产最多绑定 20 个")
}
if profile.ExecutionPolicy != "" && profile.ExecutionPolicy != "compatible-fallback" && profile.ExecutionPolicy != "strict-assets" {
return "", errors.New("项目画风执行策略不支持")
}
if profile.Source != "builtin" && profile.Source != "user" && profile.Source != "external" {
return "", errors.New("项目画风来源不支持")
}
if len(profile.Selection) > 20 {
return "", errors.New("项目画风辅助标注最多 20 项")
}
for key, value := range profile.Selection {
if strings.TrimSpace(key) == "" || len([]rune(key)) > 64 || len([]rune(value)) > 200 {
return "", errors.New("项目画风辅助标注格式无效")
}
}
assetIDs := make(map[string]struct{}, len(profile.Assets))
for _, asset := range profile.Assets {
if strings.TrimSpace(asset.ID) == "" || strings.TrimSpace(asset.Title) == "" || strings.TrimSpace(asset.Provider) == "" || !styleProfileValueAllowed(asset.Kind, "lora", "template", "reference", "prompt") || !styleProfileValueAllowed(asset.Status, "draft", "validated", "unavailable") {
return "", errors.New("项目画风执行资产字段不完整")
}
if _, exists := assetIDs[asset.ID]; exists {
return "", errors.New("项目画风执行资产 ID 不能重复")
}
assetIDs[asset.ID] = struct{}{}
if asset.Weight != nil && (*asset.Weight < 0 || *asset.Weight > 2) {
return "", errors.New("LoRA 权重必须在 0 到 2 之间")
}
if len(asset.BaseModels) > 20 {
return "", errors.New("单个画风资产最多声明 20 个兼容模型")
}
if len(asset.TriggerWords) > 50 || len(asset.ReferenceURLs) > 20 || len(asset.ReferenceResourceIDs) > 20 {
return "", errors.New("项目画风执行资产的触发词或参考图数量过多")
}
if asset.Parameters != nil {
if asset.Parameters.Steps != nil && (*asset.Parameters.Steps < 1 || *asset.Parameters.Steps > 200) {
return "", errors.New("画风资产 Steps 必须在 1 到 200 之间")
}
if asset.Parameters.CFG != nil && (*asset.Parameters.CFG < 0 || *asset.Parameters.CFG > 50) {
return "", errors.New("画风资产 CFG 必须在 0 到 50 之间")
}
}
if asset.Status == "validated" {
switch asset.Kind {
case "lora":
if strings.TrimSpace(asset.SourceID) == "" && strings.TrimSpace(asset.SourceURL) == "" {
return "", errors.New("已验证的 LoRA 必须填写来源资产 ID 或 URL")
}
case "template", "prompt":
if strings.TrimSpace(asset.PromptFragment) == "" && len(nonEmptyStyleProfileStrings(asset.TriggerWords)) == 0 {
return "", errors.New("已验证的模板或提示词模块必须填写提示词内容")
}
case "reference":
if len(nonEmptyStyleProfileStrings(asset.ReferenceURLs)) == 0 && len(nonEmptyStyleProfileStrings(asset.ReferenceResourceIDs)) == 0 {
return "", errors.New("已验证的参考图组必须绑定参考图")
}
}
}
}
return trimmed, nil
}
func normalizeUserStyleProfileJSON(value string, presetID string, revision int64) (string, styleProfileDocument, error) {
validated, err := validateStyleProfileJSON(value)
if err != nil {
return "", styleProfileDocument{}, err
}
var document styleProfileDocument
if err := json.Unmarshal([]byte(validated), &document); err != nil {
return "", styleProfileDocument{}, errors.New("用户风格配置解析失败")
}
if len([]rune(strings.TrimSpace(document.Title))) > 80 {
return "", styleProfileDocument{}, errors.New("风格名称最多 80 个字")
}
if len([]rune(strings.TrimSpace(document.Description))) > 500 {
return "", styleProfileDocument{}, errors.New("风格简介最多 500 个字")
}
if len(document.Tags) > 20 {
return "", styleProfileDocument{}, errors.New("风格标签最多 20 个")
}
if len([]byte(document.CoverURL)) > 4096 || len([]byte(document.NegativePrompt)) > 64*1024 {
return "", styleProfileDocument{}, errors.New("风格封面或负面 Prompt 过大")
}
if coverURL := strings.ToLower(strings.TrimSpace(document.CoverURL)); coverURL != "" && !strings.HasPrefix(coverURL, "http://") && !strings.HasPrefix(coverURL, "https://") && !strings.HasPrefix(coverURL, "/") && !strings.HasPrefix(coverURL, "data:image/") {
return "", styleProfileDocument{}, errors.New("风格封面只支持 http(s)、站内路径或图片 Data URL")
}
if strings.TrimSpace(presetID) != "" {
document.PresetID = strings.TrimSpace(presetID)
}
document.SourceProfileID = document.PresetID
document.Source = "user"
document.Revision = int(revision)
document.Title = strings.TrimSpace(document.Title)
document.Description = strings.TrimSpace(document.Description)
document.CoverURL = strings.TrimSpace(document.CoverURL)
document.NegativePrompt = strings.TrimSpace(document.NegativePrompt)
document.Tags = nonEmptyStyleProfileStrings(document.Tags)
encoded, err := json.Marshal(document)
if err != nil {
return "", styleProfileDocument{}, errors.New("用户风格配置序列化失败")
}
if len(encoded) > 256*1024 {
return "", styleProfileDocument{}, errors.New("用户风格配置过大")
}
return string(encoded), document, nil
}
func validateStyleProfilePreset(presetID string, profileJSON string) error {
if strings.TrimSpace(profileJSON) == "" {
return nil
}
var profile styleProfileDocument
if err := json.Unmarshal([]byte(profileJSON), &profile); err != nil {
return errors.New("项目画风资产配置解析失败")
}
if strings.TrimSpace(presetID) == "" || strings.TrimSpace(profile.PresetID) != strings.TrimSpace(presetID) {
return errors.New("项目画风预设与结构化快照不一致")
}
return nil
}
func mustStyleProfileJSON(value any) string {
encoded, _ := json.Marshal(value)
return string(encoded)
}
func nonEmptyStyleProfileStrings(values []string) []string {
result := make([]string, 0, len(values))
for _, value := range values {
if trimmed := strings.TrimSpace(value); trimmed != "" {
result = append(result, trimmed)
}
}
return result
}
func styleProfileValueAllowed(value string, allowed ...string) bool {
for _, item := range allowed {
if value == item {
return true
}
}
return false
}
@@ -0,0 +1,105 @@
package service
import (
"encoding/json"
"testing"
"infinite-canvas/backend/internal/model"
"infinite-canvas/backend/internal/repository"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func TestStyleProfileCreateAndUpdateOwnsIdentityAndRevision(t *testing.T) {
svc := newStyleProfileTestService(t)
created, err := svc.CreateStyleProfile("user-1", styleProfileTestRequest(t, "志怪暗彩", 88))
if err != nil {
t.Fatal(err)
}
var createdDocument styleProfileDocument
if err := json.Unmarshal([]byte(created.ProfileJSON), &createdDocument); err != nil {
t.Fatal(err)
}
if created.Revision != 1 || createdDocument.PresetID != created.ID || createdDocument.SourceProfileID != created.ID || createdDocument.Source != "user" || createdDocument.Revision != 1 {
t.Fatalf("created profile identity was not normalized: model=%+v document=%+v", created, createdDocument)
}
if createdDocument.Selection["medium"] != "工笔暗彩" || len(createdDocument.Assets) != 1 || createdDocument.Assets[0].License == nil || createdDocument.Assets[0].License.Note != "需保留来源记录" {
t.Fatalf("created profile metadata was not preserved: document=%+v", createdDocument)
}
updated, err := svc.UpdateStyleProfile("user-1", created.ID, styleProfileTestRequest(t, "志怪暗彩二版", 300))
if err != nil {
t.Fatal(err)
}
var updatedDocument styleProfileDocument
if err := json.Unmarshal([]byte(updated.ProfileJSON), &updatedDocument); err != nil {
t.Fatal(err)
}
if updated.Revision != 2 || updatedDocument.Revision != 2 || updatedDocument.PresetID != created.ID || updatedDocument.Title != "志怪暗彩二版" {
t.Fatalf("updated profile revision was not server controlled: model=%+v document=%+v", updated, updatedDocument)
}
}
func TestStyleProfileMutationsRejectOtherUsers(t *testing.T) {
svc := newStyleProfileTestService(t)
created, err := svc.CreateStyleProfile("user-1", styleProfileTestRequest(t, "用户一风格", 1))
if err != nil {
t.Fatal(err)
}
if _, err := svc.UpdateStyleProfile("user-2", created.ID, styleProfileTestRequest(t, "越权修改", 1)); err == nil {
t.Fatal("expected cross-user update to fail")
}
if err := svc.SetStyleProfileFavorite("user-2", created.ID, true); err == nil {
t.Fatal("expected cross-user favorite to fail")
}
if err := svc.TouchStyleProfile("user-2", created.ID); err == nil {
t.Fatal("expected cross-user use tracking to fail")
}
if err := svc.DeleteStyleProfile("user-2", created.ID); err == nil {
t.Fatal("expected cross-user delete to fail")
}
profiles, err := svc.ListStyleProfiles("user-1")
if err != nil {
t.Fatal(err)
}
if len(profiles) != 1 || profiles[0].ID != created.ID {
t.Fatalf("owner profile was changed by rejected mutations: %+v", profiles)
}
}
func newStyleProfileTestService(t *testing.T) *Service {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
sqlDB, err := db.DB()
if err != nil {
t.Fatal(err)
}
sqlDB.SetMaxOpenConns(1)
if err := db.AutoMigrate(&model.StyleProfile{}); err != nil {
t.Fatal(err)
}
return New(repository.New(db), t.TempDir())
}
func styleProfileTestRequest(t *testing.T, title string, revision int) StyleProfileRequest {
t.Helper()
document := styleProfileDocument{
SchemaVersion: 1, PresetID: "client-controlled-id", Title: title, Description: "可复用风格",
Tags: []string{"志怪", "暗彩"}, Prompt: "统一使用工笔线条、暗彩矿物色和克制光影。", NegativePrompt: "禁止媒介漂移和随机文字。",
Selection: map[string]string{"world": "东方志怪", "medium": "工笔暗彩"},
Assets: []styleProfileAsset{{
ID: "license-snapshot", Kind: "prompt", Provider: "manual", Title: "材质约束", PromptFragment: "矿物色与宣纸肌理", Status: "validated",
License: &styleProfileAssetLicense{Note: "需保留来源记录", Source: "内部规范"},
}},
ExecutionPolicy: "compatible-fallback", Source: "external", Revision: revision,
}
encoded, err := json.Marshal(document)
if err != nil {
t.Fatal(err)
}
return StyleProfileRequest{ProfileJSON: string(encoded)}
}