Spaces:
Paused
Paused
File size: 10,924 Bytes
89ba751 |
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 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
/**
* File Upload Handler for Legal Dashboard
* Manages document uploads, OCR processing, and real-time progress
*/
class FileUploadHandler {
constructor() {
this.uploadEndpoint = '/api/ocr/upload';
this.processEndpoint = '/api/ocr/process';
this.maxFileSize = 10 * 1024 * 1024; // 10MB
this.allowedTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/tiff'];
this.currentUpload = null;
this.uploadQueue = [];
this.initializeEventListeners();
}
initializeEventListeners() {
// File input change
const fileInput = document.getElementById('documentUpload');
if (fileInput) {
fileInput.addEventListener('change', (e) => this.handleFileSelection(e));
}
// Upload button
const uploadBtn = document.getElementById('uploadButton');
if (uploadBtn) {
uploadBtn.addEventListener('click', () => this.startUpload());
}
// Drag and drop
const dropZone = document.getElementById('uploadDropZone');
if (dropZone) {
dropZone.addEventListener('dragover', (e) => this.handleDragOver(e));
dropZone.addEventListener('drop', (e) => this.handleDrop(e));
dropZone.addEventListener('dragleave', (e) => this.handleDragLeave(e));
}
}
handleFileSelection(event) {
const files = event.target.files;
if (files.length > 0) {
this.validateAndQueueFiles(files);
}
}
handleDragOver(event) {
event.preventDefault();
event.currentTarget.classList.add('drag-over');
}
handleDragLeave(event) {
event.preventDefault();
event.currentTarget.classList.remove('drag-over');
}
handleDrop(event) {
event.preventDefault();
event.currentTarget.classList.remove('drag-over');
const files = event.dataTransfer.files;
if (files.length > 0) {
this.validateAndQueueFiles(files);
}
}
validateAndQueueFiles(files) {
const validFiles = [];
const errors = [];
for (let file of files) {
// Check file size
if (file.size > this.maxFileSize) {
errors.push(`${file.name}: File too large (max 10MB)`);
continue;
}
// Check file type
if (!this.allowedTypes.includes(file.type)) {
errors.push(`${file.name}: Unsupported file type`);
continue;
}
validFiles.push(file);
}
// Show errors if any
if (errors.length > 0) {
this.showErrors(errors);
}
// Queue valid files
if (validFiles.length > 0) {
this.uploadQueue.push(...validFiles);
this.updateUploadQueue();
}
}
updateUploadQueue() {
const queueContainer = document.getElementById('uploadQueue');
if (!queueContainer) return;
if (this.uploadQueue.length === 0) {
queueContainer.innerHTML = '<p class="no-files">هیچ فایلی برای آپلود انتخاب نشده</p>';
return;
}
const queueHTML = this.uploadQueue.map((file, index) => `
<div class="queue-item" data-index="${index}">
<div class="file-info">
<span class="file-name">${file.name}</span>
<span class="file-size">${this.formatFileSize(file.size)}</span>
</div>
<div class="file-actions">
<button class="remove-file" onclick="fileUploadHandler.removeFromQueue(${index})">
<i class="fas fa-times"></i>
</button>
</div>
</div>
`).join('');
queueContainer.innerHTML = queueHTML;
}
removeFromQueue(index) {
this.uploadQueue.splice(index, 1);
this.updateUploadQueue();
}
async startUpload() {
if (this.uploadQueue.length === 0) {
this.showToast('لطفاً فایلی برای آپلود انتخاب کنید', 'warning');
return;
}
if (this.currentUpload) {
this.showToast('آپلود در حال انجام است، لطفاً صبر کنید', 'warning');
return;
}
this.currentUpload = true;
this.showUploadProgress();
try {
for (let i = 0; i < this.uploadQueue.length; i++) {
const file = this.uploadQueue[i];
await this.uploadFile(file, i + 1, this.uploadQueue.length);
}
this.showToast('تمام فایلها با موفقیت آپلود شدند', 'success');
this.refreshDocumentsList();
} catch (error) {
this.showToast(`خطا در آپلود: ${error.message}`, 'error');
} finally {
this.currentUpload = false;
this.hideUploadProgress();
this.uploadQueue = [];
this.updateUploadQueue();
}
}
async uploadFile(file, current, total) {
return new Promise((resolve, reject) => {
const formData = new FormData();
formData.append('file', file);
formData.append('filename', file.name);
const xhr = new XMLHttpRequest();
// Progress tracking
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
this.updateProgress(percentComplete, current, total);
}
});
// Response handling
xhr.addEventListener('load', () => {
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
this.handleUploadSuccess(response, file);
resolve(response);
} catch (error) {
reject(new Error('Invalid response format'));
}
} else {
reject(new Error(`Upload failed: ${xhr.status} ${xhr.statusText}`));
}
});
xhr.addEventListener('error', () => {
reject(new Error('Network error during upload'));
});
xhr.addEventListener('abort', () => {
reject(new Error('Upload cancelled'));
});
// Start upload
xhr.open('POST', this.uploadEndpoint);
xhr.send(formData);
});
}
handleUploadSuccess(response, file) {
// Update dashboard stats
this.updateDashboardStats();
// Show success message
this.showToast(`${file.name} با موفقیت آپلود شد`, 'success');
// Process OCR if needed
if (response.document_id) {
this.processOCR(response.document_id, file.name);
}
}
async processOCR(documentId, fileName) {
try {
const response = await fetch(this.processEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
document_id: documentId,
filename: fileName
})
});
if (!response.ok) {
throw new Error(`OCR processing failed: ${response.status}`);
}
const result = await response.json();
this.showOCRResult(result, fileName);
} catch (error) {
this.showToast(`خطا در پردازش OCR: ${error.message}`, 'error');
}
}
showOCRResult(result, fileName) {
const ocrResultsContainer = document.getElementById('ocrResults');
if (!ocrResultsContainer) return;
const resultHTML = `
<div class="ocr-result">
<h4>نتایج OCR - ${fileName}</h4>
<div class="ocr-content">
<p><strong>کیفیت:</strong> ${(result.quality || 0).toFixed(2)}%</p>
<p><strong>متن استخراج شده:</strong></p>
<div class="extracted-text">
${result.text || 'متنی استخراج نشد'}
</div>
</div>
</div>
`;
ocrResultsContainer.insertAdjacentHTML('afterbegin', resultHTML);
}
updateProgress(percent, current, total) {
const progressBar = document.getElementById('uploadProgressBar');
const progressText = document.getElementById('uploadProgressText');
if (progressBar) {
progressBar.style.width = `${percent}%`;
}
if (progressText) {
progressText.textContent = `آپلود فایل ${current} از ${total} (${Math.round(percent)}%)`;
}
}
showUploadProgress() {
const progressContainer = document.getElementById('uploadProgress');
if (progressContainer) {
progressContainer.style.display = 'block';
}
}
hideUploadProgress() {
const progressContainer = document.getElementById('uploadProgress');
if (progressContainer) {
progressContainer.style.display = 'none';
}
}
updateDashboardStats() {
// Trigger dashboard stats refresh
if (typeof loadDashboardStats === 'function') {
loadDashboardStats();
}
}
refreshDocumentsList() {
// Trigger documents list refresh
if (typeof loadDocumentsList === 'function') {
loadDocumentsList();
}
}
showErrors(errors) {
const errorMessage = errors.join('\n');
this.showToast(errorMessage, 'error');
}
showToast(message, type = 'info') {
if (typeof showToast === 'function') {
showToast(message, type);
} else {
console.log(`${type.toUpperCase()}: ${message}`);
}
}
formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
}
// Initialize file upload handler
const fileUploadHandler = new FileUploadHandler(); |