File size: 10,826 Bytes
9bd422a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
329
330
331
332
333
334
335
336
337
/**
 * FileUploadHandler - Handles ONNX file uploads via button click and drag-and-drop
 * Requirements: 3.1, 3.2, 3.3, 3.4, 3.5, 3.6
 */

class FileUploadHandler {
  /**
   * @param {string} [uploadBtnId='uploadBtn']   - ID of the upload button
   * @param {string} [fileInputId='fileInput']   - ID of the hidden file input
   * @param {string} [dropZoneId='app']          - ID of the drag-and-drop zone
   */
  constructor(uploadBtnId = 'uploadBtn', fileInputId = 'fileInput', dropZoneId = 'app') {
    this._uploadBtn  = document.getElementById(uploadBtnId);
    this._fileInput  = document.getElementById(fileInputId);
    this._dropZone   = document.getElementById(dropZoneId);
    this._errorContainer = document.getElementById('errorContainer');

    this._dragCounter = 0; // track nested dragenter/dragleave

    if (!this._uploadBtn) {
      console.warn(`[FileUploadHandler] Upload button #${uploadBtnId} not found`);
    }
    if (!this._fileInput) {
      console.warn(`[FileUploadHandler] File input #${fileInputId} not found`);
    }

    this._bindEvents();
  }

  // ─── Private ──────────────────────────────────────────────────────────────

  _bindEvents() {
    // Button click β†’ open file dialog
    if (this._uploadBtn) {
      this._uploadBtn.addEventListener('click', () => {
        if (this._fileInput) this._fileInput.click();
      });
    }

    // File input change
    if (this._fileInput) {
      this._fileInput.addEventListener('change', (e) => {
        const file = e.target.files && e.target.files[0];
        if (file) this._processFile(file);
        // Reset so the same file can be re-selected
        e.target.value = '';
      });
    }

    // Drag-and-drop on drop zone
    if (this._dropZone) {
      this._dropZone.addEventListener('dragenter', (e) => this._onDragEnter(e));
      this._dropZone.addEventListener('dragleave', (e) => this._onDragLeave(e));
      this._dropZone.addEventListener('dragover',  (e) => this._onDragOver(e));
      this._dropZone.addEventListener('drop',      (e) => this._onDrop(e));
    }
  }

  _onDragEnter(e) {
    e.preventDefault();
    e.stopPropagation();
    this._dragCounter++;
    if (this._dropZone) this._dropZone.classList.add('drag-over');
  }

  _onDragLeave(e) {
    e.preventDefault();
    e.stopPropagation();
    this._dragCounter--;
    if (this._dragCounter <= 0) {
      this._dragCounter = 0;
      if (this._dropZone) this._dropZone.classList.remove('drag-over');
    }
  }

  _onDragOver(e) {
    e.preventDefault();
    e.stopPropagation();
    if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';
  }

  _onDrop(e) {
    e.preventDefault();
    e.stopPropagation();
    this._dragCounter = 0;
    if (this._dropZone) this._dropZone.classList.remove('drag-over');

    const files = e.dataTransfer && e.dataTransfer.files;
    if (files && files.length > 0) {
      this._processFile(files[0]);
    }
  }

  /**
   * Validate and process a File object.
   * @param {File} file
   */
  async _processFile(file) {
    // Validate extension
    const name = file.name || '';
    const hasValidExt = CONFIG.FILE.ALLOWED_EXTENSIONS.some(ext =>
      name.toLowerCase().endsWith(ext)
    );

    if (!hasValidExt) {
      // Detect PyTorch .pt/.pth files and show conversion guide
      if (name.toLowerCase().endsWith('.pt') || name.toLowerCase().endsWith('.pth')) {
        this._showPtConversionGuide(name);
        return;
      }
      const allowed = CONFIG.FILE.ALLOWED_EXTENSIONS.join(', ');
      this._showError(
        `Invalid file type "${name}". Only ${allowed} files are supported.`
      );
      return;
    }

    // Check for conversion-guide formats (e.g. .h5, .keras, .pb, .mlmodel, etc.)
    if (window.ConversionGuideManager) {
      const cgm = new ConversionGuideManager();
      if (cgm.isConversionFormat(name)) {
        cgm.showGuide(name);
        return; // Don't emit FILE_UPLOADED
      }
    }

    // Validate empty file
    if (file.size === 0) {
      this._showError('The file is empty.');
      return;
    }

    // Show progress indicator
    this._showProgress(`Reading "${name}"…`);

    try {
      // Delegate reading + validation to ModelLoader
      const loader = window.ModelLoader ? new window.ModelLoader() : null;
      let result;

      if (loader) {
        result = await loader.handleFileUpload(file);
      } else {
        // Fallback: read directly
        const data = await this._readFileAsArrayBuffer(file);
        result = { success: true, data };
      }

      if (!result.success) {
        this._showError(result.error || CONFIG.ERRORS.UPLOAD_ERROR);
        return;
      }

      // Clear progress
      this._clearMessages();

      // Emit FILE_UPLOADED event
      if (window.EventBus) {
        window.EventBus.emit(CONFIG.EVENTS.FILE_UPLOADED, {
          file,
          data: result.data,
          fileName: name
        });
      }

      // Update StateManager loading state if available
      if (window.StateManager) {
        window.StateManager.setLoading(false);
      }

    } catch (err) {
      console.error('[FileUploadHandler] Upload error:', err);
      this._showError(err.message || CONFIG.ERRORS.UPLOAD_ERROR);
    }
  }

  /**
   * Read a File as ArrayBuffer.
   * @param {File} file
   * @returns {Promise<ArrayBuffer>}
   */
  _readFileAsArrayBuffer(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload  = (e) => resolve(e.target.result);
      reader.onerror = ()  => reject(new Error(reader.error ? reader.error.message : 'FileReader error'));
      reader.readAsArrayBuffer(file);
    });
  }

  /**
   * Show a conversion guide when user uploads a PyTorch .pt/.pth file.
   * @param {string} fileName
   */
  _showPtConversionGuide(fileName) {
    if (!this._errorContainer) return;

    this._errorContainer.innerHTML = '';
    const div = document.createElement('div');
    div.className = 'alert alert-warning alert-dismissible fade show';
    div.setAttribute('role', 'alert');
    div.innerHTML = `
      <div class="d-flex align-items-start">
        <i class="fas fa-exchange-alt me-3 mt-1 fs-4 text-warning"></i>
        <div class="flex-grow-1">
          <h6 class="alert-heading mb-2">
            <i class="fas fa-file-code me-1"></i>
            Tệp PyTorch (.pt) khΓ΄ng được hα»— trợ trα»±c tiαΊΏp
          </h6>
          <p class="mb-2">
            Tệp <strong>"${this._escapeHtml(fileName)}"</strong> lΓ  Δ‘α»‹nh dαΊ‘ng PyTorch. 
            Vui lΓ²ng convert sang <strong>.onnx</strong> hoαΊ·c <strong>.safetensors</strong> trΖ°α»›c khi upload.
          </p>
          <hr class="my-2">
          <p class="mb-1 fw-bold"><i class="fas fa-code me-1"></i> Convert PyTorch β†’ ONNX:</p>
          <pre class="bg-dark text-light p-2 rounded small mb-2" style="white-space:pre-wrap;"><code>import torch

model = torch.load("model.pt", map_location="cpu")
model.eval()

# TαΊ‘o dummy input phΓΉ hợp vα»›i model
dummy_input = torch.randn(1, 3, 224, 224)

torch.onnx.export(
    model, dummy_input, "model.onnx",
    input_names=["input"],
    output_names=["output"],
    dynamic_axes={"input": {0: "batch"}, "output": {0: "batch"}}
)</code></pre>
          <p class="mb-1 fw-bold"><i class="fas fa-code me-1"></i> Convert PyTorch β†’ SafeTensors:</p>
          <pre class="bg-dark text-light p-2 rounded small mb-2" style="white-space:pre-wrap;"><code>from safetensors.torch import save_file
import torch

state_dict = torch.load("model.pt", map_location="cpu")
# NαΊΏu lΓ  model Δ‘αΊ§y Δ‘α»§ (khΓ΄ng phαΊ£i state_dict):
# state_dict = model.state_dict()

save_file(state_dict, "model.safetensors")</code></pre>
          <p class="mb-0 text-muted small">
            <i class="fas fa-info-circle me-1"></i>
            CΓ i Δ‘αΊ·t: <code>pip install torch onnx safetensors</code>
          </p>
        </div>
      </div>
      <button type="button" class="btn-close" aria-label="Close"
        onclick="this.closest('.alert').remove()"></button>
    `;
    this._errorContainer.appendChild(div);
  }

  /**
   * Display an error message in #errorContainer.
   * @param {string} message
   */
  _showError(message) {
    if (window.ErrorDisplay && window.ErrorDisplay.show) {
      window.ErrorDisplay.show(message, 'error');
      return;
    }
    if (!this._errorContainer) return;

    const div = document.createElement('div');
    div.className = 'alert alert-danger alert-dismissible fade show';
    div.setAttribute('role', 'alert');
    div.innerHTML = `
      <i class="fas fa-exclamation-circle me-2"></i>${this._escapeHtml(message)}
      <button type="button" class="btn-close" aria-label="Close"
        onclick="this.closest('.alert').remove()"></button>
    `;
    this._errorContainer.innerHTML = '';
    this._errorContainer.appendChild(div);

    // Auto-dismiss
    setTimeout(() => {
      if (div.parentElement) div.remove();
    }, CONFIG.UI.ERROR_DISPLAY_DURATION);
  }

  /**
   * Display a progress/info message in #errorContainer.
   * @param {string} message
   */
  _showProgress(message) {
    if (!this._errorContainer) return;

    const div = document.createElement('div');
    div.className = 'alert alert-info d-flex align-items-center';
    div.setAttribute('role', 'status');
    div.id = 'fileUploadProgress';
    div.innerHTML = `
      <span class="spinner-border spinner-border-sm me-2" aria-hidden="true"></span>
      ${this._escapeHtml(message)}
    `;
    this._errorContainer.innerHTML = '';
    this._errorContainer.appendChild(div);
  }

  /**
   * Clear any progress/error messages.
   */
  _clearMessages() {
    if (this._errorContainer) this._errorContainer.innerHTML = '';
  }

  /**
   * Escape HTML to prevent XSS.
   * @param {string} str
   * @returns {string}
   */
  _escapeHtml(str) {
    const div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
  }

  // ─── Public API ───────────────────────────────────────────────────────────

  /**
   * Programmatically trigger the file dialog.
   */
  openFileDialog() {
    if (this._fileInput) this._fileInput.click();
  }

  /**
   * Destroy the handler and remove event listeners.
   * (Useful for cleanup in SPA-style navigation.)
   */
  destroy() {
    // Listeners are attached to DOM elements; removing the elements cleans them up.
    // For explicit cleanup, re-bind with AbortController in future refactors.
  }
}

// Export as global for browser usage
window.FileUploadHandler = FileUploadHandler;