Spaces:
Sleeping
Sleeping
File size: 9,158 Bytes
89a0490 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | // ── State ──────────────────────────────────────────────────────────────────
let currentFile = null;
let lastJSON = null;
// ── File Input ─────────────────────────────────────────────────────────────
const fileInput = document.getElementById('file-input');
const dropZone = document.getElementById('drop-zone');
fileInput.addEventListener('change', e => handleFile(e.target.files[0]));
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('drag-over'); });
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
dropZone.addEventListener('drop', e => {
e.preventDefault();
dropZone.classList.remove('drag-over');
const f = e.dataTransfer.files[0];
if (f) handleFile(f);
});
dropZone.addEventListener('click', (e) => {
if (e.target !== fileInput) {
fileInput.click();
}
});
function handleFile(file) {
if (!file || !file.type.startsWith('image/')) {
showToast('⚠️ Vui lòng chọn file ảnh!', true); return;
}
currentFile = file;
// Preview
const reader = new FileReader();
reader.onload = e => {
document.getElementById('preview-img').src = e.target.result;
document.getElementById('preview-name').textContent =
`${file.name} · ${(file.size / 1024).toFixed(1)} KB`;
document.getElementById('preview-wrap').style.display = 'block';
};
reader.readAsDataURL(file);
document.getElementById('btn-predict').disabled = false;
}
// ── Predict ────────────────────────────────────────────────────────────────
async function runPredict() {
if (!currentFile) return;
setLoading(true);
const formData = new FormData();
formData.append('image', currentFile);
formData.append('conf', document.getElementById('conf-slider').value);
formData.append('iou', document.getElementById('iou-slider').value);
try {
const res = await fetch('/predict', { method: 'POST', body: formData });
const data = await res.json();
if (!res.ok || data.error) {
throw new Error(data.error || 'Lỗi server');
}
// ① Update annotated image
const resImg = document.getElementById('result-img');
resImg.src = `data:image/jpeg;base64,${data.image_b64}`;
resImg.style.display = 'block';
document.getElementById('placeholder').style.display = 'none';
// ② Stats bar
document.getElementById('stat-time').textContent = `${data.inference_time_ms} ms`;
document.getElementById('stat-count').textContent = `${data.total_detections} vật thể`;
document.getElementById('stats-bar').style.display = 'flex';
// ③ JSON
lastJSON = data;
updateOCRPanel(data.detections);
const displayDetections = data.detections.map(d => {
const copy = { ...d };
delete copy.crop_b64;
return copy;
});
const finalJSON = {
image: data.filename || "unknown.jpg",
objects: displayDetections
};
document.getElementById('json-output').innerHTML = syntaxHighlight(JSON.stringify(finalJSON, null, 2));
showToast(`✅ Phát hiện ${data.total_detections} vật thể · ${data.inference_time_ms}ms`);
} catch (err) {
showToast('❌ ' + err.message, true);
document.getElementById('json-output').textContent = `// Lỗi: ${err.message}`;
} finally {
setLoading(false);
}
}
// ── Helpers ────────────────────────────────────────────────────────────────
function setLoading(on) {
document.getElementById('spinner').style.display = on ? 'block' : 'none';
document.getElementById('btn-text').textContent = on ? 'Đang xử lý...' : '⚡ Nhận diện';
document.getElementById('btn-predict').disabled = on;
}
function syntaxHighlight(json) {
return json.replace(
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
match => {
let cls = 'j-num';
if (/^"/.test(match)) {
cls = /:$/.test(match) ? 'j-key' : 'j-str';
} else if (/true|false/.test(match)) {
cls = 'j-bool';
} else if (/null/.test(match)) {
cls = 'j-null';
}
return `<span class="${cls}">${match}</span>`;
}
);
}
function updateOCRPanel(detections) {
const ocrOutput = document.getElementById('ocr-output');
const ocrItems = detections.map((item, index) => ({
id: index + 1,
className: item.class,
text: item.ocr_content ? item.ocr_content.trim() : "",
crop: item.crop_image,
crop_b64: item.crop_b64
}));
if (ocrItems.length === 0) {
ocrOutput.innerHTML = '<p>Không tìm thấy đối tượng nào.</p>';
return;
}
ocrOutput.innerHTML = ocrItems.map(item => `
<div class="ocr-card" style="margin-bottom: 12px; border: 1px solid #eee; padding: 10px; border-radius: 8px; background: #fafafa;">
<div class="ocr-card-header" style="display: flex; justify-content: space-between; align-items: center; font-weight: 600; margin-bottom: 8px; color: #444;">
<span>${item.className} #${item.id}</span>
${item.crop_b64 ? `<a href="javascript:void(0)" onclick="downloadCrop(${item.id})" style="font-size: 13px; color: #0066cc; text-decoration: none; border: 1px solid #0066cc; padding: 4px 8px; border-radius: 4px;">⬇ Tải Ảnh Cắt</a>` : ''}
</div>
${item.text ? `<div class="ocr-card-body" style="white-space: pre-wrap; font-size: 14px; color: #222; background: #fff; padding: 8px; border-radius: 4px; border: 1px solid #ddd;">${escapeHtml(item.text)}</div>` : ''}
</div>
`).join('');
}
function downloadCrop(id) {
if (!lastJSON || !lastJSON.detections) return;
const item = lastJSON.detections.find(d => d.id === id);
if (!item || !item.crop_b64) return;
try {
const byteCharacters = atob(item.crop_b64);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: 'image/jpeg'});
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = item.crop_image || `crop_${id}.jpg`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
showToast('⬇ Đã tải ảnh cắt!');
} catch (err) {
showToast('❌ Lỗi tải ảnh!', true);
console.error(err);
}
}
function escapeHtml(value) {
return value
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function copyJSON() {
if (!lastJSON) { showToast('Chưa có kết quả!', true); return; }
const displayDetections = lastJSON.detections.map(d => {
const copy = { ...d };
delete copy.crop_b64;
return copy;
});
const finalJSON = {
image: lastJSON.filename || "unknown.jpg",
objects: displayDetections
};
navigator.clipboard.writeText(JSON.stringify(finalJSON, null, 2));
showToast('📋 Đã copy JSON!');
}
function downloadJSON() {
if (!lastJSON) { showToast('Chưa có kết quả!', true); return; }
const displayDetections = lastJSON.detections.map(d => {
const copy = { ...d };
delete copy.crop_b64;
return copy;
});
const finalJSON = {
image: lastJSON.filename || "unknown.jpg",
objects: displayDetections
};
const blob = new Blob([JSON.stringify(finalJSON, null, 2)], { type: 'application/json' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `rtdetr_result_${Date.now()}.json`;
a.click();
showToast('⬇ Đã tải JSON!');
}
function clearAll() {
currentFile = null; lastJSON = null;
document.getElementById('preview-wrap').style.display = 'none';
document.getElementById('result-img').style.display = 'none';
document.getElementById('placeholder').style.display = 'flex';
document.getElementById('stats-bar').style.display = 'none';
document.getElementById('json-output').textContent = '// Chạy nhận diện để xem kết quả JSON ở đây...';
document.getElementById('ocr-output').innerHTML = '<p>Các đối tượng được cắt (Crops) và nội dung OCR sẽ hiển thị ở đây.</p>';
document.getElementById('btn-predict').disabled = true;
fileInput.value = '';
}
function showToast(msg, isError = false) {
const t = document.getElementById('toast');
t.textContent = msg;
t.className = isError ? 'error' : '';
t.classList.add('show');
setTimeout(() => t.classList.remove('show'), 3000);
}
|