diff --git a/README.md b/README.md
index de194958a..66397f76b 100644
--- a/README.md
+++ b/README.md
@@ -98,6 +98,8 @@ Configure a model service in **Settings → Model connections** to use AI chat a
Use Chrome or Edge for MP4 export, and keep the page and editor open while rendering.
+For a reference video, [edit its shot breakdown](docs/guides/user-guide.md#edit-a-reference-videos-shot-breakdown) to review detected cuts, adjust shot ranges, and save descriptions with the project.
+
## Documentation
- [Installation and updates](docs/guides/installation.md): Prerequisites, platform instructions, startup, and updates.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index b28e0a2df..47e10bd25 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -30,7 +30,7 @@ OpenDirector 是一个在本地运行、通过浏览器使用的 AI 视频创作
-
+
## 最新动态
@@ -98,6 +98,8 @@ opendirector serve
导出 MP4 推荐使用 Chrome 或 Edge,合成期间需保持页面和编辑器打开。
+有参考视频时,可以[编辑分镜](docs/guides/user-guide.zh-CN.md#编辑参考视频的分镜),复核检测切点、调整镜头区间,并将描述保存在项目中。
+
## 文档
- [安装与更新](docs/guides/installation.zh-CN.md):环境准备、各平台安装、启动与更新。
diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py
index 8081f3a84..a719add9e 100644
--- a/apps/api/src/opendirector_api/creation.py
+++ b/apps/api/src/opendirector_api/creation.py
@@ -13,32 +13,32 @@
from urllib.parse import quote, unquote
from fastapi import APIRouter, Header, Query, Request
-from pydantic import BaseModel, Field
from fastapi.responses import FileResponse, Response, StreamingResponse
from filelock import Timeout
+from pydantic import BaseModel, ConfigDict, Field
from starlette.background import BackgroundTask, BackgroundTasks
from starlette.concurrency import run_in_threadpool
from opendirector.application.creation_assets import CreationAssets
from opendirector.application.creation_canvas import CreationCanvas
from opendirector.application.creation_history import CreationHistory
+from opendirector.application.creation_shots import CreationShots
from opendirector.application.creation_timeline_packages import CreationTimelinePackages
from opendirector.application.creation_video_compatibility import CreationVideoCompatibility, VideoConversionTask
-from opendirector.domain.creation.timeline_packages import TimelinePackageImportRequest, TimelinePackageImportReceipt
from opendirector.domain.creation.assets import ASSET_REVISION_HEADER, Asset, UploadInfo
from opendirector.domain.creation.base import MediaKind
from opendirector.domain.creation.commands import Command, CommandReceipt, Query as CreationQuery
+from opendirector.domain.creation.editors import ShotBreakdownDocument
from opendirector.domain.creation.project import ProjectSnapshot, ViewState
+from opendirector.domain.creation.timeline_packages import TimelinePackageImportRequest, TimelinePackageImportReceipt
from opendirector.domain.projects import ProjectError
from opendirector.application.prompt_optimization import PromptOptimizationInput
from opendirector.domain.timeline_errors import timeline_error, timeline_error_message
from opendirector.infrastructure.creation_projects import CreationProjects
from opendirector.media.fonts import MAX_FONT_BYTES, inspect_font
from opendirector.media.system_fonts import list_local_system_fonts
+from opendirector_api.localization import localized_error_for_language, localized_receipt, wants_english
from opendirector_api.models import AssetSource, Session, UrlSource
-from opendirector_api.localization import localized_receipt
-
-from opendirector_api.localization import localized_error_for_language
class FontCoverageResponse(BaseModel):
@@ -84,13 +84,23 @@ async def disconnected():
await asyncio.gather(work, disconnect, return_exceptions=True)
-def creation_routes(projects: CreationProjects, generation=None, prompt_optimization=None):
+class ShotBreakdownRequest(BaseModel):
+ model_config = ConfigDict(extra='forbid')
+ 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)
assets = CreationAssets(projects)
canvas = CreationCanvas(projects)
history = CreationHistory(projects, assets=assets)
timeline_packages = CreationTimelinePackages(projects)
+ shots = CreationShots(projects, model_configs)
video_compat = CreationVideoCompatibility(projects)
def localized_video_task(request: Request, task: VideoConversionTask) -> VideoConversionTask:
@@ -459,6 +469,32 @@ def list_assets(project_id: UUID):
def describe_asset(project_id: UUID, asset_id: UUID):
return assets.get(project_id, asset_id)
+ @router.get('/projects/{project_id}/assets/{asset_id}/shot-breakdown', response_model=ShotBreakdownDocument | None)
+ 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, response: Response,
+ x_opendirector_session: UUID = Header()):
+ 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, response: Response,
+ x_opendirector_session: UUID = Header()):
+ 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):
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 94914358a..b7f4e5aec 100644
--- a/apps/api/src/opendirector_api/localization.py
+++ b/apps/api/src/opendirector_api/localization.py
@@ -111,6 +111,16 @@
'voice_provider_timeout': 'The voice service timed out. Check its status and try again.',
'voice_name_taken': 'This account already has a voice with that name. Choose another name.',
'voice_provider_quota': 'The voice service account has insufficient balance or resource packages. Top up and try again.',
+ "shot_evidence_immutable": "The original detection and model suggestions are read-only.",
+ "shot_video_required": "Select a video stored in this project.",
+ "shot_video_duration": "Shot analysis accepts videos up to 120 seconds.",
+ "shot_analysis_failed": "Could not analyze the video. Check that it can be decoded and is at most 120 seconds.",
+ "shot_dependencies": "Install opendirector[shot-analysis] to analyze reference videos.",
+ "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_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/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py
index 1a5d95024..cdfa4a077 100644
--- a/apps/api/src/opendirector_api/main.py
+++ b/apps/api/src/opendirector_api/main.py
@@ -98,7 +98,7 @@ async def lifespan(app):
app = FastAPI(title="OpenDirector Local API", version="0.1.7", lifespan=lifespan)
app.include_router(creation_routes(creation_projects, creation_generation,
PromptOptimization(creation_projects, model_configs, chat_provider or ChatCompletions(),
- cli_rewrite=_cli_prompt_rewrite)))
+ cli_rewrite=_cli_prompt_rewrite), model_configs=model_configs))
app.include_router(agent_routes(creation_projects, creation_generation, model_configs, chat_provider, active=active_agents))
app.include_router(motion_routes(motion_generation, projects=creation_projects))
app.include_router(library_routes(creation_projects))
diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md
index 0a97c9715..6981ad67b 100644
--- a/docs/guides/user-guide.md
+++ b/docs/guides/user-guide.md
@@ -242,6 +242,18 @@ Right-click the canvas, choose **New node → Import video from link**, and past
- Which sites work depends on the yt-dlp downloader. Some sites block downloads from servers or data centres, and some (such as YouTube) may need extra yt-dlp components. If the import fails, download the file yourself and use **Upload**.
- Import only videos you have the right to use. The asset is named after the page title; the link itself is not stored in the project.
+## Edit a reference video's shot breakdown
+
+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.
+
+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. 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. 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.
+
## Arrange and export videos
1. Create a timeline node and open its editor.
diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md
index 981ef886d..6ec178263 100644
--- a/docs/guides/user-guide.zh-CN.md
+++ b/docs/guides/user-guide.zh-CN.md
@@ -242,6 +242,18 @@ Codex 网页检索引用在具有匹配来源时显示为编号链接;复制
- 可用站点取决于 yt-dlp 下载组件:部分网站会拦截服务器或机房的下载,部分网站(如 YouTube)可能需要额外的 yt-dlp 组件。导入失败时,可自行下载后使用 **上传**。
- 请只导入你有权使用的视频。素材以网页标题命名,工程中不保存链接本身。
+## 编辑参考视频的分镜
+
+在运行 OpenDirector 的 Python 环境执行 `python -m pip install 'opendirector[shot-analysis]'` 安装可选分析依赖,源码工作区可执行 `python -m pip install -e '.[shot-analysis]'`。准备好 FFmpeg 和 FFprobe。把视频导入画布,选中视频节点并打开**分镜**。点击**分析分镜**后,应用用 CPU 检测切点,为每镜保存一张代表帧。
+
+本地检测支持 120 秒以内、最多 48 个镜头的视频。如果需要主体、场景和景别建议,可在点击**分析分镜**前选择支持图片输入的对话模型,也可以先保存检测结果,以后再选模型。每次最多处理 12 个镜头,每镜向所选模型发送一张 JPEG 代表帧。
+
+分镜顶部会显示还有多少镜头缺少建议。先保存草稿修改,再选择模型,点击**补全缺失建议**,就能用已有的代表帧处理下一批。遇到模型限流或返回内容无法读取时,编辑器会提示原因。问题解决后,点击**补全缺失建议**即可接着处理,重开视频后也可以继续。每次补全都会保留检测区间、已有建议和你保存的修改。
+
+在原片里对照检测区间和草稿边界,修改后点击**保存分镜**。重开同一个视频仍可查看原检测区间、代表帧和模型建议。区间使用源视频的归一化时间戳,终点不含在区间内。多切了一刀时,选中切点后的镜头。若两段草稿首尾相接,点击**与上一镜合并**。用**恢复此切点**可加回切点。漏切了一刀时,在原视频里暂停到要切的位置,点击**在播放位置拆分**,就能给切点两边各写一段描述。手动拆分直接使用原片,不消耗模型额度。
+
+让助手接着编辑前,先保存自己的修改。如果助手保存了新版本,编辑器会保留你尚未保存的草稿,重新加载前会请你确认是否丢弃。
+
## 编排和导出视频
1. 创建时间线节点并打开编辑器。
diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py
index a2c3a2f73..3fe2d4526 100644
--- a/packages/core/src/opendirector/application/creation_canvas.py
+++ b/packages/core/src/opendirector/application/creation_canvas.py
@@ -312,12 +312,16 @@ 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, 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)
+ 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:
@@ -512,7 +516,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))
@@ -543,6 +547,11 @@ def _mutate(self, data, kind, payload):
immutable = ('kind', 'purpose', 'currentResultId') if key == 'spec' else ('kind',)
if any(obj[field] != old[field] for field in (*immutable, 'projectId')):
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(generated_suggestions)
+ if payload.document.data.analysis_basis() != basis:
+ raise ContractError('shot_evidence_immutable', '不能修改原始分镜检测或模型建议。', UUID(obj['id']))
for item in data['canvasItems']:
binding = item['binding']
ref = binding.get('objectRef') or binding.get('draftSpec')
diff --git a/packages/core/src/opendirector/application/creation_shots.py b/packages/core/src/opendirector/application/creation_shots.py
new file mode 100644
index 000000000..c3a3db7f9
--- /dev/null
+++ b/packages/core/src/opendirector/application/creation_shots.py
@@ -0,0 +1,249 @@
+"""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 uuid4, uuid5
+
+from opendirector.application.creation_assets import CreationAssets
+from opendirector.application.creation_canvas import CreationCanvas, asset_ref
+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
+
+
+class CreationShots:
+ def __init__(self, projects, model_configs):
+ self.projects = projects
+ self.model_configs = model_configs
+ self.assets = CreationAssets(projects)
+ self.analysis_slot = asyncio.Lock()
+
+ def get(self, project_id, asset_id):
+ snapshot = self.projects.snapshot(project_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()
+ project_path, _ = self.projects._find(db, project_id)
+ self.projects._lease(db, project_id, project_path, session)
+
+ def _inspect(self, project_id, asset_id, session, directory):
+ self._require_session(project_id, session)
+ asset = self.assets.get(project_id, asset_id)
+ if asset.kind != 'video':
+ raise ProjectError('仅支持工程内的视频素材。', code='shot_video_required')
+ if asset.metadata.durationSeconds and asset.metadata.durationSeconds > DEFAULT_MAX_DURATION_SECONDS:
+ raise ProjectError('分镜分析仅支持 120 秒以内的视频。', code='shot_video_duration')
+ video = directory / 'source'
+ stream, source = self.assets.open_media(project_id, asset_id)
+ with stream, video.open('wb') as target:
+ copyfileobj(stream, target)
+ try:
+ analysis = inspect_video_shots(video, directory)
+ except (ImportError, RuntimeError, ValueError) as exc:
+ if isinstance(exc, ImportError) or isinstance(exc.__cause__, ImportError):
+ raise ProjectError('分镜分析需要可选依赖。请安装 opendirector[shot-analysis]。',
+ 503, code='shot_dependencies') from exc
+ raise ProjectError('无法分析这段视频。请确认视频可解码且时长不超过 120 秒。',
+ code='shot_analysis_failed') from exc
+ if source.fingerprint != 'sha256:' + analysis['source']['sha256']:
+ raise ProjectError('视频内容已变化,请重新导入后分析。', 409, code='storage_unavailable')
+ return source, analysis
+
+ 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)
+ 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, detected_shot_document_id=document_id)
+
+ 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
+ code = receipt.issues[0].code if receipt.issues else 'operation_rejected'
+ raise ProjectError('保存分镜失败,请重新打开工程后再试。', 409, code=code)
+ finally:
+ if staged:
+ self.assets.uploads.discard_outputs(project_id, staged)
+
+ @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, 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)
+ 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')
+ saved = await blocking(self._save_detection, project_id, source, analysis, directory, session)
+ 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, None
+ 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):
+ 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) 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, None
+ 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/packages/core/src/opendirector/application/shot_descriptions.py b/packages/core/src/opendirector/application/shot_descriptions.py
new file mode 100644
index 000000000..c5bdc57e7
--- /dev/null
+++ b/packages/core/src/opendirector/application/shot_descriptions.py
@@ -0,0 +1,221 @@
+"""Bounded frame-only descriptions for explicitly selected reference shots.
+
+One representative JPEG is described per request through the configured chat
+adapter. The result records the exact frame bytes and measured timing as model
+inference; it is never treated as a source fact or a user edit.
+"""
+
+from fractions import Fraction
+import hashlib
+import json
+import re
+import time
+
+from opendirector.domain.capabilities import ChatRequest, agent_input_modalities
+from opendirector.domain.input_rules import input_rules
+from opendirector.integrations.model_adapters import adapter_for
+from opendirector.integrations.reference_inputs import data_uri, image_type, request_size
+
+SCHEMA_VERSION = 1
+DEFAULT_MAX_TOKENS = 384
+MAX_FIELD_CHARS = 1200
+LANGUAGES = {
+ "en-US": "Write the three field values in English.",
+ "zh-CN": "字段值请使用简体中文;画面无法确认的内容写“无法判断”。",
+}
+_FENCE = re.compile(r"^```(?:json)?\s*(.*?)\s*```$", re.S)
+_SYSTEM = (
+ "You describe one representative still frame from a video shot. Return only "
+ "a JSON object with exactly three non-empty string fields: \"subject\", "
+ "\"scene\", and \"framing\". Report only what is visible in this single frame. "
+ "You may mention visible pose or objects being held. Do not claim or infer "
+ "temporal change, motion, actions across time, camera movement, audio, "
+ "identities, named people, story meaning, or events that one frame cannot "
+ "show. Write \"unclear\" instead of guessing. Your text is model inference "
+ "about the frame, not a source fact or a user edit. Do not add prose outside "
+ "the JSON object."
+)
+
+
+def validate_frame_description_config(config, *, transport=None):
+ """Reject a configuration that cannot serve one frame description."""
+ if not isinstance(config, dict):
+ raise ValueError("镜头描述需要已配置的对话模型。")
+ if config.get("kind") != "agent":
+ raise ValueError("镜头描述需要已配置的对话模型(kind=agent)。")
+ modalities = agent_input_modalities(config["kind"], config.get("inputModalities"))
+ if "image" not in modalities:
+ raise ValueError("镜头描述需要支持图片输入的对话模型,请启用图片输入模态。")
+ if not config.get("id") or not config.get("modelId") or not config.get("url"):
+ raise ValueError("模型配置缺少 id、modelId 或 url。")
+ adapter = adapter_for(config, transport)
+ if adapter is None or "text.chat" not in adapter.capabilities:
+ raise ValueError("所选模型不提供文本对话能力,不能用于镜头描述。")
+
+
+def frame_reference(shot):
+ """Validate one shot and return its exact representative-frame provenance."""
+ if not isinstance(shot, dict):
+ raise ValueError("镜头记录无效。")
+ shot_id = shot.get("id")
+ if not isinstance(shot_id, str) or not shot_id.strip():
+ raise ValueError("镜头缺少有效 id。")
+ representative = shot.get("representative")
+ if not isinstance(representative, dict):
+ raise ValueError(f"镜头 {shot_id} 缺少代表帧。")
+ path = representative.get("path")
+ if not isinstance(path, str) or not path.strip():
+ raise ValueError(f"镜头 {shot_id} 的代表帧缺少路径。")
+ start_pts = _integer(shot.get("startPts"), "startPts", shot_id)
+ end_pts = _integer(shot.get("endPts"), "endPts", shot_id)
+ pts = _integer(representative.get("pts"), "representative.pts", shot_id)
+ if not start_pts <= pts < end_pts:
+ raise ValueError(
+ f"镜头 {shot_id} 的代表帧 PTS {pts} 不在区间 "
+ f"[{start_pts}, {end_pts}) 内。"
+ )
+ shot_time_base = _time_base(shot.get("timeBase"), "timeBase", shot_id)
+ representative_time_base = _time_base(
+ representative.get("timeBase"), "representative.timeBase", shot_id
+ )
+ if shot_time_base != representative_time_base:
+ raise ValueError(f"镜头 {shot_id} 的镜头与代表帧 timeBase 不一致。")
+ seconds = round(float(Fraction(pts) * shot_time_base), 6)
+ return {
+ "path": path,
+ "pts": pts,
+ "timeBase": _time_base_text(shot_time_base),
+ "seconds": seconds,
+ "startSeconds": round(float(Fraction(start_pts) * shot_time_base), 6),
+ "endSeconds": round(float(Fraction(end_pts) * shot_time_base), 6),
+ }
+
+
+async def describe_shot_frame(
+ config, shot, image_bytes, *, transport=None,
+ max_tokens=DEFAULT_MAX_TOKENS, language="en-US"
+):
+ """Describe one representative JPEG and return a frame-only provenance row."""
+ validate_frame_description_config(config, transport=transport)
+ frame = frame_reference(shot)
+ if not isinstance(image_bytes, (bytes, bytearray)) or not image_bytes:
+ raise ValueError("代表帧图片为空。")
+ if image_type(image_bytes) != "image/jpeg":
+ raise ValueError("镜头描述只接受 JPEG 代表帧。")
+ if (
+ not isinstance(max_tokens, int)
+ or isinstance(max_tokens, bool)
+ or max_tokens < 1
+ ):
+ raise ValueError("max_tokens 必须是正整数。")
+ if language not in LANGUAGES:
+ raise ValueError("language 必须是 en-US 或 zh-CN。")
+
+ rules = input_rules(config)
+ if len(image_bytes) > rules["imageBytes"]:
+ raise ValueError("代表帧图片超过当前对话模型的参考图片大小限制。")
+ messages = _messages(shot["id"], frame, image_bytes, language)
+ request_size(messages, rules["requestBytes"])
+
+ adapter = adapter_for(config, transport)
+ started = time.perf_counter()
+ content = await adapter.chat(
+ config, ChatRequest(messages=tuple(messages), max_tokens=max_tokens)
+ )
+ request_seconds = round(time.perf_counter() - started, 6)
+ description = _parse_description(content)
+
+ return {
+ "shotId": shot["id"],
+ "mode": "frame_only",
+ "interpretation": "model_inference",
+ "language": language,
+ "inputFrame": {
+ "path": frame["path"],
+ "sha256": hashlib.sha256(image_bytes).hexdigest(),
+ "pts": frame["pts"],
+ "timeBase": frame["timeBase"],
+ "seconds": frame["seconds"],
+ },
+ "model": {"configId": config["id"], "modelId": config["modelId"]},
+ "description": description,
+ "requestSeconds": request_seconds,
+ }
+
+
+def _messages(shot_id, frame, image_bytes, language):
+ text = (
+ f"Shot {shot_id}: measured interval {frame['startSeconds']:.6f}s to "
+ f"{frame['endSeconds']:.6f}s. Representative frame timestamp "
+ f"{frame['seconds']:.6f}s (pts {frame['pts']}, "
+ f"timeBase {frame['timeBase']}). Describe only this single still frame "
+ "and return the JSON object with subject, scene, and framing."
+ )
+ return [
+ {"role": "system", "content": _SYSTEM + " " + LANGUAGES[language]},
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": text},
+ {
+ "type": "image_url",
+ "image_url": {"url": data_uri(image_bytes, "image/jpeg")},
+ },
+ ],
+ },
+ ]
+
+
+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 InvalidShotDescription("模型没有返回镜头描述。")
+ text = content.strip()
+ match = _FENCE.match(text)
+ if match:
+ text = match.group(1).strip()
+ try:
+ value = json.loads(text)
+ except (TypeError, ValueError):
+ raise InvalidShotDescription("模型返回的镜头描述不是有效 JSON。") from None
+ if not isinstance(value, dict) or set(value) != {"subject", "scene", "framing"}:
+ raise InvalidShotDescription(
+ "模型返回的镜头描述必须且只能包含 subject、scene、framing。"
+ )
+ description = {}
+ for key in ("subject", "scene", "framing"):
+ item = value[key]
+ if not isinstance(item, str):
+ raise InvalidShotDescription(f"模型返回的 {key} 必须是非空字符串。")
+ item = item.strip()
+ if not item or len(item) > MAX_FIELD_CHARS:
+ raise InvalidShotDescription(
+ f"模型返回的 {key} 必须为 1–{MAX_FIELD_CHARS} 个字符。"
+ )
+ description[key] = item
+ return description
+
+
+def _integer(value, field, shot_id):
+ if not isinstance(value, int) or isinstance(value, bool):
+ raise ValueError(f"镜头 {shot_id} 的 {field} 必须是整数 PTS。")
+ return value
+
+
+def _time_base(value, field, shot_id):
+ if value is None:
+ raise ValueError(f"镜头 {shot_id} 缺少 {field}。")
+ try:
+ result = Fraction(str(value).strip())
+ except (TypeError, ValueError, ZeroDivisionError):
+ raise ValueError(f"镜头 {shot_id} 的 {field} 不是有理时间基。") from None
+ if result <= 0:
+ raise ValueError(f"镜头 {shot_id} 的 {field} 必须为正数。")
+ return result
+
+
+def _time_base_text(value):
+ return f"{value.numerator}/{value.denominator}"
diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py
index 124476e58..316dfd430 100644
--- a/packages/core/src/opendirector/domain/creation/commands.py
+++ b/packages/core/src/opendirector/domain/creation/commands.py
@@ -615,7 +615,7 @@ def command_fingerprint(command: Command) -> str:
'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']
+ 'voice_name_taken', 'voice_provider_quota', 'shot_evidence_immutable']
class ContractIssue(Contract):
diff --git a/packages/core/src/opendirector/domain/creation/editors.py b/packages/core/src/opendirector/domain/creation/editors.py
index b97343050..2665d90b6 100644
--- a/packages/core/src/opendirector/domain/creation/editors.py
+++ b/packages/core/src/opendirector/domain/creation/editors.py
@@ -12,6 +12,8 @@
from .assets import AssetRef
from .base import Contract, Identifier, NonNegative, Number, Point, Positive, PositiveInt, ProjectEntity, unique
+ShotTick = Annotated[int, Field(strict=True, ge=0)]
+
Color = Annotated[str, Field(pattern=r'^#[0-9a-fA-F]{6}$')]
Unit = Annotated[float, Field(strict=True, ge=0, le=1)]
@@ -639,6 +641,91 @@ class MediaEditDocument(EditorDocumentBase):
data: MediaEditData = Field(description='Typed editable document contents.')
+class MeasuredShot(Contract):
+ startPts: ShotTick = Field(description='Detected inclusive start in normalized source ticks.')
+ endPts: PositiveInt = Field(description='Detected exclusive end in normalized source ticks.')
+ representativePts: ShotTick = Field(description='PTS of the selected source frame.')
+ representative: AssetRef = Field(description='Pinned representative image.')
+
+ @model_validator(mode='after')
+ def evidence(self):
+ if self.representative.kind != 'image' or not self.startPts <= self.representativePts < self.endPts:
+ raise ValueError('The representative must be an image inside the detected interval')
+ return self
+
+
+class ShotFrameSuggestion(Contract):
+ modelId: str = Field(min_length=1, description='Model that described the representative frame.')
+ subject: str = Field(min_length=1, max_length=1200, description='Subject visible in the representative frame.')
+ scene: str = Field(min_length=1, max_length=1200, description='Scene visible in the representative frame.')
+ 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.')
+
+
+class BreakdownShot(Contract):
+ id: Identifier = Field(description='Stable ID within the breakdown.')
+ measured: MeasuredShot = Field(description='Original detector evidence.')
+ frameSuggestion: ShotFrameSuggestion | None = Field(default=None, description='Optional still-frame interpretation.')
+ edit: ShotEdit = Field(description='Editable interval and description.')
+
+
+class ShotBreakdownData(Contract):
+ source: AssetRef = Field(description='Pinned reference video.')
+ timeBase: str = Field(pattern=r'^[1-9][0-9]*/[1-9][0-9]*$', description='Seconds per source tick.')
+ originPts: int = Field(strict=True, description='Stream PTS of the first decoded frame.')
+ durationPts: PositiveInt = Field(description='Exclusive end of the analyzed video in normalized ticks.')
+ shots: tuple[BreakdownShot, ...] = Field(min_length=1, description='Ordered detected shots and their editable versions.')
+
+ @model_validator(mode='after')
+ def evidence(self):
+ unique([shot.id for shot in self.shots], 'shot IDs')
+ if self.source.kind != 'video':
+ raise ValueError('Shot breakdown requires a video source')
+ cursor = 0
+ previous_edit_end = None
+ for shot in self.shots:
+ if shot.measured.startPts != cursor:
+ raise ValueError('Detected intervals must cover the source continuously')
+ 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
+ if cursor != self.durationPts:
+ raise ValueError('Last measured shot must end at the analyzed video end')
+ return 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 or generated.get(shot.id)) for shot in self.shots))
+
+
+class ShotBreakdownDocument(EditorDocumentBase):
+ kind: Literal['shot_breakdown'] = Field(description='Reference video shot breakdown.')
+ data: ShotBreakdownData = Field(description='Source video, measured evidence, suggestions and user edits.')
+
+
class MotionInputRef(Contract):
id: Identifier = Field(description='Stable motion input slot ID.')
title: str = Field(default='', max_length=255, description='User-visible reference title.')
@@ -771,4 +858,4 @@ class MotionDocument(EditorDocumentBase):
EditorDocument = Annotated[TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument |
- ToolDocument | DirectorDocument | MediaEditDocument | MotionDocument, Field(discriminator='kind')]
+ ToolDocument | DirectorDocument | MediaEditDocument | MotionDocument | ShotBreakdownDocument, Field(discriminator='kind')]
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 eead9a10f..419a395c1 100644
--- a/packages/core/src/opendirector/infrastructure/creation_uploads.py
+++ b/packages/core/src/opendirector/infrastructure/creation_uploads.py
@@ -222,6 +222,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 e700a7e3f..04e69944d 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/packages/core/src/opendirector/integrations/model_adapters.py b/packages/core/src/opendirector/integrations/model_adapters.py
index 25aa73823..237591012 100644
--- a/packages/core/src/opendirector/integrations/model_adapters.py
+++ b/packages/core/src/opendirector/integrations/model_adapters.py
@@ -920,8 +920,8 @@ async def work():
async with client.stream('POST', endpoint(config['url'], '/chat/completions'), headers=auth_headers(config),
json=payload) as response:
value = json.loads(await bounded(response, stage='submit', secrets=(config.get('apiKey', ''),)))
- return value['choices'][0]['message']['content'] or ''
- return self.THINKING.sub('', await _call('submit', work)).strip()
+ return self.THINKING.sub('', value['choices'][0]['message']['content'] or '').strip()
+ return await _call('submit', work)
class VllmOmniSegmentation(ModelAdapter):
diff --git a/packages/core/src/opendirector/media/shot_detection.py b/packages/core/src/opendirector/media/shot_detection.py
new file mode 100644
index 000000000..eefb359c3
--- /dev/null
+++ b/packages/core/src/opendirector/media/shot_detection.py
@@ -0,0 +1,818 @@
+"""Bounded shot analysis for reference videos.
+
+This internal analysis slice decodes a bounded source with PyAV, feeds real frame
+timestamps to PySceneDetect's AdaptiveDetector, and writes representative JPEGs.
+It does not call a VLM, create descriptions, or persist project objects.
+"""
+
+from bisect import bisect_left
+from fractions import Fraction
+import hashlib
+import json
+import math
+from pathlib import Path
+import subprocess
+import time
+
+from opendirector.media.probe import probe_file, require_ffprobe
+
+SCHEMA_VERSION = 1
+DEFAULT_MAX_DURATION_SECONDS = 120.0
+DEFAULT_REPRESENTATIVE_INTENSITY_THRESHOLD = 12.0
+_JPEG_QUALITY = 85
+_REPRESENTATIVE_CANDIDATE_LIMIT = 3
+_REPRESENTATIVE_SAMPLE_WIDTH = 64
+_FFPROBE_STREAM_FIELDS = (
+ "index,codec_name,width,height,time_base,avg_frame_rate,r_frame_rate,"
+ "duration,duration_ts,start_time,start_pts,nb_frames"
+)
+
+
+def inspect_video_shots(
+ path,
+ output_directory,
+ adaptive_threshold=3.0,
+ min_scene_seconds=0.1,
+ min_content_val=15.0,
+ max_width=640,
+ representative_intensity_threshold=DEFAULT_REPRESENTATIVE_INTENSITY_THRESHOLD,
+ *,
+ max_duration_seconds=DEFAULT_MAX_DURATION_SECONDS,
+):
+ """Decode a bounded video and return a concise shot analysis record.
+
+ Representative frames are written below ``output_directory/frames``. All PTS
+ values in shots are normalized to the first decoded frame and expressed in
+ ``source.timeBase`` units. ``source.originPts`` and ``lastFramePts`` retain
+ native stream PTS. Seconds never come from a frame ordinal divided by FPS.
+
+ Brightness of up to three sampled frames is a heuristic, not a semantic
+ quality score. Dark footage remains valid and can be marked low_visibility.
+ """
+ source_path = Path(path)
+ output_path = Path(output_directory)
+ if not source_path.is_file():
+ raise ValueError(f"Video does not exist: {source_path}")
+ if not math.isfinite(adaptive_threshold) or adaptive_threshold <= 0:
+ raise ValueError("adaptive_threshold must be a positive finite number")
+ if not math.isfinite(min_scene_seconds) or min_scene_seconds < 0:
+ raise ValueError("min_scene_seconds must be a non-negative finite number")
+ if not math.isfinite(min_content_val) or min_content_val < 0:
+ raise ValueError("min_content_val must be a non-negative finite number")
+ if not isinstance(max_width, int) or max_width < 1:
+ raise ValueError("max_width must be a positive integer")
+ if not math.isfinite(representative_intensity_threshold) or not (
+ 0 <= representative_intensity_threshold <= 255
+ ):
+ raise ValueError(
+ "representative_intensity_threshold must be a finite number "
+ "between 0 and 255"
+ )
+ if not math.isfinite(max_duration_seconds) or max_duration_seconds <= 0:
+ raise ValueError("max_duration_seconds must be a positive finite number")
+
+ output_path.mkdir(parents=True, exist_ok=True)
+ (output_path / "frames").mkdir(parents=True, exist_ok=True)
+
+ probe_started = time.perf_counter()
+ try:
+ probe_info = probe_file(
+ source_path, "video", include_container=True, include_codecs=True
+ )
+ except Exception as exc:
+ raise RuntimeError(f"Could not probe video {source_path.name}") from exc
+ stream_info = _ffprobe_video_stream(source_path)
+ stream_duration = _positive_float(stream_info.get("duration"))
+ if stream_duration is not None and stream_duration > max_duration_seconds:
+ raise ValueError(
+ f"Video is {stream_duration:.3f}s, above the {max_duration_seconds:.3f}s limit"
+ )
+ if stream_duration is None:
+ probe_duration = _positive_float(probe_info.get("durationSeconds"))
+ if probe_duration is not None and probe_duration > max_duration_seconds:
+ raise ValueError(
+ f"Video is {probe_duration:.3f}s, above the {max_duration_seconds:.3f}s limit"
+ )
+ probe_seconds = time.perf_counter() - probe_started
+
+ hash_started = time.perf_counter()
+ digest = _sha256(source_path)
+ hash_seconds = time.perf_counter() - hash_started
+
+ detection_started = time.perf_counter()
+ detection = _detect_cuts(
+ source_path,
+ probe_info,
+ stream_info,
+ adaptive_threshold=adaptive_threshold,
+ min_scene_seconds=min_scene_seconds,
+ min_content_val=min_content_val,
+ max_width=max_width,
+ max_duration_seconds=max_duration_seconds,
+ )
+ detection_seconds = time.perf_counter() - detection_started
+
+ time_base = detection["time_base"]
+ frame_pts = detection["frame_pts"]
+ shots = _shot_records(
+ frame_pts,
+ time_base,
+ detection["cut_pts"],
+ detection["end_pts"],
+ detection["end_method"],
+ representative_intensity_threshold,
+ )
+
+ thumbnail_started = time.perf_counter()
+ _save_representatives(
+ source_path,
+ detection["origin_pts"],
+ time_base,
+ shots,
+ output_path,
+ max_width,
+ representative_intensity_threshold,
+ )
+ thumbnail_seconds = time.perf_counter() - thumbnail_started
+
+ avg_rate = _rate_fraction(stream_info.get("avg_frame_rate")) or _rate_fraction(
+ probe_info.get("frameRate")
+ )
+ r_rate = _rate_fraction(stream_info.get("r_frame_rate"))
+ origin_pts = detection["origin_pts"]
+
+ return {
+ "schemaVersion": SCHEMA_VERSION,
+ "source": {
+ "filename": source_path.name,
+ "sha256": digest,
+ "width": int(probe_info["width"]),
+ "height": int(probe_info["height"]),
+ "durationSeconds": _round_seconds(_pts_seconds(detection["end_pts"], time_base)),
+ "avgFrameRate": _fraction_text(avg_rate),
+ "rFrameRate": _fraction_text(r_rate),
+ "timeBase": _fraction_text(time_base),
+ "originPts": int(origin_pts),
+ "lastFramePts": int(origin_pts) + frame_pts[-1],
+ "decodedFrameCount": len(frame_pts),
+ "ptsSemantics": (
+ "Shot and representative PTS values are original stream PTS minus "
+ "originPts; seconds are PTS * timeBase."
+ ),
+ "videoStreamDurationSeconds": _round_seconds(stream_duration)
+ if stream_duration is not None
+ else None,
+ "vfr": _vfr_summary(frame_pts, time_base),
+ },
+ "detector": {
+ "name": "AdaptiveDetector",
+ "version": detection["version"],
+ "parameters": {
+ "adaptiveThreshold": adaptive_threshold,
+ "minSceneSeconds": min_scene_seconds,
+ "minContentVal": min_content_val,
+ "windowWidth": 2,
+ "maxWidth": max_width,
+ "maxDurationSeconds": max_duration_seconds,
+ "representativeIntensityThreshold": float(
+ representative_intensity_threshold
+ ),
+ },
+ },
+ "shots": shots,
+ "timings": {
+ "probeSeconds": _round_seconds(probe_seconds),
+ "hashSeconds": _round_seconds(hash_seconds),
+ "detectionSeconds": _round_seconds(detection_seconds),
+ "thumbnailSeconds": _round_seconds(thumbnail_seconds),
+ },
+ }
+
+
+def _detect_cuts(
+ path,
+ probe_info,
+ stream_info,
+ *,
+ adaptive_threshold,
+ min_scene_seconds,
+ min_content_val,
+ max_width,
+ max_duration_seconds,
+):
+ try:
+ import scenedetect
+ from scenedetect import AdaptiveDetector, FrameTimecode
+ from scenedetect.common import Timecode
+ from av.video.reformatter import VideoReformatter
+ except ImportError as exc:
+ raise RuntimeError(
+ "Shot analysis requires PySceneDetect 0.7.1 and PyAV"
+ ) from exc
+
+ rate = _detector_rate(probe_info, stream_info)
+ container, stream, time_base = _open_video(path)
+ detector = AdaptiveDetector(
+ adaptive_threshold=adaptive_threshold,
+ min_scene_len=min_scene_seconds,
+ min_content_val=min_content_val,
+ )
+ frame_pts = []
+ cuts = []
+ origin_pts = None
+ last_frame_duration = None
+ resize = VideoReformatter()
+ to_bgr = VideoReformatter()
+ try:
+ for frame in container.decode(stream):
+ if frame.pts is None:
+ raise RuntimeError("Decoded video frame has no presentation timestamp")
+ if frame.time_base != time_base:
+ raise RuntimeError("Decoded frame and stream time bases differ")
+ original_pts = int(frame.pts)
+ if origin_pts is None:
+ origin_pts = original_pts
+ normalized_pts = _normalize_pts(original_pts, origin_pts)
+ if frame_pts and normalized_pts <= frame_pts[-1]:
+ raise RuntimeError("Video frame PTS values are not strictly increasing")
+ if _pts_seconds(normalized_pts, time_base) > max_duration_seconds:
+ raise ValueError(
+ f"Video exceeds the {max_duration_seconds:.3f}s analysis limit"
+ )
+ frame_pts.append(normalized_pts)
+ frame_duration = getattr(frame, "duration", None)
+ last_frame_duration = (
+ int(frame_duration)
+ if frame_duration is not None and int(frame_duration) > 0
+ else None
+ )
+ timecode = FrameTimecode(Timecode(normalized_pts, time_base), rate)
+ picture = frame
+ if frame.width > max_width:
+ picture = resize.reformat(frame, width=max_width,
+ height=max(1, round(frame.height * max_width / frame.width)))
+ cuts.extend(
+ detector.process_frame(
+ timecode, to_bgr.reformat(picture, format="bgr24").to_ndarray()
+ )
+ )
+ finally:
+ container.close()
+
+ if origin_pts is None or not frame_pts:
+ raise ValueError("Video contains no decodable frames")
+
+ last_timecode = FrameTimecode(Timecode(frame_pts[-1], time_base), rate)
+ cuts.extend(detector.post_process(last_timecode))
+ cut_pts = sorted({int(timecode.pts) for timecode in cuts})
+
+ end_pts, end_method = _end_boundary(
+ frame_pts,
+ time_base,
+ last_frame_duration,
+ _normalized_stream_end(stream_info, origin_pts, time_base),
+ )
+ return {
+ "version": str(getattr(scenedetect, "__version__", "unknown")),
+ "time_base": time_base,
+ "origin_pts": origin_pts,
+ "frame_pts": frame_pts,
+ "cut_pts": cut_pts,
+ "end_pts": end_pts,
+ "end_method": end_method,
+ }
+
+
+def _save_representatives(
+ path,
+ origin_pts,
+ time_base,
+ shots,
+ output_path,
+ max_width,
+ representative_intensity_threshold,
+):
+ candidate_owner = {}
+ for shot_index, shot in enumerate(shots):
+ for sample in shot["representative"]["selection"]["sampledFrames"]:
+ pts = int(sample["pts"])
+ if pts in candidate_owner:
+ raise RuntimeError(
+ "Representative candidate frames are not unique across shots"
+ )
+ candidate_owner[pts] = shot_index
+
+ selected = {}
+ current_index = None
+ requested_candidates = len(candidate_owner)
+ seen_candidates = 0
+
+ def finalize(shot_index):
+ record = selected[shot_index]
+ shot = shots[shot_index]
+ target = output_path / shot["representative"]["path"]
+ 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(
+ _pts_seconds(record["pts"], time_base)
+ )
+ shot["representative"]["visibility"] = record["visibility"]
+ del selected[shot_index]
+
+ container, stream, second_time_base = _open_video(path)
+ if second_time_base != time_base:
+ container.close()
+ raise RuntimeError("Video time base changed between analysis passes")
+ try:
+ for frame in container.decode(stream):
+ if frame.pts is None:
+ raise RuntimeError("Decoded video frame has no presentation timestamp")
+ normalized_pts = _normalize_pts(int(frame.pts), origin_pts)
+ shot_index = candidate_owner.get(normalized_pts)
+ if shot_index is None:
+ continue
+ seen_candidates += 1
+ if current_index is not None and shot_index != current_index:
+ finalize(current_index)
+ current_index = None
+ shot = shots[shot_index]
+ sample = next(
+ candidate
+ for candidate in shot["representative"]["selection"]["sampledFrames"]
+ if int(candidate["pts"]) == normalized_pts
+ )
+ image = frame.to_image()
+ mean_intensity = _mean_intensity(image)
+ sample["meanIntensity"] = round(float(mean_intensity), 3)
+ candidate = {
+ "pts": normalized_pts,
+ "meanIntensity": mean_intensity,
+ "visibility": (
+ "visible"
+ if mean_intensity >= representative_intensity_threshold
+ else "low_visibility"
+ ),
+ "image": image,
+ "rotation": frame.rotation,
+ }
+ midpoint = _midpoint_pts(shot["startPts"], shot["endPts"])
+ if _prefer_candidate(
+ candidate,
+ selected.get(shot_index),
+ representative_intensity_threshold,
+ midpoint,
+ ):
+ selected[shot_index] = candidate
+ current_index = shot_index
+ if seen_candidates >= requested_candidates:
+ break
+ if current_index is not None:
+ finalize(current_index)
+ finally:
+ container.close()
+
+ missing = [
+ int(sample["pts"])
+ for shot in shots
+ for sample in shot["representative"]["selection"]["sampledFrames"]
+ if "meanIntensity" not in sample
+ ]
+ if missing:
+ raise RuntimeError(
+ "Representative frames were not found during the second decode: "
+ + ", ".join(str(value) for value in sorted(missing))
+ )
+
+
+def _mean_intensity(image, max_sample_width=_REPRESENTATIVE_SAMPLE_WIDTH):
+ try:
+ from PIL import Image
+ except ImportError as exc:
+ raise RuntimeError("Shot analysis requires Pillow") from exc
+
+ sample = image.convert("RGB")
+ if sample.width > max_sample_width:
+ height = max(1, round(sample.height * max_sample_width / sample.width))
+ sample = sample.resize(
+ (max_sample_width, height), Image.Resampling.BILINEAR
+ )
+ data = sample.tobytes()
+ if not data:
+ return 0.0
+ return sum(data) / len(data)
+
+
+def _save_thumbnail(image, target, max_width):
+ try:
+ from PIL import Image
+ except ImportError as exc:
+ raise RuntimeError("Shot analysis requires Pillow") from exc
+
+ if image.width > max_width:
+ height = max(1, round(image.height * max_width / image.width))
+ image = image.resize((max_width, height), Image.Resampling.LANCZOS)
+ image.convert("RGB").save(target, "JPEG", quality=_JPEG_QUALITY)
+
+
+def _open_video(path):
+ try:
+ import av
+ except ImportError as exc:
+ raise RuntimeError("Shot analysis requires PyAV") from exc
+ try:
+ container = av.open(str(path))
+ except Exception as exc:
+ raise RuntimeError(f"PyAV could not open video {path.name}") from exc
+ try:
+ if not container.streams.video:
+ raise RuntimeError(f"Video {path.name} has no video stream")
+ stream = container.streams.video[0]
+ time_base = _time_base(stream.time_base)
+ except BaseException:
+ container.close()
+ raise
+ return container, stream, time_base
+
+
+def _time_base(value):
+ try:
+ result = Fraction(value)
+ except (TypeError, ValueError, ZeroDivisionError) as exc:
+ raise RuntimeError("Video stream has no valid rational time base") from exc
+ if result <= 0:
+ raise RuntimeError("Video stream time base must be positive")
+ return result
+
+
+def _detector_rate(probe_info, stream_info):
+ rate = (
+ _rate_fraction(stream_info.get("avg_frame_rate"))
+ or _rate_fraction(stream_info.get("r_frame_rate"))
+ or _rate_fraction(probe_info.get("frameRate"))
+ )
+ if rate is None:
+ raise RuntimeError("Video stream has no valid frame rate")
+ return rate
+
+
+def _ffprobe_video_stream(path):
+ try:
+ require_ffprobe()
+ except Exception as exc:
+ raise RuntimeError("ffprobe is required for shot analysis") from exc
+ try:
+ process = subprocess.run(
+ [
+ "ffprobe",
+ "-v",
+ "error",
+ "-protocol_whitelist",
+ "file,pipe",
+ "-select_streams",
+ "v:0",
+ "-show_entries",
+ f"stream={_FFPROBE_STREAM_FIELDS}",
+ "-of",
+ "json",
+ str(path),
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ timeout=15,
+ check=True,
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ raise RuntimeError(f"ffprobe failed for {path.name}") from exc
+ if len(process.stdout) > 1024 * 1024:
+ raise RuntimeError("ffprobe video stream metadata is unexpectedly large")
+ try:
+ value = json.loads(process.stdout)
+ except (TypeError, ValueError) as exc:
+ raise RuntimeError(f"ffprobe returned invalid JSON for {path.name}") from exc
+ streams = value.get("streams") or []
+ if not streams:
+ raise RuntimeError(f"Video {path.name} has no video stream")
+ return streams[0]
+
+
+def _sha256(path):
+ digest = hashlib.sha256()
+ with path.open("rb") as source:
+ while True:
+ chunk = source.read(1024 * 1024)
+ if not chunk:
+ break
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _normalize_pts(original_pts, origin_pts):
+ return int(original_pts) - int(origin_pts)
+
+
+def _pts_seconds(pts, time_base):
+ return float(Fraction(pts) * time_base)
+
+
+def _vfr_summary(frame_pts, time_base):
+ intervals = [
+ float(Fraction(later - earlier) * time_base)
+ for earlier, later in zip(frame_pts, frame_pts[1:])
+ if later > earlier
+ ]
+ if not intervals:
+ return {
+ "intervalCount": 0,
+ "isVariable": False,
+ "minIntervalSeconds": None,
+ "maxIntervalSeconds": None,
+ "meanIntervalSeconds": None,
+ "distinctIntervalCount": 0,
+ "observed": [],
+ }
+
+ counts = {}
+ for value in intervals:
+ key = round(value, 6)
+ counts[key] = counts.get(key, 0) + 1
+ observed = [
+ {"seconds": seconds, "count": count}
+ for seconds, count in sorted(
+ counts.items(), key=lambda item: (-item[1], item[0])
+ )[:8]
+ ]
+ minimum = min(intervals)
+ maximum = max(intervals)
+ mean = sum(intervals) / len(intervals)
+ tolerance = max(1e-6, mean * 0.001)
+ return {
+ "intervalCount": len(intervals),
+ "isVariable": (maximum - minimum) > tolerance,
+ "minIntervalSeconds": round(minimum, 6),
+ "maxIntervalSeconds": round(maximum, 6),
+ "meanIntervalSeconds": round(mean, 6),
+ "distinctIntervalCount": len(counts),
+ "observed": observed,
+ }
+
+
+def _end_boundary(frame_pts, time_base, last_frame_duration, stream_duration):
+ last_pts = frame_pts[-1]
+ if isinstance(last_frame_duration, int) and last_frame_duration > 0:
+ return last_pts + last_frame_duration, "last-frame-duration"
+ if stream_duration is not None:
+ end_pts = round(Fraction(str(stream_duration)) / time_base)
+ if end_pts > last_pts:
+ return int(end_pts), "video-stream-duration"
+ if len(frame_pts) > 1:
+ interval = frame_pts[-1] - frame_pts[-2]
+ if interval > 0:
+ return last_pts + interval, "estimated-last-interval"
+ return last_pts + 1, "estimated-timebase-tick"
+
+
+def _normalized_stream_end(stream_info, origin_pts, time_base):
+ """Locate the stream end relative to the first frame, never the audio end."""
+ try:
+ stream_base = _time_base(stream_info["time_base"])
+ end = (int(stream_info["start_pts"]) + int(stream_info["duration_ts"])) * stream_base
+ except (KeyError, TypeError, ValueError, RuntimeError):
+ duration = _positive_float(stream_info.get("duration"))
+ if duration is None:
+ return None
+ try:
+ start = Fraction(str(stream_info["start_time"]))
+ except (KeyError, TypeError, ValueError, ZeroDivisionError):
+ return None
+ end = start + Fraction(str(duration))
+ relative_end = end - origin_pts * time_base
+ return float(relative_end) if relative_end > 0 else None
+
+
+def _midpoint_pts(start_pts, end_pts):
+ return Fraction(int(start_pts) + int(end_pts), 2)
+
+
+def _nearest_frame_pts(frame_pts, target_pts, start_pts, end_pts):
+ """Return the frame nearest ``target_pts`` within ``[start_pts, end_pts)``.
+
+ ``frame_pts`` is the strictly increasing decoded PTS sequence produced by
+ ``_detect_cuts``. Binary search avoids rescanning every frame for each
+ representative candidate.
+ """
+ if not frame_pts or end_pts <= start_pts:
+ return None
+ first = bisect_left(frame_pts, start_pts)
+ stop = bisect_left(frame_pts, end_pts)
+ if first >= stop:
+ return None
+ insertion = bisect_left(frame_pts, target_pts, first, stop)
+ best_key = None
+ best_pts = None
+ if insertion > first:
+ pts = int(frame_pts[insertion - 1])
+ best_key = (abs(Fraction(pts) - target_pts), pts)
+ best_pts = pts
+ if insertion < stop:
+ pts = int(frame_pts[insertion])
+ key = (abs(Fraction(pts) - target_pts), pts)
+ if best_key is None or key < best_key:
+ best_key = key
+ best_pts = pts
+ return best_pts
+
+
+def _representative_pts(frame_pts, start_pts, end_pts):
+ return _nearest_frame_pts(
+ frame_pts, _midpoint_pts(start_pts, end_pts), start_pts, end_pts
+ )
+
+
+def _representative_candidates(
+ frame_pts,
+ start_pts,
+ end_pts,
+ limit=_REPRESENTATIVE_CANDIDATE_LIMIT,
+):
+ start = int(start_pts)
+ end = int(end_pts)
+ if end <= start:
+ return []
+ span = end - start
+ candidates = []
+ seen = set()
+ for numerator in (1, 2, 3):
+ target = Fraction(start, 1) + Fraction(span * numerator, 4)
+ pts = _nearest_frame_pts(frame_pts, target, start, end)
+ if pts is None or pts in seen:
+ continue
+ seen.add(pts)
+ candidates.append(pts)
+ if len(candidates) >= limit:
+ break
+ return candidates
+
+
+def _representative_sort_key(pts, midpoint):
+ return (abs(Fraction(int(pts)) - midpoint), int(pts))
+
+
+def _prefer_candidate(candidate, current, threshold, midpoint):
+ if current is None:
+ return True
+ candidate_visible = candidate["meanIntensity"] >= threshold
+ current_visible = current["meanIntensity"] >= threshold
+ if candidate_visible != current_visible:
+ return candidate_visible
+ return _representative_sort_key(
+ candidate["pts"], midpoint
+ ) < _representative_sort_key(current["pts"], midpoint)
+
+
+def _select_representative(samples, start_pts, end_pts, threshold):
+ if not samples:
+ raise ValueError("Cannot select a representative without sampled frames")
+ midpoint = _midpoint_pts(start_pts, end_pts)
+ chosen = None
+ for sample in samples:
+ candidate = {
+ "pts": int(sample["pts"]),
+ "meanIntensity": float(sample["meanIntensity"]),
+ }
+ if _prefer_candidate(candidate, chosen, threshold, midpoint):
+ chosen = candidate
+ return {
+ "pts": chosen["pts"],
+ "visibility": (
+ "visible"
+ if chosen["meanIntensity"] >= threshold
+ else "low_visibility"
+ ),
+ }
+
+
+def _shot_records(
+ frame_pts,
+ time_base,
+ cut_pts,
+ end_pts,
+ end_method,
+ representative_intensity_threshold=DEFAULT_REPRESENTATIVE_INTENSITY_THRESHOLD,
+):
+ if not frame_pts:
+ raise ValueError("Cannot build shots without decoded frames")
+ if end_pts <= frame_pts[-1]:
+ raise ValueError("Shot end must be after the last decoded frame")
+
+ frame_set = set(frame_pts)
+ starts = [frame_pts[0]]
+ for pts in sorted({int(value) for value in cut_pts}):
+ if pts in frame_set and pts > starts[-1]:
+ starts.append(pts)
+ bounds = starts + [int(end_pts)]
+ time_base_text = _fraction_text(time_base)
+
+ shots = []
+ for index, (start_pts, stop_pts) in enumerate(zip(bounds, bounds[1:]), 1):
+ if stop_pts <= start_pts:
+ continue
+ candidates = _representative_candidates(frame_pts, start_pts, stop_pts)
+ if not candidates:
+ raise RuntimeError(f"Shot {index} contains no decoded frame")
+ midpoint = _midpoint_pts(start_pts, stop_pts)
+ representative_pts = _representative_pts(frame_pts, start_pts, stop_pts)
+ if representative_pts not in candidates:
+ representative_pts = min(
+ candidates,
+ key=lambda pts: _representative_sort_key(pts, midpoint),
+ )
+ is_last = index == len(bounds) - 1
+ shots.append(
+ {
+ "id": f"shot-{index:04d}",
+ "startSeconds": _round_seconds(_pts_seconds(start_pts, time_base)),
+ "endSeconds": _round_seconds(_pts_seconds(stop_pts, time_base)),
+ "startPts": int(start_pts),
+ "endPts": int(stop_pts),
+ "timeBase": time_base_text,
+ "representative": {
+ "path": f"frames/shot-{index:04d}.jpg",
+ "pts": int(representative_pts),
+ "timeBase": time_base_text,
+ "seconds": _round_seconds(
+ _pts_seconds(representative_pts, time_base)
+ ),
+ "selection": {
+ "method": "visible-near-midpoint",
+ "scope": "sampled_frames",
+ "intensityThreshold": float(
+ representative_intensity_threshold
+ ),
+ "sampledFrames": [
+ {
+ "pts": int(pts),
+ "seconds": _round_seconds(
+ _pts_seconds(pts, time_base)
+ ),
+ }
+ for pts in candidates
+ ],
+ },
+ },
+ "endMethod": end_method if is_last else "next-cut",
+ "description": None,
+ }
+ )
+ return shots
+
+
+def _rate_fraction(value):
+ if value is None:
+ return None
+ if isinstance(value, Fraction):
+ return value if value > 0 else None
+ if isinstance(value, (int, float)):
+ if not math.isfinite(value) or value <= 0:
+ return None
+ return Fraction(value).limit_denominator(1001)
+ text = str(value).strip()
+ if not text or text.lower() in {"n/a", "unknown", "0/0"}:
+ return None
+ try:
+ if "/" in text:
+ numerator, denominator = text.split("/", 1)
+ result = Fraction(int(numerator), int(denominator))
+ else:
+ number = float(text)
+ if not math.isfinite(number) or number <= 0:
+ return None
+ result = Fraction(number).limit_denominator(1001)
+ except (ValueError, ZeroDivisionError, OverflowError):
+ return None
+ return result if result > 0 else None
+
+
+def _fraction_text(value):
+ if value is None:
+ return None
+ return f"{value.numerator}/{value.denominator}"
+
+
+def _positive_float(value):
+ try:
+ number = float(value)
+ except (TypeError, ValueError):
+ return None
+ if not math.isfinite(number) or number <= 0:
+ return None
+ return number
+
+
+def _round_seconds(value):
+ if value is None:
+ return None
+ return round(float(value), 6)
diff --git a/pyproject.toml b/pyproject.toml
index 5e0b2507c..e236492b9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -19,6 +19,7 @@ dependencies = [
[project.optional-dependencies]
test = ["pytest>=8,<10", "distlib>=0.4,<1", "import-linter>=2.1,<3"]
+shot-analysis = ["av>=16,<17", "scenedetect-headless==0.7.1"]
[project.scripts]
opendirector = "opendirector.cli:main"
diff --git a/scripts/analyze_reference_shots.py b/scripts/analyze_reference_shots.py
new file mode 100644
index 000000000..d648991c2
--- /dev/null
+++ b/scripts/analyze_reference_shots.py
@@ -0,0 +1,72 @@
+"""Analyze a reference video into shots and representative JPEGs.
+
+Example:
+ python scripts/analyze_reference_shots.py input.mp4 --output /tmp/shots
+"""
+
+import argparse
+import json
+from pathlib import Path
+import sys
+
+root = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(root / "packages/core/src"))
+
+from opendirector.media.shot_detection import ( # noqa: E402
+ DEFAULT_MAX_DURATION_SECONDS,
+ DEFAULT_REPRESENTATIVE_INTENSITY_THRESHOLD,
+ inspect_video_shots,
+)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("input", type=Path, help="Reference video to analyze")
+ parser.add_argument(
+ "--output", type=Path, required=True, help="Directory for analysis.json and frames/"
+ )
+ parser.add_argument("--adaptive-threshold", type=float, default=3.0)
+ parser.add_argument("--min-scene-seconds", type=float, default=0.1)
+ parser.add_argument("--min-content-val", type=float, default=15.0)
+ parser.add_argument("--max-width", type=int, default=640)
+ parser.add_argument(
+ "--representative-intensity-threshold",
+ type=float,
+ default=DEFAULT_REPRESENTATIVE_INTENSITY_THRESHOLD,
+ help="Heuristic mean RGB threshold (0-255) for sampled-frame visibility",
+ )
+ parser.add_argument(
+ "--max-duration-seconds",
+ type=float,
+ default=DEFAULT_MAX_DURATION_SECONDS,
+ )
+ arguments = parser.parse_args()
+
+ result = inspect_video_shots(
+ arguments.input,
+ arguments.output,
+ adaptive_threshold=arguments.adaptive_threshold,
+ min_scene_seconds=arguments.min_scene_seconds,
+ min_content_val=arguments.min_content_val,
+ max_width=arguments.max_width,
+ representative_intensity_threshold=(
+ arguments.representative_intensity_threshold
+ ),
+ max_duration_seconds=arguments.max_duration_seconds,
+ )
+
+ analysis_path = arguments.output / "analysis.json"
+ analysis_path.write_text(
+ json.dumps(result, ensure_ascii=False, indent=2) + "\n",
+ encoding="utf-8",
+ )
+ print(
+ f"{result['source']['filename']}: {len(result['shots'])} shot(s), "
+ f"{result['source']['decodedFrameCount']} frames, "
+ f"{result['timings']['detectionSeconds']:.3f}s detection"
+ )
+ print(f"analysis: {analysis_path}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/describe_reference_shots.py b/scripts/describe_reference_shots.py
new file mode 100644
index 000000000..0acdccd08
--- /dev/null
+++ b/scripts/describe_reference_shots.py
@@ -0,0 +1,180 @@
+"""Describe explicitly selected reference shots from an analysis.json sidecar.
+
+Example:
+ python scripts/describe_reference_shots.py \
+ --analysis /tmp/shots/analysis.json \
+ --repository /path/to/repository \
+ --model-config-id 00000000-0000-0000-0000-000000000000 \
+ --shot-id shot-0001 --shot-id shot-0002 \
+ --output /tmp/shots/descriptions.json
+"""
+
+import argparse
+import asyncio
+import json
+from pathlib import Path
+import sys
+from uuid import UUID
+
+root = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(root / "packages/core/src"))
+
+from opendirector.application.shot_descriptions import ( # noqa: E402
+ DEFAULT_MAX_TOKENS,
+ LANGUAGES,
+ SCHEMA_VERSION,
+ describe_shot_frame,
+ frame_reference,
+ validate_frame_description_config,
+)
+from opendirector.infrastructure.model_configs import ModelConfigs # noqa: E402
+from opendirector.integrations.reference_inputs import image_type # noqa: E402
+
+
+def _resolve_frame_path(base, relative):
+ base = Path(base).resolve()
+ candidate = Path(relative)
+ if candidate.is_absolute():
+ raise ValueError("代表帧路径必须是 analysis 目录内的相对路径。")
+ try:
+ resolved = (base / candidate).resolve(strict=True)
+ except OSError:
+ raise ValueError(f"代表帧不存在:{relative}") from None
+ if resolved != base and base not in resolved.parents:
+ raise ValueError(f"代表帧路径越出 analysis 目录:{relative}")
+ if not resolved.is_file():
+ raise ValueError(f"代表帧不是普通文件:{relative}")
+ return resolved
+
+
+def _validate_output(analysis_path, output_path):
+ if analysis_path.resolve() == output_path.resolve():
+ raise ValueError("输出文件不能与 analysis 文件相同。")
+ if output_path.exists() or output_path.is_symlink():
+ raise ValueError(f"输出文件已存在,请显式选择新路径:{output_path}")
+
+
+def _load_analysis(path):
+ try:
+ value = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ raise ValueError(f"无法读取 analysis 文件:{path}") from None
+ source = value.get("source") if isinstance(value, dict) else None
+ source_sha = source.get("sha256") if isinstance(source, dict) else None
+ if not isinstance(source_sha, str) or not source_sha:
+ raise ValueError("analysis 文件缺少 source.sha256。")
+ if not isinstance(value.get("shots"), list):
+ raise ValueError("analysis 文件缺少 shots 列表。")
+ return value, source_sha
+
+
+def _selected_ids(shot_ids):
+ ids = list(shot_ids)
+ if not ids:
+ raise ValueError("请明确选择至少一个镜头。")
+ if len(set(ids)) != len(ids):
+ raise ValueError("所选镜头 id 不能重复。")
+ return ids
+
+
+def _selected_shots(analysis, shot_ids):
+ by_id = {
+ shot.get("id"): shot
+ for shot in analysis["shots"]
+ if isinstance(shot, dict)
+ }
+ shots = []
+ for shot_id in _selected_ids(shot_ids):
+ shot = by_id.get(shot_id)
+ if shot is None:
+ raise ValueError(f"analysis 中不存在镜头:{shot_id}")
+ shots.append(shot)
+ return shots
+
+
+def _write_output(output_path, source_sha, rows):
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ output_path.write_text(
+ json.dumps(
+ {
+ "schemaVersion": SCHEMA_VERSION,
+ "sourceSha256": source_sha,
+ "descriptions": rows,
+ },
+ ensure_ascii=False,
+ indent=2,
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+
+
+async def _describe_all(config, entries, output_path, source_sha, max_tokens, language):
+ rows = []
+ for shot, data in entries:
+ row = await describe_shot_frame(
+ config, shot, data, max_tokens=max_tokens, language=language
+ )
+ rows.append(row)
+ _write_output(output_path, source_sha, rows)
+ print(f"{row['shotId']}: described in {row['requestSeconds']:.3f}s")
+ return rows
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--analysis", type=Path, required=True)
+ parser.add_argument("--repository", type=Path, required=True)
+ parser.add_argument("--model-config-id", required=True)
+ parser.add_argument("--shot-id", action="append", required=True)
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--max-tokens", type=int, default=DEFAULT_MAX_TOKENS)
+ parser.add_argument("--language", choices=tuple(LANGUAGES), default="en-US")
+ arguments = parser.parse_args()
+
+ if arguments.max_tokens < 1:
+ parser.error("--max-tokens 必须是正整数")
+ try:
+ config_id = str(UUID(arguments.model_config_id))
+ except (AttributeError, TypeError, ValueError):
+ parser.error("--model-config-id 必须是 UUID")
+
+ analysis_path = arguments.analysis.resolve()
+ output_path = arguments.output
+ _validate_output(analysis_path, output_path)
+ analysis, source_sha = _load_analysis(analysis_path)
+ shots = _selected_shots(analysis, arguments.shot_id)
+
+ models_path = arguments.repository.resolve() / ".opendirector" / "models.json"
+ if not models_path.is_file():
+ raise ValueError(
+ f"未找到已有模型配置:{models_path};请先在现有设置中配置对话模型。"
+ )
+ config = ModelConfigs(arguments.repository).resolve(config_id, "agent")
+ validate_frame_description_config(config)
+
+ analysis_dir = analysis_path.parent
+ entries = []
+ for shot in shots:
+ frame = frame_reference(shot)
+ frame_path = _resolve_frame_path(analysis_dir, frame["path"])
+ data = frame_path.read_bytes()
+ if image_type(data) != "image/jpeg":
+ raise ValueError(f"代表帧不是 JPEG:{frame['path']}")
+ entries.append((shot, data))
+
+ asyncio.run(
+ _describe_all(
+ config,
+ entries,
+ output_path,
+ source_sha,
+ arguments.max_tokens,
+ arguments.language,
+ )
+ )
+ print(f"descriptions: {output_path}")
+
+
+if __name__ == "__main__":
+ main()
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/backend/creationProjection.ts b/src/backend/creationProjection.ts
index 8a63d3552..d515ffdfa 100644
--- a/src/backend/creationProjection.ts
+++ b/src/backend/creationProjection.ts
@@ -9,6 +9,7 @@ import type {
EditorDocumentInput,
EditorInputConnection,
EditorInputConnectionInput,
+ EditorRef,
GenerationSpec,
GenerationSpecInput,
ObjectVersion,
@@ -506,6 +507,8 @@ export class CreationProjection {
height: doc.data.height,
},
};
+ case "shot_breakdown":
+ return {};
case "media_edit": {
// A changed source starts a fresh edit; keep the old document in history
// rather than applying its mask to unrelated pixels of the same size.
@@ -1186,12 +1189,12 @@ export class CreationProjection {
private async editorInput(
node: CanvasNode,
- kind: EditorDocument["kind"],
+ kind: EditorRef["kind"],
current?: EditorDocument,
edges: CanvasDocument["edges"] = [],
nodes: readonly CanvasNode[] = [],
materializedAssets?: ReadonlyMap,
- ): Promise {
+ ): Promise> {
// A link the domain already recorded is retained: the source may have moved
// on since, and the snapshot deliberately keeps the original relation.
const retained = new Map(
@@ -1753,7 +1756,7 @@ export class CreationProjection {
: undefined;
const doc = await this.editorInput(
node,
- kind as EditorDocument["kind"],
+ kind as EditorRef["kind"],
current,
document.edges,
[...document.nodes, ...(document.hiddenNodes ?? [])],
@@ -1767,7 +1770,7 @@ export class CreationProjection {
else {
const previous = await this.editorInput(
old ?? node,
- kind as EditorDocument["kind"],
+ kind as EditorRef["kind"],
current,
this.baseline.edges,
[...this.baseline.nodes, ...(this.baseline.hiddenNodes ?? [])],
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({