Skip to content
Draft
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
166 changes: 122 additions & 44 deletions apps/api/src/opendirector_api/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
from opendirector.application.creation_canvas import CreationCanvas
from opendirector.application.creation_history import CreationHistory
from opendirector.application.creation_timeline_packages import CreationTimelinePackages
from opendirector.application.linked_draft import LinkedVideoDrafts
from opendirector.domain.creation.linked_draft import LinkedClipSaveInput, LinkedDraftView
from opendirector.domain.creation.timeline_packages import TimelinePackageImportRequest, TimelinePackageImportReceipt
from opendirector.domain.creation.assets import Asset, UploadInfo
from opendirector.domain.creation.base import MediaKind
Expand All @@ -31,7 +33,7 @@
from opendirector.infrastructure.creation_projects import CreationProjects
from opendirector.media.fonts import MAX_FONT_BYTES, inspect_font
from opendirector_api.models import AssetSource, Session
from opendirector_api.localization import localized_receipt
from opendirector_api.localization import localized_error, localized_receipt

from opendirector_api.localization import localized_error_for_language

Expand Down Expand Up @@ -79,12 +81,79 @@ async def disconnected():
await asyncio.gather(work, disconnect, return_exceptions=True)


def _stream_byte_range(
stream,
*,
size: int,
etag: str,
mime_type: str,
filename: str,
attachment: bool,
range_header: str | None,
if_none_match: str | None,
):
headers = {
'Accept-Ranges': 'bytes',
'ETag': etag,
'Cache-Control': 'private, no-cache',
'X-Content-Type-Options': 'nosniff',
'Content-Disposition': ('attachment' if attachment else 'inline')
+ "; filename*=utf-8''" + quote(filename, safe=''),
}
if range_header is None and if_none_match == etag:
stream.close()
return Response(status_code=304, headers=headers)
start, end = 0, size - 1
if range_header is not None:
try:
match = re.fullmatch(r'bytes=(\d*)-(\d*)', range_header) if len(range_header) <= 128 else None
if match is None or not any(match.groups()) or not size:
raise ValueError()
first, last = match.groups()
if first:
start, end = int(first), min(int(last), size - 1) if last else size - 1
else:
suffix = int(last)
if suffix <= 0:
raise ValueError()
start = max(0, size - suffix)
if start > end or start >= size:
raise ValueError()
except ValueError:
stream.close()
return Response(status_code=416, headers={**headers, 'Content-Range': f'bytes */{size}'})
headers['Content-Range'] = f'bytes {start}-{end}/{size}'
headers['Content-Length'] = str(end - start + 1)

async def chunks():
try:
await run_in_threadpool(stream.seek, start)
remaining = end - start + 1
while remaining > 0:
data = await run_in_threadpool(stream.read, min(1024 * 1024, remaining))
if not data:
break
remaining -= len(data)
yield data
finally:
stream.close()

return StreamingResponse(
chunks(),
status_code=206 if range_header else 200,
media_type=mime_type,
headers=headers,
background=BackgroundTask(stream.close),
)


def creation_routes(projects: CreationProjects, generation=None, prompt_optimization=None):
router = APIRouter(prefix='/api/creation', tags=['Unified creation projects'])
assets = CreationAssets(projects)
canvas = CreationCanvas(projects)
history = CreationHistory(projects, assets=assets)
timeline_packages = CreationTimelinePackages(projects)
linked_drafts = LinkedVideoDrafts(projects)

