diff --git a/backend/open_webui/routers/images.py b/backend/open_webui/routers/images.py index 7f4fb3f651..538bf0dd77 100644 --- a/backend/open_webui/routers/images.py +++ b/backend/open_webui/routers/images.py @@ -155,6 +155,21 @@ def normalize_openai_edit_image_data_url(data_url: str) -> str: return data_url +def get_image_data_url(data: bytes) -> str: + """Validate image bytes and encode them with their detected MIME type.""" + with Image.open(io.BytesIO(data)) as image: + if image.format not in {'PNG', 'JPEG', 'MPO', 'WEBP', 'GIF'}: + raise ValueError('Image must be PNG, JPEG, WebP, or GIF.') + if image.width * image.height > 25_000_000: + raise ValueError('Image must be at most 25 megapixels.') + mime_type = Image.MIME[image.format] + image.verify() + # verify() does not decode pixels for every format. + with Image.open(io.BytesIO(data)) as image: + image.load() + return f'data:{mime_type};base64,{base64.b64encode(data).decode("utf-8")}' + + def get_image_file_item(base64_string, param_name='image'): header, encoded = base64_string.split(',', 1) mime_type = header.split(';')[0].lstrip('data:') or 'image/png' diff --git a/backend/open_webui/tools/builtin.py b/backend/open_webui/tools/builtin.py index b9b7f4794e..63917ee8c5 100644 --- a/backend/open_webui/tools/builtin.py +++ b/backend/open_webui/tools/builtin.py @@ -33,6 +33,7 @@ from open_webui.retrieval.vector.async_client import ASYNC_VECTOR_DB_CLIENT from open_webui.routers.images import ( CreateImageForm, EditImageForm, + get_image_data_url, image_edits, image_generations, ) @@ -69,7 +70,7 @@ from open_webui.utils.json_codec import JSONCodec from open_webui.utils.notifications import notify_target from open_webui.utils.sanitize import sanitize_code from open_webui.utils.skill_files import SkillFile, SkillFileOperation, skill_content_page, skill_overview -from open_webui.utils.terminals import upload_files_to_terminal +from open_webui.utils.terminals import get_terminal_file, upload_files_to_terminal log = logging.getLogger(__name__) @@ -461,7 +462,7 @@ async def edit_image( Supports targeted edits such as adding, removing, replacing, inpainting, extending, or compositing image content. :param prompt: A description of the transformation to apply to the provided images - :param image_urls: Source image URLs to modify or use as composition inputs + :param image_urls: Source image URLs or absolute file paths to modify or use as composition inputs :param size: Optional output size in WIDTHxHEIGHT pixels (e.g. "1536x1024"), supported by the configured image model. Omit to use the configured default. :return: Image URLs and, when a terminal is selected, terminal_path for display_file or further processing. @@ -472,9 +473,15 @@ async def edit_image( try: user = UserModel(**__user__) if __user__ else None + resolved_images = [] + for url in image_urls: + if url.startswith('/') and not url.startswith('/api/v1/files/'): + data = await get_terminal_file(__request__, user, __metadata__ or {}, url, max_bytes=50 * 1024 * 1024) + url = await asyncio.to_thread(get_image_data_url, data) + resolved_images.append(url) images = await image_edits( request=__request__, - form_data=EditImageForm(prompt=prompt, image=image_urls, size=size), + form_data=EditImageForm(prompt=prompt, image=resolved_images, size=size), metadata=( {'channel_id': __chat_id__.removeprefix('channel:'), 'message_id': __message_id__} if isinstance(__chat_id__, str) and __chat_id__.startswith('channel:') diff --git a/backend/open_webui/utils/terminals.py b/backend/open_webui/utils/terminals.py index 0ac9a5dee3..dd212431bc 100644 --- a/backend/open_webui/utils/terminals.py +++ b/backend/open_webui/utils/terminals.py @@ -387,6 +387,40 @@ async def upload_files_to_terminal(request, user, files: list[dict], metadata: d entry['terminal_error'] = 'File saved in Open WebUI, but the selected terminal is unavailable.' +async def get_terminal_file(request, user, metadata: dict, path: str, *, max_bytes: int) -> bytes: + """Read a bounded file through the authorized terminal connection.""" + import aiohttp + from open_webui.env import AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL + from open_webui.utils.tether import get_terminal_client + + resolved = await resolve_terminal_connection(request, user, metadata) + if not resolved: + raise ValueError('Reading files requires a terminal connection reachable by Open WebUI.') + connection, headers, cookies = resolved + base_url = get_terminal_server_url(connection) + async with get_terminal_client( + base_url, + user.id if hasattr(user, 'id') else user['id'], + timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_TERMINAL), + trust_env=True, + ) as session: + async with session.get( + f'{base_url}/files/view?path={quote(path, safe="")}', + headers=headers, + cookies=cookies, + ssl=AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL, + allow_redirects=False, + ) as response: + if response.status != 200: + raise ValueError(f'Could not read {path} from the terminal.') + data = bytearray() + async for chunk in response.content.iter_chunked(64 * 1024): + if len(data) + len(chunk) > max_bytes: + raise ValueError(f'File exceeds the {max_bytes}-byte limit.') + data.extend(chunk) + return bytes(data) + + async def get_terminal_agents_md(request, user, metadata: dict, extra_params: dict | None = None) -> str | None: """Load the selected terminal user's home AGENTS.md afresh for this turn.""" try: