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 >
-
-

+
+

{#if edit} {$i18n.t('Edit Connection')} {:else} @@ -336,7 +336,7 @@ show = false; }} > - +

@@ -349,7 +349,7 @@ submitHandler(); }} > -
+
{$i18n.t('Connection Type')}
diff --git a/src/lib/components/AddTerminalServerModal.svelte b/src/lib/components/AddTerminalServerModal.svelte index 04c990cfcd..12c131ee30 100644 --- a/src/lib/components/AddTerminalServerModal.svelte +++ b/src/lib/components/AddTerminalServerModal.svelte @@ -118,19 +118,19 @@ size="sm" ariaLabel={$i18n.t(edit ? 'Edit Terminal Connection' : 'Add Terminal Connection')} > -
-

+
+

{$i18n.t(edit ? 'Edit Terminal Connection' : 'Add Terminal Connection')}

{#if error}{/if} diff --git a/src/lib/components/AddToolServerModal.svelte b/src/lib/components/AddToolServerModal.svelte index ea2fd539c6..ace1dc8e46 100644 --- a/src/lib/components/AddToolServerModal.svelte +++ b/src/lib/components/AddToolServerModal.svelte @@ -499,8 +499,8 @@ bind:show >
-
-

+
+

{#if edit} {$i18n.t('Edit Connection')} {:else} @@ -555,7 +555,7 @@ submitHandler(); }} > -
+
{$i18n.t('Type')}
diff --git a/src/lib/components/ChangelogModal.svelte b/src/lib/components/ChangelogModal.svelte index aba3aab8db..d0df4a8921 100644 --- a/src/lib/components/ChangelogModal.svelte +++ b/src/lib/components/ChangelogModal.svelte @@ -91,13 +91,13 @@ >
-

+

{$i18n.t("What's New in")} {$WEBUI_NAME}

diff --git a/src/lib/components/admin/Settings/Apps/AppModal.svelte b/src/lib/components/admin/Settings/Apps/AppModal.svelte index 4c2a4d495b..e8b9bf8d18 100644 --- a/src/lib/components/admin/Settings/Apps/AppModal.svelte +++ b/src/lib/components/admin/Settings/Apps/AppModal.svelte @@ -220,8 +220,8 @@ size="sm" bind:show > -
-

+
+

{showScopes ? scopeMode === 'requested' ? $i18n.t('Requested scopes') @@ -236,11 +236,11 @@ class="self-center" on:click={() => { show = false; - }}>

{#if showScopes} -
+

{scopeMode === 'requested' ? $i18n.t('Enter the scopes requested by the app.') @@ -313,7 +313,7 @@

{:else} - + {#if loading}
{:else} {#if !manifest}
-
-
+
+
{#if edit} {$i18n.t('Edit Arena Model')} {:else} @@ -178,7 +178,7 @@ show = false; }} > - +
@@ -190,7 +190,7 @@ submitHandler(); }} > -
+
- {#if workflow} - - {/if} + +
- {$i18n.t('*Prompt node ID(s) are required for image generation')} + {requiredNote || $i18n.t('*Prompt node ID(s) are required for image generation')}
{/if}
diff --git a/src/lib/components/admin/Settings/Images/ImageConnectionModal.svelte b/src/lib/components/admin/Settings/Images/ImageConnectionModal.svelte index 9819b28d70..dd6fe03f40 100644 --- a/src/lib/components/admin/Settings/Images/ImageConnectionModal.svelte +++ b/src/lib/components/admin/Settings/Images/ImageConnectionModal.svelte @@ -318,8 +318,8 @@ bind:show >
-
-

+
+

{#if edit} {$i18n.t('Edit Connection')} {:else} @@ -333,7 +333,7 @@ show = false; }} > - +

@@ -346,7 +346,7 @@ submitHandler(); }} > -
+
-
+
-
+
{editingKey ? $i18n.t('Edit control') : $i18n.t('Add control')}
(show = false)}>
diff --git a/src/lib/components/admin/Settings/Videos/VideoConnectionModal.svelte b/src/lib/components/admin/Settings/Videos/VideoConnectionModal.svelte index 51b67d0122..b1c68badfb 100644 --- a/src/lib/components/admin/Settings/Videos/VideoConnectionModal.svelte +++ b/src/lib/components/admin/Settings/Videos/VideoConnectionModal.svelte @@ -17,6 +17,10 @@ import Textarea from '$lib/components/common/Textarea.svelte'; import AccessButton from '$lib/components/common/AccessButton.svelte'; import AccessControlModal from '$lib/components/workspace/common/AccessControlModal.svelte'; + import ComfyUIWorkflow from '$lib/components/admin/Settings/Images/ComfyUIWorkflow.svelte'; + + type ConnectionType = 'openai' | 'comfyui'; + type WorkflowNode = { type: string; key: string; node_ids: string }; export let onSubmit: Function = () => {}; export let onDelete: Function = () => {}; @@ -26,6 +30,21 @@ export let connection: any = null; + // Input keys of the usual nodes in a Wan, LTX-Video or HunyuanVideo workflow. + const VIDEO_WORKFLOW_NODES: WorkflowNode[] = [ + { type: 'prompt', key: 'text', node_ids: '' }, + { type: 'negative_prompt', key: 'text', node_ids: '' }, + { type: 'model', key: 'unet_name', node_ids: '' }, + { type: 'image', key: 'image', node_ids: '' }, + { type: 'width', key: 'width', node_ids: '' }, + { type: 'height', key: 'height', node_ids: '' }, + { type: 'length', key: 'length', node_ids: '' }, + { type: 'fps', key: 'fps', node_ids: '' }, + { type: 'steps', key: 'steps', node_ids: '' }, + { type: 'seed', key: 'seed', node_ids: '' } + ]; + + let connectionType: ConnectionType = 'openai'; let name = ''; let url = ''; let key = ''; @@ -43,6 +62,9 @@ let provider = ''; let params = ''; let headers = ''; + let fps = ''; + let workflow = ''; + let nodes: WorkflowNode[] = []; let loading = false; let showDeleteConfirmDialog = false; @@ -54,6 +76,35 @@ const selectClass = 'bg-transparent pr-5 outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'; + $: typeLabel = { + openai: $i18n.t('OpenAI compatible'), + comfyui: $i18n.t('ComfyUI') + }[connectionType]; + + // Only OpenAI compatible connections authenticate the way chat model connections do. + $: if (connectionType !== 'openai' && !['none', 'bearer'].includes(auth_type)) { + auth_type = 'bearer'; + } + + const mapNodes = (defaults: WorkflowNode[], saved: any[] = []) => + defaults.map((node) => { + const match = saved.find((n) => n.type === node.type) ?? node; + return { + type: match.type, + key: match.key, + node_ids: Array.isArray(match.node_ids) ? match.node_ids.join(',') : (match.node_ids ?? '') + }; + }); + + const toNodeConfig = (workflowNodes: WorkflowNode[]) => + workflowNodes.map((node) => ({ + ...node, + node_ids: node.node_ids + .split(',') + .map((id) => id.trim()) + .filter(Boolean) + })); + const formatJSON = (value: any) => { if (!value) return ''; if (typeof value === 'object') { @@ -85,6 +136,21 @@ toast.error($i18n.t('Enter Video Length in seconds (e.g. 8)')); return false; } + if (connectionType === 'comfyui') { + if (!workflow.trim()) { + toast.error($i18n.t('Upload a ComfyUI workflow to generate videos')); + return false; + } + if (!isJSONObject(workflow)) { + toast.error($i18n.t('Invalid JSON format for ComfyUI Workflow.')); + return false; + } + if (fps !== '' && !(Number(fps) > 0)) { + showAdvanced = true; + toast.error($i18n.t('Enter Frame Rate in frames per second (e.g. 24)')); + return false; + } + } if (headers.trim() && !isJSONObject(headers)) { showAdvanced = true; toast.error($i18n.t('Headers must be a valid JSON object')); @@ -100,10 +166,10 @@ const buildConnection = () => ({ ...(connection?.id ? { id: connection.id } : {}), - name: name.trim() || $i18n.t('OpenAI compatible'), - type: 'openai', + name: name.trim() || typeLabel, + type: connectionType, url, - key, + key: connectionType !== 'openai' && auth_type === 'none' ? '' : key, config: { enable, model_ids: modelIds, @@ -111,10 +177,13 @@ size: size.trim(), seconds: seconds === '' ? null : Number(seconds), api_version: apiVersion.trim(), - provider, + provider: connectionType === 'openai' ? provider : '', auth_type, - headers: headers.trim() ? JSON.parse(headers) : {}, - params: params.trim() ? JSON.parse(params) : {} + headers: connectionType === 'openai' && headers.trim() ? JSON.parse(headers) : {}, + params: connectionType === 'openai' && params.trim() ? JSON.parse(params) : {}, + workflow: connectionType === 'comfyui' ? workflow.trim() : '', + nodes: connectionType === 'comfyui' ? toNodeConfig(nodes) : [], + fps: connectionType === 'comfyui' && fps !== '' ? Number(fps) : null } }); @@ -183,6 +252,7 @@ showAdvanced = false; modelId = ''; + connectionType = connection?.type ?? 'openai'; name = connection?.name ?? ''; url = connection?.url ?? ''; key = connection?.key ?? ''; @@ -197,6 +267,9 @@ provider = config.provider ?? ''; params = formatJSON(config.params); headers = formatJSON(config.headers); + fps = config.fps === null || config.fps === undefined ? '' : `${config.fps}`; + workflow = formatJSON(config.workflow); + nodes = mapNodes(VIDEO_WORKFLOW_NODES, config.nodes ?? []); }; $: if (show) { @@ -214,8 +287,8 @@ bind:show >
-
-

+
+

{#if edit} {$i18n.t('Edit Connection')} {:else} @@ -229,7 +302,7 @@ show = false; }} > - +

@@ -242,7 +315,27 @@ submitHandler(); }} > -
+
+
+ + +
+ +
+
+
@@ -404,10 +501,14 @@ {:else}
- {$i18n.t( - 'Leave empty to include all video models from "{{url}}/models" endpoint, or the server\'s default model if it does not mark which models make videos', - { url } - )} + {#if connectionType === 'comfyui'} + {$i18n.t('Leave empty to use the model set in the workflow')} + {:else} + {$i18n.t( + 'Leave empty to include all video models from "{{url}}/models" endpoint, or the server\'s default model if it does not mark which models make videos', + { url } + )} + {/if}
{/if}
@@ -450,6 +551,22 @@
+ {#if connectionType === 'comfyui'} + + {/if} +
-
- - -
- -
-
- - {#if provider !== 'openrouter' && !url.includes('openrouter.ai')} + {#if connectionType === 'comfyui'}
- {$i18n.t('Frame Rate')}
- {/if} - -
-
- + -
- + +
+
+ + {#if provider !== 'openrouter' && !url.includes('openrouter.ai')} +
+
+ + +
+
+ {/if} + +
+
+ + +
+ +