Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from opendirector.application.creation_assets import CreationAssets
from opendirector.application.creation_canvas import CreationCanvas
from opendirector.application.creation_history import CreationHistory
from opendirector.application.creation_segment_run_publication import publish_segment_plan, save_segment_plan
from opendirector.domain.creation.project import ProjectSnapshot
from opendirector.domain.projects import ProjectError, project_name
from opendirector.ports.dispatch import register_command_dispatcher
Expand All @@ -27,6 +28,10 @@ def execute(self, projects, command, *, session=None, source='ui', imported_from
command, session=session, source=source, imported_from=imported_from)
if imported_from is not None:
raise ProjectError('只有素材导入可以声明归档来源。', 400, code='invalid_input')
if command.type == 'group.saveRunPlan':
return save_segment_plan(projects, command, session=session, source=source)
if command.type == 'group.publishRun':
return publish_segment_plan(projects, command, session=session, source=source)
if command.type == 'project.create':
return projects._create(command, source)
if command.type in _HISTORY_COMMANDS:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
"""Save and publish segment plans on existing canvas groups."""

from pathlib import Path
from shutil import copyfileobj
from tempfile import TemporaryDirectory
from uuid import uuid4, uuid5

from opendirector.application.creation_assets import CreationAssets
from opendirector.application.creation_canvas import asset_ref, visible_item_ids
from opendirector.domain.creation.assets import Asset, AssetProvenance
from opendirector.domain.creation.canvas import GroupCanvasItem, TextCanvasItem
from opendirector.domain.creation.commands import Command, CommandReceipt, GroupPlanDraft
from opendirector.domain.creation.project import ProjectSnapshot
from opendirector.domain.creation.validation import ContractError
from opendirector.domain.projects import ProjectError
from opendirector.media.probe import count_video_frames
from opendirector.ports.files import AssetFileWrite
from opendirector.ports.gateway import gateway


def validate_plan(snapshot: ProjectSnapshot, payload: GroupPlanDraft) -> GroupCanvasItem:
items = {item.id: item for item in snapshot.canvasItems}
group = items.get(payload.groupId)
if not isinstance(group, GroupCanvasItem) or group.runPlan is not None or group.locked or group.parentId or not group.visible:
raise ContractError('role_restricted', '请选择可见且未锁定的草稿分组。', payload.groupId)

source = next((asset for asset in snapshot.assets if asset.id == payload.plan.source.assetId), None)
if source is None or asset_ref(source) != payload.plan.source:
raise ContractError('reference_invalid', '计划源片已变更或无法读取。', payload.plan.source.assetId)
if source.metadata.frameRate is not None and source.metadata.frameRate != payload.plan.fps:
raise ContractError('reference_invalid', '计划帧率与源片不一致。', source.id)

entries = payload.plan.by_item()
clips = payload.assembly.clips
if tuple(clip.itemId for clip in clips) != tuple(entries):
raise ContractError('invalid_input', '组装片段须按源片顺序与生成区间对应。', group.id)
visible = visible_item_ids(snapshot)
for clip in clips:
item = items.get(clip.itemId)
entry = entries[clip.itemId]
if (item is None or item.kind != 'video' or item.binding.role != 'generation'
or item.parentId != group.id or item.id not in visible):
raise ContractError('invalid_input', '生成区间须引用分组内可见的视频生成节点。', clip.itemId)
if clip.outFrame - clip.inFrame != entry.sourceEnd - entry.sourceStart:
raise ContractError('invalid_input', '保留帧数须与源片区间长度一致。', clip.itemId)
timeline = items.get(payload.assembly.timelineItemId)
if timeline is None or timeline.kind != 'timeline' or timeline.parentId != group.id or timeline.id not in visible:
raise ContractError('invalid_input', '计划须关联分组内可见的时间线。', group.id)
return group


def plan_markdown(group: GroupCanvasItem, snapshot: ProjectSnapshot, payload: GroupPlanDraft) -> str:
chinese = payload.planLocale == 'zh-CN'
titles = {item.id: item.title.replace('|', '/').replace('\n', ' ') for item in snapshot.canvasItems}
clips = {clip.itemId: clip for clip in payload.assembly.clips}
rows = [
f'# {group.title}', '',
f'{payload.plan.frameCount} {"帧" if chinese else "frames"} · {payload.plan.fps} fps', '',
'| 源片帧区间 | 片段 | 导帧 | 保留区间 |' if chinese else '| Source frames | Segment | Guide | Retained frames |',
'| --- | --- | --- | --- |',
]
for entry in payload.plan.entries:
interval = f'[{entry.sourceStart}, {entry.sourceEnd})'
if entry.kind == 'source':
original = '保留原片' if chinese else 'Original footage'
rows.append(f'| {interval} | {original} | — | {interval} |')
continue
clip = clips[entry.itemId]
guide = '锚点' if chinese else 'Anchor'
if entry.step.kind == 'continuation':
first, last = entry.step.sourceFrames
guide = f'{titles[entry.step.upstreamItemId]} · {first} / {last}'
direction = ''
if clip.reverse:
direction = ' · 反转后取帧' if chinese else ' · after reversal'
rows.append(f'| {interval} | {titles[entry.itemId]} | {guide} | [{clip.inFrame}, {clip.outFrame}){direction} |')
if payload.planNotes.strip():
rows.extend(['', '## 编排说明' if chinese else '## Planning notes', '', payload.planNotes.strip()])
return '\n'.join(rows) + '\n'


def save_segment_plan(projects, command: Command, *, session: str | None, source: str) -> CommandReceipt:
payload = command.payload

def save(snapshot: ProjectSnapshot) -> ProjectSnapshot:
group = validate_plan(snapshot, payload)
if (group.draftRunPlan, group.assembly, group.runPlanLocale, group.runPlanNotes) == (
payload.plan, payload.assembly, payload.planLocale, payload.planNotes):
return snapshot
updated = group.model_copy(update={
'draftRunPlan': payload.plan, 'assembly': payload.assembly, 'runPlanLocale': payload.planLocale,
'runPlanNotes': payload.planNotes, 'revision': group.revision + 1,
})
return snapshot.model_copy(update={'canvasItems': tuple(
updated if item.id == group.id else item for item in snapshot.canvasItems)})

return projects.commit(command, save, session=session, source=source)


def publish_segment_plan(projects, command: Command, *, session: str | None, source: str) -> CommandReceipt:
replay = projects.replay(command)
if replay is not None:
return replay
payload = command.payload
snapshot = projects.snapshot(command.projectId)
try:
group = validate_plan(snapshot, payload)
except ContractError as error:
def reject(_: ProjectSnapshot) -> ProjectSnapshot:
raise error

return projects.commit(command, reject, session=session, source=source)

assets = CreationAssets(projects)
handle = uuid4()
writer = assets.uploads.begin(command.projectId, handle, session, 'Run plan.md', expected_kind='text')
try:
with TemporaryDirectory(prefix='opendirector-segment-plan-') as folder:
path = Path(folder, 'source')
stream, _ = assets.open_media(command.projectId, payload.plan.source.assetId, snapshot=snapshot)
with stream, path.open('wb') as target:
copyfileobj(stream, target)
if count_video_frames(path, fps=payload.plan.fps) != payload.plan.frameCount:
raise ProjectError('计划帧数与实际源片不一致。', 409, code='reference_invalid')
writer.write(plan_markdown(group, snapshot, payload).encode('utf-8'))
upload = writer.finish()
finally:
writer.abort()
asset_id = gateway().upload_asset_id(command.projectId, handle)
asset = Asset(id=asset_id, projectId=command.projectId, kind='text', name='Run plan.md',
path=f'assets/{asset_id}', metadata=upload.metadata, fingerprint=upload.fingerprint,
provenance=AssetProvenance(source='manual'))
plan_id = uuid5(command.commandId, 'published-segment-plan')
card = TextCanvasItem(id=plan_id, projectId=command.projectId, kind='text',
title='运行计划' if payload.planLocale == 'zh-CN' else 'Run plan',
parentId=group.id, locked=True, position={'x': 32, 'y': 48}, width=640, height=400,
binding={'role': 'material', 'objectRef': asset_ref(asset)})
published = group.model_copy(update={
'assembly': payload.assembly, 'runPlan': payload.plan, 'draftRunPlan': None,
'runPlanItemId': plan_id, 'runDefinitionId': command.commandId, 'runPlanLocale': payload.planLocale,
'runPlanNotes': payload.planNotes, 'revision': group.revision + 1,
})

def publish(before: ProjectSnapshot) -> ProjectSnapshot:
if before != snapshot:
raise ContractError('revision_conflict', '工程在发布前已更新,请重试。', group.id)
items = tuple(published if item.id == group.id else item for item in before.canvasItems)
return before.model_copy(update={'assets': (*before.assets, asset), 'canvasItems': (*items, card)})

write = AssetFileWrite(assetId=asset_id, uploadHandle=handle, fingerprint=asset.fingerprint, size=asset.metadata.size)
receipt = projects.commit(command, publish, session=session, source=source, files=(write,))
if not any(version.id == asset_id for version in receipt.changed):
try:
assets.uploads.cancel(command.projectId, handle, session)
except ProjectError as error:
if error.code != 'session_expired':
raise
return receipt
1 change: 1 addition & 0 deletions packages/core/src/opendirector/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"result": "Select a generated result for adoption.",
"editor": "Create and save editable media documents.",
"timeline": "Discover resources for editable timelines.",
"group": "Save and publish segment run plans.",
"history": "Undo or redo reversible project operations.",
"creation": "Apply multiple project operations atomically.",
}
Expand Down
60 changes: 60 additions & 0 deletions packages/core/src/opendirector/domain/creation/canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .base import CanvasColor, CanvasItemVersion, Contract, Identifier, Point, Positive, ProjectEntity, unique
from .generation import FollowingSource, GenerationSpec, ResolvedReference, validate_generation
from .models import ModelConfigPublic
from .segment_run import SegmentRunPlan


class FollowingReferenceSource(Contract):
Expand Down Expand Up @@ -189,12 +190,71 @@ class DirectorCanvasItem(EditorCanvasItem):
kind: Literal['external'] = Field(description='Business object or media type.')


class WorkflowClip(Contract):
itemId: UUID = Field(description='Generation canvas node providing the raw video.')
inFrame: Annotated[int, Field(strict=True, ge=0, le=4095)] = Field(description='First retained frame in playback order.')
outFrame: Annotated[int, Field(strict=True, ge=1, le=4096)] = Field(description='Exclusive end of the retained frames.')
reverse: bool = Field(default=False, description='Reverse the raw window before keeping the selected frames.')
frameLimit: Annotated[int, Field(strict=True, ge=1, le=4096)] | None = Field(
default=None, description='Optional cap on the raw window before reversal.')

@model_validator(mode='after')
def frame_window(self):
if self.outFrame <= self.inFrame or (self.frameLimit is not None and self.outFrame > self.frameLimit):
raise ValueError('Invalid workflow frame window')
return self


class GroupAssembly(Contract):
timelineItemId: UUID = Field(description='Timeline canvas node receiving the assembled clips.')
outputItemId: UUID = Field(description='Stable canvas node ID for the published video.')
clips: tuple[WorkflowClip, ...] = Field(min_length=1, max_length=50, description='Generated clips in assembly order.')
requireTimelineGuides: bool = Field(default=False, strict=True, exclude_if=lambda value: not value,
description='Required for H3 segmented plans. A confirmed plan keeps its guide requirement when its assembly is edited.')
guideExemptItemId: UUID | None = Field(default=None, exclude_if=lambda value: value is None,
description='The only generation anchor that may omit a timeline guide. Omit this to require a guide on every clip.')

@model_validator(mode='after')
def distinct_items(self):
clip_ids = {clip.itemId for clip in self.clips}
ids = {self.timelineItemId, self.outputItemId, *clip_ids}
if len(ids) != len(self.clips) + 2:
raise ValueError('Assembly nodes must have distinct identities')
if self.guideExemptItemId is not None and (not self.requireTimelineGuides or self.guideExemptItemId not in clip_ids):
raise ValueError('The guide-exempt anchor must be a clip in a guide-required assembly')
return self


class GroupCanvasItem(CanvasItemBase):
kind: Literal['group'] = Field(description='Business object or media type.')
autoLayout: Literal['run'] | None = Field(default=None, exclude_if=lambda value: value is None,
description='Set to run to opt this top-level group into shared Run layout. Put its plan, clips and timeline under this group ID.')
runPlan: SegmentRunPlan | None = Field(default=None, exclude_if=lambda value: value is None,
description='Frozen plan assigned only by the Run publication command.')
draftRunPlan: SegmentRunPlan | None = Field(default=None, exclude_if=lambda value: value is None,
description='Editable plan input from a published Run. Publish it before starting execution.')
runPlanItemId: UUID | None = Field(default=None, exclude_if=lambda value: value is None,
description='Read-only canvas node showing the published plan.')
runDefinitionId: UUID | None = Field(default=None, exclude_if=lambda value: value is None,
description='Publication command ID identifying this frozen Run definition.')
runPlanLocale: Literal['zh-CN', 'en-US'] | None = Field(default=None, exclude_if=lambda value: value is None,
description='Language of the visible Run plan.')
runPlanNotes: str | None = Field(default=None, exclude_if=lambda value: value is None, max_length=16000,
description='Editable notes accompanying the Run plan.')
assembly: GroupAssembly | None = Field(default=None, exclude_if=lambda value: value is None,
description='Optional frame-accurate assembly after the group generation run.')
binding: ContainerBinding = Field(default_factory=lambda: ContainerBinding(role='container'), description='Business object displayed by this canvas item.')

