diff --git a/backend/open_webui/config.py b/backend/open_webui/config.py index 8b71335d46..0b6ae4b249 100644 --- a/backend/open_webui/config.py +++ b/backend/open_webui/config.py @@ -1557,6 +1557,14 @@ except JSONCodec.JSONDecodeError: IMAGES_EDIT_COMFYUI_WORKFLOW_NODES = images_edit_comfyui_workflow_nodes +# Videos + +ENABLE_VIDEO_GENERATION = os.getenv('ENABLE_VIDEO_GENERATION', '').lower() == 'true' + +# How long to wait for a video job to finish, and how often to check on it. +VIDEO_GENERATION_TIMEOUT = int(os.getenv('VIDEO_GENERATION_TIMEOUT', '900')) +VIDEO_GENERATION_POLL_INTERVAL = float(os.getenv('VIDEO_GENERATION_POLL_INTERVAL', '5')) + # Audio # Transcription @@ -1937,6 +1945,11 @@ USER_PERMISSIONS_FEATURES_IMAGE_GENERATION = ( os.getenv('USER_PERMISSIONS_FEATURES_IMAGE_GENERATION', 'True').lower() == 'true' ) +# Off by default: video costs far more per request than images. +USER_PERMISSIONS_FEATURES_VIDEO_GENERATION = ( + os.getenv('USER_PERMISSIONS_FEATURES_VIDEO_GENERATION', 'False').lower() == 'true' +) + USER_PERMISSIONS_FEATURES_CODE_INTERPRETER = ( os.getenv('USER_PERMISSIONS_FEATURES_CODE_INTERPRETER', 'True').lower() == 'true' ) @@ -2042,6 +2055,7 @@ DEFAULT_USER_PERMISSIONS = { # Chat features 'web_search': USER_PERMISSIONS_FEATURES_WEB_SEARCH, 'image_generation': USER_PERMISSIONS_FEATURES_IMAGE_GENERATION, + 'video_generation': USER_PERMISSIONS_FEATURES_VIDEO_GENERATION, 'code_interpreter': USER_PERMISSIONS_FEATURES_CODE_INTERPRETER, 'memories': USER_PERMISSIONS_FEATURES_MEMORIES, 'subagents': USER_PERMISSIONS_FEATURES_SUBAGENTS, @@ -3185,6 +3199,8 @@ DEFAULT_CONFIG = { 'images.edit.engine': IMAGE_EDIT_ENGINE, 'images.edit.model': IMAGE_EDIT_MODEL, 'images.edit.default_model': '', + 'video_generation.enable': ENABLE_VIDEO_GENERATION, + 'video_generation.default_model': '', 'images.edit.size': IMAGE_EDIT_SIZE, 'images.edit.openai.api_base_url': IMAGES_EDIT_OPENAI_API_BASE_URL, 'images.edit.openai.api_version': IMAGES_EDIT_OPENAI_API_VERSION, diff --git a/backend/open_webui/events.py b/backend/open_webui/events.py index 440e9d8f6e..38d3ff71c2 100644 --- a/backend/open_webui/events.py +++ b/backend/open_webui/events.py @@ -695,6 +695,9 @@ class EventDefinitions(BaseModel): IMAGE_EDITED: EventDefinition = EventDefinition( name='image.edited', description='An image was edited.', message='Image edited' ) + VIDEO_GENERATED: EventDefinition = EventDefinition( + name='video.generated', description='A video was generated.', message='Video generated' + ) AUDIO_SPEECH_REQUESTED: EventDefinition = EventDefinition( name='audio.speech_requested', description='Speech generation was requested.', message='Speech requested' ) diff --git a/backend/open_webui/main.py b/backend/open_webui/main.py index aa1293fba5..2a8d7839d1 100644 --- a/backend/open_webui/main.py +++ b/backend/open_webui/main.py @@ -184,6 +184,7 @@ from open_webui.routers import ( tools, users, utils, + videos, ) from open_webui.routers.retrieval import ( get_ef, @@ -820,6 +821,7 @@ app.include_router(openai.router, prefix='/openai', tags=['openai']) app.include_router(pipelines.router, prefix='/api/v1/pipelines', tags=['pipelines']) app.include_router(tasks.router, prefix='/api/v1/tasks', tags=['tasks']) app.include_router(images.router, prefix='/api/v1/images', tags=['images']) +app.include_router(videos.router, prefix='/api/v1/videos', tags=['videos']) app.include_router(audio.router, prefix='/api/v1/audio', tags=['audio']) app.include_router(retrieval.router, prefix='/api/v1/retrieval', tags=['retrieval']) @@ -2384,6 +2386,7 @@ async def get_app_config(request: Request): 'code_execution.enable', 'code_interpreter.enable', 'image_generation.enable', + 'video_generation.enable', 'task.autocomplete.enable', 'task.title.enable', 'task.follow_up.enable', @@ -2498,6 +2501,7 @@ async def get_app_config(request: Request): 'enable_code_execution': config.get('code_execution.enable'), 'enable_code_interpreter': config.get('code_interpreter.enable'), 'enable_image_generation': config.get('image_generation.enable'), + 'enable_video_generation': config.get('video_generation.enable'), 'enable_autocomplete_generation': config.get('task.autocomplete.enable'), 'enable_title_generation': config.get('task.title.enable'), 'enable_follow_up_generation': config.get('task.follow_up.enable'), diff --git a/backend/open_webui/routers/images.py b/backend/open_webui/routers/images.py index 7729d0369e..b46856af1a 100644 --- a/backend/open_webui/routers/images.py +++ b/backend/open_webui/routers/images.py @@ -497,13 +497,13 @@ async def get_image_data(data: str, headers=None, trusted_base_url: str | None = return None, None -async def upload_image(request, image_data, content_type, metadata, user, db=None): +async def upload_image(request, image_data, content_type, metadata, user, db=None, name='generated-image'): if image_data is None or content_type is None: raise ValueError('Failed to retrieve image data from the generation backend') image_format = IMAGE_FILE_EXTENSIONS.get(content_type.lower()) or mimetypes.guess_extension(content_type) or '.png' file = UploadFile( file=io.BytesIO(image_data), - filename=f'generated-image{image_format}', # will be converted to a unique ID on upload_file + filename=f'{name}{image_format}', # will be converted to a unique ID on upload_file headers={ 'content-type': content_type, }, @@ -824,6 +824,58 @@ async def image_generations( raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(error)) +async def load_url_image(data: str, user) -> str: + """An image as a data URL, from a data URL, a web URL (SSRF-checked) or an Open WebUI file.""" + if data.startswith('data:'): + return data + + if data.startswith('http://') or data.startswith('https://'): + parsed = urlparse(data) + # Fetching /api/v1/files/{id}/content over the network would be unauthenticated. + if parsed.path.startswith('/api/v1/files/') and '/content' in parsed.path: + return await load_url_image(parsed.path, user) + + # Validate URL to prevent SSRF attacks against local/private networks. + # allow_redirects=False prevents redirect-based SSRF: validate_url() is + # called only on the originally-submitted URL; following 3xx redirects + # without re-validation would let an attacker reach private IPs via a + # public host that redirects internally (e.g. cloud-metadata exfil). + await asyncio.to_thread(validate_url, data) + # SSRF-safe session: re-checks the connect-time IP so a rebinding DNS answer + # that passed validate_url cannot reach an internal address. + async with get_ssrf_safe_session() as session: + async with session.get( + data, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + allow_redirects=AIOHTTP_CLIENT_ALLOW_REDIRECTS, + headers={'Accept-Encoding': 'identity'}, + ) as r: + r.raise_for_status() + assert_identity_encoding(r.headers.getall('Content-Encoding', ())) + + image_data = base64.b64encode(await r.read()).decode('utf-8') + return f'data:{r.headers["content-type"]};base64,{image_data}' + + else: + file_id = None + if data.startswith('/api/v1/files'): + file_id = data.split('/api/v1/files/')[1].split('/content')[0] + else: + file_id = data + + file_response = await get_file_content_by_id(file_id, user) + if isinstance(file_response, FileResponse): + file_path = file_response.path + + async with aiofiles.open(file_path, 'rb') as f: + file_bytes = await f.read() + image_data = base64.b64encode(file_bytes).decode('utf-8') + mime_type, _ = mimetypes.guess_type(file_path) + + return f'data:{mime_type};base64,{image_data}' + return data + + class EditImageForm(BaseModel): image: str | list[str] # base64-encoded image(s) or URL(s) prompt: str @@ -891,63 +943,12 @@ async def image_edits( width, height = tuple(map(int, size.split('x'))) try: - - async def load_url_image(data): - if data.startswith('data:'): - return data - - if data.startswith('http://') or data.startswith('https://'): - parsed = urlparse(data) - # Fetching /api/v1/files/{id}/content over the network would be unauthenticated. - if parsed.path.startswith('/api/v1/files/') and '/content' in parsed.path: - return await load_url_image(parsed.path) - - # Validate URL to prevent SSRF attacks against local/private networks. - # allow_redirects=False prevents redirect-based SSRF: validate_url() is - # called only on the originally-submitted URL; following 3xx redirects - # without re-validation would let an attacker reach private IPs via a - # public host that redirects internally (e.g. cloud-metadata exfil). - await asyncio.to_thread(validate_url, data) - # SSRF-safe session: re-checks the connect-time IP so a rebinding DNS answer - # that passed validate_url cannot reach an internal address. - async with get_ssrf_safe_session() as session: - async with session.get( - data, - ssl=AIOHTTP_CLIENT_SESSION_SSL, - allow_redirects=AIOHTTP_CLIENT_ALLOW_REDIRECTS, - headers={'Accept-Encoding': 'identity'}, - ) as r: - r.raise_for_status() - assert_identity_encoding(r.headers.getall('Content-Encoding', ())) - - image_data = base64.b64encode(await r.read()).decode('utf-8') - return f'data:{r.headers["content-type"]};base64,{image_data}' - - else: - file_id = None - if data.startswith('/api/v1/files'): - file_id = data.split('/api/v1/files/')[1].split('/content')[0] - else: - file_id = data - - file_response = await get_file_content_by_id(file_id, user) - if isinstance(file_response, FileResponse): - file_path = file_response.path - - async with aiofiles.open(file_path, 'rb') as f: - file_bytes = await f.read() - image_data = base64.b64encode(file_bytes).decode('utf-8') - mime_type, _ = mimetypes.guess_type(file_path) - - return f'data:{mime_type};base64,{image_data}' - return data - # Load image(s) from URL(s) if necessary if isinstance(form_data.image, str): - form_data.image = await load_url_image(form_data.image) + form_data.image = await load_url_image(form_data.image, user) elif isinstance(form_data.image, list): # Load all images in parallel for better performance - form_data.image = list(await asyncio.gather(*[load_url_image(img) for img in form_data.image])) + form_data.image = list(await asyncio.gather(*[load_url_image(img, user) for img in form_data.image])) except HTTPException: raise except Exception as e: diff --git a/backend/open_webui/routers/users.py b/backend/open_webui/routers/users.py index 072294325b..3d33d56e71 100644 --- a/backend/open_webui/routers/users.py +++ b/backend/open_webui/routers/users.py @@ -280,6 +280,7 @@ class FeaturesPermissions(BaseModel): web_search: bool = True image_generation: bool = True + video_generation: bool = False code_interpreter: bool = True memories: bool = True subagents: bool = True diff --git a/backend/open_webui/routers/videos.py b/backend/open_webui/routers/videos.py new file mode 100644 index 0000000000..0ab4c09cee --- /dev/null +++ b/backend/open_webui/routers/videos.py @@ -0,0 +1,309 @@ +from __future__ import annotations + +import asyncio +import logging +import time + +import aiohttp +from fastapi import APIRouter, Depends, HTTPException, Request +from open_webui.config import VIDEO_GENERATION_POLL_INTERVAL, VIDEO_GENERATION_TIMEOUT +from open_webui.constants import ERROR_MESSAGES +from open_webui.env import AIOHTTP_CLIENT_SESSION_SSL +from open_webui.events import EVENTS, publish_event +from open_webui.models.config import Config +from open_webui.routers.images import ( + get_image_file_item, + load_url_image, + raise_for_provider_status, + upload_image, +) +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.connections import get_openai_connection_models +from open_webui.utils.session_pool import get_session +from open_webui.utils.videos.connections import ( + VIDEO_CONNECTIONS_CONFIG_KEY, + VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY, + get_video_models, + normalize_video_connection, + resolve_video_model, +) +from pydantic import BaseModel, ConfigDict + +log = logging.getLogger(__name__) + +router = APIRouter() + + +VIDEO_CONFIG_KEYS = { + 'ENABLE_VIDEO_GENERATION': 'video_generation.enable', + 'VIDEO_GENERATION_DEFAULT_MODEL': VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY, + 'VIDEO_CONNECTIONS': VIDEO_CONNECTIONS_CONFIG_KEY, +} + + +class VideoConnection(BaseModel): + id: str | None = None + name: str = '' + type: str = 'openai' + url: str = '' + key: str = '' + config: dict = {} + + model_config = ConfigDict(extra='allow') + + +class VideosConfig(BaseModel): + ENABLE_VIDEO_GENERATION: bool + VIDEO_GENERATION_DEFAULT_MODEL: str = '' + VIDEO_CONNECTIONS: list[VideoConnection] = [] + + +async def get_video_config_values() -> dict: + values = await Config.get_many(*VIDEO_CONFIG_KEYS.values()) + return { + 'ENABLE_VIDEO_GENERATION': bool(values.get('video_generation.enable')), + 'VIDEO_GENERATION_DEFAULT_MODEL': values.get(VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY) or '', + 'VIDEO_CONNECTIONS': values.get(VIDEO_CONNECTIONS_CONFIG_KEY) or [], + } + + +@router.get('/config', response_model=VideosConfig) +async def get_config(request: Request, user=Depends(get_admin_user)): + return await get_video_config_values() + + +@router.post('/config/update') +async def update_config(request: Request, form_data: VideosConfig, user=Depends(get_admin_user)): + connections = [] + try: + for connection in form_data.VIDEO_CONNECTIONS: + connections.append(normalize_video_connection(connection.model_dump())) + except (ValueError, TypeError) as e: + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e)) + + if len({connection['id'] for connection in connections}) != len(connections): + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT('Video connection IDs must be unique')) + + await Config.upsert( + { + 'video_generation.enable': form_data.ENABLE_VIDEO_GENERATION, + VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY: form_data.VIDEO_GENERATION_DEFAULT_MODEL, + VIDEO_CONNECTIONS_CONFIG_KEY: connections, + } + ) + + values = await get_video_config_values() + await publish_event( + request, + EVENTS.CONFIG_UPDATED, + actor=user, + subject_id='videos', + data={ + 'video_generation_enabled': values['ENABLE_VIDEO_GENERATION'], + 'video_connections': [ + {'id': connection['id'], 'name': connection['name'], 'type': connection['type']} + for connection in connections + ], + }, + ) + return values + + +@router.post('/connections/verify') +async def verify_video_connection(request: Request, form_data: VideoConnection, user=Depends(get_admin_user)): + """Reach a connection before saving it and list the models it serves.""" + try: + connection = normalize_video_connection(form_data.model_dump()) + except (ValueError, TypeError) as e: + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e)) + + if not connection['url']: + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.INVALID_URL) + + try: + return await get_openai_connection_models(request, connection, user) + except Exception as e: + log.error( + f'Failed to verify video connection {connection["url"]}: {str(e) or type(e).__name__}', + exc_info=not isinstance(e, (aiohttp.ClientConnectionError, aiohttp.ClientResponseError, TimeoutError)), + ) + error = e.message if isinstance(e, aiohttp.ClientResponseError) else e + raise HTTPException( + status_code=400, + detail=ERROR_MESSAGES.DEFAULT(error, 'Failed to connect to the video generation server'), + ) + + +def public_video_model(model: dict) -> dict: + return {key: value for key, value in model.items() if key != 'connection'} + + +@router.get('/models') +async def get_models(request: Request, user=Depends(get_verified_user)): + """Video models this user can pick from.""" + if not await Config.get('video_generation.enable'): + return [] + + if user.role != 'admin' and not await has_permission( + user.id, 'features.video_generation', await Config.get('user.permissions') + ): + return [] + + return [public_video_model(model) for model in await get_video_models(request, user)] + + +@router.get('/connections/models') +async def get_connection_models(request: Request, user=Depends(get_admin_user)): + """Every model the enabled connections offer, whoever may use them, for choosing the default model.""" + return [public_video_model(model) for model in await get_video_models(request, user, bypass_access=True)] + + +class CreateVideoForm(BaseModel): + model: str | None = None + prompt: str + seconds: int | None = None + size: str | None = None + image: str | None = None # starting frame: a data URL, a URL or an Open WebUI file + + +@router.post('/generations') +async def generate_videos(request: Request, form_data: CreateVideoForm, user=Depends(get_verified_user)): + if not await Config.get('video_generation.enable'): + raise HTTPException( + status_code=403, + detail=ERROR_MESSAGES.ACCESS_PROHIBITED, + ) + + if user.role != 'admin' and not await has_permission( + user.id, 'features.video_generation', await Config.get('user.permissions') + ): + raise HTTPException( + status_code=403, + detail=ERROR_MESSAGES.ACCESS_PROHIBITED, + ) + + result = await video_generations(request, form_data, user=user, strict=True) + await publish_event( + request, + EVENTS.VIDEO_GENERATED, + actor=user, + subject_id=None, + subject_type='video', + data={ + 'model': form_data.model, + 'size': form_data.size, + 'seconds': form_data.seconds, + 'prompt_preview': form_data.prompt[:300], + }, + ) + return result + + +async def video_generations( + request: Request, + form_data: CreateVideoForm, + metadata: dict | None = None, + user=None, + strict: bool = False, + event_emitter=None, +): + """Start a video job, wait for it while reporting progress, and save the finished video as a file. + + 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``. + """ + connection, model = await resolve_video_model(request, user, form_data.model, strict=strict) + connection_config = connection.get('config') or {} + seconds = form_data.seconds or connection_config.get('seconds') + size = form_data.size or connection_config.get('size') + metadata = metadata or {} + + async def emit_status(description: str): + if event_emitter: + await event_emitter({'type': 'status', 'data': {'description': description, 'done': False}}) + + try: + headers, cookies = await get_headers_and_cookies( + request, connection['url'], connection['key'], connection_config, metadata, user=user + ) + # The create request is multipart, so the connection's JSON content type does not apply. + headers.pop('Content-Type', None) + + api_version = connection_config.get('api_version') + query = f'?api-version={api_version}' if api_version else '' + base_url = f'{connection["url"]}/videos' + + form = aiohttp.FormData() + if model: + form.add_field('model', model) + form.add_field('prompt', form_data.prompt) + if seconds: + form.add_field('seconds', str(seconds)) + if size: + form.add_field('size', size) + if form_data.image: + name, (filename, file, content_type) = get_image_file_item( + await load_url_image(form_data.image, user), 'input_reference' + ) + form.add_field(name, file, filename=filename, content_type=content_type) + for key, value in (connection_config.get('params') or {}).items(): + form.add_field(key, value if isinstance(value, str) else str(value)) + + session = await get_session() + async with session.post( + url=f'{base_url}{query}', data=form, headers=headers, cookies=cookies, ssl=AIOHTTP_CLIENT_SESSION_SSL + ) as r: + await raise_for_provider_status(r) + job = await r.json(content_type=None) + + await emit_status('Generating video') + deadline = time.monotonic() + VIDEO_GENERATION_TIMEOUT + # OpenAI's video API (and LiteLLM's, which follows it) reports queued, in_progress, completed or failed. + while job.get('status') in ('queued', 'in_progress'): + if time.monotonic() > deadline: + raise HTTPException( + status_code=400, detail=f'The video was not ready after {VIDEO_GENERATION_TIMEOUT} seconds' + ) + + await asyncio.sleep(VIDEO_GENERATION_POLL_INTERVAL) + async with session.get( + url=f'{base_url}/{job["id"]}{query}', headers=headers, cookies=cookies, ssl=AIOHTTP_CLIENT_SESSION_SSL + ) as r: + await raise_for_provider_status(r) + job = await r.json(content_type=None) + + if isinstance(job.get('progress'), (int, float)): + await emit_status(f'Generating video ({round(job["progress"])}%)') + + if job.get('status') != 'completed': + error = job.get('error') + message = error.get('message') if isinstance(error, dict) else error + raise HTTPException(status_code=400, detail=message or f'The video job {job.get("status")}') + + async with session.get( + url=f'{base_url}/{job["id"]}/content{query}', + headers=headers, + cookies=cookies, + ssl=AIOHTTP_CLIENT_SESSION_SSL, + ) as r: + await raise_for_provider_status(r) + video_data = await r.read() + content_type = r.headers.get('content-type', 'video/mp4').split(';')[0] or 'video/mp4' + + _, video_file = await upload_image( + request, + video_data, + content_type, + {'model': model, 'prompt': form_data.prompt, 'video_id': job['id'], **metadata}, + user, + name='generated-video', + ) + return [video_file] + 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/tools/builtin.py b/backend/open_webui/tools/builtin.py index bfd1aa071a..e36e8aa122 100644 --- a/backend/open_webui/tools/builtin.py +++ b/backend/open_webui/tools/builtin.py @@ -37,7 +37,9 @@ from open_webui.routers.images import ( image_edits, image_generations, ) +from open_webui.routers.videos import CreateVideoForm, video_generations from open_webui.utils.images.connections import get_requested_image_model +from open_webui.utils.videos.connections import get_requested_video_model from open_webui.routers.memories import ( AddMemoryForm, ListMemoryPathsForm, @@ -540,6 +542,108 @@ async def edit_image( return JSONCodec.dumps({'error': str(e)}) +# Video generation tools + + +async def generate_video( + prompt: str, + seconds: Optional[int] = None, + size: Optional[str] = None, + image_url: Optional[str] = None, + __request__: Request = None, + __user__: dict = None, + __event_emitter__: callable = None, + __chat_id__: str = None, + __message_id__: str = None, + __metadata__: dict = None, + __event_call__: callable = None, +) -> str: + """ + Generate a video based on a text prompt. Videos take minutes; progress is shown in chat while it runs. + + :param prompt: A detailed description of the video to generate + :param seconds: Optional length in seconds (e.g. 8), supported by the configured video model. + Omit to use the configured default. + :param size: Optional output size in WIDTHxHEIGHT pixels (e.g. "1280x720"), supported by the configured video model. + Omit to use the configured default. + :param image_url: Optional image to start the video from, as a URL from the conversation or a terminal path. + :return: Video URLs and, when a terminal is selected, terminal_path for display_file or further processing. + """ + if __request__ is None: + return JSONCodec.dumps({'error': 'Request context not available'}) + + try: + user = UserModel(**__user__) if __user__ else None + + if image_url and image_url.startswith('/') and not image_url.startswith('/api/v1/files/'): + data = await get_terminal_file(__request__, user, __metadata__ or {}, image_url, max_bytes=50 * 1024 * 1024) + image_url = await asyncio.to_thread(get_image_data_url, data) + + videos = await video_generations( + request=__request__, + form_data=CreateVideoForm( + prompt=prompt, + seconds=seconds, + size=size, + image=image_url, + model=get_requested_video_model(__metadata__), + ), + metadata=( + {'channel_id': __chat_id__.removeprefix('channel:'), 'message_id': __message_id__} + if isinstance(__chat_id__, str) and __chat_id__.startswith('channel:') + else None + ), + user=user, + event_emitter=__event_emitter__, + ) + + await upload_files_to_terminal( + __request__, user, videos, __metadata__ or {}, {'__event_call__': __event_call__} + ) + + # Prepare file entries for the videos + video_files = [{'type': 'video', **video} for video in videos] + + # Persist files to DB if chat context is available + if is_saved_chat_id(__chat_id__) and __message_id__ and videos: + db_files = await Chats.add_message_files_by_id_and_message_id( + __chat_id__, + __message_id__, + video_files, + ) + if db_files is not None: + video_files = db_files + + # Emit the videos to the UI if event emitter is available + if __event_emitter__ and video_files: + await __event_emitter__({'type': 'status', 'data': {'description': 'Video created', 'done': True}}) + await __event_emitter__( + { + 'type': 'chat:message:files', + 'data': { + 'files': video_files, + }, + } + ) + # Return a message indicating the video is already displayed + return JSONCodec.dumps( + { + 'status': 'success', + 'message': ( + 'The video is already visible in chat. Use terminal_path with terminal tools or ' + 'display_file when available to continue the requested task.' + ), + 'videos': videos, + }, + ensure_ascii=False, + ) + + return JSONCodec.dumps({'status': 'success', 'videos': videos}, ensure_ascii=False) + except Exception as e: + log.exception(f'generate_video error: {e}') + return JSONCodec.dumps({'error': str(getattr(e, 'detail', None) or e)}) + + # User input tools diff --git a/backend/open_webui/utils/agents/discovery.py b/backend/open_webui/utils/agents/discovery.py index bc039c94f4..3d3012c332 100644 --- a/backend/open_webui/utils/agents/discovery.py +++ b/backend/open_webui/utils/agents/discovery.py @@ -65,6 +65,7 @@ async def get_models(request, user, metadata, *, provider=None, cwd=None): 'file_upload': True, 'web_search': False, 'image_generation': False, + 'video_generation': False, 'code_interpreter': False, 'builtin_tools': False, } diff --git a/backend/open_webui/utils/automations.py b/backend/open_webui/utils/automations.py index b47c50a5a2..ee4630e556 100644 --- a/backend/open_webui/utils/automations.py +++ b/backend/open_webui/utils/automations.py @@ -185,6 +185,7 @@ async def _resolve_model_defaults(app, model_id: str) -> dict: feature_checks = { 'web_search': await Config.get('web.search.enable'), 'image_generation': await Config.get('image_generation.enable'), + 'video_generation': await Config.get('video_generation.enable'), } for feature_id in default_feature_ids: diff --git a/backend/open_webui/utils/images/connections.py b/backend/open_webui/utils/images/connections.py index ebaf509d7d..9429cb7f40 100644 --- a/backend/open_webui/utils/images/connections.py +++ b/backend/open_webui/utils/images/connections.py @@ -176,7 +176,7 @@ def get_image_connection_capabilities(connection: dict) -> dict[str, bool]: async def get_openai_connection_models(request: Request, connection: dict, user: UserModel | None = None) -> list[dict]: """The models an OpenAI compatible connection serves. LiteLLM also reports each one's mode and endpoints, - which mark its image models (``image``) and what they can do.""" + which mark its image models (``image``) and what they can do, and its video models (``video``).""" from open_webui.routers.images import raise_for_provider_status headers, cookies = await get_headers_and_cookies( @@ -220,8 +220,10 @@ async def get_openai_connection_models(request: Request, connection: dict, user: 'image_generation': any(endpoint.endswith('/images/generations') for endpoint in endpoints), 'image_edit': any(endpoint.endswith('/images/edits') for endpoint in endpoints), } + model['video'] = any(endpoint.endswith('/videos') for endpoint in endpoints) else: capabilities = {capability: model_info.get('mode') == capability for capability in IMAGE_CAPABILITIES} + model['video'] = model_info.get('mode') == 'video_generation' model['image'] = any(capabilities.values()) if model['image']: model.update(capabilities) @@ -296,19 +298,21 @@ async def get_image_models(request: Request, user: UserModel, *, bypass_access: return models -def get_requested_image_model(metadata: dict | None) -> str | None: - """The image model a chat asked for: the user's pick, else the chat model's default. +def get_requested_model(metadata: dict | None, feature: str, meta_key: str) -> str | None: + """The model a chat asked for: the user's pick, else the chat model's default. - The pick rides on the image feature itself, ``features.image_generation = {'model': ref}``; - plain ``true`` means no pick. + The pick rides on the feature itself, ``features. = {'model': ref}``; plain ``true`` means no pick. """ metadata = metadata or {} - image_generation = (metadata.get('features') or {}).get('image_generation') - if isinstance(image_generation, dict) and isinstance(image_generation.get('model'), str): - if image_generation['model']: - return image_generation['model'] + requested = (metadata.get('features') or {}).get(feature) + if isinstance(requested, dict) and isinstance(requested.get('model'), str) and requested['model']: + return requested['model'] model = metadata.get('model') or {} - return ((model.get('info') or {}).get('meta') or {}).get('imageModelId') or None + return ((model.get('info') or {}).get('meta') or {}).get(meta_key) or None + + +def get_requested_image_model(metadata: dict | None) -> str | None: + return get_requested_model(metadata, 'image_generation', 'imageModelId') async def resolve_image_model( diff --git a/backend/open_webui/utils/middleware.py b/backend/open_webui/utils/middleware.py index 272ce61dfc..4dd95f4eec 100644 --- a/backend/open_webui/utils/middleware.py +++ b/backend/open_webui/utils/middleware.py @@ -60,6 +60,7 @@ from open_webui.routers.images import ( image_edits, image_generations, ) +from open_webui.routers.videos import CreateVideoForm, video_generations from open_webui.routers.pipelines import ( get_sorted_filters, process_pipeline_inlet_filter, @@ -104,6 +105,7 @@ from open_webui.utils.filter import ( process_filter_functions, ) from open_webui.utils.images.connections import get_requested_image_model +from open_webui.utils.videos.connections import get_requested_video_model from open_webui.utils.json_codec import JSONCodec, dumps_bytes from open_webui.utils.mcp.apps import MCPAppResult from open_webui.utils.memory import add_memory_context, recall_memories, review_memory_after_turn @@ -1694,6 +1696,117 @@ async def chat_image_generation_handler(request: Request, form_data: dict, extra return form_data +async def chat_video_generation_handler(request: Request, form_data: dict, extra_params: dict, user): + metadata = extra_params.get('__metadata__', {}) + chat_id = metadata.get('chat_id', None) + __event_emitter__ = extra_params.get('__event_emitter__', None) + + if not chat_id or not isinstance(chat_id, str) or not __event_emitter__: + return form_data + + is_channel_chat = chat_id.startswith('channel:') + video_metadata = { + 'message_id': metadata.get('message_id', None), + **({'channel_id': chat_id.removeprefix('channel:')} if is_channel_chat else {'chat_id': chat_id}), + } + terminal_metadata = {**metadata, 'terminal_id': form_data.get('terminal_id')} + + if not is_saved_chat_id(chat_id): + message_list = form_data.get('messages', []) + else: + chat = await Chats.get_accessible_chat_by_id(chat_id, user, permission='write') + + messages_map = chat.chat.get('history', {}).get('messages', {}) + message_id = metadata.get('user_message_id') or chat.chat.get('history', {}).get('currentId') + message_list = get_message_list(messages_map, message_id) + + prompt = get_last_user_message(message_list) + # An image in the latest messages becomes the video's first frame. + starting_image = next( + iter(image for images in get_images_from_messages(message_list)[:2] for image in images), None + ) + + system_message_content = '' + + if not await Config.get('video_generation.enable'): + await __event_emitter__( + { + 'type': 'status', + 'data': { + 'description': 'Video generation is disabled', + 'done': True, + }, + } + ) + + system_message_content = 'Video generation was requested but the feature is currently disabled by the administrator, so no video was created. Let the user know that video generation is currently unavailable.' + else: + try: + videos = await video_generations( + request=request, + form_data=CreateVideoForm( + prompt=prompt, image=starting_image, model=get_requested_video_model(metadata) + ), + metadata=video_metadata, + user=user, + event_emitter=__event_emitter__, + ) + await upload_files_to_terminal(request, user, videos, terminal_metadata, extra_params) + + await __event_emitter__( + { + 'type': 'status', + 'data': {'description': 'Video created', 'done': True}, + } + ) + + await __event_emitter__( + { + 'type': 'files', + 'data': { + 'files': [ + { + 'type': 'video', + **video, + } + for video in videos + ] + }, + } + ) + + system_message_content = ( + 'The generated videos are shown in chat. Use terminal_path with terminal tools or ' + f'display_file when available. Videos: {JSONCodec.dumps(videos)}' + ) + except Exception as e: + log.debug(e) + + error_message = '' + if isinstance(e, HTTPException): + if e.detail and isinstance(e.detail, dict): + error_message = e.detail.get('message', str(e.detail)) + else: + error_message = str(e.detail) + + await __event_emitter__( + { + 'type': 'status', + 'data': { + 'description': 'An error occurred while generating a video', + 'done': True, + }, + } + ) + + system_message_content = f'Video generation was attempted but failed because of an error. The system is currently unable to generate the video. Tell the user that the following error occurred: {error_message}' + + if system_message_content: + form_data['messages'] = add_or_update_system_message(system_message_content, form_data['messages']) + + return form_data + + async def chat_completion_files_handler( request: Request, body: dict, extra_params: dict, user: UserModel ) -> tuple[dict, dict[str, list]]: @@ -2424,6 +2537,17 @@ async def process_chat_payload(request, form_data, user, metadata, model): if metadata.get('params', {}).get('function_calling') == 'legacy': form_data = await chat_image_generation_handler(request, form_data, extra_params, user) + if 'video_generation' in features and features['video_generation']: + # features is client-supplied; re-check the permission the direct /videos routes enforce. + if getattr(user, 'role', None) == 'admin' or await has_permission( + getattr(user, 'id', ''), + 'features.video_generation', + await Config.get('user.permissions'), + ): + # Skip forced video generation when native FC is enabled - model can use generate_video tool + if metadata.get('params', {}).get('function_calling') == 'legacy': + form_data = await chat_video_generation_handler(request, form_data, extra_params, user) + if 'code_interpreter' in features and features['code_interpreter']: engine = await Config.get('code_interpreter.engine', 'pyodide') diff --git a/backend/open_webui/utils/tools.py b/backend/open_webui/utils/tools.py index 91cd6f750d..999f77b16a 100644 --- a/backend/open_webui/utils/tools.py +++ b/backend/open_webui/utils/tools.py @@ -62,6 +62,7 @@ from open_webui.tools.builtin import ( execute_code, fetch_url, generate_image, + generate_video, get_current_timestamp, grep_chat_files, grep_knowledge_files, @@ -689,6 +690,7 @@ async def get_builtin_tools( 'web.search.enable', 'image_generation.enable', 'images.edit.enable', + 'video_generation.enable', 'code_interpreter.enable', 'notes.enable', 'channels.enable', @@ -888,6 +890,17 @@ async def get_builtin_tools( ): builtin_functions.append(edit_image) + # Add video generation tool if builtin category enabled, + # globally enabled, and allowed by model capability. + if ( + is_builtin_tool_enabled('video_generation') + and config.get('video_generation.enable') + and get_model_capability('video_generation') + and features.get('video_generation') + and await has_user_permission('video_generation') + ): + builtin_functions.append(generate_video) + # Add code interpreter tool if builtin category enabled, # globally enabled, and allowed by model capability. if ( diff --git a/backend/open_webui/utils/videos/connections.py b/backend/open_webui/utils/videos/connections.py new file mode 100644 index 0000000000..ac90b564ba --- /dev/null +++ b/backend/open_webui/utils/videos/connections.py @@ -0,0 +1,189 @@ +"""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 or +OpenAI, 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. +""" + +from __future__ import annotations + +import logging +import uuid +from typing import Any + +from aiocache import cached +from fastapi import HTTPException, Request +from open_webui.constants import ERROR_MESSAGES +from open_webui.env import MODELS_CACHE_TTL +from open_webui.models.config import Config +from open_webui.models.groups import Groups +from open_webui.models.users import UserModel +from open_webui.utils.access_control import has_connection_access +from open_webui.utils.images.connections import ( + IMAGE_CONNECTION_AUTH_TYPES, + _json_object, + _size, + get_image_model_ref, + get_openai_connection_models, + get_requested_model, +) + +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_AUTH_TYPES = IMAGE_CONNECTION_AUTH_TYPES + + +def normalize_video_connection(connection: dict[str, Any]) -> dict[str, Any]: + """Validate a video connection and fill in defaults. Raises ValueError on invalid input.""" + connection_type = str(connection.get('type') or 'openai') + if connection_type not in VIDEO_CONNECTION_TYPES: + raise ValueError(f'Unsupported video connection type: {connection_type}') + + connection_id = str(connection.get('id') or uuid.uuid4()) + if ':' in connection_id: + raise ValueError('Video connection IDs cannot contain ":"') + + config = connection.get('config') or {} + + model_ids = [] + for model_id in config.get('model_ids') or []: + model_id = str(model_id).strip() + if model_id and model_id not in model_ids: + model_ids.append(model_id) + + 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}') + + seconds = config.get('seconds') + if seconds not in (None, ''): + seconds = int(seconds) + if seconds <= 0: + raise ValueError('Video length must be a positive number of seconds (e.g. 8)') + else: + seconds = None + + return { + 'id': connection_id, + 'name': str(connection.get('name') or '').strip() or connection_type, + 'type': connection_type, + 'url': str(connection.get('url') or '').strip().rstrip('/'), + 'key': str(connection.get('key') or ''), + 'config': { + 'enable': bool(config.get('enable', True)), + 'model_ids': model_ids, + 'access_grants': list(config.get('access_grants') or []), + 'auth_type': auth_type, + 'headers': _json_object(config.get('headers'), 'headers'), + 'size': _size(config.get('size')), + 'seconds': seconds, + 'api_version': str(config.get('api_version') or ''), + 'params': _json_object(config.get('params'), 'additional parameters'), + }, + } + + +@cached( + ttl=MODELS_CACHE_TTL, + key_builder=lambda _func, request, connection, user=None: ( + f'video_connection_models_{connection["id"]}_{user.id}' + if user + else f'video_connection_models_{connection["id"]}' + ), +) +async def get_synced_video_models(request: Request, connection: dict, user: UserModel | None = None) -> list[dict]: + """The video models a connection with no model IDs offers, listed live so new ones appear on their own. + Servers that do not label video models (plain OpenAI) offer their default model.""" + try: + models = await get_openai_connection_models(request, connection, user) + except Exception as e: + log.warning('Could not list video models from %s: %s', connection.get('url'), e) + return [] + + if not any('video' in model for model in models): + return [{'id': ''}] + return [model for model in models if model['video']] + + +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. + """ + 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)} + + models = [] + for connection in connections: + config = connection.get('config') or {} + if not config.get('enable', True): + continue + if not bypass_access and not await has_connection_access(user, connection, user_group_ids): + continue + + if config.get('model_ids'): + entries = [{'id': model_id} for model_id in config['model_ids']] + else: + entries = await get_synced_video_models(request, connection, user) + + for entry in entries: + model_id = entry['id'] + models.append( + { + 'id': get_image_model_ref(connection['id'], model_id), + 'name': model_id or connection.get('name') or connection['id'], + 'model': model_id, + 'connection_id': connection['id'], + 'connection_name': connection.get('name') or connection['id'], + 'connection': connection, + } + ) + return models + + +def get_requested_video_model(metadata: dict | None) -> str | None: + return get_requested_model(metadata, 'video_generation', 'videoModelId') + + +async def resolve_video_model( + request: Request, + user: UserModel, + model: str | None = None, + *, + strict: bool = False, +) -> tuple[dict, str]: + """Pick the connection and model to run a request on. + + Order: the requested model (a reference or a bare model id), then the admin's default, then the + first model the user can use. A requested model the user cannot use falls back to the default + unless ``strict`` is set, as on the direct API route. + """ + models = await get_video_models(request, user) + + def find(value: str | None) -> dict | None: + if not value: + return None + return next((m for m in models if m['id'] == value), None) or next( + (m for m in models if m['model'] == value), None + ) + + if model: + requested = find(model) + if requested: + return requested['connection'], requested['model'] + if strict: + raise HTTPException(status_code=400, detail=f'Video model "{model}" was not found') + log.debug('Video model %s is not available to %s; using the default', model, user.id) + + default = find(await Config.get(VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY)) + if default: + return default['connection'], default['model'] + + if models: + return models[0]['connection'], models[0]['model'] + + raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT('No video model is available')) diff --git a/src/lib/apis/videos/index.ts b/src/lib/apis/videos/index.ts new file mode 100644 index 0000000000..6707f79cd2 --- /dev/null +++ b/src/lib/apis/videos/index.ts @@ -0,0 +1,165 @@ +import { VIDEOS_API_BASE_URL } from '$lib/constants'; + +export const getConfig = async (token: string = '') => { + let error = null; + + const res = await fetch(`${VIDEOS_API_BASE_URL}/config`, { + method: 'GET', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + } + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .catch((err) => { + console.error(err); + if ('detail' in err) { + error = err.detail; + } else { + error = 'Server connection failed'; + } + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + +export const updateConfig = async (token: string = '', config: object) => { + let error = null; + + const res = await fetch(`${VIDEOS_API_BASE_URL}/config/update`, { + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + }, + body: JSON.stringify({ + ...config + }) + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .catch((err) => { + console.error(err); + if ('detail' in err) { + error = err.detail; + } else { + error = 'Server connection failed'; + } + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + +export const verifyVideoConnection = async (token: string = '', connection: object) => { + let error = null; + + const res = await fetch(`${VIDEOS_API_BASE_URL}/connections/verify`, { + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + }, + body: JSON.stringify(connection) + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .catch((err) => { + console.error(err); + if ('detail' in err) { + error = err.detail; + } else { + error = 'Server connection failed'; + } + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + +export const getVideoConnectionModels = async (token: string = '') => { + let error = null; + + const res = await fetch(`${VIDEOS_API_BASE_URL}/connections/models`, { + method: 'GET', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + } + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .catch((err) => { + console.error(err); + if ('detail' in err) { + error = err.detail; + } else { + error = 'Server connection failed'; + } + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + +export const getVideoModels = async (token: string = '') => { + let error = null; + + const res = await fetch(`${VIDEOS_API_BASE_URL}/models`, { + method: 'GET', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + } + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .catch((err) => { + console.error(err); + if ('detail' in err) { + error = err.detail; + } else { + error = 'Server connection failed'; + } + return null; + }); + + if (error) { + throw error; + } + + return res; +}; diff --git a/src/lib/components/admin/Settings/AdminTabIcon.svelte b/src/lib/components/admin/Settings/AdminTabIcon.svelte index da0fbdcff3..f40a25f14d 100644 --- a/src/lib/components/admin/Settings/AdminTabIcon.svelte +++ b/src/lib/components/admin/Settings/AdminTabIcon.svelte @@ -9,6 +9,7 @@ import Link from '$lib/components/icons/Link.svelte'; import Lock from '$lib/components/icons/Lock.svelte'; import Photo from '$lib/components/icons/Photo.svelte'; + import VideoCamera from '$lib/components/icons/VideoCamera.svelte'; import QueueList from '$lib/components/icons/QueueList.svelte'; import SettingsAlt from '$lib/components/icons/SettingsAlt.svelte'; import SoundHigh from '$lib/components/icons/SoundHigh.svelte'; @@ -86,6 +87,8 @@ {:else if id === 'images'} +{:else if id === 'videos'} + {:else if id === 'pipelines'} {:else if id === 'db'} diff --git a/src/lib/components/admin/Settings/Videos.svelte b/src/lib/components/admin/Settings/Videos.svelte new file mode 100644 index 0000000000..1a7eb928fe --- /dev/null +++ b/src/lib/components/admin/Settings/Videos.svelte @@ -0,0 +1,206 @@ + + + { + await saveConnections([...(config?.VIDEO_CONNECTIONS ?? []), connection]); + }} +/> + +
+

