amine_dubs commited on
Commit
9b675a2
·
1 Parent(s): 91dbc5b
Files changed (1) hide show
  1. static/script.js +103 -141
static/script.js CHANGED
@@ -2,63 +2,39 @@ document.addEventListener('DOMContentLoaded', () => {
2
  // Log when the page loads to confirm JavaScript is working
3
  console.log("Translation app initialized");
4
 
5
- // Safely get DOM elements with error handling
6
- function safeGetElement(id) {
7
- const element = document.getElementById(id);
8
- if (!element) {
9
- console.error(`Element not found: #${id}`);
10
- }
11
- return element;
12
- }
 
 
 
 
 
13
 
14
- const textForm = safeGetElement('text-translation-form');
15
- const docForm = safeGetElement('doc-translation-form');
16
- const textResultBox = safeGetElement('text-result');
17
- const textOutput = safeGetElement('text-output');
18
- const docResultBox = safeGetElement('doc-result');
19
- const docOutput = safeGetElement('doc-output');
20
- const docFilename = safeGetElement('doc-filename');
21
- const docSourceLang = safeGetElement('doc-source-lang');
22
- const errorMessageDiv = safeGetElement('error-message');
23
- const docLoadingIndicator = safeGetElement('doc-loading');
24
- const debugInfoDiv = safeGetElement('debug-info');
25
-
26
- // Create text loading indicator if it doesn't exist
27
- let textLoadingDiv = safeGetElement('text-loading');
28
- if (!textLoadingDiv && textForm) {
29
- console.log("Creating missing text loading indicator");
30
- textLoadingDiv = document.createElement('div');
31
- textLoadingDiv.id = 'text-loading';
32
- textLoadingDiv.className = 'loading-spinner';
33
- textLoadingDiv.textContent = 'Translating...';
34
- textForm.appendChild(textLoadingDiv);
35
- }
36
-
37
- // Helper function to display debug info
38
  function showDebug(message, data = null) {
39
  let debugText = typeof message === 'string' ? message : JSON.stringify(message);
40
-
41
  if (data) {
42
  debugText += '\n' + JSON.stringify(data, null, 2);
43
  }
44
-
45
  console.log("DEBUG:", message, data || '');
46
  if (debugInfoDiv) {
47
  debugInfoDiv.textContent = debugText;
48
  debugInfoDiv.style.display = 'block';
49
- } else {
50
- console.error("Debug div not found!");
51
  }
52
  }
53
 
54
  // Helper function to display errors
55
  function displayError(message) {
56
  let errorText = 'Error: ';
57
-
58
  if (message === undefined || message === null) {
59
  errorText += 'Unknown error occurred';
60
  } else if (typeof message === 'object') {
61
- // Improved error object handling
62
  if (message.message) {
63
  errorText += message.message;
64
  } else if (message.detail) {
@@ -80,12 +56,9 @@ document.addEventListener('DOMContentLoaded', () => {
80
  if (errorMessageDiv) {
81
  errorMessageDiv.textContent = errorText;
82
  errorMessageDiv.style.display = 'block';
83
-
84
- // Hide result boxes on error
85
  if (textResultBox) textResultBox.style.display = 'none';
86
  if (docResultBox) docResultBox.style.display = 'none';
87
  } else {
88
- // If error div not found, use alert as fallback
89
  alert("Error: " + errorText);
90
  }
91
  }
@@ -113,48 +86,51 @@ document.addEventListener('DOMContentLoaded', () => {
113
  }
114
  }
115
 
116
- // Fix the text form submission handler
117
  if (textForm) {
118
- console.log("Adding submit event listener to text form");
119
- textForm.addEventListener('submit', async (e) => {
120
- console.log("Form submitted!");
121
  e.preventDefault();
122
  clearFeedback();
123
-
124
- // Show debug immediately to confirm the handler is working
125
- showDebug('Translation submission triggered');
126
-
127
- // Use correct field IDs matching the HTML and check if they exist
128
- const textInput = safeGetElement('text-input');
129
- const sourceLangSelect = safeGetElement('source-lang-text');
130
- const targetLangSelect = safeGetElement('target-lang-text');
131
-
132
- // Check all required elements exist before proceeding
133
- if (!textInput || !sourceLangSelect || !targetLangSelect) {
134
- displayError('One or more required form elements are missing. Check your HTML structure.');
135
- console.error('Missing elements:',
136
- !textInput ? 'text-input' : '',
137
- !sourceLangSelect ? 'source-lang-text' : '',
138
- !targetLangSelect ? 'target-lang-text' : ''
139
- );
140
- return;
141
- }
142
-
143
- // Safely extract values
144
- const sourceText = textInput.value ? textInput.value.trim() : '';
145
- const sourceLang = sourceLangSelect.value;
146
- const targetLang = targetLangSelect.value;
147
-
148
- if (!sourceText) {
149
- displayError('Please enter text to translate');
150
- return;
151
- }
152
 
153
  try {
154
- // Show loading state
155
- if (textLoadingDiv) textLoadingDiv.style.display = 'block';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
- // Log payload for debugging
 
 
 
 
 
 
 
 
 
 
 
158
  const payload = {
159
  text: sourceText,
160
  source_lang: sourceLang,
@@ -162,85 +138,71 @@ document.addEventListener('DOMContentLoaded', () => {
162
  };
163
  showDebug('Sending translation request', payload);
164
 
165
- // Check if API is available
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  try {
167
- const response = await fetch('/translate/text', {
168
- method: 'POST',
169
- headers: {
170
- 'Content-Type': 'application/json'
171
- },
172
- body: JSON.stringify(payload)
173
- });
174
-
175
- // Log response status
176
- showDebug(`Response status: ${response.status}`);
177
-
178
- // Get the raw response text first for debugging
179
- const responseText = await response.text();
180
- showDebug('Raw response:', responseText);
181
-
182
- // Then parse it as JSON
183
- let data;
184
- try {
185
- data = JSON.parse(responseText);
186
- } catch (jsonError) {
187
- showDebug('JSON parse error:', jsonError);
188
- throw new Error(`Invalid JSON response: ${responseText}`);
189
- }
190
-
191
- // Hide loading state
192
- if (textLoadingDiv) textLoadingDiv.style.display = 'none';
193
-
194
- if (!response.ok) {
195
- if (data && data.error) {
196
- displayError(data.error);
197
- } else {
198
- displayError(`Server error: ${response.status}`);
199
- }
200
- return;
201
- }
202
-
203
- if (!data.success && data.error) {
204
- displayError(data.error);
205
- return;
206
- }
207
-
208
- if (!data.translated_text) {
209
- displayError('Translation returned empty text');
210
- return;
211
- }
212
-
213
- if (textOutput) {
214
- textOutput.textContent = data.translated_text;
215
- if (textResultBox) textResultBox.style.display = 'block';
216
  } else {
217
- displayError('Text output element not found!');
218
  }
219
-
220
- } catch (fetchError) {
221
- console.error('Fetch error:', fetchError);
222
- displayError(`Network error: ${fetchError.message}. Make sure the backend server is running.`);
223
  }
224
- } catch (error) {
225
- console.error('General error:', error);
226
- displayError(`Error: ${error.message}`);
227
 
228
- // Hide loading
229
- if (textLoadingDiv) textLoadingDiv.style.display = 'none';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  }
231
  });
232
  } else {
233
- console.error("Text translation form not found in the document!");
234
  }
235
 
236
- // Handle Document Translation Form Submission
237
  if (docForm) {
238
  docForm.addEventListener('submit', async (event) => {
239
  event.preventDefault();
240
  clearFeedback();
241
 
242
  const formData = new FormData(docForm);
243
- const fileInput = safeGetElement('doc-input');
244
  const button = docForm.querySelector('button');
245
 
246
  if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
@@ -302,6 +264,6 @@ document.addEventListener('DOMContentLoaded', () => {
302
  }
303
  });
304
  } else {
305
- console.error("Document translation form not found in the document!");
306
  }
307
  });
 
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) {
 
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
  }
 
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,
 
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) {
 
264
  }
265
  });
266
  } else {
267
+ console.error("Document translation form not found!");
268
  }
269
  });