setShotBreakdownNode(null)}
+ />
+ )}
{activeAction && actionNode && (
<>
;
}
+export interface BreakdownShotInput extends ContractInput {
+ readonly id: string;
+ readonly measured: MeasuredShotInput;
+ readonly frameSuggestion?: ShotFrameSuggestionInput | null;
+ readonly edit: ShotEditInput;
+}
+
export interface CameraFrameInput extends ContractInput {
readonly id: string;
readonly time: number;
@@ -358,7 +365,7 @@ export interface CanvasPublishMediaInput extends ContractInput {
readonly itemId: string;
readonly source?: AssetRefInput | null;
readonly sourceEditorId?: string | null;
- readonly document: TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput;
+ readonly document: TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput | ShotBreakdownDocumentInput;
readonly outputs: ReadonlyArray
;
}
@@ -483,7 +490,7 @@ export interface ContractInput {
}
export interface ContractIssueInput extends ContractInput {
- readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota";
+ readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "shot_evidence_immutable";
readonly message: string;
readonly objectId?: string | null;
readonly field?: string | null;
@@ -495,7 +502,7 @@ export interface CreationContractsInput extends ContractInput {
readonly canvasItem: TextCanvasItemInput | ImageCanvasItemInput | VideoCanvasItemInput | AudioCanvasItemInput | FileCanvasItemInput | SubjectCanvasItemInput | TimelineCanvasItemInput | StackCanvasItemInput | ToolCanvasItemInput | DirectorCanvasItemInput | GroupCanvasItemInput;
readonly generationSpec: TextGenerationSpecInput | ImageGenerationSpecInput | VideoGenerationSpecInput | AudioGenerationSpecInput;
readonly reference: PinnedReferenceInput | FollowingReferenceInput;
- readonly editorDocument: TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput;
+ readonly editorDocument: TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput | ShotBreakdownDocumentInput;
readonly command: ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | GroupSavePlanCommandInput | GroupPublishRunCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasLayoutRunsCommandInput | CanvasLayoutPipelinesCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | PipelineStartCommandInput | PipelinePauseCommandInput | PipelineResumeCommandInput | PipelineCancelCommandInput | PipelineRetryCommandInput | PipelineAdoptCommandInput | NodeVersionApplyCommandInput | CanvasConfigureCommandInput | CanvasEditorAttachCommandInput | CanvasEditorDetachCommandInput | SpecCreateCommandInput | SpecUpdateCommandInput | SpecRestoreCommandInput | SpecPromptCommandInput | ReferenceAddCommandInput | ReferenceUpdateCommandInput | ReferenceRestoreCommandInput | ReferenceRemoveCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput;
readonly receipt: CommandReceiptInput;
readonly query: ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | JobStatusQueryInput | AssetPreviewQueryInput | PipelinePlanQueryInput | PipelineExecutionQueryInput | PipelineExecutionsQueryInput;
@@ -584,7 +591,7 @@ export interface EditorSaveCommandOperationInput {
}
export interface EditorWriteInput extends ContractInput {
- readonly document: TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput;
+ readonly document: TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput | ShotBreakdownDocumentInput;
}
export interface EmptyBindingInput extends ContractInput {
@@ -932,6 +939,13 @@ export interface MaterialBindingInput extends ContractInput {
readonly objectRef: AssetRefInput;
}
+export interface MeasuredShotInput extends ContractInput {
+ readonly startPts: number;
+ readonly endPts: number;
+ readonly representativePts: number;
+ readonly representative: AssetRefInput;
+}
+
export interface MediaCanvasItemInput extends CanvasItemBaseInput {
readonly binding: EmptyBindingInput | MaterialBindingInput | GenerationBindingInput;
readonly editors?: ReadonlyArray;
@@ -1250,7 +1264,7 @@ export interface ProjectSnapshotInput extends ContractInput {
readonly generationSpecs?: ReadonlyArray;
readonly references?: ReadonlyArray;
readonly canvasItems?: ReadonlyArray;
- readonly editorDocuments?: ReadonlyArray;
+ readonly editorDocuments?: ReadonlyArray;
readonly jobs?: ReadonlyArray;
readonly results?: ReadonlyArray;
readonly eventCursor?: number;
@@ -1423,6 +1437,33 @@ export interface SelectionPipelineScopeInput extends ContractInput {
readonly itemIds: ReadonlyArray;
}
+export interface ShotBreakdownDataInput extends ContractInput {
+ readonly source: AssetRefInput;
+ readonly timeBase: string;
+ readonly originPts: number;
+ readonly durationPts: number;
+ readonly shots: ReadonlyArray;
+}
+
+export interface ShotBreakdownDocumentInput extends EditorDocumentBaseInput {
+ readonly kind: "shot_breakdown";
+ readonly data: ShotBreakdownDataInput;
+}
+
+export interface ShotEditInput extends ContractInput {
+ readonly startPts: number;
+ readonly endPts: number;
+ readonly description?: string;
+ readonly joinPrevious?: boolean;
+}
+
+export interface ShotFrameSuggestionInput extends ContractInput {
+ readonly modelId: string;
+ readonly subject: string;
+ readonly scene: string;
+ readonly framing: string;
+}
+
export interface SpecCreateCommandInput extends CommandBaseInput {
readonly type: "generationSpec.create";
readonly payload: SpecWriteInput;
@@ -1879,7 +1920,7 @@ export type GenerationSpecInput = TextGenerationSpecInput | ImageGenerationSpecI
export type ReferenceInput = PinnedReferenceInput | FollowingReferenceInput;
-export type EditorDocumentInput = TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput;
+export type EditorDocumentInput = TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput | ShotBreakdownDocumentInput;
export type CommandInput = ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | GroupSavePlanCommandInput | GroupPublishRunCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasLayoutRunsCommandInput | CanvasLayoutPipelinesCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | PipelineStartCommandInput | PipelinePauseCommandInput | PipelineResumeCommandInput | PipelineCancelCommandInput | PipelineRetryCommandInput | PipelineAdoptCommandInput | NodeVersionApplyCommandInput | CanvasConfigureCommandInput | CanvasEditorAttachCommandInput | CanvasEditorDetachCommandInput | SpecCreateCommandInput | SpecUpdateCommandInput | SpecRestoreCommandInput | SpecPromptCommandInput | ReferenceAddCommandInput | ReferenceUpdateCommandInput | ReferenceRestoreCommandInput | ReferenceRemoveCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput;
@@ -2048,6 +2089,13 @@ export interface BatchPayload extends Contract {
readonly operations: ReadonlyArray;
}
+export interface BreakdownShot extends Contract {
+ readonly id: string;
+ readonly measured: MeasuredShot;
+ readonly frameSuggestion: ShotFrameSuggestion | null;
+ readonly edit: ShotEdit;
+}
+
export interface CameraFrame extends Contract {
readonly id: string;
readonly time: number;
@@ -2251,7 +2299,7 @@ export interface CanvasPublishMedia extends Contract {
readonly itemId: string;
readonly source: AssetRef | null;
readonly sourceEditorId: string | null;
- readonly document: TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument;
+ readonly document: TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument | ShotBreakdownDocument;
readonly outputs: ReadonlyArray;
}
@@ -2376,7 +2424,7 @@ export interface Contract {
}
export interface ContractIssue extends Contract {
- readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota";
+ readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "shot_evidence_immutable";
readonly message: string;
readonly objectId: string | null;
readonly field: string | null;
@@ -2388,7 +2436,7 @@ export interface CreationContracts extends Contract {
readonly canvasItem: TextCanvasItem | ImageCanvasItem | VideoCanvasItem | AudioCanvasItem | FileCanvasItem | SubjectCanvasItem | TimelineCanvasItem | StackCanvasItem | ToolCanvasItem | DirectorCanvasItem | GroupCanvasItem;
readonly generationSpec: TextGenerationSpec | ImageGenerationSpec | VideoGenerationSpec | AudioGenerationSpec;
readonly reference: PinnedReference | FollowingReference;
- readonly editorDocument: TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument;
+ readonly editorDocument: TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument | ShotBreakdownDocument;
readonly command: ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | GroupSavePlanCommand | GroupPublishRunCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasLayoutRunsCommand | CanvasLayoutPipelinesCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | PipelineStartCommand | PipelinePauseCommand | PipelineResumeCommand | PipelineCancelCommand | PipelineRetryCommand | PipelineAdoptCommand | NodeVersionApplyCommand | CanvasConfigureCommand | CanvasEditorAttachCommand | CanvasEditorDetachCommand | SpecCreateCommand | SpecUpdateCommand | SpecRestoreCommand | SpecPromptCommand | ReferenceAddCommand | ReferenceUpdateCommand | ReferenceRestoreCommand | ReferenceRemoveCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand;
readonly receipt: CommandReceipt;
readonly query: ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | JobStatusQuery | AssetPreviewQuery | PipelinePlanQuery | PipelineExecutionQuery | PipelineExecutionsQuery;
@@ -2477,7 +2525,7 @@ export interface EditorSaveCommandOperation {
}
export interface EditorWrite extends Contract {
- readonly document: TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument;
+ readonly document: TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument | ShotBreakdownDocument;
}
export interface EmptyBinding extends Contract {
@@ -2825,6 +2873,13 @@ export interface MaterialBinding extends Contract {
readonly objectRef: AssetRef;
}
+export interface MeasuredShot extends Contract {
+ readonly startPts: number;
+ readonly endPts: number;
+ readonly representativePts: number;
+ readonly representative: AssetRef;
+}
+
export interface MediaCanvasItem extends CanvasItemBase {
readonly binding: EmptyBinding | MaterialBinding | GenerationBinding;
readonly editors: ReadonlyArray;
@@ -3142,7 +3197,7 @@ export interface ProjectSnapshot extends Contract {
readonly generationSpecs: ReadonlyArray;
readonly references: ReadonlyArray;
readonly canvasItems: ReadonlyArray;
- readonly editorDocuments: ReadonlyArray;
+ readonly editorDocuments: ReadonlyArray;
readonly jobs: ReadonlyArray;
readonly results: ReadonlyArray;
readonly eventCursor: number;
@@ -3315,6 +3370,33 @@ export interface SelectionPipelineScope extends Contract {
readonly itemIds: ReadonlyArray;
}
+export interface ShotBreakdownData extends Contract {
+ readonly source: AssetRef;
+ readonly timeBase: string;
+ readonly originPts: number;
+ readonly durationPts: number;
+ readonly shots: ReadonlyArray;
+}
+
+export interface ShotBreakdownDocument extends EditorDocumentBase {
+ readonly kind: "shot_breakdown";
+ readonly data: ShotBreakdownData;
+}
+
+export interface ShotEdit extends Contract {
+ readonly startPts: number;
+ readonly endPts: number;
+ readonly description: string;
+ readonly joinPrevious?: boolean;
+}
+
+export interface ShotFrameSuggestion extends Contract {
+ readonly modelId: string;
+ readonly subject: string;
+ readonly scene: string;
+ readonly framing: string;
+}
+
export interface SpecCreateCommand extends CommandBase {
readonly type: "generationSpec.create";
readonly payload: SpecWrite;
@@ -3771,7 +3853,7 @@ export type GenerationSpec = TextGenerationSpec | ImageGenerationSpec | VideoGen
export type Reference = PinnedReference | FollowingReference;
-export type EditorDocument = TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument;
+export type EditorDocument = TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument | ShotBreakdownDocument;
export type Command = ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | GroupSavePlanCommand | GroupPublishRunCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasLayoutRunsCommand | CanvasLayoutPipelinesCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | PipelineStartCommand | PipelinePauseCommand | PipelineResumeCommand | PipelineCancelCommand | PipelineRetryCommand | PipelineAdoptCommand | NodeVersionApplyCommand | CanvasConfigureCommand | CanvasEditorAttachCommand | CanvasEditorDetachCommand | SpecCreateCommand | SpecUpdateCommand | SpecRestoreCommand | SpecPromptCommand | ReferenceAddCommand | ReferenceUpdateCommand | ReferenceRestoreCommand | ReferenceRemoveCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand;
diff --git a/src/i18n/messages/en-US/editors.ts b/src/i18n/messages/en-US/editors.ts
index ccab55bc8..a5d9416bd 100644
--- a/src/i18n/messages/en-US/editors.ts
+++ b/src/i18n/messages/en-US/editors.ts
@@ -392,4 +392,111 @@ export const editors = {
"editors.stage.ui.startSeconds": "Start (s)",
"editors.stage.ui.durationSeconds": "Duration (s)",
"editors.stage.ui.previewSuffix": "preview",
+
+ "editors.shotBreakdown.open": "Shot breakdown",
+ "editors.shotBreakdown.title": "Shot breakdown · {title}",
+ "editors.shotBreakdown.subtitle":
+ "Measured cuts, representative frames, and an editable shot draft. Detection and model suggestions are separate from your edits.",
+ "editors.shotBreakdown.startAria": "Start shot analysis",
+ "editors.shotBreakdown.empty.title": "No shot breakdown yet",
+ "editors.shotBreakdown.empty.body":
+ "Analyze a project video to detect cuts and representative frames. Detection runs on the local CPU; no model is called by default.",
+ "editors.shotBreakdown.model.label": "Frame suggestion model (optional)",
+ "editors.shotBreakdown.model.aria": "Frame suggestion model",
+ "editors.shotBreakdown.model.detectionOnly": "Detection only · no model",
+ "editors.shotBreakdown.model.defaultHint":
+ "Only cut detection runs. No frame is sent to a model.",
+ "editors.shotBreakdown.model.selectedHint":
+ "The selected model receives one representative JPEG per shot and returns a single-frame suggestion. Detection remains the measured source of truth.",
+ "editors.shotBreakdown.analyze": "Analyze shots",
+ "editors.shotBreakdown.analyzeAria": "Analyze shots",
+ "editors.shotBreakdown.analyzing": "Analyzing…",
+ "editors.shotBreakdown.reload": "Reload",
+ "editors.shotBreakdown.reloadAria": "Reload breakdown",
+ "editors.shotBreakdown.save": "Save breakdown",
+ "editors.shotBreakdown.summary.shots": "{count} shots",
+ "editors.shotBreakdown.summary.draftShots": {
+ one: "{count} draft shot",
+ other: "{count} draft shots",
+ },
+ "editors.shotBreakdown.summary.duration": "Duration",
+ "editors.shotBreakdown.summary.timeBase": "Time base",
+ "editors.shotBreakdown.badge.detected": "Detected",
+ "editors.shotBreakdown.badge.model": "Model suggestion",
+ "editors.shotBreakdown.badge.draft": "Draft",
+ "editors.shotBreakdown.badge.joined": "Cut removed",
+ "editors.shotBreakdown.videoAria": "Source video",
+ "editors.shotBreakdown.videoUnavailable": "The source video is unavailable.",
+ "editors.shotBreakdown.playhead": "Playhead {seconds} s",
+ "editors.shotBreakdown.listAria": "Detected shots",
+ "editors.shotBreakdown.detailAria": "Shot {number} details",
+ "editors.shotBreakdown.detailHint":
+ "Locate the detected or draft start and end in the same video.",
+ "editors.shotBreakdown.shotAria": "Select shot {number}",
+ "editors.shotBreakdown.shotNumber": "Shot {number}",
+ "editors.shotBreakdown.representativeAria":
+ "Shot {number} representative frame",
+ "editors.shotBreakdown.measured.title": "Detected interval",
+ "editors.shotBreakdown.measured.start": "Detected start",
+ "editors.shotBreakdown.measured.end": "Detected end",
+ "editors.shotBreakdown.measured.representative": "Representative frame",
+ "editors.shotBreakdown.locate.measuredStart": "Detected start",
+ "editors.shotBreakdown.locate.measuredStartAria": "Go to detected start",
+ "editors.shotBreakdown.locate.measuredEnd": "Detected end",
+ "editors.shotBreakdown.locate.measuredEndAria": "Go to detected end",
+ "editors.shotBreakdown.locate.representative": "Representative frame",
+ "editors.shotBreakdown.locate.representativeAria":
+ "Go to representative frame",
+ "editors.shotBreakdown.suggestion.title": "Model suggestion · {model}",
+ "editors.shotBreakdown.suggestion.titleEmpty": "Model suggestion",
+ "editors.shotBreakdown.suggestion.note":
+ "Model inference about this single frame, not a detected fact or your edit.",
+ "editors.shotBreakdown.suggestion.subject": "Subject",
+ "editors.shotBreakdown.suggestion.scene": "Scene",
+ "editors.shotBreakdown.suggestion.framing": "Framing",
+ "editors.shotBreakdown.suggestion.empty":
+ "This shot has no model suggestion. Detection remains available.",
+ "editors.shotBreakdown.edit.title": "Shot draft",
+ "editors.shotBreakdown.edit.joinPrevious": "Join previous shot",
+ "editors.shotBreakdown.edit.restoreCut": "Restore cut",
+ "editors.shotBreakdown.edit.joinHint": "Align this start with the previous draft end to join them.",
+ "editors.shotBreakdown.edit.joinedRange": "Joined shots {first}–{last} · {start}–{end}",
+ "editors.shotBreakdown.edit.start": "Draft start (PTS)",
+ "editors.shotBreakdown.edit.startAria": "Shot {number} draft start PTS",
+ "editors.shotBreakdown.edit.end": "Draft end (PTS)",
+ "editors.shotBreakdown.edit.endAria": "Shot {number} draft end PTS",
+ "editors.shotBreakdown.edit.description": "Description",
+ "editors.shotBreakdown.edit.descriptionAria": "Shot {number} description",
+ "editors.shotBreakdown.edit.reset": "Use detected range",
+ "editors.shotBreakdown.edit.resetAria": "Use the detected range",
+ "editors.shotBreakdown.edit.note":
+ "Draft changes are kept while you switch shots. They are saved only when you choose Save breakdown.",
+ "editors.shotBreakdown.locate.editStart": "Draft start",
+ "editors.shotBreakdown.locate.editStartAria": "Go to draft start",
+ "editors.shotBreakdown.locate.editEnd": "Draft end",
+ "editors.shotBreakdown.locate.editEndAria": "Go to draft end",
+ "editors.shotBreakdown.durationLabel": "Total duration (PTS)",
+ "editors.shotBreakdown.durationAria": "Total duration PTS",
+ "editors.shotBreakdown.notice.analyzed": "Shots detected and saved.",
+ "editors.shotBreakdown.notice.partial":
+ "Shots saved. The model completed {described} of {total} descriptions. You can edit every shot.",
+ "editors.shotBreakdown.notice.reloaded": "Loaded the latest saved breakdown.",
+ "editors.shotBreakdown.notice.empty": "No saved breakdown exists now.",
+ "editors.shotBreakdown.notice.saved": "Shot breakdown saved.",
+ "editors.shotBreakdown.notice.draft":
+ "Draft changed. Save breakdown to keep it.",
+ "editors.shotBreakdown.conflict":
+ "The saved version changed. Your draft is kept; choose Reload only when you want the server version.",
+ "editors.shotBreakdown.discardReload":
+ "Discard your unsaved changes and load the latest saved breakdown?",
+ "editors.shotBreakdown.discardClose":
+ "Discard your unsaved changes and close the breakdown?",
+ "editors.shotBreakdown.error.load":
+ "Could not read the shot breakdown: {reason}",
+ "editors.shotBreakdown.error.analyze":
+ "Could not analyze the video: {reason}",
+ "editors.shotBreakdown.error.save":
+ "Could not save the shot breakdown: {reason}",
+ "editors.shotBreakdown.error.interval":
+ "Shot {number} needs integer start and end PTS values within the video, and the end must be after the start.",
} as const;
diff --git a/src/i18n/messages/zh-CN/editors.ts b/src/i18n/messages/zh-CN/editors.ts
index d90be7290..b2ee8ecec 100644
--- a/src/i18n/messages/zh-CN/editors.ts
+++ b/src/i18n/messages/zh-CN/editors.ts
@@ -356,4 +356,99 @@ export const editors = {
"editors.stage.ui.startSeconds": "开始(秒)",
"editors.stage.ui.durationSeconds": "时长(秒)",
"editors.stage.ui.previewSuffix": "预演",
+
+ "editors.shotBreakdown.open": "分镜",
+ "editors.shotBreakdown.title": "分镜 · {title}",
+ "editors.shotBreakdown.subtitle":
+ "检测到的切镜、代表帧与可编辑镜头草稿。检测结果、单帧模型建议和你的编辑分别保留。",
+ "editors.shotBreakdown.startAria": "开始分镜分析",
+ "editors.shotBreakdown.empty.title": "还没有分镜",
+ "editors.shotBreakdown.empty.body":
+ "分析工程内的视频以检测切镜和代表帧。默认只在本机 CPU 运行检测,不调用模型。",
+ "editors.shotBreakdown.model.label": "单帧建议模型(可选)",
+ "editors.shotBreakdown.model.aria": "单帧建议模型",
+ "editors.shotBreakdown.model.detectionOnly": "仅检测 · 不使用模型",
+ "editors.shotBreakdown.model.defaultHint":
+ "只运行切镜检测,不向任何模型发送画面。",
+ "editors.shotBreakdown.model.selectedHint":
+ "所选模型会为每个镜头接收一张代表帧 JPEG,并返回单帧建议。检测结果仍是实际测量的依据。",
+ "editors.shotBreakdown.analyze": "分析分镜",
+ "editors.shotBreakdown.analyzeAria": "分析分镜",
+ "editors.shotBreakdown.analyzing": "正在分析…",
+ "editors.shotBreakdown.reload": "重新加载",
+ "editors.shotBreakdown.reloadAria": "重新加载分镜",
+ "editors.shotBreakdown.save": "保存分镜",
+ "editors.shotBreakdown.summary.shots": "{count} 个镜头",
+ "editors.shotBreakdown.summary.draftShots": "{count} 个草稿镜头",
+ "editors.shotBreakdown.summary.duration": "总时长",
+ "editors.shotBreakdown.summary.timeBase": "时间基",
+ "editors.shotBreakdown.badge.detected": "检测结果",
+ "editors.shotBreakdown.badge.model": "模型建议",
+ "editors.shotBreakdown.badge.draft": "草稿",
+ "editors.shotBreakdown.badge.joined": "已去掉切点",
+ "editors.shotBreakdown.videoAria": "源视频",
+ "editors.shotBreakdown.videoUnavailable": "源视频当前不可用。",
+ "editors.shotBreakdown.playhead": "播放位置 {seconds} 秒",
+ "editors.shotBreakdown.listAria": "检测到的镜头",
+ "editors.shotBreakdown.detailAria": "镜头 {number} 详情",
+ "editors.shotBreakdown.detailHint": "在同一视频中定位检测或草稿的起止位置。",
+ "editors.shotBreakdown.shotAria": "选择镜头 {number}",
+ "editors.shotBreakdown.shotNumber": "镜头 {number}",
+ "editors.shotBreakdown.representativeAria": "镜头 {number} 代表帧",
+ "editors.shotBreakdown.measured.title": "检测区间",
+ "editors.shotBreakdown.measured.start": "检测起点",
+ "editors.shotBreakdown.measured.end": "检测终点",
+ "editors.shotBreakdown.measured.representative": "代表帧",
+ "editors.shotBreakdown.locate.measuredStart": "检测起点",
+ "editors.shotBreakdown.locate.measuredStartAria": "定位到检测起点",
+ "editors.shotBreakdown.locate.measuredEnd": "检测终点",
+ "editors.shotBreakdown.locate.measuredEndAria": "定位到检测终点",
+ "editors.shotBreakdown.locate.representative": "代表帧",
+ "editors.shotBreakdown.locate.representativeAria": "定位到代表帧",
+ "editors.shotBreakdown.suggestion.title": "模型建议 · {model}",
+ "editors.shotBreakdown.suggestion.titleEmpty": "模型建议",
+ "editors.shotBreakdown.suggestion.note":
+ "这是模型对该单帧的推断,不是检测事实,也不是你的编辑。",
+ "editors.shotBreakdown.suggestion.subject": "主体",
+ "editors.shotBreakdown.suggestion.scene": "场景",
+ "editors.shotBreakdown.suggestion.framing": "景别",
+ "editors.shotBreakdown.suggestion.empty":
+ "该镜头没有模型建议,检测结果仍可使用。",
+ "editors.shotBreakdown.edit.title": "镜头草稿",
+ "editors.shotBreakdown.edit.joinPrevious": "与上一镜合并",
+ "editors.shotBreakdown.edit.restoreCut": "恢复此切点",
+ "editors.shotBreakdown.edit.joinHint": "让这一镜的起点与上一镜的草稿终点对齐,就能合并。",
+ "editors.shotBreakdown.edit.joinedRange": "镜头 {first}–{last} 已合并 · {start}–{end}",
+ "editors.shotBreakdown.edit.start": "草稿起点(PTS)",
+ "editors.shotBreakdown.edit.startAria": "镜头 {number} 草稿起点 PTS",
+ "editors.shotBreakdown.edit.end": "草稿终点(PTS)",
+ "editors.shotBreakdown.edit.endAria": "镜头 {number} 草稿终点 PTS",
+ "editors.shotBreakdown.edit.description": "描述",
+ "editors.shotBreakdown.edit.descriptionAria": "镜头 {number} 描述",
+ "editors.shotBreakdown.edit.reset": "使用检测区间",
+ "editors.shotBreakdown.edit.resetAria": "使用检测区间",
+ "editors.shotBreakdown.edit.note":
+ "切换镜头不会丢失草稿;只有点击“保存分镜”才会写入工程。",
+ "editors.shotBreakdown.locate.editStart": "草稿起点",
+ "editors.shotBreakdown.locate.editStartAria": "定位到草稿起点",
+ "editors.shotBreakdown.locate.editEnd": "草稿终点",
+ "editors.shotBreakdown.locate.editEndAria": "定位到草稿终点",
+ "editors.shotBreakdown.durationLabel": "总时长(PTS)",
+ "editors.shotBreakdown.durationAria": "总时长 PTS",
+ "editors.shotBreakdown.notice.analyzed": "分镜已检测并保存。",
+ "editors.shotBreakdown.notice.partial":
+ "分镜已保存。模型完成了 {described}/{total} 条描述,每个镜头仍可编辑。",
+ "editors.shotBreakdown.notice.reloaded": "已加载最新保存的分镜。",
+ "editors.shotBreakdown.notice.empty": "当前没有已保存的分镜。",
+ "editors.shotBreakdown.notice.saved": "分镜已保存。",
+ "editors.shotBreakdown.notice.draft": "草稿已修改,保存分镜后才会写入工程。",
+ "editors.shotBreakdown.conflict":
+ "保存的版本已变化。草稿已保留;只有需要服务器版本时才选择“重新加载”。",
+ "editors.shotBreakdown.discardReload": "丢弃未保存的修改,加载最新分镜?",
+ "editors.shotBreakdown.discardClose": "丢弃未保存的修改,关闭分镜?",
+ "editors.shotBreakdown.error.load": "无法读取分镜:{reason}",
+ "editors.shotBreakdown.error.analyze": "无法分析视频:{reason}",
+ "editors.shotBreakdown.error.save": "无法保存分镜:{reason}",
+ "editors.shotBreakdown.error.interval":
+ "镜头 {number} 的起止必须是视频范围内的整数 PTS,且终点必须晚于起点。",
} as const;
diff --git a/tests/test_creation_shots.py b/tests/test_creation_shots.py
new file mode 100644
index 000000000..f3b7d5f12
--- /dev/null
+++ b/tests/test_creation_shots.py
@@ -0,0 +1,189 @@
+"""Reference-video breakdowns use the same project and command for UI and Agent."""
+import asyncio
+from copy import deepcopy
+from functools import partial
+from hashlib import sha256
+from io import BytesIO
+import json
+import subprocess
+from threading import Event
+from uuid import uuid4
+
+from fastapi.testclient import TestClient
+import httpx
+from PIL import Image
+import pytest
+
+from capabilities import requires_ffmpeg
+from opendirector.agent.tools import AgentTools
+from opendirector.application import creation_shots
+from opendirector.domain.projects import ProjectError
+from opendirector.infrastructure.creation_projects import CreationProjects
+from opendirector.infrastructure.local_projects import LocalProjects
+from opendirector.infrastructure.model_configs import ModelConfigs
+from opendirector_api.main import create_app
+
+
+@requires_ffmpeg()
+@pytest.mark.parametrize('model_failure', [None, 'rate-limit', 'malformed-content'],
+ ids=['model-ok', 'provider-429', 'bad-provider-content'])
+def test_shot_evidence_and_interleaved_user_agent_edits(tmp_path, monkeypatch, model_failure):
+ media = tmp_path / 'input.mp4'
+ subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'color=red:s=32x32:r=24:d=1',
+ '-threads', '1', '-c:v', 'mpeg4', str(media)], check=True)
+ jpg = BytesIO()
+ Image.new('RGB', (32, 32), 'red').save(jpg, 'JPEG')
+ calls = []
+
+ def scan(video, output):
+ assert video.read_bytes() == media.read_bytes()
+ calls.append(video)
+ shots = []
+ for index in range(3):
+ shot_id = f'shot-{index + 1:04d}'
+ frame = output / f'{shot_id}.jpg'
+ frame.write_bytes(jpg.getvalue())
+ start = index * 8
+ shots.append(dict(id=shot_id, startPts=start, endPts=start + 8, timeBase='1/24',
+ representative=dict(path=frame.name, pts=start + 4, timeBase='1/24')))
+ return dict(source=dict(timeBase='1/24', originPts=900, sha256=sha256(video.read_bytes()).hexdigest()), shots=shots)
+
+ requests = []
+
+ def model_response(request):
+ payload = json.loads(request.content)
+ assert payload['model'] == 'vision-fixture'
+ requests.append(payload)
+ if len(requests) == 2 and model_failure == 'rate-limit':
+ return httpx.Response(429, json={'error': {'code': 'rate_limit'}})
+ description = json.dumps(dict(subject='Red square', scene='Plain frame', framing='Full frame'))
+ content = [{'text': description}] if len(requests) == 2 and model_failure == 'malformed-content' else description
+ return httpx.Response(200, json={'choices': [{'message': {'content': content}}]})
+
+ monkeypatch.setattr(creation_shots, 'inspect_video_shots', scan)
+ monkeypatch.setattr(creation_shots, 'describe_shot_frame',
+ partial(creation_shots.describe_shot_frame, transport=httpx.MockTransport(model_response)))
+
+ project_id, session = uuid4(), str(uuid4())
+ local = LocalProjects(tmp_path / 'projects')
+ configs = ModelConfigs(local.repository)
+ model = configs.save('agent', 'https://model.test/v1', 'vision-fixture', 'test-key',
+ protocol='openai', input_modalities=['text', 'image'])
+ headers = {'X-OpenDirector-Request': '1', 'X-OpenDirector-Session': session, 'Accept-Language': 'en-US'}
+ path = f'/api/creation/projects/{project_id}'
+ with TestClient(create_app(local), headers=headers) as client:
+ def command(kind, payload, versions=(), *, status=200):
+ result = client.post(path + '/commands', json=dict(type=kind, payload=payload,
+ projectId=str(project_id), commandId=str(uuid4()), expectedVersions=versions))
+ assert result.status_code == status, result.text
+ return result.json()
+
+ def version(document):
+ return [dict(objectType='editor_document', id=document['id'], revision=document['revision'])]
+
+ assert command('project.create', dict(name='Reference shot proof'))['status'] == 'applied'
+ client.post(path + '/open').raise_for_status()
+ handle = str(uuid4())
+ uploaded = client.put(path + '/uploads/' + handle, content=media.read_bytes(), headers={
+ 'Content-Type': 'application/octet-stream', 'X-Asset-Name': 'input.mp4',
+ })
+ assert uploaded.status_code == 200, uploaded.text
+ asset = command('asset.import', dict(uploadHandle=handle, name='input.mp4', expectedKind='video'))['changed'][0]['id']
+ route = f'{path}/assets/{asset}/shot-breakdown'
+ assert client.get(route).json() is None
+ denied = client.post(route, json={}, headers={'X-OpenDirector-Session': str(uuid4())})
+ assert denied.status_code == 409 and not calls
+ created = client.post(route, json=dict(modelConfigId=model['id']))
+ assert created.status_code == 200, created.text
+ original = created.json()
+ assert original['data']['originPts'] == 900
+ assert original['data']['source']['assetId'] == asset
+ shot, *other_shots = original['data']['shots']
+ assert len(other_shots) == 2
+ assert all('joinPrevious' not in row['edit'] for row in original['data']['shots'])
+ assert shot['frameSuggestion']['modelId'] == 'vision-fixture'
+ assert all((row['frameSuggestion'] is None) == bool(model_failure) for row in other_shots)
+ assert len(requests) == (2 if model_failure else 3)
+ representative = shot['measured']['representative']['assetId']
+ assert client.get(path + '/assets/' + representative + '/content').content == jpg.getvalue()
+ deletion = client.post(path + '/asset-delete-preview', json=dict(assetIds=[asset, representative],
+ clearHistory=True))
+ deletion.raise_for_status()
+ assert deletion.json()['canDelete'] is False
+ assert [entry['used'] for entry in deletion.json()['usage']] == [True, True]
+
+ user_edit = deepcopy(original)
+ user_edit['data']['shots'][0]['edit'].update(startPts=1, endPts=7, description='User correction')
+ for index in (0, 1):
+ invalid = deepcopy(user_edit)
+ invalid['data']['shots'][index]['edit']['joinPrevious'] = True
+ command('editor.save', dict(document=invalid), version(original), status=422)
+ assert command('editor.save', dict(document=user_edit), version(original))['status'] == 'applied'
+ agent = AgentTools(CreationProjects(local), generation=None, configs=configs)
+ turn = uuid4()
+ discovered = asyncio.run(agent.execute(project_id, turn, session, 'discover-shot', 'read_project', {}, [], None))
+ current, = discovered['project']['editorDocuments']
+ assert current['data']['shots'][0]['edit']['description'] == 'User correction'
+ assert 'editor.save' in discovered['commands']
+ help_result = asyncio.run(agent.execute(project_id, turn, session, 'help-shot', 'command_schema',
+ dict(type='editor.save'), [], None))
+ assert help_result['command'] == 'editor.save'
+ agent_edit = deepcopy(current)
+ agent_edit['data']['shots'][0]['edit']['description'] += ' and Agent review'
+ agent_edit['data']['shots'][2]['edit']['joinPrevious'] = True
+ response = asyncio.run(agent.execute(project_id, turn, session, 'save-shot', 'execute_command',
+ dict(type='editor.save', payload=dict(document=agent_edit), expectedVersions=version(current)), [], None))
+ assert response['status'] == 'applied', response
+ stale = command('editor.save', dict(document=user_edit), version(original))
+ assert stale['issues'][0]['code'] == 'revision_conflict'
+ client.delete('/api/creation/sessions/' + session).raise_for_status()
+ reopened = client.post(path + '/open').json()['editorDocuments'][0]
+ updated, *remaining = reopened['data']['shots']
+ expected_remaining = deepcopy(other_shots)
+ expected_remaining[1]['edit']['joinPrevious'] = True
+ assert remaining == expected_remaining
+ assert updated['measured'] == shot['measured']
+ assert updated['frameSuggestion'] == shot['frameSuggestion']
+ assert updated['edit'] == dict(startPts=1, endPts=7, description='User correction and Agent review')
+ tampered = deepcopy(reopened)
+ tampered['data']['shots'][0]['frameSuggestion']['subject'] = 'Overwritten'
+ rejected = command('editor.save', dict(document=tampered), version(reopened))
+ assert rejected['issues'][0]['code'] == 'shot_evidence_immutable'
+ assert client.post(route, json=dict(modelConfigId=model['id'])).json() == reopened
+ assert len(calls) == 1
+ assert len(requests) == (2 if model_failure else 3)
+
+
+def test_cancellation_keeps_scan_files_and_slot_until_worker_stops(monkeypatch):
+ async def run():
+ service = creation_shots.CreationShots(None, None)
+ monkeypatch.setattr(service, 'get', lambda *_: None)
+ loop = asyncio.get_running_loop()
+ started = asyncio.Event()
+ finish = Event()
+ directories = []
+
+ def scan(_project, _asset, _session, directory):
+ directories.append(directory)
+ loop.call_soon_threadsafe(started.set)
+ assert finish.wait(timeout=5)
+ (directory / 'last-frame.jpg').write_bytes(b'test')
+
+ monkeypatch.setattr(service, '_inspect', scan)
+ task = asyncio.create_task(service.create(uuid4(), uuid4(), str(uuid4())))
+ try:
+ await asyncio.wait_for(started.wait(), timeout=5)
+ task.cancel()
+ await asyncio.sleep(0)
+ assert directories[0].is_dir()
+ with pytest.raises(ProjectError, match='正在分析') as rejection:
+ await service.create(uuid4(), uuid4(), str(uuid4()))
+ assert rejection.value.code == 'shot_analysis_busy'
+ finally:
+ finish.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert not directories[0].exists()
+ assert not service.analysis_slot.locked()
+
+ asyncio.run(run())
diff --git a/tests/test_shot_descriptions.py b/tests/test_shot_descriptions.py
new file mode 100644
index 000000000..09a8c36de
--- /dev/null
+++ b/tests/test_shot_descriptions.py
@@ -0,0 +1,266 @@
+import asyncio
+import base64
+import copy
+import hashlib
+import importlib.util
+import json
+from pathlib import Path
+
+import httpx
+import pytest
+
+from opendirector.application.shot_descriptions import describe_shot_frame
+
+JPEG = base64.b64decode(
+ "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAP//////////////////////////////////////////"
+ "////////////////////////////////////////////wAALCAABAAEBAREA/8QAFAABAAAA"
+ "AAAAAAAAAAAAAAAACf/EABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAD8AKp//2Q=="
+)
+
+
+def config(**changes):
+ value = {
+ "id": "config-1",
+ "kind": "agent",
+ "url": "https://model.test/v1",
+ "modelId": "vision-chat",
+ "apiKey": "secret-key",
+ "inputModalities": ["text", "image"],
+ "protocol": "openai",
+ "authMode": "bearer",
+ "proxyMode": "direct",
+ }
+ value.update(changes)
+ return value
+
+
+def shot(**changes):
+ value = {
+ "id": "shot-0001",
+ "startPts": 1000,
+ "endPts": 3000,
+ "timeBase": "1/1000",
+ "representative": {
+ "path": "frames/shot-0001.jpg",
+ "pts": 1500,
+ "timeBase": "1/1000",
+ "seconds": 1.5,
+ },
+ }
+ value.update(changes)
+ return value
+
+
+def _answer(**changes):
+ value = {
+ "subject": "A woman holding a lantern",
+ "scene": "A snowy street at night",
+ "framing": "Medium shot, centered",
+ }
+ value.update(changes)
+ return json.dumps(value, ensure_ascii=False)
+
+
+def test_describe_shot_frame_uses_real_chat_transport_and_frame_only_provenance():
+ calls = []
+
+ def handler(request):
+ calls.append(request)
+ return httpx.Response(
+ 200, json={"choices": [{"message": {"content": _answer()}}]}
+ )
+
+ original = shot()
+ before = copy.deepcopy(original)
+ row = asyncio.run(
+ describe_shot_frame(
+ config(), original, JPEG, transport=httpx.MockTransport(handler)
+ )
+ )
+
+ assert len(calls) == 1
+ assert str(calls[0].url) == "https://model.test/v1/chat/completions"
+ payload = json.loads(calls[0].content)
+ assert payload["model"] == "vision-chat"
+ assert payload["max_tokens"] == 384
+ assert payload["stream"] is False
+ assert len(payload["messages"]) == 2
+ assert payload["messages"][0]["role"] == "system"
+ user = payload["messages"][1]
+ assert user["role"] == "user"
+ blocks = user["content"]
+ assert [block["type"] for block in blocks] == ["text", "image_url"]
+ assert "1.000000s" in blocks[0]["text"]
+ assert "3.000000s" in blocks[0]["text"]
+ assert "1.500000s" in blocks[0]["text"]
+ image_url = blocks[1]["image_url"]["url"]
+ assert image_url.startswith("data:image/jpeg;base64,")
+ assert base64.b64decode(image_url.split(",", 1)[1]) == JPEG
+
+ assert set(row) == {
+ "shotId",
+ "mode",
+ "interpretation",
+ "language",
+ "inputFrame",
+ "model",
+ "description",
+ "requestSeconds",
+ }
+ assert row["shotId"] == "shot-0001"
+ assert row["mode"] == "frame_only"
+ assert row["interpretation"] == "model_inference"
+ assert row["language"] == "en-US"
+ assert row["inputFrame"] == {
+ "path": "frames/shot-0001.jpg",
+ "sha256": hashlib.sha256(JPEG).hexdigest(),
+ "pts": 1500,
+ "timeBase": "1/1000",
+ "seconds": 1.5,
+ }
+ assert row["model"] == {"configId": "config-1", "modelId": "vision-chat"}
+ assert row["description"] == {
+ "subject": "A woman holding a lantern",
+ "scene": "A snowy street at night",
+ "framing": "Medium shot, centered",
+ }
+ assert row["requestSeconds"] >= 0
+ assert original == before
+
+ stored = json.dumps(row, ensure_ascii=False)
+ assert "secret-key" not in stored
+ assert "model.test" not in stored
+ assert base64.b64encode(JPEG).decode() not in stored
+
+
+def test_describe_shot_frame_rejects_text_only_and_segmentation_before_http():
+ calls = []
+
+ def handler(request):
+ calls.append(request)
+ return httpx.Response(500)
+
+ for rejected in (
+ config(inputModalities=["text"]),
+ config(protocol="vllm_omni_segmentation"),
+ ):
+ with pytest.raises(ValueError):
+ asyncio.run(
+ describe_shot_frame(
+ rejected, shot(), JPEG, transport=httpx.MockTransport(handler)
+ )
+ )
+ assert calls == []
+
+
+@pytest.mark.parametrize(
+ "content",
+ [
+ "not json",
+ "[]",
+ json.dumps({"subject": 1, "scene": "s", "framing": "f"}),
+ json.dumps({"subject": "s", "scene": "s", "framing": "f", "extra": "x"}),
+ "",
+ ],
+)
+def test_bad_model_json_raises_after_exactly_one_call(content):
+ calls = []
+
+ def handler(request):
+ calls.append(request)
+ return httpx.Response(
+ 200, json={"choices": [{"message": {"content": content}}]}
+ )
+
+ with pytest.raises(ValueError):
+ asyncio.run(
+ describe_shot_frame(
+ config(), shot(), JPEG, transport=httpx.MockTransport(handler)
+ )
+ )
+ assert len(calls) == 1
+
+
+def test_fenced_json_is_accepted():
+ calls = []
+ content = "```json\n" + _answer() + "\n```"
+
+ def handler(request):
+ calls.append(request)
+ return httpx.Response(
+ 200, json={"choices": [{"message": {"content": content}}]}
+ )
+
+ row = asyncio.run(
+ describe_shot_frame(
+ config(), shot(), JPEG, transport=httpx.MockTransport(handler)
+ )
+ )
+
+ assert len(calls) == 1
+ assert row["description"]["subject"] == "A woman holding a lantern"
+
+
+def test_chinese_is_requested_by_the_application_without_transport_rewriting():
+ calls = []
+
+ def handler(request):
+ calls.append(json.loads(request.content))
+ return httpx.Response(200, json={"choices": [{"message": {"content": _answer(
+ subject="手持灯笼的人物", scene="夜间雪地街道", framing="居中中景"
+ )}}]})
+
+ row = asyncio.run(describe_shot_frame(config(), shot(), JPEG, language="zh-CN",
+ transport=httpx.MockTransport(handler)))
+ assert "简体中文" in calls[0]["messages"][0]["content"]
+ assert row["language"] == "zh-CN"
+ assert row["description"]["subject"] == "手持灯笼的人物"
+
+
+def test_default_token_budget_is_not_a_permanent_product_limit():
+ calls = []
+
+ def handler(request):
+ calls.append(json.loads(request.content))
+ return httpx.Response(200, json={"choices": [{"message": {"content": _answer()}}]})
+
+ asyncio.run(describe_shot_frame(config(), shot(), JPEG, max_tokens=512,
+ transport=httpx.MockTransport(handler)))
+ assert calls[0]["max_tokens"] == 512
+
+
+def test_cli_explicit_four_shots_are_not_rejected_by_experiment_budget():
+ ids = ["shot-0001", "shot-0002", "shot-0003", "shot-0004"]
+ assert _cli_module()._selected_ids(ids) == ids
+
+
+def test_cli_frame_path_stays_beneath_the_analysis_directory(tmp_path):
+ module = _cli_module()
+ base = tmp_path / "analysis"
+ (base / "frames").mkdir(parents=True)
+ inside = base / "frames" / "shot-0001.jpg"
+ inside.write_bytes(JPEG)
+ outside = tmp_path / "outside.jpg"
+ outside.write_bytes(JPEG)
+
+ assert module._resolve_frame_path(base, "frames/shot-0001.jpg") == inside.resolve()
+ with pytest.raises(ValueError):
+ module._resolve_frame_path(base, str(outside))
+ with pytest.raises(ValueError):
+ module._resolve_frame_path(base, "../outside.jpg")
+
+ (base / "frames" / "link.jpg").symlink_to(outside)
+ with pytest.raises(ValueError):
+ module._resolve_frame_path(base, "frames/link.jpg")
+
+
+def _cli_module():
+ path = (
+ Path(__file__).resolve().parents[1]
+ / "scripts"
+ / "describe_reference_shots.py"
+ )
+ spec = importlib.util.spec_from_file_location("describe_reference_shots", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
diff --git a/tests/test_shot_detection.py b/tests/test_shot_detection.py
new file mode 100644
index 000000000..d5999fecf
--- /dev/null
+++ b/tests/test_shot_detection.py
@@ -0,0 +1,420 @@
+from fractions import Fraction
+
+import pytest
+
+from opendirector.media.shot_detection import (
+ _end_boundary,
+ _fraction_text,
+ _mean_intensity,
+ _nearest_frame_pts,
+ _normalize_pts,
+ _normalized_stream_end,
+ _pts_seconds,
+ _rate_fraction,
+ _representative_candidates,
+ _select_representative,
+ _shot_records,
+ _vfr_summary,
+)
+
+
+def test_shot_records_use_real_pts_nonzero_origin_and_exclusive_ends():
+ time_base = Fraction(1, 1000)
+ original_pts = [5000, 5040, 5130, 5200, 5250]
+ normalized = [_normalize_pts(pts, original_pts[0]) for pts in original_pts]
+ assert normalized == [0, 40, 130, 200, 250]
+
+ shots = _shot_records(
+ normalized, time_base, [130], 300, "video-stream-duration"
+ )
+
+ assert [(shot["startPts"], shot["endPts"]) for shot in shots] == [
+ (0, 130),
+ (130, 300),
+ ]
+ assert shots[0]["endSeconds"] == pytest.approx(0.13)
+ assert shots[1]["startSeconds"] == pytest.approx(0.13)
+ assert shots[0]["endMethod"] == "next-cut"
+ assert shots[-1]["endMethod"] == "video-stream-duration"
+ assert shots[0]["representative"]["pts"] == 40
+ assert shots[0]["representative"]["pts"] < shots[0]["endPts"]
+ assert shots[0]["representative"]["seconds"] == pytest.approx(0.04)
+
+
+def test_single_shot_spans_the_whole_bounded_input():
+ shots = _shot_records(
+ [0, 40, 80], Fraction(1, 1000), [], 120, "estimated-last-interval"
+ )
+
+ assert len(shots) == 1
+ shot = shots[0]
+ assert (shot["startPts"], shot["endPts"]) == (0, 120)
+ assert shot["endMethod"] == "estimated-last-interval"
+ assert shot["representative"]["pts"] == 40
+ assert shot["representative"]["path"] == "frames/shot-0001.jpg"
+ assert shot["timeBase"] == "1/1000"
+ assert shot["description"] is None
+ boundary = Fraction(shot["startPts"] + shot["endPts"], 2)
+ assert abs(shot["representative"]["pts"] - boundary) == 20
+
+
+def test_rapid_cuts_are_sorted_deduplicated_and_tail_cut_is_not_empty():
+ time_base = Fraction(1, 1000)
+ shots = _shot_records(
+ [0, 10, 20, 30, 40],
+ time_base,
+ [30, 10, 30, 999, 0, 20],
+ 50,
+ "video-stream-duration",
+ )
+
+ assert [(shot["startPts"], shot["endPts"]) for shot in shots] == [
+ (0, 10),
+ (10, 20),
+ (20, 30),
+ (30, 50),
+ ]
+ assert all(shot["endPts"] > shot["startPts"] for shot in shots)
+ assert shots[-1]["startPts"] == 30
+ assert shots[-1]["representative"]["pts"] == 40
+
+
+def test_shot_times_only_come_from_pts_and_time_base_not_fps_ordinals():
+ time_base = Fraction(1, 90000)
+ shots = _shot_records(
+ [0, 9000, 18000],
+ time_base,
+ [],
+ 27000,
+ "video-stream-duration",
+ )
+
+ shot = shots[0]
+ assert _pts_seconds(9000, time_base) == pytest.approx(0.1)
+ assert shot["endSeconds"] == pytest.approx(0.3)
+ assert shot["representative"]["pts"] == 9000
+ assert shot["representative"]["seconds"] == pytest.approx(0.1)
+ assert shot["representative"]["seconds"] != pytest.approx(300.0)
+
+
+def test_vfr_summary_reports_irregular_observed_intervals():
+ summary = _vfr_summary(
+ [0, 33, 66, 133, 166], Fraction(1, 1000)
+ )
+
+ assert summary["intervalCount"] == 4
+ assert summary["isVariable"] is True
+ assert summary["minIntervalSeconds"] == pytest.approx(0.033)
+ assert summary["maxIntervalSeconds"] == pytest.approx(0.067)
+ assert summary["distinctIntervalCount"] == 2
+ assert summary["observed"][0] == {"seconds": 0.033, "count": 3}
+
+
+def test_regular_intervals_are_not_reported_as_vfr():
+ summary = _vfr_summary([0, 40, 80, 120], Fraction(1, 1000))
+
+ assert summary["intervalCount"] == 3
+ assert summary["isVariable"] is False
+ assert summary["minIntervalSeconds"] == pytest.approx(0.04)
+ assert summary["maxIntervalSeconds"] == pytest.approx(0.04)
+
+
+def test_end_boundary_prefers_real_frame_duration_then_video_stream_duration():
+ time_base = Fraction(1, 1000)
+
+ assert _end_boundary([0, 100, 200], time_base, 50, None) == (
+ 250,
+ "last-frame-duration",
+ )
+ assert _end_boundary([0, 100, 200], time_base, None, 0.3) == (
+ 300,
+ "video-stream-duration",
+ )
+ assert _end_boundary([0, 100, 200], time_base, None, 0.15) == (
+ 300,
+ "estimated-last-interval",
+ )
+ assert _end_boundary([0], time_base, None, None) == (
+ 1,
+ "estimated-timebase-tick",
+ )
+
+
+def test_rate_helpers_keep_rational_strings():
+ assert _rate_fraction("30000/1001") == Fraction(30000, 1001)
+ assert _rate_fraction("0/0") is None
+ assert _fraction_text(Fraction(30000, 1001)) == "30000/1001"
+
+
+def test_video_stream_end_accounts_for_first_decoded_pts_offset():
+ stream = {"start_pts": 5000, "duration_ts": 300, "time_base": "1/1000"}
+ assert _normalized_stream_end(stream, 5040, Fraction(1, 1000)) == pytest.approx(.26)
+ assert _normalized_stream_end({"start_time": "5", "duration": "0.3"},
+ 5040, Fraction(1, 1000)) == pytest.approx(.26)
+ assert _normalized_stream_end({"duration": "20"}, 5040, Fraction(1, 1000)) is None
+
+
+def test_adaptive_detector_does_not_fabricate_cuts_from_incomplete_tail_window():
+ pytest.importorskip("scenedetect")
+ numpy = pytest.importorskip("numpy")
+ from scenedetect import AdaptiveDetector, FrameTimecode
+ from scenedetect.common import Timecode
+
+ fps = 30
+ time_base = Fraction(1, fps)
+ black = numpy.zeros((36, 64, 3), dtype=numpy.uint8)
+ white = numpy.full((36, 64, 3), 255, dtype=numpy.uint8)
+ frames = [black] * 6 + [white] * 4 + [black] * 2
+ detector = AdaptiveDetector(
+ adaptive_threshold=3.0, min_scene_len=0.1, min_content_val=15.0
+ )
+
+ cuts = []
+ for index, image in enumerate(frames):
+ timecode = FrameTimecode(Timecode(index, time_base), Fraction(fps, 1))
+ cuts.extend(detector.process_frame(timecode, image))
+
+ cut_pts = [int(timecode.pts) for timecode in cuts]
+ assert cut_pts, "expected a cut from the complete adaptive window"
+ assert all(pts < 10 for pts in cut_pts), (
+ "the incomplete adaptive window tail must not invent cuts"
+ )
+
+ shots = _shot_records(
+ list(range(len(frames))),
+ time_base,
+ cut_pts,
+ len(frames),
+ "video-stream-duration",
+ )
+ assert shots[-1]["endPts"] == len(frames)
+ assert all(shot["endPts"] > shot["startPts"] for shot in shots)
+
+
+def test_nearest_frame_pts_matches_bruteforce_for_ranges_ties_and_fractions():
+ frame_pts = [0, 40, 130, 200, 250]
+
+ def bruteforce(target, start, end):
+ best = None
+ for pts in frame_pts:
+ if pts < start or pts >= end:
+ continue
+ key = (abs(Fraction(int(pts)) - target), int(pts))
+ if best is None or key < best[0]:
+ best = (key, int(pts))
+ return best[1] if best is not None else None
+
+ cases = [
+ (Fraction(65), 0, 200),
+ (Fraction(85), 0, 200),
+ (Fraction(85, 2), 40, 130),
+ (Fraction(-1000), 0, 130),
+ (Fraction(1000), 0, 130),
+ (Fraction(129), 40, 130),
+ (Fraction(130), 40, 130),
+ (Fraction(0), 130, 250),
+ (Fraction(200), 0, 200),
+ (Fraction(999), 0, 0),
+ (Fraction(999), 10, 10),
+ ]
+
+ for target, start, end in cases:
+ assert _nearest_frame_pts(frame_pts, target, start, end) == bruteforce(
+ target, start, end
+ )
+ assert _nearest_frame_pts([], Fraction(0), 0, 10) is None
+
+
+def test_save_representatives_stops_after_last_candidate_and_detects_missing(
+ monkeypatch, tmp_path
+):
+ from opendirector.media import shot_detection
+
+ time_base = Fraction(1, 1000)
+ shots = [
+ {
+ "startPts": 0,
+ "endPts": 1000,
+ "representative": {
+ "path": "frames/shot-0001.jpg",
+ "selection": {"sampledFrames": [{"pts": 100}, {"pts": 200}]},
+ },
+ },
+ {
+ "startPts": 1000,
+ "endPts": 2000,
+ "representative": {
+ "path": "frames/shot-0002.jpg",
+ "selection": {"sampledFrames": [{"pts": 1100}, {"pts": 1200}]},
+ },
+ },
+ ]
+
+ class FakeFrame:
+ def __init__(self, pts):
+ self.pts = pts
+
+ def to_image(self):
+ return object()
+
+ class FakeContainer:
+ def __init__(self, frame_pts, decoded):
+ self._frame_pts = frame_pts
+ self._decoded = decoded
+
+ def decode(self, stream):
+ for pts in self._frame_pts:
+ self._decoded.append(pts)
+ yield FakeFrame(pts)
+
+ def close(self):
+ pass
+
+ frames_to_decode = [list(range(0, 2001))]
+
+ def fake_open_video(path):
+ container = FakeContainer(frames_to_decode[0], decoded)
+ return container, object(), time_base
+
+ saved = []
+ decoded = []
+ monkeypatch.setattr(shot_detection, "_open_video", fake_open_video)
+ monkeypatch.setattr(
+ shot_detection, "_mean_intensity", lambda image: 128.0
+ )
+ monkeypatch.setattr(
+ shot_detection,
+ "_save_thumbnail",
+ lambda image, target, max_width: saved.append(target.name),
+ )
+
+ shot_detection._save_representatives(
+ tmp_path / "video.mp4", 0, time_base, shots, tmp_path, 640, 12.0
+ )
+
+ assert decoded == list(range(0, 1201))
+ assert saved == ["shot-0001.jpg", "shot-0002.jpg"]
+ assert shots[-1]["representative"]["pts"] == 1200
+
+ frames_to_decode[0] = [pts for pts in range(0, 2001) if pts != 1200]
+ missing_shots = [
+ {
+ **shot,
+ "representative": {
+ **shot["representative"],
+ "selection": {
+ "sampledFrames": [
+ dict(sample)
+ for sample in shot["representative"]["selection"][
+ "sampledFrames"
+ ]
+ ]
+ },
+ },
+ }
+ for shot in shots
+ ]
+ for shot in missing_shots:
+ for sample in shot["representative"]["selection"]["sampledFrames"]:
+ sample.pop("meanIntensity", None)
+ with pytest.raises(RuntimeError, match="1200"):
+ shot_detection._save_representatives(
+ tmp_path / "video.mp4",
+ 0,
+ time_base,
+ missing_shots,
+ tmp_path,
+ 640,
+ 12.0,
+ )
+
+
+def test_representative_candidates_stay_inside_shot_and_exclude_end():
+ frame_pts = [0, 40, 60, 100, 200]
+
+ candidates = _representative_candidates(frame_pts, 0, 100)
+
+ assert candidates == [40, 60]
+ assert all(0 <= pts < 100 for pts in candidates)
+ assert 100 not in candidates
+
+
+def test_representative_candidates_deduplicate_single_frame_shot():
+ assert _representative_candidates([0], 0, 10) == [0]
+ assert _representative_candidates([], 0, 10) == []
+
+
+def test_representative_selection_prefers_visible_over_black_midpoint():
+ samples = [
+ {"pts": 50, "meanIntensity": 160.0},
+ {"pts": 100, "meanIntensity": 0.0},
+ {"pts": 150, "meanIntensity": 120.0},
+ ]
+
+ selected = _select_representative(samples, 0, 200, 12.0)
+
+ assert selected == {"pts": 50, "visibility": "visible"}
+
+
+def test_representative_selection_keeps_midpoint_when_all_samples_are_dark():
+ samples = [
+ {"pts": 50, "meanIntensity": 0.0},
+ {"pts": 100, "meanIntensity": 3.0},
+ {"pts": 150, "meanIntensity": 1.0},
+ ]
+
+ selected = _select_representative(samples, 0, 200, 12.0)
+
+ assert selected == {"pts": 100, "visibility": "low_visibility"}
+
+
+def test_representative_selection_uses_earlier_pts_on_midpoint_tie():
+ samples = [
+ {"pts": 60, "meanIntensity": 80.0},
+ {"pts": 40, "meanIntensity": 80.0},
+ ]
+
+ selected = _select_representative(samples, 0, 100, 12.0)
+
+ assert selected["pts"] == 40
+
+
+def test_representative_candidates_use_normalized_pts_for_nonzero_origin():
+ original_pts = [9000, 9040, 9100, 9200]
+ normalized = [_normalize_pts(pts, original_pts[0]) for pts in original_pts]
+ assert normalized == [0, 40, 100, 200]
+
+ candidates = _representative_candidates(normalized, 0, 100)
+
+ assert candidates == [40]
+
+
+def test_shot_records_sample_candidates_in_representative_time_base():
+ time_base = Fraction(1, 1000)
+
+ shots = _shot_records(
+ [0, 100, 200, 300], time_base, [], 400, "video-stream-duration"
+ )
+
+ representative = shots[0]["representative"]
+ assert representative["selection"]["method"] == "visible-near-midpoint"
+ assert representative["selection"]["intensityThreshold"] == 12.0
+ samples = representative["selection"]["sampledFrames"]
+ assert [sample["pts"] for sample in samples] == [100, 200, 300]
+ assert all(
+ sample["seconds"] == pytest.approx(sample["pts"] / 1000)
+ for sample in samples
+ )
+
+
+def test_mean_intensity_measures_downscaled_rgb_pixels():
+ image_module = pytest.importorskip("PIL.Image")
+ image = image_module.new("RGB", (200, 100), (10, 20, 30))
+
+ assert _mean_intensity(image) == pytest.approx(20.0)
+
+ split = image_module.new("RGB", (200, 100), (0, 0, 0))
+ draw = pytest.importorskip("PIL.ImageDraw").Draw(split)
+ draw.rectangle((100, 0, 199, 99), fill=(255, 255, 255))
+
+ assert _mean_intensity(split) == pytest.approx(127.5, abs=2.0)
From 7ad0b12bb6c056eb233ef346ca4b0c1277dced49 Mon Sep 17 00:00:00 2001
From: Dragonborn <1078757180@qq.com>
Date: Mon, 30 Nov 2026 23:56:48 +0800
Subject: [PATCH 2/9] Honor video display rotation in representative frames
---
.../src/opendirector/media/shot_detection.py | 6 +++-
tests/test_shot_detection.py | 29 +++++++++++++++++++
2 files changed, 34 insertions(+), 1 deletion(-)
diff --git a/packages/core/src/opendirector/media/shot_detection.py b/packages/core/src/opendirector/media/shot_detection.py
index 017306e99..eefb359c3 100644
--- a/packages/core/src/opendirector/media/shot_detection.py
+++ b/packages/core/src/opendirector/media/shot_detection.py
@@ -311,7 +311,10 @@ def finalize(shot_index):
record = selected[shot_index]
shot = shots[shot_index]
target = output_path / shot["representative"]["path"]
- _save_thumbnail(record["image"], target, max_width)
+ image = record["image"]
+ if record["rotation"]:
+ image = image.rotate(record["rotation"], expand=True)
+ _save_thumbnail(image, target, max_width)
shot["representative"]["pts"] = int(record["pts"])
shot["representative"]["timeBase"] = _fraction_text(time_base)
shot["representative"]["seconds"] = _round_seconds(
@@ -354,6 +357,7 @@ def finalize(shot_index):
else "low_visibility"
),
"image": image,
+ "rotation": frame.rotation,
}
midpoint = _midpoint_pts(shot["startPts"], shot["endPts"])
if _prefer_candidate(
diff --git a/tests/test_shot_detection.py b/tests/test_shot_detection.py
index d5999fecf..c73fbb2ef 100644
--- a/tests/test_shot_detection.py
+++ b/tests/test_shot_detection.py
@@ -1,7 +1,9 @@
from fractions import Fraction
+import subprocess
import pytest
+from capabilities import requires_ffmpeg
from opendirector.media.shot_detection import (
_end_boundary,
_fraction_text,
@@ -15,9 +17,34 @@
_select_representative,
_shot_records,
_vfr_summary,
+ inspect_video_shots,
)
+@requires_ffmpeg()
+def test_representative_follows_display_rotation(tmp_path):
+ pytest.importorskip("av")
+ pytest.importorskip("scenedetect")
+ from PIL import Image
+
+ source = tmp_path / "landscape.mp4"
+ rotated = tmp_path / "portrait.mp4"
+ ffmpeg = ["ffmpeg", "-nostdin", "-v", "error"]
+ subprocess.run([*ffmpeg, "-f", "lavfi", "-i",
+ "color=red:s=128x64:r=8:d=1,drawbox=x=64:y=0:w=64:h=64:color=blue:t=fill",
+ "-c:v", "libx264", "-threads", "1", str(source)], check=True)
+ subprocess.run([*ffmpeg, "-display_rotation", "90", "-i", str(source),
+ "-c", "copy", str(rotated)], check=True)
+
+ output = tmp_path / "breakdown"
+ result = inspect_video_shots(rotated, output)
+ shot, = result["shots"]
+ with Image.open(output / shot["representative"]["path"]) as frame:
+ assert frame.size == (64, 128)
+ assert frame.getpixel((32, 32))[2] > 200
+ assert frame.getpixel((32, 96))[0] > 200
+
+
def test_shot_records_use_real_pts_nonzero_origin_and_exclusive_ends():
time_base = Fraction(1, 1000)
original_pts = [5000, 5040, 5130, 5200, 5250]
@@ -251,6 +278,8 @@ def test_save_representatives_stops_after_last_candidate_and_detects_missing(
]
class FakeFrame:
+ rotation = 0
+
def __init__(self, pts):
self.pts = pts
From 137d4146b4d207995580fda20c6a864f4f991607 Mon Sep 17 00:00:00 2001
From: Dragonborn <1078757180@qq.com>
Date: Tue, 1 Dec 2026 00:52:40 +0800
Subject: [PATCH 3/9] Resume missing shot suggestions from retained frames
---
apps/api/src/opendirector_api/creation.py | 10 +
apps/api/src/opendirector_api/localization.py | 2 +-
docs/guides/user-guide.md | 4 +-
docs/guides/user-guide.zh-CN.md | 6 +-
.../application/creation_canvas.py | 8 +-
.../application/creation_shots.py | 118 +++++++--
.../opendirector/domain/creation/editors.py | 5 +-
src/canvas/ShotBreakdownEditor.tsx | 226 +++++++++---------
src/canvas/shot-breakdown-editor.css | 12 +
src/i18n/messages/en-US/editors.ts | 21 +-
src/i18n/messages/zh-CN/editors.ts | 18 +-
tests/test_creation_shots.py | 76 +++++-
12 files changed, 348 insertions(+), 158 deletions(-)
diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py
index 6776b945e..d378bbc7d 100644
--- a/apps/api/src/opendirector_api/creation.py
+++ b/apps/api/src/opendirector_api/creation.py
@@ -89,6 +89,10 @@ class ShotBreakdownRequest(BaseModel):
modelConfigId: UUID | None = None
+class ShotSuggestionsRequest(ShotBreakdownRequest):
+ modelConfigId: UUID = Field(...)
+
+
def creation_routes(projects: CreationProjects, generation=None, prompt_optimization=None, model_configs=None):
router = APIRouter(prefix='/api/creation', tags=['Unified creation projects'])
reference_checks = asyncio.Semaphore(2)
@@ -455,6 +459,12 @@ async def analyze_shots(project_id: UUID, asset_id: UUID, value: ShotBreakdownRe
return await shots.create(project_id, asset_id, str(x_opendirector_session), model_config_id=value.modelConfigId,
language='en-US' if wants_english(request) else 'zh-CN')
+ @router.post('/projects/{project_id}/assets/{asset_id}/shot-breakdown/suggestions', response_model=ShotBreakdownDocument)
+ async def fill_shot_suggestions(project_id: UUID, asset_id: UUID, value: ShotSuggestionsRequest, request: Request,
+ x_opendirector_session: UUID = Header()):
+ return await shots.fill_missing(project_id, asset_id, str(x_opendirector_session), model_config_id=value.modelConfigId,
+ language='en-US' if wants_english(request) else 'zh-CN')
+
@router.get('/projects/{project_id}/assets/{asset_id}/thumbnail')
def thumbnail(project_id: UUID, asset_id: UUID):
value, asset = assets.thumbnail(project_id, asset_id)
diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py
index dc19e731c..aa9d5b54b 100644
--- a/apps/api/src/opendirector_api/localization.py
+++ b/apps/api/src/opendirector_api/localization.py
@@ -98,7 +98,7 @@
"shot_analysis_busy": "Another reference video is being analyzed. Try again shortly.",
"shot_count_limit": "The video has more than 48 shots. Analyze a shorter excerpt.",
"shot_model_required": "Select a chat model that accepts images.",
- "shot_model_limit": "Only 12 shots can be described at once. Run detection alone for longer breakdowns.",
+ "shot_breakdown_missing": "Detect the shots in this video first.",
"moss_speech_text": "Enter the text to read aloud.",
"moss_speech_voice": "Enter a Voice ID available to your MOSS account.",
"moss_speech_reference": "MOSS speech generation does not accept references. Enter speech text and a Voice ID.",
diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md
index e33ec955e..cd3b4f937 100644
--- a/docs/guides/user-guide.md
+++ b/docs/guides/user-guide.md
@@ -212,7 +212,9 @@ For a local edit, mark an area or create a selection first, then enter your inst
Install the optional analyzer in the same Python environment as OpenDirector with `python -m pip install 'opendirector[shot-analysis]'`, or `python -m pip install -e '.[shot-analysis]'` from a source checkout. Make FFmpeg and FFprobe available. Import a video, select its canvas node, and choose **Shot breakdown**. **Analyze shots** detects cuts on the CPU and saves a representative frame for each shot.
-To get suggestions for subjects, scenes, and framing, choose an image-capable chat model before the first analysis. The model receives one JPEG per shot. If the model stops early, the detected shots and completed suggestions are saved. Analysis supports videos up to 120 seconds and 48 detected shots. A run with model suggestions supports up to 12 shots.
+Local detection supports videos up to 120 seconds and 48 detected shots. To add suggestions about the subject, scene, and framing, choose a chat model that accepts images. You can choose one before **Analyze shots** or add suggestions to a saved breakdown later. Each run sends the selected model one representative JPEG per shot, for up to 12 shots.
+
+The summary shows how many shots still need a suggestion. Save any draft edits, choose a model, and click **Fill missing suggestions** to process the next batch using the saved frames. If the model stops early, for example because of a rate limit, you can pick up where it stopped, even after reopening the video. Each batch keeps the detected cuts, previous suggestions, and your saved edits.
Compare the detected range with the draft in the source video, then use **Save breakdown** to save your edited ranges and descriptions. The detected boundaries, representative frames, and model suggestions remain available when you reopen the same video. Ranges use normalized source timestamps with an exclusive end. To remove an extra cut, select the shot just after it and choose **Join previous shot** when the two draft ranges touch. Use **Restore cut** to bring the cut back.
diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md
index e324b2f9d..ba3db1073 100644
--- a/docs/guides/user-guide.zh-CN.md
+++ b/docs/guides/user-guide.zh-CN.md
@@ -210,9 +210,11 @@ Codex 网页检索引用在具有匹配来源时显示为编号链接;复制
## 编辑参考视频的分镜
-在运行 OpenDirector 的 Python 环境执行 `python -m pip install 'opendirector[shot-analysis]'` 安装可选分析依赖,源码工作区可执行 `python -m pip install -e '.[shot-analysis]'`。准备好 FFmpeg 和 FFprobe。把视频导入画布,选中视频节点并打开**分镜**。点击**分析镜头**后,应用用 CPU 检测切点,为每镜保存一张代表帧。
+在运行 OpenDirector 的 Python 环境执行 `python -m pip install 'opendirector[shot-analysis]'` 安装可选分析依赖,源码工作区可执行 `python -m pip install -e '.[shot-analysis]'`。准备好 FFmpeg 和 FFprobe。把视频导入画布,选中视频节点并打开**分镜**。点击**分析分镜**后,应用用 CPU 检测切点,为每镜保存一张代表帧。
-如果需要主体、场景和构图建议,在首次分析前选择支持图片输入的对话模型。模型每镜收到一张 JPEG。模型中途出错时,已检测的镜头和已完成的建议会保存下来。分析支持 120 秒以内、最多 48 个镜头的视频。使用模型建议时,每次最多处理 12 镜。
+本地检测支持 120 秒以内、最多 48 个镜头的视频。如果需要主体、场景和景别建议,可在点击**分析分镜**前选择支持图片输入的对话模型,也可以先保存检测结果,以后再选模型。每次最多处理 12 个镜头,每镜向所选模型发送一张 JPEG 代表帧。
+
+分镜顶部会显示还有多少镜头缺少建议。先保存草稿修改,再选择模型,点击**补全缺失建议**,就能用已有的代表帧处理下一批。如果遇到模型限流等中断,重新打开视频后也能从缺少建议的镜头继续。每次补全都会保留检测区间、已有建议和你保存的修改。
在原片里对照检测区间和草稿边界,修改后点击**保存分镜**。重开同一个视频仍可查看原检测区间、代表帧和模型建议。区间使用源视频的归一化时间戳,终点不含在区间内。多切了一刀时,选中切点后的镜头。若两段草稿首尾相接,点击**与上一镜合并**。用**恢复此切点**可加回切点。
diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py
index e4335fc51..5d3d12d05 100644
--- a/packages/core/src/opendirector/application/creation_canvas.py
+++ b/packages/core/src/opendirector/application/creation_canvas.py
@@ -304,12 +304,12 @@ def _available(self, asset):
def execute(self, command, *, session=None, source='ui'):
return self.projects.commit(command, lambda before: self.apply(before, command), session=session, source=source)
- def apply(self, before, command):
+ def apply(self, before, command, *, generated_suggestions=None):
data = before.model_dump(mode='json')
operations = command.payload.operations if command.type == 'creation.batch' else [command]
for operation in operations:
if operation.type != 'canvas.applyEdit':
- self._mutate(data, operation.type, operation.payload)
+ self._mutate(data, operation.type, operation.payload, generated_suggestions=generated_suggestions)
# Publish against the final document in this atomic batch.
published = set()
for operation in operations:
@@ -504,7 +504,7 @@ def _publish_render(self, data, payload):
editorDocumentId=str(doc.id), editorRevision=doc.revision,
sources=[ref.model_dump(mode='json') for ref in sources])
- def _mutate(self, data, kind, payload):
+ def _mutate(self, data, kind, payload, *, generated_suggestions=None):
value = payload.model_dump(mode='json', exclude_unset=True)
if kind in {'editor.create', 'editor.save'} and payload.document.kind == 'timeline':
self._validate_timeline(payload.document, ProjectSnapshot.model_validate(data))
@@ -537,7 +537,7 @@ def _mutate(self, data, kind, payload):
raise ContractError('role_restricted', '配置编辑不能修改对象角色或结果选择。', UUID(obj['id']))
if key == 'document' and obj['kind'] == 'shot_breakdown':
from opendirector.domain.creation.editors import ShotBreakdownDocument
- basis = ShotBreakdownDocument.model_validate(old).data.analysis_basis()
+ basis = ShotBreakdownDocument.model_validate(old).data.analysis_basis(generated_suggestions)
if payload.document.data.analysis_basis() != basis:
raise ContractError('shot_evidence_immutable', '不能修改原始分镜检测或模型建议。', UUID(obj['id']))
for item in data['canvasItems']:
diff --git a/packages/core/src/opendirector/application/creation_shots.py b/packages/core/src/opendirector/application/creation_shots.py
index c5d5dda1c..4f7413859 100644
--- a/packages/core/src/opendirector/application/creation_shots.py
+++ b/packages/core/src/opendirector/application/creation_shots.py
@@ -1,15 +1,18 @@
"""Build a retained shot breakdown from a pinned project video."""
import asyncio
+from contextlib import asynccontextmanager
+from functools import partial
from pathlib import Path
from shutil import copyfileobj
from tempfile import TemporaryDirectory
-from uuid import uuid5
+from uuid import uuid4, uuid5
from opendirector.application.creation_assets import CreationAssets
-from opendirector.application.creation_canvas import asset_ref
+from opendirector.application.creation_canvas import CreationCanvas, asset_ref
from opendirector.application.creation_tool_assets import CreationToolAssets
from opendirector.application.shot_descriptions import describe_shot_frame, validate_frame_description_config
from opendirector.domain.creation.commands import parse_command
+from opendirector.domain.creation.editors import ShotFrameSuggestion
from opendirector.domain.projects import ProjectError
from opendirector.media.async_work import blocking
from opendirector.media.shot_detection import DEFAULT_MAX_DURATION_SECONDS, inspect_video_shots
@@ -31,6 +34,12 @@ def get(self, project_id, asset_id):
return next((doc for doc in snapshot.editorDocuments
if doc.kind == 'shot_breakdown' and doc.data.source.assetId == asset_id), None)
+ def _require_breakdown(self, project_id, asset_id):
+ document = self.get(project_id, asset_id)
+ if document is None:
+ raise ProjectError('请先检测参考视频的镜头。', 404, code='shot_breakdown_missing')
+ return document
+
def _require_session(self, project_id, session):
with self.projects.local.transaction() as db:
self.projects._recover()
@@ -60,12 +69,12 @@ def _inspect(self, project_id, asset_id, session, directory):
raise ProjectError('视频内容已变化,请重新导入后分析。', 409, code='storage_unavailable')
return source, analysis
- def _save(self, project_id, source, analysis, descriptions, directory, session):
+ def _save_detection(self, project_id, source, analysis, directory, session):
self._require_session(project_id, session)
document_id = uuid5(source.id, 'reference-shot-breakdown')
source_ref = asset_ref(source)
shots = []
- for shot, suggestion in zip(analysis['shots'], descriptions, strict=True):
+ for shot in analysis['shots']:
frame = shot['representative']
start, end = shot['startPts'], shot['endPts']
frame_id = uuid5(document_id, f"{shot['id']}:{frame['pts']}")
@@ -75,7 +84,7 @@ def _save(self, project_id, source, analysis, descriptions, directory, session):
image = self.assets.get(project_id, imported['id'])
shots.append(dict(id=shot['id'], measured=dict(startPts=start, endPts=end,
representativePts=frame['pts'], representative=asset_ref(image)),
- frameSuggestion=suggestion, edit=dict(startPts=start, endPts=end, description='')))
+ edit=dict(startPts=start, endPts=end, description='')))
video = analysis['source']
command = parse_command(dict(commandId=uuid5(document_id, 'create'), projectId=project_id,
type='editor.create', payload=dict(document=dict(id=document_id, projectId=project_id,
@@ -87,35 +96,92 @@ def _save(self, project_id, source, analysis, descriptions, directory, session):
raise ProjectError('保存分镜失败,请重新打开工程后再试。', 409, code=code)
return self.get(project_id, source.id)
- async def create(self, project_id, asset_id, session, *, model_config_id=None, language='en-US'):
+ @asynccontextmanager
+ async def _analysis(self):
if self.analysis_slot.locked():
raise ProjectError('正在分析另一段参考视频,请稍后重试。', 409, code='shot_analysis_busy')
async with self.analysis_slot:
+ yield
+
+ def _model(self, model_config_id):
+ config = self.model_configs.agent(str(model_config_id))
+ try:
+ validate_frame_description_config(config)
+ except ValueError as exc:
+ raise ProjectError('请选择支持图片输入的对话模型。', code='shot_model_required') from exc
+ return config
+
+ async def create(self, project_id, asset_id, session, *, model_config_id=None, language='en-US'):
+ async with self._analysis():
saved = await asyncio.to_thread(self.get, project_id, asset_id)
if saved is not None:
return saved
- config = None
- if model_config_id is not None:
- config = await asyncio.to_thread(self.model_configs.agent, str(model_config_id))
- try:
- validate_frame_description_config(config)
- except ValueError as exc:
- raise ProjectError('请选择支持图片输入的对话模型。', code='shot_model_required') from exc
+ config = await asyncio.to_thread(self._model, model_config_id) if model_config_id is not None else None
with TemporaryDirectory(prefix='opendirector-shots-') as temporary:
directory = Path(temporary)
source, analysis = await blocking(self._inspect, project_id, asset_id, session, directory)
if len(analysis['shots']) > MAX_SHOTS:
raise ProjectError('切镜超过 48 个。请截取较短的参考片段再试。', code='shot_count_limit')
- descriptions = [None] * len(analysis['shots'])
- if config is not None:
- if len(descriptions) > MAX_DESCRIBED_SHOTS:
- raise ProjectError('单次最多描述 12 个镜头。可先仅检测切镜。',
- code='shot_model_limit')
- for index, shot in enumerate(analysis['shots']):
- frame = (directory / shot['representative']['path']).read_bytes()
- try:
- row = await describe_shot_frame(config, shot, frame, language=language)
- except (ProjectError, ValueError):
- break
- descriptions[index] = dict(modelId=row['model']['modelId'], **row['description'])
- return await blocking(self._save, project_id, source, analysis, descriptions, directory, session)
+ saved = await blocking(self._save_detection, project_id, source, analysis, directory, session)
+ return saved if config is None else await self._describe_missing(saved, config, session, language)
+
+ async def fill_missing(self, project_id, asset_id, session, *, model_config_id, language):
+ async with self._analysis():
+ await asyncio.to_thread(self._require_session, project_id, session)
+ saved = await asyncio.to_thread(self._require_breakdown, project_id, asset_id)
+ if all(shot.frameSuggestion is not None for shot in saved.data.shots):
+ return saved
+ config = await asyncio.to_thread(self._model, model_config_id)
+ return await self._describe_missing(saved, config, session, language)
+
+ def _read_frame(self, document, shot, session):
+ self._require_session(document.projectId, session)
+ measured = shot.measured
+ stream, asset = self.assets.open_media(document.projectId, measured.representative.assetId)
+ with stream:
+ if asset.fingerprint != measured.representative.fingerprint:
+ raise ProjectError('代表帧内容已变化。', 409, code='storage_unavailable')
+ frame = stream.read()
+ reference = dict(id=shot.id, startPts=measured.startPts, endPts=measured.endPts, timeBase=document.data.timeBase,
+ representative=dict(path=asset.name, pts=measured.representativePts, timeBase=document.data.timeBase))
+ return reference, frame
+
+ def _record_suggestion(self, document, shot, suggestion, session):
+ canvas = CreationCanvas(self.projects)
+ for _ in range(3):
+ current = self._require_breakdown(document.projectId, document.data.source.assetId)
+ if current.id != document.id or current.data.source != document.data.source:
+ break
+ target = next((entry for entry in current.data.shots if entry.id == shot.id), None)
+ if target is None or target.measured != shot.measured:
+ break
+ if target.frameSuggestion is not None:
+ return current
+ updated = target.model_copy(update={'frameSuggestion': suggestion})
+ shots = tuple(updated if entry.id == shot.id else entry for entry in current.data.shots)
+ revised = current.model_copy(update={'data': current.data.model_copy(update={'shots': shots})})
+ command = parse_command(dict(commandId=uuid4(), projectId=current.projectId, type='editor.save',
+ expectedVersions=[dict(objectType='editor_document', id=current.id, revision=current.revision)],
+ payload=dict(document=revised)))
+ apply = partial(canvas.apply, command=command, generated_suggestions={shot.id: suggestion})
+ receipt = self.projects.commit(command, apply, session=session)
+ if receipt.status == 'applied':
+ return self._require_breakdown(current.projectId, current.data.source.assetId)
+ issue = receipt.issues[0]
+ if issue.code != 'revision_conflict':
+ raise ProjectError(issue.message, 409, code=issue.code)
+ raise ProjectError('分镜已变化,请重新加载后继续。', 409, code='revision_conflict')
+
+ async def _describe_missing(self, document, config, session, language):
+ for _ in range(MAX_DESCRIBED_SHOTS):
+ shot = next((entry for entry in document.data.shots if entry.frameSuggestion is None), None)
+ if shot is None:
+ break
+ reference, frame = await asyncio.to_thread(self._read_frame, document, shot, session)
+ try:
+ row = await describe_shot_frame(config, reference, frame, language=language)
+ except (ProjectError, ValueError):
+ return await asyncio.to_thread(self._require_breakdown, document.projectId, document.data.source.assetId)
+ suggestion = ShotFrameSuggestion(modelId=row['model']['modelId'], **row['description'])
+ document = await blocking(self._record_suggestion, document, shot, suggestion, session)
+ return document
diff --git a/packages/core/src/opendirector/domain/creation/editors.py b/packages/core/src/opendirector/domain/creation/editors.py
index 701ff76dc..affdc0b18 100644
--- a/packages/core/src/opendirector/domain/creation/editors.py
+++ b/packages/core/src/opendirector/domain/creation/editors.py
@@ -699,9 +699,10 @@ def evidence(self):
raise ValueError('Last measured shot must end at the analyzed video end')
return self
- def analysis_basis(self):
+ def analysis_basis(self, generated_suggestions=None):
+ generated = generated_suggestions or {}
return (self.source, self.timeBase, self.originPts, self.durationPts,
- tuple((shot.id, shot.measured, shot.frameSuggestion) for shot in self.shots))
+ tuple((shot.id, shot.measured, shot.frameSuggestion or generated.get(shot.id)) for shot in self.shots))
class ShotBreakdownDocument(EditorDocumentBase):
diff --git a/src/canvas/ShotBreakdownEditor.tsx b/src/canvas/ShotBreakdownEditor.tsx
index bcfd37cf3..8726e7516 100644
--- a/src/canvas/ShotBreakdownEditor.tsx
+++ b/src/canvas/ShotBreakdownEditor.tsx
@@ -10,40 +10,19 @@ import {
import { errorMessage, json, request } from "../backend/api.ts";
import { creationClient, objectVersion } from "../backend/creationClient.ts";
import type { ModelConfig } from "../backend/rules.ts";
-import type { AssetRef, EditorDocument } from "../contracts/generated.ts";
+import type {
+ AssetRef,
+ BreakdownShot,
+ ShotBreakdownDocument,
+} from "../contracts/generated.ts";
import { useT } from "../i18n/I18nProvider.tsx";
import { CanvasIcon } from "./CanvasIcon";
import { EditorModal } from "./EditorModal";
import type { CanvasNode } from "./model";
import "./shot-breakdown-editor.css";
-type ShotBreakdown = Extract;
-type FrameSuggestion = NonNullable<
- ShotBreakdown["data"]["shots"][number]["frameSuggestion"]
->;
-
-interface DraftShot {
- id: string;
- measured: {
- startPts: number;
- endPts: number;
- representativePts: number;
- representative: AssetRef;
- };
- frameSuggestion: FrameSuggestion | null;
- edit: ShotBreakdown["data"]["shots"][number]["edit"];
-}
-
-interface DraftData {
- source: AssetRef;
- timeBase: string;
- originPts: number;
- durationPts: number;
- shots: DraftShot[];
-}
-
function validInterval(
- { startPts, endPts }: DraftShot["edit"],
+ { startPts, endPts }: BreakdownShot["edit"],
durationPts: number,
) {
return (
@@ -75,7 +54,7 @@ export function ShotBreakdownEditor({
const readDocument = useCallback(
() =>
client.snapshot?.editorDocuments.find(
- (document): document is ShotBreakdown =>
+ (document): document is ShotBreakdownDocument =>
document.kind === "shot_breakdown" &&
document.data.source.assetId === assetId,
) ?? null,
@@ -83,15 +62,18 @@ export function ShotBreakdownEditor({
);
const savedDocument = useSyncExternalStore(subscribe, readDocument);
const [pending, setPending] = useState<{
- base: ShotBreakdown;
- data: DraftData;
+ base: ShotBreakdownDocument;
+ data: ShotBreakdownDocument["data"];
} | null>(null);
const document = pending?.base ?? savedDocument;
- const draft = useMemo(
- () => pending?.data ?? (savedDocument ? toDraft(savedDocument) : null),
- [pending, savedDocument],
- );
- const [busy, setBusy] = useState(false);
+ const draft = pending?.data ?? savedDocument?.data;
+ const totalShots = savedDocument?.data.shots.length ?? 0;
+ const missing =
+ savedDocument?.data.shots.filter((shot) => !shot.frameSuggestion).length ?? 0;
+ const [operation, setOperation] = useState<
+ "analysis" | "suggestions" | "save" | "reload" | null
+ >(null);
+ const busy = operation !== null;
const [notice, setNotice] = useState("");
const [error, setError] = useState("");
const conflict =
@@ -204,39 +186,53 @@ export function ShotBreakdownEditor({
canSeek && selectedShot != null && draft != null &&
validInterval(selectedShot.edit, draft.durationPts);
- const analyze = async () => {
- setBusy(true);
+ const runAnalysis = async (action: "analysis" | "suggestions") => {
+ const fillMissing = action === "suggestions";
+ if (busy || pending || (fillMissing && (!modelConfigId || !missing))) return;
+ setOperation(action);
setError("");
setNotice("");
try {
- const value = await request(
- path,
+ const value = await request(
+ fillMissing ? `${path}/suggestions` : path,
json("POST", modelConfigId ? { modelConfigId } : {}),
);
- await client.refresh();
- if (!mounted.current) return;
const total = value.data.shots.length;
const described = value.data.shots.filter((shot) => shot.frameSuggestion).length;
- setNotice(
- modelConfigId && described < total
- ? t("editors.shotBreakdown.notice.partial", { described, total })
- : t("editors.shotBreakdown.notice.analyzed"),
- );
+ if (!mounted.current) return;
+ if (fillMissing) {
+ const remaining = total - described;
+ if (remaining === 0) {
+ setNotice(t("editors.shotBreakdown.notice.suggestionsComplete"));
+ } else if (remaining >= missing) {
+ setNotice(t("editors.shotBreakdown.notice.noProgress"));
+ } else {
+ setNotice(t("editors.shotBreakdown.notice.batchPartial", { described, total }));
+ }
+ } else if (modelConfigId && described < total) {
+ setNotice(t("editors.shotBreakdown.notice.partial", { described, total }));
+ } else {
+ setNotice(t("editors.shotBreakdown.notice.analyzed"));
+ }
} catch (failure) {
if (mounted.current)
- setError(
- t("editors.shotBreakdown.error.analyze", {
- reason: errorMessage(failure),
- }),
- );
+ setError(t(fillMissing
+ ? "editors.shotBreakdown.error.suggestions"
+ : "editors.shotBreakdown.error.analyze", { reason: errorMessage(failure) }));
+ }
+ try {
+ await client.refresh();
+ } catch (failure) {
+ if (mounted.current)
+ setError((error) => error || t("editors.shotBreakdown.error.load", { reason: errorMessage(failure) }));
} finally {
- if (mounted.current) setBusy(false);
+ if (mounted.current) setOperation(null);
}
};
const reload = async () => {
if (pending && !window.confirm(t("editors.shotBreakdown.discardReload"))) return;
- setBusy(true);
+ setOperation("reload");
setError("");
try {
await client.refresh();
@@ -255,11 +251,11 @@ export function ShotBreakdownEditor({
}),
);
} finally {
- if (mounted.current) setBusy(false);
+ if (mounted.current) setOperation(null);
}
};
- const editShot = (patch: (shot: DraftShot) => DraftShot) => {
+ const editShot = (patch: (shot: BreakdownShot) => BreakdownShot) => {
if (!document || !draft || !selectedShot) return;
setPending((current) => {
const data = current?.data ?? draft;
@@ -302,26 +298,13 @@ export function ShotBreakdownEditor({
setError(t("editors.shotBreakdown.error.interval", { number: invalidShot + 1 }));
return;
}
- setBusy(true);
+ setOperation("save");
setError("");
setNotice("");
try {
- const revised: ShotBreakdown = {
- ...document,
- data: {
- ...document.data,
- ...draft,
- shots: draft.shots.map((shot) => ({
- id: shot.id,
- measured: shot.measured,
- frameSuggestion: shot.frameSuggestion,
- edit: shot.edit,
- })),
- },
- };
await client.command(
"editor.save",
- { document: revised },
+ { document: { ...document, data: draft } },
[objectVersion("editor_document", document)],
);
if (!mounted.current) return;
@@ -335,7 +318,7 @@ export function ShotBreakdownEditor({
}),
);
} finally {
- if (mounted.current) setBusy(false);
+ if (mounted.current) setOperation(null);
}
};
@@ -345,6 +328,34 @@ export function ShotBreakdownEditor({
onClose();
};
+ const modelPicker = (
+
+ );
+
return (
{t("editors.shotBreakdown.empty.title")}
{t("editors.shotBreakdown.empty.body")}
-
+ {modelPicker}
{modelConfigId
? t("editors.shotBreakdown.model.selectedHint")
@@ -409,7 +400,7 @@ export function ShotBreakdownEditor({
className="cw-domain-primary"
aria-label={t("editors.shotBreakdown.analyzeAria")}
disabled={busy}
- onClick={() => void analyze()}
+ onClick={() => void runAnalysis("analysis")}
>
{busy
@@ -441,7 +432,39 @@ export function ShotBreakdownEditor({
{t("editors.shotBreakdown.summary.timeBase")} · {draft.timeBase}
+
+ {t(missing
+ ? "editors.shotBreakdown.summary.suggestionsMissing"
+ : "editors.shotBreakdown.summary.suggestionsComplete", {
+ described: totalShots - missing, total: totalShots, missing,
+ })}
+
+ {missing > 0 && (
+
+ {agentModels.length > 0 && (
+
+ {modelPicker}
+
+
+ )}
+
+ {t(!agentModels.length
+ ? "editors.shotBreakdown.model.configure"
+ : pending
+ ? "editors.shotBreakdown.suggestion.saveFirst"
+ : "editors.shotBreakdown.suggestion.batchHint")}
+
+
+ )}
{notice && (
{notice}
@@ -854,23 +877,6 @@ export function ShotBreakdownEditor({
);
}
-function toDraft(document: ShotBreakdown): DraftData {
- return {
- source: document.data.source,
- timeBase: document.data.timeBase,
- originPts: document.data.originPts,
- durationPts: document.data.durationPts,
- shots: document.data.shots.map((shot) => ({
- id: shot.id,
- measured: { ...shot.measured },
- frameSuggestion: shot.frameSuggestion
- ? { ...shot.frameSuggestion }
- : null,
- edit: { ...shot.edit },
- })),
- };
-}
-
function parseTimeBase(value: string): number | null {
const match = /^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(value);
if (!match) return null;
diff --git a/src/canvas/shot-breakdown-editor.css b/src/canvas/shot-breakdown-editor.css
index ce275d018..1b2448917 100644
--- a/src/canvas/shot-breakdown-editor.css
+++ b/src/canvas/shot-breakdown-editor.css
@@ -41,6 +41,18 @@
color: #a992b9;
font-size: 10px;
}
+.cw-shot-breakdown-suggestions .cw-domain-row {
+ align-items: flex-end;
+ margin: 0 0 4px;
+}
+.cw-shot-breakdown-suggestions .cw-domain-field {
+ max-width: 100%;
+ min-width: min(200px, 100%);
+ margin: 0;
+}
+.cw-shot-breakdown-suggestions .cw-domain-note {
+ margin: 0;
+}
.cw-shot-breakdown-notice,
.cw-shot-breakdown-conflict {
margin: 0;
diff --git a/src/i18n/messages/en-US/editors.ts b/src/i18n/messages/en-US/editors.ts
index a5d9416bd..1937eda85 100644
--- a/src/i18n/messages/en-US/editors.ts
+++ b/src/i18n/messages/en-US/editors.ts
@@ -404,10 +404,13 @@ export const editors = {
"editors.shotBreakdown.model.label": "Frame suggestion model (optional)",
"editors.shotBreakdown.model.aria": "Frame suggestion model",
"editors.shotBreakdown.model.detectionOnly": "Detection only · no model",
+ "editors.shotBreakdown.model.choose": "Choose a model",
+ "editors.shotBreakdown.model.configure":
+ "To add suggestions, configure a chat model that accepts images in Settings, then reopen the breakdown.",
"editors.shotBreakdown.model.defaultHint":
"Only cut detection runs. No frame is sent to a model.",
"editors.shotBreakdown.model.selectedHint":
- "The selected model receives one representative JPEG per shot and returns a single-frame suggestion. Detection remains the measured source of truth.",
+ "Local detection runs first. The selected model then receives up to 12 representative JPEGs, one per shot.",
"editors.shotBreakdown.analyze": "Analyze shots",
"editors.shotBreakdown.analyzeAria": "Analyze shots",
"editors.shotBreakdown.analyzing": "Analyzing…",
@@ -421,7 +424,9 @@ export const editors = {
},
"editors.shotBreakdown.summary.duration": "Duration",
"editors.shotBreakdown.summary.timeBase": "Time base",
- "editors.shotBreakdown.badge.detected": "Detected",
+ "editors.shotBreakdown.summary.suggestionsMissing": "Model suggestions: {described}/{total} · {missing} missing",
+ "editors.shotBreakdown.summary.suggestionsComplete": "Model suggestions: {described}/{total} · complete",
+ "editors.shotBreakdown.badge.detected": "Detected locally",
"editors.shotBreakdown.badge.model": "Model suggestion",
"editors.shotBreakdown.badge.draft": "Draft",
"editors.shotBreakdown.badge.joined": "Cut removed",
@@ -449,6 +454,12 @@ export const editors = {
"Go to representative frame",
"editors.shotBreakdown.suggestion.title": "Model suggestion · {model}",
"editors.shotBreakdown.suggestion.titleEmpty": "Model suggestion",
+ "editors.shotBreakdown.suggestion.fill": "Fill missing suggestions",
+ "editors.shotBreakdown.suggestion.filling": "Filling suggestions…",
+ "editors.shotBreakdown.suggestion.batchHint":
+ "Each run sends one saved frame per missing suggestion to the selected model, up to 12 frames.",
+ "editors.shotBreakdown.suggestion.saveFirst":
+ "Save your edits with “Save breakdown” before filling suggestions.",
"editors.shotBreakdown.suggestion.note":
"Model inference about this single frame, not a detected fact or your edit.",
"editors.shotBreakdown.suggestion.subject": "Subject",
@@ -480,6 +491,11 @@ export const editors = {
"editors.shotBreakdown.notice.analyzed": "Shots detected and saved.",
"editors.shotBreakdown.notice.partial":
"Shots saved. The model completed {described} of {total} descriptions. You can edit every shot.",
+ "editors.shotBreakdown.notice.noProgress":
+ "No new suggestions were saved. Try again later or choose another model.",
+ "editors.shotBreakdown.notice.batchPartial":
+ "Suggestions saved for {described} of {total} shots. Run another batch to continue.",
+ "editors.shotBreakdown.notice.suggestionsComplete": "All shots now have model suggestions.",
"editors.shotBreakdown.notice.reloaded": "Loaded the latest saved breakdown.",
"editors.shotBreakdown.notice.empty": "No saved breakdown exists now.",
"editors.shotBreakdown.notice.saved": "Shot breakdown saved.",
@@ -495,6 +511,7 @@ export const editors = {
"Could not read the shot breakdown: {reason}",
"editors.shotBreakdown.error.analyze":
"Could not analyze the video: {reason}",
+ "editors.shotBreakdown.error.suggestions": "Could not fill missing suggestions: {reason}",
"editors.shotBreakdown.error.save":
"Could not save the shot breakdown: {reason}",
"editors.shotBreakdown.error.interval":
diff --git a/src/i18n/messages/zh-CN/editors.ts b/src/i18n/messages/zh-CN/editors.ts
index b2ee8ecec..5bfe3c9bd 100644
--- a/src/i18n/messages/zh-CN/editors.ts
+++ b/src/i18n/messages/zh-CN/editors.ts
@@ -368,10 +368,13 @@ export const editors = {
"editors.shotBreakdown.model.label": "单帧建议模型(可选)",
"editors.shotBreakdown.model.aria": "单帧建议模型",
"editors.shotBreakdown.model.detectionOnly": "仅检测 · 不使用模型",
+ "editors.shotBreakdown.model.choose": "选择模型",
+ "editors.shotBreakdown.model.configure":
+ "如需生成建议,请在设置中添加支持图片输入的对话模型,再重新打开分镜。",
"editors.shotBreakdown.model.defaultHint":
"只运行切镜检测,不向任何模型发送画面。",
"editors.shotBreakdown.model.selectedHint":
- "所选模型会为每个镜头接收一张代表帧 JPEG,并返回单帧建议。检测结果仍是实际测量的依据。",
+ "先在本地检测切点,再将最多 12 张代表帧发给所选模型,每镜一张 JPEG。",
"editors.shotBreakdown.analyze": "分析分镜",
"editors.shotBreakdown.analyzeAria": "分析分镜",
"editors.shotBreakdown.analyzing": "正在分析…",
@@ -382,7 +385,9 @@ export const editors = {
"editors.shotBreakdown.summary.draftShots": "{count} 个草稿镜头",
"editors.shotBreakdown.summary.duration": "总时长",
"editors.shotBreakdown.summary.timeBase": "时间基",
- "editors.shotBreakdown.badge.detected": "检测结果",
+ "editors.shotBreakdown.summary.suggestionsMissing": "模型建议 {described}/{total} · 还缺 {missing} 条",
+ "editors.shotBreakdown.summary.suggestionsComplete": "模型建议 {described}/{total} · 已齐全",
+ "editors.shotBreakdown.badge.detected": "本地检测",
"editors.shotBreakdown.badge.model": "模型建议",
"editors.shotBreakdown.badge.draft": "草稿",
"editors.shotBreakdown.badge.joined": "已去掉切点",
@@ -407,6 +412,11 @@ export const editors = {
"editors.shotBreakdown.locate.representativeAria": "定位到代表帧",
"editors.shotBreakdown.suggestion.title": "模型建议 · {model}",
"editors.shotBreakdown.suggestion.titleEmpty": "模型建议",
+ "editors.shotBreakdown.suggestion.fill": "补全缺失建议",
+ "editors.shotBreakdown.suggestion.filling": "正在补全建议…",
+ "editors.shotBreakdown.suggestion.batchHint":
+ "每次从缺少建议的镜头中取最多 12 张已保存的代表帧,发给所选模型,每镜一张。",
+ "editors.shotBreakdown.suggestion.saveFirst": "请先点击“保存分镜”保存修改,再补全建议。",
"editors.shotBreakdown.suggestion.note":
"这是模型对该单帧的推断,不是检测事实,也不是你的编辑。",
"editors.shotBreakdown.suggestion.subject": "主体",
@@ -438,6 +448,9 @@ export const editors = {
"editors.shotBreakdown.notice.analyzed": "分镜已检测并保存。",
"editors.shotBreakdown.notice.partial":
"分镜已保存。模型完成了 {described}/{total} 条描述,每个镜头仍可编辑。",
+ "editors.shotBreakdown.notice.noProgress": "这次没有新增建议。可以稍后再试,也可以换一个模型。",
+ "editors.shotBreakdown.notice.batchPartial": "已有 {described}/{total} 个镜头保存了建议,可继续补全下一批。",
+ "editors.shotBreakdown.notice.suggestionsComplete": "所有镜头都已有模型建议。",
"editors.shotBreakdown.notice.reloaded": "已加载最新保存的分镜。",
"editors.shotBreakdown.notice.empty": "当前没有已保存的分镜。",
"editors.shotBreakdown.notice.saved": "分镜已保存。",
@@ -448,6 +461,7 @@ export const editors = {
"editors.shotBreakdown.discardClose": "丢弃未保存的修改,关闭分镜?",
"editors.shotBreakdown.error.load": "无法读取分镜:{reason}",
"editors.shotBreakdown.error.analyze": "无法分析视频:{reason}",
+ "editors.shotBreakdown.error.suggestions": "无法补全缺失建议:{reason}",
"editors.shotBreakdown.error.save": "无法保存分镜:{reason}",
"editors.shotBreakdown.error.interval":
"镜头 {number} 的起止必须是视频范围内的整数 PTS,且终点必须晚于起点。",
diff --git a/tests/test_creation_shots.py b/tests/test_creation_shots.py
index f3b7d5f12..942bbd041 100644
--- a/tests/test_creation_shots.py
+++ b/tests/test_creation_shots.py
@@ -17,6 +17,7 @@
from capabilities import requires_ffmpeg
from opendirector.agent.tools import AgentTools
from opendirector.application import creation_shots
+from opendirector.domain.creation.commands import parse_command
from opendirector.domain.projects import ProjectError
from opendirector.infrastructure.creation_projects import CreationProjects
from opendirector.infrastructure.local_projects import LocalProjects
@@ -25,8 +26,8 @@
@requires_ffmpeg()
-@pytest.mark.parametrize('model_failure', [None, 'rate-limit', 'malformed-content'],
- ids=['model-ok', 'provider-429', 'bad-provider-content'])
+@pytest.mark.parametrize('model_failure', [None, 'rate-limit', 'malformed-content', 'detect-only'],
+ ids=['model-ok', 'provider-429', 'bad-provider-content', 'detect-only'])
def test_shot_evidence_and_interleaved_user_agent_edits(tmp_path, monkeypatch, model_failure):
media = tmp_path / 'input.mp4'
subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'color=red:s=32x32:r=24:d=1',
@@ -49,12 +50,16 @@ def scan(video, output):
return dict(source=dict(timeBase='1/24', originPts=900, sha256=sha256(video.read_bytes()).hexdigest()), shots=shots)
requests = []
+ during_inference = None
+ rate_limited = False
def model_response(request):
payload = json.loads(request.content)
assert payload['model'] == 'vision-fixture'
requests.append(payload)
- if len(requests) == 2 and model_failure == 'rate-limit':
+ if during_inference is not None:
+ during_inference()
+ if rate_limited or (len(requests) == 2 and model_failure == 'rate-limit'):
return httpx.Response(429, json={'error': {'code': 'rate_limit'}})
description = json.dumps(dict(subject='Red square', scene='Plain frame', framing='Full frame'))
content = [{'text': description}] if len(requests) == 2 and model_failure == 'malformed-content' else description
@@ -91,9 +96,13 @@ def version(document):
asset = command('asset.import', dict(uploadHandle=handle, name='input.mp4', expectedKind='video'))['changed'][0]['id']
route = f'{path}/assets/{asset}/shot-breakdown'
assert client.get(route).json() is None
+ resume = route + '/suggestions'
+ selected_model = dict(modelConfigId=model['id'])
+ assert client.post(resume, json=selected_model).status_code == 404
denied = client.post(route, json={}, headers={'X-OpenDirector-Session': str(uuid4())})
assert denied.status_code == 409 and not calls
- created = client.post(route, json=dict(modelConfigId=model['id']))
+ detect_only = model_failure == 'detect-only'
+ created = client.post(route, json={} if detect_only else selected_model)
assert created.status_code == 200, created.text
original = created.json()
assert original['data']['originPts'] == 900
@@ -101,9 +110,13 @@ def version(document):
shot, *other_shots = original['data']['shots']
assert len(other_shots) == 2
assert all('joinPrevious' not in row['edit'] for row in original['data']['shots'])
- assert shot['frameSuggestion']['modelId'] == 'vision-fixture'
+ if detect_only:
+ assert shot['frameSuggestion'] is None
+ else:
+ assert shot['frameSuggestion']['modelId'] == 'vision-fixture'
assert all((row['frameSuggestion'] is None) == bool(model_failure) for row in other_shots)
- assert len(requests) == (2 if model_failure else 3)
+ initial_calls = 0 if detect_only else 2 if model_failure else 3
+ assert len(requests) == initial_calls
representative = shot['measured']['representative']['assetId']
assert client.get(path + '/assets/' + representative + '/content').content == jpg.getvalue()
deletion = client.post(path + '/asset-delete-preview', json=dict(assetIds=[asset, representative],
@@ -146,12 +159,59 @@ def version(document):
assert updated['frameSuggestion'] == shot['frameSuggestion']
assert updated['edit'] == dict(startPts=1, endPts=7, description='User correction and Agent review')
tampered = deepcopy(reopened)
- tampered['data']['shots'][0]['frameSuggestion']['subject'] = 'Overwritten'
+ tampered['data']['shots'][0]['frameSuggestion'] = dict(modelId='fake', subject='Overwritten',
+ scene='Fake', framing='Fake')
rejected = command('editor.save', dict(document=tampered), version(reopened))
assert rejected['issues'][0]['code'] == 'shot_evidence_immutable'
assert client.post(route, json=dict(modelConfigId=model['id'])).json() == reopened
assert len(calls) == 1
- assert len(requests) == (2 if model_failure else 3)
+ assert len(requests) == initial_calls
+ assert client.post(resume, json={}).status_code == 422
+ assert client.post(resume, json=selected_model, headers={'X-OpenDirector-Session': str(uuid4())}).status_code == 409
+ assert len(requests) == initial_calls
+ if model_failure == 'rate-limit':
+ rate_limited = True
+ assert client.post(resume, json=selected_model).json() == reopened
+ assert len(requests) == initial_calls + 1
+ rate_limited = False
+ calls_before_recovery = len(requests)
+
+ def save_during_inference():
+ nonlocal during_inference
+ during_inference = None
+ concurrent = deepcopy(reopened)
+ concurrent['data']['shots'][0]['edit']['description'] = 'Edited during inference'
+ edit = parse_command(dict(commandId=uuid4(), projectId=project_id, type='editor.save',
+ payload=dict(document=concurrent), expectedVersions=version(reopened)))
+ assert CreationProjects(local).execute(edit, session=session).status == 'applied'
+
+ during_inference = save_during_inference
+ if detect_only:
+ monkeypatch.setattr(creation_shots, 'MAX_DESCRIBED_SHOTS', 2)
+ resumed = client.post(resume, json=selected_model)
+ assert resumed.status_code == 200, resumed.text
+ if detect_only:
+ assert [bool(s['frameSuggestion']) for s in resumed.json()['data']['shots']] == [True, True, False]
+ resumed = client.post(resume, json=selected_model)
+ resumed.raise_for_status()
+ completed = resumed.json()
+ after = completed['data']['shots']
+ assert [s['measured'] for s in after] == [s['measured'] for s in reopened['data']['shots']]
+ expected_edits = [deepcopy(s['edit']) for s in reopened['data']['shots']]
+ if model_failure:
+ expected_edits[0]['description'] = 'Edited during inference'
+ assert [s['edit'] for s in after] == expected_edits
+ assert all(s['frameSuggestion']['modelId'] == 'vision-fixture' for s in after)
+ missing_ids = [s['id'] for s in reopened['data']['shots'] if s['frameSuggestion'] is None]
+ sent_ids = [r['messages'][1]['content'][0]['text'].split(':')[0].split()[-1] for r in requests[calls_before_recovery:]]
+ assert sent_ids == missing_ids
+ for old, new in zip(reopened['data']['shots'], after, strict=True):
+ if old['frameSuggestion']:
+ assert old['frameSuggestion'] == new['frameSuggestion']
+ assert client.post(resume, json=selected_model).json() == completed
+ assert client.get(route).json() == completed
+ assert len(requests) == calls_before_recovery + len(missing_ids)
+ assert len(calls) == 1
def test_cancellation_keeps_scan_files_and_slot_until_worker_stops(monkeypatch):
From 1b1c9910a19256ea2a645de8c8c4c07f15d33e33 Mon Sep 17 00:00:00 2001
From: Dragonborn <1078757180@qq.com>
Date: Tue, 1 Dec 2026 00:59:15 +0800
Subject: [PATCH 4/9] Stop automatic batch replay after a model request
---
apps/api/src/opendirector_api/localization.py | 1 +
.../application/creation_shots.py | 32 ++++++++++++-------
tests/test_creation_shots.py | 15 ++++++++-
3 files changed, 35 insertions(+), 13 deletions(-)
diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py
index aa9d5b54b..2ee12906c 100644
--- a/apps/api/src/opendirector_api/localization.py
+++ b/apps/api/src/opendirector_api/localization.py
@@ -99,6 +99,7 @@
"shot_count_limit": "The video has more than 48 shots. Analyze a shorter excerpt.",
"shot_model_required": "Select a chat model that accepts images.",
"shot_breakdown_missing": "Detect the shots in this video first.",
+ "shot_suggestions_interrupted": "A model request was sent before the project session expired. Reopen the project to continue filling missing suggestions.",
"moss_speech_text": "Enter the text to read aloud.",
"moss_speech_voice": "Enter a Voice ID available to your MOSS account.",
"moss_speech_reference": "MOSS speech generation does not accept references. Enter speech text and a Voice ID.",
diff --git a/packages/core/src/opendirector/application/creation_shots.py b/packages/core/src/opendirector/application/creation_shots.py
index 4f7413859..3357d36db 100644
--- a/packages/core/src/opendirector/application/creation_shots.py
+++ b/packages/core/src/opendirector/application/creation_shots.py
@@ -173,15 +173,23 @@ def _record_suggestion(self, document, shot, suggestion, session):
raise ProjectError('分镜已变化,请重新加载后继续。', 409, code='revision_conflict')
async def _describe_missing(self, document, config, session, language):
- for _ in range(MAX_DESCRIBED_SHOTS):
- shot = next((entry for entry in document.data.shots if entry.frameSuggestion is None), None)
- if shot is None:
- break
- reference, frame = await asyncio.to_thread(self._read_frame, document, shot, session)
- try:
- row = await describe_shot_frame(config, reference, frame, language=language)
- except (ProjectError, ValueError):
- return await asyncio.to_thread(self._require_breakdown, document.projectId, document.data.source.assetId)
- suggestion = ShotFrameSuggestion(modelId=row['model']['modelId'], **row['description'])
- document = await blocking(self._record_suggestion, document, shot, suggestion, session)
- return document
+ dispatched = False
+ try:
+ for _ in range(MAX_DESCRIBED_SHOTS):
+ shot = next((entry for entry in document.data.shots if entry.frameSuggestion is None), None)
+ if shot is None:
+ break
+ reference, frame = await asyncio.to_thread(self._read_frame, document, shot, session)
+ dispatched = True
+ try:
+ row = await describe_shot_frame(config, reference, frame, language=language)
+ except (ProjectError, ValueError):
+ return await asyncio.to_thread(self._require_breakdown, document.projectId, document.data.source.assetId)
+ suggestion = ShotFrameSuggestion(modelId=row['model']['modelId'], **row['description'])
+ document = await blocking(self._record_suggestion, document, shot, suggestion, session)
+ return document
+ except ProjectError as exc:
+ if exc.code != 'session_expired' or not dispatched:
+ raise
+ raise ProjectError('模型请求已发出,但工程会话已过期。重新打开工程后可继续补全缺失建议。',
+ 409, code='shot_suggestions_interrupted') from exc
diff --git a/tests/test_creation_shots.py b/tests/test_creation_shots.py
index 942bbd041..2eb3efc6b 100644
--- a/tests/test_creation_shots.py
+++ b/tests/test_creation_shots.py
@@ -167,13 +167,26 @@ def version(document):
assert len(calls) == 1
assert len(requests) == initial_calls
assert client.post(resume, json={}).status_code == 422
- assert client.post(resume, json=selected_model, headers={'X-OpenDirector-Session': str(uuid4())}).status_code == 409
+ denied = client.post(resume, json=selected_model, headers={'X-OpenDirector-Session': str(uuid4())})
+ assert denied.status_code == 409 and denied.json()['code'] == 'session_expired'
assert len(requests) == initial_calls
if model_failure == 'rate-limit':
rate_limited = True
assert client.post(resume, json=selected_model).json() == reopened
assert len(requests) == initial_calls + 1
rate_limited = False
+ if detect_only:
+ def expire_after_dispatch():
+ nonlocal during_inference
+ during_inference = None
+ with local.transaction() as db:
+ db.execute('UPDATE sessions SET expires=0 WHERE id=?', (session,))
+
+ during_inference = expire_after_dispatch
+ interrupted = client.post(resume, json=selected_model)
+ assert interrupted.status_code == 409 and interrupted.json()['code'] == 'shot_suggestions_interrupted'
+ assert len(requests) == 1
+ assert client.post(path + '/open').json()['editorDocuments'][0] == reopened
calls_before_recovery = len(requests)
def save_during_inference():
From 798970a82bad0a67c9b3ade4077fdf4ee17dba37 Mon Sep 17 00:00:00 2001
From: Dragonborn <1078757180@qq.com>
Date: Tue, 1 Dec 2026 23:17:52 +0800
Subject: [PATCH 5/9] Make shot corrections editable and recover interrupted
analysis atomically
---
apps/api/src/opendirector_api/creation.py | 22 +-
docs/guides/user-guide.md | 4 +-
docs/guides/user-guide.zh-CN.md | 4 +-
.../application/creation_shots.py | 110 ++--
.../application/shot_descriptions.py | 14 +-
.../opendirector/domain/creation/editors.py | 12 +
.../src/opendirector/domain/generation.py | 4 +
.../infrastructure/creation_uploads.py | 22 +
.../integrations/generation_errors.py | 4 +-
src/backend/api.ts | 10 +-
src/canvas/EditorModal.tsx | 3 +
src/canvas/NodeSelectionToolbar.tsx | 10 +-
src/canvas/ShotBreakdownDetail.tsx | 219 ++++++++
src/canvas/ShotBreakdownEditor.tsx | 468 +++---------------
src/canvas/shot-breakdown-editor.css | 8 +
src/canvas/shotDraft.ts | 59 +++
src/canvas/workspace/WorkspaceView.tsx | 3 +-
src/contracts/creation.schema.json | 65 +++
src/contracts/generated.ts | 12 +
src/i18n/messages/en-US/canvasShell.ts | 2 +
src/i18n/messages/en-US/editors.ts | 17 +-
src/i18n/messages/zh-CN/canvasShell.ts | 2 +
src/i18n/messages/zh-CN/editors.ts | 16 +-
tests/sessionLease.test.ts | 11 +-
tests/shotDraft.test.ts | 54 ++
tests/test_creation_shots.py | 177 ++++++-
26 files changed, 878 insertions(+), 454 deletions(-)
create mode 100644 src/canvas/ShotBreakdownDetail.tsx
create mode 100644 src/canvas/shotDraft.ts
create mode 100644 tests/shotDraft.test.ts
diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py
index 0e02d61c8..d94ac33db 100644
--- a/apps/api/src/opendirector_api/creation.py
+++ b/apps/api/src/opendirector_api/creation.py
@@ -454,17 +454,27 @@ def describe_asset(project_id: UUID, asset_id: UUID):
def read_shots(project_id: UUID, asset_id: UUID):
return shots.get(project_id, asset_id)
+ def shot_result(response, result):
+ document, stop = result
+ if stop is not None:
+ response.headers['X-OpenDirector-Shot-Stop'] = stop
+ return document
+
@router.post('/projects/{project_id}/assets/{asset_id}/shot-breakdown', response_model=ShotBreakdownDocument)
- async def analyze_shots(project_id: UUID, asset_id: UUID, value: ShotBreakdownRequest, request: Request,
+ async def analyze_shots(project_id: UUID, asset_id: UUID, value: ShotBreakdownRequest, request: Request, response: Response,
x_opendirector_session: UUID = Header()):
- return await shots.create(project_id, asset_id, str(x_opendirector_session), model_config_id=value.modelConfigId,
- language='en-US' if wants_english(request) else 'zh-CN')
+ result = await shots.create(
+ project_id, asset_id, str(x_opendirector_session), model_config_id=value.modelConfigId,
+ language='en-US' if wants_english(request) else 'zh-CN')
+ return shot_result(response, result)
@router.post('/projects/{project_id}/assets/{asset_id}/shot-breakdown/suggestions', response_model=ShotBreakdownDocument)
- async def fill_shot_suggestions(project_id: UUID, asset_id: UUID, value: ShotSuggestionsRequest, request: Request,
+ async def fill_shot_suggestions(project_id: UUID, asset_id: UUID, value: ShotSuggestionsRequest, request: Request, response: Response,
x_opendirector_session: UUID = Header()):
- return await shots.fill_missing(project_id, asset_id, str(x_opendirector_session), model_config_id=value.modelConfigId,
- language='en-US' if wants_english(request) else 'zh-CN')
+ result = await shots.fill_missing(
+ project_id, asset_id, str(x_opendirector_session), model_config_id=value.modelConfigId,
+ language='en-US' if wants_english(request) else 'zh-CN')
+ return shot_result(response, result)
@router.get('/projects/{project_id}/assets/{asset_id}/thumbnail')
def thumbnail(project_id: UUID, asset_id: UUID):
diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md
index 3860c8be8..df269467d 100644
--- a/docs/guides/user-guide.md
+++ b/docs/guides/user-guide.md
@@ -225,9 +225,9 @@ Install the optional analyzer in the same Python environment as OpenDirector wit
Local detection supports videos up to 120 seconds and 48 detected shots. To add suggestions about the subject, scene, and framing, choose a chat model that accepts images. You can choose one before **Analyze shots** or add suggestions to a saved breakdown later. Each run sends the selected model one representative JPEG per shot, for up to 12 shots.
-The summary shows how many shots still need a suggestion. Save any draft edits, choose a model, and click **Fill missing suggestions** to process the next batch using the saved frames. If the model stops early, for example because of a rate limit, you can pick up where it stopped, even after reopening the video. Each batch keeps the detected cuts, previous suggestions, and your saved edits.
+The summary shows how many shots still need a suggestion. Save any draft edits, choose a model, and click **Fill missing suggestions** to process the next batch using the saved frames. The editor tells you when the model rate-limits a request or returns an unreadable answer. After resolving the problem, click **Fill missing suggestions** to resume, even after reopening the video. Each batch keeps the detected cuts, previous suggestions, and your saved edits.
-Compare the detected range with the draft in the source video, then use **Save breakdown** to save your edited ranges and descriptions. The detected boundaries, representative frames, and model suggestions remain available when you reopen the same video. Ranges use normalized source timestamps with an exclusive end. To remove an extra cut, select the shot just after it and choose **Join previous shot** when the two draft ranges touch. Use **Restore cut** to bring the cut back.
+Compare the detected range with the draft in the source video, then use **Save breakdown** to save your edited ranges and descriptions. The detected boundaries, representative frames, and model suggestions remain available when you reopen the same video. Ranges use normalized source timestamps with an exclusive end. To remove an extra cut, select the shot just after it and choose **Join previous shot** when the two draft ranges touch. Use **Restore cut** to bring the cut back. If detection missed a cut, pause the source video at the boundary and choose **Split at playhead**. You can write a different description for each draft segment. A manual split uses the existing video and adds no model calls.
Save your changes before asking the assistant to continue editing. If the assistant saves a newer version while you have unsaved changes, the editor keeps your draft and asks before discarding it on reload.
diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md
index 3bee9b647..45e1b150c 100644
--- a/docs/guides/user-guide.zh-CN.md
+++ b/docs/guides/user-guide.zh-CN.md
@@ -225,9 +225,9 @@ Codex 网页检索引用在具有匹配来源时显示为编号链接;复制
本地检测支持 120 秒以内、最多 48 个镜头的视频。如果需要主体、场景和景别建议,可在点击**分析分镜**前选择支持图片输入的对话模型,也可以先保存检测结果,以后再选模型。每次最多处理 12 个镜头,每镜向所选模型发送一张 JPEG 代表帧。
-分镜顶部会显示还有多少镜头缺少建议。先保存草稿修改,再选择模型,点击**补全缺失建议**,就能用已有的代表帧处理下一批。如果遇到模型限流等中断,重新打开视频后也能从缺少建议的镜头继续。每次补全都会保留检测区间、已有建议和你保存的修改。
+分镜顶部会显示还有多少镜头缺少建议。先保存草稿修改,再选择模型,点击**补全缺失建议**,就能用已有的代表帧处理下一批。遇到模型限流或返回内容无法读取时,编辑器会提示原因。问题解决后,点击**补全缺失建议**即可接着处理,重开视频后也可以继续。每次补全都会保留检测区间、已有建议和你保存的修改。
-在原片里对照检测区间和草稿边界,修改后点击**保存分镜**。重开同一个视频仍可查看原检测区间、代表帧和模型建议。区间使用源视频的归一化时间戳,终点不含在区间内。多切了一刀时,选中切点后的镜头。若两段草稿首尾相接,点击**与上一镜合并**。用**恢复此切点**可加回切点。
+在原片里对照检测区间和草稿边界,修改后点击**保存分镜**。重开同一个视频仍可查看原检测区间、代表帧和模型建议。区间使用源视频的归一化时间戳,终点不含在区间内。多切了一刀时,选中切点后的镜头。若两段草稿首尾相接,点击**与上一镜合并**。用**恢复此切点**可加回切点。漏切了一刀时,在原视频里暂停到要切的位置,点击**在播放位置拆分**,就能给切点两边各写一段描述。手动拆分直接使用原片,不消耗模型额度。
让助手接着编辑前,先保存自己的修改。如果助手保存了新版本,编辑器会保留你尚未保存的草稿,重新加载前会请你确认是否丢弃。
diff --git a/packages/core/src/opendirector/application/creation_shots.py b/packages/core/src/opendirector/application/creation_shots.py
index 3357d36db..15497ecfd 100644
--- a/packages/core/src/opendirector/application/creation_shots.py
+++ b/packages/core/src/opendirector/application/creation_shots.py
@@ -9,13 +9,16 @@
from opendirector.application.creation_assets import CreationAssets
from opendirector.application.creation_canvas import CreationCanvas, asset_ref
-from opendirector.application.creation_tool_assets import CreationToolAssets
-from opendirector.application.shot_descriptions import describe_shot_frame, validate_frame_description_config
+from opendirector.application.shot_descriptions import InvalidShotDescription, describe_shot_frame, validate_frame_description_config
+from opendirector.domain.creation.assets import Asset, AssetProvenance
from opendirector.domain.creation.commands import parse_command
from opendirector.domain.creation.editors import ShotFrameSuggestion
+from opendirector.domain.generation import GenerationError, ProviderProtocolError
from opendirector.domain.projects import ProjectError
from opendirector.media.async_work import blocking
from opendirector.media.shot_detection import DEFAULT_MAX_DURATION_SECONDS, inspect_video_shots
+from opendirector.ports.files import AssetFileWrite
+from opendirector.ports.gateway import gateway
MAX_SHOTS = 48
MAX_DESCRIBED_SHOTS = 12
@@ -26,7 +29,6 @@ def __init__(self, projects, model_configs):
self.projects = projects
self.model_configs = model_configs
self.assets = CreationAssets(projects)
- self.outputs = CreationToolAssets(projects)
self.analysis_slot = asyncio.Lock()
def get(self, project_id, asset_id):
@@ -72,29 +74,72 @@ def _inspect(self, project_id, asset_id, session, directory):
def _save_detection(self, project_id, source, analysis, directory, session):
self._require_session(project_id, session)
document_id = uuid5(source.id, 'reference-shot-breakdown')
+ guard = self.assets.uploads.lock(project_id, document_id)
+ try:
+ guard.acquire()
+ except TimeoutError as exc:
+ raise ProjectError('正在保存这段参考视频的分镜。', 409, code='shot_analysis_busy') from exc
+ try:
+ slots = tuple(uuid5(document_id, f'staged-frame:{i}') for i in range(MAX_SHOTS))
+ if not self.assets.uploads.discard_outputs(project_id, slots):
+ raise ProjectError('分镜文件提交尚未恢复。', 409, code='storage_unavailable')
+ saved = self.get(project_id, source.id)
+ if saved is not None:
+ return saved
+ return self._publish_detection(project_id, source, analysis, directory, session, document_id, slots)
+ finally:
+ guard.release()
+
+ def _publish_detection(self, project_id, source, analysis, directory, session, document_id, slots):
source_ref = asset_ref(source)
- shots = []
- for shot in analysis['shots']:
- frame = shot['representative']
- start, end = shot['startPts'], shot['endPts']
- frame_id = uuid5(document_id, f"{shot['id']}:{frame['pts']}")
- path = directory / frame['path']
- imported = self.outputs.import_file(project_id, frame_id, f"{source.fingerprint[7:15]}-{path.name}",
- path.read_bytes(), session, sources=(source_ref,))
- image = self.assets.get(project_id, imported['id'])
- shots.append(dict(id=shot['id'], measured=dict(startPts=start, endPts=end,
- representativePts=frame['pts'], representative=asset_ref(image)),
- edit=dict(startPts=start, endPts=end, description='')))
- video = analysis['source']
- command = parse_command(dict(commandId=uuid5(document_id, 'create'), projectId=project_id,
- type='editor.create', payload=dict(document=dict(id=document_id, projectId=project_id,
- kind='shot_breakdown', data=dict(source=source_ref, timeBase=video['timeBase'],
- originPts=video['originPts'], durationPts=shots[-1]['measured']['endPts'], shots=shots)))))
- receipt = self.projects.execute(command, session=session)
- if receipt.status != 'applied':
+ provenance = AssetProvenance(source='manual', sources=(source_ref,))
+ existing = {asset.id: asset for asset in self.assets.list(project_id)}
+ shots, images, writes, staged = [], [], [], []
+ try:
+ for index, shot in enumerate(analysis['shots']):
+ frame = shot['representative']
+ start, end = shot['startPts'], shot['endPts']
+ frame_id = uuid5(document_id, f"{shot['id']}:{frame['pts']}")
+ asset_id = gateway().upload_asset_id(project_id, uuid5(frame_id, 'tool-output'))
+ path = directory / frame['path']
+ image = existing.get(asset_id)
+ if image is not None and (image.kind != 'image' or image.provenance != provenance
+ or gateway().file_identity(path) != (image.fingerprint, image.metadata.size)):
+ asset_id, image = uuid4(), None
+ if image is None:
+ handle = slots[index]
+ staged.append(handle)
+ name = f"{source.fingerprint[7:15]}-{path.name}"
+ upload = self.assets.stage_output(project_id, handle, name, path, expected_kind='image')
+ image = Asset(id=asset_id, projectId=project_id, name=name, kind='image', path=f'assets/{asset_id}',
+ fingerprint=upload.fingerprint, metadata=upload.metadata, provenance=provenance)
+ images.append(image)
+ writes.append(AssetFileWrite(assetId=asset_id, uploadHandle=handle,
+ fingerprint=image.fingerprint, size=image.metadata.size))
+ else:
+ self.assets.reference_available(project_id, image.id)
+ shots.append(dict(id=shot['id'], measured=dict(startPts=start, endPts=end,
+ representativePts=frame['pts'], representative=asset_ref(image)),
+ edit=dict(startPts=start, endPts=end, description='')))
+ video = analysis['source']
+ command = parse_command(dict(commandId=uuid4(), projectId=project_id, type='editor.create',
+ payload=dict(document=dict(id=document_id, projectId=project_id, kind='shot_breakdown',
+ data=dict(source=source_ref, timeBase=video['timeBase'], originPts=video['originPts'],
+ durationPts=shots[-1]['measured']['endPts'], shots=shots)))))
+
+ def publish(before):
+ with_frames = before.model_copy(update={'assets': (*before.assets, *images)})
+ return CreationCanvas(self.projects).apply(with_frames, command)
+
+ receipt = self.projects.commit(command, publish, session=session, files=tuple(writes))
+ saved = self.get(project_id, source.id)
+ if saved is not None:
+ return saved
code = receipt.issues[0].code if receipt.issues else 'operation_rejected'
raise ProjectError('保存分镜失败,请重新打开工程后再试。', 409, code=code)
- return self.get(project_id, source.id)
+ finally:
+ if staged:
+ self.assets.uploads.discard_outputs(project_id, staged)
@asynccontextmanager
async def _analysis(self):
@@ -115,7 +160,7 @@ async def create(self, project_id, asset_id, session, *, model_config_id=None, l
async with self._analysis():
saved = await asyncio.to_thread(self.get, project_id, asset_id)
if saved is not None:
- return saved
+ return saved, None
config = await asyncio.to_thread(self._model, model_config_id) if model_config_id is not None else None
with TemporaryDirectory(prefix='opendirector-shots-') as temporary:
directory = Path(temporary)
@@ -123,14 +168,14 @@ async def create(self, project_id, asset_id, session, *, model_config_id=None, l
if len(analysis['shots']) > MAX_SHOTS:
raise ProjectError('切镜超过 48 个。请截取较短的参考片段再试。', code='shot_count_limit')
saved = await blocking(self._save_detection, project_id, source, analysis, directory, session)
- return saved if config is None else await self._describe_missing(saved, config, session, language)
+ return (saved, None) if config is None else await self._describe_missing(saved, config, session, language)
async def fill_missing(self, project_id, asset_id, session, *, model_config_id, language):
async with self._analysis():
await asyncio.to_thread(self._require_session, project_id, session)
saved = await asyncio.to_thread(self._require_breakdown, project_id, asset_id)
if all(shot.frameSuggestion is not None for shot in saved.data.shots):
- return saved
+ return saved, None
config = await asyncio.to_thread(self._model, model_config_id)
return await self._describe_missing(saved, config, session, language)
@@ -183,11 +228,18 @@ async def _describe_missing(self, document, config, session, language):
dispatched = True
try:
row = await describe_shot_frame(config, reference, frame, language=language)
- except (ProjectError, ValueError):
- return await asyncio.to_thread(self._require_breakdown, document.projectId, document.data.source.assetId)
+ except (ProjectError, ValueError) as exc:
+ if isinstance(exc, (InvalidShotDescription, ProviderProtocolError)):
+ reason = 'invalid_response'
+ elif isinstance(exc, GenerationError) and exc.details.category == 'rate_limit':
+ reason = 'rate_limited'
+ else:
+ reason = 'model_error'
+ saved = await asyncio.to_thread(self._require_breakdown, document.projectId, document.data.source.assetId)
+ return saved, reason
suggestion = ShotFrameSuggestion(modelId=row['model']['modelId'], **row['description'])
document = await blocking(self._record_suggestion, document, shot, suggestion, session)
- return document
+ return document, None
except ProjectError as exc:
if exc.code != 'session_expired' or not dispatched:
raise
diff --git a/packages/core/src/opendirector/application/shot_descriptions.py b/packages/core/src/opendirector/application/shot_descriptions.py
index d8c7b4b1f..c5bdc57e7 100644
--- a/packages/core/src/opendirector/application/shot_descriptions.py
+++ b/packages/core/src/opendirector/application/shot_descriptions.py
@@ -166,9 +166,13 @@ def _messages(shot_id, frame, image_bytes, language):
]
+class InvalidShotDescription(ValueError):
+ """The returned text does not contain a usable shot description."""
+
+
def _parse_description(content):
if not isinstance(content, str) or not content.strip():
- raise ValueError("模型没有返回镜头描述。")
+ raise InvalidShotDescription("模型没有返回镜头描述。")
text = content.strip()
match = _FENCE.match(text)
if match:
@@ -176,19 +180,19 @@ def _parse_description(content):
try:
value = json.loads(text)
except (TypeError, ValueError):
- raise ValueError("模型返回的镜头描述不是有效 JSON。") from None
+ raise InvalidShotDescription("模型返回的镜头描述不是有效 JSON。") from None
if not isinstance(value, dict) or set(value) != {"subject", "scene", "framing"}:
- raise ValueError(
+ raise InvalidShotDescription(
"模型返回的镜头描述必须且只能包含 subject、scene、framing。"
)
description = {}
for key in ("subject", "scene", "framing"):
item = value[key]
if not isinstance(item, str):
- raise ValueError(f"模型返回的 {key} 必须是非空字符串。")
+ raise InvalidShotDescription(f"模型返回的 {key} 必须是非空字符串。")
item = item.strip()
if not item or len(item) > MAX_FIELD_CHARS:
- raise ValueError(
+ raise InvalidShotDescription(
f"模型返回的 {key} 必须为 1–{MAX_FIELD_CHARS} 个字符。"
)
description[key] = item
diff --git a/packages/core/src/opendirector/domain/creation/editors.py b/packages/core/src/opendirector/domain/creation/editors.py
index affdc0b18..a98e9f8b0 100644
--- a/packages/core/src/opendirector/domain/creation/editors.py
+++ b/packages/core/src/opendirector/domain/creation/editors.py
@@ -657,10 +657,17 @@ class ShotFrameSuggestion(Contract):
framing: str = Field(min_length=1, max_length=1200, description='Framing visible in the representative frame.')
+class ShotDraftCut(Contract):
+ startPts: ShotTick = Field(description='Inclusive start of an additional draft shot inside the edited interval.')
+ description: str = Field(default='', max_length=2000, description='Note for the draft shot starting at this cut.')
+
+
class ShotEdit(Contract):
startPts: ShotTick = Field(description='Edited inclusive start in normalized source ticks.')
endPts: PositiveInt = Field(description='Edited exclusive end in normalized source ticks.')
description: str = Field(default='', max_length=2000, description='Description entered by the user or Agent.')
+ cuts: tuple[ShotDraftCut, ...] = Field(default=(), exclude_if=lambda cuts: not cuts,
+ description='Additional user cuts in strictly increasing source ticks. The first segment uses the outer description.')
joinPrevious: StrictBool = Field(default=False, exclude_if=lambda value: not value,
description='Remove the cut before this shot in the edited sequence. The preceding and current edited intervals must touch.')
@@ -692,6 +699,11 @@ def evidence(self):
cursor = shot.measured.endPts
if not shot.edit.startPts < shot.edit.endPts <= self.durationPts:
raise ValueError('Edited shot exceeds the analyzed video interval')
+ start = shot.edit.startPts
+ for cut in shot.edit.cuts:
+ if not start < cut.startPts < shot.edit.endPts:
+ raise ValueError('Draft cuts must be strictly ordered inside the edited shot')
+ start = cut.startPts
if shot.edit.joinPrevious and shot.edit.startPts != previous_edit_end:
raise ValueError('A shot can only join a contiguous preceding shot')
previous_edit_end = shot.edit.endPts
diff --git a/packages/core/src/opendirector/domain/generation.py b/packages/core/src/opendirector/domain/generation.py
index 3721dbf78..677300697 100644
--- a/packages/core/src/opendirector/domain/generation.py
+++ b/packages/core/src/opendirector/domain/generation.py
@@ -35,3 +35,7 @@ class GenerationError(ProjectError):
def __init__(self, details: GenerationFailure, status=502, message=None):
super().__init__(message or f'{details.message} {details.suggestion} 不会自动重新提交。', status)
self.details = details
+
+
+class ProviderProtocolError(GenerationError):
+ """The provider replied, but its response could not be read."""
diff --git a/packages/core/src/opendirector/infrastructure/creation_uploads.py b/packages/core/src/opendirector/infrastructure/creation_uploads.py
index 81707ee89..72829281d 100644
--- a/packages/core/src/opendirector/infrastructure/creation_uploads.py
+++ b/packages/core/src/opendirector/infrastructure/creation_uploads.py
@@ -212,6 +212,28 @@ def cancel(self, project_id, handle, session):
sync_directory(folder)
return self._info(owner, snapshot)
+ def discard_outputs(self, project_id, handles):
+ """Reset service-owned slots under the caller's group lock; a pending publication keeps its bytes."""
+ with self.projects._publication_lock(project_id):
+ journal = self.projects._journal(project_id)
+ if journal.exists():
+ pending = {UUID(write['uploadHandle']) for write in read_json(journal).get('files', ())}
+ if pending.intersection(handles):
+ return False
+ for handle in handles:
+ folder = upload_directory(self.projects.state_dir, UUID(str(project_id)), handle)
+ if not folder.exists():
+ continue
+ with self.lock(project_id, handle):
+ if not child(folder, 'owner.json').exists():
+ continue
+ self._owner(folder, project_id, handle, None)
+ for file in [*folder.glob('.partial-*'), folder / 'content', folder / 'ready.json', folder / 'owner.json']:
+ child(folder, file.name).unlink(missing_ok=True)
+ folder.rmdir()
+ sync_directory(folder.parent)
+ return True
+
class UploadWriter:
def __init__(self, uploads, folder, owner, lock, trusted):
diff --git a/packages/core/src/opendirector/integrations/generation_errors.py b/packages/core/src/opendirector/integrations/generation_errors.py
index 01b5c5e7b..4b7f5f3aa 100644
--- a/packages/core/src/opendirector/integrations/generation_errors.py
+++ b/packages/core/src/opendirector/integrations/generation_errors.py
@@ -5,7 +5,7 @@
import re
from urllib.parse import unquote
-from opendirector.domain.generation import GenerationError, GenerationFailure
+from opendirector.domain.generation import GenerationError, GenerationFailure, ProviderProtocolError
from opendirector.integrations.http_settings import MODEL_JOB_CONTEXT
@@ -190,6 +190,6 @@ def protocol_failure(stage, *, message='生成服务返回了无法识别或不
context = MODEL_JOB_CONTEXT.get()
logger.error(f'model.error {json.dumps({"project_id": context[0] if context else None, "job_id": context[1] if context else None, "stage": stage, "error_type": "ProtocolError"})}')
unknown = stage == 'submit'
- return GenerationError(GenerationFailure(category='submission_unknown' if unknown else 'protocol', stage=stage,
+ return ProviderProtocolError(GenerationFailure(category='submission_unknown' if unknown else 'protocol', stage=stage,
message=message,
suggestion=suggestion or ('请先核对请求是否已被接收,避免重复生成。' if unknown else '请核对原任务状态和接口协议。')))
diff --git a/src/backend/api.ts b/src/backend/api.ts
index 4050dc079..e0343bfdf 100644
--- a/src/backend/api.ts
+++ b/src/backend/api.ts
@@ -105,7 +105,9 @@ export function backgroundRead(task: () => Promise, signal?: AbortSignal)
const BACKGROUND_PROJECT_READ = /^\/creation\/projects\/[^/]+\/(?:assistant(?:\/[^?]*)?|reference-catalog(?!\?nodeId=)|reference-evidence|canvas-texts|history|version-counts)(?:\?|$)/;
-export function request(path: string, options: RequestInit = {}, leaseRenewed = false): Promise {
+type RequestOptions = RequestInit & { onResponseHeaders?: (headers: Headers) => void };
+
+export function request(path: string, options: RequestOptions = {}, leaseRenewed = false): Promise {
const run = () => requestNow(path, options, leaseRenewed);
if ((options.method === undefined || options.method === "GET") && BACKGROUND_PROJECT_READ.test(path))
return backgroundRead(run, options.signal ?? undefined);
@@ -114,15 +116,16 @@ export function request(path: string, options: RequestInit = {}, leaseRenewed
async function requestNow(
path: string,
- options: RequestInit = {},
+ options: RequestOptions = {},
leaseRenewed = false,
): Promise {
await sessionReady;
const requestedSession = sessionId;
+ const { onResponseHeaders, ...init } = options;
let response: Response;
try {
response = await fetch(`/api${path}`, {
- ...options,
+ ...init,
headers: { ...headers, ...options.headers },
});
} catch (failure) {
@@ -146,6 +149,7 @@ async function requestNow(
}
throw error;
}
+ onResponseHeaders?.(response.headers);
if (response.status === 204) return undefined as T;
return (await response.json()) as T;
}
diff --git a/src/canvas/EditorModal.tsx b/src/canvas/EditorModal.tsx
index 653a48fe8..010ae740c 100644
--- a/src/canvas/EditorModal.tsx
+++ b/src/canvas/EditorModal.tsx
@@ -14,6 +14,7 @@ export function EditorModal({
onClose,
onApply,
applyLabel,
+ applyStatus,
disabled = false,
error,
className = "",
@@ -25,6 +26,7 @@ export function EditorModal({
onClose: () => void;
onApply?: () => void;
applyLabel?: string;
+ applyStatus?: ReactNode;
disabled?: boolean;
error?: string;
className?: string;
@@ -120,6 +122,7 @@ export function EditorModal({
{actions}
+ {applyStatus}
{onApply && (
- {selectedShot && draft && (
-
-
-
- {t("editors.shotBreakdown.shotNumber", {
- number: selectedIndex + 1,
- })}
-
- {t("editors.shotBreakdown.detailHint")}
-
-
-
-
-
- {t("editors.shotBreakdown.badge.detected")}
-
- {t("editors.shotBreakdown.measured.title")}
-
-
-
-
- {t("editors.shotBreakdown.measured.start")}
- -
- {formatSeconds(
- selectedShot.measured.startPts,
- timeScale,
- )}{" "}
- · PTS {formatPts(selectedShot.measured.startPts)}
-
-
-
-
- {t("editors.shotBreakdown.measured.end")}
- -
- {formatSeconds(
- selectedShot.measured.endPts,
- timeScale,
- )}{" "}
- · PTS {formatPts(selectedShot.measured.endPts)}
-
-
-
-
-
- {t("editors.shotBreakdown.measured.representative")}
-
- -
- {formatSeconds(
- selectedShot.measured.representativePts,
- timeScale,
- )}{" "}
- · PTS{" "}
- {formatPts(selectedShot.measured.representativePts)}
-
-
-
-
- seek(selectedShot.measured.startPts)}
- >
-
- {t("editors.shotBreakdown.locate.measuredStart")}
-
- seek(selectedShot.measured.endPts)}
- >
-
- {t("editors.shotBreakdown.locate.measuredEnd")}
-
-
- seek(selectedShot.measured.representativePts)
- }
- >
-
- {t("editors.shotBreakdown.locate.representative")}
-
-
-
- {selectedShot.frameSuggestion ? (
-
-
-
- {t("editors.shotBreakdown.badge.model")}
-
- {t("editors.shotBreakdown.suggestion.title", {
- model: selectedShot.frameSuggestion.modelId,
- })}
-
-
- {t("editors.shotBreakdown.suggestion.note")}
-
-
-
-
-
- {t("editors.shotBreakdown.suggestion.subject")}
-
- - {selectedShot.frameSuggestion.subject}
-
-
-
- {t("editors.shotBreakdown.suggestion.scene")}
- - {selectedShot.frameSuggestion.scene}
-
-
-
-
- {t("editors.shotBreakdown.suggestion.framing")}
-
- - {selectedShot.frameSuggestion.framing}
-
-
-
- ) : (
-
-
- {t("editors.shotBreakdown.suggestion.titleEmpty")}
-
-
- {t("editors.shotBreakdown.suggestion.empty")}
-
-
- )}
-
-
-
- {t("editors.shotBreakdown.badge.draft")}
-
- {t("editors.shotBreakdown.edit.title")}
-
- {firstJoined !== lastJoined && (
-
- {t("editors.shotBreakdown.edit.joinedRange", {
- first: firstJoined + 1,
- last: lastJoined + 1,
- start: formatSeconds(draft.shots[firstJoined]!.edit.startPts, timeScale),
- end: formatSeconds(draft.shots[lastJoined]!.edit.endPts, timeScale),
- })}
-
- )}
- {previousShot && (
-
-
- editShot((shot) => ({
- ...shot,
- edit: { ...shot.edit, joinPrevious: !joinsPrevious },
- }))
- }
- >
- {t(joinsPrevious
- ? "editors.shotBreakdown.edit.restoreCut"
- : "editors.shotBreakdown.edit.joinPrevious")}
-
- {!joinsPrevious && !canJoinPrevious && (
- {t("editors.shotBreakdown.edit.joinHint")}
- )}
-
- )}
-
-
-
-
- seek(selectedShot.edit.startPts)}
- >
-
- {t("editors.shotBreakdown.locate.editStart")}
-
- seek(selectedShot.edit.endPts)}
- >
-
- {t("editors.shotBreakdown.locate.editEnd")}
-
-
- editShot((shot) => ({
- ...shot,
- edit: {
- ...shot.edit,
- startPts: shot.measured.startPts,
- endPts: shot.measured.endPts,
- },
- }))
- }
- >
-
- {t("editors.shotBreakdown.edit.reset")}
-
-
-
- {t("editors.shotBreakdown.edit.note")}
-
-
-
-
- {t("editors.shotBreakdown.durationLabel")}
-
-
-
+ {selectedShot && (
+
)}
>
)}
@@ -892,15 +595,6 @@ function parseTimeBase(value: string): number | null {
return numerator / denominator;
}
-function formatSeconds(pts: number, scale: number | null): string {
- if (!scale || !Number.isFinite(pts)) return "—";
- return `${(pts * scale).toFixed(3)} s`;
-}
-
-function formatPts(pts: number): string {
- return Number.isFinite(pts) ? String(pts) : "—";
-}
-
function RepresentativeThumbnail({
projectId,
asset,
diff --git a/src/canvas/shot-breakdown-editor.css b/src/canvas/shot-breakdown-editor.css
index 1b2448917..5c9b0044d 100644
--- a/src/canvas/shot-breakdown-editor.css
+++ b/src/canvas/shot-breakdown-editor.css
@@ -6,6 +6,14 @@
flex-direction: column;
gap: 16px;
}
+.cw-shot-breakdown-save-state {
+ color: var(--cw-control-muted, #a992b9);
+ font-size: 11px;
+}
+.cw-shot-breakdown-save-state[data-dirty="true"] {
+ color: var(--cw-control-accent, #dab78f);
+ font-weight: 600;
+}
.cw-shot-breakdown-start {
display: flex;
max-width: 660px;
diff --git a/src/canvas/shotDraft.ts b/src/canvas/shotDraft.ts
new file mode 100644
index 000000000..0aaaee846
--- /dev/null
+++ b/src/canvas/shotDraft.ts
@@ -0,0 +1,59 @@
+import type { ShotEdit } from "../contracts/generated.ts";
+
+export type DraftSegment = { startPts: number; endPts: number; description: string };
+
+export function shotDraftSegments(edit: ShotEdit): DraftSegment[] {
+ const starts = [edit, ...(edit.cuts ?? [])];
+ return starts.map((start, index) => ({
+ startPts: start.startPts,
+ endPts: starts[index + 1]?.startPts ?? edit.endPts,
+ description: start.description ?? "",
+ }));
+}
+
+export function validShotEdit(edit: ShotEdit, durationPts: number): boolean {
+ return shotDraftSegments(edit).every(({ startPts, endPts }) =>
+ Number.isSafeInteger(startPts) && Number.isSafeInteger(endPts) &&
+ 0 <= startPts && startPts < endPts && endPts <= durationPts
+ );
+}
+
+export function splitShotDraft(edit: ShotEdit, pts: number): ShotEdit {
+ const cuts = edit.cuts ?? [];
+ if (!Number.isSafeInteger(pts) || !(edit.startPts < pts && pts < edit.endPts) ||
+ cuts.some((cut) => cut.startPts === pts)) return edit;
+ const insert = cuts.findIndex((cut) => cut.startPts > pts);
+ const index = insert < 0 ? cuts.length : insert;
+ return { ...edit, cuts: [...cuts.slice(0, index), { startPts: pts, description: "" }, ...cuts.slice(index)] };
+}
+
+export function removeShotDraftCut(edit: ShotEdit, segmentIndex: number): ShotEdit {
+ const { cuts, ...rest } = edit;
+ const cutIndex = segmentIndex - 1;
+ if (!cuts?.[cutIndex]) return edit;
+ const remaining = cuts.filter((_, index) => index !== cutIndex);
+ return remaining.length ? { ...rest, cuts: remaining } : rest;
+}
+
+export function updateShotDraftSegment(edit: ShotEdit, index: number, patch: Partial): ShotEdit {
+ const segments = shotDraftSegments(edit);
+ const current = segments[index];
+ if (!current) return edit;
+ const updated = { ...current, ...patch };
+ if (updated.startPts === current.startPts && updated.endPts === current.endPts &&
+ updated.description === current.description) return edit;
+ segments[index] = updated;
+ if (index + 1 < segments.length) segments[index + 1].startPts = updated.endPts;
+ const cuts = segments.slice(1).map(({ startPts, description }) => ({ startPts, description }));
+ return {
+ ...edit,
+ startPts: segments[0].startPts,
+ description: segments[0].description,
+ endPts: segments[segments.length - 1].endPts,
+ ...(cuts.length ? { cuts } : {}),
+ };
+}
+
+export function formatShotSeconds(pts: number, scale: number | null): string {
+ return scale !== null && Number.isFinite(pts * scale) ? (pts * scale).toFixed(3) + " s" : "—";
+}
diff --git a/src/canvas/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx
index 157b5d711..0a4b2bf6e 100644
--- a/src/canvas/workspace/WorkspaceView.tsx
+++ b/src/canvas/workspace/WorkspaceView.tsx
@@ -1616,7 +1616,8 @@ export function WorkspaceView({ rt, editingState, editSession }: {
void timelineOutput.run(single, () => persist(doc, false)) : undefined}
outputBusy={timelineOutput.busy || !!(timelineOutput.blockedItemId && timelineOutput.blockedItemId !== single.id)}
diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json
index b2e729579..a3382162a 100644
--- a/src/contracts/creation.schema.json
+++ b/src/contracts/creation.schema.json
@@ -13907,6 +13907,29 @@
"title": "ShotBreakdownDocument",
"type": "object"
},
+ "ShotDraftCut": {
+ "additionalProperties": false,
+ "properties": {
+ "startPts": {
+ "description": "Inclusive start of an additional draft shot inside the edited interval.",
+ "minimum": 0,
+ "title": "Startpts",
+ "type": "integer"
+ },
+ "description": {
+ "default": "",
+ "description": "Note for the draft shot starting at this cut.",
+ "maxLength": 2000,
+ "title": "Description",
+ "type": "string"
+ }
+ },
+ "required": [
+ "startPts"
+ ],
+ "title": "ShotDraftCut",
+ "type": "object"
+ },
"ShotEdit": {
"additionalProperties": false,
"properties": {
@@ -13929,6 +13952,15 @@
"title": "Description",
"type": "string"
},
+ "cuts": {
+ "default": [],
+ "description": "Additional user cuts in strictly increasing source ticks. The first segment uses the outer description.",
+ "items": {
+ "$ref": "#/$defs/ShotDraftCut"
+ },
+ "title": "Cuts",
+ "type": "array"
+ },
"joinPrevious": {
"default": false,
"description": "Remove the cut before this shot in the edited sequence. The preceding and current edited intervals must touch.",
@@ -32957,6 +32989,30 @@
"title": "ShotBreakdownDocument",
"type": "object"
},
+ "ShotDraftCut": {
+ "additionalProperties": false,
+ "properties": {
+ "startPts": {
+ "description": "Inclusive start of an additional draft shot inside the edited interval.",
+ "minimum": 0,
+ "title": "Startpts",
+ "type": "integer"
+ },
+ "description": {
+ "default": "",
+ "description": "Note for the draft shot starting at this cut.",
+ "maxLength": 2000,
+ "title": "Description",
+ "type": "string"
+ }
+ },
+ "required": [
+ "startPts",
+ "description"
+ ],
+ "title": "ShotDraftCut",
+ "type": "object"
+ },
"ShotEdit": {
"additionalProperties": false,
"properties": {
@@ -32979,6 +33035,15 @@
"title": "Description",
"type": "string"
},
+ "cuts": {
+ "default": [],
+ "description": "Additional user cuts in strictly increasing source ticks. The first segment uses the outer description.",
+ "items": {
+ "$ref": "#/$defs/ShotDraftCut"
+ },
+ "title": "Cuts",
+ "type": "array"
+ },
"joinPrevious": {
"default": false,
"description": "Remove the cut before this shot in the edited sequence. The preceding and current edited intervals must touch.",
diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts
index 02dc22492..5d2a4ca36 100644
--- a/src/contracts/generated.ts
+++ b/src/contracts/generated.ts
@@ -1453,10 +1453,16 @@ export interface ShotBreakdownDocumentInput extends EditorDocumentBaseInput {
readonly data: ShotBreakdownDataInput;
}
+export interface ShotDraftCutInput extends ContractInput {
+ readonly startPts: number;
+ readonly description?: string;
+}
+
export interface ShotEditInput extends ContractInput {
readonly startPts: number;
readonly endPts: number;
readonly description?: string;
+ readonly cuts?: ReadonlyArray;
readonly joinPrevious?: boolean;
}
@@ -3389,10 +3395,16 @@ export interface ShotBreakdownDocument extends EditorDocumentBase {
readonly data: ShotBreakdownData;
}
+export interface ShotDraftCut extends Contract {
+ readonly startPts: number;
+ readonly description: string;
+}
+
export interface ShotEdit extends Contract {
readonly startPts: number;
readonly endPts: number;
readonly description: string;
+ readonly cuts?: ReadonlyArray;
readonly joinPrevious?: boolean;
}
diff --git a/src/i18n/messages/en-US/canvasShell.ts b/src/i18n/messages/en-US/canvasShell.ts
index 7bb3bf744..87a28d28f 100644
--- a/src/i18n/messages/en-US/canvasShell.ts
+++ b/src/i18n/messages/en-US/canvasShell.ts
@@ -78,6 +78,8 @@ export const canvasShell = {
"canvas.selection.toolbar": "Node actions",
"canvas.selection.locked": "{label} · Unlock the node first",
+ "canvas.selection.groupLocked": "{label} · Unlock the parent group first",
+ "canvas.selection.preview": "To use {label}, choose “Edit in this window”.",
"canvas.selection.unavailable": "{label} · Not available right now",
"canvas.selection.gridSplit": "Grid split",
diff --git a/src/i18n/messages/en-US/editors.ts b/src/i18n/messages/en-US/editors.ts
index 1937eda85..bcd00960e 100644
--- a/src/i18n/messages/en-US/editors.ts
+++ b/src/i18n/messages/en-US/editors.ts
@@ -468,6 +468,12 @@ export const editors = {
"editors.shotBreakdown.suggestion.empty":
"This shot has no model suggestion. Detection remains available.",
"editors.shotBreakdown.edit.title": "Shot draft",
+ "editors.shotBreakdown.edit.split": "Split at playhead",
+ "editors.shotBreakdown.edit.splitHint": "Move the playhead inside this shot to add a draft cut.",
+ "editors.shotBreakdown.edit.segment": "Draft segment",
+ "editors.shotBreakdown.edit.segmentRange": "Segment {number} · {start}–{end}",
+ "editors.shotBreakdown.edit.removeCut": "Remove this draft cut",
+ "editors.shotBreakdown.edit.removeCutConfirm": "Remove this cut and discard the selected segment’s description? The preceding segment keeps its description.",
"editors.shotBreakdown.edit.joinPrevious": "Join previous shot",
"editors.shotBreakdown.edit.restoreCut": "Restore cut",
"editors.shotBreakdown.edit.joinHint": "Align this start with the previous draft end to join them.",
@@ -490,7 +496,10 @@ export const editors = {
"editors.shotBreakdown.durationAria": "Total duration PTS",
"editors.shotBreakdown.notice.analyzed": "Shots detected and saved.",
"editors.shotBreakdown.notice.partial":
- "Shots saved. The model completed {described} of {total} descriptions. You can edit every shot.",
+ "Shots saved. The model completed {described} of {total} descriptions.",
+ "editors.shotBreakdown.notice.rateLimited": "The model reached its rate limit. Try filling the missing suggestions later.",
+ "editors.shotBreakdown.notice.invalidResponse": "The model returned an unreadable suggestion. Try again or select another model.",
+ "editors.shotBreakdown.notice.modelError": "The model request failed. Check the model connection and try again.",
"editors.shotBreakdown.notice.noProgress":
"No new suggestions were saved. Try again later or choose another model.",
"editors.shotBreakdown.notice.batchPartial":
@@ -499,8 +508,8 @@ export const editors = {
"editors.shotBreakdown.notice.reloaded": "Loaded the latest saved breakdown.",
"editors.shotBreakdown.notice.empty": "No saved breakdown exists now.",
"editors.shotBreakdown.notice.saved": "Shot breakdown saved.",
- "editors.shotBreakdown.notice.draft":
- "Draft changed. Save breakdown to keep it.",
+ "editors.shotBreakdown.notice.draft": "Unsaved changes",
+ "editors.shotBreakdown.notice.saving": "Saving…",
"editors.shotBreakdown.conflict":
"The saved version changed. Your draft is kept; choose Reload only when you want the server version.",
"editors.shotBreakdown.discardReload":
@@ -515,5 +524,5 @@ export const editors = {
"editors.shotBreakdown.error.save":
"Could not save the shot breakdown: {reason}",
"editors.shotBreakdown.error.interval":
- "Shot {number} needs integer start and end PTS values within the video, and the end must be after the start.",
+ "Check shot {number}. Draft boundaries must be whole PTS values in increasing order within the video.",
} as const;
diff --git a/src/i18n/messages/zh-CN/canvasShell.ts b/src/i18n/messages/zh-CN/canvasShell.ts
index b813463fc..9395f3281 100644
--- a/src/i18n/messages/zh-CN/canvasShell.ts
+++ b/src/i18n/messages/zh-CN/canvasShell.ts
@@ -78,6 +78,8 @@ export const canvasShell = {
"canvas.selection.toolbar": "节点操作",
"canvas.selection.locked": "{label} · 请先解锁节点",
+ "canvas.selection.groupLocked": "{label} · 请先解锁父分组",
+ "canvas.selection.preview": "当前为预览模式。点击“在此编辑”后即可使用“{label}”。",
"canvas.selection.unavailable": "{label} · 此操作暂不可用",
"canvas.selection.gridSplit": "网格切分",
diff --git a/src/i18n/messages/zh-CN/editors.ts b/src/i18n/messages/zh-CN/editors.ts
index 5bfe3c9bd..befa56b4c 100644
--- a/src/i18n/messages/zh-CN/editors.ts
+++ b/src/i18n/messages/zh-CN/editors.ts
@@ -425,6 +425,12 @@ export const editors = {
"editors.shotBreakdown.suggestion.empty":
"该镜头没有模型建议,检测结果仍可使用。",
"editors.shotBreakdown.edit.title": "镜头草稿",
+ "editors.shotBreakdown.edit.split": "在播放位置拆分",
+ "editors.shotBreakdown.edit.splitHint": "将播放位置移到本镜头区间内,即可添加草稿切点。",
+ "editors.shotBreakdown.edit.segment": "草稿分段",
+ "editors.shotBreakdown.edit.segmentRange": "第 {number} 段 · {start}–{end}",
+ "editors.shotBreakdown.edit.removeCut": "移除此草稿切点",
+ "editors.shotBreakdown.edit.removeCutConfirm": "移除这个切点并丢弃当前分段的描述?合并后保留前一段的描述。",
"editors.shotBreakdown.edit.joinPrevious": "与上一镜合并",
"editors.shotBreakdown.edit.restoreCut": "恢复此切点",
"editors.shotBreakdown.edit.joinHint": "让这一镜的起点与上一镜的草稿终点对齐,就能合并。",
@@ -447,14 +453,18 @@ export const editors = {
"editors.shotBreakdown.durationAria": "总时长 PTS",
"editors.shotBreakdown.notice.analyzed": "分镜已检测并保存。",
"editors.shotBreakdown.notice.partial":
- "分镜已保存。模型完成了 {described}/{total} 条描述,每个镜头仍可编辑。",
+ "分镜已保存。模型完成了 {described}/{total} 条描述。",
+ "editors.shotBreakdown.notice.rateLimited": "模型请求已被限流,可稍后再补全缺失建议。",
+ "editors.shotBreakdown.notice.invalidResponse": "模型返回的建议无法解析,可重试或换一个模型。",
+ "editors.shotBreakdown.notice.modelError": "模型请求失败,请检查连接后重试。",
"editors.shotBreakdown.notice.noProgress": "这次没有新增建议。可以稍后再试,也可以换一个模型。",
"editors.shotBreakdown.notice.batchPartial": "已有 {described}/{total} 个镜头保存了建议,可继续补全下一批。",
"editors.shotBreakdown.notice.suggestionsComplete": "所有镜头都已有模型建议。",
"editors.shotBreakdown.notice.reloaded": "已加载最新保存的分镜。",
"editors.shotBreakdown.notice.empty": "当前没有已保存的分镜。",
"editors.shotBreakdown.notice.saved": "分镜已保存。",
- "editors.shotBreakdown.notice.draft": "草稿已修改,保存分镜后才会写入工程。",
+ "editors.shotBreakdown.notice.draft": "有未保存的修改",
+ "editors.shotBreakdown.notice.saving": "正在保存…",
"editors.shotBreakdown.conflict":
"保存的版本已变化。草稿已保留;只有需要服务器版本时才选择“重新加载”。",
"editors.shotBreakdown.discardReload": "丢弃未保存的修改,加载最新分镜?",
@@ -464,5 +474,5 @@ export const editors = {
"editors.shotBreakdown.error.suggestions": "无法补全缺失建议:{reason}",
"editors.shotBreakdown.error.save": "无法保存分镜:{reason}",
"editors.shotBreakdown.error.interval":
- "镜头 {number} 的起止必须是视频范围内的整数 PTS,且终点必须晚于起点。",
+ "请检查镜头 {number} 的草稿边界。起点、各切点和终点均须为视频范围内的整数 PTS,并按时间递增。",
} as const;
diff --git a/tests/sessionLease.test.ts b/tests/sessionLease.test.ts
index 880004f56..420761dd4 100644
--- a/tests/sessionLease.test.ts
+++ b/tests/sessionLease.test.ts
@@ -8,7 +8,9 @@ test("a write rejected for a lapsed lease renews it and is resent once", async (
const expired = () =>
new Response(JSON.stringify({ detail: "会话已过期", code: "session_expired" }), { status: 409 });
try {
- let answers = [expired(), new Response(JSON.stringify({ status: "applied" }), { status: 200 })];
+ let answers = [expired(), new Response(JSON.stringify({ status: "applied" }), {
+ status: 200, headers: { "X-OpenDirector-Shot-Stop": "rate_limited" },
+ })];
globalThis.fetch = (async (url: string) => {
calls.push(String(url));
return answers.shift()!;
@@ -17,9 +19,14 @@ test("a write rejected for a lapsed lease renews it and is resent once", async (
renewed.push(projectId);
return true;
});
- assert.deepEqual(await request("/creation/projects/p1/commands", { method: "POST", body: "{}" }), {
+ const observed: (string | null)[] = [];
+ assert.deepEqual(await request("/creation/projects/p1/commands", {
+ method: "POST", body: "{}",
+ onResponseHeaders: (headers) => observed.push(headers.get("X-OpenDirector-Shot-Stop")),
+ }), {
status: "applied",
});
+ assert.deepEqual(observed, ["rate_limited"]);
assert.deepEqual(renewed, ["p1"]);
assert.deepEqual(calls, ["/api/creation/projects/p1/commands", "/api/creation/projects/p1/commands"]);
diff --git a/tests/shotDraft.test.ts b/tests/shotDraft.test.ts
new file mode 100644
index 000000000..b6c966e1b
--- /dev/null
+++ b/tests/shotDraft.test.ts
@@ -0,0 +1,54 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { formatShotSeconds, removeShotDraftCut, shotDraftSegments, splitShotDraft, updateShotDraftSegment, validShotEdit } from "../src/canvas/shotDraft.ts";
+
+const original = { startPts: 10, endPts: 40, description: "left", joinPrevious: true };
+
+test("split missed boundaries without moving the original edges or its note", () => {
+ const draft = splitShotDraft(splitShotDraft(original, 30), 20);
+ assert.deepEqual(shotDraftSegments(draft), [
+ { startPts: 10, endPts: 20, description: "left" },
+ { startPts: 20, endPts: 30, description: "" },
+ { startPts: 30, endPts: 40, description: "" },
+ ]);
+ for (const pts of [9, 10, 20, 40, 40.5, NaN]) assert.equal(splitShotDraft(draft, pts), draft);
+ assert.equal(draft.joinPrevious, true);
+ assert.ok(!("cuts" in original));
+});
+
+test("moving either side of a shared boundary updates both adjacent segments", () => {
+ const split = splitShotDraft(original, 20);
+ const right = updateShotDraftSegment(split, 1, { startPts: 24, endPts: 37, description: "right" });
+ assert.equal(shotDraftSegments(right)[0].endPts, 24);
+ const left = updateShotDraftSegment(right, 0, { startPts: 12, endPts: 26 });
+ assert.deepEqual(shotDraftSegments(left), [
+ { startPts: 12, endPts: 26, description: "left" },
+ { startPts: 26, endPts: 37, description: "right" },
+ ]);
+ assert.deepEqual(removeShotDraftCut(left, 1), { ...original, startPts: 12, endPts: 37 });
+ assert.equal(removeShotDraftCut(original, 0), original);
+ assert.equal(updateShotDraftSegment(original, 0, { startPts: 10 }), original);
+});
+
+test("invalid draft ranges are visible to the form, while zero and the final tick are valid edges", () => {
+ const split = splitShotDraft(original, 20);
+ for (const startPts of [10, -1, 20.5, NaN, 40]) {
+ assert.equal(validShotEdit(updateShotDraftSegment(split, 1, { startPts }), 40), false);
+ }
+ assert.ok(validShotEdit(updateShotDraftSegment(split, 0, { startPts: 0 }), 40));
+ assert.equal(validShotEdit(original, 39), false);
+ assert.equal(formatShotSeconds(17408, 1 / 12288), "1.417 s");
+ assert.equal(formatShotSeconds(NaN, 1 / 12288), "—");
+});
+
+test("removing an invalid cut keeps the other segment and its note", () => {
+ const split = splitShotDraft(splitShotDraft(original, 20), 30);
+ const noted = updateShotDraftSegment(split, 2, { description: "keep me" });
+ for (const startPts of [30, NaN]) {
+ const invalid = updateShotDraftSegment(noted, 1, { startPts });
+ assert.equal(validShotEdit(invalid, 40), false);
+ const repaired = removeShotDraftCut(invalid, 1);
+ assert.deepEqual(repaired.cuts, [{ startPts: 30, description: "keep me" }]);
+ assert.ok(validShotEdit(repaired, 40));
+ }
+});
diff --git a/tests/test_creation_shots.py b/tests/test_creation_shots.py
index 2eb3efc6b..9fe7b728d 100644
--- a/tests/test_creation_shots.py
+++ b/tests/test_creation_shots.py
@@ -26,8 +26,8 @@
@requires_ffmpeg()
-@pytest.mark.parametrize('model_failure', [None, 'rate-limit', 'malformed-content', 'detect-only'],
- ids=['model-ok', 'provider-429', 'bad-provider-content', 'detect-only'])
+@pytest.mark.parametrize('model_failure', [None, 'rate-limit', 'malformed-content', 'invalid-json', 'unavailable', 'detect-only'],
+ ids=['model-ok', 'provider-429', 'bad-provider-content', 'bad-description', 'provider-503', 'detect-only'])
def test_shot_evidence_and_interleaved_user_agent_edits(tmp_path, monkeypatch, model_failure):
media = tmp_path / 'input.mp4'
subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'color=red:s=32x32:r=24:d=1',
@@ -63,6 +63,10 @@ def model_response(request):
return httpx.Response(429, json={'error': {'code': 'rate_limit'}})
description = json.dumps(dict(subject='Red square', scene='Plain frame', framing='Full frame'))
content = [{'text': description}] if len(requests) == 2 and model_failure == 'malformed-content' else description
+ if len(requests) == 2 and model_failure == 'unavailable':
+ return httpx.Response(503)
+ if len(requests) == 2 and model_failure == 'invalid-json':
+ content = 'one unstructured sentence'
return httpx.Response(200, json={'choices': [{'message': {'content': content}}]})
monkeypatch.setattr(creation_shots, 'inspect_video_shots', scan)
@@ -104,12 +108,16 @@ def version(document):
detect_only = model_failure == 'detect-only'
created = client.post(route, json={} if detect_only else selected_model)
assert created.status_code == 200, created.text
+ stop_header = 'X-OpenDirector-Shot-Stop'
+ expected_stop = {'rate-limit': 'rate_limited', 'malformed-content': 'invalid_response',
+ 'invalid-json': 'invalid_response', 'unavailable': 'model_error'}
+ assert created.headers.get(stop_header) == expected_stop.get(model_failure)
original = created.json()
assert original['data']['originPts'] == 900
assert original['data']['source']['assetId'] == asset
shot, *other_shots = original['data']['shots']
assert len(other_shots) == 2
- assert all('joinPrevious' not in row['edit'] for row in original['data']['shots'])
+ assert all(not {'joinPrevious', 'cuts'}.intersection(row['edit']) for row in original['data']['shots'])
if detect_only:
assert shot['frameSuggestion'] is None
else:
@@ -126,7 +134,13 @@ def version(document):
assert [entry['used'] for entry in deletion.json()['usage']] == [True, True]
user_edit = deepcopy(original)
- user_edit['data']['shots'][0]['edit'].update(startPts=1, endPts=7, description='User correction')
+ cuts = [dict(startPts=4, description='Right of the missed cut')]
+ user_edit['data']['shots'][0]['edit'].update(startPts=1, endPts=7, description='User correction', cuts=cuts)
+ if detect_only:
+ for invalid_ticks in ([1], [7], [5, 4], [4, 4], [4.25]):
+ invalid = deepcopy(user_edit)
+ invalid['data']['shots'][0]['edit']['cuts'] = [dict(startPts=pts) for pts in invalid_ticks]
+ command('editor.save', dict(document=invalid), version(original), status=422)
for index in (0, 1):
invalid = deepcopy(user_edit)
invalid['data']['shots'][index]['edit']['joinPrevious'] = True
@@ -157,7 +171,7 @@ def version(document):
assert remaining == expected_remaining
assert updated['measured'] == shot['measured']
assert updated['frameSuggestion'] == shot['frameSuggestion']
- assert updated['edit'] == dict(startPts=1, endPts=7, description='User correction and Agent review')
+ assert updated['edit'] == dict(startPts=1, endPts=7, description='User correction and Agent review', cuts=cuts)
tampered = deepcopy(reopened)
tampered['data']['shots'][0]['frameSuggestion'] = dict(modelId='fake', subject='Overwritten',
scene='Fake', framing='Fake')
@@ -172,7 +186,9 @@ def version(document):
assert len(requests) == initial_calls
if model_failure == 'rate-limit':
rate_limited = True
- assert client.post(resume, json=selected_model).json() == reopened
+ stopped = client.post(resume, json=selected_model)
+ assert stopped.json() == reopened
+ assert stopped.headers[stop_header] == 'rate_limited'
assert len(requests) == initial_calls + 1
rate_limited = False
if detect_only:
@@ -203,6 +219,7 @@ def save_during_inference():
monkeypatch.setattr(creation_shots, 'MAX_DESCRIBED_SHOTS', 2)
resumed = client.post(resume, json=selected_model)
assert resumed.status_code == 200, resumed.text
+ assert stop_header not in resumed.headers
if detect_only:
assert [bool(s['frameSuggestion']) for s in resumed.json()['data']['shots']] == [True, True, False]
resumed = client.post(resume, json=selected_model)
@@ -260,3 +277,151 @@ def scan(_project, _asset, _session, directory):
assert not service.analysis_slot.locked()
asyncio.run(run())
+
+
+def _pause_after_two_staged_frames(repository, project_id, source_id, analysis, directory, session, ready):
+ from opendirector.wiring import configure_runtime
+
+ configure_runtime()
+ service = creation_shots.CreationShots(CreationProjects(LocalProjects(repository)), None)
+ stage = service.assets.stage_output
+ count = 0
+
+ def pause(*args, **kwargs):
+ nonlocal count
+ upload = stage(*args, **kwargs)
+ count += 1
+ if count == 2:
+ ready.set()
+ Event().wait(60)
+ return upload
+
+ service.assets.stage_output = pause
+ source = service.assets.get(project_id, source_id)
+ service._save_detection(project_id, source, analysis, directory, session)
+
+
+@requires_ffmpeg()
+@pytest.mark.parametrize('failure', ['staging', 'publication', 'process-exit'])
+def test_detection_publishes_all_frames_with_the_document(tmp_path, monkeypatch, failure):
+ import multiprocessing
+ from uuid import uuid5
+
+ from opendirector.application.creation_tool_assets import CreationToolAssets
+ from test_creation_assets import command, import_asset, ref
+
+ project_id, session = uuid4(), str(uuid4())
+ local = LocalProjects(tmp_path / 'projects')
+ projects = CreationProjects(local)
+ projects.execute(command(project_id, name='Shots'))
+ projects.open(project_id, session)
+ video = tmp_path / 'clip.mp4'
+ subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'color=red:s=32x32:r=24:d=1',
+ '-threads', '1', '-c:v', 'mpeg4', str(video)], check=True)
+ source, _, _ = import_asset((projects, project_id, session), video.name, video.read_bytes())
+ frames = []
+ for color in ('red', 'green', 'blue'):
+ buffer = BytesIO()
+ Image.new('RGB', (16, 16), color).save(buffer, 'JPEG')
+ frames.append(buffer.getvalue())
+
+ def scan(_video, directory):
+ shots = []
+ for index, data in enumerate(frames):
+ name = f'{index}.jpg'
+ (directory / name).write_bytes(data)
+ shots.append(dict(id=f'shot-{index}', startPts=index * 8, endPts=index * 8 + 8,
+ representative=dict(path=name, pts=index * 8 + 4)))
+ return dict(source=dict(sha256=source.fingerprint[7:], timeBase='1/24', originPts=0), shots=shots)
+
+ monkeypatch.setattr(creation_shots, 'inspect_video_shots', scan)
+ service = creation_shots.CreationShots(projects, None)
+ if failure == 'staging':
+ frame_id = uuid5(uuid5(source.id, 'reference-shot-breakdown'), 'shot-0:4')
+ old_frame = CreationToolAssets(projects).import_file(project_id, frame_id, 'old-name.jpg', frames[0],
+ session, sources=(ref(source),))
+ changed_id = uuid5(uuid5(source.id, 'reference-shot-breakdown'), 'shot-1:12')
+ old_encoding = CreationToolAssets(projects).import_file(project_id, changed_id, 'old-encoding.jpg', frames[0],
+ session, sources=(ref(source),))
+ before = projects.snapshot(project_id)
+ manifest = projects.root / 'Shots' / 'project.json'
+ old_manifest = manifest.read_bytes()
+ failure_count = 0
+ upload_dir = projects.state_dir / 'creation-uploads' / str(project_id)
+ retained_uploads = set()
+
+ def fail_second():
+ nonlocal failure_count
+ failure_count += 1
+ if failure_count == 2:
+ raise OSError('second frame interrupted')
+
+ if failure == 'process-exit':
+ ctx = multiprocessing.get_context('spawn')
+ ready = ctx.Event()
+ analysis = scan(video, tmp_path)
+ worker = ctx.Process(target=_pause_after_two_staged_frames,
+ args=(local.repository, project_id, source.id, analysis, tmp_path, session, ready))
+ worker.start()
+ try:
+ assert ready.wait(30)
+ assert len(list(upload_dir.glob('*/content'))) == 2
+ with pytest.raises(ProjectError) as busy:
+ service._save_detection(project_id, source, analysis, tmp_path, session)
+ assert busy.value.code == 'shot_analysis_busy'
+ assert len(list(upload_dir.glob('*/content'))) == 2
+ handle = uuid4()
+ other_data = frames[-1]
+ writer = service.assets.uploads.begin(project_id, handle, session, 'unrelated.jpg')
+ try:
+ writer.write(other_data)
+ writer.finish()
+ finally:
+ writer.abort()
+ other_content = upload_dir / str(handle) / 'content'
+ retained_uploads.add(other_content)
+ finally:
+ worker.kill()
+ worker.join(10)
+ assert not worker.is_alive()
+ assert worker.exitcode != 0
+ assert manifest.read_bytes() == old_manifest
+ del frames[1:]
+ else:
+ with monkeypatch.context() as fault:
+ if failure == 'staging':
+ stage = service.assets.stage_output
+
+ def interrupt_stage(*args, **kwargs):
+ fail_second()
+ return stage(*args, **kwargs)
+
+ fault.setattr(service.assets, 'stage_output', interrupt_stage)
+ else:
+ fault.setattr(projects, '_checkpoint', lambda stage: fail_second() if stage == 'asset_installed' else None)
+ with pytest.raises(OSError, match='second frame interrupted'):
+ asyncio.run(service.create(project_id, source.id, session))
+ assert failure_count == 2
+ assert manifest.read_bytes() == old_manifest
+ if failure == 'staging':
+ assert projects.snapshot(project_id) == before
+ assert not list(upload_dir.glob('*/content'))
+ restarted = creation_shots.CreationShots(CreationProjects(local), None)
+ document, stop_reason = asyncio.run(restarted.create(project_id, source.id, session))
+ assert stop_reason is None
+ current = restarted.projects.snapshot(project_id)
+ assert current.editorDocuments == (document,)
+ assert len(current.assets) == len(frames) + 1 + (failure == 'staging')
+ assert current.eventCursor == before.eventCursor + 1
+ if failure == 'staging':
+ assert str(document.data.shots[0].measured.representative.assetId) == old_frame['id']
+ assert restarted.assets.get(project_id, old_frame['id']).name == 'old-name.jpg'
+ assert str(document.data.shots[1].measured.representative.assetId) != old_encoding['id']
+ assert CreationToolAssets(restarted.projects).read_bytes(project_id, old_encoding['id']) == frames[0]
+ for shot, expected in zip(document.data.shots, frames, strict=True):
+ stream, _ = restarted.assets.open_media(project_id, shot.measured.representative.assetId)
+ with stream:
+ assert stream.read() == expected
+ assert set(upload_dir.glob('*/content')) == retained_uploads
+ if failure == 'process-exit':
+ assert other_content.read_bytes() == other_data
From 924bbde48ad7977818a7b233d00538505bb70845 Mon Sep 17 00:00:00 2001
From: Dragonborn <1078757180@qq.com>
Date: Tue, 1 Dec 2026 23:21:08 +0800
Subject: [PATCH 6/9] Keep a successful shot save independent of staging
cleanup
---
.../core/src/opendirector/application/creation_shots.py | 2 ++
tests/test_creation_shots.py | 9 +++++++++
2 files changed, 11 insertions(+)
diff --git a/packages/core/src/opendirector/application/creation_shots.py b/packages/core/src/opendirector/application/creation_shots.py
index 15497ecfd..962e0b861 100644
--- a/packages/core/src/opendirector/application/creation_shots.py
+++ b/packages/core/src/opendirector/application/creation_shots.py
@@ -132,6 +132,8 @@ def publish(before):
return CreationCanvas(self.projects).apply(with_frames, command)
receipt = self.projects.commit(command, publish, session=session, files=tuple(writes))
+ if receipt.status == 'applied':
+ staged.clear()
saved = self.get(project_id, source.id)
if saved is not None:
return saved
diff --git a/tests/test_creation_shots.py b/tests/test_creation_shots.py
index 9fe7b728d..a15b8ee48 100644
--- a/tests/test_creation_shots.py
+++ b/tests/test_creation_shots.py
@@ -407,6 +407,15 @@ def interrupt_stage(*args, **kwargs):
assert projects.snapshot(project_id) == before
assert not list(upload_dir.glob('*/content'))
restarted = creation_shots.CreationShots(CreationProjects(local), None)
+ if failure == 'staging':
+ discard = restarted.assets.uploads.discard_outputs
+
+ def reject_cleanup_after_publication(*args):
+ if restarted.get(project_id, source.id) is not None:
+ raise PermissionError('staging locked after successful publication')
+ return discard(*args)
+
+ monkeypatch.setattr(restarted.assets.uploads, 'discard_outputs', reject_cleanup_after_publication)
document, stop_reason = asyncio.run(restarted.create(project_id, source.id, session))
assert stop_reason is None
current = restarted.projects.snapshot(project_id)
From b531be7c5d07b70f47ed7acf3453ef3859b4222d Mon Sep 17 00:00:00 2001
From: Dragonborn <1078757180@qq.com>
Date: Wed, 2 Dec 2026 19:53:00 +0800
Subject: [PATCH 7/9] Clarify the pending frame seek and keep the README diff
focused
---
README.zh-CN.md | 2 +-
src/canvas/ShotBreakdownEditor.tsx | 11 +++++------
2 files changed, 6 insertions(+), 7 deletions(-)
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 47e10bd25..3fad376b6 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -30,7 +30,7 @@ OpenDirector 是一个在本地运行、通过浏览器使用的 AI 视频创作
-
+
## 最新动态
diff --git a/src/canvas/ShotBreakdownEditor.tsx b/src/canvas/ShotBreakdownEditor.tsx
index 10539bce8..1875e8720 100644
--- a/src/canvas/ShotBreakdownEditor.tsx
+++ b/src/canvas/ShotBreakdownEditor.tsx
@@ -83,7 +83,7 @@ export function ShotBreakdownEditor({
const [videoTime, setVideoTime] = useState(0);
const [playbackOrigin, setPlaybackOrigin] = useState(null);
const video = useRef(null);
- const requestedFrame = useRef(null);
+ const representativePtsBeforePlaybackReady = useRef(null);
const mounted = useRef(true);
const attachVideo = useCallback((element: HTMLVideoElement | null) => {
@@ -277,11 +277,10 @@ export function ShotBreakdownEditor({
element.pause();
}, [timeScale, playbackOrigin]);
- // A click can arrive before the first decoded frame establishes the video's time origin.
useEffect(() => {
- if (canSeek && requestedFrame.current !== null) {
- seek(requestedFrame.current);
- requestedFrame.current = null;
+ if (canSeek && representativePtsBeforePlaybackReady.current !== null) {
+ seek(representativePtsBeforePlaybackReady.current);
+ representativePtsBeforePlaybackReady.current = null;
}
}, [canSeek, seek]);
@@ -524,7 +523,7 @@ export function ShotBreakdownEditor({
onClick={() => {
if (shot.id === selectedShot?.id) return;
if (canSeek) seek(shot.measured.representativePts);
- else requestedFrame.current = shot.measured.representativePts;
+ else representativePtsBeforePlaybackReady.current = shot.measured.representativePts;
setSelectedShotId(shot.id);
}}
>
From 6aa64357f5e603d0ce4be721b4cd3cef8092fe6c Mon Sep 17 00:00:00 2001
From: Dragonborn <1078757180@qq.com>
Date: Wed, 2 Dec 2026 20:01:40 +0800
Subject: [PATCH 8/9] Create measured shot evidence only through video analysis
---
.../application/creation_canvas.py | 6 ++++-
.../application/creation_shots.py | 2 +-
tests/test_creation_shots.py | 26 +++++++++++++++++++
3 files changed, 32 insertions(+), 2 deletions(-)
diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py
index f4901b4db..ebc0d56e3 100644
--- a/packages/core/src/opendirector/application/creation_canvas.py
+++ b/packages/core/src/opendirector/application/creation_canvas.py
@@ -304,10 +304,14 @@ def _available(self, asset):
def execute(self, command, *, session=None, source='ui'):
return self.projects.commit(command, lambda before: self.apply(before, command), session=session, source=source)
- def apply(self, before, command, *, generated_suggestions=None):
+ def apply(self, before, command, *, generated_suggestions=None, detected_shot_document_id=None):
data = before.model_dump(mode='json')
operations = command.payload.operations if command.type == 'creation.batch' else [command]
for operation in operations:
+ if operation.type == 'editor.create':
+ document = operation.payload.document
+ if document.kind == 'shot_breakdown' and document.id != detected_shot_document_id:
+ raise ContractError('role_restricted', '请先通过参考视频分镜工具分析视频。', document.id)
if operation.type != 'canvas.applyEdit':
self._mutate(data, operation.type, operation.payload, generated_suggestions=generated_suggestions)
# Publish against the final document in this atomic batch.
diff --git a/packages/core/src/opendirector/application/creation_shots.py b/packages/core/src/opendirector/application/creation_shots.py
index 962e0b861..c3a3db7f9 100644
--- a/packages/core/src/opendirector/application/creation_shots.py
+++ b/packages/core/src/opendirector/application/creation_shots.py
@@ -129,7 +129,7 @@ def _publish_detection(self, project_id, source, analysis, directory, session, d
def publish(before):
with_frames = before.model_copy(update={'assets': (*before.assets, *images)})
- return CreationCanvas(self.projects).apply(with_frames, command)
+ return CreationCanvas(self.projects).apply(with_frames, command, detected_shot_document_id=document_id)
receipt = self.projects.commit(command, publish, session=session, files=tuple(writes))
if receipt.status == 'applied':
diff --git a/tests/test_creation_shots.py b/tests/test_creation_shots.py
index a15b8ee48..9646ee6b2 100644
--- a/tests/test_creation_shots.py
+++ b/tests/test_creation_shots.py
@@ -106,6 +106,32 @@ def version(document):
denied = client.post(route, json={}, headers={'X-OpenDirector-Session': str(uuid4())})
assert denied.status_code == 409 and not calls
detect_only = model_failure == 'detect-only'
+ if detect_only:
+ image_handle = str(uuid4())
+ client.put(path + '/uploads/' + image_handle, content=jpg.getvalue(), headers={
+ 'Content-Type': 'application/octet-stream', 'X-Asset-Name': 'other.jpg',
+ }).raise_for_status()
+ other_image = command('asset.import', dict(uploadHandle=image_handle, name='other.jpg',
+ expectedKind='image'))['changed'][0]['id']
+
+ def reference(asset_id):
+ saved_asset = client.get(f'{path}/assets/{asset_id}').raise_for_status().json()
+ return dict(assetId=asset_id, revision=saved_asset['revision'],
+ fingerprint=saved_asset['fingerprint'], kind=saved_asset['kind'])
+
+ synthetic = dict(id=str(uuid4()), projectId=str(project_id), kind='shot_breakdown', data=dict(
+ source=reference(asset), timeBase='1/24', originPts=0, durationPts=24, shots=[
+ dict(id='shot-0001', measured=dict(startPts=0, endPts=24, representativePts=12,
+ representative=reference(other_image)),
+ edit=dict(startPts=0, endPts=24)),
+ ]))
+ operation = dict(type='editor.create', payload=dict(document=synthetic))
+ for kind, payload in (('editor.create', operation['payload']),
+ ('creation.batch', dict(operations=[operation]))):
+ rejected = command(kind, payload)
+ assert rejected['status'] == 'rejected'
+ assert rejected['issues'][0]['code'] == 'role_restricted'
+ assert client.get(route).json() is None
created = client.post(route, json={} if detect_only else selected_model)
assert created.status_code == 200, created.text
stop_header = 'X-OpenDirector-Shot-Stop'
From a9e762fd13c7259b4236be3e1e1daa8515267031 Mon Sep 17 00:00:00 2001
From: Dragonborn <1078757180@qq.com>
Date: Wed, 2 Dec 2026 22:57:49 +0800
Subject: [PATCH 9/9] Remove trailing whitespace from the Chinese README
---
README.zh-CN.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 3fad376b6..47e10bd25 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -30,7 +30,7 @@ OpenDirector 是一个在本地运行、通过浏览器使用的 AI 视频创作
-
+
## 最新动态