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/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
from opendirector.domain.creation.assets import ASSET_DOWNLOAD_ENGLISH

ENGLISH_BY_CODE = {
'video_compression_preset': 'Choose a valid compression preset.',
'video_compression_source': 'Select one video to compress.',
**ASSET_DOWNLOAD_ENGLISH,
'keyframe_unsupported': 'This model or mode does not support keyframes. Clear the keyframe times or choose another model.',
'keyframe_mode': 'Keyframes work in Universal reference mode only, not with first/last frames, continuation or structure control.',
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/opendirector_api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ def create_app(store: LocalProjects | None = None, chat_provider=None, generatio
pipelines = PipelineExecutor(creation_projects, creation_generation, model_configs)
creation_generation.pipelines = pipelines
creation_tools = ToolTasks(store, model_configs, CreationToolAssets(creation_projects), projects=creation_projects, availability=availability)
creation_generation.tool_tasks = creation_tools
catalog = ModelCatalog(model_configs, chat_provider or ChatCompletions(), availability)

active_agents = {}
Expand Down
16 changes: 16 additions & 0 deletions docs/guides/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,19 @@ opendirector --project PROJECT_UUID asset download --id ASSET_UUID --revision 1
### Download original assets

Use `project show` to get the asset ID and revision. `asset download` copies the original bytes of that revision to a new file. This read requires no editing lease or asset registration. In Agent Shell the active project is already selected, and the output path must stay inside the current execution directory.

## Video compression / 视频压缩

Open **Compress Video** on a video node, choose a preset, and start compression. The local FFmpeg task keeps the original and places a compressed H.264 MP4 on a new canvas node when it succeeds. The presets are original resolution, 1080p, 720p and 480p. Resolution presets cap the short edge and do not upscale the video. Audio is encoded as AAC when present.

选中视频节点后打开**视频压缩**,选择档位并开始压缩。本地 FFmpeg 任务保留原片,成功后将压缩后的 H.264 MP4 放在新画布节点上。档位有原分辨率、1080p、720p 和 480p。分辨率档位限制短边,低于该分辨率的素材不会放大。有音轨时使用 AAC 编码。

From the CLI, supply the source asset ID and a stable operation ID. The operation ID is also the task ID. Query the task, request cancellation with `--action cancel`, or publish a successful result with `--action publish`.

在 CLI 中传入源素材 ID 和固定的操作 ID。操作 ID 同时也是任务 ID。可以查询任务,用 `--action cancel` 请求取消,或用 `--action publish` 将成功结果发布到画布。

```sh
opendirector video compress --asset-id ASSET_ID --operation-id TASK_ID --preset balanced
opendirector video compression-task TASK_ID
opendirector video compression-task TASK_ID --action publish
```
27 changes: 27 additions & 0 deletions packages/core/src/opendirector/agent/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,17 @@ def tools() -> list[dict]:
{'type': 'object', 'properties': {'type': command_type, 'payload': {'type': 'object'},
'expectedVersions': versions, 'expectedPreview': {'type': ['string', 'null']}}, '$defs': definitions,
'required': ['type', 'payload'], 'additionalProperties': False}))
result.append(tool_schema('video_compress',
'Start local MP4 compression without overwriting the source. Returns a durable task; inspect with compression_task and publish explicitly after success.',
{'type': 'object', 'properties': {'taskId': {'type': 'string', 'format': 'uuid'},
'sourceAssetId': {'type': 'string', 'format': 'uuid'},
'preset': {'type': 'string', 'enum': ['quality', 'balanced', 'small', 'preview']}},
'required': ['taskId', 'sourceAssetId', 'preset'], 'additionalProperties': False}))
result.append(tool_schema('compression_task',
'Inspect, request cancellation, or publish a successful compression result as a new canvas node. Reuse the original task ID.',
{'type': 'object', 'properties': {'taskId': {'type': 'string', 'format': 'uuid'},
'action': {'type': 'string', 'enum': ['get', 'cancel', 'publish']}},
'required': ['taskId', 'action'], 'additionalProperties': False}))
result.append(tool_schema('prompt_optimize',
'Rewrite an image or video draft with its saved references and the configured text model. '
'Return a draft only; does not edit the node or generate media. Use [[OD_REF_n]] and inlineReferences to retain inline reference positions.',
Expand Down Expand Up @@ -351,6 +362,22 @@ def __init__(self, projects, generation, configs, chat_provider=None):
async def execute(self, project_id: UUID, turn_id: UUID, session: str, call_id: str,
name: str, arguments: dict, roots: list[Path], config: dict | None, native_runtime: str | None = None,
execution_directory: Path | None = None, *, runtime_model=None, thinking='auto') -> JsonValue:
if name in {'video_compress', 'compression_task'}:
service = self.generation.tool_tasks
task_id = str(UUID(arguments['taskId']))
pid = str(project_id)
if name == 'video_compress':
return await service.submit(pid, dict(id=task_id, tool='video-compress',
sourceAssetIds=[str(UUID(arguments['sourceAssetId']))],
parameters={'preset': arguments['preset']}), session)
task = await asyncio.to_thread(service.get, pid, task_id)
if task['tool'] != 'video-compress':
raise ProjectError('Select a video compression task.', 422, code='invalid_input')
if arguments['action'] == 'cancel':
return await service.cancel(pid, task_id, session, wait=False)
if arguments['action'] == 'publish':
return await asyncio.to_thread(service.placement, pid, task_id, 'placed', session, policy='explicit')
return task
if name == 'prompt_optimize':
item_id = UUID(arguments['itemId'])
value = PromptOptimizationInput.model_validate({k: v for k, v in arguments.items() if k != 'itemId'})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
outpaint, panorama, product_replacement, smart_edit, view_control,
)
from opendirector.application.tool_image_segments import cutout, layer_decompose, select_image_objects
from opendirector.application.tool_video_compression import PRESETS as COMPRESSION_PRESETS, video_compress
from opendirector.domain.image_presets import PRESETS, preset_instructions
from opendirector.application.tool_video_recipes import (
AUDIO_MODES, audio_separation, depth_capture, mask_composite, frame_interpolation, partial_reshoot,
Expand Down Expand Up @@ -92,6 +93,8 @@ def _preset_select():
lambda parameters: ('audio.separate',) if parameters.get('mode') in {'soundEffects', 'description'} else (),
audio_separation, (_select('mode', '分离方式', list(AUDIO_MODES.items()), 'all'),),
note='本地处理:完整音轨直接分离;人声/背景声为滤波近似,干净分轨需接入音轨分离模型。'),
ToolSpec('video-compress', ('video',), _needs(), video_compress,
(_select('preset', '压缩档位', [(key, value.label) for key, value in COMPRESSION_PRESETS.items()], 'balanced'),)),
ToolSpec('video-upscale', ('video',), _needs(), video_upscale, note='本地 Lanczos 插值放大,不调用模型。'),
ToolSpec('video-frame-interpolation', ('video',), _needs(), frame_interpolation,
(_select('fps', '输出帧率', [(30, '30 fps'), (60, '60 fps')], 60),), note='本地运动补偿插帧,不调用模型。'),
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/opendirector/application/tool_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,11 @@ def _prepare_locked(self, project_id, value, session, *, inspect=False, prepared
if spec.recipe is None:
raise ProjectError(f"该工具需要接入具备「{'、'.join(LABELS[item] for item in spec.requires({}))}」能力的模型。", 409)
parameters = value.get('parameters') or {}
if spec.id == 'video-compress':
from .tool_video_compression import compression_preset
compression_preset(parameters)
if len(value.get('sourceAssetIds') or []) != 1:
raise ProjectError('压缩时请选择一个视频。', 422, code='video_compression_source')
mask_id = identifier(str(value['maskAssetId'])) if value.get('maskAssetId') else None
annotation_id = identifier(str(value['annotationAssetId'])) if value.get('annotationAssetId') else None
needs = spec.requires(parameters)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""Model-free compression presets shared by tool admission and execution."""
from dataclasses import dataclass
from pathlib import PurePath

from opendirector.application.tool_context import Output
from opendirector.domain.projects import ProjectError
from opendirector.media import processing as media
from opendirector.media.async_work import blocking


@dataclass(frozen=True)
class CompressionPreset:
label: str
short_edge: int | None
crf: int
maxrate: int
audio_rate: int


PRESETS = {
'quality': CompressionPreset('原分辨率 · 高画质', None, 20, 12000, 192),
'balanced': CompressionPreset('1080p · 均衡(推荐)', 1080, 24, 4000, 128),
'small': CompressionPreset('720p · 小文件', 720, 27, 1500, 96),
'preview': CompressionPreset('480p · 预览', 480, 30, 600, 64),
}


def compression_preset(parameters):
key = parameters.get('preset', 'balanced')
if not isinstance(key, str) or key not in PRESETS:
raise ProjectError('请选择有效的压缩档位。', 422, code='video_compression_preset')
return PRESETS[key]


def _compress(source, preset):
with media.Workspace() as work:
original = work.write('source', source.data)
factor = f'min(1,{preset.short_edge}/min(iw*sar,ih))' if preset.short_edge else '1'
size = f"scale=w='max(2,trunc(iw*sar*{factor}/2)*2)':h='max(2,trunc(ih*{factor}/2)*2)':flags=lanczos,setsar=1"
output = work.path / 'compressed.mp4'
media._run(['ffmpeg', '-nostdin', '-v', 'error', '-y', '-i', str(original),
'-map', '0:V:0', '-map', '0:a:0?', '-sn', '-dn',
'-vf', size,
'-c:v', 'libx264', '-preset', 'medium', '-crf', str(preset.crf),
'-maxrate', f'{preset.maxrate}k', '-bufsize', f'{preset.maxrate * 2}k',
'-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', f'{preset.audio_rate}k',
'-movflags', '+faststart', str(output)], timeout=3600)
return output.read_bytes()


async def video_compress(ctx):
preset = compression_preset(ctx.parameters)
await ctx.progress('正在压缩视频')
source = ctx.sources[0]
data = await blocking(_compress, source, preset)
return [Output('video', data, 'mp4', f'{PurePath(source.name).stem}-H264')]
34 changes: 34 additions & 0 deletions packages/core/src/opendirector/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,40 @@ def timeline_import(ctx: typer.Context, file: Path, operation_id: Annotated[UUID
if value['status'] != 'applied': raise typer.Exit(1)


@group("video").command("compress", help="Compress one asset in the background; keeps the original. Query the returned task ID.")
def video_compress(ctx: typer.Context, asset_id: Annotated[UUID, typer.Option()],
operation_id: Annotated[UUID, typer.Option()],
preset: Annotated[Literal['quality', 'balanced', 'small', 'preview'], typer.Option()] = 'balanced'):
client = ctx.obj
client.command = ctx.command_path
if client.live:
value = client.call('video_compress', dict(taskId=str(operation_id), sourceAssetId=str(asset_id), preset=preset), identity=operation_id)
else:
client.open()
value = client.request('POST', client.path('/tool-tasks'), json=dict(id=str(operation_id),
tool='video-compress', sourceAssetIds=[str(asset_id)], parameters={'preset': preset}))
emit(value)


@group("video").command("compression-task", help="Query a compression task, request cancellation or publish its successful output.")
def compression_task(ctx: typer.Context, task_id: Annotated[UUID, typer.Argument()],
action: Annotated[Literal['get', 'cancel', 'publish'], typer.Option()] = 'get'):
client = ctx.obj
client.command = ctx.command_path
if client.live:
value = client.call('compression_task', dict(taskId=str(task_id), action=action))
else:
value = client.request('GET', client.path(f'/tool-tasks/{task_id}'))
if value['tool'] != 'video-compress':
raise ProjectError('Select a video compression task.', 422)
if action != 'get':
client.open()
suffix = 'cancel' if action == 'cancel' else 'placement'
value = client.request('POST', client.path(f'/tool-tasks/{task_id}/{suffix}'),
json={'state': 'placed', 'policy': 'explicit'} if action == 'publish' else {})
emit(value)


TAKE_OVER_HINT = {
"en": ("Or, with the user's agreement, run the command again with --take-over before the subcommand; that window "
"then switches to preview and can take editing back with \u201cEdit in this window\u201d."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ class SelectionBox(Contract):
'dynamic-poster', 'ecommerce-main', 'image-presets', 'grid-split', 'composition', 'annotation',
'video-edit', 'video-extend', 'video-partial-reshoot', 'video-upscale', 'video-frame-interpolation',
'video-depth-capture', 'video-subtitle-erasure', 'video-matting', 'video-crop', 'video-translation',
'video-mask-composite', 'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage']
'video-mask-composite', 'video-compress', 'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage']


class ToolDraftBinding(Contract):
Expand Down
1 change: 1 addition & 0 deletions src/canvas/NodeSelectionToolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ const imageTools: readonly [CanvasToolId, MessageKey, string, ToolGlyphName][] =
["cutout", "canvas.selection.tool.cutout", "subject", "cutout"],
];
const videoTools: readonly [CanvasToolId, MessageKey, string][] = [
["video-compress", "tools.compression.title", "video"],
["video-partial-reshoot", "canvas.selection.tool.videoReshoot", "camera"],
["video-upscale", "canvas.selection.tool.upscale", "video"],
["video-edit", "canvas.selection.tool.videoEdit", "edit"],
Expand Down
15 changes: 13 additions & 2 deletions src/canvas/VideoActionEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
import { createPortal } from "react-dom";
import { useI18n } from "../i18n/I18nProvider.tsx";
import type { MessageKey } from "../i18n/types.ts";
import { translateTool } from "./toolText.ts";
import { translateTool, translateToolText } from "./toolText.ts";
import { CanvasIcon } from "./CanvasIcon";
import { ControlSlider } from "./ControlSlider";
import { TooltipButton } from "./TooltipButton";
Expand All @@ -25,6 +25,7 @@ import {
type CanvasToolTask,
type ToolParameters,
type ToolValue,
type ToolField,
} from "./toolCatalog";
import { centeredVideoCrop, fitVideoCrop, type VideoCrop } from "./videoCrop";
import { withMediaDuration } from "./editorMedia";
Expand Down Expand Up @@ -57,6 +58,7 @@ export interface VideoActionEditorProps {
unavailableReason?: string;
/** Canvas nodes offered as the second source of two-source tools. */
nodes?: readonly CanvasNode[];
fields?: readonly ToolField[];
}

const LOCAL = new Set<CanvasToolId>([
Expand Down Expand Up @@ -106,6 +108,7 @@ function VideoActionSession({
onGenerate,
unavailableReason,
nodes = [],
fields = [],
}: VideoActionEditorProps) {
const { t, locale } = useI18n();
const definition = translateTool(
Expand Down Expand Up @@ -1312,6 +1315,14 @@ function VideoActionSession({
{tool === "extract-audio" && (
<p className="cw-va-hint">{t("tools.videoEditor.extract.hint")}</p>
)}
{tool === "video-compress" && (
<>
{choices(t("tools.compression.preset"), "preset",
(fields.find((field) => field.key === "preset")?.options ?? []).map((option) =>
[option.value, translateToolText(locale, option.label)]))}
<p className="cw-va-hint">{t("tools.compression.hint")}</p>
</>
)}
{tool === "video-trim" &&
choices(t("tools.videoEditor.outputFormat"), "outputFormat", [
["webm", "WebM"],
Expand Down Expand Up @@ -1422,7 +1433,7 @@ function VideoActionSession({
}
}}
>
{t("tools.videoEditor.generate")}
{tool === "video-compress" ? t("tools.compression.start") : t("tools.videoEditor.generate")}
</button>
</>
)}
Expand Down
5 changes: 4 additions & 1 deletion src/canvas/toolCatalog.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/** Authored local task contract. These descriptors are not a private API client.
* Unverified dynamic model, price, distance, brightness and resolution options require capabilities.
*/
import { getActiveLocale, tNow } from "../i18n/messages.ts";
import { getActiveLocale, tNow, translate } from "../i18n/messages.ts";
import { translateToolText } from "./toolText.ts";

export type CanvasToolId =
Expand All @@ -27,6 +27,7 @@ export type CanvasToolId =
| "video-edit"
| "video-extend"
| "video-partial-reshoot"
| "video-compress"
| "video-upscale"
| "video-frame-interpolation"
| "video-depth-capture"
Expand Down Expand Up @@ -191,6 +192,8 @@ function tool(
};
}
export const CANVAS_TOOLS: readonly CanvasToolDefinition[] = [
tool("video-compress", translate("zh-CN", "tools.compression.title"), translate("zh-CN", "tools.compression.hint"), [],
{ category: "video", sources: ["video"], parameterCoverage: "verified" }),
tool(
"layers",
"图层工作台",
Expand Down
3 changes: 3 additions & 0 deletions src/canvas/toolTaskText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ export interface ToolTaskFailure {
}

const CODE: Record<string, MessageKey> = {
video_compression_preset: "errors.tools.error.compressionPreset",
video_compression_source: "errors.tools.error.compressionSource",
tool_concept_translation: "errors.tools.error.conceptTranslation",
tool_no_video_match: "errors.tools.error.noVideoMatch",
};

const PHASE: Record<string, MessageKey> = {
正在压缩视频: "errors.tools.phase.compressVideo",
准备素材: "errors.tools.phase.prepare",
停止处理中: "errors.tools.phase.stopping",
正在扩展画面: "errors.tools.phase.outpaint",
Expand Down
9 changes: 9 additions & 0 deletions src/canvas/toolText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,18 @@
* translating on read preserves stable ids/values and avoids cloning the whole
* catalog for every locale.
*/
import { translate } from "../i18n/messages.ts";
import type { Locale } from "../i18n/types.ts";
import type { CanvasToolDefinition, ToolField } from "./toolCatalog.ts";

const EN: Record<string, string> = {
"视频压缩": "Compress Video",
"压缩档位": "Compression preset",
"原分辨率 · 高画质": "Original resolution · High quality",
"1080p · 均衡(推荐)": "1080p · Balanced (recommended)",
"720p · 小文件": "720p · Small file",
"480p · 预览": "480p · Preview",

"仅自定义画幅使用,单位像素;服务上限未确认。":
"Only used for custom aspect ratios, in pixels; the service limit is unconfirmed.",
"选区矩形数据无效。": "Invalid selection rectangle data.",
Expand Down Expand Up @@ -274,6 +282,7 @@ export function translateTool(
locale: Locale,
tool: CanvasToolDefinition,
): CanvasToolDefinition {
if (tool.id === "video-compress") return { ...tool, title: translate(locale, "tools.compression.title"), description: translate(locale, "tools.compression.hint") };
if (locale === "zh-CN") return tool;
return {
...tool,
Expand Down
2 changes: 2 additions & 0 deletions src/canvas/videoActionRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ export function initialVideoActionParameters(
switch (tool) {
case "video-trim":
return { outputFormat: "webm" };
case "video-compress":
return { preset: "balanced" };
case "video-upscale":
return { resolution: "4K" };
case "video-depth-capture":
Expand Down
1 change: 1 addition & 0 deletions src/canvas/workspace/WorkspaceView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1857,6 +1857,7 @@ export function WorkspaceView({ rt, editingState, editSession }: {
key={activeAction.token}
node={actionNode}
tool={activeAction.tool}
fields={toolCatalog.capabilities[activeAction.tool]?.fields}
nodes={doc.nodes}
draft={actionNode.data.taskDraft}
mediaContainer={actionMedia}
Expand Down
Loading
Loading