000001 / dataset_builder.html
schatmodels's picture
Upload folder using huggingface_hub
ca4eb2f verified
Raw
History Blame Contribute Delete
30.5 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modern Dataset Builder</title>
<!-- Marked.js -->
<script src="https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js"></script>
<!-- Phosphor Icons (para ícones mais bonitos) -->
<script src="https://unpkg.com/@phosphor-icons/web"></script>
<style>
:root {
/* Palette: Indigo & Slate */
--primary: #4f46e5;
--primary-hover: #4338ca;
--secondary: #64748b;
--danger: #ef4444;
--danger-hover: #dc2626;
--success: #22c55e;
--bg: #f1f5f9;
--surface: #ffffff;
--border: #e2e8f0;
--text-main: #1e293b;
--text-muted: #64748b;
--shadow-sm: 0 1px 3px rgba(0,0,0,0.1);
--shadow-md: 0 4px 6px -1px rgba(0,0,0,0.1);
--radius: 12px;
}
* { box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background-color: var(--bg);
color: var(--text-main);
margin: 0;
padding: 40px 20px;
line-height: 1.5;
}
.container {
max-width: 1000px;
margin: 0 auto;
}
h1 {
text-align: center;
color: var(--text-main);
margin-bottom: 40px;
font-weight: 800;
letter-spacing: -0.025em;
}
/* --- Card Styles --- */
.card {
background: var(--surface);
padding: 30px;
border-radius: var(--radius);
box-shadow: var(--shadow-md);
margin-bottom: 30px;
border: 1px solid var(--border);
}
/* --- Form --- */
.form-title {
margin-top: 0;
display: flex;
align-items: center;
gap: 10px;
color: var(--primary);
}
.form-group { margin-bottom: 20px; }
label {
display: block;
font-weight: 600;
margin-bottom: 8px;
color: var(--text-main);
font-size: 0.95rem;
}
textarea {
width: 100%;
padding: 15px;
border: 1px solid var(--border);
border-radius: 8px;
font-family: monospace;
font-size: 14px;
resize: vertical;
transition: border-color 0.2s, box-shadow 0.2s;
background: #f8fafc;
}
textarea:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
background: #fff;
}
/* --- Buttons --- */
.btn-group { display: flex; gap: 12px; flex-wrap: wrap; }
button {
padding: 10px 20px;
border: none;
border-radius: 8px;
cursor: pointer;
font-weight: 600;
font-size: 0.95rem;
transition: all 0.2s;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
}
button:active { transform: translateY(1px); }
.btn-primary { background-color: var(--primary); color: white; }
.btn-primary:hover { background-color: var(--primary-hover); }
.btn-danger { background-color: var(--danger); color: white; }
.btn-danger:hover { background-color: var(--danger-hover); }
.btn-success { background-color: var(--success); color: white; }
.btn-success:hover { filter: brightness(90%); }
.btn-secondary { background-color: var(--surface); border: 1px solid var(--border); color: var(--text-main); }
.btn-secondary:hover { background-color: #f8fafc; border-color: #cbd5e1; }
.btn-icon { padding: 8px; border-radius: 6px; }
/* --- Toolbar (Search & Global Actions) --- */
.toolbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 20px;
margin-bottom: 20px;
flex-wrap: wrap;
}
.search-box {
flex: 1;
position: relative;
min-width: 250px;
}
.search-box input {
width: 100%;
padding: 10px 15px 10px 40px;
border-radius: 8px;
border: 1px solid var(--border);
font-size: 1rem;
}
.search-box i {
position: absolute;
left: 12px;
top: 50%;
transform: translateY(-50%);
color: var(--text-muted);
}
/* --- List --- */
.list-header-info {
font-weight: 700; color: var(--text-muted); margin-bottom: 10px;
display: flex; justify-content: space-between; align-items: center;
}
.accordion-item {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 8px;
margin-bottom: 12px;
overflow: hidden;
transition: box-shadow 0.2s;
}
.accordion-item:hover { box-shadow: var(--shadow-sm); }
.accordion-header {
padding: 15px 20px;
cursor: pointer;
display: flex; justify-content: space-between; align-items: center;
user-select: none;
background: #fff;
}
.accordion-header:hover { background-color: #f8fafc; }
.header-content {
display: flex; align-items: center; gap: 15px; flex: 1; overflow: hidden;
}
.id-badge {
background: #e0e7ff; color: var(--primary);
padding: 4px 8px; border-radius: 6px; font-size: 0.8em; font-weight: 700;
}
.preview-text {
color: var(--text-main);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
font-weight: 500;
}
.header-actions {
display: flex; gap: 8px; align-items: center; margin-left: 15px;
}
.accordion-content {
display: none; border-top: 1px solid var(--border);
background-color: #fafafa; padding: 25px;
}
.accordion-item.active .accordion-content { display: block; animation: slideDown 0.2s ease-out; }
.accordion-item.active .caret-icon { transform: rotate(180deg); }
.caret-icon { transition: transform 0.2s; color: var(--text-muted); }
/* --- Tabs in Item --- */
.item-tabs { display: flex; gap: 2px; margin-bottom: 20px; border-bottom: 2px solid var(--border); }
.tab-btn {
background: transparent; border: none; padding: 10px 20px; cursor: pointer;
color: var(--text-muted); border-bottom: 2px solid transparent; margin-bottom: -2px;
border-radius: 6px 6px 0 0;
}
.tab-btn:hover { color: var(--primary); background: rgba(79, 70, 229, 0.05); }
.tab-btn.active { color: var(--primary); border-bottom-color: var(--primary); font-weight: 700; background: #fff; border: 1px solid var(--border); border-bottom-color: #fff; }
.tab-content { display: none; }
.tab-content.active { display: block; }
.field-label { font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted); font-weight: 700; margin: 15px 0 5px; display: flex; justify-content: space-between;}
.data-box { background: #fff; border: 1px solid var(--border); padding: 15px; border-radius: 6px; white-space: pre-wrap; word-break: break-all; color: var(--text-main); font-family: monospace; font-size: 0.9em; }
/* --- Pagination --- */
.pagination { display: flex; justify-content: center; align-items: center; gap: 10px; margin-top: 30px; }
.page-info { color: var(--text-muted); font-size: 0.9em; }
/* --- Modal Custom --- */
.modal-overlay {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.5); backdrop-filter: blur(2px);
display: flex; justify-content: center; align-items: center;
z-index: 1000; opacity: 0; pointer-events: none;
transition: opacity 0.2s;
}
.modal-overlay.open { opacity: 1; pointer-events: auto; }
.modal {
background: white; width: 90%; max-width: 450px;
border-radius: 16px; padding: 25px;
box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1);
transform: scale(0.95); transition: transform 0.2s;
}
.modal-overlay.open .modal { transform: scale(1); }
.modal h3 { margin-top: 0; color: var(--text-main); }
.modal p { color: var(--text-muted); margin-bottom: 25px; }
.modal-actions { display: flex; justify-content: flex-end; gap: 10px; }
/* File input hidden */
#fileInput { display: none; }
@keyframes slideDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
</style>
</head>
<body>
<div class="container">
<h1>Dataset Builder</h1>
<!-- Editor Card -->
<div class="card">
<h3 id="formTitle" class="form-title"><i class="ph ph-pencil-simple"></i> New Record</h3>
<form id="datasetForm">
<div class="form-group">
<label for="input">Input</label>
<textarea id="input" name="input" rows="10" placeholder="Type the input text here..."></textarea>
</div>
<div class="form-group">
<label for="output">Output</label>
<textarea id="output" name="output" rows="10" placeholder="Type the expected output here..."></textarea>
</div>
<div class="btn-group">
<button type="submit" class="btn-primary" id="saveBtn"><i class="ph ph-floppy-disk"></i> Save Record</button>
<button type="button" class="btn-secondary" id="cancelBtn" style="display: none;"><i class="ph ph-x"></i> Cancel</button>
</div>
</form>
</div>
<!-- Toolbar -->
<div class="toolbar">
<div class="search-box">
<i class="ph ph-magnifying-glass"></i>
<input type="text" id="searchInput" placeholder="Search inputs..." onkeyup="handleSearch()" autocomplete="off">
</div>
<div class="btn-group">
<input type="file" id="fileInput" accept=".json" onchange="processFile(this)">
<button onclick="document.getElementById('fileInput').click()" class="btn-secondary">
<i class="ph ph-upload-simple"></i> Import JSON
</button>
<button onclick="downloadJSON()" class="btn-success">
<i class="ph ph-download-simple"></i> Export JSON
</button>
<button onclick="confirmDeleteAll()" class="btn-danger">
<i class="ph ph-trash"></i> Delete All
</button>
</div>
</div>
<!-- List Stats -->
<div class="list-header-info">
<span>Total Records: <span id="totalCount">0</span></span>
<span>Showing: <span id="showingCount">0</span></span>
</div>
<!-- List Container -->
<div id="listContainer"></div>
<!-- Pagination -->
<div class="pagination" id="paginationControls">
<button class="btn-secondary btn-icon" id="prevPageBtn" onclick="changePage(-1)"><i class="ph ph-caret-left"></i></button>
<span class="page-info">Page <span id="currPageDisplay">1</span> of <span id="totalPageDisplay">1</span></span>
<button class="btn-secondary btn-icon" id="nextPageBtn" onclick="changePage(1)"><i class="ph ph-caret-right"></i></button>
</div>
</div>
<!-- Custom Modal -->
<div class="modal-overlay" id="customModal">
<div class="modal">
<h3 id="modalTitle">Title</h3>
<p id="modalMessage">Message goes here</p>
<div class="modal-actions">
<button class="btn-secondary" id="modalCancelBtn">Cancel</button>
<button class="btn-primary" id="modalConfirmBtn">Confirm</button>
</div>
</div>
</div>
<script>
// State
let dataset = [];
let filteredDataset = [];
let editingIndex = -1; // Index in the original dataset
let currentPage = 1;
const itemsPerPage = 10;
let searchTerm = "";
// Elements
const form = document.getElementById('datasetForm');
const inputField = document.getElementById('input');
const outputField = document.getElementById('output');
const listContainer = document.getElementById('listContainer');
const saveBtn = document.getElementById('saveBtn');
const cancelBtn = document.getElementById('cancelBtn');
const formTitle = document.getElementById('formTitle');
const modalOverlay = document.getElementById('customModal');
// Init
document.addEventListener('DOMContentLoaded', () => {
if (typeof marked !== 'undefined') marked.setOptions({ breaks: true, gfm: true });
loadFromStorage();
filterAndRender();
});
// --- Core Functions ---
form.addEventListener('submit', (e) => {
e.preventDefault();
const inputVal = inputField.value;
const outputVal = outputField.value;
if (!inputVal.trim() && !outputVal.trim()) {
showAlert("Validation", "Please fill in at least one field.");
return;
}
const record = { input: inputVal, output: outputVal };
if (editingIndex >= 0) {
dataset[editingIndex] = record;
showAlert("Success", "Record updated successfully!", "success");
editingIndex = -1;
} else {
dataset.push(record);
showAlert("Success", "New record added!", "success");
}
saveToStorage();
resetForm();
filterAndRender(); // Re-filters and goes to page 1 or current
});
function handleSearch() {
searchTerm = document.getElementById('searchInput').value.toLowerCase();
currentPage = 1; // Reset to page 1 on search
filterAndRender();
}
function filterAndRender() {
// 1. Filter
if (!searchTerm) {
filteredDataset = dataset.map((item, index) => ({...item, originalIndex: index}));
} else {
filteredDataset = dataset
.map((item, index) => ({...item, originalIndex: index}))
.filter(item => item.input.toLowerCase().includes(searchTerm));
}
// 2. Update Stats
document.getElementById('totalCount').innerText = dataset.length;
document.getElementById('showingCount').innerText = filteredDataset.length;
// 3. Pagination Logic
const totalPages = Math.ceil(filteredDataset.length / itemsPerPage) || 1;
if (currentPage > totalPages) currentPage = totalPages;
if (currentPage < 1) currentPage = 1;
const start = (currentPage - 1) * itemsPerPage;
const end = start + itemsPerPage;
const pageData = filteredDataset.slice(start, end);
// 4. Render
renderList(pageData);
updatePaginationControls(totalPages);
}
function renderList(pageData) {
listContainer.innerHTML = '';
if (pageData.length === 0) {
listContainer.innerHTML = `
<div style="text-align:center; padding:60px; color:var(--text-muted);">
<i class="ph ph-tray" style="font-size: 3em; margin-bottom:10px;"></i><br>
No records found.
</div>`;
return;
}
pageData.forEach((item) => {
const div = document.createElement('div');
div.className = 'accordion-item';
div.id = `item-${item.originalIndex}`;
const previewText = item.input.length > 80
? item.input.substring(0, 80).replace(/\n/g, ' ') + '...'
: item.input.replace(/\n/g, ' ');
// Markdown rendering
let mdRendered = "<i>Markdown library not loaded.</i>";
let mdRaw = `### Record\n\n**Input:**\n${safeForMarkdown(item.input)}\n\n**Output:**\n${safeForMarkdown(item.output)}`;
if (typeof marked !== 'undefined') {
mdRendered = marked.parse(mdRaw);
}
div.innerHTML = `
<div class="accordion-header" onclick="toggleAccordion(${item.originalIndex})">
<div class="header-content">
<span class="id-badge">#${item.originalIndex + 1}</span>
<span class="preview-text">${escapeHtml(previewText)}</span>
</div>
<div class="header-actions">
<!-- Side Buttons (Stop Propagation) -->
<button onclick="editItem(event, ${item.originalIndex})" class="btn-secondary btn-icon" title="Edit">
<i class="ph ph-pencil-simple"></i>
</button>
<button onclick="confirmDeleteItem(event, ${item.originalIndex})" class="btn-danger btn-icon" title="Delete">
<i class="ph ph-trash"></i>
</button>
<i class="ph ph-caret-down caret-icon" style="margin-left:10px;"></i>
</div>
</div>
<div class="accordion-content">
<div class="item-tabs">
<button class="tab-btn active" onclick="switchTab(event, 'view-data-${item.originalIndex}')">Raw Data</button>
<button class="tab-btn" onclick="switchTab(event, 'view-md-${item.originalIndex}')">Rendered Markdown</button>
</div>
<div id="view-data-${item.originalIndex}" class="tab-content active">
<div class="field-label">Input</div>
<div class="data-box">${escapeHtml(item.input)}</div>
<div class="field-label">
<span>Output</span>
<button onclick="copyOutput(${item.originalIndex})" style="padding:2px 8px; font-size:0.75rem;" class="btn-secondary">
<i class="ph ph-copy"></i> Copy
</button>
</div>
<div class="data-box">${escapeHtml(item.output)}</div>
</div>
<div id="view-md-${item.originalIndex}" class="tab-content">
<div style="background:#fff; padding:20px; border:1px solid var(--border); border-radius:8px;">
${mdRendered}
</div>
</div>
</div>
`;
listContainer.appendChild(div);
});
}
// --- Actions ---
function editItem(e, index) {
e.stopPropagation(); // Don't open accordion
const item = dataset[index];
inputField.value = item.input;
outputField.value = item.output;
editingIndex = index;
saveBtn.innerHTML = '<i class="ph ph-arrows-clockwise"></i> Update Record';
saveBtn.classList.remove('btn-primary');
saveBtn.classList.add('btn-success');
cancelBtn.style.display = 'inline-flex';
formTitle.innerHTML = `<i class="ph ph-pencil-simple"></i> Editing Record #${index + 1}`;
window.scrollTo({ top: 0, behavior: 'smooth' });
inputField.focus();
}
function confirmDeleteItem(e, index) {
e.stopPropagation();
showConfirm(
"Delete Record",
"Are you sure you want to delete this record? This cannot be undone.",
() => deleteItem(index),
"Delete",
"danger"
);
}
function deleteItem(index) {
dataset.splice(index, 1);
if (editingIndex === index) resetForm();
saveToStorage();
filterAndRender();
}
function confirmDeleteAll() {
if (dataset.length === 0) return showAlert("Info", "No records to delete.");
showConfirm(
"Delete All Records",
"⚠️ Are you sure you want to delete ALL records? This action is irreversible.",
() => {
dataset = [];
resetForm();
saveToStorage();
filterAndRender();
},
"Delete All",
"danger"
);
}
function resetForm() {
form.reset();
editingIndex = -1;
saveBtn.innerHTML = '<i class="ph ph-floppy-disk"></i> Save Record';
saveBtn.classList.add('btn-primary');
saveBtn.classList.remove('btn-success');
cancelBtn.style.display = 'none';
formTitle.innerHTML = '<i class="ph ph-pencil-simple"></i> New Record';
}
cancelBtn.addEventListener('click', resetForm);
// --- JSON Import/Export ---
function downloadJSON() {
if (dataset.length === 0) return showAlert("Info", "Nothing to download.");
const dataStr = JSON.stringify(dataset, null, 4);
const blob = new Blob([dataStr], { type: "application/json;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `dataset_${new Date().toISOString().slice(0,10)}.json`;
a.click();
URL.revokeObjectURL(url);
}
function processFile(input) {
const file = input.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
try {
let importedData = JSON.parse(e.target.result);
// Handle wrapped data { data: [...] } or raw array [...]
if (!Array.isArray(importedData) && importedData.data && Array.isArray(importedData.data)) {
importedData = importedData.data;
} else if (!Array.isArray(importedData)) {
throw new Error("Invalid JSON format. Expected an array.");
}
let addedCount = 0;
// Deduplication Logic
importedData.forEach(newItem => {
if (!newItem.input && !newItem.output) return; // Skip empty
// Check if exists
const exists = dataset.some(existing =>
existing.input === newItem.input && existing.output === newItem.output
);
if (!exists) {
dataset.push({ input: newItem.input, output: newItem.output });
addedCount++;
}
});
saveToStorage();
filterAndRender();
input.value = ''; // Reset file input
if (addedCount > 0) {
showAlert("Import Successful", `Successfully imported ${addedCount} new records. Duplicates were skipped.`, "success");
} else {
showAlert("Import Info", "No new records were added. All records already existed.", "normal");
}
} catch (err) {
showAlert("Import Error", "Failed to parse JSON file. Make sure format is correct.", "danger");
console.error(err);
}
};
reader.readAsText(file);
}
// --- UI Helpers ---
function changePage(delta) {
const totalPages = Math.ceil(filteredDataset.length / itemsPerPage) || 1;
const newPage = currentPage + delta;
if (newPage >= 1 && newPage <= totalPages) {
currentPage = newPage;
filterAndRender();
window.scrollTo({ top: document.querySelector('.list-header-info').offsetTop - 20, behavior: 'smooth' });
}
}
function updatePaginationControls(totalPages) {
document.getElementById('currPageDisplay').innerText = currentPage;
document.getElementById('totalPageDisplay').innerText = totalPages;
document.getElementById('prevPageBtn').disabled = currentPage === 1;
document.getElementById('nextPageBtn').disabled = currentPage === totalPages;
// Visual disable style
document.getElementById('prevPageBtn').style.opacity = currentPage === 1 ? '0.5' : '1';
document.getElementById('nextPageBtn').style.opacity = currentPage === totalPages ? '0.5' : '1';
}
function toggleAccordion(originalIndex) {
const item = document.getElementById(`item-${originalIndex}`);
item.classList.toggle('active');
}
function switchTab(event, tabId) {
event.stopPropagation();
const contentDiv = event.target.closest('.accordion-content');
contentDiv.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
contentDiv.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
event.target.classList.add('active');
document.getElementById(tabId).classList.add('active');
}
function copyOutput(index) {
const item = dataset[index];
if(!item.output) return showAlert("Info", "Output is empty.");
copyToClipboard(item.output, "Output copied to clipboard!");
}
function copyToClipboard(text, successMsg) {
navigator.clipboard.writeText(text).then(() => {
showAlert("Success", successMsg, "success");
}).catch(err => {
// Fallback
const txt = document.createElement("textarea");
txt.value = text;
document.body.appendChild(txt);
txt.select();
document.execCommand("copy");
document.body.removeChild(txt);
showAlert("Success", successMsg, "success");
});
}
// --- Custom Modal System ---
function showModal(title, message, onConfirm, showCancel = false, confirmText = "OK", type = "primary") {
const titleEl = document.getElementById('modalTitle');
const msgEl = document.getElementById('modalMessage');
const confirmBtn = document.getElementById('modalConfirmBtn');
const cancelBtn = document.getElementById('modalCancelBtn');
titleEl.textContent = title;
msgEl.textContent = message;
confirmBtn.textContent = confirmText;
confirmBtn.className = type === 'danger' ? 'btn-danger' : 'btn-primary';
cancelBtn.style.display = showCancel ? 'block' : 'none';
// Clone buttons to remove old event listeners
const newConfirm = confirmBtn.cloneNode(true);
const newCancel = cancelBtn.cloneNode(true);
confirmBtn.parentNode.replaceChild(newConfirm, confirmBtn);
cancelBtn.parentNode.replaceChild(newCancel, cancelBtn);
newConfirm.addEventListener('click', () => {
if (onConfirm) onConfirm();
closeModal();
});
newCancel.addEventListener('click', closeModal);
modalOverlay.classList.add('open');
}
function closeModal() {
modalOverlay.classList.remove('open');
}
function showAlert(title, message, type="primary") {
showModal(title, message, null, false, "OK", type);
}
function showConfirm(title, message, onConfirm, confirmText="Confirm", type="primary") {
showModal(title, message, onConfirm, true, confirmText, type);
}
// --- Utilities ---
function safeForMarkdown(text) { return text ? text.replace(/</g, "&lt;").replace(/>/g, "&gt;") : ""; }
function escapeHtml(text) {
if (!text) return "";
return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
// --- Storage (Mantido 'jsonDatasetRender' para compatibilidade) ---
function saveToStorage() { localStorage.setItem('jsonDatasetRender', JSON.stringify(dataset)); }
function loadFromStorage() {
const saved = localStorage.getItem('jsonDatasetRender');
if (saved) dataset = JSON.parse(saved);
}
</script>
</body>
</html>