Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 3 additions & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ OpenDirector 是一个在本地运行、通过浏览器使用的 AI 视频创作
<a href="https://space.bilibili.com/3747582748658251">
<img src="https://img.shields.io/badge/Bilibili-OpenDirector-00A1D6?logo=bilibili&amp;logoColor=white" alt="OpenDirector 官方 B 站账号" />
</a>
</p>
</p>

## 最新动态

Expand Down Expand Up @@ -98,6 +98,8 @@ opendirector serve

导出 MP4 推荐使用 Chrome 或 Edge,合成期间需保持页面和编辑器打开。

有参考视频时,可以[编辑分镜](docs/guides/user-guide.zh-CN.md#编辑参考视频的分镜),复核检测切点、调整镜头区间,并将描述保存在项目中。

## 文档

- [安装与更新](docs/guides/installation.zh-CN.md):环境准备、各平台安装、启动与更新。
Expand Down
48 changes: 42 additions & 6 deletions apps/api/src/opendirector_api/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
10 changes: 10 additions & 0 deletions apps/api/src/opendirector_api/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/opendirector_api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
12 changes: 12 additions & 0 deletions docs/guides/user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 12 additions & 0 deletions docs/guides/user-guide.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 创建时间线节点并打开编辑器。
Expand Down
15 changes: 12 additions & 3 deletions packages/core/src/opendirector/application/creation_canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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')
Expand Down
Loading
Loading