@router.post('/fonts/inspect', response_model=FontCoverageResponse)
async def inspect_preview_font(request: Request, response: Response,
Expand Down Expand Up @@ -375,48 +444,57 @@ def browser_image(project_id: UUID, asset_id: UUID,
def content(project_id: UUID, asset_id: UUID, range_header: str | None = Header(default=None, alias='Range'),
if_none_match: str | None = Header(default=None, alias='If-None-Match')):
stream, asset = assets.open_media(project_id, asset_id)
size, etag = asset.metadata.size, '"' + asset.fingerprint + '"'
headers = {'Accept-Ranges': 'bytes', 'ETag': etag, 'Cache-Control': 'private, no-cache',
'X-Content-Type-Options': 'nosniff',
'Content-Disposition': ('attachment' if asset.kind == 'file' else 'inline')
+ "; filename*=utf-8''" + quote(asset.name, safe='')}
if range_header is None and if_none_match == etag:
stream.close()
return Response(status_code=304, headers=headers)
start, end = 0, size - 1
if range_header is not None:
try:
match = re.fullmatch(r'bytes=(\d*)-(\d*)', range_header) if len(range_header) <= 128 else None
if match is None or not any(match.groups()) or not size:
raise ValueError()
first, last = match.groups()
if first:
start, end = int(first), min(int(last), size - 1) if last else size - 1
else:
suffix = int(last)
if suffix <= 0:
raise ValueError()
start = max(0, size - suffix)
if start > end or start >= size:
raise ValueError()
except ValueError:
stream.close()
return Response(status_code=416, headers={**headers, 'Content-Range': f'bytes */{size}'})
headers['Content-Range'] = f'bytes {start}-{end}/{size}'
headers['Content-Length'] = str(end - start + 1)
async def chunks():
try:
stream.seek(start)
remaining = end - start + 1
while remaining > 0:
data = await run_in_threadpool(stream.read, min(1024 * 1024, remaining))
if not data:
break
remaining -= len(data)
yield data
finally:
stream.close()
return StreamingResponse(chunks(), status_code=206 if range_header else 200,
media_type=asset.metadata.mimeType, headers=headers, background=BackgroundTask(stream.close))
return _stream_byte_range(
stream,
size=asset.metadata.size,
etag='"' + asset.fingerprint + '"',
mime_type=asset.metadata.mimeType,
filename=asset.name,
attachment=asset.kind == 'file',
range_header=range_header,
if_none_match=if_none_match,
)

@router.get('/projects/{project_id}/linked-draft', response_model=LinkedDraftView)
def get_linked_draft(
project_id: UUID,
request: Request,
source_id: UUID | None = Query(default=None, alias='sourceId'),
):
view = linked_drafts.get_draft(project_id, source_id=source_id)
if view.reason and view.reasonCode:
view = view.model_copy(update={
'reason': localized_error(request, chinese=view.reason, status=409, code=view.reasonCode),
})
return view

@router.put('/projects/{project_id}/linked-draft', response_model=LinkedDraftView)
def put_linked_draft(
project_id: UUID,
value: LinkedClipSaveInput,
x_opendirector_session: UUID | None = Header(default=None),
):
session = str(x_opendirector_session) if x_opendirector_session else None
return linked_drafts.save_clip(project_id, value, session=session)

@router.get('/projects/{project_id}/linked-sources/{source_id}/content')
def linked_source_content(
project_id: UUID,
source_id: UUID,
range_header: str | None = Header(default=None, alias='Range'),
if_none_match: str | None = Header(default=None, alias='If-None-Match'),
):
stream, info = linked_drafts.open_media(project_id, source_id)
etag = f'"linked-{info.sourceId}-{info.size}-{info.modifiedAt}"'
return _stream_byte_range(
stream,
size=info.size,
etag=etag,
mime_type=info.mimeType,
filename=info.title,
attachment=False,
range_header=range_header,
if_none_match=if_none_match,
)

return router
68 changes: 59 additions & 9 deletions apps/api/src/opendirector_api/desktop.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@
from starlette.types import ASGIApp, Scope, Receive, Send
from starlette.requests import Request

from opendirector_api.localization import localized_error
from opendirector_api.localization import localized_error, localized_error_for_language

from opendirector.domain.projects import ProjectError
from opendirector.infrastructure.local_projects import LocalProjects
from opendirector.installation import data_root
from opendirector_api.main import create_app
Expand Down Expand Up @@ -67,7 +68,16 @@ class SessionRegistration(BaseModel):
sessionId: UUID


CONTROL = TypeAdapter(Annotated[Control | SessionRegistration, Field(discriminator='type')])
class BindLinkedVideo(BaseModel):
model_config = ConfigDict(extra='forbid')
type: Literal['bind-linked-video']
requestId: int = Field(ge=1)
projectId: UUID
filePath: str = Field(min_length=1, max_length=4096)
locale: str = Field(default='zh-CN', max_length=32)


CONTROL = TypeAdapter(Annotated[Control | SessionRegistration | BindLinkedVideo, Field(discriminator='type')])


def runtime_check() -> dict[str, str]:
Expand All @@ -87,6 +97,10 @@ def runtime_check() -> dict[str, str]:


async def serve(token: str) -> None:
if hasattr(sys.stdout, 'reconfigure'):
sys.stdout.reconfigure(encoding='utf-8')
if hasattr(sys.stderr, 'reconfigure'):
sys.stderr.reconfigure(encoding='utf-8')
output = sys.stdout

def emit(event: dict[str, object]) -> None:
Expand All @@ -105,16 +119,16 @@ def emit(event: dict[str, object]) -> None:
port = listener.getsockname()[1]
os.environ['OPENDIRECTOR_API_URL'] = f'http://127.0.0.1:{port}'
sessions: set[str] = set()
commands: asyncio.Queue[str] = asyncio.Queue()
commands: asyncio.Queue[bytes] = asyncio.Queue()
loop = asyncio.get_running_loop()

def read_controls() -> None:
while line := sys.stdin.readline(65537):
if len(line) > 65536:
loop.call_soon_threadsafe(commands.put_nowait, 'invalid\n')
while raw := sys.stdin.buffer.readline(65537):
if len(raw) > 65536:
loop.call_soon_threadsafe(commands.put_nowait, b'invalid\n')
return
loop.call_soon_threadsafe(commands.put_nowait, line)
loop.call_soon_threadsafe(commands.put_nowait, '')
loop.call_soon_threadsafe(commands.put_nowait, raw)
loop.call_soon_threadsafe(commands.put_nowait, b'')

class DesktopServer(uvicorn.Server):
async def startup(self, sockets: list[socket.socket] | None = None) -> None:
Expand All @@ -138,6 +152,42 @@ async def control() -> None:
if message.type == 'shutdown':
server.should_exit = True
return
if message.type == 'bind-linked-video':
try:
info = await asyncio.to_thread(
app.state.bind_linked_video, message.projectId, message.filePath,
)
emit({
'type': 'linked-video-bound',
'requestId': message.requestId,
'ok': True,
'source': info.model_dump(mode='json'),
})
except ProjectError as error:
emit({
'type': 'linked-video-bound',
'requestId': message.requestId,
'ok': False,
'code': error.code,
'message': localized_error_for_language(
message.locale, chinese=str(error), status=error.status, code=error.code,
),
})
except Exception:
logging.getLogger(__name__).exception('Unexpected error binding linked video')
emit({
'type': 'linked-video-bound',
'requestId': message.requestId,
'ok': False,
'code': 'linked_source_offline',
'message': localized_error_for_language(
message.locale,
chinese='无法读取所选视频文件,请检查文件格式与挂载盘状态。',
status=409,
code='linked_source_offline',
),
})
continue
emit({'type': 'inspection', 'requestId': message.requestId, **app.state.desktop_activity()})

threading.Thread(target=read_controls, name='desktop-parent', daemon=True).start()
Expand All @@ -161,7 +211,7 @@ async def control() -> None:

def main() -> None:
try:
message = Initialize.model_validate_json(sys.stdin.readline(65537))
message = Initialize.model_validate_json(sys.stdin.buffer.readline(65537))
asyncio.run(serve(message.token))
except ValueError:
print(json.dumps({'type': 'fatal', 'version': 1, 'message': 'Invalid desktop control message.'}), flush=True)
Expand Down
3 changes: 3 additions & 0 deletions apps/api/src/opendirector_api/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@
"canvas_run_layout_conflict": "Locked Run areas overlap. Unlock one of the groups and try again.",
"canvas_run_layout_shared_object": "Two Runs use the same editable object. Copy the configuration or editor document and try again.",
"storage_unavailable": "A stored file is missing or has changed. Restore the file and try again.",
"linked_source_offline": "The linked source video is currently unavailable (drive disconnected, file moved, or access denied). Your clip and trim points were kept.",
"linked_source_modified": "The linked source video size or modification time changed. Playback is paused while keeping your saved trim points.",
"linked_source_unbound": "This computer does not have a local binding for the linked video source. Your clip and trim points were kept.",
"capability_unsupported": "This capability is not supported yet.",
"model_list_http_error": "Could not load the model list from the service.",
"operation_rejected": "The operation was rejected. Reload the item and try again.",
Expand Down
2 changes: 2 additions & 0 deletions apps/api/src/opendirector_api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from opendirector.application.prompt_optimization import PromptOptimization
from opendirector.application.tool_tasks import ToolTasks
from opendirector.application.creation_tool_assets import CreationToolAssets
from opendirector.application.linked_draft import LinkedVideoDrafts
from opendirector.infrastructure.local_projects import LocalProjects
from opendirector.infrastructure.creation_projects import CreationProjects
from opendirector.infrastructure.model_configs import ModelConfigs
Expand Down Expand Up @@ -94,6 +95,7 @@ async def lifespan(app):
app.state.desktop_activity = lambda: dict(
agents=len(active_agents), generations=sum(not job.future.done() for job in creation_generation.jobs.values()),
tools=sum(not job.done() for job in creation_tools.jobs.values()))
app.state.bind_linked_video = LinkedVideoDrafts(creation_projects).bind_video


@app.exception_handler(RequestValidationError)
Expand Down
Loading
Loading