File size: 14,808 Bytes
0a32234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1305a78
0a32234
 
 
1305a78
0a32234
 
 
1305a78
0a32234
1305a78
 
 
 
0a32234
 
 
 
 
1305a78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a32234
 
1305a78
 
0a32234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1305a78
 
0a32234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22473f8
 
 
 
 
 
 
0a32234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
class DocumentTranslator {
    constructor() {
        this.currentFile = null;
        this.models = [];
        this.initializeElements();
        this.setupEventListeners();
        this.loadModels();
    }

    initializeElements() {
        this.uploadArea = document.getElementById('uploadArea');
        this.fileInput = document.getElementById('fileInput');
        this.fileInfo = document.getElementById('fileInfo');
        this.fileName = document.getElementById('fileName');
        this.fileSize = document.getElementById('fileSize');
        this.removeFile = document.getElementById('removeFile');
        this.modelSelect = document.getElementById('modelSelect');
        this.sourceLanguage = document.getElementById('sourceLanguage');
        this.targetLanguage = document.getElementById('targetLanguage');
        this.translateBtn = document.getElementById('translateBtn');
        this.progressSection = document.getElementById('progressSection');
        this.progressFill = document.getElementById('progressFill');
        this.progressText = document.getElementById('progressText');
        this.resultsSection = document.getElementById('resultsSection');
        this.reportContent = document.getElementById('reportContent');
        this.originalFileName = document.getElementById('originalFileName');
        this.translatedFileName = document.getElementById('translatedFileName');
        this.downloadOriginal = document.getElementById('downloadOriginal');
        this.downloadTranslated = document.getElementById('downloadTranslated');
        this.newTranslationBtn = document.getElementById('newTranslationBtn');
        this.errorSection = document.getElementById('errorSection');
        this.errorMessage = document.getElementById('errorMessage');
        this.retryBtn = document.getElementById('retryBtn');
        this.modelInfo = document.getElementById('modelInfo');
    }

    setupEventListeners() {
        // File upload events
        this.uploadArea.addEventListener('click', () => this.fileInput.click());
        this.uploadArea.addEventListener('dragover', this.handleDragOver.bind(this));
        this.uploadArea.addEventListener('dragleave', this.handleDragLeave.bind(this));
        this.uploadArea.addEventListener('drop', this.handleDrop.bind(this));
        this.fileInput.addEventListener('change', this.handleFileSelect.bind(this));
        
        // File removal
        this.removeFile.addEventListener('click', this.clearFile.bind(this));
        
        // Model selection
        this.modelSelect.addEventListener('change', this.updateTranslateButton.bind(this));
        
        // Translation
        this.translateBtn.addEventListener('click', this.startTranslation.bind(this));
        
        // New translation
        this.newTranslationBtn.addEventListener('click', this.resetInterface.bind(this));
        
        // Retry
        this.retryBtn.addEventListener('click', this.hideError.bind(this));
    }

    async loadModels() {
        try {
            const response = await fetch('/models');
            const data = await response.json();
            this.models = data.models;
            
            this.modelSelect.innerHTML = '';
            this.models.forEach((model, index) => {
                const option = document.createElement('option');
                option.value = model.id;
                option.textContent = `${model.name}${model.description ? ' - ' + model.description : ''}`;
                option.selected = index === 0; // Auto-select the first model
                this.modelSelect.appendChild(option);
            });
            
            // Show model selection since we have multiple models
            const modelGroup = this.modelSelect.closest('.form-group');
            if (modelGroup) {
                modelGroup.style.display = 'block';
                // Hide model info card since we're showing the selection
                this.modelInfo.style.display = 'none';
            }
            
            this.updateTranslateButton();
        } catch (error) {
            console.error('Error loading models:', error);
            // Fallback to the specified free models if API fails
            this.modelSelect.innerHTML = '';
            const fallbackModels = [
                { id: 'google/gemini-2.0-flash-exp:free', name: 'Google Gemini 2.0 Flash (Free)', description: 'Fast and free Google AI model' },
                { id: 'tngtech/deepseek-r1t2-chimera:free', name: 'DeepSeek R1T2 Chimera (Free)', description: 'Free advanced reasoning model' }
            ];
            
            fallbackModels.forEach((model, index) => {
                const option = document.createElement('option');
                option.value = model.id;
                option.textContent = `${model.name} - ${model.description}`;
                option.selected = index === 0;
                this.modelSelect.appendChild(option);
            });
            
            // Show model selection on fallback too
            const modelGroup = this.modelSelect.closest('.form-group');
            if (modelGroup) {
                modelGroup.style.display = 'block';
                this.modelInfo.style.display = 'none';
            }
            this.updateTranslateButton();
        }
    }

    handleDragOver(e) {
        e.preventDefault();
        this.uploadArea.classList.add('dragover');
    }

    handleDragLeave(e) {
        e.preventDefault();
        this.uploadArea.classList.remove('dragover');
    }

    handleDrop(e) {
        e.preventDefault();
        this.uploadArea.classList.remove('dragover');
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            this.handleFile(files[0]);
        }
    }

    handleFileSelect(e) {
        const files = e.target.files;
        if (files.length > 0) {
            this.handleFile(files[0]);
        }
    }

    handleFile(file) {
        // Validate file type
        const allowedTypes = ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
        const allowedExtensions = ['.pdf', '.docx'];
        
        const fileExtension = file.name.toLowerCase().slice(file.name.lastIndexOf('.'));
        
        if (!allowedTypes.includes(file.type) && !allowedExtensions.includes(fileExtension)) {
            this.showError('Please select a PDF or DOCX file.');
            return;
        }

        // Validate file size (max 50MB)
        if (file.size > 50 * 1024 * 1024) {
            this.showError('File size must be less than 50MB.');
            return;
        }

        this.currentFile = file;
        this.displayFileInfo(file);
        this.updateTranslateButton();
    }

    displayFileInfo(file) {
        this.fileName.textContent = file.name;
        this.fileSize.textContent = this.formatFileSize(file.size);
        this.uploadArea.style.display = 'none';
        this.fileInfo.style.display = 'flex';
    }

    clearFile() {
        this.currentFile = null;
        this.fileInput.value = '';
        this.uploadArea.style.display = 'block';
        this.fileInfo.style.display = 'none';
        this.updateTranslateButton();
    }

    updateTranslateButton() {
        const hasFile = this.currentFile !== null;
        const hasModel = this.modelSelect.value !== '';
        this.translateBtn.disabled = !hasFile; // Only check for file since model is auto-selected
    }

    async startTranslation() {
        if (!this.currentFile) {
            this.showError('Please select a file first.');
            return;
        }
        
        // Ensure model is selected (should be auto-selected)
        if (!this.modelSelect.value && this.modelSelect.options.length > 0) {
            this.modelSelect.selectedIndex = 0;
        }

        this.hideError();
        this.hideResults();
        this.showProgress();
        this.setTranslatingState(true);

        try {
            const formData = new FormData();
            formData.append('file', this.currentFile);
            formData.append('model', this.modelSelect.value);
            formData.append('source_language', this.sourceLanguage.value);
            formData.append('target_language', this.targetLanguage.value);

            this.updateProgress(20, 'Uploading file...');

            const response = await fetch('/translate', {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.detail || 'Translation failed');
            }

            this.updateProgress(90, 'Processing translation...');

            const result = await response.json();
            
            this.updateProgress(100, 'Translation complete!');
            
            setTimeout(() => {
                this.hideProgress();
                this.showResults(result);
                this.setTranslatingState(false);
            }, 1000);

        } catch (error) {
            console.error('Translation error:', error);
            this.hideProgress();
            this.setTranslatingState(false);
            
            // Handle rate limit errors specifically
            if (error.message && (error.message.includes('rate limit') || error.message.includes('429'))) {
                this.showError('Rate limit exceeded. Please try again later or switch to a different model.');
            } else {
                this.showError(error.message || 'Translation failed. Please try again.');
            }
        }
    }

    showProgress() {
        this.progressSection.style.display = 'block';
        this.progressSection.classList.add('fade-in');
        this.updateProgress(10, 'Starting translation...');
    }

    hideProgress() {
        this.progressSection.style.display = 'none';
        this.progressSection.classList.remove('fade-in');
    }

    updateProgress(percentage, text) {
        this.progressFill.style.width = `${percentage}%`;
        this.progressText.textContent = text;
    }

    showResults(result) {
        this.resultsSection.style.display = 'block';
        this.resultsSection.classList.add('fade-in');

        // Populate report
        this.reportContent.innerHTML = `
            <div class="report-item">
                <span class="report-label">Original File:</span>
                <span class="report-value">${result.original_filename}</span>
            </div>
            <div class="report-item">
                <span class="report-label">Translated File:</span>
                <span class="report-value">${result.translated_filename}</span>
            </div>
            <div class="report-item">
                <span class="report-label">Pages Processed:</span>
                <span class="report-value">${result.pages_translated}</span>
            </div>
            <div class="report-item">
                <span class="report-label">Paragraphs Translated:</span>
                <span class="report-value">${result.paragraphs_translated}</span>
            </div>
            <div class="report-item">
                <span class="report-label">Model Used:</span>
                <span class="report-value">${result.model_used}</span>
            </div>
            <div class="report-item">
                <span class="report-label">Languages:</span>
                <span class="report-value">${result.source_language}${result.target_language}</span>
            </div>
        `;

        // Setup download buttons
        this.originalFileName.textContent = result.original_filename;
        this.translatedFileName.textContent = result.translated_filename;

        if (result.files.original) {
            this.downloadOriginal.onclick = () => this.downloadFile(result.files.original, result.original_filename);
        }

        if (result.files.translated) {
            this.downloadTranslated.onclick = () => this.downloadFile(result.files.translated, result.translated_filename);
        }
    }

    hideResults() {
        this.resultsSection.style.display = 'none';
        this.resultsSection.classList.remove('fade-in');
    }

    showError(message) {
        this.errorMessage.textContent = message;
        this.errorSection.style.display = 'block';
        this.errorSection.classList.add('fade-in');
        
        // Add shake animation to upload area
        this.uploadArea.classList.add('shake');
        setTimeout(() => {
            this.uploadArea.classList.remove('shake');
        }, 500);
    }

    hideError() {
        this.errorSection.style.display = 'none';
        this.errorSection.classList.remove('fade-in');
    }

    setTranslatingState(isTranslating) {
        if (isTranslating) {
            this.translateBtn.querySelector('.btn-text').style.display = 'none';
            this.translateBtn.querySelector('.btn-spinner').style.display = 'inline';
            this.translateBtn.disabled = true;
        } else {
            this.translateBtn.querySelector('.btn-text').style.display = 'inline';
            this.translateBtn.querySelector('.btn-spinner').style.display = 'none';
            this.updateTranslateButton();
        }
    }

    async downloadFile(filePath, filename) {
        try {
            const response = await fetch(`/download/${filePath}`);
            if (!response.ok) {
                throw new Error('Download failed');
            }

            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        } catch (error) {
            console.error('Download error:', error);
            this.showError('Failed to download file. Please try again.');
        }
    }

    resetInterface() {
        this.clearFile();
        this.hideResults();
        this.hideError();
        this.hideProgress();
        this.modelSelect.selectedIndex = 0;
        this.sourceLanguage.selectedIndex = 0;
        this.targetLanguage.selectedIndex = 0;
        this.updateTranslateButton();
    }

    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 the application when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new DocumentTranslator();
});