File size: 8,414 Bytes
02efbd4
 
 
 
 
 
 
 
 
 
3bb55a6
b17d8bf
02efbd4
 
5d570c5
 
 
 
 
7f4d6ac
5d570c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f4d6ac
5d570c5
02efbd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bb55a6
02efbd4
 
ec41997
f742657
 
 
 
7f4d6ac
ec41997
 
 
 
7f4d6ac
f742657
 
 
7f4d6ac
 
f742657
ec41997
 
 
 
 
 
 
 
 
 
f742657
050f2a9
 
 
f742657
 
 
 
 
 
 
 
 
 
 
 
 
ec41997
f742657
050f2a9
 
 
f742657
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec41997
 
 
 
 
f742657
 
 
 
 
 
ec41997
 
 
 
b17d8bf
f742657
 
02efbd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bb55a6
 
02efbd4
 
 
 
 
 
 
7f4d6ac
 
 
 
 
 
 
 
 
 
02efbd4
 
7f4d6ac
 
 
 
 
 
3bb55a6
 
 
 
 
 
02efbd4
 
 
 
7f4d6ac
 
 
02efbd4
 
 
 
 
 
 
3bb55a6
 
02efbd4
 
 
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
document.addEventListener('DOMContentLoaded', () => {
    const textForm = document.getElementById('text-translation-form');
    const docForm = document.getElementById('doc-translation-form');
    const textResultBox = document.getElementById('text-result');
    const textOutput = document.getElementById('text-output');
    const docResultBox = document.getElementById('doc-result');
    const docOutput = document.getElementById('doc-output');
    const docFilename = document.getElementById('doc-filename');
    const docSourceLang = document.getElementById('doc-source-lang');
    const errorMessageDiv = document.getElementById('error-message');
    const docLoadingIndicator = document.getElementById('doc-loading');
    
    // Helper function to display errors
    function displayError(message) {
        let errorText = 'Error: ';
        
        if (message === undefined || message === null) {
            errorText += 'Unknown error occurred';
        } else if (typeof message === 'object') {
            // Improved error object handling
            if (message.message) {
                errorText += message.message;
            } else if (message.detail) {
                errorText += message.detail;
            } else if (message.error) {
                errorText += message.error;
            } else {
                try {
                    errorText += JSON.stringify(message);
                } catch (e) {
                    errorText += 'Unable to display error details';
                }
            }
        } else {
            errorText += message;
        }
        
        console.error("Error details:", message);
        errorMessageDiv.textContent = errorText;
        errorMessageDiv.style.display = 'block';
        // Hide result boxes on error
        textResultBox.style.display = 'none';
        docResultBox.style.display = 'none';
    }

    // Helper function to clear errors and results
    function clearFeedback() {
        errorMessageDiv.style.display = 'none';
        errorMessageDiv.textContent = '';
        textResultBox.style.display = 'none';
        textOutput.textContent = '';
        docResultBox.style.display = 'none';
        docOutput.textContent = '';
        docFilename.textContent = '';
        docSourceLang.textContent = '';
        docLoadingIndicator.style.display = 'none';
    }

    // Fix the text form submission handler to use correct field IDs
    if (textForm) {
        textForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            clearFeedback();
            
            // Use correct field IDs matching the HTML
            const sourceText = document.getElementById('text-input').value.trim();
            const sourceLang = document.getElementById('source-lang-text').value;
            const targetLang = document.getElementById('target-lang-text').value;
            
            if (!sourceText) {
                displayError('Please enter text to translate');
                return;
            }
            
            try {
                // Show loading state (create it if missing)
                let textLoading = document.getElementById('text-loading');
                if (!textLoading) {
                    textLoading = document.createElement('div');
                    textLoading.id = 'text-loading';
                    textLoading.className = 'loading-spinner';
                    textLoading.innerHTML = 'Translating...';
                    textForm.appendChild(textLoading);
                }
                textLoading.style.display = 'block';
                
                // Log payload for debugging
                console.log('Sending payload:', { text: sourceText, source_lang: sourceLang, target_lang: targetLang });
                
                const response = await fetch('/translate/text', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        text: sourceText,
                        source_lang: sourceLang,
                        target_lang: targetLang
                    })
                });
                
                // Hide loading state
                textLoading.style.display = 'none';
                
                // Log response status
                console.log('Response status:', response.status);
                
                const data = await response.json();
                
                if (!response.ok) {
                    if (data && data.error) {
                        displayError(data.error);
                    } else {
                        displayError(`Server error: ${response.status}`);
                    }
                    return;
                }
                
                if (!data.success && data.error) {
                    displayError(data.error);
                    return;
                }
                
                if (!data.translated_text) {
                    displayError('Translation returned empty text');
                    return;
                }
                
                textOutput.textContent = data.translated_text;
                textResultBox.style.display = 'block';
                
            } catch (error) {
                console.error('Error:', error);
                displayError('Network error or invalid response format');
                
                // Hide loading if it exists
                const textLoading = document.getElementById('text-loading');
                if (textLoading) textLoading.style.display = 'none';
            }
        });
    }

    // Handle Document Translation Form Submission
    docForm.addEventListener('submit', async (event) => {
        event.preventDefault();
        clearFeedback();

        const formData = new FormData(docForm);
        const fileInput = document.getElementById('doc-input');
        const button = docForm.querySelector('button');

        if (!fileInput.files || fileInput.files.length === 0) {
            displayError('Please select a document to upload.');
            return;
        }

        button.disabled = true;
        button.textContent = 'Translating...';
        // Show loading indicator
        docLoadingIndicator.style.display = 'block';

        try {
            const response = await fetch('/translate/document', {
                method: 'POST',
                body: formData // FormData handles multipart/form-data automatically
            });

            // Get response as text first for debugging
            const responseText = await response.text();
            console.log('Raw document response:', responseText);
            
            // Try to parse as JSON
            let result;
            try {
                result = JSON.parse(responseText);
            } catch (jsonError) {
                throw new Error(`Failed to parse server response: ${responseText}`);
            }

            if (!response.ok) {
                const errorMessage = result.error || result.detail || `HTTP error! status: ${response.status}`;
                throw new Error(errorMessage);
            }
            
            console.log('Document translation response:', result);
            
            // Check if result contains the expected fields
            if (!result.translated_text) {
                throw new Error('Translation response is missing translated text');
            }
            
            docFilename.textContent = result.original_filename || 'N/A';
            docSourceLang.textContent = result.detected_source_lang || 'N/A';
            docOutput.textContent = result.translated_text;
            docResultBox.style.display = 'block';
            
            // Set text direction based on target language (document always goes to Arabic)
            docOutput.dir = 'rtl';

        } catch (error) {
            console.error('Document translation error:', error);
            displayError(error.message || 'An unexpected error occurred during document translation.');
        } finally {
            button.disabled = false;
            button.textContent = 'Translate Document';
            // Hide loading indicator
            docLoadingIndicator.style.display = 'none';
        }
    });
});