Skip to content

Commit e0d74db

Browse files
committed
cleanup
1 parent fca8013 commit e0d74db

File tree

5 files changed

+15
-211
lines changed

5 files changed

+15
-211
lines changed

src/api/blueprints/config_routes.py

Lines changed: 3 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -139,14 +139,8 @@ def mask_api_key(key):
139139
"gemini_api_key_configured": bool(GEMINI_API_KEY),
140140
"openai_api_key_configured": bool(OPENAI_API_KEY),
141141
"openrouter_api_key_configured": bool(OPENROUTER_API_KEY)
142-
# Languages are no longer sent from server - handled by browser detection
143142
}
144143

145-
if DEBUG_MODE:
146-
logger.debug(f"📤 /api/config response:")
147-
logger.debug(f" api_endpoint: {DEFAULT_OLLAMA_API_ENDPOINT}")
148-
logger.debug(f" default_model: {DEFAULT_MODEL}")
149-
150144
return jsonify(config_response)
151145

152146
@bp.route('/api/config/max-tokens', methods=['GET'])
@@ -257,9 +251,6 @@ def _get_openai_models(provided_api_key=None, api_endpoint=None):
257251
if api_key:
258252
headers['Authorization'] = f'Bearer {api_key}'
259253

260-
if DEBUG_MODE:
261-
logger.debug(f"📥 Fetching models from OpenAI-compatible endpoint: {models_url}")
262-
263254
response = requests.get(models_url, headers=headers, timeout=10)
264255

265256
if response.status_code == 200:
@@ -295,19 +286,11 @@ def _get_openai_models(provided_api_key=None, api_endpoint=None):
295286
"count": len(models)
296287
})
297288

298-
# If we get here, either request failed or no models returned
299-
# Fall back to static list
300-
if DEBUG_MODE:
301-
logger.debug(f"⚠️ No models returned from {base_url}, using fallback list")
302-
303289
except requests.exceptions.ConnectionError as e:
304-
error_msg = f"Connection error to {base_url}"
305-
if DEBUG_MODE:
306-
logger.debug(f"❌ OpenAI-compatible endpoint connection error: {error_msg}")
290+
pass
307291

308292
except Exception as e:
309-
if DEBUG_MODE:
310-
logger.debug(f"❌ OpenAI-compatible endpoint error: {e}")
293+
pass
311294

312295
# Fallback: return static OpenAI models
313296
model_ids = [m['id'] for m in openai_static_models]
@@ -375,59 +358,33 @@ def _get_ollama_models():
375358
"""Get available models from Ollama API"""
376359
ollama_base_from_ui = request.args.get('api_endpoint', DEFAULT_OLLAMA_API_ENDPOINT)
377360

378-
if DEBUG_MODE:
379-
logger.debug(f"📥 /api/models request for Ollama")
380-
logger.debug(f" api_endpoint from UI: {ollama_base_from_ui}")
381-
logger.debug(f" default endpoint: {DEFAULT_OLLAMA_API_ENDPOINT}")
382-
383361
try:
384362
base_url = ollama_base_from_ui.split('/api/')[0]
385363
tags_url = f"{base_url}/api/tags"
386364

387-
if DEBUG_MODE:
388-
logger.debug(f" Connecting to: {tags_url}")
389-
390-
response = requests.get(tags_url, timeout=10) # Increased timeout from 5 to 10
391-
392-
if DEBUG_MODE:
393-
logger.debug(f" Response status: {response.status_code}")
365+
response = requests.get(tags_url, timeout=10)
394366

395367
if response.status_code == 200:
396368
data = response.json()
397369
models_data = data.get('models', [])
398370
model_names = [m.get('name') for m in models_data if m.get('name')]
399371

400-
if DEBUG_MODE:
401-
logger.debug(f" Models found: {model_names}")
402-
403372
return jsonify({
404373
"models": model_names,
405374
"default": DEFAULT_MODEL if DEFAULT_MODEL in model_names else (model_names[0] if model_names else DEFAULT_MODEL),
406375
"status": "ollama_connected",
407376
"count": len(model_names)
408377
})
409-
else:
410-
if DEBUG_MODE:
411-
logger.debug(f" ❌ Non-200 response: {response.status_code}")
412-
logger.debug(f" Response body: {response.text[:500]}")
413378

414379
except requests.exceptions.ConnectionError as e:
415380
error_msg = f"Connection refused to {tags_url}. Is Ollama running?"
416-
if DEBUG_MODE:
417-
logger.debug(f" ❌ ConnectionError: {e}")
418381
print(f"❌ {error_msg}")
419382
except requests.exceptions.Timeout as e:
420383
error_msg = f"Timeout connecting to {tags_url} (10s)"
421-
if DEBUG_MODE:
422-
logger.debug(f" ❌ Timeout: {e}")
423384
print(f"❌ {error_msg}")
424385
except requests.exceptions.RequestException as e:
425-
if DEBUG_MODE:
426-
logger.debug(f" ❌ RequestException: {type(e).__name__}: {e}")
427386
print(f"❌ Could not connect to Ollama at {ollama_base_from_ui}: {e}")
428387
except Exception as e:
429-
if DEBUG_MODE:
430-
logger.debug(f" ❌ Unexpected error: {type(e).__name__}: {e}")
431388
print(f"❌ Error retrieving models from {ollama_base_from_ui}: {e}")
432389

