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 @@ -142,8 +142,8 @@ def reference_policy(spec, values, rules=None, *, selected_frame=False):
raise ContractError('reference_invalid', '指定的首尾帧不能作为图片传入当前模型;请使用明确的图片素材引用,且不要填写主体槽位 subjectRole。', value.referenceId)
if value.subjectRole is not None and rules is not None:
ignored = ignored or kind not in rules.allowedKinds or (kind == 'image' and not rules.maxImages) or (kind == 'video' and not rules.maxVideos) or (kind == 'audio' and not rules.maxAudios)
if spec.kind == 'video' and spec.parameters.videoMode == 'continuation' and kind == 'video':
ignored = True # Subject clips are not a remote continuation ID.
if spec.kind == 'video' and spec.parameters.videoMode in {'continuation', 'control'} and kind == 'video':
ignored = True # Subject clips are neither a remote continuation ID nor a control video.
transmission = 'context_only' if ignored else 'latent' if value.role == 'continuation' else 'metadata' if spec.kind == 'text' and kind in {'audio', 'video'} else 'content'
output.append(value.model_copy(update={'transmission': transmission}))
return tuple(output)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from opendirector.domain.video_output import apply_video_resolution
from opendirector.ports.gateway import gateway
from opendirector.integrations.http_settings import MODEL_JOB_CONTEXT
from opendirector.integrations.fasth3 import video_parameters
from opendirector.integrations.fasth3 import control_parameters, video_parameters
from opendirector.integrations.vllm_omni import FPS, video_frame_parameters
from opendirector.integrations.model_adapters import capabilities_of
from opendirector.integrations.providers import GenerationProviders
Expand Down Expand Up @@ -200,14 +200,19 @@ def _parameters(self, spec, config, node, records):
else:
params.pop('generate_audio', None)
seconds = intent.get('durationSeconds')
if rules['profile'] == 'fasth3-omni':
control = rules['profile'] == 'fasth3-omni' and node.get('videoMode') == 'control'
if control:
params = control_parameters(node, records, resolution=str(intent.get('resolution', 'auto')).upper())
params['seed'] = new_seed()
seconds = None # The control video sets the length.
elif rules['profile'] == 'fasth3-omni':
params = video_parameters(node, records, duration_seconds=seconds)
if config.get('videoAdapter') == 'fasth3_dual' and node.get('videoMode') == 'first_frame':
params['num_inference_steps'] = 20
params['seed'] = new_seed()
elif rules['profile'] == 'standard-video':
params = {}
if seconds is None and config.get('videoCapabilities'):
if seconds is None and config.get('videoCapabilities') and not control:
seconds = rules['videoCapabilities']['defaultDuration']
if seconds is not None:
params['duration'] = seconds
Expand All @@ -223,7 +228,9 @@ def _parameters(self, spec, config, node, records):
raise ProjectError('指定视频比例前,请在模型接入中配置输出规格。', 422)
preferred = next((item for item in choices if item['resolution'] == caps.get('defaultResolution')), choices[0])
output['resolution'] = preferred['resolution']
if config['protocol'] == 'minimax_video_v2':
if control:
pass # Size and frames already follow the control video.
elif config['protocol'] == 'minimax_video_v2':
params['resolution'] = (intent.get('resolution') if intent.get('resolution') != 'auto' else None) or rules['videoCapabilities']['defaultResolution']
has_frames = node['videoMode'] == 'first_frame' and any(records[key]['kind'] == 'image' for key in node['referenceIds'])
if has_frames:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def publish_media(service, data, payload):
expected, allowed = 'video', {'audio'}
if not actual.metadata.hasAudio:
raise ContractError('invalid_input', '来源视频没有可提取的音轨。', actual.id)
elif tool in {'video-depth-capture', 'video-extend', 'video-partial-reshoot', 'video-trim', 'video-crop', 'video-edit', 'video-upscale', 'video-frame-interpolation', 'video-subtitle-erasure', 'video-matting', 'video-translation'}:
elif tool in {'video-depth-capture', 'video-extend', 'video-partial-reshoot', 'video-trim', 'video-crop', 'video-edit', 'video-upscale', 'video-frame-interpolation', 'video-subtitle-erasure', 'video-matting', 'video-translation', 'video-mask-composite'}:
expected, allowed = 'video', {'video'}
elif tool in {'audio-trim', 'audio-separation'}:
expected, allowed = ('video' if tool == 'audio-separation' and actual.kind == 'video' else 'audio'), {'audio'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
)
from opendirector.application.tool_image_segments import cutout, layer_decompose, select_image_objects
from opendirector.application.tool_video_recipes import (
AUDIO_MODES, audio_separation, depth_capture, frame_interpolation, partial_reshoot,
AUDIO_MODES, audio_separation, depth_capture, mask_composite, frame_interpolation, partial_reshoot,
subtitle_erasure, video_edit, video_matting, video_upscale,
)

