ShareGPT_Dialogue_Studio / src /utils /imageExport.ts
zelk12's picture
Upload 63 files
536e72d verified
Raw History Blame Contribute Delete
4.81 kB
import JSZip from 'jszip';
import { MessageImageAttachment, ShareGPTConversation } from '../types';
import {
getImageBlobRecord,
getImageRelativePath,
renderResizedImageBlob,
sanitizeSubfolderPath,
} from './imageStorage';
export interface ZipImageExportSummary {
totalAttachments: number;
uploadedWritten: number;
placeholderCount: number;
missingBlobCount: number;
}
interface ExpectedImageNoteEntry {
relativePath: string;
dialogueTitle: string;
note?: string;
reason: 'placeholder' | 'missing_blob';
}
/**
* Populates `images/` (and user-defined subfolders) inside a JSZip archive:
* - Uploaded images are decoded and resized via Canvas according to their settings.
* - Placeholder images ensure their target folders exist and are listed in `images/EXPECTED_IMAGES.txt`.
*/
export async function appendImagesToZip(
zip: JSZip,
conversations: ShareGPTConversation[]
): Promise<ZipImageExportSummary> {
const allItems: Array<{
att: MessageImageAttachment;
dialogueTitle: string;
}> = [];
conversations.forEach((conv) => {
const dialogueTitle = conv.metadata?.title || conv.id;
conv.conversations.forEach((turn) => {
turn.images?.forEach((att) => {
allItems.push({ att, dialogueTitle });
});
});
});
if (allItems.length === 0) {
return {
totalAttachments: 0,
uploadedWritten: 0,
placeholderCount: 0,
missingBlobCount: 0,
};
}
zip.folder('images');
const writtenPaths = new Set<string>();
const expectedEntries: ExpectedImageNoteEntry[] = [];
let uploadedWritten = 0;
let placeholderCount = 0;
let missingBlobCount = 0;
const seenExpectedPaths = new Set<string>();
for (const { att, dialogueTitle } of allItems) {
const relativePath = getImageRelativePath(att);
const sub = sanitizeSubfolderPath(att.subfolder || '');
if (sub) {
zip.folder(`images/${sub}`);
}
if (att.kind === 'uploaded' && att.blobId) {
if (writtenPaths.has(relativePath)) {
continue;
}
const record = await getImageBlobRecord(att.blobId);
if (record) {
const rendered = await renderResizedImageBlob(record.originalBlob, att);
zip.file(relativePath, rendered.blob);
writtenPaths.add(relativePath);
uploadedWritten += 1;
} else {
missingBlobCount += 1;
if (!seenExpectedPaths.has(relativePath)) {
seenExpectedPaths.add(relativePath);
expectedEntries.push({
relativePath,
dialogueTitle,
note: att.note,
reason: 'missing_blob',
});
}
}
} else {
placeholderCount += 1;
if (!seenExpectedPaths.has(relativePath)) {
seenExpectedPaths.add(relativePath);
expectedEntries.push({
relativePath,
dialogueTitle,
note: att.note,
reason: 'placeholder',
});
}
}
}
if (expectedEntries.length > 0) {
const lines: string[] = [
'=== Ожидаемые файлы изображений (ShareGPT / LLaMA-Factory) ===',
'Положите недостающие изображения по указанным ниже путям внутри папки датасета.',
'Пути указаны точно так же, как они записаны в поле "images" JSON/JSONL-файла.',
'',
];
expectedEntries.forEach((entry, idx) => {
const statusLabel =
entry.reason === 'missing_blob'
? '[Файл не найден в локальном хранилище браузера]'
: '[Заглушка по имени файла]';
lines.push(`${idx + 1}. ${entry.relativePath} ${statusLabel}`);
lines.push(` Диалог: ${entry.dialogueTitle}`);
if (entry.note && entry.note.trim()) {
lines.push(` Заметка автора: ${entry.note.trim()}`);
}
lines.push('');
});
zip.file('images/EXPECTED_IMAGES.txt', lines.join('\n'));
}
return {
totalAttachments: allItems.length,
uploadedWritten,
placeholderCount,
missingBlobCount,
};
}
/**
* Bundles a standard JSON/JSONL dataset file together with the `images/` folder into a single ZIP archive.
*/
export async function createDatasetFilesZipPackage(
datasetContent: string,
datasetFileName: string,
conversations: ShareGPTConversation[]
): Promise<{ blob: Blob; imageSummary: ZipImageExportSummary }> {
const zip = new JSZip();
const safeName = (datasetFileName || 'dataset.json').replace(/^\/+/, '');
zip.file(safeName, datasetContent);
const imageSummary = await appendImagesToZip(zip, conversations);
const blob = await zip.generateAsync({ type: 'blob' });
return { blob, imageSummary };
}