433390
return jsonify({
@@ -477,8 +434,6 @@ def get_model_warning():
477434
})
478435

479436
except Exception as e:
480-
if DEBUG_MODE:
481-
logger.debug(f"Error getting model warning: {e}")
482437
return jsonify({"warning": None, "behavior": None, "error": str(e)})
483438

484439
def _get_env_file_path():
@@ -568,8 +523,6 @@ def save_settings():
568523
'DEFAULT_MODEL',
569524
'LLM_PROVIDER',
570525
'API_ENDPOINT'
571-
# DEFAULT_SOURCE_LANGUAGE and DEFAULT_TARGET_LANGUAGE removed
572-
# Languages are now auto-detected (source) and browser-detected (target)
573526
}
574527

575528
try:
@@ -617,7 +570,6 @@ def get_settings():
617570
"default_model": DEFAULT_MODEL or "",
618571
"llm_provider": os.getenv('LLM_PROVIDER', 'ollama'),
619572
"api_endpoint": DEFAULT_OLLAMA_API_ENDPOINT or ""
620-
# Languages are no longer stored in .env - auto-detected per session
621573
})
622574

623575
return bp

src/web/static/js/index.js

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -246,14 +246,10 @@ function initializeState() {
246246

247247
/**
248248
* Calculate and apply preview height based on MAX_TOKENS_PER_CHUNK
249-
* Formula: Fixed 300px height regardless of token count
250-
* @param {number} maxTokens - MAX_TOKENS_PER_CHUNK value (not used, kept for API compatibility)
249+
* @param {number} maxTokens - MAX_TOKENS_PER_CHUNK value
251250
*/
252251
function updatePreviewHeight(maxTokens = 450) {
253-
// Fixed height of 300px
254252
const fixedHeight = 300;
255-
256-
// Apply to CSS variable
257253
document.documentElement.style.setProperty('--preview-height', `${fixedHeight}px`);
258254
}
259255

@@ -535,7 +531,6 @@ async function showTTSModal(filename, filepath) {
535531
providersInfo = providersInfo.providers || {};
536532
voicePrompts = voicePrompts.voice_prompts || [];
537533
} catch {
538-
// TTS info load failed
539534
}
540535

541536
const isChatterboxAvailable = providersInfo.chatterbox?.available || false;

src/web/static/js/translation/batch-controller.js

Lines changed: 2 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,6 @@ function getTranslationConfig(file) {
4040

4141
const provider = DomHelpers.getValue('llmProvider');
4242

43-
// Build prompt options object
44-
// Technical content protection is always enabled
4543
const promptOptions = {
4644
preserve_technical_content: true,
4745
text_cleanup: DomHelpers.getElement('textCleanup')?.checked || false,
@@ -62,27 +60,21 @@ function getTranslationConfig(file) {
6260
gemini_api_key: provider === 'gemini' ? ApiKeyUtils.getValue('geminiApiKey') : '',
6361
openai_api_key: provider === 'openai' ? ApiKeyUtils.getValue('openaiApiKey') : '',
6462
openrouter_api_key: provider === 'openrouter' ? ApiKeyUtils.getValue('openrouterApiKey') : '',
65-
// Advanced settings (chunk_size, timeout, context_window, max_attempts, retry_delay)
66-
// are now controlled via .env only - server will use defaults from config.py
67-
input_filename: file.name, // Store original filename for UI restoration after browser refresh
63+
input_filename: file.name,
6864
output_filename: file.outputFilename,
6965
file_type: file.fileType,
7066
prompt_options: promptOptions,
71-
// Bilingual output (original + translation interleaved)
7267
bilingual_output: DomHelpers.getElement('bilingualMode')?.checked || false,
73-
// TTS configuration
7468
tts_enabled: ttsEnabled,
7569
tts_voice: ttsEnabled ? (DomHelpers.getValue('ttsVoice') || '') : '',
7670
tts_rate: ttsEnabled ? (DomHelpers.getValue('ttsRate') || '+0%') : '+0%',
7771
tts_format: ttsEnabled ? (DomHelpers.getValue('ttsFormat') || 'opus') : 'opus',
7872
tts_bitrate: ttsEnabled ? (DomHelpers.getValue('ttsBitrate') || '64k') : '64k'
7973
};
8074

81-
// Handle file input based on type
8275
if (file.fileType === 'epub' || file.fileType === 'srt') {
8376
config.file_path = file.filePath;
8477
} else {
85-
// Text file
8678
if (file.content) {
8779
config.text = file.content;
8880
} else {
@@ -123,10 +115,7 @@ export const BatchController = {
123115
* Start batch translation
124116
*/
125117
async startBatchTranslation() {
126-
// Wait for TranslationTracker to be fully initialized
127118
if (!TranslationTracker.isInitialized || !TranslationTracker.isInitialized()) {
128-
console.warn('TranslationTracker not yet initialized, waiting...');
129-
// Wait a bit and try again
130119
await new Promise(resolve => setTimeout(resolve, 100));
131120
if (!TranslationTracker.isInitialized || !TranslationTracker.isInitialized()) {
132121
MessageLogger.showMessage('⚠️ System still initializing, please wait...', 'warning');
@@ -169,7 +158,6 @@ export const BatchController = {
169158
}
170159
}
171160

172-
// Update any queued files that have empty languages with current form values
173161
let filesUpdated = false;
174162
for (const file of filesToProcess) {
175163
if (file.status !== 'Queued') continue;
@@ -184,15 +172,12 @@ export const BatchController = {
184172
}
185173
}
186174

187-
// Save updated file queue if any changes
188175
if (filesUpdated) {
189176
StateManager.setState('files.toProcess', filesToProcess);
190177
}
191178

192-
// Mark batch as active
193179
StateManager.setState('translation.isBatchActive', true);
194180

195-
// Count queued files
196181
const queuedFilesCount = filesToProcess.filter(f => f.status === 'Queued').length;
197182

198183
// Update UI
@@ -220,13 +205,12 @@ export const BatchController = {
220205
*/
221206
async processNextFileInQueue() {
222207
const currentJob = StateManager.getState('translation.currentJob');
223-
if (currentJob) return; // Already processing
208+
if (currentJob) return;
224209

225210
const filesToProcess = StateManager.getState('files.toProcess') || [];
226211
const fileToTranslate = filesToProcess.find(f => f.status === 'Queued');
227212

228213
if (!fileToTranslate) {
229-
// Batch completed
230214
StateManager.setState('translation.isBatchActive', false);
231215
StateManager.setState('translation.currentJob', null);
232216

@@ -244,29 +228,24 @@ export const BatchController = {
244228
return;
245229
}
246230

247-
// Reset progress for new file
248231
ProgressManager.reset();
249232

250-
// Reset translation preview
251233
const lastTranslationPreview = DomHelpers.getElement('lastTranslationPreview');
252234
if (lastTranslationPreview) {
253235
lastTranslationPreview.innerHTML = '<div style="color: #6b7280; font-style: italic; padding: 10px;">No translation yet...</div>';
254236
}
255237

256-
// Show/hide stats based on file type
257238
if (fileToTranslate.fileType === 'epub') {
258239
DomHelpers.hide('statsGrid');
259240
} else {
260241
DomHelpers.show('statsGrid');
261242
}
262243

263-
// Update UI
264244
this.updateTranslationTitle(fileToTranslate);
265245
ProgressManager.show();
266246
MessageLogger.addLog(`▶️ Starting translation for: ${fileToTranslate.name} (${fileToTranslate.fileType.toUpperCase()})`);
267247
updateFileStatusInList(fileToTranslate.name, 'Preparing...');
268248

269-
// Validate API keys for cloud providers using shared utility
270249
const provider = DomHelpers.getValue('llmProvider');
271250
const endpoint = provider === 'openai' ? DomHelpers.getValue('openaiEndpoint') : '';
272251
const apiKeyValidation = ApiKeyUtils.validateForProvider(provider, endpoint);
@@ -290,14 +269,11 @@ export const BatchController = {
290269
return;
291270
}
292271

293-
// Get translation config
294272
const config = getTranslationConfig(fileToTranslate);
295273

296274
try {
297-
// Start translation
298275
const data = await ApiClient.startTranslation(config);
299276

300-
// Update state
301277
StateManager.setState('translation.currentJob', {
302278
fileRef: fileToTranslate,
303279
translationId: data.translation_id
@@ -306,29 +282,20 @@ export const BatchController = {
306282
fileToTranslate.translationId = data.translation_id;
307283
updateFileStatusInList(fileToTranslate.name, 'Submitted', data.translation_id);
308284

309-
// Show progress section immediately (don't wait for WebSocket)
310-
// Use requestAnimationFrame to ensure immediate DOM update
311285
DomHelpers.show('progressSection');
312286
DomHelpers.show('interruptBtn');
313287

314-
// Force immediate DOM render
315288
requestAnimationFrame(() => {
316289
const progressSection = DomHelpers.getElement('progressSection');
317290
if (progressSection) {
318291
progressSection.style.display = 'block';
319292
}
320293
});
321294

322-
// Update title immediately
323295
this.updateTranslationTitle(fileToTranslate);
324-
325-
// Show initial message
326296
MessageLogger.addLog(`⏳ Translation submitted for ${fileToTranslate.name}...`);
327-
328-
// Remove file from processing list immediately when translation starts
329297
this.removeFileFromProcessingList(fileToTranslate.name);
330298

331-
// Emit event
332299
const event = new CustomEvent('translationStarted', { detail: { file: fileToTranslate, translationId: data.translation_id } });
333300
window.dispatchEvent(event);
334301

0 commit comments

Comments
 (0)