Expand Down Expand Up @@ -84,7 +84,11 @@ def _select(key, label, options, default=None, required=True):
note='智能拆分识别人物、动物、车辆、商品等常见对象;按描述拆分可写多个对象,用逗号分隔。'
'接入图片编辑模型时会补全背景。'),
ToolSpec('video-matting', ('video',), _needs('video.matting'), video_matting,
note='按描述跟踪对象(默认人物),多个对象用逗号分隔;透明背景输出带透明通道的 WebM。'),
note='按描述跟踪对象(默认人物),多个对象用逗号分隔;透明背景输出带透明通道的 WebM;遮罩输出黑底白色对象。'),
# Two video sources: the content first, then its mask (e.g. depth + person mask for FastH3 结构控制).
ToolSpec('video-mask-composite', ('video',), _needs(), mask_composite,
({'key': 'stretch', 'label': '拉伸明暗范围', 'type': 'boolean', 'default': True, 'required': False},),
note='本地处理:保留内容视频在遮罩白色区域内的画面,其余变黑;可把遮罩内的明暗拉伸到完整范围(适合人物深度控制视频)。'),
ToolSpec('video-depth-capture', ('video',), _needs('video.motion_capture'), depth_capture,
note='逐帧估计景深,输出灰度深度视频(近处亮、远处暗),可作为视频生成的动作与结构参考;最长 30 秒。'),
]}
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def _write_mattes(tracks: Tracks, folder):

async def video_matting(ctx: ToolContext):
source = _source_video(ctx)
background = ctx.choice('background', ('black', 'green', 'transparent'), 'green')
background = ctx.choice('background', ('black', 'green', 'transparent', 'mask'), 'green')
pairs = await ctx.concepts(ctx.text('prompt'), ('人物',))
with media.Workspace() as work:
raw = work.write('source', source.data)
Expand All @@ -132,10 +132,86 @@ async def video_matting(ctx: ToolContext):
code='tool_no_video_match', label=label)
await ctx.progress('正在合成抠像视频')
await blocking(_write_mattes, tracks, work.path / 'mattes')
if background == 'mask':
# White where the tracked objects are, black elsewhere: an input for 遮罩合成 and other masked steps.
data = await blocking(media.encode_frames, str(work.path / 'mattes' / '%05d.png'), info['fps'], work.path / 'mask.mp4')
return [Output('video', data, 'mp4', '视频遮罩')]
data, suffix = await blocking(media.matte, clip, str(work.path / 'mattes' / '%05d.png'), info['fps'],
work.path / 'matted', background=background)
return [Output('video', data, suffix, '视频抠像')]

COMPOSITE_MAX_FRAMES = 2048

def _grow(mask: Image.Image) -> Image.Image:
"""The mask thresholded and grown by about four pixels, so hair and loose clothing edges stay inside."""
return mask.point(lambda value: 255 if value > 127 else 0).filter(ImageFilter.GaussianBlur(3)).point(
lambda value: 255 if value > 16 else 0)

