amine_dubs commited on
Commit
bf7a078
·
1 Parent(s): 9b675a2
Files changed (1) hide show
  1. static/script.js +177 -211
static/script.js CHANGED
@@ -1,266 +1,232 @@
1
  document.addEventListener('DOMContentLoaded', () => {
2
- // Log when the page loads to confirm JavaScript is working
3
  console.log("Translation app initialized");
4
 
5
- // Get references to main form elements
6
  const textForm = document.getElementById('text-translation-form');
7
  const docForm = document.getElementById('doc-translation-form');
8
- const textResultBox = document.getElementById('text-result');
9
- const textOutput = document.getElementById('text-output');
10
- const docResultBox = document.getElementById('doc-result');
11
- const docOutput = document.getElementById('doc-output');
12
- const docFilename = document.getElementById('doc-filename');
13
- const docSourceLang = document.getElementById('doc-source-lang');
14
- const errorMessageDiv = document.getElementById('error-message');
15
- const docLoadingIndicator = document.getElementById('doc-loading');
16
- const debugInfoDiv = document.getElementById('debug-info');
17
- const textLoadingDiv = document.getElementById('text-loading');
18
 
19
- // Helper function for debugging
20
- function showDebug(message, data = null) {
21
- let debugText = typeof message === 'string' ? message : JSON.stringify(message);
22
- if (data) {
23
- debugText += '\n' + JSON.stringify(data, null, 2);
24
- }
25
- console.log("DEBUG:", message, data || '');
26
- if (debugInfoDiv) {
27
- debugInfoDiv.textContent = debugText;
28
- debugInfoDiv.style.display = 'block';
29
  }
30
  }
31
 
32
- // Helper function to display errors
33
- function displayError(message) {
34
- let errorText = 'Error: ';
35
- if (message === undefined || message === null) {
36
- errorText += 'Unknown error occurred';
37
- } else if (typeof message === 'object') {
38
- if (message.message) {
39
- errorText += message.message;
40
- } else if (message.detail) {
41
- errorText += message.detail;
42
- } else if (message.error) {
43
- errorText += message.error;
44
- } else {
45
- try {
46
- errorText += JSON.stringify(message);
47
- } catch (e) {
48
- errorText += 'Unable to display error details';
49
- }
50
- }
51
- } else {
52
- errorText += message;
53
- }
54
-
55
- console.error("Error details:", message);
56
- if (errorMessageDiv) {
57
- errorMessageDiv.textContent = errorText;
58
- errorMessageDiv.style.display = 'block';
59
- if (textResultBox) textResultBox.style.display = 'none';
60
- if (docResultBox) docResultBox.style.display = 'none';
61
- } else {
62
- alert("Error: " + errorText);
63
  }
64
  }
65
-
66
- // Helper function to clear errors and results
67
  function clearFeedback() {
68
- if (errorMessageDiv) {
69
- errorMessageDiv.style.display = 'none';
70
- errorMessageDiv.textContent = '';
71
- }
72
- if (textResultBox) {
73
- textResultBox.style.display = 'none';
74
- if (textOutput) textOutput.textContent = '';
75
- }
76
- if (docResultBox) {
77
- docResultBox.style.display = 'none';
78
- if (docOutput) docOutput.textContent = '';
79
- if (docFilename) docFilename.textContent = '';
80
- if (docSourceLang) docSourceLang.textContent = '';
81
- }
82
- if (docLoadingIndicator) docLoadingIndicator.style.display = 'none';
83
- if (debugInfoDiv) {
84
- debugInfoDiv.style.display = 'none';
85
- debugInfoDiv.textContent = '';
86
- }
87
  }
88
-
89
- // Text translation form handler
90
  if (textForm) {
91
- textForm.addEventListener('submit', async function(e) {
92
  e.preventDefault();
93
  clearFeedback();
94
- showDebug('Translation form submitted');
95
 
96
  try {
97
- // IMPORTANT: Get the input elements directly by their IDs inside this function
98
- // This ensures the elements are found at the time the form is submitted
99
  const textInput = document.getElementById('text-input');
100
- const sourceLangSelect = document.getElementById('source-lang-text');
101
- const targetLangSelect = document.getElementById('target-lang-text');
 
 
 
 
 
 
 
 
 
 
102
 
103
- if (!textInput) {
104
- throw new Error('Text input element not found');
105
- }
106
- if (!sourceLangSelect) {
107
- throw new Error('Source language select not found');
108
- }
109
- if (!targetLangSelect) {
110
- throw new Error('Target language select not found');
111
  }
112
 
113
- const sourceText = textInput.value ? textInput.value.trim() : '';
114
- if (!sourceText) {
115
- displayError('Please enter text to translate');
 
116
  return;
117
  }
118
 
119
- const sourceLang = sourceLangSelect.value;
120
- const targetLang = targetLangSelect.value;
121
-
122
- showDebug('Form values:', {
123
- text: sourceText,
124
- sourceLang: sourceLang,
125
- targetLang: targetLang
126
- });
127
-
128
- // Show loading indication
129
- if (textLoadingDiv) {
130
- textLoadingDiv.style.display = 'block';
131
- }
132
 
133
- // Prepare payload
134
- const payload = {
135
- text: sourceText,
136
- source_lang: sourceLang,
137
- target_lang: targetLang
138
  };
139
- showDebug('Sending translation request', payload);
140
 
141
- // Send API request
142
- const response = await fetch('/translate/text', {
 
 
 
143
  method: 'POST',
144
  headers: {
145
  'Content-Type': 'application/json'
146
  },
147
- body: JSON.stringify(payload)
148
- });
149
-
150
- // Get and process response
151
- const responseText = await response.text();
152
- showDebug('Raw response:', responseText);
153
- let data;
154
-
155
- try {
156
- data = JSON.parse(responseText);
157
- } catch (error) {
158
- throw new Error(`Invalid JSON response: ${responseText}`);
159
- }
160
-
161
- if (!response.ok) {
162
- if (data && data.error) {
163
- throw new Error(data.error);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  } else {
165
- throw new Error(`Server error: ${response.status}`);
166
  }
167
- }
168
-
169
- if (!data.success && data.error) {
170
- throw new Error(data.error);
171
- }
172
-
173
- if (!data.translated_text) {
174
- throw new Error('Translation returned empty text');
175
- }
176
-
177
- // Display result
178
- if (textOutput && textResultBox) {
179
- textOutput.textContent = data.translated_text;
180
- textResultBox.style.display = 'block';
181
- } else {
182
- throw new Error('Result display elements not found');
183
- }
184
 
185
  } catch (error) {
186
- console.error('Translation error:', error);
187
- displayError(error.message || 'An unexpected error occurred');
188
- } finally {
189
- if (textLoadingDiv) {
190
- textLoadingDiv.style.display = 'none';
191
- }
192
  }
193
  });
194
  } else {
195
  console.error("Text translation form not found!");
196
  }
197
 
198
- // Document translation form handler - similar approach
199
  if (docForm) {
200
- docForm.addEventListener('submit', async (event) => {
201
- event.preventDefault();
202
  clearFeedback();
203
-
204
- const formData = new FormData(docForm);
205
- const fileInput = document.getElementById('doc-input');
206
- const button = docForm.querySelector('button');
207
-
208
- if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
209
- displayError('Please select a document to upload.');
210
- return;
211
- }
212
-
213
- button.disabled = true;
214
- button.textContent = 'Translating...';
215
- // Show loading indicator
216
- docLoadingIndicator.style.display = 'block';
217
-
218
  try {
219
- const response = await fetch('/translate/document', {
220
- method: 'POST',
221
- body: formData // FormData handles multipart/form-data automatically
222
- });
223
-
224
- // Get response as text first for debugging
225
- const responseText = await response.text();
226
- showDebug('Raw document response:', responseText);
227
 
228
- // Try to parse as JSON
229
- let result;
230
- try {
231
- result = JSON.parse(responseText);
232
- } catch (jsonError) {
233
- throw new Error(`Failed to parse server response: ${responseText}`);
234
- }
235
-
236
- if (!response.ok) {
237
- const errorMessage = result.error || result.detail || `HTTP error! status: ${response.status}`;
238
- throw new Error(errorMessage);
239
  }
240
 
241
- showDebug('Document translation response:', result);
242
 
243
- // Check if result contains the expected fields
244
- if (!result.translated_text) {
245
- throw new Error('Translation response is missing translated text');
246
- }
247
 
248
- docFilename.textContent = result.original_filename || 'N/A';
249
- docSourceLang.textContent = result.detected_source_lang || 'N/A';
250
- docOutput.textContent = result.translated_text;
251
- docResultBox.style.display = 'block';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
 
253
- // Set text direction based on target language (document always goes to Arabic)
254
- docOutput.dir = 'rtl';
255
-
256
  } catch (error) {
257
- console.error('Document translation error:', error);
258
- displayError(error.message || 'An unexpected error occurred during document translation.');
259
- } finally {
260
- button.disabled = false;
261
- button.textContent = 'Translate Document';
262
- // Hide loading indicator
263
- docLoadingIndicator.style.display = 'none';
264
  }
265
  });
266
  } else {
 
1
  document.addEventListener('DOMContentLoaded', () => {
 
2
  console.log("Translation app initialized");
3
 
4
+ // Get form elements - only get the base forms on page load
5
  const textForm = document.getElementById('text-translation-form');
6
  const docForm = document.getElementById('doc-translation-form');
 
 
 
 
 
 
 
 
 
 
7
 
8
+ // Simple function to show errors
9
+ function showError(message) {
10
+ const errorDiv = document.getElementById('error-message');
11
+ if (errorDiv) {
12
+ errorDiv.textContent = "Error: " + message;
13
+ errorDiv.style.display = 'block';
14
+ console.error("Error:", message);
15
+ } else {
16
+ alert("Error: " + message);
17
+ console.error("Error div not found. Error:", message);
18
  }
19
  }
20
 
21
+ // Simple function to show debug information
22
+ function showDebug(message) {
23
+ console.log("DEBUG:", message);
24
+ const debugDiv = document.getElementById('debug-info');
25
+ if (debugDiv) {
26
+ debugDiv.textContent = typeof message === 'string' ? message : JSON.stringify(message, null, 2);
27
+ debugDiv.style.display = 'block';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  }
29
  }
30
+
31
+ // Clear all feedback elements
32
  function clearFeedback() {
33
+ const elements = ['error-message', 'debug-info', 'text-result'];
34
+ elements.forEach(id => {
35
+ const el = document.getElementById(id);
36
+ if (el) {
37
+ el.style.display = 'none';
38
+ if (id !== 'text-result') el.textContent = '';
39
+ }
40
+ });
 
 
 
 
 
 
 
 
 
 
 
41
  }
42
+
43
+ // Add text form submission handler
44
  if (textForm) {
45
+ textForm.addEventListener('submit', function(e) {
46
  e.preventDefault();
47
  clearFeedback();
 
48
 
49
  try {
50
+ // Find form elements when needed, not earlier
 
51
  const textInput = document.getElementById('text-input');
52
+ const sourceLang = document.getElementById('source-lang-text');
53
+ const targetLang = document.getElementById('target-lang-text');
54
+ const textLoading = document.getElementById('text-loading');
55
+
56
+ // Debug which elements were found/not found
57
+ const foundElements = {
58
+ textInput: !!textInput,
59
+ sourceLang: !!sourceLang,
60
+ targetLang: !!targetLang,
61
+ textLoading: !!textLoading
62
+ };
63
+ showDebug("Found elements: " + JSON.stringify(foundElements));
64
 
65
+ // Check if elements exist
66
+ if (!textInput || !sourceLang || !targetLang) {
67
+ showError("Required form elements not found");
68
+ return;
 
 
 
 
69
  }
70
 
71
+ // Get values safely
72
+ const text = textInput.value ? textInput.value.trim() : '';
73
+ if (!text) {
74
+ showError("Please enter text to translate");
75
  return;
76
  }
77
 
78
+ // Show loading state if element exists
79
+ if (textLoading) textLoading.style.display = 'block';
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ // Prepare request data
82
+ const requestData = {
83
+ text: text,
84
+ source_lang: sourceLang.value,
85
+ target_lang: targetLang.value
86
  };
 
87
 
88
+ // Debug the request data
89
+ showDebug("Sending request: " + JSON.stringify(requestData));
90
+
91
+ // Use simple promise then/catch for better browser compatibility
92
+ fetch('/translate/text', {
93
  method: 'POST',
94
  headers: {
95
  'Content-Type': 'application/json'
96
  },
97
+ body: JSON.stringify(requestData)
98
+ })
99
+ .then(response => {
100
+ // First check if response is ok
101
+ if (!response.ok) {
102
+ throw new Error('Server returned ' + response.status);
103
+ }
104
+ return response.text();
105
+ })
106
+ .then(responseText => {
107
+ // Parse the response text
108
+ showDebug("Got response: " + responseText);
109
+
110
+ let data;
111
+ try {
112
+ data = JSON.parse(responseText);
113
+ } catch (err) {
114
+ throw new Error('Invalid JSON response');
115
+ }
116
+
117
+ // Check for translation result
118
+ if (data && data.translated_text) {
119
+ // Display the result
120
+ const resultBox = document.getElementById('text-result');
121
+ const outputEl = document.getElementById('text-output');
122
+
123
+ if (resultBox && outputEl) {
124
+ outputEl.textContent = data.translated_text;
125
+ resultBox.style.display = 'block';
126
+ } else {
127
+ throw new Error('Result display elements not found');
128
+ }
129
  } else {
130
+ throw new Error(data.error || 'No translation result returned');
131
  }
132
+ })
133
+ .catch(error => {
134
+ showError(error.message || "Translation failed");
135
+ console.error("Translation error:", error);
136
+ })
137
+ .finally(() => {
138
+ // Hide loading indicator
139
+ if (textLoading) textLoading.style.display = 'none';
140
+ });
 
 
 
 
 
 
 
 
141
 
142
  } catch (error) {
143
+ showError(error.message || "An unexpected error occurred");
144
+ console.error("General error:", error);
145
+
146
+ // Ensure loading indicator is hidden
147
+ const textLoading = document.getElementById('text-loading');
148
+ if (textLoading) textLoading.style.display = 'none';
149
  }
150
  });
151
  } else {
152
  console.error("Text translation form not found!");
153
  }
154
 
155
+ // Document translation handler with similar approach
156
  if (docForm) {
157
+ docForm.addEventListener('submit', function(e) {
158
+ e.preventDefault();
159
  clearFeedback();
160
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  try {
162
+ const fileInput = document.getElementById('doc-input');
163
+ const loadingIndicator = document.getElementById('doc-loading');
 
 
 
 
 
 
164
 
165
+ if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
166
+ showError("Please select a document to upload");
167
+ return;
 
 
 
 
 
 
 
 
168
  }
169
 
170
+ if (loadingIndicator) loadingIndicator.style.display = 'block';
171
 
172
+ // Create form data
173
+ const formData = new FormData(docForm);
 
 
174
 
175
+ fetch('/translate/document', {
176
+ method: 'POST',
177
+ body: formData
178
+ })
179
+ .then(response => {
180
+ if (!response.ok) throw new Error('Server returned ' + response.status);
181
+ return response.text();
182
+ })
183
+ .then(responseText => {
184
+ showDebug("Document response: " + responseText);
185
+
186
+ let data;
187
+ try {
188
+ data = JSON.parse(responseText);
189
+ } catch (err) {
190
+ throw new Error('Invalid JSON response');
191
+ }
192
+
193
+ if (!data || !data.translated_text) {
194
+ throw new Error('No translation returned');
195
+ }
196
+
197
+ // Display result
198
+ const resultBox = document.getElementById('doc-result');
199
+ const outputEl = document.getElementById('doc-output');
200
+ const filenameEl = document.getElementById('doc-filename');
201
+ const sourceLangEl = document.getElementById('doc-source-lang');
202
+
203
+ if (resultBox && outputEl) {
204
+ if (filenameEl) filenameEl.textContent = data.original_filename || 'N/A';
205
+ if (sourceLangEl) sourceLangEl.textContent = data.detected_source_lang || 'N/A';
206
+ outputEl.textContent = data.translated_text;
207
+ resultBox.style.display = 'block';
208
+ } else {
209
+ throw new Error('Result display elements not found');
210
+ }
211
+ })
212
+ .catch(error => {
213
+ showError(error.message || "Document translation failed");
214
+ })
215
+ .finally(() => {
216
+ if (loadingIndicator) loadingIndicator.style.display = 'none';
217
+ const button = docForm.querySelector('button');
218
+ if (button) {
219
+ button.disabled = false;
220
+ button.textContent = 'Translate Document';
221
+ }
222
+ });
223
 
 
 
 
224
  } catch (error) {
225
+ showError(error.message || "An unexpected error occurred");
226
+ console.error("Document error:", error);
227
+
228
+ const loadingIndicator = document.getElementById('doc-loading');
229
+ if (loadingIndicator) loadingIndicator.style.display = 'none';
 
 
230
  }
231
  });
232
  } else {