+ {$i18n.t('settings.admin.videos.title')} +

+ +
+ {#if config} +
+ + + + + + {#if config.ENABLE_VIDEO_GENERATION} +
+
+
+ {$i18n.t('settings.admin.videos.manageVideoConnections.label')} +
+ + + + +
+ +
+ {#each config.VIDEO_CONNECTIONS as connection, idx (connection.id)} + { + saveConnections( + (config?.VIDEO_CONNECTIONS ?? []).map((c, i) => (i === idx ? updated : c)) + ); + }} + onDelete={() => { + saveConnections( + (config?.VIDEO_CONNECTIONS ?? []).filter((_, i) => i !== idx) + ); + }} + /> + {/each} +
+
+ {/if} +
+ + {#if config.ENABLE_VIDEO_GENERATION} + + + + + {#each modelOptions as option (option.value)} + + {/each} + + + + {/if} +
+ {/if} +
+ +
+ +
+
diff --git a/src/lib/components/admin/Settings/Videos/VideoConnection.svelte b/src/lib/components/admin/Settings/Videos/VideoConnection.svelte new file mode 100644 index 0000000000..4989aeb68d --- /dev/null +++ b/src/lib/components/admin/Settings/Videos/VideoConnection.svelte @@ -0,0 +1,88 @@ + + + { + onDelete(); + showConfigModal = false; + }} + onSubmit={(c: any) => { + connection = c; + onSubmit(c); + }} +/> + +
+ +
+
+ + + +
+
+
+ +
+ + + + + + { + connection = { + ...connection, + config: { ...(connection?.config ?? {}), enable: !(connection?.config?.enable ?? true) } + }; + onSubmit(connection); + }} + /> + +
+
diff --git a/src/lib/components/admin/Settings/Videos/VideoConnectionModal.svelte b/src/lib/components/admin/Settings/Videos/VideoConnectionModal.svelte new file mode 100644 index 0000000000..33c9a5c700 --- /dev/null +++ b/src/lib/components/admin/Settings/Videos/VideoConnectionModal.svelte @@ -0,0 +1,619 @@ + + + +
+
+

+ {#if edit} + {$i18n.t('Edit Connection')} + {:else} + {$i18n.t('Add Connection')} + {/if} +

+ +
+ +
+
+
{ + e.preventDefault(); + submitHandler(); + }} + > +
+
+
+ + +
+ +
+
+
+ +
+
+ + +
+ + + + +
+
+ + + + + +
+ + + + +
+
+ +
+
+ + +
+
+ +
+ +
+ {#if auth_type === 'bearer'} + + {:else if auth_type === 'none'} +
+ {$i18n.t('No authentication')} +
+ {:else if auth_type === 'session'} +
+ {$i18n.t('Forwards system user session credentials to authenticate')} +
+ {:else if auth_type === 'system_oauth'} +
+ {$i18n.t('Forwards system user OAuth access token to authenticate')} +
+ {:else if auth_type === 'microsoft_entra_id'} +
+ {$i18n.t('Uses DefaultAzureCredential to authenticate')} +
+ {/if} +
+
+
+
+ +
+
+
+ {$i18n.t('Model IDs')} +
+
+ + {#if modelIds.length > 0} +
    + {#each modelIds as modelId, modelIdx} +
  • +
    + {modelId} +
    +
    + +
    +
  • + {/each} +
+ {: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 (event.key === 'Enter') { + event.preventDefault(); + addModelHandler(); + } + }} + /> + {#if availableModelIds.length} + + {#each availableModelIds.filter((id) => !modelIds.includes(id)) as id} + + {/each} + + {/if} + +
+ +
+
+ +
+ + + { + showAccessControlModal = true; + }} + label={$i18n.t('Access Control')} + /> +
+ + {#if showAdvanced} +
+
+ + +
+ +
+ + +
+
+ +
+
+ + +
+
+ +
+
+ + +
+ +