def composite_frames(content: list, masks: list, folder, *, stretch: bool) -> int:
"""content inside the mask (white in masks), black elsewhere; returns the frame count.

With stretch, brightness inside the mask is spread over 50..255 from its own 1st..99.5th percentile,
so a person's depth uses the full control range and stays distinct from the black background.
"""
count = min(len(content), len(masks))
if not count:
raise ProjectError('视频中没有可合成的画面。', 422)
curve = list(range(256))
if stretch:
histogram = [0] * 256
for index in range(0, count, max(1, count // 48)):
picture = Image.open(content[index]).convert('L')
mask = _grow(Image.open(masks[index]).convert('L').resize(picture.size))
histogram = [a + b for a, b in zip(histogram, picture.histogram(mask))]
total = sum(histogram)
if not total:
raise ProjectError('遮罩视频中没有白色区域,请检查遮罩。', 422)
def percentile(share):
running = 0
for value, number in enumerate(histogram):
running += number
if running >= share * total:
return value
return 255
low, high = percentile(0.01), percentile(0.995)
span = max(high - low, 1)
curve = [round(50 + 205 * min(max((value - low) / span, 0.0), 1.0)) for value in range(256)]
folder.mkdir()
for index in range(count):
picture = Image.open(content[index]).convert('RGB')
frame = Image.new('RGB', picture.size, 0)
frame.paste(picture.point(curve * 3), mask=_grow(Image.open(masks[index]).convert('L').resize(picture.size)))
frame.save(folder / f'{index:05d}.png', compress_level=1)
return count

async def mask_composite(ctx: ToolContext):
if len(ctx.sources) != 2 or any(source.kind != 'video' for source in ctx.sources):
raise ProjectError('遮罩合成需要两个视频:先选内容视频(例如深度视频),再选遮罩视频。', 422)
stretch = ctx.parameters.get('stretch', True)
if not isinstance(stretch, bool):
raise ProjectError('参数 stretch 无效。', 422)
content, mask = ctx.sources
with media.Workspace() as work:
raw = work.write('content', content.data)
info = await blocking(media.video_info, raw)
if info['duration'] * info['fps'] > COMPOSITE_MAX_FRAMES:
raise ProjectError(f'遮罩合成单次最多处理 {COMPOSITE_MAX_FRAMES} 帧,请先裁剪视频。', 422)
mask_raw = work.write('mask', mask.data)
mask_info = await blocking(media.video_info, mask_raw)
# Frames are paired by index, so the mask must share the content's timeline
# (e.g. both made from the same source clip); otherwise the mask drifts silently.
if abs(mask_info['fps'] - info['fps']) > 0.01:
raise ProjectError('遮罩视频与内容视频的帧率不一致,请使用由同一段视频生成的遮罩。', 422)
await ctx.progress('正在读取画面和遮罩')
frames = await blocking(media.frames_of, raw, work.path / 'content-frames')
mattes = await blocking(media.frames_of, mask_raw, work.path / 'mask-frames', gray=True)
if abs(len(frames) - len(mattes)) > 1:
raise ProjectError('遮罩视频与内容视频的帧数不一致,请使用由同一段视频生成的遮罩。', 422)
await ctx.progress('正在合成')
await blocking(composite_frames, frames, mattes, work.path / 'composite', stretch=stretch)
data = await blocking(media.encode_frames, str(work.path / 'composite' / '%05d.png'), info['fps'], work.path / 'composite.mp4')
return [Output('video', data, 'mp4', '遮罩合成')]

DEPTH_MAX_SECONDS = 30

DEPTH_MAX_FRAMES = 2048
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',
'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage']
'video-mask-composite', 'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage']


