Spaces:
Running
Running
Download src/components/ExportModal.tsx from zelk12/ShareGPT_Dialogue_Studio: direct link, hf CLI and curl.
- Browser
- Download file 81 kB
-
https://huggingface.co/spaces/zelk12/ShareGPT_Dialogue_Studio/resolve/main/src/components/ExportModal.tsx
- Command line
-
hf download hf://spaces/zelk12/ShareGPT_Dialogue_Studio/src/components/ExportModal.tsx
-
curl -L -o ExportModal.tsx https://huggingface.co/spaces/zelk12/ShareGPT_Dialogue_Studio/resolve/main/src/components/ExportModal.tsx
81 kB
import React, { useEffect, useMemo, useState } from 'react';
import {
AlertCircle,
Check,
Copy,
Cpu,
Download,
FileJson,
Image as ImageIcon,
Loader2,
PackageCheck,
Sparkles,
X,
} from 'lucide-react';
import {
Dataset,
DatasetFolder,
DialogueFolder,
ExportSettings,
HistoryThoughtMode,
HistoryThoughtRules,
MessageTag,
RoleMappingPreset,
ShareGPTConversation,
SystemPromptPlacement,
} from '../types';
import { copyTextToClipboard } from '../utils/clipboard';
import {
getDatasetAllDialogueIds,
getExportSelectionSummary,
} from '../utils/dataset';
import {
computeDatasetStats,
createHuggingFaceZipPackage,
generateHfJsonl,
generateHfPythonScript,
generateHfReadme,
HuggingFaceExportOptions,
HuggingFaceFormat,
} from '../utils/huggingface';
import { createDatasetFilesZipPackage } from '../utils/imageExport';
import { getConversationImages, getImageRelativePath } from '../utils/imageStorage';
import { DEFAULT_LAYOUT_SIZES } from '../utils/layout';
import {
createLlamaFactoryZipPackage,
generateDatasetInfoSnippet,
sanitizeDatasetKey,
} from '../utils/llamaFactory';
import { downloadFile, generateExportString } from '../utils/sharegpt';
import {
normalizeHistoryThoughtRules,
transformConversationsWithSource,
} from '../utils/tags';
import { ExportSelectionTree } from './ExportSelectionTree';
import { HistoryThoughtControls } from './HistoryThoughtControls';
import { ResizableSplitter } from './ResizableSplitter';
interface ExportModalProps {
isOpen: boolean;
onClose: () => void;
conversations: ShareGPTConversation[];
activeConversation: ShareGPTConversation;
datasets?: Dataset[];
datasetFolders?: DatasetFolder[];
dialogueFolders?: DialogueFolder[];
messageTags?: MessageTag[];
activeDatasetId?: string | 'all';
settings: ExportSettings;
onSaveSettings: (settings: ExportSettings) => void;
onOpenTemplatePreview?: () => void;
sidebarWidth?: number;
onChangeSidebarWidth?: (width: number) => void;
}
type ExportDestination = 'dataset_file' | 'huggingface' | 'llama_factory';
type HfPreviewTab = 'jsonl' | 'readme' | 'python';
type LlamaPreviewTab = 'dataset_info' | 'jsonl' | 'cli';
function pluralizeDatasets(count: number): string {
const mod10 = count % 10;
const mod100 = count % 100;
if (mod10 === 1 && mod100 !== 11) return 'набора';
return 'наборов';
}
export const ExportModal: React.FC<ExportModalProps> = ({
isOpen,
onClose,
conversations,
activeConversation,
datasets = [],
datasetFolders = [],
dialogueFolders = [],
messageTags = [],
activeDatasetId = 'all',
settings,
onSaveSettings,
onOpenTemplatePreview,
sidebarWidth,
onChangeSidebarWidth,
}) => {
const [destination, setDestination] =
useState<ExportDestination>('dataset_file');
const [localSettings, setLocalSettings] = useState<ExportSettings>({
...settings,
});
// Hierarchical multi-dataset & dialogue selection state (Source of Truth)
const [selectedConversationIds, setSelectedConversationIds] = useState<
Set<string>
>(() => new Set());
// Local sidebar width fallback when parent does not wire persistence
const [internalSidebarWidth, setInternalSidebarWidth] = useState<number>(
sidebarWidth ?? DEFAULT_LAYOUT_SIZES.exportModalSidebarWidth
);
useEffect(() => {
if (typeof sidebarWidth === 'number') {
setInternalSidebarWidth(sidebarWidth);
}
}, [sidebarWidth]);
const effectiveSidebarWidth = sidebarWidth ?? internalSidebarWidth;
const handleSidebarWidthChange = (nextWidth: number) => {
setInternalSidebarWidth(nextWidth);
onChangeSidebarWidth?.(nextWidth);
};
// Destination preview subtabs & copy flags
const [hfPreviewTab, setHfPreviewTab] = useState<HfPreviewTab>('jsonl');
const [llamaPreviewTab, setLlamaPreviewTab] =
useState<LlamaPreviewTab>('dataset_info');
const [copiedPreview, setCopiedPreview] = useState(false);
// Single file export fields
const [customFilename, setCustomFilename] = useState<string>('');
const [isDatasetZipping, setIsDatasetZipping] = useState(false);
const [datasetZipError, setDatasetZipError] = useState<string | null>(null);
// Hugging Face package state
const [hfFormat, setHfFormat] = useState<HuggingFaceFormat>('messages');
const [hfSplitTrainTest, setHfSplitTrainTest] = useState(true);
const [hfTrainRatio, setHfTrainRatio] = useState(0.9);
const [hfLanguage, setHfLanguage] = useState('ru');
const [hfLicense, setHfLicense] = useState('apache-2.0');
const [hfRepoName, setHfRepoName] = useState('');
const [hasManualHfRepo, setHasManualHfRepo] = useState(false);
const [hfZipError, setHfZipError] = useState<string | null>(null);
const [isZipping, setIsZipping] = useState(false);
// LLaMA-Factory state
const [llamaDatasetKey, setLlamaDatasetKey] = useState('');
const [hasManualLlamaKey, setHasManualLlamaKey] = useState(false);
const [llamaCustomFilename, setLlamaCustomFilename] = useState('');
const [includeToolsColumn, setIncludeToolsColumn] = useState(false);
const [includeImagesColumn, setIncludeImagesColumn] = useState(true);
const [isLlamaZipping, setIsLlamaZipping] = useState(false);
const [llamaZipError, setLlamaZipError] = useState<string | null>(null);
const effectiveDatasets = useMemo<Dataset[]>(() => {
if (datasets.length > 0) return datasets;
return [
{
id: 'ds_default',
name: 'Набор по умолчанию',
color: 'amber',
createdAt: 0,
updatedAt: 0,
},
];
}, [datasets]);
const knownDatasetIds = useMemo(
() => new Set(effectiveDatasets.map((d) => d.id)),
[effectiveDatasets]
);
const fallbackDatasetId = effectiveDatasets[0]?.id || 'ds_default';
// Sync localSettings whenever incoming settings prop updates without resetting dialogue selection
useEffect(() => {
if (!isOpen) return;
setLocalSettings({ ...settings });
}, [isOpen, settings]);
// Initialize selection and reset transient modal state only when modal opens or activeDatasetId changes
useEffect(() => {
if (!isOpen) return;
setHfZipError(null);
setLlamaZipError(null);
setDatasetZipError(null);
setHasManualLlamaKey(false);
setHasManualHfRepo(false);
if (activeDatasetId !== 'all') {
const dsIds = getDatasetAllDialogueIds(
conversations,
activeDatasetId,
knownDatasetIds,
fallbackDatasetId
);
setSelectedConversationIds(new Set(dsIds));
} else {
setSelectedConversationIds(new Set(conversations.map((c) => c.id)));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen, activeDatasetId]);
// Prune any deleted conversations if the list changes while open
useEffect(() => {
if (!isOpen) return;
const validIds = new Set(conversations.map((c) => c.id));
setSelectedConversationIds((prev) => {
let changed = false;
const next = new Set<string>();
prev.forEach((id) => {
if (validIds.has(id)) next.add(id);
else changed = true;
});
return changed ? next : prev;
});
}, [isOpen, conversations]);
const selectionSummary = useMemo(
() =>
getExportSelectionSummary(
conversations,
effectiveDatasets,
selectedConversationIds
),
[conversations, effectiveDatasets, selectedConversationIds]
);
const {
selectedConversations,
selectedDatasets,
singleDataset,
isSingleDialogue,
isAllSelected,
} = selectionSummary;
const historyMode: HistoryThoughtMode =
localSettings.historyThoughtMode || 'keep_all';
const historyRules: HistoryThoughtRules = normalizeHistoryThoughtRules(
localSettings.historyThoughtRules
);
const transformedEntries = useMemo(
() =>
transformConversationsWithSource(
selectedConversations,
messageTags,
historyMode,
historyRules
),
[selectedConversations, messageTags, historyMode, historyRules]
);
const effectiveExportConversations = useMemo(
() => transformedEntries.map((entry) => entry.conversation),
[transformedEntries]
);
const effectiveSourceIds = useMemo(
() => transformedEntries.map((entry) => entry.sourceId),
[transformedEntries]
);
// Sync default LLaMA-Factory key & HF repo name unless manually edited
const defaultLlamaKey = useMemo(() => {
if (isSingleDialogue && selectedConversations[0]) {
return sanitizeDatasetKey(
selectedConversations[0].metadata?.title ||
selectedConversations[0].id ||
'dialogue'
);
}
if (singleDataset) {
return sanitizeDatasetKey(singleDataset.name);
}
if (selectedDatasets.length > 1 && !isAllSelected) {
return `merged_${selectedDatasets.length}_datasets_${effectiveExportConversations.length}_dialogues`;
}
return `sharegpt_dataset_${effectiveExportConversations.length}_dialogues`;
}, [
isSingleDialogue,
selectedConversations,
singleDataset,
selectedDatasets.length,
isAllSelected,
effectiveExportConversations.length,
]);
const defaultHfRepo = useMemo(() => {
if (isSingleDialogue && selectedConversations[0]) {
return sanitizeDatasetKey(
selectedConversations[0].metadata?.title || 'dialogue_dataset'
).replace(/_/g, '-');
}
if (singleDataset) {
return sanitizeDatasetKey(singleDataset.name).replace(/_/g, '-');
}
if (selectedDatasets.length > 1 && !isAllSelected) {
return `merged-${selectedDatasets.length}-datasets-${effectiveExportConversations.length}`;
}
return 'sft-conversations';
}, [
isSingleDialogue,
selectedConversations,
singleDataset,
selectedDatasets.length,
isAllSelected,
effectiveExportConversations.length,
]);
useEffect(() => {
if (!hasManualLlamaKey) {
setLlamaDatasetKey(defaultLlamaKey);
}
}, [defaultLlamaKey, hasManualLlamaKey]);
useEffect(() => {
if (!hasManualHfRepo) {
setHfRepoName(defaultHfRepo);
}
}, [defaultHfRepo, hasManualHfRepo]);
if (!isOpen) return null;
const uniqueImageByPath = new Map<
string,
ReturnType<typeof getConversationImages>[number]
>();
effectiveExportConversations.forEach((c) => {
getConversationImages(c).forEach((img) => {
const relPath = getImageRelativePath(img);
if (!uniqueImageByPath.has(relPath)) {
uniqueImageByPath.set(relPath, img);
}
});
});
const scopedAllImages = Array.from(uniqueImageByPath.values());
const totalExportImages = scopedAllImages.length;
const uploadedExportImages = scopedAllImages.filter(
(img) => img.kind === 'uploaded'
).length;
const placeholderExportImages = totalExportImages - uploadedExportImages;
const isSingleObjectOutput =
isSingleDialogue && effectiveExportConversations.length <= 1;
const currentSettings: ExportSettings = {
...localSettings,
format:
localSettings.format === 'jsonl'
? 'jsonl'
: isSingleObjectOutput
? 'single_json'
: 'json',
};
const ext = currentSettings.format === 'jsonl' ? 'jsonl' : 'json';
const defaultFilename = isSingleDialogue
? effectiveExportConversations.length > 1
? `${selectedConversations[0]?.id || 'sharegpt_dialogue'}_steps_${effectiveExportConversations.length}.${ext}`
: `${selectedConversations[0]?.id || 'sharegpt_dialogue'}.${ext}`
: singleDataset
? `${sanitizeDatasetKey(singleDataset.name)}_${effectiveExportConversations.length}_dialogues.${ext}`
: selectedDatasets.length > 1 && !isAllSelected
? `merged_${selectedDatasets.length}_datasets_${effectiveExportConversations.length}_dialogues.${ext}`
: `sharegpt_dataset_${effectiveExportConversations.length}_dialogues.${ext}`;
const effectiveFileName = customFilename.trim() || defaultFilename;
const previewString = generateExportString(
effectiveExportConversations,
currentSettings,
isSingleObjectOutput ? effectiveExportConversations[0]?.id : undefined,
messageTags
);
// Hugging Face options & previews
const fullHfRepoId = hfRepoName || 'username/my-sft-dataset';
const datasetTitleSummary = isSingleDialogue
? selectedConversations[0]?.metadata?.title || 'Single Dialogue Dataset'
: singleDataset
? singleDataset.name
: selectedDatasets.length > 1
? `Merged (${selectedDatasets
.map((d) => d.name)
.slice(0, 3)
.join(' + ')}${
selectedDatasets.length > 3 ? ` +${selectedDatasets.length - 3}` : ''
})`
: 'ShareGPT Dialogue Studio Dataset';
const datasetDescriptionSummary = singleDataset?.description
? singleDataset.description
: selectedDatasets.length > 1
? `Объединённый датасет из ${selectedDatasets.length} наборов (${selectedDatasets
.map((d) => d.name)
.join(', ')}) — ${effectiveExportConversations.length} диалогов для Supervised Fine-Tuning (SFT).`
: `Датасет из ${effectiveExportConversations.length} диалогов для Supervised Fine-Tuning (SFT). Подготовлен в ShareGPT Dialogue Studio.`;
const hfOptions: HuggingFaceExportOptions = {
format: hfFormat,
splitTrainTest:
hfSplitTrainTest && effectiveExportConversations.length > 1,
trainRatio: hfTrainRatio,
repoName: fullHfRepoId,
language: hfLanguage,
license: hfLicense,
sourceIds: effectiveSourceIds,
datasetName: datasetTitleSummary,
datasetDescription: datasetDescriptionSummary,
};
const hfJsonlSamplePreview =
effectiveExportConversations.length > 0
? generateHfJsonl(
effectiveExportConversations.slice(0, 6),
hfFormat,
messageTags
) +
(effectiveExportConversations.length > 6
? `\n... (ещё ${effectiveExportConversations.length - 6} строк в итоговом файле)`
: '')
: '';
const hfReadmePreview = generateHfReadme(
effectiveExportConversations,
hfOptions,
singleDataset,
messageTags
);
const hfPythonScript = generateHfPythonScript(
hfOptions.repoName || 'my-dataset',
hfFormat
);
const stats = computeDatasetStats(effectiveExportConversations, messageTags);
// LLaMA-Factory config & JSONL generation
const llamaDefaultFilename = `${sanitizeDatasetKey(
llamaDatasetKey || 'sharegpt_dataset'
)}.jsonl`;
const trimmedLlamaCustom = llamaCustomFilename.trim();
const llamaEffectiveFileName = trimmedLlamaCustom
? trimmedLlamaCustom.toLowerCase().endsWith('.jsonl') ||
trimmedLlamaCustom.toLowerCase().endsWith('.json')
? trimmedLlamaCustom
: `${trimmedLlamaCustom}.jsonl`
: llamaDefaultFilename;
const llamaJsonlContent = generateExportString(
effectiveExportConversations,
{ ...localSettings, format: 'jsonl', prettyPrint: false },
undefined,
messageTags
);
const llamaJsonlSamplePreview =
effectiveExportConversations.length > 0
? generateExportString(
effectiveExportConversations.slice(0, 6),
{ ...localSettings, format: 'jsonl', prettyPrint: false },
undefined,
messageTags
) +
(effectiveExportConversations.length > 6
? `\n... (ещё ${effectiveExportConversations.length - 6} строк в итоговом файле)`
: '')
: '';
const llamaConfigSnippet = generateDatasetInfoSnippet({
datasetKey: llamaDatasetKey || 'my_sharegpt_dataset',
fileName: llamaEffectiveFileName,
roleMapping: localSettings.roleMapping,
humanRoleName: localSettings.humanRoleName,
gptRoleName: localSettings.gptRoleName,
systemPlacement: localSettings.systemPlacement,
includeTools: includeToolsColumn,
includeImages: totalExportImages > 0 && includeImagesColumn,
});
const llamaCliExample = `# Положите ${llamaEffectiveFileName} и dataset_info.json в одну папку (например ./my_data)
llamafactory-cli train \\
--stage sft \\
--do_train \\
--model_name_or_path meta-llama/Meta-Llama-3-8B-Instruct \\
--dataset ${llamaDatasetKey || 'my_sharegpt_dataset'} \\
--dataset_dir ./my_data \\
--template empty \\
--finetuning_type lora \\
--output_dir saves/LLaMA3-8B/lora/sft \\
--overwrite_output_dir \\
--cutoff_len 2048 \\
--per_device_train_batch_size 2 \\
--gradient_accumulation_steps 4 \\
--learning_rate 1.0e-4 \\
--num_train_epochs 3.0 \\
--bf16 true`;
// Active preview payload & copy handler
const getActivePreviewPayload = (): { text: string; label: string } => {
if (destination === 'dataset_file') {
return { text: previewString, label: 'Скопировать файл' };
}
if (destination === 'huggingface') {
if (hfPreviewTab === 'readme') {
return { text: hfReadmePreview, label: 'Скопировать README.md' };
}
if (hfPreviewTab === 'python') {
return { text: hfPythonScript, label: 'Скопировать Python-код' };
}
const fullHfJsonl = generateHfJsonl(
effectiveExportConversations,
hfFormat,
messageTags
);
return { text: fullHfJsonl, label: 'Скопировать train.jsonl' };
}
if (llamaPreviewTab === 'cli') {
return { text: llamaCliExample, label: 'Скопировать команду' };
}
if (llamaPreviewTab === 'jsonl') {
return { text: llamaJsonlContent, label: 'Скопировать JSONL' };
}
return {
text: llamaConfigSnippet,
label: 'Скопировать dataset_info.json',
};
};
const activePreviewPayload = getActivePreviewPayload();
const handleCopyPreview = () => {
void copyTextToClipboard(activePreviewPayload.text);
setCopiedPreview(true);
setTimeout(() => setCopiedPreview(false), 2000);
};
const handleDownload = () => {
if (selectedConversations.length === 0) return;
downloadFile(
previewString,
effectiveFileName,
currentSettings.format === 'jsonl'
? 'application/x-jsonlines'
: 'application/json'
);
onSaveSettings(localSettings);
};
const handleDownloadWithImagesZip = async () => {
if (selectedConversations.length === 0) return;
try {
setIsDatasetZipping(true);
setDatasetZipError(null);
const { blob } = await createDatasetFilesZipPackage(
previewString,
effectiveFileName,
effectiveExportConversations
);
const baseStem = effectiveFileName.replace(/\.(json|jsonl)$/i, '');
const zipName = `${baseStem || 'sharegpt_dataset'}_with_images.zip`;
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = zipName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
onSaveSettings(localSettings);
} catch (err: any) {
console.error('Dataset ZIP generation error:', err);
setDatasetZipError(
`Ошибка создания ZIP-архива: ${err.message || 'неизвестная ошибка'}`
);
} finally {
setIsDatasetZipping(false);
}
};
const handleDownloadHfZip = async () => {
if (selectedConversations.length === 0) return;
try {
setIsZipping(true);
setHfZipError(null);
const zipBlob = await createHuggingFaceZipPackage(
effectiveExportConversations,
hfOptions,
singleDataset,
messageTags
);
const zipName = `${sanitizeDatasetKey(
hfRepoName || 'huggingface_dataset'
)}_repo_package.zip`;
const url = URL.createObjectURL(zipBlob);
const link = document.createElement('a');
link.href = url;
link.download = zipName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
onSaveSettings(localSettings);
} catch (err: any) {
console.error('ZIP generation error:', err);
setHfZipError(
`Ошибка создания архива: ${err.message || 'неизвестная ошибка'}`
);
} finally {
setIsZipping(false);
}
};
const handleDownloadHfTrainJsonl = () => {
if (selectedConversations.length === 0) return;
const jsonl = generateHfJsonl(
effectiveExportConversations,
hfFormat,
messageTags
);
downloadFile(jsonl, 'train.jsonl', 'application/x-jsonlines');
onSaveSettings(localSettings);
};
const handleDownloadHfReadme = () => {
downloadFile(hfReadmePreview, 'README.md', 'text/markdown');
};
const handleDownloadLlamaZip = async () => {
if (selectedConversations.length === 0) return;
try {
setIsLlamaZipping(true);
setLlamaZipError(null);
const zipBlob = await createLlamaFactoryZipPackage(
llamaJsonlContent,
llamaEffectiveFileName,
llamaConfigSnippet,
effectiveExportConversations
);
const zipName = `${sanitizeDatasetKey(
llamaDatasetKey || 'llamafactory_dataset'
)}_llamafactory.zip`;
const url = URL.createObjectURL(zipBlob);
const link = document.createElement('a');
link.href = url;
link.download = zipName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
onSaveSettings(localSettings);
} catch (err: any) {
console.error('LLaMA-Factory ZIP generation error:', err);
setLlamaZipError(
`Ошибка создания ZIP-архива: ${err.message || 'неизвестная ошибка'}`
);
} finally {
setIsLlamaZipping(false);
}
};
const handleDownloadLlamaJsonl = () => {
if (selectedConversations.length === 0) return;
downloadFile(
llamaJsonlContent,
llamaEffectiveFileName,
'application/x-jsonlines'
);
onSaveSettings(localSettings);
};
const handleDownloadLlamaDatasetInfo = () => {
downloadFile(llamaConfigSnippet, 'dataset_info.json', 'application/json');
};
const noSelection = selectedConversations.length === 0;
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-stone-950/60 backdrop-blur-xs p-2 sm:p-4"
onClick={onClose}
>
<div
id="export-dialog-modal"
onClick={(e) => e.stopPropagation()}
style={
{
'--export-sidebar-w': `${effectiveSidebarWidth}px`,
} as React.CSSProperties
}
className="relative w-full max-w-6xl h-[92dvh] max-h-[880px] rounded-2xl bg-white dark:bg-stone-900 shadow-2xl border border-stone-200 dark:border-stone-800 overflow-hidden flex flex-col"
>
{/* Header */}
<div className="flex items-center justify-between px-4 sm:px-6 py-3.5 border-b border-stone-200 dark:border-stone-800 bg-stone-50 dark:bg-stone-950 shrink-0 gap-3">
<div className="flex items-center gap-3 min-w-0">
<div className="p-2 rounded-xl bg-amber-500/15 border border-amber-500/30 text-amber-700 dark:text-amber-400 shrink-0">
<Download className="w-4 h-4" />
</div>
<div className="min-w-0">
<h3 className="text-sm sm:text-base font-bold text-stone-900 dark:text-stone-100 truncate">
Экспорт датасета
</h3>
<p className="text-xs text-stone-500 dark:text-stone-400 truncate font-mono tabular-nums">
Выбрано: {selectedConversations.length} диалогов (из{' '}
{selectedDatasets.length}{' '}
{pluralizeDatasets(selectedDatasets.length)}) · На экспорт:{' '}
{effectiveExportConversations.length} · ~
{stats.estimatedTokens.toLocaleString()} ток.
{totalExportImages > 0 ? ` · ${totalExportImages} фото` : ''}
</p>
</div>
</div>
<button
id="close-export-modal-btn"
type="button"
onClick={onClose}
className="p-1.5 rounded-lg text-stone-400 hover:text-stone-700 dark:hover:text-stone-200 hover:bg-stone-200/60 dark:hover:bg-stone-800 transition-colors shrink-0"
title="Закрыть"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Two-column Pipeline Body */}
<div className="flex-1 min-h-0 flex flex-col md:flex-row overflow-y-auto md:overflow-hidden">
{/* LEFT COLUMN: 1. What to Export */}
<aside className="w-full md:w-[var(--export-sidebar-w)] md:shrink-0 bg-stone-50/70 dark:bg-stone-950/60 flex flex-col md:min-h-0">
<ExportSelectionTree
datasets={effectiveDatasets}
datasetFolders={datasetFolders}
dialogueFolders={dialogueFolders}
conversations={conversations}
activeConversation={activeConversation}
activeDatasetId={activeDatasetId}
selectedIds={selectedConversationIds}
onChangeSelectedIds={setSelectedConversationIds}
/>
</aside>
{/* Resizable Vertical Splitter (Desktop) / Hairline Divider (Mobile) */}
<ResizableSplitter
orientation="vertical"
value={effectiveSidebarWidth}
min={260}
max={560}
defaultValue={DEFAULT_LAYOUT_SIZES.exportModalSidebarWidth}
onChange={handleSidebarWidthChange}
className="hidden md:flex"
ariaLabel="Изменить ширину панели выбора наборов"
/>
<div className="h-px bg-stone-200 dark:bg-stone-800 md:hidden shrink-0" />
{/* RIGHT COLUMN: 2. Pipeline, Format, Settings & Preview */}
<main className="flex-1 min-w-0 md:overflow-y-auto p-4 sm:p-5 space-y-5 bg-white dark:bg-stone-900">
{noSelection && (
<div className="p-3 rounded-xl bg-rose-50/80 dark:bg-rose-950/35 border border-rose-200 dark:border-rose-800/70 text-xs text-rose-800 dark:text-rose-200 flex items-center gap-2">
<AlertCircle className="w-4 h-4 text-rose-600 dark:text-rose-400 shrink-0" />
<span>
Выберите хотя бы один набор, папку или диалог слева, чтобы
сформировать экспорт.
</span>
</div>
)}
{/* Step 2.1: History Thought Mode & Unrolling */}
<HistoryThoughtControls
mode={historyMode}
rules={historyRules}
messageTags={messageTags}
sourceCount={selectedConversations.length}
outputCount={effectiveExportConversations.length}
outputTokens={stats.estimatedTokens}
onChangeMode={(nextMode) => {
const nextSettings: ExportSettings = {
...localSettings,
historyThoughtMode: nextMode,
historyThoughtRules: historyRules,
};
setLocalSettings(nextSettings);
onSaveSettings(nextSettings);
}}
onChangeRules={(nextRules) => {
const nextSettings: ExportSettings = {
...localSettings,
historyThoughtMode: historyMode,
historyThoughtRules: nextRules,
};
setLocalSettings(nextSettings);
onSaveSettings(nextSettings);
}}
/>
{/* Step 2.2: Destination Target Selection */}
<section className="space-y-2.5">
<div className="flex items-center justify-between gap-2">
<label className="text-xs font-bold uppercase tracking-wider text-stone-700 dark:text-stone-200">
2. Куда и в каком формате выгружаем
</label>
<span className="text-[11px] text-stone-500 dark:text-stone-400">
единый поток для выбранных диалогов
</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5 text-xs">
<button
id="tab-dataset-file-btn"
type="button"
onClick={() => setDestination('dataset_file')}
className={`p-3 rounded-xl border text-left transition-all flex flex-col justify-between gap-1.5 ${
destination === 'dataset_file'
? 'border-amber-500 bg-amber-50/50 dark:bg-amber-950/30 ring-2 ring-amber-500/20 text-stone-900 dark:text-stone-100'
: 'border-stone-200 dark:border-stone-800 bg-stone-50/60 dark:bg-stone-950/40 hover:border-stone-300 dark:hover:border-stone-700 text-stone-700 dark:text-stone-300'
}`}
>
<div className="flex items-center gap-2 font-bold">
<FileJson className="w-4 h-4 text-amber-600 dark:text-amber-400 shrink-0" />
<span>Один файл (.json / .jsonl)</span>
</div>
<div className="text-[11px] text-stone-500 dark:text-stone-400 leading-snug">
Объединённый ShareGPT JSON или JSONL (опц. ZIP с images/)
</div>
</button>
<button
id="tab-huggingface-btn"
type="button"
onClick={() => setDestination('huggingface')}
className={`p-3 rounded-xl border text-left transition-all flex flex-col justify-between gap-1.5 ${
destination === 'huggingface'
? 'border-amber-500 bg-amber-50/50 dark:bg-amber-950/30 ring-2 ring-amber-500/20 text-stone-900 dark:text-stone-100'
: 'border-stone-200 dark:border-stone-800 bg-stone-50/60 dark:bg-stone-950/40 hover:border-stone-300 dark:hover:border-stone-700 text-stone-700 dark:text-stone-300'
}`}
>
<div className="flex items-center gap-2 font-bold">
<PackageCheck className="w-4 h-4 text-amber-600 dark:text-amber-400 shrink-0" />
<span>Пакет Hugging Face (.zip)</span>
</div>
<div className="text-[11px] text-stone-500 dark:text-stone-400 leading-snug">
train / test, карточка README.md, dataset_info.json и Python
</div>
</button>
<button
id="tab-llama-factory-btn"
type="button"
onClick={() => setDestination('llama_factory')}
className={`p-3 rounded-xl border text-left transition-all flex flex-col justify-between gap-1.5 ${
destination === 'llama_factory'
? 'border-amber-500 bg-amber-50/50 dark:bg-amber-950/30 ring-2 ring-amber-500/20 text-stone-900 dark:text-stone-100'
: 'border-stone-200 dark:border-stone-800 bg-stone-50/60 dark:bg-stone-950/40 hover:border-stone-300 dark:hover:border-stone-700 text-stone-700 dark:text-stone-300'
}`}
>
<div className="flex items-center gap-2 font-bold">
<Cpu className="w-4 h-4 text-amber-600 dark:text-amber-400 shrink-0" />
<span>LLaMA-Factory (.zip / JSONL)</span>
</div>
<div className="text-[11px] text-stone-500 dark:text-stone-400 leading-snug">
Готовый JSONL, конфигурация dataset_info.json и CLI
</div>
</button>
</div>
</section>
{/* Step 2.3: Destination-Specific Settings */}
{destination === 'dataset_file' && (
<section className="space-y-4">
{totalExportImages > 0 && (
<div className="p-3.5 rounded-xl bg-amber-50/70 dark:bg-amber-950/30 text-stone-900 dark:text-stone-100 border border-amber-200 dark:border-amber-800/70 flex flex-wrap items-center justify-between gap-3 text-xs">
<div className="flex items-start sm:items-center gap-2.5 min-w-0">
<ImageIcon className="w-4 h-4 text-amber-600 dark:text-amber-400 shrink-0 mt-0.5 sm:mt-0" />
<div className="min-w-0">
<div className="font-bold text-stone-900 dark:text-stone-100">
Мультимодальный датасет ({totalExportImages}{' '}
изображений)
</div>
<div className="text-[11px] text-stone-600 dark:text-stone-400 tabular-nums">
Загружено: {uploadedExportImages} · По имени файла:{' '}
{placeholderExportImages} (папка{' '}
<code className="font-mono text-amber-800 dark:text-amber-300">
images/
</code>
)
</div>
</div>
</div>
<button
id="dataset-download-with-images-zip-btn"
type="button"
onClick={handleDownloadWithImagesZip}
disabled={isDatasetZipping || noSelection}
className="px-3 py-1.5 rounded-lg bg-amber-500 hover:bg-amber-400 disabled:opacity-50 text-stone-950 font-bold text-[11px] flex items-center gap-1.5 transition-colors shrink-0 whitespace-nowrap"
>
{isDatasetZipping ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<Download className="w-3.5 h-3.5" />
)}
<span>Скачать с папкой images/ (.zip)</span>
</button>
</div>
)}
{datasetZipError && (
<div className="p-2.5 rounded-lg bg-rose-50 dark:bg-rose-950/50 border border-rose-200 dark:border-rose-800 text-xs text-rose-800 dark:text-rose-200 flex items-center gap-2">
<AlertCircle className="w-4 h-4 text-rose-600 dark:text-rose-400 shrink-0" />
<span>{datasetZipError}</span>
</div>
)}
<div className="p-4 rounded-xl bg-stone-50/80 dark:bg-stone-950/60 border border-stone-200 dark:border-stone-800 space-y-4">
{/* Format Radio */}
<div>
<label className="block text-xs font-bold uppercase tracking-wider text-stone-700 dark:text-stone-300 mb-2">
Формат файла
</label>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
<label
className={`p-3 rounded-xl border flex items-center gap-3 cursor-pointer transition-all ${
localSettings.format !== 'jsonl'
? 'border-amber-500 bg-white dark:bg-stone-900 ring-2 ring-amber-500/15'
: 'border-stone-200 dark:border-stone-700 hover:border-stone-300 dark:hover:border-stone-600 bg-white/70 dark:bg-stone-900/60'
}`}
>
<input
type="radio"
name="format_choice"
checked={localSettings.format !== 'jsonl'}
onChange={() =>
setLocalSettings({
...localSettings,
format: 'json',
})
}
className="text-amber-600 accent-amber-500"
/>
<div>
<div className="text-xs font-bold text-stone-900 dark:text-stone-100">
Стандартный JSON (.json)
</div>
<div className="text-[11px] text-stone-500 dark:text-stone-400">
{isSingleObjectOutput
? 'Одиночный JSON-объект'
: 'Массив [ { id, conversations: [...] } ]'}
</div>
</div>
</label>
<label
className={`p-3 rounded-xl border flex items-center gap-3 cursor-pointer transition-all ${
localSettings.format === 'jsonl'
? 'border-amber-500 bg-white dark:bg-stone-900 ring-2 ring-amber-500/15'
: 'border-stone-200 dark:border-stone-700 hover:border-stone-300 dark:hover:border-stone-600 bg-white/70 dark:bg-stone-900/60'
}`}
>
<input
type="radio"
name="format_choice"
checked={localSettings.format === 'jsonl'}
onChange={() =>
setLocalSettings({
...localSettings,
format: 'jsonl',
})
}
className="text-amber-600 accent-amber-500"
/>
<div>
<div className="text-xs font-bold text-stone-900 dark:text-stone-100">
JSON Lines (.jsonl)
</div>
<div className="text-[11px] text-stone-500 dark:text-stone-400">
Один диалог на строку (рекомендуется для обучения)
</div>
</div>
</label>
</div>
</div>
{/* Filename Input */}
<div>
<label className="block text-xs font-bold uppercase tracking-wider text-stone-700 dark:text-stone-300 mb-1.5">
Имя сохраняемого файла
</label>
<div className="flex items-center gap-2">
<input
type="text"
value={customFilename}
onChange={(e) => setCustomFilename(e.target.value)}
className="w-full text-xs bg-white dark:bg-stone-900 border border-stone-300 dark:border-stone-700 rounded-lg p-2 text-stone-900 dark:text-stone-100 placeholder-stone-400 dark:placeholder-stone-500 font-mono focus:outline-hidden focus:border-amber-500"
placeholder={defaultFilename}
/>
<button
type="button"
onClick={() => setCustomFilename('')}
className="px-2.5 py-2 text-xs border border-stone-300 dark:border-stone-700 rounded-lg text-stone-600 dark:text-stone-300 hover:bg-stone-100 dark:hover:bg-stone-800 shrink-0 font-medium"
title="Сбросить к имени по умолчанию"
>
Сброс
</button>
</div>
</div>
{/* Role Mapping & System Placement */}
<div className="pt-3 border-t border-stone-200 dark:border-stone-800 space-y-3">
<label className="block text-xs font-bold uppercase tracking-wider text-stone-700 dark:text-stone-300">
Схема именования ролей (`from`)
</label>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
<label className="flex items-center gap-2 p-2.5 rounded-lg bg-white dark:bg-stone-900 border border-stone-200 dark:border-stone-700 cursor-pointer">
<input
type="radio"
name="roleMapping"
value="human_gpt"
checked={localSettings.roleMapping === 'human_gpt'}
onChange={(e) =>
setLocalSettings({
...localSettings,
roleMapping: e.target.value as RoleMappingPreset,
})
}
className="text-amber-600 accent-amber-500"
/>
<div>
<span className="font-semibold text-stone-900 dark:text-stone-100">
human / gpt
</span>
<span className="text-stone-500 dark:text-stone-400 block text-[11px]">
Классический ShareGPT (Vicuna, FastChat)
</span>
</div>
</label>
<label className="flex items-center gap-2 p-2.5 rounded-lg bg-white dark:bg-stone-900 border border-stone-200 dark:border-stone-700 cursor-pointer">
<input
type="radio"
name="roleMapping"
value="user_assistant"
checked={
localSettings.roleMapping === 'user_assistant'
}
onChange={(e) =>
setLocalSettings({
...localSettings,
roleMapping: e.target.value as RoleMappingPreset,
})
}
className="text-amber-600 accent-amber-500"
/>
<div>
<span className="font-semibold text-stone-900 dark:text-stone-100">
user / assistant
</span>
<span className="text-stone-500 dark:text-stone-400 block text-[11px]">
Стиль OpenAI / LLaMA-3 Chat
</span>
</div>
</label>
</div>
<div>
<label className="block text-xs font-medium text-stone-700 dark:text-stone-300 mb-1">
Расположение системного промпта:
</label>
<select
id="system-placement-select"
value={localSettings.systemPlacement}
onChange={(e) =>
setLocalSettings({
...localSettings,
systemPlacement: e.target
.value as SystemPromptPlacement,
})
}
className="w-full text-xs bg-white dark:bg-stone-900 border border-stone-300 dark:border-stone-700 rounded-lg p-2 text-stone-800 dark:text-stone-100 focus:outline-hidden focus:border-amber-500"
>
<option value="root_property">
Отдельное свойство "system": "..."
(Рекомендуется для LLaMA-Factory/Axolotl)
</option>
<option value="first_turn">
Первая реплика в списке "from":
"system" (FastChat)
</option>
<option value="omit">
Не экспортировать системный промпт
</option>
</select>
</div>
<div className="flex flex-wrap gap-4 pt-1">
<label className="flex items-center gap-2 text-xs text-stone-700 dark:text-stone-300 cursor-pointer">
<input
type="checkbox"
checked={localSettings.prettyPrint}
onChange={(e) =>
setLocalSettings({
...localSettings,
prettyPrint: e.target.checked,
})
}
className="rounded text-amber-600 accent-amber-500"
/>
<span>Форматированный отступ (2 пробела)</span>
</label>
<label className="flex items-center gap-2 text-xs text-stone-700 dark:text-stone-300 cursor-pointer">
<input
type="checkbox"
checked={localSettings.includeMetadata}
onChange={(e) =>
setLocalSettings({
...localSettings,
includeMetadata: e.target.checked,
})
}
className="rounded text-amber-600 accent-amber-500"
/>
<span>Включить метаданные (_metadata: теги, дата)</span>
</label>
</div>
</div>
</div>
</section>
)}
{destination === 'huggingface' && (
<section className="space-y-4">
<div className="p-4 rounded-xl bg-stone-50/80 dark:bg-stone-950/60 border border-stone-200 dark:border-stone-800 space-y-4">
<div className="flex items-center justify-between gap-2">
<label className="text-xs font-bold uppercase tracking-wider text-stone-800 dark:text-stone-200">
Схема записей для Hugging Face
</label>
{totalExportImages > 0 && (
<span className="text-[11px] font-mono tabular-nums text-amber-700 dark:text-amber-400">
+ папка images/ ({uploadedExportImages} фото,{' '}
{placeholderExportImages} заглушек)
</span>
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5 text-xs">
<label
className={`p-3 rounded-xl border flex flex-col justify-between cursor-pointer transition-all ${
hfFormat === 'messages'
? 'border-amber-500 bg-white dark:bg-stone-900 ring-2 ring-amber-500/15 text-stone-900 dark:text-stone-100'
: 'border-stone-200 dark:border-stone-700 bg-white/70 dark:bg-stone-900/60 hover:border-stone-300 dark:hover:border-stone-600 text-stone-700 dark:text-stone-300'
}`}
>
<div className="flex items-center gap-2 mb-1">
<input
type="radio"
name="hf_format"
checked={hfFormat === 'messages'}
onChange={() => setHfFormat('messages')}
className="text-amber-600 accent-amber-500"
/>
<span className="font-bold">HF Messages</span>
</div>
<div className="text-[11px] text-stone-500 dark:text-stone-400 leading-snug">
<code className="font-mono text-[10px]">
messages: [role, content]
</code>
<br />
Для TRL SFTTrainer и Chat Template
</div>
</label>
<label
className={`p-3 rounded-xl border flex flex-col justify-between cursor-pointer transition-all ${
hfFormat === 'sharegpt'
? 'border-amber-500 bg-white dark:bg-stone-900 ring-2 ring-amber-500/15 text-stone-900 dark:text-stone-100'
: 'border-stone-200 dark:border-stone-700 bg-white/70 dark:bg-stone-900/60 hover:border-stone-300 dark:hover:border-stone-600 text-stone-700 dark:text-stone-300'
}`}
>
<div className="flex items-center gap-2 mb-1">
<input
type="radio"
name="hf_format"
checked={hfFormat === 'sharegpt'}
onChange={() => setHfFormat('sharegpt')}
className="text-amber-600 accent-amber-500"
/>
<span className="font-bold">ShareGPT</span>
</div>
<div className="text-[11px] text-stone-500 dark:text-stone-400 leading-snug">
<code className="font-mono text-[10px]">
conversations: [from, value]
</code>
<br />
Для LLaMA-Factory, Axolotl, FastChat
</div>
</label>
<label
className={`p-3 rounded-xl border flex flex-col justify-between cursor-pointer transition-all ${
hfFormat === 'alpaca'
? 'border-amber-500 bg-white dark:bg-stone-900 ring-2 ring-amber-500/15 text-stone-900 dark:text-stone-100'
: 'border-stone-200 dark:border-stone-700 bg-white/70 dark:bg-stone-900/60 hover:border-stone-300 dark:hover:border-stone-600 text-stone-700 dark:text-stone-300'
}`}
>
<div className="flex items-center gap-2 mb-1">
<input
type="radio"
name="hf_format"
checked={hfFormat === 'alpaca'}
onChange={() => setHfFormat('alpaca')}
className="text-amber-600 accent-amber-500"
/>
<span className="font-bold">Alpaca</span>
</div>
<div className="text-[11px] text-stone-500 dark:text-stone-400 leading-snug">
<code className="font-mono text-[10px]">
instruction, input, output
</code>
<br />
Классический формат инструкций
</div>
</label>
</div>
{/* Train/Test Split & Metadata */}
<div className="pt-3 border-t border-stone-200 dark:border-stone-800 grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs">
<div>
<label className="flex items-center gap-2 text-stone-700 dark:text-stone-200 cursor-pointer mb-1.5 font-medium">
<input
type="checkbox"
checked={hfSplitTrainTest}
onChange={(e) =>
setHfSplitTrainTest(e.target.checked)
}
className="rounded text-amber-600 accent-amber-500"
/>
<span>Разбить на train / test выборки</span>
</label>
{hfSplitTrainTest && (
<div className="pl-6 flex items-center gap-2 text-[11px] text-stone-600 dark:text-stone-300 tabular-nums">
<span>
Train:{' '}
<strong>{Math.round(hfTrainRatio * 100)}%</strong>
</span>
<input
type="range"
min="0.5"
max="0.95"
step="0.05"
value={hfTrainRatio}
onChange={(e) =>
setHfTrainRatio(parseFloat(e.target.value))
}
className="w-24 accent-amber-600"
/>
<span>
Test:{' '}
<strong>
{Math.round((1 - hfTrainRatio) * 100)}%
</strong>
</span>
</div>
)}
</div>
<div className="flex items-center gap-3">
<div className="flex-1">
<label className="block text-[11px] text-stone-500 dark:text-stone-400 font-medium mb-1">
Язык датасета:
</label>
<select
value={hfLanguage}
onChange={(e) => setHfLanguage(e.target.value)}
className="w-full text-xs bg-white dark:bg-stone-900 border border-stone-300 dark:border-stone-700 rounded-lg p-1.5 text-stone-800 dark:text-stone-100 focus:outline-hidden focus:border-amber-500"
>
<option value="ru">Русский (ru)</option>
<option value="en">English (en)</option>
<option value="multilingual">
Multilingual (ru, en)
</option>
</select>
</div>
<div className="flex-1">
<label className="block text-[11px] text-stone-500 dark:text-stone-400 font-medium mb-1">
Лицензия:
</label>
<select
value={hfLicense}
onChange={(e) => setHfLicense(e.target.value)}
className="w-full text-xs bg-white dark:bg-stone-900 border border-stone-300 dark:border-stone-700 rounded-lg p-1.5 text-stone-800 dark:text-stone-100 focus:outline-hidden focus:border-amber-500"
>
<option value="apache-2.0">Apache 2.0</option>
<option value="mit">MIT</option>
<option value="cc-by-4.0">CC-BY-4.0</option>
<option value="other">Other</option>
</select>
</div>
</div>
</div>
{/* Repo Name + Single File Buttons */}
<div className="pt-3 border-t border-stone-200 dark:border-stone-800 space-y-2.5">
<div>
<label className="block text-[11px] text-stone-600 dark:text-stone-300 font-medium mb-1">
Имя репозитория для карточки README.md и Python-примера:
</label>
<div className="flex items-center gap-2">
<input
type="text"
value={hfRepoName}
onChange={(e) => {
setHasManualHfRepo(true);
setHfRepoName(e.target.value);
}}
placeholder="username/my-sft-dataset"
className="w-full text-xs font-mono bg-white dark:bg-stone-900 border border-stone-300 dark:border-stone-700 rounded-lg p-2 text-stone-900 dark:text-stone-100 placeholder-stone-400 dark:placeholder-stone-500 focus:outline-hidden focus:border-amber-500"
/>
{hasManualHfRepo && (
<button
type="button"
onClick={() => setHasManualHfRepo(false)}
className="px-2.5 py-2 text-xs border border-stone-300 dark:border-stone-700 rounded-lg text-stone-600 dark:text-stone-300 hover:bg-stone-100 dark:hover:bg-stone-800 shrink-0 font-medium"
>
Авто
</button>
)}
</div>
</div>
<div className="flex flex-wrap items-center gap-2 text-xs">
<span className="text-[11px] text-stone-500 dark:text-stone-400">
Отдельные файлы:
</span>
<button
type="button"
onClick={handleDownloadHfTrainJsonl}
disabled={noSelection}
className="px-2.5 py-1.5 rounded-lg bg-white dark:bg-stone-900 border border-stone-200 dark:border-stone-700 hover:bg-stone-100 dark:hover:bg-stone-800 disabled:opacity-50 text-stone-700 dark:text-stone-200 text-[11px] font-medium flex items-center gap-1.5"
>
<FileJson className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
<span>Скачать train.jsonl</span>
</button>
<button
type="button"
onClick={handleDownloadHfReadme}
className="px-2.5 py-1.5 rounded-lg bg-white dark:bg-stone-900 border border-stone-200 dark:border-stone-700 hover:bg-stone-100 dark:hover:bg-stone-800 text-stone-700 dark:text-stone-200 text-[11px] font-medium flex items-center gap-1.5"
>
<span>Скачать README.md</span>
</button>
</div>
{hfZipError && (
<div className="p-2.5 rounded-lg bg-rose-50 dark:bg-rose-950/50 border border-rose-200 dark:border-rose-800 text-xs text-rose-800 dark:text-rose-200 flex items-center gap-2">
<AlertCircle className="w-4 h-4 text-rose-600 dark:text-rose-400 shrink-0" />
<span>{hfZipError}</span>
</div>
)}
</div>
</div>
</section>
)}
{destination === 'llama_factory' && (
<section className="space-y-4">
<div className="p-4 rounded-xl bg-stone-50/80 dark:bg-stone-950/60 border border-stone-200 dark:border-stone-800 space-y-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<div className="text-xs font-bold uppercase tracking-wider text-stone-800 dark:text-stone-200">
Параметры LLaMA-Factory
</div>
<p className="text-[11px] text-stone-500 dark:text-stone-400 mt-0.5">
Файлы{' '}
<code className="font-mono text-stone-700 dark:text-stone-300">
{llamaEffectiveFileName}
</code>{' '}
и{' '}
<code className="font-mono text-stone-700 dark:text-stone-300">
dataset_info.json
</code>
{totalExportImages > 0
? ` + images/ (${totalExportImages} фото)`
: ''}
</p>
</div>
{onOpenTemplatePreview && (
<button
id="export-open-template-preview-btn"
type="button"
onClick={onOpenTemplatePreview}
className="px-3 py-1.5 rounded-lg bg-amber-500 hover:bg-amber-400 text-stone-950 font-bold text-xs flex items-center gap-1.5 transition-colors whitespace-nowrap shrink-0"
title="Открыть предпросмотр шаблонов токенизации"
>
<Sparkles className="w-3.5 h-3.5" />
<span>Предпросмотр шаблонов моделей</span>
</button>
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className="block text-xs font-semibold text-stone-700 dark:text-stone-200 mb-1">
Ключ датасета в LLaMA-Factory:
</label>
<div className="flex items-center gap-1.5">
<input
id="llama-dataset-key-input"
type="text"
value={llamaDatasetKey}
onChange={(e) => {
setHasManualLlamaKey(true);
setLlamaDatasetKey(e.target.value);
}}
placeholder="my_sharegpt_dataset"
className="w-full text-xs font-mono bg-white dark:bg-stone-900 border border-stone-300 dark:border-stone-700 rounded-lg p-2 text-stone-900 dark:text-stone-100 placeholder-stone-400 dark:placeholder-stone-500 focus:outline-hidden focus:border-amber-500"
/>
{hasManualLlamaKey && (
<button
type="button"
onClick={() => setHasManualLlamaKey(false)}
className="px-2 py-2 text-[11px] border border-stone-300 dark:border-stone-700 rounded-lg text-stone-600 dark:text-stone-300 hover:bg-stone-100 dark:hover:bg-stone-800 shrink-0 font-medium"
>
Авто
</button>
)}
</div>
</div>
<div>
<label className="block text-xs font-semibold text-stone-700 dark:text-stone-200 mb-1">
Имя JSONL-файла данных:
</label>
<div className="flex items-center gap-1.5">
<input
id="llama-filename-input"
type="text"
value={llamaCustomFilename}
onChange={(e) =>
setLlamaCustomFilename(e.target.value)
}
placeholder={llamaDefaultFilename}
className="w-full text-xs font-mono bg-white dark:bg-stone-900 border border-stone-300 dark:border-stone-700 rounded-lg p-2 text-stone-900 dark:text-stone-100 placeholder-stone-400 dark:placeholder-stone-500 focus:outline-hidden focus:border-amber-500"
/>
{llamaCustomFilename && (
<button
type="button"
onClick={() => setLlamaCustomFilename('')}
className="px-2 py-2 text-[11px] border border-stone-300 dark:border-stone-700 rounded-lg text-stone-600 dark:text-stone-300 hover:bg-stone-100 dark:hover:bg-stone-800 shrink-0 font-medium"
>
Сброс
</button>
)}
</div>
</div>
</div>
<div className="flex flex-wrap gap-4 pt-2 border-t border-stone-200 dark:border-stone-800 text-xs">
<label className="flex items-center gap-2 text-stone-700 dark:text-stone-300 cursor-pointer">
<input
type="checkbox"
checked={
localSettings.systemPlacement === 'root_property'
}
onChange={(e) =>
setLocalSettings({
...localSettings,
systemPlacement: e.target.checked
? 'root_property'
: 'omit',
})
}
className="rounded text-amber-600 accent-amber-500"
/>
<span>
Колонка системного промпта (
<code className="font-mono">system</code>)
</span>
</label>
<label className="flex items-center gap-2 text-stone-700 dark:text-stone-300 cursor-pointer">
<input
type="checkbox"
checked={includeToolsColumn}
onChange={(e) =>
setIncludeToolsColumn(e.target.checked)
}
className="rounded text-amber-600 accent-amber-500"
/>
<span>
Колонка инструментов (
<code className="font-mono">tools</code>)
</span>
</label>
{totalExportImages > 0 && (
<label className="flex items-center gap-2 text-stone-700 dark:text-stone-300 cursor-pointer">
<input
type="checkbox"
checked={includeImagesColumn}
onChange={(e) =>
setIncludeImagesColumn(e.target.checked)
}
className="rounded text-amber-600 accent-amber-500"
/>
<span className="tabular-nums">
Колонка изображений (
<code className="font-mono">images</code>) ·{' '}
{totalExportImages} шт.
</span>
</label>
)}
</div>
<div className="pt-2 border-t border-stone-200 dark:border-stone-800 flex flex-wrap items-center gap-2 text-xs">
<span className="text-[11px] text-stone-500 dark:text-stone-400">
Отдельные файлы:
</span>
<button
id="llama-download-jsonl-btn"
type="button"
onClick={handleDownloadLlamaJsonl}
disabled={noSelection}
className="px-2.5 py-1.5 rounded-lg bg-white dark:bg-stone-900 border border-stone-200 dark:border-stone-700 hover:bg-stone-100 dark:hover:bg-stone-800 disabled:opacity-50 text-stone-800 dark:text-stone-100 text-[11px] font-medium flex items-center gap-1.5"
>
<FileJson className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
<span>Скачать {llamaEffectiveFileName}</span>
</button>
<button
id="llama-download-info-btn"
type="button"
onClick={handleDownloadLlamaDatasetInfo}
className="px-2.5 py-1.5 rounded-lg bg-white dark:bg-stone-900 border border-stone-200 dark:border-stone-700 hover:bg-stone-100 dark:hover:bg-stone-800 text-stone-800 dark:text-stone-100 text-[11px] font-medium"
>
Скачать dataset_info.json
</button>
</div>
{llamaZipError && (
<div className="p-2.5 rounded-lg bg-rose-50 dark:bg-rose-950/50 border border-rose-200 dark:border-rose-800 text-xs text-rose-800 dark:text-rose-200 flex items-center gap-2">
<AlertCircle className="w-4 h-4 text-rose-600 dark:text-rose-400 shrink-0" />
<span>{llamaZipError}</span>
</div>
)}
</div>
</section>
)}
{/* Step 2.4: Unified Live Result Preview */}
<section className="space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2">
<span className="text-xs font-bold uppercase tracking-wider text-stone-700 dark:text-stone-200">
3. Предпросмотр результата
</span>
{destination === 'huggingface' && (
<div className="flex items-center gap-1 border border-stone-200 dark:border-stone-800 rounded-lg p-0.5 bg-stone-50 dark:bg-stone-950 text-[11px]">
{(
[
{ id: 'jsonl', label: 'train.jsonl' },
{ id: 'readme', label: 'README.md' },
{ id: 'python', label: 'Python' },
] as const
).map((tab) => (
<button
key={tab.id}
type="button"
onClick={() => setHfPreviewTab(tab.id)}
className={`px-2 py-0.5 rounded-md font-medium transition-colors ${
hfPreviewTab === tab.id
? 'bg-white dark:bg-stone-800 text-stone-900 dark:text-stone-100 shadow-2xs'
: 'text-stone-500 dark:text-stone-400 hover:text-stone-800 dark:hover:text-stone-200'
}`}
>
{tab.label}
</button>
))}
</div>
)}
{destination === 'llama_factory' && (
<div className="flex items-center gap-1 border border-stone-200 dark:border-stone-800 rounded-lg p-0.5 bg-stone-50 dark:bg-stone-950 text-[11px]">
{(
[
{ id: 'dataset_info', label: 'dataset_info.json' },
{ id: 'jsonl', label: 'Строки JSONL' },
{ id: 'cli', label: 'Команда CLI' },
] as const
).map((tab) => (
<button
key={tab.id}
type="button"
onClick={() => setLlamaPreviewTab(tab.id)}
className={`px-2 py-0.5 rounded-md font-medium transition-colors ${
llamaPreviewTab === tab.id
? 'bg-white dark:bg-stone-800 text-stone-900 dark:text-stone-100 shadow-2xs'
: 'text-stone-500 dark:text-stone-400 hover:text-stone-800 dark:hover:text-stone-200'
}`}
>
{tab.label}
</button>
))}
</div>
)}
</div>
<div className="flex items-center gap-3">
<span className="text-[11px] font-mono tabular-nums text-stone-500 dark:text-stone-400">
~{activePreviewPayload.text.length.toLocaleString()} симв.
</span>
<button
type="button"
onClick={handleCopyPreview}
disabled={noSelection && destination === 'dataset_file'}
className="text-xs text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 disabled:opacity-40 font-semibold flex items-center gap-1"
>
{copiedPreview ? (
<>
<Check className="w-3.5 h-3.5 text-emerald-600 dark:text-emerald-400" />
<span className="text-emerald-600 dark:text-emerald-400">
Скопировано
</span>
</>
) : (
<>
<Copy className="w-3.5 h-3.5" />
<span>Копировать</span>
</>
)}
</button>
</div>
</div>
<div className="p-3.5 rounded-xl bg-stone-50 dark:bg-stone-950 font-mono text-[11px] max-h-52 overflow-auto border border-stone-200 dark:border-stone-800 leading-relaxed text-stone-800 dark:text-stone-200">
<pre className="whitespace-pre-wrap break-words">
{destination === 'dataset_file'
? previewString.slice(0, 1400) +
(previewString.length > 1400
? '\n... (продолжение при сохранении файла)'
: '')
: destination === 'huggingface'
? hfPreviewTab === 'jsonl'
? hfJsonlSamplePreview || '// Выберите диалоги слева'
: hfPreviewTab === 'readme'
? hfReadmePreview
: hfPythonScript
: llamaPreviewTab === 'dataset_info'
? llamaConfigSnippet
: llamaPreviewTab === 'jsonl'
? llamaJsonlSamplePreview || '// Выберите диалоги слева'
: llamaCliExample}
</pre>
</div>
</section>
</main>
</div>
{/* Footer Actions */}
<div className="flex flex-wrap items-center justify-between gap-2 px-4 sm:px-6 py-3.5 border-t border-stone-200 dark:border-stone-800 bg-stone-50 dark:bg-stone-950 shrink-0">
<button
id="modal-copy-btn"
type="button"
onClick={handleCopyPreview}
disabled={noSelection && destination === 'dataset_file'}
className="px-4 py-2 rounded-xl border border-stone-300 dark:border-stone-700 bg-white dark:bg-stone-800 hover:bg-stone-100 dark:hover:bg-stone-700 disabled:opacity-50 text-stone-700 dark:text-stone-200 text-xs font-semibold flex items-center gap-1.5 transition-colors whitespace-nowrap"
>
{copiedPreview ? (
<>
<Check className="w-4 h-4 text-emerald-600 dark:text-emerald-400" />
<span className="text-emerald-600 dark:text-emerald-400 font-bold">
Скопировано
</span>
</>
) : (
<>
<Copy className="w-4 h-4 text-stone-500 dark:text-stone-400" />
<span>{activePreviewPayload.label}</span>
</>
)}
</button>
<div className="flex flex-wrap items-center gap-2">
<button
id="modal-cancel-btn"
type="button"
onClick={onClose}
className="px-4 py-2 rounded-xl text-stone-600 dark:text-stone-400 hover:text-stone-900 dark:hover:text-stone-100 text-xs font-medium transition-colors"
>
Закрыть
</button>
{destination === 'huggingface' ? (
<button
id="modal-hf-zip-footer-btn"
type="button"
onClick={handleDownloadHfZip}
disabled={isZipping || noSelection}
className="px-5 py-2 rounded-xl bg-amber-600 hover:bg-amber-700 disabled:opacity-50 text-white text-xs font-semibold flex items-center gap-2 shadow-xs transition-all whitespace-nowrap"
>
{isZipping ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
<span>Сборка ZIP...</span>
</>
) : (
<>
<Download className="w-4 h-4" />
<span>Скачать ZIP для Hugging Face</span>
</>
)}
</button>
) : destination === 'llama_factory' ? (
<button
id="modal-llama-zip-footer-btn"
type="button"
onClick={handleDownloadLlamaZip}
disabled={isLlamaZipping || noSelection}
className="px-5 py-2 rounded-xl bg-amber-600 hover:bg-amber-700 disabled:opacity-50 text-white text-xs font-semibold flex items-center gap-2 shadow-xs transition-all whitespace-nowrap"
>
{isLlamaZipping ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
<span>Сборка ZIP...</span>
</>
) : (
<>
<Download className="w-4 h-4" />
<span>
{totalExportImages > 0
? 'Скачать ZIP (JSONL + info + images/)'
: 'Скачать ZIP (JSONL + dataset_info.json)'}
</span>
</>
)}
</button>
) : (
<>
{totalExportImages > 0 && (
<button
id="modal-download-with-images-btn"
type="button"
onClick={handleDownloadWithImagesZip}
disabled={isDatasetZipping || noSelection}
className="px-4 py-2 rounded-xl bg-stone-900 dark:bg-stone-800 hover:bg-stone-800 dark:hover:bg-stone-700 disabled:opacity-50 text-white text-xs font-semibold flex items-center gap-1.5 border border-stone-700 transition-colors whitespace-nowrap"
>
{isDatasetZipping ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<ImageIcon className="w-4 h-4 text-amber-400" />
)}
<span>ZIP + images/</span>
</button>
)}
<button
id="modal-download-btn"
type="button"
onClick={handleDownload}
disabled={noSelection}
className="px-5 py-2 rounded-xl bg-amber-600 hover:bg-amber-700 disabled:opacity-50 text-white text-xs font-semibold flex items-center gap-2 shadow-xs transition-all whitespace-nowrap"
>
<Download className="w-4 h-4" />
<span>Скачать {effectiveFileName}</span>
</button>
</>
)}
</div>
</div>
</div>
</div>
);
};
import React, { useEffect, useMemo, useState } from 'react';
import {
AlertCircle,
Check,
Copy,
Cpu,
Download,
FileJson,
Image as ImageIcon,
Loader2,
PackageCheck,
Sparkles,
X,
} from 'lucide-react';
import {
Dataset,
DatasetFolder,
DialogueFolder,
ExportSettings,
HistoryThoughtMode,
HistoryThoughtRules,
MessageTag,
RoleMappingPreset,
ShareGPTConversation,
SystemPromptPlacement,
} from '../types';
import { copyTextToClipboard } from '../utils/clipboard';
import {
getDatasetAllDialogueIds,
getExportSelectionSummary,
} from '../utils/dataset';
import {
computeDatasetStats,
createHuggingFaceZipPackage,
generateHfJsonl,
generateHfPythonScript,
generateHfReadme,
HuggingFaceExportOptions,
HuggingFaceFormat,
} from '../utils/huggingface';
import { createDatasetFilesZipPackage } from '../utils/imageExport';
import { getConversationImages, getImageRelativePath } from '../utils/imageStorage';
import { DEFAULT_LAYOUT_SIZES } from '../utils/layout';
import {
createLlamaFactoryZipPackage,
generateDatasetInfoSnippet,
sanitizeDatasetKey,
} from '../utils/llamaFactory';
import { downloadFile, generateExportString } from '../utils/sharegpt';
import {
normalizeHistoryThoughtRules,
transformConversationsWithSource,
} from '../utils/tags';
import { ExportSelectionTree } from './ExportSelectionTree';
import { HistoryThoughtControls } from './HistoryThoughtControls';
import { ResizableSplitter } from './ResizableSplitter';
interface ExportModalProps {
isOpen: boolean;
onClose: () => void;
conversations: ShareGPTConversation[];
activeConversation: ShareGPTConversation;
datasets?: Dataset[];
datasetFolders?: DatasetFolder[];
dialogueFolders?: DialogueFolder[];
messageTags?: MessageTag[];
activeDatasetId?: string | 'all';
settings: ExportSettings;
onSaveSettings: (settings: ExportSettings) => void;
onOpenTemplatePreview?: () => void;
sidebarWidth?: number;
onChangeSidebarWidth?: (width: number) => void;
}
type ExportDestination = 'dataset_file' | 'huggingface' | 'llama_factory';
type HfPreviewTab = 'jsonl' | 'readme' | 'python';
type LlamaPreviewTab = 'dataset_info' | 'jsonl' | 'cli';
function pluralizeDatasets(count: number): string {
const mod10 = count % 10;
const mod100 = count % 100;
if (mod10 === 1 && mod100 !== 11) return 'набора';
return 'наборов';
}
export const ExportModal: React.FC<ExportModalProps> = ({
isOpen,
onClose,
conversations,
activeConversation,
datasets = [],
datasetFolders = [],
dialogueFolders = [],
messageTags = [],
activeDatasetId = 'all',
settings,
onSaveSettings,
onOpenTemplatePreview,
sidebarWidth,
onChangeSidebarWidth,