Files
puter/src/backend/drivers/ai/interfaces/image/imageOutput.ts
T

53 lines
1.9 KiB
TypeScript

/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { SVG_SNIFF_WINDOW, sniffImageMime } from '../../../../util/appIcon.js';
// Base64 chars needed to recover SVG_SNIFF_WINDOW decoded bytes.
const SNIFF_BASE64_CHARS = Math.ceil((SVG_SNIFF_WINDOW * 4) / 3);
/** The URL of an OpenAI-style image entry, or its base64 as a data URI. */
export const imageEntryUrl = (
entry: unknown,
fallbackMime?: string,
): string | undefined => {
const { url, b64_json: base64 } = (entry ?? {}) as {
url?: unknown;
b64_json?: unknown;
};
if (typeof url === 'string' && url) return url;
return typeof base64 === 'string' && base64
? imageDataUri(base64, fallbackMime)
: undefined;
};
/** Label generated bytes with the existing content-based MIME detector. */
export function imageDataUri(
base64: string,
fallbackMime = 'image/png',
): string {
// Sniff enough of the payload to see an SVG root element; fixed-offset
// signatures (PNG/JPEG/GIF/WEBP) appear in the first bytes regardless.
const mime =
sniffImageMime(
Buffer.from(base64.slice(0, SNIFF_BASE64_CHARS), 'base64'),
) ?? fallbackMime;
return `data:${mime};base64,${base64}`;
}