@model_validator(mode='after')
def published_plan(self) -> 'GroupCanvasItem':
if self.runPlan is not None and (
self.runPlanItemId is None or self.runDefinitionId is None or self.assembly is None
or self.draftRunPlan is not None):
raise ValueError('Published plans require a plan card, a definition ID and an assembly.')
if self.runPlan is None and (self.runPlanItemId is not None or self.runDefinitionId is not None):
raise ValueError('Only published plans can reference a plan card or definition ID.')
return self


CanvasItem = Annotated[TextCanvasItem | ImageCanvasItem | VideoCanvasItem | AudioCanvasItem | FileCanvasItem |
SubjectCanvasItem | TimelineCanvasItem | StackCanvasItem | ToolCanvasItem | DirectorCanvasItem | GroupCanvasItem,
Expand Down
39 changes: 38 additions & 1 deletion packages/core/src/opendirector/domain/creation/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

from .assets import AssetRef, MediaMetadata
from .base import CanvasColor, Contract, Digest, GenerationKind, MediaKind, ObjectVersion, Point, Positive, Revision, digest, unique
from .canvas import CanvasItem
from .segment_run import SegmentRunPlan
from .canvas import GroupAssembly, CanvasItem
from .editors import EditorDocument
from opendirector.domain.rule_facts import PROMPT_MAX_LENGTH
from .generation import GenerationSpec, Job, PromptPart, Reference
Expand Down Expand Up @@ -64,6 +65,38 @@ def assets(self):
return self


class GroupPlanDraft(Contract):
model_config = ConfigDict(json_schema_extra={'examples': [{
'groupId': '00000000-0000-0000-0000-000000000001',
'plan': {
'source': {
'assetId': '00000000-0000-0000-0000-000000000002',
'kind': 'video', 'revision': 1, 'fingerprint': 'sha256:' + '0' * 64,
},
'fps': 24, 'frameCount': 24,
'entries': [{
'kind': 'generated', 'sourceStart': 0, 'sourceEnd': 24,
'itemId': '00000000-0000-0000-0000-000000000003',
'shot': 'opening', 'step': {'kind': 'anchor'},
}],
},
'assembly': {
'timelineItemId': '00000000-0000-0000-0000-000000000004',
'outputItemId': '00000000-0000-0000-0000-000000000005',
'clips': [{
'itemId': '00000000-0000-0000-0000-000000000003',
'inFrame': 0, 'outFrame': 24,
}],
},
}]})

groupId: UUID = Field(description='Canvas group holding the draft.')
plan: SegmentRunPlan = Field(description='Segment intervals in source order.')
assembly: GroupAssembly = Field(description='Retained frames for the generated intervals.')
planLocale: Literal['zh-CN', 'en-US'] = Field(default='zh-CN', description='Language of the published plan.')
planNotes: str = Field(default='', max_length=16000, description='Notes accompanying the plan.')


class CanvasShow(Contract):
item: CanvasItem = Field(description='Canvas display item to create or restore.')

Expand Down Expand Up @@ -293,6 +326,8 @@ def required_versions(self) -> list[tuple[str, UUID]]:
required = []
if self.type in {'project.rename', 'project.trash', 'project.restore'}:
required = [('project', self.projectId)]
elif self.type in {'group.saveRunPlan', 'group.publishRun'}:
required = [('canvas_item', payload.groupId)]
elif self.type == 'canvas.publishMedia':
required = [('canvas_item', payload.itemId), *[('asset', o.asset.assetId) for o in payload.outputs]]
if payload.sourceEditorId:
Expand Down Expand Up @@ -338,6 +373,8 @@ def required_versions(self) -> list[tuple[str, UUID]]:
('AssetMetadataCommand', 'asset.updateMetadata', AssetMetadataUpdate, 'Rename an asset.'),
('AssetDeleteCommand', 'asset.delete', AssetDelete, 'Delete assets after an impact preview.'),
('CanvasCreateGenerationCommand', 'canvas.createGeneration', CanvasCreateGeneration, 'Create a visible generation node and references atomically, preserving canvas source connections, including pinned ones.'),
('GroupSavePlanCommand', 'group.saveRunPlan', GroupPlanDraft, 'Save a draft segment plan.'),
('GroupPublishRunCommand', 'group.publishRun', GroupPlanDraft, 'Publish the segment plan as a Markdown canvas node.'),
('CanvasShowCommand', 'canvas.show', CanvasShow, 'Create or restore a canvas display item.'),
('CanvasMoveCommand', 'canvas.move', CanvasMove, 'Move one or more canvas items.'),
('CanvasUpdateCommand', 'canvas.update', CanvasPresentationUpdate, 'Update canvas presentation, grouping or lock state.'),
Expand Down
Loading
Loading