diff --git a/backend/open_webui/routers/videos.py b/backend/open_webui/routers/videos.py index 1a6d74b5db..3d9089b52b 100644 --- a/backend/open_webui/routers/videos.py +++ b/backend/open_webui/routers/videos.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio import logging import time +import uuid import aiohttp from fastapi import APIRouter, Depends, HTTPException, Request @@ -20,6 +21,13 @@ from open_webui.routers.images import ( from open_webui.utils.access_control import has_permission from open_webui.utils.auth import get_admin_user, get_verified_user from open_webui.utils.headers import get_headers_and_cookies +from open_webui.utils.images.comfyui import ( + ComfyUICreateVideoForm, + ComfyUIWorkflow, + comfyui_create_video, + comfyui_upload_image, +) +from open_webui.utils.json_codec import JSONCodec from open_webui.utils.session_pool import get_session from open_webui.utils.videos.connections import ( VIDEO_CONNECTIONS_CONFIG_KEY, @@ -214,6 +222,7 @@ async def video_generations( Video models take minutes, so the provider runs each request as a job: create it with ``POST /videos``, check ``GET /videos/{id}`` until it is done, then download ``/videos/{id}/content``. OpenAI's API (which LiteLLM follows) takes a multipart form; OpenRouter's takes JSON. + ComfyUI connections run the admin's workflow instead (see ``comfyui_video_generations``). """ connection, model = await resolve_video_model(request, user, form_data.model, strict=strict) connection_config = connection.get('config') or {} @@ -221,6 +230,9 @@ async def video_generations( size = form_data.size or connection_config.get('size') metadata = metadata or {} + if connection['type'] == 'comfyui': + return await comfyui_video_generations(request, connection, model, form_data, seconds, size, metadata, user) + try: headers, cookies = await get_headers_and_cookies( request, connection['url'], connection['key'], connection_config, metadata, user=user @@ -321,3 +333,104 @@ async def video_generations( log.exception(f'Video generation failed: {e}') error = e.message if isinstance(e, aiohttp.ClientResponseError) else e raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(error)) + + +COMFYUI_DEFAULT_FPS = 24 + + +def get_comfyui_video_length(seconds: int, fps: float) -> int: + """Frames for a video of *seconds* at *fps*. Video models want 8n+1 frames (Wan 4n+1, LTX-Video 8n+1), + so the count is rounded to the nearest such length.""" + return max(round(seconds * fps / 8), 1) * 8 + 1 + + +def get_comfyui_workflow_fps(connection_config: dict) -> float | None: + """The frame rate the workflow's mapped fps node already has, if any.""" + workflow = JSONCodec.loads(connection_config['workflow']) + for node in connection_config.get('nodes') or []: + if node.get('type') != 'fps': + continue + for node_id in node.get('node_ids') or []: + value = ((workflow.get(node_id) or {}).get('inputs') or {}).get(node.get('key') or 'fps') + if isinstance(value, (int, float)) and value > 0: + return value + return None + + +async def comfyui_video_generations( + request: Request, + connection: dict, + model: str, + form_data: CreateVideoForm, + seconds: int | None, + size: str | None, + metadata: dict, + user, +): + """Run the connection's ComfyUI video workflow and save each video it makes as a file. + + The request's prompt, size, length, frame rate and starting frame go into the workflow nodes the admin + mapped; anything left out keeps the workflow's own value. + """ + connection_config = connection.get('config') or {} + if not connection_config.get('workflow'): + raise HTTPException( + status_code=400, detail=ERROR_MESSAGES.DEFAULT('This ComfyUI connection has no video workflow') + ) + + try: + width, height = (int(value) for value in size.split('x')) if size and size != 'auto' else (None, None) + except ValueError: + raise HTTPException( + status_code=400, detail=ERROR_MESSAGES.DEFAULT(f'Invalid video size: {size} (e.g. 1280x720)') + ) + + # Frames are counted at the admin's frame rate, else the one the workflow saves at. + fps = connection_config.get('fps') or get_comfyui_workflow_fps(connection_config) or COMFYUI_DEFAULT_FPS + + try: + image = None + if form_data.image: + image_file_item = get_image_file_item(await load_url_image(form_data.image, user)) + res = await comfyui_upload_image(image_file_item, connection['url'], connection['key']) + image = res.get('name') or image_file_item[1][0] + + payload = ComfyUICreateVideoForm( + workflow=ComfyUIWorkflow( + workflow=connection_config['workflow'], + nodes=connection_config.get('nodes') or [], + ), + prompt=form_data.prompt, + image=image, + width=width, + height=height, + length=get_comfyui_video_length(seconds, fps) if seconds else None, + fps=fps if connection_config.get('fps') else None, + ) + videos = await comfyui_create_video( + model, + payload, + str(uuid.uuid4()), + connection['url'], + connection['key'], + timeout=VIDEO_GENERATION_TIMEOUT, + ) + + files = [] + for video_data, content_type in videos: + _, video_file = await upload_image( + request, + video_data, + content_type, + {'model': model, 'prompt': form_data.prompt, **metadata}, + user, + name='generated-video', + ) + files.append(video_file) + return files + except HTTPException: + raise + except Exception as e: + log.exception(f'Video generation failed: {e}') + error = e.message if isinstance(e, aiohttp.ClientResponseError) else e + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(error)) diff --git a/backend/open_webui/utils/images/comfyui.py b/backend/open_webui/utils/images/comfyui.py index 0474c480e0..a9cf4eca88 100644 --- a/backend/open_webui/utils/images/comfyui.py +++ b/backend/open_webui/utils/images/comfyui.py @@ -1,4 +1,6 @@ +import asyncio import logging +import mimetypes import random import urllib.parse from typing import Optional @@ -66,13 +68,12 @@ async def get_history(prompt_id, base_url, api_key): return await r.json() -async def _ws_get_images(ws, workflow, client_id, base_url, api_key): - """Queue a prompt and wait on *ws* for ComfyUI to finish executing it. +async def _ws_run_prompt(ws, workflow, client_id, base_url, api_key) -> dict: + """Queue a prompt, wait on *ws* for ComfyUI to finish executing it, and return its history entry. - Returns a dict of ``{'data': [{'url': ...}, ...]}``. + Raises when the workflow failed. """ prompt_id = (await queue_prompt(workflow, client_id, base_url, api_key))['prompt_id'] - output_images = [] async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: @@ -93,6 +94,16 @@ async def _ws_get_images(ws, workflow, client_id, base_url, api_key): raise Exception( f'ComfyUI {error.get("node_type", "workflow")} failed: {error.get("exception_message", "").strip()}' ) + return history + + +async def _ws_get_images(ws, workflow, client_id, base_url, api_key): + """Queue a prompt and wait on *ws* for ComfyUI to finish executing it. + + Returns a dict of ``{'data': [{'url': ...}, ...]}``. + """ + history = await _ws_run_prompt(ws, workflow, client_id, base_url, api_key) + output_images = [] for node_id in history['outputs']: node_output = history['outputs'][node_id] @@ -154,46 +165,48 @@ class ComfyUICreateImageForm(BaseModel): seed: Optional[int] = None +# Node types filled from the request field of the same name, with the input key used when none is set. +WORKFLOW_NODE_INPUT_KEYS = { + 'prompt': 'text', + 'negative_prompt': 'text', + 'width': 'width', + 'height': 'height', + 'n': 'batch_size', + 'steps': 'steps', + 'length': 'length', + 'fps': 'fps', +} + + def _apply_workflow_nodes(workflow, nodes, model, payload): - """Mutate *workflow* dict in-place based on typed node definitions.""" + """Mutate *workflow* dict in-place based on typed node definitions. + + A value the request leaves out (None) keeps the one already in the workflow. + """ + + def set_input(node, value, default_key=None): + if value is None: + return + for node_id in node.node_ids: + workflow[node_id]['inputs'][node.key or default_key] = value + for node in nodes: - if node.type: - if node.type == 'model': - for node_id in node.node_ids: - workflow[node_id]['inputs'][node.key] = model - elif node.type == 'prompt': - for node_id in node.node_ids: - workflow[node_id]['inputs'][node.key if node.key else 'text'] = payload.prompt - elif node.type == 'negative_prompt': - for node_id in node.node_ids: - workflow[node_id]['inputs'][node.key if node.key else 'text'] = payload.negative_prompt - elif node.type == 'image': - if isinstance(payload.image, list): - for idx, node_id in enumerate(node.node_ids): - if idx < len(payload.image): - workflow[node_id]['inputs'][node.key] = payload.image[idx] - else: - for node_id in node.node_ids: - workflow[node_id]['inputs'][node.key] = payload.image - elif node.type == 'width': - for node_id in node.node_ids: - workflow[node_id]['inputs'][node.key if node.key else 'width'] = payload.width - elif node.type == 'height': - for node_id in node.node_ids: - workflow[node_id]['inputs'][node.key if node.key else 'height'] = payload.height - elif node.type == 'n': - for node_id in node.node_ids: - workflow[node_id]['inputs'][node.key if node.key else 'batch_size'] = payload.n - elif node.type == 'steps': - for node_id in node.node_ids: - workflow[node_id]['inputs'][node.key if node.key else 'steps'] = payload.steps - elif node.type == 'seed': - seed = payload.seed if payload.seed else random.randint(0, 1125899906842624) - for node_id in node.node_ids: - workflow[node_id]['inputs'][node.key] = seed - else: - for node_id in node.node_ids: - workflow[node_id]['inputs'][node.key] = node.value + if not node.type: + set_input(node, node.value) + elif node.type == 'model': + # No model (a connection without model IDs) runs the one the workflow sets. + set_input(node, model or None) + elif node.type == 'image': + image = getattr(payload, 'image', None) + if isinstance(image, list): + for node_id, value in zip(node.node_ids, image): + workflow[node_id]['inputs'][node.key] = value + else: + set_input(node, image) + elif node.type == 'seed': + set_input(node, getattr(payload, 'seed', None) or random.randint(0, 1125899906842624)) + elif node.type in WORKFLOW_NODE_INPUT_KEYS: + set_input(node, getattr(payload, node.type, None), WORKFLOW_NODE_INPUT_KEYS[node.type]) async def comfyui_create_image(model: str, payload: ComfyUICreateImageForm, client_id, base_url, api_key): @@ -263,3 +276,91 @@ async def comfyui_edit_image(model: str, payload: ComfyUIEditImageForm, client_i return None return images + + +class ComfyUICreateVideoForm(BaseModel): + workflow: ComfyUIWorkflow + + prompt: str + negative_prompt: Optional[str] = None + image: Optional[str] = None # starting frame, as a file name uploaded to ComfyUI + width: Optional[int] = None + height: Optional[int] = None + length: Optional[int] = None # in frames + fps: Optional[float] = None + + steps: Optional[int] = None + seed: Optional[int] = None + + +VIDEO_EXTENSIONS = ('.mp4', '.webm', '.mkv', '.mov', '.gif', '.webp') + + +def get_video_outputs(history: dict) -> list[dict]: + """The video files a finished prompt saved, as ``{filename, subfolder, type}`` entries. + + ComfyUI's SaveVideo and SaveWEBM list them under ``images`` (marked ``animated``), and + VideoHelperSuite's Video Combine under ``gifs``. Inputs a workflow loaded (LoadVideo) are left out. + """ + outputs = [] + for node_output in (history.get('outputs') or {}).values(): + for key in ('images', 'gifs', 'videos'): + for entry in node_output.get(key) or []: + if ( + isinstance(entry, dict) + and entry.get('filename', '').lower().endswith(VIDEO_EXTENSIONS) + and entry.get('type') != 'input' + ): + outputs.append(entry) + # Prefer saved files over the temporary previews some nodes also write. + saved = [entry for entry in outputs if entry.get('type') == 'output'] + return saved or outputs + + +async def get_video(entry: dict, base_url: str, api_key: str) -> tuple[bytes, str]: + """Download a video ComfyUI saved, with its content type.""" + data = {'filename': entry['filename'], 'subfolder': entry.get('subfolder', ''), 'type': entry.get('type', 'output')} + headers = {**default_headers} + if api_key: + headers['Authorization'] = f'Bearer {api_key}' + + session = await get_session() + async with session.get( + f'{base_url}/view?{urllib.parse.urlencode(data)}', headers=headers, ssl=AIOHTTP_CLIENT_SESSION_SSL + ) as r: + r.raise_for_status() + content_type = r.headers.get('content-type', '').split(';')[0] + if not content_type.startswith(('video/', 'image/')): + content_type = mimetypes.guess_type(entry['filename'])[0] or 'video/mp4' + return await r.read(), content_type + + +async def comfyui_create_video( + model: str, payload: ComfyUICreateVideoForm, client_id, base_url, api_key, timeout: float +) -> list[tuple[bytes, str]]: + """Run a video workflow and return each video it saved, as ``(data, content_type)``. + + Raises when the workflow fails, saves no video, or is not done within *timeout* seconds. + """ + ws_url = base_url.replace('http://', 'ws://').replace('https://', 'wss://') + workflow = JSONCodec.loads(payload.workflow.workflow) + _apply_workflow_nodes(workflow, payload.workflow.nodes, model, payload) + log.debug('Workflow: %s', workflow) + + headers = {'Authorization': f'Bearer {api_key}'} if api_key else {} + session = await get_session() + try: + async with asyncio.timeout(timeout): + async with session.ws_connect( + f'{ws_url}/ws?clientId={client_id}', + headers=headers, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + ) as ws: + history = await _ws_run_prompt(ws, workflow, client_id, base_url, api_key) + except TimeoutError: + raise Exception(f'The video was not ready after {int(timeout)} seconds') + + outputs = get_video_outputs(history) + if not outputs: + raise Exception('The ComfyUI workflow saved no video. Add a Save Video node to it.') + return [await get_video(entry, base_url, api_key) for entry in outputs] diff --git a/backend/open_webui/utils/videos/connections.py b/backend/open_webui/utils/videos/connections.py index 52ab0387cd..aa2953fbda 100644 --- a/backend/open_webui/utils/videos/connections.py +++ b/backend/open_webui/utils/videos/connections.py @@ -1,7 +1,8 @@ """Video connections: the configured backends that built-in video generation runs on. A connection is one OpenAI compatible server with a video API (``/videos``), such as LiteLLM, -OpenAI or OpenRouter, with the video models it exposes. Users pick a model by its reference, +OpenAI or OpenRouter, or a ComfyUI server running the admin's video workflow, with the video models it +exposes. Users pick a model by its reference, ``{connection_id}:{model_id}``, and only see models their access grants allow. """ @@ -24,6 +25,8 @@ from open_webui.utils.images.connections import ( IMAGE_CONNECTION_AUTH_TYPES, _json_object, _size, + _workflow, + _workflow_nodes, get_image_model_ref, get_openai_connection_models, get_requested_model, @@ -35,7 +38,7 @@ log = logging.getLogger(__name__) VIDEO_CONNECTIONS_CONFIG_KEY = 'videos.connections' VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY = 'video_generation.default_model' -VIDEO_CONNECTION_TYPES = ('openai',) +VIDEO_CONNECTION_TYPES = ('openai', 'comfyui') VIDEO_CONNECTION_AUTH_TYPES = IMAGE_CONNECTION_AUTH_TYPES # Like chat model connections: '' is the OpenAI video API (OpenAI, LiteLLM); OpenRouter has its own. @@ -71,8 +74,10 @@ def normalize_video_connection(connection: dict[str, Any]) -> dict[str, Any]: auth_type = str(config.get('auth_type') or 'bearer') if auth_type not in VIDEO_CONNECTION_AUTH_TYPES: raise ValueError(f'Unsupported auth type: {auth_type}') + if connection_type != 'openai' and auth_type not in ('none', 'bearer'): + raise ValueError(f'{connection_type} connections support no auth or a key') - provider = str(config.get('provider') or '') + provider = str(config.get('provider') or '') if connection_type == 'openai' else '' if provider not in VIDEO_CONNECTION_PROVIDERS: raise ValueError(f'Unsupported video provider: {provider}') @@ -84,6 +89,14 @@ def normalize_video_connection(connection: dict[str, Any]) -> dict[str, Any]: else: seconds = None + fps = config.get('fps') + if fps not in (None, ''): + fps = float(fps) + if fps <= 0: + raise ValueError('Frame rate must be a positive number of frames per second (e.g. 24)') + else: + fps = None + return { 'id': connection_id, 'name': str(connection.get('name') or '').strip() or connection_type, @@ -101,6 +114,9 @@ def normalize_video_connection(connection: dict[str, Any]) -> dict[str, Any]: 'seconds': seconds, 'api_version': str(config.get('api_version') or ''), 'params': _json_object(config.get('params'), 'additional parameters'), + 'workflow': _workflow(config.get('workflow'), 'ComfyUI workflow'), + 'nodes': _workflow_nodes(config.get('nodes')), + 'fps': fps, }, } @@ -108,7 +124,12 @@ def normalize_video_connection(connection: dict[str, Any]) -> dict[str, Any]: async def get_video_connection_models(request: Request, connection: dict, user: UserModel | None = None) -> list[dict]: """The models a connection serves, with video models marked (``video``). OpenRouter lists its video models on their own at ``/videos/models``; other servers list everything at ``/models``, and LiteLLM - marks which ones make video.""" + marks which ones make video. ComfyUI offers the models its workflow's model node can load.""" + if connection.get('type') == 'comfyui': + from open_webui.routers.images import get_comfyui_connection_models + + return [{**model, 'video': True} for model in await get_comfyui_connection_models(connection)] + if get_video_connection_provider(connection) != 'openrouter': return await get_openai_connection_models(request, connection, user) @@ -157,7 +178,8 @@ async def get_synced_video_models(request: Request, connection: dict, user: User async def get_video_models(request: Request, user: UserModel, *, bypass_access: bool = False) -> list[dict]: """Video models the user may use, across enabled connections. Each carries its connection for internal use. - A connection without model IDs offers every video model the server labels (LiteLLM), else its default model. + A connection without model IDs offers every video model the server labels (LiteLLM), else its default + model, or for ComfyUI the model its workflow sets. """ connections = await Config.get(VIDEO_CONNECTIONS_CONFIG_KEY) or [] user_group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id, include_inherited=True)} @@ -172,6 +194,8 @@ async def get_video_models(request: Request, user: UserModel, *, bypass_access: if config.get('model_ids'): entries = [{'id': model_id} for model_id in config['model_ids']] + elif connection.get('type') == 'comfyui': + entries = [{'id': ''}] else: entries = await get_synced_video_models(request, connection, user) diff --git a/src/lib/components/AddConnectionModal.svelte b/src/lib/components/AddConnectionModal.svelte index f3d8da26d4..8ba7c401da 100644 --- a/src/lib/components/AddConnectionModal.svelte +++ b/src/lib/components/AddConnectionModal.svelte @@ -321,8 +321,8 @@ bind:show >