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
7 changes: 6 additions & 1 deletion docs/development/lessons.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u
- **Assistant completion follow-up:** [PR #465's browser run](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/45526547494/job/138913562926) read a saved reply while the Agent still held its write lease. The assistant panel test must wait for both the reply's final status and removal of the active turn ID. Delaying lease release reproduced the failure on the upstream baseline.

- **Shared model catalog follow-up:** [Nightly run 45309310680](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/45309310680/job/138160760923) reached the empty-video-selector test after an earlier script saved a video model. A new page still reads the shared server's catalog. For a UI test of an empty category, scope that catalog response to the test page and verify the flow with a model already present on the shared server.
- **Shared composer follow-up:** [PR #529's voice library check](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/45865822618/job/140084924197) timed out when a save refreshed the audio draft and dropped its image-only preset default. A shared panel was closed by the preset's reset effect. Scope panel resets to the state the panel owns, and exercise a save while the panel is open in another media mode.

## A pending checkpoint can race with accepted cancellation

Expand Down Expand Up @@ -114,7 +115,11 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u
- **Lesson:** A timer may run after the editor's saving flag clears but before React installs the new document. Comparing that old closure against the new baseline can turn a view-only save into a business rollback, invalidating a previously captured publication version.
- **Check:** Invalidate scheduled automatic callbacks when the editor transaction starts, drain queued saves and explicitly persist the current draft before the edit. Preserve publication CAS checks. Exercise the real due callback at the acknowledgment boundary; isolate projection-test gates by snapshot identity, assert release/restoration and always clean up. Distinguish a forced reproduction from proof of the exact CI schedule.
- **Queued-edit follow-up:** The H3 browser regression in [PR #266](https://github.com/ThinkFlowLab/OpenDirector/pull/266) holds the first import's background hydration until the second import queues an edit. A ref updated during render can still describe the old document; a late refresh then replaces both nodes with one. Track requested and rendered history writes, defer refreshes while they differ, and recheck when hydration finishes. Resume after a no-op write too. Verify both saved nodes, their bytes, and subsequent edits after reopening. / **排队编辑补充:** React 尚未显示的编辑也需要保护;后台刷新必须检查已经请求的修改,并在页面更新后继续。回归检查两张图片的保存内容及重开后的编辑,不能把人工控制的执行顺序当作原 CI 顺序的证明。

- **Preset editor follow-up:** Selecting an image preset used to queue a settings edit and a prompt-chip edit that still held the old settings. Render the chip from the saved preset and publish preset changes caused by prompt editing in the same command as the prompt. Check the saved parameters after autosave and reopening. Chrome can move the caret past a wrapped hint through native mouse-down selection. Verify the caret's rendered position after the chip with a visible multiline hint before releasing the button. Check that typing replaces the hint, retains the first character and saves only the user's text.
- **Preset submission follow-up:** Treat the selected preset as a prompt in both the button preflight and the generation service. Freeze its instructions in the accepted job, since updating only the draft's plain prompt can be ignored by structured references and can duplicate instructions on a second run. Check preset-only submission, the structured provider prompt, and adoption without modifying the draft.
- **Image preset prompt variants:** Use the resolved image inputs to choose between image-guided and text-guided instructions. Publish both variants so the preview can make the same choice from usable references. Check that enabling face emphasis and adding or removing the last image change both the preview and the submitted prompt. Keep the ordered steps of multi-shot presets in both variants.
- **Four-view cropping:** A frozen face-emphasis prompt proves the setting reached the provider, while visual compliance still requires reviewing the generated image. Put the crop before appearance guidance and scope it to the first two columns. Specify a separate scale and headroom for the full back view. Check both a text-only subject and a reference with a less obvious neck.
- **Reference medium:** Explicit photography wording corrected a photograph but turned an illustrated reference into a live-action portrait. Treat the layout as composition only and use medium-neutral framing language. Verify style changes against a photo and an illustration.

## An upstream response and a consumer finishing it are separate facts

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from opendirector.domain.creation.models import ModelConfigPublic, ModelSnapshot
from opendirector.domain.creation.project import ProjectSnapshot
from opendirector.domain.creation.validation import ContractError
from opendirector.domain.image_presets import preset_prompt
from opendirector.domain.input_rules import input_rules
from opendirector.domain.minimax_speech import is_minimax_speech
from opendirector.domain.projects import ProjectError
Expand Down Expand Up @@ -93,6 +94,15 @@ def new_seed():
return secrets.randbelow(2**31)


def transmitted_assets(references):
"""Keep the first transmitted binding for each asset, in request order."""
assets = {}
for reference in references:
if reference.transmission != 'context_only':
assets.setdefault(reference.asset.assetId, reference)
return assets


class CreationGeneration(GenerationRuntime):
def __init__(self, projects, configs, provider=None, *, availability=None):
super().__init__()
Expand All @@ -118,7 +128,7 @@ def task(self, job):
# Project accepted jobs without revalidating the current speech catalog.
profile = 'minimax-speech' if is_minimax_speech(config) else input_rules(config)['profile']
assets = {a.id: a for a in self.projects.snapshot(job.projectId).assets}
reference_ids = list(dict.fromkeys(str(r.asset.assetId) for r in job.inputSnapshot.references if r.transmission != 'context_only'))
reference_ids = [str(asset_id) for asset_id in transmitted_assets(job.inputSnapshot.references)]
content = None
kling_content = None
if spec.promptContent is not None:
Expand All @@ -138,13 +148,19 @@ def task(self, job):
content.append(rendered)
if kling_content is not None:
kling_content.append({**rendered, 'referenceId': str(ref.referenceId), 'subjectRole': ref.subjectRole})
prompt = spec.prompt
if job.inputSnapshot.presetPrompt:
prefix = job.inputSnapshot.presetPrompt
prompt = f'{prefix}\n\n{prompt}' if prompt.strip() else prefix
if content is not None:
content.insert(0, dict(type='text', text=prefix + ('\n\n' if content else '')))
adapter_content = {} if model.protocol != 'kling_video' else dict(klingPromptContent=kling_content,
klingReferences=[dict(assetId=str(r.asset.assetId), role=r.role, referenceId=str(r.referenceId), subjectRole=r.subjectRole)
for r in job.inputSnapshot.references if r.transmission != 'context_only'])
return dict(schemaVersion=1, id=str(job.id), projectId=str(job.projectId), nodeId=str(job.originItemId or spec.id),
kind=spec.kind, status=job.status, phase=job.phase, recovery=job.recovery, resumeAllowed=job.resumeAllowed,
modelConfigId=str(model.modelConfigId), model=model.modelId, baseURL=model.url, protocol=model.protocol,
title=spec.prompt[:80] or spec.kind, prompt=spec.prompt, promptContent=content, referenceIds=reference_ids,
title=spec.prompt[:80] or spec.kind, prompt=prompt, promptContent=content, referenceIds=reference_ids,
referenceRoles=[{'assetId': str(r.asset.assetId), 'role': r.role} for r in job.inputSnapshot.references if r.transmission != 'context_only'],
referenceInputs={'profile': profile},
videoMode=spec.parameters.videoMode if spec.kind == 'video' else 'first_frame', parameters=job.adapterParameters,
Expand Down Expand Up @@ -414,9 +430,15 @@ def accept(before):
if reference.transmission != 'context_only':
self.assets.reference_available(command.projectId, reference.asset.assetId)
self.provider.validate(spec.kind, config)
preset = preset_prompt(
spec.parameters.preset, spec.parameters.faceEmphasis,
tuple(reference.sourceTitle or reference.name for reference in transmitted_assets(resolved).values()
if reference.asset.kind == 'image'),
) if spec.kind == 'image' else None
snapshot = InputSnapshot(spec=spec.model_copy(update={'currentResultId': None}),
model=ModelSnapshot(modelConfigId=public.id, inputRules=public.inputRules,
**{k: getattr(public, k) for k in ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'proxyMode', 'videoAdapter')}), references=resolved)
**{k: getattr(public, k) for k in ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'proxyMode', 'videoAdapter')}),
references=resolved, presetPrompt=preset)
# Use the same rendering, protocol validation and parameter resolver
# as the established adapters, with immutable media from the facade.
stub = Job(id=uuid5(command.commandId, 'job'), projectId=command.projectId, inputSnapshot=snapshot,
Expand Down Expand Up @@ -553,7 +575,8 @@ def apply(current, asset):
projected_spec, references = current_generation_inputs(current, current_spec, current_job.inputSnapshot.model.inputRules)
effective = execution_spec(projected_spec, references, current_job.inputSnapshot.model.inputRules)
now = InputSnapshot(spec=effective.model_copy(update={'purpose': 'generation', 'currentResultId': None}),
model=current_job.inputSnapshot.model, references=references)
model=current_job.inputSnapshot.model, references=references,
presetPrompt=current_job.inputSnapshot.presetPrompt)
eligible = eligible and now.fingerprint() == current_job.inputFingerprint
except (ValueError, ContractError):
eligible = False
Expand Down
65 changes: 3 additions & 62 deletions packages/core/src/opendirector/application/tool_image_edits.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""Image edit recipes: reframing, cleanup, presets, and poster motion."""
import json
from dataclasses import dataclass

from PIL import Image

from opendirector.application.tool_context import Output, ToolContext, _source_image, _with, image_output
from opendirector.domain.image_presets import PRESETS, preset_instructions
from opendirector.domain.projects import ProjectError
from opendirector.media import processing as media

Expand Down Expand Up @@ -168,71 +168,12 @@ async def panorama(ctx: ToolContext):
edge = {'4K': 4096, '2K': 2048}.get(ctx.parameters.get('resolution'), 2048)
return [image_output(media.resize(result, edge, edge // 2), '720 全景')]

@dataclass(frozen=True)
class ImagePreset:
title: str
prompts: tuple[str, ...]
size: tuple[int, int] = (2048, 1152)

PRESETS = {
# Written as edit instructions: editing models follow imperatives, not captions.
'three-view': ImagePreset('人物三视图', (
'以参考图中的人物为唯一身份依据,生成同一人物的全身三视图设定板。'
'横版画面分为三个等宽区域,从左至右严格排列:正面全身、右侧90度全身、背面全身。'
'三个视图保持同一身份、年龄、体型、头身比、发型、服装、配色、材质及配饰,衣服结构与细节相互对应。'
'全部自然站立、双臂放松,同一高度与地面基线,完整呈现头顶到鞋底,不裁头、不切脚、不遮挡、不重叠。'
'若原图仅有半身,依据可见服装合理补全下半身,补全部分在三个视角保持一致。'
'保持参考图画风,纯净浅灰背景、均匀柔光、弱透视,无剧情场景、文字、标签、水印、分割线或额外视图。',)),
'four-view': ImagePreset('人物四视图', (
'根据参考图生成一张同一人物的横版四视图设定板。'
'从左到右依次为正面全身、右侧90度全身、背面全身、正脸特写,四个视图并排分开。'
'前三格自然站立,头顶到鞋底完整,同一比例与地面基线;最右格只展示正面头肩,清楚呈现正脸。'
'各视图保持同一人物、发型、服装和配饰。若参考图只展示半身,合理补全下半身并保持一致。'
'保持参考图画风、浅灰背景、均匀柔光,无文字、分割线、水印或额外视图。',), (3456, 1152)),
'face-three-view': ImagePreset('面部三视图', (
'以参考图人物的面部为唯一身份依据,生成同一人物的面部三视图参考板。'
'3:1超宽横版画面均分为三个等宽区域,从左至右严格排列:正面、左侧90度、右侧90度。'
'第二格(左侧90度)鼻尖朝向画面右方,第三格(右侧90度)鼻尖朝向画面左方;'
'两张侧脸朝向相反、左右镜像对称,不要输出两张朝向相同的侧脸。'
'每个区域只放一个居中的头肩像,三个头像之间留有自然间隔,不接触、不重叠、不粘连。'
'每个视图只呈现完整头部至肩颈,头顶、下巴、耳朵均完整,不出现背面或全身视图。'
'保持同一身份、年龄、脸型、骨相、五官比例、肤色、发际线、发型及识别性细节,左右侧面符合真实结构。'
'三个头部大小一致、眼睛基线对齐、中性表情、视线随朝向自然变化,面部不被头发遮挡。'
'保持参考图画风、纯净浅灰背景、均匀柔光,无美颜改脸、夸张透视、文字、标签、水印或额外人物。',), (3456, 1152)),
'product-three-view': ImagePreset('产品三视图', (
'以参考图中的产品为唯一设计依据,生成同一产品的工业设计三视图参考板。'
'横版画面分为三个等宽区域,从左至右严格排列:正视图、右侧90度侧视图、后视图。'
'采用近正交投影、无广角畸变,同一比例尺、同一高度与底部基线,完整展示产品外轮廓,不裁切、不重叠。'
'三个视图保持结构、尺寸关系、材质、颜色、表面纹理、接口、按钮、接缝及标识一致,细节在视角之间符合物理对应关系。'
'不可见部位依据已知结构作合理且一致的补全,不增加功能件或改变产品设计。'
'产品独立展示,纯白背景、均匀棚拍光,无人物、手、包装道具、剧情场景、说明文字、尺寸标注、水印或额外视图;保留原有品牌标识。',)),
'storyboard': ImagePreset('连续分镜图', ('把镜头拉远成远景建立镜头,完整交代周围环境,主体在画面中较小',
'改为中景镜头,主体占画面一半高度,动作清晰',
'改为近景镜头,镜头推近到主体胸口以上,突出表情',
'改为特写镜头,只拍主体面部或关键细节,背景虚化')),
'multi-camera': ImagePreset('多机位', ('把机位移到主体正前方,平视拍摄',
'把机位向左绕到主体左前方约45度,从左侧斜角拍摄,透视随之改变',
'把机位向右绕到主体右前方约45度,从右侧斜角拍摄,透视随之改变',
'把机位升高到主体上方,高角度俯拍')),
}

FOUR_VIEW_FACE_EMPHASIS = (
'根据参考图生成同一人物的横版四格设定板,四张独立取景的照片从左到右并排。'
'第一格为正面、第二格为右侧90度。两格都降低取景范围,画框上缘正好切在下巴下沿,'
'脖子从顶边进入画面,从颈部一直拍到鞋底;下巴以上完全在画框外。'
'前两格顶边紧贴颈部,不在颈部上方留空;保持平直透视,不仰拍,不用面罩。'
'第三格拍完整的背面全身,从头顶到鞋底。第四格拍清晰的正脸头肩特写,保留参考人物的完整五官。'
'保持同一人物、体型、发型、服装、配饰和参考图画风。若参考图只展示半身,合理补全下半身并保持一致。'
'浅灰背景、均匀柔光,无文字、分割线、水印或额外视图。'
)

async def image_presets(ctx: ToolContext):
image = _source_image(ctx)
key = ctx.choice('preset', PRESETS)
preset = PRESETS[key]
title, prompts = preset.title, preset.prompts
if key == 'four-view' and ctx.parameters.get('faceEmphasis') is True:
prompts = (FOUR_VIEW_FACE_EMPHASIS,)
title = preset.title
prompts = preset_instructions(key, ctx.parameters.get('faceEmphasis') is True)
outputs = []
for index, instruction in enumerate(prompts, 1):
await ctx.progress(f'正在生成{title}({index}/{len(prompts)})')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def image_execution(tool, parameters, source, *, has_mask, has_annotation, polic
edge = {'4K': 4096, '2K': 2048}.get(parameters.get('resolution'), 2048)
candidate = (width, height) != original and (width, height) == (edge, edge // 2)
elif tool == 'image-presets':
from opendirector.application.tool_image_edits import PRESETS
from opendirector.domain.image_presets import PRESETS
preset = PRESETS.get(parameters.get('preset'))
if preset is not None:
width, height = preset.size
Expand Down
Loading
Loading