class ToolDraftBinding(Contract):
Expand Down
24 changes: 19 additions & 5 deletions packages/core/src/opendirector/domain/creation/generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from opendirector.domain.generation import GenerationFailure, ResultCheck
from opendirector.domain.projects import ProjectError
from opendirector.domain.rule_facts import (
FASTH3_MEDIA_REFERENCE_LIMIT, FRAME_IMAGE_LIMIT, LYRICS_MAX_LENGTH, MAX_REFERENCES,
CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, FRAME_IMAGE_LIMIT, LYRICS_MAX_LENGTH, MAX_REFERENCES,
MUSIC_SECONDS_INITIAL, MUSIC_SECONDS_MAX, MUSIC_SECONDS_MIN, PROMPT_MAX_LENGTH,
REFERENCE_MEDIA_SECONDS, STORED_VOICE_PATTERN, TEXT_DEFAULT_MAX_TOKENS, TEXT_MAX_TOKENS,
duration_matches, effective_video_mode, generate_audio_options,
Expand Down Expand Up @@ -154,7 +154,7 @@ class FollowingSource(Contract):

class ReferenceBase(ProjectEntity):
targetSpecId: UUID = Field(description='Target generation configuration ID.')
role: Literal['reference', 'first_frame', 'last_frame', 'continuation'] = Field(default='reference', description='Business role of this binding or reference.')
role: Literal['reference', 'first_frame', 'last_frame', 'continuation', 'control'] = Field(default='reference', description='Business role of this binding or reference.')
order: int = Field(default=0, ge=0, strict=True, description='Reference ordering within the target configuration.')
active: bool = Field(default=True, description='Whether this reference participates in generation.') # Retained tombstone prevents revision ABA on undo.

Expand Down Expand Up @@ -182,7 +182,7 @@ class FollowingReference(ReferenceBase):

class ResolvedReference(Contract):
referenceId: UUID = Field(description='Generation reference ID.')
role: Literal['reference', 'first_frame', 'last_frame', 'continuation'] = Field(description='Business role of this binding or reference.')
role: Literal['reference', 'first_frame', 'last_frame', 'continuation', 'control'] = Field(description='Business role of this binding or reference.')
asset: AssetRef = Field(description='Immutable asset version.')
metadata: MediaMetadata = Field(description='Verified media properties.')
sourceVersion: ObjectVersion | None = Field(default=None, description='Captured source object version.')
Expand Down Expand Up @@ -487,6 +487,19 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc
raise ValueError('视频续写会沿用原视频尺寸,不能修改分辨率。')
elif any(ref.role == 'continuation' for ref in references):
raise ValueError('续写参考必须使用续写模式。')
if params.videoMode == 'control':
# FastH3 + ControlNet: one structure (depth) video fixes motion and layout; images give the look.
control = [ref for ref in transmitted if ref.role == 'control']
if len(control) != 1 or control[0].asset.kind != 'video' or kinds.count('video') != 1:
raise ValueError('结构控制需要且只能连接一个控制视频(例如人物深度视频)。')
if kinds.count('audio'):
raise ValueError('结构控制模式不接受音频参考。')
seconds = control[0].metadata.durationSeconds
if seconds is None or not CONTROL_VIDEO_SECONDS[0] <= seconds <= CONTROL_VIDEO_SECONDS[1] + 0.05:
low, high = CONTROL_VIDEO_SECONDS
raise ValueError(f'控制视频需要 {low:g}–{high:g} 秒,生成时长与它一致。')
elif any(ref.role == 'control' for ref in references):
raise ValueError('控制视频必须使用结构控制模式。')
if params.videoMode == 'first_frame' and (kinds.count('image') > (FRAME_IMAGE_LIMIT if rules.frameRoles and 'last_frame' in rules.frameRoles else 1) or any(kind in {'audio', 'video'} for kind in kinds)):
raise ValueError('首帧模式最多只能连接一个图片参考和文本。')
for role in ('first_frame', 'last_frame'):
Expand All @@ -500,7 +513,8 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc
if kinds.count('audio') and not rules.audioReferenceStandalone and not (kinds.count('image') or kinds.count('video')):
raise ValueError('音频参考必须同时连接图片或视频参考。')
for kind in ('audio', 'video'):
seconds = [ref.metadata.durationSeconds for ref in transmitted if ref.asset.kind == kind]
# The control video is the output's timeline, not a reference clip; its own limit applies above.
seconds = [ref.metadata.durationSeconds for ref in transmitted if ref.asset.kind == kind and ref.role != 'control']
minimum = 2 if kind == 'audio' or rules.profile == 'minimax-h3-official' else 0
if any(value is None or value < minimum or value <= 0 for value in seconds) or sum(seconds) > REFERENCE_MEDIA_SECONDS:
label = '视频' if kind == 'video' else '音频'
Expand All @@ -512,7 +526,7 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc
if params.resolution not in choices:
raise ValueError('当前参考模式不支持该输出分辨率。')
caps = rules.videoCapabilities
if caps and params.durationSeconds is not None:
if caps and params.durationSeconds is not None and params.videoMode != 'control':
choices = [output for output in caps.outputs if params.resolution == 'auto' or output.resolution == params.resolution]
if not any(duration_matches(params.durationSeconds, output.durations, rules.fractionalDuration) for output in choices):
raise ValueError('当前时长与分辨率组合不受支持。')
2 changes: 1 addition & 1 deletion packages/core/src/opendirector/domain/creation/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

ModelKind = Literal['agent', 'image', 'video', 'audio', 'vision']
Protocol = Literal['openai', 'volcengine', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score']
VideoMode = Literal['first_frame', 'reference', 'continuation']
VideoMode = Literal['first_frame', 'reference', 'continuation', 'control']
ImageQuality = Literal['auto', 'low', 'medium', 'high']
Count = Annotated[int, Field(strict=True, ge=0)]

Expand Down
Loading
Loading