feat(*): 分镜与资产 - 完善五类资产、候选去重、搜索、中文镜头编号与分类整理

This commit is contained in:
ddCat committed 2026-08-31 13:16:10 +08:00
1 parent ce6e20f749
commit f548681787
53 files changed
+816 -188

No files matched your search

+1 -1
View File
@@ -462,7 +462,7 @@ func containsString(values []string, target string) bool {
func validAssetCategory(category model.AssetCategory) bool {
switch category {
case model.AssetCategoryCharacter, model.AssetCategoryEnvironment, model.AssetCategoryWardrobe, model.AssetCategoryProp, model.AssetCategoryWeapon, model.AssetCategoryStyle, model.AssetCategoryOther:
case model.AssetCategoryCharacter, model.AssetCategoryEnvironment, model.AssetCategoryProp, model.AssetCategoryMaterial, model.AssetCategoryOther:
return true
default:
return false
+117 -7
View File
@@ -3,6 +3,7 @@ package service
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
@@ -61,8 +62,11 @@ type AssetCandidateInput struct {
type CreateAssetCandidatesRequest struct {
Candidates []AssetCandidateInput `json:"candidates"`
Source string `json:"source"`
}
const assetCandidateSourceChapterCharacter = "chapter_character_extract"
func (s *Service) CreateProjectShot(userID string, projectID string, req CreateProjectShotRequest) (model.Shot, error) {
if _, err := s.activeProjectForUser(userID, projectID); err != nil {
return model.Shot{}, err
@@ -301,14 +305,31 @@ func (s *Service) CreateProjectAssetCandidates(userID string, projectID string,
if len(req.Candidates) == 0 || len(req.Candidates) > 100 {
return nil, BadAuthRequest("资产候选数量必须在 1 到 100 之间")
}
source := strings.TrimSpace(req.Source)
existingCandidates, err := s.repo.ProjectAssetCandidates(projectID)
if err != nil {
return nil, err
}
projectAssets, err := s.repo.ProjectAssets(userID, projectID)
if err != nil {
return nil, err
}
knownKeys := projectAssetCandidateIdentityKeys(existingCandidates, projectAssets)
now := time.Now()
candidates := make([]model.ProjectAssetCandidate, 0, len(req.Candidates))
for _, input := range req.Candidates {
name := strings.TrimSpace(input.Name)
nameKey := model.AssetCandidateNameKey(name)
category := model.AssetCategory(strings.TrimSpace(input.Category))
if name == "" || !validAssetCategory(category) {
if name == "" || nameKey == "" || !validAssetCategory(category) {
return nil, BadAuthRequest("资产候选名称或分类无效")
}
if category == model.AssetCategoryCharacter && source != assetCandidateSourceChapterCharacter {
return nil, BadAuthRequest("角色候选只能从剧情章节的角色提取流程创建")
}
if category == model.AssetCategoryCharacter && strings.TrimSpace(input.UnitID) == "" {
return nil, BadAuthRequest("角色候选必须关联剧情章节")
}
if input.UnitID != "" {
if _, err := s.repo.ProjectUnit(projectID, input.UnitID); err != nil {
return nil, err
@@ -328,17 +349,106 @@ func (s *Service) CreateProjectAssetCandidates(userID string, projectID string,
return nil, err
}
}
candidates = append(candidates, model.ProjectAssetCandidate{ID: newID(), ProjectID: projectID, UnitID: strings.TrimSpace(input.UnitID), ShotID: strings.TrimSpace(input.ShotID), Name: name, Category: category, Status: "pending_confirmation", DetailsJSON: detailsJSON, CreatedAt: now, UpdatedAt: now})
identityKeys := assetCandidateInputIdentityKeys(name, input.Details)
if assetCandidateIdentityExists(knownKeys, category, identityKeys) {
continue
}
candidate := model.ProjectAssetCandidate{ID: newID(), ProjectID: projectID, UnitID: strings.TrimSpace(input.UnitID), ShotID: strings.TrimSpace(input.ShotID), Name: name, NameKey: nameKey, Category: category, Status: "pending_confirmation", Source: source, DetailsJSON: detailsJSON, CreatedAt: now, UpdatedAt: now}
inserted, createErr := s.repo.CreateProjectAssetCandidate(&candidate)
if createErr != nil {
return nil, createErr
}
if !inserted {
continue
}
candidates = append(candidates, candidate)
addAssetCandidateIdentityKeys(knownKeys, category, identityKeys)
}
if err := s.repo.CreateProjectAssetCandidates(candidates); err != nil {
return nil, err
}
if err := s.repo.BumpProjectRevision(projectID); err != nil {
return nil, err
if len(candidates) > 0 {
if err := s.repo.BumpProjectRevision(projectID); err != nil {
return nil, err
}
}
return candidates, nil
}
func projectAssetCandidateIdentityKeys(candidates []model.ProjectAssetCandidate, assets []model.Asset) map[string]struct{} {
known := make(map[string]struct{}, len(candidates)+len(assets))
for _, candidate := range candidates {
keys := []string{candidate.NameKey}
if strings.TrimSpace(candidate.DetailsJSON) != "" {
var details map[string]any
if json.Unmarshal([]byte(candidate.DetailsJSON), &details) == nil {
keys = append(keys, assetCandidateAliases(details)...)
}
}
addAssetCandidateIdentityKeys(known, candidate.Category, keys)
}
for _, asset := range assets {
keys := []string{model.AssetCandidateNameKey(asset.Title)}
if asset.Category == model.AssetCategoryCharacter {
keys = append(keys, characterAssetAliasKeys(asset.PayloadJSON)...)
}
addAssetCandidateIdentityKeys(known, asset.Category, keys)
}
return known
}
func assetCandidateInputIdentityKeys(name string, details map[string]any) []string {
return append([]string{model.AssetCandidateNameKey(name)}, assetCandidateAliases(details)...)
}
func assetCandidateAliases(details map[string]any) []string {
if details == nil {
return nil
}
values, ok := details["aliases"].([]any)
if !ok {
if stringsValue, stringsOK := details["aliases"].([]string); stringsOK {
values = make([]any, len(stringsValue))
for index, value := range stringsValue {
values[index] = value
}
}
}
keys := make([]string, 0, len(values))
for _, value := range values {
if key := model.AssetCandidateNameKey(fmt.Sprint(value)); key != "" {
keys = append(keys, key)
}
}
return keys
}
func characterAssetAliasKeys(payloadJSON string) []string {
var payload struct {
Data struct {
Definition map[string]any `json:"definition"`
} `json:"data"`
}
if json.Unmarshal([]byte(payloadJSON), &payload) != nil {
return nil
}
return assetCandidateAliases(payload.Data.Definition)
}
func assetCandidateIdentityExists(known map[string]struct{}, category model.AssetCategory, keys []string) bool {
for _, key := range keys {
if _, exists := known[string(category)+":"+key]; exists {
return true
}
}
return false
}
func addAssetCandidateIdentityKeys(known map[string]struct{}, category model.AssetCategory, keys []string) {
for _, key := range keys {
if key != "" {
known[string(category)+":"+key] = struct{}{}
}
}
}
func validShotAssetRole(role string) bool {
switch role {
case "reference", "start_frame", "end_frame", "keyframe", "storyboard", "output":
@@ -354,12 +354,12 @@ func (s *Service) ProjectCanvasesPage(userID string, projectID string, page int,
return ProjectCanvasPage{Canvases: canvases, CanvasUnitLinks: links, Page: page, PageSize: pageSize, Total: total, HasMore: int64(page*pageSize) < total}, nil
}
func (s *Service) ProjectAssetCandidatesPage(userID string, projectID string, page int, pageSize int, unitID string, status string, category string) (ProjectAssetCandidatePage, error) {
func (s *Service) ProjectAssetCandidatesPage(userID string, projectID string, page int, pageSize int, unitID string, status string, category string, query string) (ProjectAssetCandidatePage, error) {
if _, err := s.repo.ProjectForUser(userID, projectID); err != nil {
return ProjectAssetCandidatePage{}, err
}
page, pageSize = normalizeProjectPage(page, pageSize, 200)
candidates, total, err := s.repo.ProjectAssetCandidatesPage(projectID, page, pageSize, unitID, status, category)
candidates, total, err := s.repo.ProjectAssetCandidatesPage(projectID, page, pageSize, unitID, status, category, query)
if err != nil {
return ProjectAssetCandidatePage{}, err
}
@@ -232,3 +232,23 @@ func TestProjectAssetsPagePaginatesAndReturnsFacets(t *testing.T) {
t.Fatalf("unexpected folder facets: %+v", page.FolderCounts)
}
}
func TestProjectAssetCandidatesPageSearchesNamesWithinFilters(t *testing.T) {
service, db := newProjectWorkbenchReadTestService(t)
project := seedWorkbenchProject(t, db)
candidates := []model.ProjectAssetCandidate{
{ID: "candidate-1", ProjectID: project.ID, UnitID: "unit-1", Name: "红色雨伞", Category: model.AssetCategoryProp, Status: "pending_confirmation"},
{ID: "candidate-2", ProjectID: project.ID, UnitID: "unit-1", Name: "蓝色雨衣", Category: model.AssetCategoryProp, Status: "pending_confirmation"},
{ID: "candidate-3", ProjectID: project.ID, UnitID: "unit-2", Name: "红色雨伞场景", Category: model.AssetCategoryEnvironment, Status: "pending_confirmation"},
}
if err := db.Create(&candidates).Error; err != nil {
t.Fatal(err)
}
page, err := service.ProjectAssetCandidatesPage("user-1", project.ID, 1, 20, "unit-1", "pending_confirmation", "prop", "雨伞")
if err != nil {
t.Fatal(err)
}
if page.Total != 1 || len(page.Candidates) != 1 || page.Candidates[0].ID != "candidate-1" {
t.Fatalf("unexpected candidate search result: %+v", page)
}
}
+2 -2
View File
@@ -602,12 +602,12 @@ func (s *Service) ensureGeneratedProjectAsset(task model.Task, projectID string,
}
title += " · " + label
payload, _ := json.Marshal(map[string]any{
"id": assetID, "kind": mediaType, "category": model.AssetCategoryOther, "status": model.AssetVersionStatusConfirmed,
"id": assetID, "kind": mediaType, "category": model.AssetCategoryMaterial, "status": model.AssetVersionStatusConfirmed,
"primaryVersionId": versionID, "title": title,
"data": map[string]any{"storageKey": "resource:" + resourceID, "url": "/api/resources/" + resourceID + "/file", "mimeType": resource.MimeType, "bytes": resource.Size},
"metadata": map[string]any{"source": "short-drama-workflow", "taskId": task.ID, "shotId": shot.ID, "projectIds": []string{projectID}},
})
asset := &model.Asset{ID: assetID, UserID: task.UserID, Kind: mediaType, Category: model.AssetCategoryOther, Status: model.AssetVersionStatusConfirmed, PrimaryVersionID: versionID, Title: title, PayloadJSON: string(payload), CreatedAt: now, UpdatedAt: now}
asset := &model.Asset{ID: assetID, UserID: task.UserID, Kind: mediaType, Category: model.AssetCategoryMaterial, Status: model.AssetVersionStatusConfirmed, PrimaryVersionID: versionID, Title: title, PayloadJSON: string(payload), CreatedAt: now, UpdatedAt: now}
version := &model.AssetVersion{ID: versionID, AssetID: assetID, Version: 1, Status: model.AssetVersionStatusConfirmed, DefinitionJSON: "{}", Prompt: task.Prompt, Note: "工作流生成产物", CreatedAt: now, UpdatedAt: now}
folderID, err := s.resolveProjectAssetFolderID(projectID, nil)
if err != nil {
@@ -20,7 +20,7 @@ func newProjectWorkflowV2TestService(t *testing.T) (*Service, *gorm.DB) {
}
if err := db.AutoMigrate(
&model.Project{}, &model.ProjectUnit{}, &model.CanvasProject{}, &model.Asset{}, &model.AssetVersion{}, &model.ProjectAssetLink{}, &model.ProjectAssetCandidate{},
&model.AssetRepresentation{},
&model.AssetRepresentation{}, &model.CharacterVoiceBinding{},
&model.Shot{}, &model.ShotRevision{}, &model.ShotArtifact{}, &model.ShotAssetReference{},
&model.WorkflowTemplateVersion{}, &model.WorkflowInstance{}, &model.WorkflowStepInstance{}, &model.WorkflowStepTask{},
&model.ProductionTaskLink{}, &model.Task{}, &model.Resource{},
@@ -131,6 +131,79 @@ func TestShortDramaWorkflowV2UsesProductionOrder(t *testing.T) {
}
}
func TestCreateProjectCharacterCandidatesIsIdempotentAcrossPendingAndConfirmed(t *testing.T) {
service, db := newProjectWorkflowV2TestService(t)
project, unit := seedWorkflowProject(t, db)
request := CreateAssetCandidatesRequest{
Source: assetCandidateSourceChapterCharacter,
Candidates: []AssetCandidateInput{{
UnitID: unit.ID, Name: " 小红帽 ", Category: string(model.AssetCategoryCharacter),
Details: validCharacterCandidateDetails([]any{"小红"}),
}},
}
created, err := service.CreateProjectAssetCandidates("user-1", project.ID, request)
if err != nil {
t.Fatal(err)
}
if len(created) != 1 {
t.Fatalf("created candidates = %d, want 1", len(created))
}
created, err = service.CreateProjectAssetCandidates("user-1", project.ID, request)
if err != nil {
t.Fatal(err)
}
if len(created) != 0 {
t.Fatalf("duplicate pending candidates = %d, want 0", len(created))
}
if _, err := service.ConfirmProjectAssetCandidate("user-1", project.ID, firstProjectCandidateID(t, db), ConfirmProjectAssetCandidateRequest{}); err != nil {
t.Fatal(err)
}
created, err = service.CreateProjectAssetCandidates("user-1", project.ID, request)
if err != nil {
t.Fatal(err)
}
if len(created) != 0 {
t.Fatalf("confirmed character was extracted again: %d", len(created))
}
var assetCount int64
if err := db.Model(&model.Asset{}).Where("user_id = ? AND category = ?", "user-1", model.AssetCategoryCharacter).Count(&assetCount).Error; err != nil {
t.Fatal(err)
}
if assetCount != 1 {
t.Fatalf("character assets = %d, want 1", assetCount)
}
}
func TestCreateProjectCharacterCandidatesRejectsNonChapterSource(t *testing.T) {
service, db := newProjectWorkflowV2TestService(t)
project, unit := seedWorkflowProject(t, db)
_, err := service.CreateProjectAssetCandidates("user-1", project.ID, CreateAssetCandidatesRequest{
Source: "agent",
Candidates: []AssetCandidateInput{{UnitID: unit.ID, Name: "猎人", Category: string(model.AssetCategoryCharacter), Details: validCharacterCandidateDetails(nil)}},
})
if err == nil {
t.Fatal("agent source unexpectedly created a character candidate")
}
}
func validCharacterCandidateDetails(aliases []any) map[string]any {
return map[string]any{
"role": "主角", "aliases": aliases, "appearance": "红色斗篷", "clothing": "红色兜帽与斗篷", "physique": "儿童体型",
"personality": "勇敢", "voiceLanguage": "普通话", "voiceAge": "儿童", "voiceTimbre": "清亮",
}
}
func firstProjectCandidateID(t *testing.T, db *gorm.DB) string {
t.Helper()
var candidate model.ProjectAssetCandidate
if err := db.Order("created_at asc").First(&candidate).Error; err != nil {
t.Fatal(err)
}
return candidate.ID
}
func TestWorkflowCompletionRequiresStageGate(t *testing.T) {
service, db := newProjectWorkflowV2TestService(t)
project, unit := seedWorkflowProject(t, db)
+1 -4
View File
@@ -292,10 +292,7 @@ func assetFromJSON(userID string, raw json.RawMessage) (model.Asset, error) {
if utf8.RuneCountInString(primaryVersionID) > 36 {
return model.Asset{}, BadAuthRequest("素材主版本 ID 不能超过 36 个字符")
}
category := model.AssetCategory(strings.TrimSpace(payload.Category))
if category == "" {
category = model.AssetCategoryOther
}
category := model.NormalizeAssetCategory(model.AssetCategory(payload.Category), payload.Kind)
status := model.AssetVersionStatus(strings.TrimSpace(payload.Status))
if status == "" {
status = model.AssetVersionStatusConfirmed
@@ -27,6 +27,35 @@ func TestAssetFromJSONAcceptsDeterministicGenerationID(t *testing.T) {
}
}
func TestAssetFromJSONNormalizesLegacyAndUnclassifiedMediaCategories(t *testing.T) {
tests := []struct {
name string
kind string
category string
want model.AssetCategory
}{
{name: "legacy accessory", kind: "image", category: "accessory", want: model.AssetCategoryProp},
{name: "legacy style", kind: "image", category: "style", want: model.AssetCategoryMaterial},
{name: "unclassified video", kind: "video", want: model.AssetCategoryMaterial},
{name: "unclassified entity", kind: "entity", want: model.AssetCategoryCharacter},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
raw, err := json.Marshal(map[string]any{"id": "asset-1", "kind": test.kind, "category": test.category, "title": "测试资产"})
if err != nil {
t.Fatal(err)
}
asset, err := assetFromJSON("user-1", raw)
if err != nil {
t.Fatal(err)
}
if asset.Category != test.want {
t.Fatalf("category = %q, want %q", asset.Category, test.want)
}
})
}
}
func TestAssetFromJSONRejectsIDOverLimit(t *testing.T) {
raw, err := json.Marshal(map[string]any{"id": strings.Repeat("a", model.AssetIDMaxLength+1), "kind": "image"})
if err != nil {