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
2 changes: 2 additions & 0 deletions apps/api/src/opendirector_api/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,8 @@ async def execute(project_id: UUID, value: Command, request: Request, x_opendire
if generation is None:
raise ProjectError('任务服务不可用。', 503)
receipt = await generation.execute(value, session=session)
elif value.type in {'canvas.applyVersion', 'canvas.exportVersion'} and x_canvas_import is None:
receipt = await run_in_threadpool(history.execute, value, session=session)
else:
receipt = await run_in_threadpool(projects.execute, value, session=session, imported_from=imported_from)
return localized_receipt(request, receipt)
Expand Down
1 change: 1 addition & 0 deletions docs/guides/user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ Select a node, then choose an action from its toolbar.

- **Images**: Crop, rotate, flip, adjust colors, work with layers, add text, shapes, or annotations, and edit selections.
- **Video and audio**: Extract frames, trim, extract audio tracks, and process clips.
To compare video results, open the node history and hover over a video to reveal playback controls and when generation started. Video versions are listed newest first. Use **Download** on the preview to save the original video. **Export to canvas** creates a video generation node with the recorded settings and reference connections, pinned to the media used for that version. Select a version to **Show prompt and settings** or **Apply to current node**. Additional results from the same batch appear in the node history.
Use the version button at the top right of a node to apply an earlier version. If a generation job blocks the change, choose **Stop blocking jobs** in the history panel, then apply the version. Previously generated results remain available.
When trimming a video, choose WebM (the default) or MP4 under **Output format**. Choose MP4 if your model requires MP4 reference video.
- **AI tools**: Extend images, erase content, remove backgrounds, edit images with AI, upscale, and more. Availability depends on the connected models.
Expand Down
1 change: 1 addition & 0 deletions docs/guides/user-guide.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ Codex 网页检索引用在具有匹配来源时显示为编号链接;复制

- **图片**:裁剪、旋转、翻转、调色、图层、文字、形状、标注和选区编辑。
- **视频与音频**:取帧、裁剪、音轨提取和片段处理。
对比视频时,打开节点历史。视频版本按生成时间从新到旧排列。将鼠标放到画面上即可预览,左上角会显示发起生成的时间,并可拖动进度条、切换声音或全屏。点击画面右上角的「下载」可保存原视频。「导出到画布」将已生成版本放入新的视频生成节点,保留生成配置及其参考连线,并固定使用该版本生成时的参考素材。选中版本后,可点击「显示提示词与生成参数」查看详情,或点击「应用到当前节点」替换当前结果。批量生成的其余候选保存在该节点的历史版本中。
从节点右上角的历史版本按钮可以应用旧版本。如果生成任务阻塞切换,请先在历史版本面板点击「停止阻塞任务」,再应用版本。之前生成的结果仍可使用。
使用「时长修剪」时,可在「保存格式」中选择 WebM(默认)或 MP4。如果模型要求参考视频为 MP4,请选择 MP4。
- **AI 工具**:扩图、消除、抠图、智能改图、超清等,是否可用取决于已接入模型。
Expand Down
87 changes: 72 additions & 15 deletions packages/core/src/opendirector/application/creation_assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from tempfile import TemporaryDirectory
from pathlib import Path
from threading import Lock
from time import monotonic
from uuid import UUID, uuid5

from opendirector.domain.creation.assets import Asset, AssetDownloadFile, AssetDownloadReceipt, AssetProvenance
Expand All @@ -22,6 +23,10 @@
from opendirector.ports.gateway import gateway


VIDEO_THUMBNAIL_TIMEOUT = 30
VIDEO_THUMBNAIL_COPY_LIMIT = 16 * 1024 * 1024


class CreationAssets:
def __init__(self, projects):
self.projects = projects
Expand Down Expand Up @@ -288,6 +293,11 @@ def read(asset_id):

return read

def media_file_present(self, path, asset):
"""Cheap advisory availability for the video comparison listing."""
with self._pin_asset_file(path, asset) as stream:
return os.fstat(stream.fileno()).st_size == asset.metadata.size

def _verify_media(self, stream, asset):
try:
def signature():
Expand Down Expand Up @@ -386,31 +396,78 @@ def browser_image(self, project_id, asset_id, *, known_fingerprint=None):
return png(open_image(stream.read())), asset

def thumbnail(self, project_id, asset_id):
"""A bounded, disposable image preview; always verify its source first."""
"""A bounded, disposable image or video preview of verified bytes."""
from PIL import Image, ImageOps
stream, asset = self.open_media(project_id, asset_id)
with stream:
if asset.kind != 'image':
raise ProjectError('只有图片素材支持缩略图。', 400)
key = asset.fingerprint
if asset.kind not in {'image', 'video'}:
raise ProjectError('只有图片和视频素材支持缩略图。', 400, code='invalid_input')
key = (asset.kind, asset.fingerprint)
with self._verification_lock:
cached = self._thumbnails.get(key)
if cached is not None:
self._thumbnails.move_to_end(key)
return cached, asset
try:
with Image.open(stream) as source:
source.thumbnail((480, 480))
image = ImageOps.exif_transpose(source).convert('RGBA')
output = BytesIO()
# A non-RGB source profile cannot describe the converted RGB pixels.
image.save(output, format='WEBP', quality=80,
icc_profile=source.info.get('icc_profile') if source.mode in {'RGB', 'RGBA', 'P', 'PA'} else None)
value = output.getvalue()
except (OSError, ValueError, EOFError, Image.DecompressionBombError):
raise ProjectError('无法读取图片素材。', 422, code='image_decode') from None
if asset.kind == 'video':
value = self._video_thumbnail(stream)
else:
try:
with Image.open(stream) as source:
source.thumbnail((480, 480))
image = ImageOps.exif_transpose(source).convert('RGBA')
output = BytesIO()
image.save(output, format='WEBP', quality=80,
icc_profile=source.info.get('icc_profile') if source.mode in {'RGB', 'RGBA', 'P', 'PA'} else None)
value = output.getvalue()
except (OSError, ValueError, EOFError, Image.DecompressionBombError):
raise ProjectError('无法读取图片素材。', 422, code='image_decode') from None
with self._verification_lock:
self._thumbnails[key] = value
while len(self._thumbnails) > 64:
self._thumbnails.popitem(last=False)
return value, asset

@staticmethod
def _video_thumbnail(stream):
deadline = monotonic() + VIDEO_THUMBNAIL_TIMEOUT
input_options = ['ffmpeg', '-nostdin', '-v', 'error']
output_options = [
'-map', '0:v:0', '-an', '-filter_threads', '1',
'-vf', "scale='min(640,iw)':'min(640,ih)':force_original_aspect_ratio=decrease",
'-frames:v', '1', '-c:v', 'libwebp', '-quality', '80', '-f', 'image2pipe', 'pipe:1',
]

def render(protocol, source, stdin=None):
remaining = deadline - monotonic()
if remaining <= 0:
raise TimeoutError
return subprocess.run(
[*input_options, '-protocol_whitelist', protocol, '-threads', '1', '-i', source, *output_options],
stdin=stdin, capture_output=True, check=True, timeout=remaining,
).stdout

try:
if os.name != 'nt':
content = render('file', '/dev/fd/0', stream)
else:
try:
content = render('fd', 'fd:', stream)
except subprocess.CalledProcessError:
if os.fstat(stream.fileno()).st_size > VIDEO_THUMBNAIL_COPY_LIMIT or monotonic() >= deadline:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

大视频用可寻址 fd 取帧的回归补得好。能再单独覆盖旧 Windows FFmpeg 不支持 fd 的分支吗?新测试在没有 fd 时会跳过,建议锁住两条预期:小视频还会生成海报,超过 16 MiB 时不落临时副本,并且仍能悬停播放。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

谢谢复核。首次取帧现在优先直接读取已验证的文件,32 MiB 的尾部索引 MP4 用例已验证可以在不创建临时视频副本的情况下解出 WebP。rebase 后的 39d49d11 已通过整套 Release checks,包括此前超时的 OpenCode 图像用例。

你提到的旧版 Windows FFmpeg 回退路径值得单独覆盖。目前的大文件用例在 Windows 缺少 fd 支持时会跳过。这个场景还需要验证小视频能生成海报,以及超过 16 MiB 的视频会跳过临时复制、仍能悬停播放。

raise
stream.seek(0)
remaining = VIDEO_THUMBNAIL_COPY_LIMIT
with TemporaryDirectory(prefix='opendirector-video-thumb-') as temporary:
source = Path(temporary) / 'media'
with source.open('wb') as destination:
while chunk := stream.read(min(CHUNK_BYTES, remaining + 1)):
if len(chunk) > remaining or monotonic() >= deadline:
raise OSError
destination.write(chunk)
remaining -= len(chunk)
content = render('file', str(source))
if content:
return content
except (OSError, subprocess.SubprocessError):
pass
raise ProjectError('无法生成素材预览。', 422, code='operation_rejected')
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

_ASSET_COMMANDS = {'asset.import', 'asset.writeText', 'asset.updateMetadata'}
_HISTORY_COMMANDS = {
'history.undo', 'history.redo', 'generationSpec.restore', 'canvas.applyVersion', 'asset.delete',
'history.undo', 'history.redo', 'generationSpec.restore', 'canvas.applyVersion', 'canvas.exportVersion', 'asset.delete',
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -627,10 +627,13 @@ def apply(current, asset):
if item and item.binding.role == 'generation':
eligible = eligible and item.binding.materialOverride == current_job.adoptionMaterial
adopt = eligible and same_selection and current_job.adoptionPolicy == 'if_current'
selected_result = next((r for r in current.results if r.id == current_spec.currentResultId), None)
selected_job = next((j for j in current.jobs if selected_result and j.id == selected_result.jobId), None)
own_batch = current_job.batchId is not None and selected_job is not None and selected_job.batchId == current_job.batchId
additional = self._additional_item(current, item, asset, current_job) if eligible and current_job.showAdditionalResult and (same_selection or own_batch) and item and item.id in visible_item_ids(current) else None
additional = None
if asset.kind != 'video' and eligible and current_job.showAdditionalResult and item and item.id in visible_item_ids(current):
selected_result = next((r for r in current.results if r.id == current_spec.currentResultId), None)
selected_job = next((j for j in current.jobs if selected_result and j.id == selected_result.jobId), None)
own_batch = current_job.batchId is not None and selected_job is not None and selected_job.batchId == current_job.batchId
if same_selection or own_batch:
additional = self._additional_item(current, item, asset, current_job)
result = ResultVersion(id=uuid5(job.id, 'result'), projectId=job.projectId, specId=spec.id, jobId=job.id,
asset=asset_ref(asset), inputFingerprint=job.inputFingerprint)
check = self._technical_check(media_record(asset))
Expand Down
34 changes: 17 additions & 17 deletions packages/core/src/opendirector/application/creation_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
EDITABLE = {'canvasItems', 'generationSpecs', 'references', 'editorDocuments'}
ABSENT = object()
UNDOABLE = {'canvas.createGeneration', 'creation.batch', 'canvas.show', 'canvas.hide', 'canvas.move', 'canvas.update', 'canvas.layoutRuns', 'canvas.layoutPipelines', 'canvas.configure',
'canvas.materialize', 'canvas.applyEdit', 'timeline.publishRender', 'canvas.publishMedia', 'canvas.applyVersion', 'canvas.attachEditor', 'canvas.detachEditor', 'generationSpec.update', 'generationSpec.restore',
'canvas.materialize', 'canvas.applyEdit', 'timeline.publishRender', 'canvas.publishMedia', 'canvas.applyVersion', 'canvas.exportVersion', 'canvas.attachEditor', 'canvas.detachEditor', 'generationSpec.update', 'generationSpec.restore',
'reference.add', 'reference.update', 'reference.restore', 'reference.remove', 'result.select', 'editor.save', 'generationSpec.setPrompt'}


Expand Down Expand Up @@ -184,7 +184,10 @@ def execute(self, command, *, session=None, source='ui'):
def apply(before, records):
if command.type == 'canvas.applyVersion':
from opendirector.application.creation_node_versions import apply_node_version
return apply_node_version(self, before, command)
return apply_node_version(self, before, command, records)
if command.type == 'canvas.exportVersion':
from opendirector.application.creation_node_versions import export_node_version
return export_node_version(self, before, command, records)
if command.type == 'generationSpec.restore':
return self._restore(before, command)
states = self._states(records)
Expand Down Expand Up @@ -252,7 +255,10 @@ def apply(before, records):
put(actual, path, restore)
self._validate_editor_locks(before, data)
return self._revisions(before, data)
return self.projects.commit(command, apply, session=session, source=source, with_history=True)
uses_video_history = command.type == 'canvas.exportVersion' or (
command.type == 'canvas.applyVersion' and command.payload.asset.kind == 'video')
history = 'facts' if uses_video_history else True
return self.projects.commit(command, apply, session=session, source=source, with_history=history)

@staticmethod
def _validate_editor_locks(before, data):
Expand All @@ -273,23 +279,17 @@ def _validate_editor_locks(before, data):
CreationCanvas._editable(current, item['id'])

def version_counts(self, project_id):
# Counting only reads snapshots; copying every record here made the
# badge refresh cost ~20 s on projects with hundreds of commits.
records = self.projects.records(project_id)
snapshot = records[0].snapshot
snapshot, facts, _ = self.projects.snapshot_with_history_facts(project_id)
families = {i.id: set() for i in snapshot.canvasItems if i.kind in {'text', 'image', 'video', 'audio'}}
owners = {}
for record in records:
for item in record.snapshot.canvasItems:
if item.id not in families:
for fact in facts:
for item_id, spec_id, asset_id in fact.media_bindings:
if item_id not in families:
continue
asset = current_asset(record.snapshot, item)
if asset:
families[item.id].add(asset.id)
binding = item.binding
spec = binding.objectRef if binding.role == 'generation' else binding.draftSpec if binding.role == 'empty' else None
if spec:
owners.setdefault(spec.id, set()).add(item.id)
if asset_id is not None:
families[item_id].add(asset_id)
if spec_id is not None:
owners.setdefault(spec_id, set()).add(item_id)
jobs = {j.id: j for j in snapshot.jobs}
for result in snapshot.results:
for item_id in owners.get(result.specId, set()) | {jobs[result.jobId].originItemId}:
Expand Down
Loading
Loading