"""
Internationalization (i18n) module for vogel-model-trainer
Provides translations for command-line output
"""

import os
import locale

# Available translations
TRANSLATIONS = {
    'en': {
        # Extraction
        'loading_yolo': '🤖 Loading YOLO model:',
        'loading_species': '🧠 Loading species classifier:',
        'loaded_species_classes': '   ✅ Loaded with {count} species classes',
        'video_info': '📹 Video:',
        'total_frames': '   📊 {total} frames, {fps:.1f} FPS',
        'analyzing_every_nth': '   🔍 Analyzing every {n}. frame...',
        'detection_threshold': '   🎯 Detection threshold: {threshold}',
        'species_threshold': '   🎯 Species threshold: {threshold}',
        'image_size': '   📐 Image size: {size}x{size}px',
        'image_size_original': '   📐 Image size: Original',
        'max_detections_per_frame': '   🔢 Max detections per frame: {max}',
        'min_box_size_filter': '   📏 Min box size: {size}px',
        'max_box_size_filter': '   📏 Max box size: {size}px',
        'jpeg_quality_filter': '   🎨 JPEG quality: {quality}',
        'blur_detection_filter': '   🔍 Blur detection: Enabled',
        'dedup_filter': '   🔄 Deduplication: Enabled (threshold: {threshold})',
        'motion_sharpness_filter': '   ✨ Motion sharpness filter: {threshold}',
        'motion_edge_filter': '   🔷 Motion edge quality filter: {threshold}',
        'background_removal_enabled': '   🎭 Background removal: Enabled (rembg/AI)',
        'motion_rejected_stats': '   🚫 Rejected due to motion/blur: {count}',
        'quality_report_title': '📊 Quality Report',
        'quality_report_total': '   Total detections processed: {count}',
        'quality_report_accepted': '   ✅ Accepted: {count} ({percent:.1f}%)',
        'quality_report_rejected': '   ❌ Rejected: {count} ({percent:.1f}%)',
        'quality_report_avg_accepted': '   📈 Average quality (accepted): {score:.1f}',
        'quality_report_avg_rejected_blur': '   📉 Average sharpness (rejected): {score:.1f}',
        'quality_report_avg_rejected_edges': '   📉 Average edge quality (rejected): {score:.1f}',
        'mode_autosorting': '   🤖 Auto-sorting mode: Using species classifier',
        'mode_manual': '   🏷️  Manual mode: Species = {species}',
        'mode_standard': '   📦 Standard mode: All birds in one directory',
        'cannot_open_video': '❌ Cannot open video: {path}',
        'bird_extracted': '   ✅ Bird #{count}: {species} (conf {conf:.2f}), frame {frame}',
        'bird_extracted_simple': '   ✅ Extracted bird #{count}: frame {frame}, conf {conf:.2f}',
        'bird_skipped': '   ⏭️  Skipped: {species} (conf {conf:.2f} < {threshold:.2f}), frame {frame}',
        'progress': '   ⏳ Progress: {percent:.1f}% ({current}/{total} frames)',
        'extraction_interrupted': '\n⚠️  Extraction interrupted by user',
        'extraction_complete': '\n✅ Extraction complete!',
        'output_directory': '   📁 Output directory: {path}',
        'detected_birds_total': '   🔍 Detected birds total: {count}',
        'exported_birds_total': '   🐦 Exported birds: {count}',
        'skipped_birds_total': '   ⏭️  Skipped (< {threshold:.2f}): {count}',
        'total_birds': '   🐦 Total birds extracted: {count}',
        'species_breakdown': '\n📊 Species breakdown:',
        'species_count': '   • {species}: {count} birds',
        'session_id': '   🆔 Session ID: {id}',
        'filename_format': '\n💡 Filename format: {format}',
        'next_steps': '\n💡 Next steps:',
        'next_step_review': '   1. Review extracted images in species subdirectories: {path}',
        'next_step_verify': '   2. Manually verify auto-classifications (if using species model)',
        'next_step_manual_sort': '   2. Create subdirectories for each species and move images into correct folders',
        'next_step_organize': '   3. Use organize_dataset.py to create train/val split',
        'next_step_train': '   4. Train improved model with new data!',
        'processing_video': '📹 Processing video {idx}/{total}: {name}',
        'error_processing': '\n❌ Error processing {name}: {error}',
        'continuing': '   Continuing with next video...',
        'all_videos_processed': '✅ All videos processed!\n   📁 Output directory: {path}',
        
        # File processing (NEW)
        'files_found_header': '📁 Found {total} file(s) to process:',
        'files_videos_count': '   🎬 {count} video(s)',
        'files_images_count': '   🖼️  {count} image(s)',
        'files_and_more': '   ... and {count} more',
        'processing_videos_header': '🎬 Processing {count} video file(s)',
        'processing_video_item': '📹 Processing video {idx}/{total}: {name}',
        'processing_images_header': '🖼️  Processing {count} image file(s)',
        'processing_image_item': '📸 Processing image {idx}/{total}: {name}',
        'convert_mode_header': '🔄 CONVERT MODE: Processing existing bird images',
        'convert_images_found': '🖼️  Found {count} image(s) to convert',
        'convert_source_dir': '📁 Source: {path}',
        'convert_target_dir': '📁 Target: {path}',
        'convert_target_directory': '📁 Target directory: {path}',
        'convert_total_processed': '🖼️  Total processed: {count}',
        'convert_quality_report': '📊 Quality Report',
        
        # Classification (Bulk Inference)
        'classify_header': 'Bulk Bird Image Classification',
        'classify_model_not_found': '❌ Model not found: {path}',
        'classify_loading_model': '🤖 Loading model: {path}',
        'classify_model_loaded': '   ✅ Model loaded on {device} with {species} species',
        'classify_detected_species': '🐦 Detected species: {species}',
        'classify_input_not_found': '❌ Input directory not found: {path}',
        'classify_found_images': '📸 Found {count} images to classify',
        'classify_no_images': 'ℹ️  No images found in {path}',
        'classify_processing_header': '\n🔄 Processing {total} images...',
        'classify_progress': 'Classifying images',
        'classify_image_error': '   ⚠️  Error processing {path}: {error}',
        'classify_exporting_csv': '\n💾 Exporting results to CSV: {path}',
        'classify_csv_saved': '   ✅ CSV report saved: {path} ({count} images)',
        'classify_sorting_header': '\n📁 Sorting images by species...',
        'classify_copying': 'Copying',
        'classify_moving': 'Moving',
        'classify_dry_run_mode': '(DRY RUN)',
        'classify_sort_progress': 'Sorting images',
        'classify_file_error': '   ⚠️  Error processing {path}: {error}',
        'classify_sorting_complete': '   ✅ Images sorted to: {path}',
        'classify_deleting_source': '\n🗑️  Deleting source directory: {path}',
        'classify_source_deleted': '   ✅ Source directory deleted',
        'classify_delete_error': '   ⚠️  Error deleting source: {error}',
        'classify_delete_warning': '⚠️  WARNING: Source directory will be PERMANENTLY deleted after processing!',
        'classify_delete_confirm': 'Continue? [y/N]: ',
        'classify_cancelled': '❌ Operation cancelled by user',
        'classify_statistics_header': 'Classification Statistics',
        'classify_total_classified': '📊 Total classified: {count}',
        'classify_species_distribution': '\n🐦 Species distribution:',
        'classify_sorted_statistics': '\n📁 Files sorted:',
        'classify_dry_run_complete': '✅ Dry run complete! No files were modified.',
        'classify_complete': '✅ Classification complete!',
        'classify_invalid_top_k': '❌ Invalid top-k value: {k}. Must be between 1 and 5.',
        'classify_invalid_confidence': '❌ Invalid confidence threshold: {conf}. Must be between 0.0 and 1.0.',
        
        # Evaluation
        'evaluate_header': 'Model Evaluation & Analytics',
        'evaluate_model_not_found': '❌ Model not found: {path}',
        'evaluate_loading_model': '🤖 Loading model: {path}',
        'evaluate_model_loaded': '   ✅ Model loaded on {device} with {species} species',
        'evaluate_test_dir_not_found': '❌ Test directory not found: {path}',
        'evaluate_no_test_images': 'ℹ️  No test images found in {path}',
        'evaluate_found_images': '📸 Found {count} test images across {species} species',
        'evaluate_species_list': 'Species',
        'evaluate_species_mismatch': '⚠️  Warning: Model and test species do not match!',
        'evaluate_model_species': 'Model species',
        'evaluate_test_species': 'Test species',
        'evaluate_species_progress': 'Species',
        'evaluate_processing': '🔄 Evaluating model...',
        'evaluate_image_error': '   ⚠️  Error processing {path}: {error}',
        'evaluate_confusion_matrix_header': 'Confusion Matrix',
        'evaluate_metrics_header': 'Per-Species Metrics',
        'evaluate_overall_accuracy': '📊 Overall Accuracy: {accuracy:.2f}%',
        'evaluate_correct': 'Correct',
        'evaluate_misclassified': 'Misclassified',
        'evaluate_no_misclassifications': 'ℹ️  No misclassifications found!',
        'evaluate_misclassifications_saved': '   ✅ Misclassifications saved: {path} ({count} images)',
        'evaluate_json_saved': '   ✅ Metrics exported to JSON: {path}',
        'evaluate_complete': '✅ Evaluation complete!',
        
        # Organization
        'organizing_dataset': '📊 Organizing dataset: {path}',
        'output_dir': '📁 Output directory: {path}',
        'train_ratio': '📈 Train/Val ratio: {ratio:.0%}/{val:.0%}',
        'found_species': '🐦 Found {count} species:',
        'species_images': '   • {species}: {count} images',
        'creating_splits': '🔄 Creating train/val splits...',
        'split_created': '   ✅ {species}: {train} train / {val} val',
        'organization_complete': '\n✅ Dataset organized!',
        'dataset_summary': '\n📊 Dataset Summary:',
        'total_images': '   📷 Total images: {count}',
        'training_images': '   🏋️  Training: {count} images',
        'validation_images': '   ✅ Validation: {count} images',
        'scanning_directory': '🔍 Scanning directory: {path}',
        'species_found': '   {species}: {count} images found',
        'no_images_found': '   ⚠️  No images found!',
        'enforcing_max_images': '\n🔢 Enforcing maximum {max} images per class...',
        'delete_error': '   ⚠️  Error deleting {filename}: {error}',
        'images_deleted': '   ✂️  {species}: {deleted} images deleted ({before} → {after})',
        'total_deleted': '\n📊 Total deleted images: {count}',
        'affected_species': '   Affected species: {species}',
        'class_balance_check': '\n⚖️  Class Balance Check:',
        'balance_minimum': '   Minimum: {count} images',
        'balance_maximum': '   Maximum: {count} images',
        'balance_average': '   Average: {avg:.1f} images',
        'balance_difference': '   Difference: {percent:.1f}%',
        'balance_error': '\n❌ ERROR: Class imbalance too large!',
        'balance_max_tolerance': '   Maximum tolerance: {percent}%',
        'balance_current_diff': '   Current difference: {percent:.1f}%',
        'balance_affected_classes': '\n   Affected classes:',
        'balance_class_item': '   • {species:15s}: {count:4d} images ({diff:+.1f}% from average)',
        'balance_recommendation': '\n💡 Recommendation:',
        'balance_rec_collect': '   - Collect more images for underrepresented species',
        'balance_rec_limit': '   - Or use --max-images-per-class {limit} to limit to {tolerance}%',
        'balance_warning': '\n⚠️  WARNING: Class balance could be better',
        'balance_warning_diff': '   Difference: {percent:.1f}% (Tolerance: {tolerance}%)',
        'balance_warning_classes': '   Affected classes:',
        'balance_warning_item': '   • {species:15s}: {count:4d} images ({diff:.1f}% below maximum)',
        'balance_good': '   ✅ Class balance is good! (< {tolerance}%)',
        
        # Training
        'training_model': '🎓 Training model on dataset: {path}',
        'model_output': '📁 Output directory: {path}',
        'loading_dataset': '📂 Loading dataset from: {path}',
        'detected_species': '🐦 Detected {count} species: {species}',
        'train_images': '   📊 Training images: {count}',
        'val_images': '   📊 Validation images: {count}',
        'loading_model': '🤖 Loading model: {model}',
        'model_params': '   ℹ️  Model parameters: {params:,}',
        'training_config': '⚙️  Training Configuration:',
        'config_epochs': '   📈 Epochs: {epochs}',
        'config_batch': '   📦 Batch size: {batch}',
        'config_learning_rate': '   📊 Learning rate: {lr}',
        'config_optimizer': '   🔧 Optimizer: {optimizer}',
        'config_scheduler': '   📉 LR Scheduler: {scheduler}',
        'starting_training': '🚀 Starting training...',
        'training_interrupted': '\n\n⚠️  Training interrupted!',
        'saving_checkpoint': '💾 Saving checkpoint...',
        'checkpoint_saved': '✅ Checkpoint saved: {path}',
        'training_complete': '\n✅ Training complete!',
        'final_model_saved': '💾 Final model saved: {path}',
        'training_summary': '\n📊 Training Summary:',
        'best_accuracy': '   🏆 Best Accuracy: {acc:.2%}',
        'final_loss': '   📉 Final Loss: {loss:.4f}',
        
        # Testing
        'testing_model': '🧪 Testing model: {path}',
        'loading_test_model': '🤖 Loading model and processor...',
        'testing_validation': '🧪 Testing model on validation set...',
        'testing_image': '🖼️  Testing single image: {path}',
        'image_not_found': '❌ Image not found: {path}',
        'predicted_species': '   🐦 Predicted: {species} ({conf:.1%} confidence)',
        'top_predictions': '\n📊 Top 5 predictions:',
        'prediction_item': '   {rank}. {species}: {conf:.1%}',
        'testing_species': '🐦 Testing {species}...',
        'test_result': '   🐦 Predicted: {predicted} ({conf:.1%} confidence)',
        'test_summary': '\n📊 Test Results:',
        'overall_accuracy': '   🎯 Overall Accuracy: {acc:.2%}',
        'correct_predictions': '   ✅ Correct: {correct}/{total}',
        'species_accuracy': '\n📈 Per-Species Accuracy:',
        'species_acc_item': '   • {species}: {acc:.1%} ({correct}/{total})',
        
        # CLI
        'cli_extracting_from': '🎥 Extracting birds from: {path}',
        'cli_output_folder': '📁 Output folder: {path}',
        'cli_output_directory': '📁 Output directory: {path}',
        'cli_species': '🐦 Species: {species}',
        'cli_using_classifier': '🤖 Using species classifier: {path}',
        'cli_processing_video': '\n📹 Processing: {path}',
        'cli_organizing_dataset': '📊 Organizing dataset: {path}',
        'cli_training_model': '🎓 Training model on dataset: {path}',
        
        # Logging
        'log_file': '📝 Log file: {path}',
        'log_permission_denied': '⚠️  WARNING: No write permission for /var/log/vogel-kamera-linux/',
        'log_permission_hint': 'Run with sudo or change permissions:',
        
        # Training
        'train_loading_model': '🤖 Loading base model: {model}',
        'train_header': 'Bird Species Recognition Training',
        'train_ctrl_c_hint': '(Press Ctrl+C to cleanly exit)',
        'train_detecting_species': '\n🔍 Detecting bird species from directory structure...',
        'train_output_dir': '\n📁 Output directory: {path}',
        'train_species': '🐦 Bird species: {species}',
        'train_num_classes': '🔢 Number of classes: {count}',
        'train_loading_dataset': '\n📂 Loading dataset...',
        'train_dataset_size': '   Training:   {train} images',
        'train_val_size': '   Validation: {val} images',
        'train_dataset_labels': '\n📋 Dataset Labels: {labels}',
        'train_detected_species': '📋 Detected Species: {species}',
        'train_species_mismatch_warning': '\n⚠️  WARNING: Species list does not match dataset!',
        'train_species_mismatch_details': '   Dataset has: {dataset}\n   Detected: {detected}',
        'train_using_dataset_labels': '\n✅ Using Dataset Label-Mapping: {labels}',
        'train_applying_transforms': '\n🔄 Applying transformations...',
        'train_augmentation_strength': '   🎨 Augmentation strength: {strength}',
        'train_image_size': '   📐 Image size: {size}x{size}px',
        'train_starting': '\n🚀 Starting training...',
        'train_batch_size': '📦 Batch Size: {size}',
        'train_learning_rate': '📈 Learning Rate: {rate}',
        'train_epochs': '🔄 Epochs: {epochs}',
        'train_weight_decay': '⚖️  Weight Decay: {decay}',
        'train_warmup_ratio': '🔥 Warmup Ratio: {ratio}',
        'train_scheduler': '📊 LR Scheduler: {scheduler}',
        'train_early_stopping': '⏹️  Early Stopping: {patience} epochs patience',
        'train_gradient_accumulation': '🔁 Gradient Accumulation: {steps} steps',
        'train_mixed_precision': '⚡ Mixed Precision: {precision}',
        'train_saving_model': '\n💾 Saving final model: {path}',
        'train_complete': '\n✅ Training complete!',
        'train_model_saved': '📁 Model saved in: {path}',
        'train_interrupted': '\n\n⚠️  Training interrupted (Ctrl+C detected)',
        'train_waiting_clean_exit': 'Waiting for clean exit of current step...',
        'train_force_exit_hint': '(Press Ctrl+C again for immediate exit)',
        'train_force_exit': '\n⚠️  Immediate exit forced!',
        'train_error': '\n❌ Training error: {error}',
        
        # Testing
        'test_loading_model': '🤖 Loading model: {path}',
        'test_classifying_image': '🖼️  Classifying image: {path}',
        'test_results': '\nResults:',
        'test_on_validation': '\n🧪 Testing on validation set: {path}',
        'test_no_images_found': '⚠️  No images found for {species}',
        'test_overall_accuracy': '📊 Overall accuracy: {correct}/{total} = {accuracy:.1f}%',
        'test_usage': 'Usage:',
        'test_usage_single': '  Test single image:',
        'test_usage_single_cmd': '    python test_model.py <model_path> <image_path>',
        'test_usage_validation': '  Test on validation set:',
        'test_usage_validation_cmd': '    python test_model.py <model_path> --data-dir <data_dir>',
        'test_error_no_input': '❌ Please specify either image path or --data-dir',
        
        # Deduplication
        'dedup_header': 'Dataset Deduplication',
        'dedup_directory': 'Directory: {path}',
        'dedup_threshold': 'Similarity threshold: {threshold} (Hamming distance 0-64)',
        'dedup_method': 'Hash method: {method}',
        'dedup_mode': 'Mode: {mode}',
        'dedup_recursive': 'Recursive: {recursive}',
        'dedup_scanning': 'Scanning {count} images...',
        'dedup_progress': 'Hashing: {current}/{total}',
        'dedup_hashed': 'Computed {count} hashes',
        'dedup_no_duplicates': 'No duplicates found! Dataset is clean.',
        'dedup_found_groups': 'Found {count} duplicate groups',
        'dedup_found_total': 'Total duplicates: {count}',
        'dedup_report_header': 'Duplicate Groups:',
        'dedup_hint_delete': 'To delete duplicates, run:',
        'dedup_move_to': 'Moving duplicates to: {path}',
        'dedup_deleted': 'Successfully deleted {count} duplicate images',
        'dedup_moved': 'Successfully moved {count} duplicate images',
        'dedup_skipped_duplicate': '   ⏭️  Skipped duplicate: similar to {filename} (distance: {distance})',
        'dedup_stats': '\n📊 Deduplication Statistics:',
        'dedup_stats_checked': '   Checked: {count} images',
        'dedup_stats_skipped': '   Skipped: {count} duplicates ({percent:.1f}%)',
        'dedup_loading_existing': '   🔄 Loading existing images for deduplication...',
        'dedup_loaded_existing': '   ✅ Loaded {count} existing images into hash cache',
        
        # Quality Check
        'quality_check_header': 'Quality Check - Dataset Image Quality Analysis',
        'quality_check_directory': 'Directory: {directory}',
        'quality_blur_threshold': 'Blur threshold: {threshold} (Laplacian variance)',
        'quality_min_resolution': 'Minimum resolution: {resolution}px',
        'quality_min_filesize': 'Minimum file size: {size} bytes',
        'quality_brightness_check_enabled': 'Brightness check: Enabled',
        'quality_mode': 'Mode: {mode}',
        'quality_scanning': 'Scanning {count} images...',
        'quality_progress': 'Checked: {current}/{total}',
        'quality_results': 'Quality Check Results',
        'quality_total_issues': 'Images with quality issues: {count}',
        'quality_no_issues': 'No quality issues found! All images are good.',
        'quality_issues_breakdown': 'Issues by type',
        'quality_detailed_report': 'Detailed Report',
        'quality_path': 'Path',
        'quality_blur_score': 'Blur score',
        'quality_resolution': 'Resolution',
        'quality_filesize': 'File size',
        'quality_deleting': 'Deleting low-quality images...',
        'quality_deleted_file': 'Deleted: {file}',
        'quality_delete_error': 'Error deleting {file}: {error}',
        'quality_moving': 'Moving low-quality images to: {directory}',
        'quality_moved_file': 'Moved: {file}',
        'quality_move_error': 'Error moving {file}: {error}',
        'quality_summary': 'Summary',
        'quality_deleted_count': 'Deleted: {count} images',
        'quality_moved_count': 'Moved: {count} images',
        'quality_filesize_too_small': 'File too small: {size} bytes (minimum: {min_size})',
        'quality_resolution_too_small': 'Resolution too small: {width}x{height} (minimum: {min_res}px)',
        'quality_image_blurry': 'Image is blurry: score {score:.1f} (threshold: {threshold})',
        'quality_image_too_dark': 'Image too dark: brightness {brightness:.1f}',
        'quality_image_too_bright': 'Image too bright: brightness {brightness:.1f} (overexposed)',
        'quality_cannot_read_opencv': 'Cannot read image with OpenCV',
        'quality_cannot_open_image': 'Cannot open image: {error}',
        'quality_file_error': 'File error: {error}',
        
        # General
        'error': 'Error',
        'warning': 'Warning',
    },
    
    'de': {
        # Extraction
        'loading_yolo': '🤖 Lade YOLO-Modell:',
        'loading_species': '🧠 Lade Arten-Klassifizierer:',
        'loaded_species_classes': '   ✅ Geladen mit {count} Arten-Klassen',
        'video_info': '📹 Video:',
        'total_frames': '   📊 {total} Frames, {fps:.1f} FPS',
        'analyzing_every_nth': '   🔍 Analysiere jeden {n}. Frame...',
        'detection_threshold': '   🎯 Erkennungs-Schwellwert: {threshold}',
        'species_threshold': '   🎯 Arten-Schwellwert: {threshold}',
        'image_size': '   📐 Bildgröße: {size}x{size}px',
        'image_size_original': '   📐 Bildgröße: Original',
        'max_detections_per_frame': '   🔢 Max. Erkennungen pro Frame: {max}',
        'min_box_size_filter': '   📏 Min. Box-Größe: {size}px',
        'max_box_size_filter': '   📏 Max. Box-Größe: {size}px',
        'jpeg_quality_filter': '   🎨 JPEG-Qualität: {quality}',
        'blur_detection_filter': '   🔍 Unschärfe-Erkennung: Aktiviert',
        'dedup_filter': '   🔄 Deduplizierung: Aktiviert (Schwelle: {threshold})',
        'motion_sharpness_filter': '   ✨ Bewegungsschärfe-Filter: {threshold}',
        'motion_edge_filter': '   🔷 Bewegungskanten-Filter: {threshold}',
        'background_removal_enabled': '   🎭 Hintergrundentfernung: Aktiviert (rembg/AI)',
        'motion_rejected_stats': '   🚫 Abgelehnt wegen Bewegung/Unschärfe: {count}',
        'quality_report_title': '📊 Qualitätsbericht',
        'quality_report_total': '   Gesamt verarbeitete Erkennungen: {count}',
        'quality_report_accepted': '   ✅ Akzeptiert: {count} ({percent:.1f}%)',
        'quality_report_rejected': '   ❌ Abgelehnt: {count} ({percent:.1f}%)',
        'quality_report_avg_accepted': '   📈 Durchschnittliche Qualität (akzeptiert): {score:.1f}',
        'quality_report_avg_rejected_blur': '   📉 Durchschnittliche Schärfe (abgelehnt): {score:.1f}',
        'quality_report_avg_rejected_edges': '   📉 Durchschnittliche Kantenqualität (abgelehnt): {score:.1f}',
        'mode_autosorting': '   🤖 Auto-Sortier-Modus: Nutze Arten-Klassifizierer',
        'mode_manual': '   🏷️  Manueller Modus: Art = {species}',
        'mode_standard': '   📦 Standard-Modus: Alle Vögel in einem Verzeichnis',
        'cannot_open_video': '❌ Kann Video nicht öffnen: {path}',
        'bird_extracted': '   ✅ Vogel #{count}: {species} (Konf {conf:.2f}), Frame {frame}',
        'bird_extracted_simple': '   ✅ Vogel extrahiert #{count}: Frame {frame}, Konf {conf:.2f}',
        'bird_skipped': '   ⏭️  Übersprungen: {species} (Konf {conf:.2f} < {threshold:.2f}), Frame {frame}',
        'progress': '   ⏳ Fortschritt: {percent:.1f}% ({current}/{total} Frames)',
        'extraction_interrupted': '\n⚠️  Extraktion vom Benutzer unterbrochen',
        'extraction_complete': '\n✅ Extraktion abgeschlossen!',
        'output_directory': '   📁 Ausgabe-Verzeichnis: {path}',
        'detected_birds_total': '   🔍 Erkannte Vögel gesamt: {count}',
        'exported_birds_total': '   🐦 Exportierte Vögel: {count}',
        'skipped_birds_total': '   ⏭️  Übersprungen (< {threshold:.2f}): {count}',
        'total_birds': '   🐦 Extrahierte Vögel gesamt: {count}',
        'species_breakdown': '\n📊 Arten-Aufschlüsselung:',
        'species_count': '   • {species}: {count} Vögel',
        'session_id': '   🆔 Sitzungs-ID: {id}',
        'filename_format': '\n💡 Dateinamen-Format: {format}',
        'next_steps': '\n💡 Nächste Schritte:',
        'next_step_review': '   1. Überprüfe extrahierte Bilder in Arten-Unterverzeichnissen: {path}',
        'next_step_verify': '   2. Manuell Auto-Klassifizierungen verifizieren (falls Arten-Modell verwendet)',
        'next_step_manual_sort': '   2. Erstelle Unterverzeichnisse für jede Art und verschiebe Bilder in korrekte Ordner',
        'next_step_organize': '   3. Nutze organize_dataset.py um Train/Val Split zu erstellen',
        'next_step_train': '   4. Trainiere verbessertes Modell mit neuen Daten!',
        'processing_video': '📹 Verarbeite Video {idx}/{total}: {name}',
        'error_processing': '\n❌ Fehler beim Verarbeiten von {name}: {error}',
        'continuing': '   Fahre mit nächstem Video fort...',
        'all_videos_processed': '✅ Alle Videos verarbeitet!\n   📁 Ausgabeverzeichnis: {path}',
        
        # File processing (NEW)
        'files_found_header': '📁 {total} Datei(en) zum Verarbeiten gefunden:',
        'files_videos_count': '   🎬 {count} Video(s)',
        'files_images_count': '   🖼️  {count} Bild(er)',
        'files_and_more': '   ... und {count} weitere',
        'processing_videos_header': '🎬 Verarbeite {count} Video-Datei(en)',
        'processing_video_item': '📹 Verarbeite Video {idx}/{total}: {name}',
        'processing_images_header': '🖼️  Verarbeite {count} Bild-Datei(en)',
        'processing_image_item': '📸 Verarbeite Bild {idx}/{total}: {name}',
        'convert_mode_header': '🔄 KONVERTIERUNGSMODUS: Verarbeite existierende Vogelbilder',
        'convert_images_found': '🖼️  {count} Bild(er) zum Konvertieren gefunden',
        'convert_source_dir': '📁 Quelle: {path}',
        'convert_target_dir': '📁 Ziel: {path}',
        'convert_target_directory': '📁 Zielverzeichnis: {path}',
        'convert_total_processed': '🖼️  Insgesamt verarbeitet: {count}',
        'convert_quality_report': '📊 Qualitätsbericht',
        
        # Klassifizierung (Batch-Inferenz)
        'classify_header': 'Vogelbild-Massen-Klassifizierung',
        'classify_model_not_found': '❌ Modell nicht gefunden: {path}',
        'classify_loading_model': '🤖 Lade Modell: {path}',
        'classify_model_loaded': '   ✅ Modell geladen auf {device} mit {species} Arten',
        'classify_detected_species': '🐦 Erkannte Arten: {species}',
        'classify_input_not_found': '❌ Eingabe-Verzeichnis nicht gefunden: {path}',
        'classify_found_images': '📸 {count} Bilder zur Klassifizierung gefunden',
        'classify_no_images': 'ℹ️  Keine Bilder in {path} gefunden',
        'classify_processing_header': '\n🔄 Verarbeite {total} Bilder...',
        'classify_progress': 'Klassifiziere Bilder',
        'classify_image_error': '   ⚠️  Fehler bei Verarbeitung von {path}: {error}',
        'classify_exporting_csv': '\n💾 Exportiere Ergebnisse nach CSV: {path}',
        'classify_csv_saved': '   ✅ CSV-Bericht gespeichert: {path} ({count} Bilder)',
        'classify_sorting_header': '\n📁 Sortiere Bilder nach Arten...',
        'classify_copying': 'Kopiere',
        'classify_moving': 'Verschiebe',
        'classify_dry_run_mode': '(PROBELAUF)',
        'classify_sort_progress': 'Sortiere Bilder',
        'classify_file_error': '   ⚠️  Fehler bei Verarbeitung von {path}: {error}',
        'classify_sorting_complete': '   ✅ Bilder sortiert nach: {path}',
        'classify_deleting_source': '\n🗑️  Lösche Quell-Verzeichnis: {path}',
        'classify_source_deleted': '   ✅ Quell-Verzeichnis gelöscht',
        'classify_delete_error': '   ⚠️  Fehler beim Löschen der Quelle: {error}',
        'classify_delete_warning': '⚠️  WARNUNG: Quell-Verzeichnis wird nach Verarbeitung DAUERHAFT gelöscht!',
        'classify_delete_confirm': 'Fortfahren? [j/N]: ',
        'classify_cancelled': '❌ Operation vom Benutzer abgebrochen',
        'classify_statistics_header': 'Klassifizierungs-Statistik',
        'classify_total_classified': '📊 Gesamt klassifiziert: {count}',
        'classify_species_distribution': '\n🐦 Arten-Verteilung:',
        'classify_sorted_statistics': '\n📁 Dateien sortiert:',
        'classify_dry_run_complete': '✅ Probelauf abgeschlossen! Keine Dateien wurden geändert.',
        'classify_complete': '✅ Klassifizierung abgeschlossen!',
        'classify_invalid_top_k': '❌ Ungültiger top-k Wert: {k}. Muss zwischen 1 und 5 liegen.',
        'classify_invalid_confidence': '❌ Ungültiger Confidence-Schwellwert: {conf}. Muss zwischen 0.0 und 1.0 liegen.',
        
        # Evaluation
        'evaluate_header': 'Modell-Evaluierung & Analytik',
        'evaluate_model_not_found': '❌ Modell nicht gefunden: {path}',
        'evaluate_loading_model': '🤖 Lade Modell: {path}',
        'evaluate_model_loaded': '   ✅ Modell geladen auf {device} mit {species} Arten',
        'evaluate_test_dir_not_found': '❌ Test-Verzeichnis nicht gefunden: {path}',
        'evaluate_no_test_images': 'ℹ️  Keine Test-Bilder in {path} gefunden',
        'evaluate_found_images': '📸 {count} Test-Bilder über {species} Arten gefunden',
        'evaluate_species_list': 'Arten',
        'evaluate_species_mismatch': '⚠️  Warnung: Modell- und Test-Arten stimmen nicht überein!',
        'evaluate_model_species': 'Modell-Arten',
        'evaluate_test_species': 'Test-Arten',
        'evaluate_species_progress': 'Arten',
        'evaluate_processing': '🔄 Evaluiere Modell...',
        'evaluate_image_error': '   ⚠️  Fehler bei Verarbeitung von {path}: {error}',
        'evaluate_confusion_matrix_header': 'Konfusionsmatrix',
        'evaluate_metrics_header': 'Metriken pro Art',
        'evaluate_overall_accuracy': '📊 Gesamtgenauigkeit: {accuracy:.2f}%',
        'evaluate_correct': 'Korrekt',
        'evaluate_misclassified': 'Fehlklassifiziert',
        'evaluate_no_misclassifications': 'ℹ️  Keine Fehlklassifikationen gefunden!',
        'evaluate_misclassifications_saved': '   ✅ Fehlklassifikationen gespeichert: {path} ({count} Bilder)',
        'evaluate_json_saved': '   ✅ Metriken nach JSON exportiert: {path}',
        'evaluate_complete': '✅ Evaluierung abgeschlossen!',
        
        # File processing (NEW)
        'files_found_header': '📁 {total} Datei(en) zum Verarbeiten gefunden:',
        'files_videos_count': '   🎬 {count} Video(s)',
        'files_images_count': '   🖼️  {count} Bild(er)',
        'files_and_more': '   ... und {count} weitere',
        'processing_videos_header': '🎬 Verarbeite {count} Video-Datei(en)',
        'processing_video_item': '📹 Verarbeite Video {idx}/{total}: {name}',
        'processing_images_header': '🖼️  Verarbeite {count} Bild-Datei(en)',
        'processing_image_item': '📸 Verarbeite Bild {idx}/{total}: {name}',
        'convert_mode_header': '🔄 KONVERTIERUNGSMODUS: Verarbeite existierende Vogelbilder',
        'convert_images_found': '🖼️  {count} Bild(er) zum Konvertieren gefunden',
        'convert_source_dir': '📁 Quelle: {path}',
        'convert_target_dir': '📁 Ziel: {path}',
        'convert_target_directory': '📁 Zielverzeichnis: {path}',
        'convert_total_processed': '🖼️  Insgesamt verarbeitet: {count}',
        'convert_quality_report': '📊 Qualitätsbericht',
        # Organization
        'organizing_dataset': '📊 Organisiere Dataset: {path}',
        'output_dir': '📁 Ausgabe-Verzeichnis: {path}',
        'train_ratio': '📈 Train/Val Verhältnis: {ratio:.0%}/{val:.0%}',
        'found_species': '🐦 {count} Arten gefunden:',
        'species_images': '   • {species}: {count} Bilder',
        'creating_splits': '🔄 Erstelle Train/Val Splits...',
        'split_created': '   ✅ {species}: {train} Train / {val} Val',
        'organization_complete': '\n✅ Dataset organisiert!',
        'dataset_summary': '\n📊 Dataset-Zusammenfassung:',
        'total_images': '   📷 Bilder gesamt: {count}',
        'training_images': '   🏋️  Training: {count} Bilder',
        'validation_images': '   ✅ Validierung: {count} Bilder',
        'scanning_directory': '🔍 Durchsuche Verzeichnis: {path}',
        'species_found': '   {species}: {count} Bilder gefunden',
        'no_images_found': '   ⚠️  Keine Bilder gefunden!',
        'enforcing_max_images': '\n🔢 Erzwinge Maximum von {max} Bildern pro Klasse...',
        'delete_error': '   ⚠️  Fehler beim Löschen {filename}: {error}',
        'images_deleted': '   ✂️  {species}: {deleted} Bilder gelöscht ({before} → {after})',
        'total_deleted': '\n📊 Gelöschte Bilder gesamt: {count}',
        'affected_species': '   Betroffene Arten: {species}',
        'class_balance_check': '\n⚖️  Class Balance Check:',
        'balance_minimum': '   Minimum: {count} Bilder',
        'balance_maximum': '   Maximum: {count} Bilder',
        'balance_average': '   Durchschnitt: {avg:.1f} Bilder',
        'balance_difference': '   Differenz: {percent:.1f}%',
        'balance_error': '\n❌ FEHLER: Class Imbalance zu groß!',
        'balance_max_tolerance': '   Maximale Toleranz: {percent}%',
        'balance_current_diff': '   Aktuelle Differenz: {percent:.1f}%',
        'balance_affected_classes': '\n   Betroffene Klassen:',
        'balance_class_item': '   • {species:15s}: {count:4d} Bilder ({diff:+.1f}% vom Durchschnitt)',
        'balance_recommendation': '\n💡 Empfehlung:',
        'balance_rec_collect': '   - Sammle mehr Bilder für unterrepräsentierte Arten',
        'balance_rec_limit': '   - Oder nutze --max-images-per-class {limit} um auf {tolerance}% zu begrenzen',
        'balance_warning': '\n⚠️  WARNUNG: Class Balance könnte besser sein',
        'balance_warning_diff': '   Differenz: {percent:.1f}% (Toleranz: {tolerance}%)',
        'balance_warning_classes': '   Betroffene Klassen:',
        'balance_warning_item': '   • {species:15s}: {count:4d} Bilder ({diff:.1f}% unter Maximum)',
        'balance_good': '   ✅ Class Balance ist gut! (< {tolerance}%)',
        
        # Training
        'training_model': '🎓 Trainiere Modell auf Dataset: {path}',
        'model_output': '📁 Ausgabe-Verzeichnis: {path}',
        'loading_dataset': '📂 Lade Dataset von: {path}',
        'detected_species': '🐦 {count} Arten erkannt: {species}',
        'train_images': '   📊 Trainingsbilder: {count}',
        'val_images': '   📊 Validierungsbilder: {count}',
        'loading_model': '🤖 Lade Modell: {model}',
        'model_params': '   ℹ️  Modell-Parameter: {params:,}',
        'training_config': '⚙️  Trainings-Konfiguration:',
        'config_epochs': '   📈 Epochen: {epochs}',
        'config_batch': '   📦 Batch-Größe: {batch}',
        'config_learning_rate': '   📊 Lernrate: {lr}',
        'config_optimizer': '   🔧 Optimizer: {optimizer}',
        'config_scheduler': '   📉 LR Scheduler: {scheduler}',
        'starting_training': '🚀 Starte Training...',
        'training_interrupted': '\n\n⚠️  Training unterbrochen!',
        'saving_checkpoint': '💾 Speichere Checkpoint...',
        'checkpoint_saved': '✅ Checkpoint gespeichert: {path}',
        'training_complete': '\n✅ Training abgeschlossen!',
        'final_model_saved': '💾 Finales Modell gespeichert: {path}',
        'training_summary': '\n📊 Trainings-Zusammenfassung:',
        'best_accuracy': '   🏆 Beste Genauigkeit: {acc:.2%}',
        'final_loss': '   📉 Finaler Loss: {loss:.4f}',
        
        # Testing
        'testing_model': '🧪 Teste Modell: {path}',
        'loading_test_model': '🤖 Lade Modell und Prozessor...',
        'testing_validation': '🧪 Teste Modell auf Validierungs-Set...',
        'testing_image': '🖼️  Teste einzelnes Bild: {path}',
        'image_not_found': '❌ Bild nicht gefunden: {path}',
        'predicted_species': '   🐦 Vorhersage: {species} ({conf:.1%} Konfidenz)',
        'top_predictions': '\n📊 Top 5 Vorhersagen:',
        'prediction_item': '   {rank}. {species}: {conf:.1%}',
        'testing_species': '🐦 Teste {species}...',
        'test_result': '   🐦 Vorhersage: {predicted} ({conf:.1%} Konfidenz)',
        'test_summary': '\n📊 Test-Ergebnisse:',
        'overall_accuracy': '   🎯 Gesamt-Genauigkeit: {acc:.2%}',
        'correct_predictions': '   ✅ Korrekt: {correct}/{total}',
        'species_accuracy': '\n📈 Genauigkeit pro Art:',
        'species_acc_item': '   • {species}: {acc:.1%} ({correct}/{total})',
        
        # CLI
        'cli_extracting_from': '🎥 Extrahiere Vögel aus: {path}',
        'cli_output_folder': '📁 Ausgabe-Ordner: {path}',
        'cli_output_directory': '📁 Ausgabe-Verzeichnis: {path}',
        'cli_species': '🐦 Art: {species}',
        'cli_using_classifier': '🤖 Nutze Arten-Klassifizierer: {path}',
        'cli_processing_video': '\n📹 Verarbeite: {path}',
        'cli_organizing_dataset': '📊 Organisiere Dataset: {path}',
        'cli_training_model': '🎓 Trainiere Modell auf Dataset: {path}',
        
        # Logging
        'log_file': '📝 Log-Datei: {path}',
        'log_permission_denied': '⚠️  WARNUNG: Keine Schreibberechtigung für /var/log/vogel-kamera-linux/',
        'log_permission_hint': 'Mit sudo ausführen oder Berechtigungen ändern:',
        
        # Training
        'train_loading_model': '🤖 Lade Basis-Modell: {model}',
        'train_header': 'Vogel-Artenerkennung Training',
        'train_ctrl_c_hint': '(Drücke Strg+C zum sauberen Beenden)',
        'train_detecting_species': '\n🔍 Erkenne Vogelarten aus Verzeichnisstruktur...',
        'train_output_dir': '\n📁 Ausgabe-Verzeichnis: {path}',
        'train_species': '🐦 Vogelarten: {species}',
        'train_num_classes': '🔢 Anzahl Klassen: {count}',
        'train_loading_dataset': '\n📂 Lade Dataset...',
        'train_dataset_size': '   Training:   {train} Bilder',
        'train_val_size': '   Validation: {val} Bilder',
        'train_dataset_labels': '\n📋 Dataset Labels: {labels}',
        'train_detected_species': '📋 Erkannte Arten: {species}',
        'train_species_mismatch_warning': '\n⚠️  WARNUNG: Arten-Liste stimmt nicht mit Dataset überein!',
        'train_species_mismatch_details': '   Dataset hat: {dataset}\n   Erkannt wurden: {detected}',
        'train_using_dataset_labels': '\n✅ Verwende Dataset Label-Mapping: {labels}',
        'train_applying_transforms': '\n🔄 Appliziere Transformationen...',
        'train_augmentation_strength': '   🎨 Augmentation-Stärke: {strength}',
        'train_image_size': '   📐 Bildgröße: {size}x{size}px',
        'train_starting': '\n🚀 Starte Training...',
        'train_batch_size': '📦 Batch Size: {size}',
        'train_learning_rate': '📈 Learning Rate: {rate}',
        'train_epochs': '🔄 Epochen: {epochs}',
        'train_weight_decay': '⚖️  Weight Decay: {decay}',
        'train_warmup_ratio': '🔥 Warmup Ratio: {ratio}',
        'train_scheduler': '📊 LR Scheduler: {scheduler}',
        'train_early_stopping': '⏹️  Early Stopping: {patience} Epochen Geduld',
        'train_gradient_accumulation': '🔁 Gradient Accumulation: {steps} Schritte',
        'train_mixed_precision': '⚡ Mixed Precision: {precision}',
        'train_saving_model': '\n💾 Speichere finales Modell: {path}',
        'train_complete': '\n✅ Training abgeschlossen!',
        'train_model_saved': '📁 Modell gespeichert in: {path}',
        'train_interrupted': '\n\n⚠️  Training wird unterbrochen (Strg+C erkannt)',
        'train_waiting_clean_exit': 'Warte auf sauberes Beenden des aktuellen Schritts...',
        'train_force_exit_hint': '(Drücke Strg+C erneut für sofortiges Beenden)',
        'train_force_exit': '\n⚠️  Sofortiges Beenden erzwungen!',
        'train_error': '\n❌ Fehler beim Training: {error}',
        
        # Testing
        'test_loading_model': '🤖 Lade Modell: {path}',
        'test_classifying_image': '🖼️  Klassifiziere Bild: {path}',
        'test_results': '\nErgebnisse:',
        'test_on_validation': '\n🧪 Teste auf Validation Set: {path}',
        'test_no_images_found': '⚠️  Keine Bilder für {species} gefunden',
        'test_overall_accuracy': '📊 Gesamtgenauigkeit: {correct}/{total} = {accuracy:.1f}%',
        'test_usage': 'Verwendung:',
        'test_usage_single': '  Einzelnes Bild testen:',
        'test_usage_single_cmd': '    python test_model.py <model_path> <image_path>',
        'test_usage_validation': '  Auf Validation Set testen:',
        'test_usage_validation_cmd': '    python test_model.py <model_path> --data-dir <data_dir>',
        'test_error_no_input': '❌ Bitte entweder Bildpfad oder --data-dir angeben',
        
        # Deduplication
        'dedup_header': 'Dataset Deduplizierung',
        'dedup_directory': 'Verzeichnis: {path}',
        'dedup_threshold': 'Ähnlichkeitsschwelle: {threshold} (Hamming-Distanz 0-64)',
        'dedup_method': 'Hash-Methode: {method}',
        'dedup_mode': 'Modus: {mode}',
        'dedup_recursive': 'Rekursiv: {recursive}',
        'dedup_scanning': 'Scanne {count} Bilder...',
        'dedup_progress': 'Hashe: {current}/{total}',
        'dedup_hashed': '{count} Hashes berechnet',
        'dedup_no_duplicates': 'Keine Duplikate gefunden! Dataset ist sauber.',
        'dedup_found_groups': '{count} Duplikat-Gruppen gefunden',
        'dedup_found_total': 'Gesamt-Duplikate: {count}',
        'dedup_report_header': 'Duplikat-Gruppen:',
        'dedup_hint_delete': 'Um Duplikate zu löschen, führe aus:',
        'dedup_move_to': 'Verschiebe Duplikate nach: {path}',
        'dedup_deleted': '{count} doppelte Bilder erfolgreich gelöscht',
        'dedup_moved': '{count} doppelte Bilder erfolgreich verschoben',
        'dedup_skipped_duplicate': '   ⏭️  Duplikat übersprungen: ähnlich zu {filename} (Distanz: {distance})',
        'dedup_stats': '\n📊 Deduplizierungs-Statistiken:',
        'dedup_stats_checked': '   Geprüft: {count} Bilder',
        'dedup_stats_skipped': '   Übersprungen: {count} Duplikate ({percent:.1f}%)',
        'dedup_loading_existing': '   🔄 Lade existierende Bilder für Deduplizierung...',
        'dedup_loaded_existing': '   ✅ {count} existierende Bilder in Hash-Cache geladen',
        
        # Quality Check
        'quality_check_header': 'Qualitätskontrolle - Bildqualitätsanalyse des Datasets',
        'quality_check_directory': 'Verzeichnis: {directory}',
        'quality_blur_threshold': 'Unschärfe-Schwellenwert: {threshold} (Laplacian-Varianz)',
        'quality_min_resolution': 'Mindestauflösung: {resolution}px',
        'quality_min_filesize': 'Mindestdateigröße: {size} Bytes',
        'quality_brightness_check_enabled': 'Helligkeitsprüfung: Aktiviert',
        'quality_mode': 'Modus: {mode}',
        'quality_scanning': 'Scanne {count} Bilder...',
        'quality_progress': 'Geprüft: {current}/{total}',
        'quality_results': 'Qualitätskontroll-Ergebnisse',
        'quality_total_issues': 'Bilder mit Qualitätsproblemen: {count}',
        'quality_no_issues': 'Keine Qualitätsprobleme gefunden! Alle Bilder sind gut.',
        'quality_issues_breakdown': 'Probleme nach Typ',
        'quality_detailed_report': 'Detaillierter Bericht',
        'quality_path': 'Pfad',
        'quality_blur_score': 'Schärfe-Wert',
        'quality_resolution': 'Auflösung',
        'quality_filesize': 'Dateigröße',
        'quality_deleting': 'Lösche Bilder mit niedriger Qualität...',
        'quality_deleted_file': 'Gelöscht: {file}',
        'quality_delete_error': 'Fehler beim Löschen von {file}: {error}',
        'quality_moving': 'Verschiebe Bilder mit niedriger Qualität nach: {directory}',
        'quality_moved_file': 'Verschoben: {file}',
        'quality_move_error': 'Fehler beim Verschieben von {file}: {error}',
        'quality_summary': 'Zusammenfassung',
        'quality_deleted_count': 'Gelöscht: {count} Bilder',
        'quality_moved_count': 'Verschoben: {count} Bilder',
        'quality_filesize_too_small': 'Datei zu klein: {size} Bytes (Minimum: {min_size})',
        'quality_resolution_too_small': 'Auflösung zu klein: {width}x{height} (Minimum: {min_res}px)',
        'quality_image_blurry': 'Bild ist unscharf: Wert {score:.1f} (Schwellenwert: {threshold})',
        'quality_image_too_dark': 'Bild zu dunkel: Helligkeit {brightness:.1f}',
        'quality_image_too_bright': 'Bild zu hell: Helligkeit {brightness:.1f} (überbelichtet)',
        'quality_cannot_read_opencv': 'Bild kann nicht mit OpenCV gelesen werden',
        'quality_cannot_open_image': 'Bild kann nicht geöffnet werden: {error}',
        'quality_file_error': 'Dateifehler: {error}',
        
        # General
        'error': 'Fehler',
        'warning': 'Warnung',
    },
    
    'ja': {
        # Extraction
        'loading_yolo': '🤖 YOLOモデルを読み込んでいます：',
        'loading_species': '🧠 種分類器を読み込んでいます：',
        'loaded_species_classes': '   ✅ {count}種のクラスを読み込みました',
        'video_info': '📹 ビデオ：',
        'total_frames': '   📊 {total}フレーム、{fps:.1f} FPS',
        'analyzing_every_nth': '   🔍 {n}フレームごとに分析中...',
        'detection_threshold': '   🎯 検出しきい値：{threshold}',
        'species_threshold': '   🎯 種のしきい値：{threshold}',
        'image_size': '   📐 画像サイズ：{size}x{size}px',
        'image_size_original': '   📐 画像サイズ：オリジナル',
        'max_detections_per_frame': '   🔢 フレームごとの最大検出数：{max}',
        'min_box_size_filter': '   📏 最小ボックスサイズ：{size}px',
        'max_box_size_filter': '   📏 最大ボックスサイズ：{size}px',
        'jpeg_quality_filter': '   🎨 JPEG品質：{quality}',
        'blur_detection_filter': '   🔍 ぼやけ検出：有効',
        'dedup_filter': '   🔄 重複削除：有効（閾値：{threshold}）',
        'motion_sharpness_filter': '   ✨ モーションシャープネスフィルター：{threshold}',
        'motion_edge_filter': '   🔷 モーションエッジ品質フィルター：{threshold}',
        'background_removal_enabled': '   🎭 背景除去：有効（rembg/AI）',
        'motion_rejected_stats': '   🚫 モーション/ぼやけで拒否：{count}',
        'quality_report_title': '📊 品質レポート',
        'quality_report_total': '   処理された総検出数：{count}',
        'quality_report_accepted': '   ✅ 受け入れ：{count} ({percent:.1f}%)',
        'quality_report_rejected': '   ❌ 拒否：{count} ({percent:.1f}%)',
        'quality_report_avg_accepted': '   📈 平均品質（受け入れ）：{score:.1f}',
        'quality_report_avg_rejected_blur': '   📉 平均シャープネス（拒否）：{score:.1f}',
        'quality_report_avg_rejected_edges': '   📉 平均エッジ品質（拒否）：{score:.1f}',
        'mode_autosorting': '   🤖 自動ソートモード：種分類器を使用',
        'mode_manual': '   🏷️  手動モード：種 = {species}',
        'mode_standard': '   📦 標準モード：すべての鳥を1つのディレクトリに',
        'cannot_open_video': '❌ ビデオを開けません：{path}',
        'bird_extracted': '   ✅ 鳥 #{count}：{species}（信頼度 {conf:.2f}）、フレーム {frame}',
        'bird_extracted_simple': '   ✅ 鳥を抽出 #{count}：フレーム {frame}、信頼度 {conf:.2f}',
        'bird_skipped': '   ⏭️  スキップ：{species}（信頼度 {conf:.2f} < {threshold:.2f}）、フレーム {frame}',
        'progress': '   ⏳ 進行状況：{percent:.1f}% （{current}/{total} フレーム）',
        'extraction_interrupted': '\n⚠️  ユーザーによって抽出が中断されました',
        'extraction_complete': '\n✅ 抽出完了！',
        'output_directory': '   📁 出力ディレクトリ：{path}',
        'detected_birds_total': '   🔍 検出された鳥の総数：{count}',
        'exported_birds_total': '   🐦 エクスポートされた鳥：{count}',
        'skipped_birds_total': '   ⏭️  スキップされた (< {threshold:.2f})：{count}',
        'total_birds': '   🐦 抽出された鳥の総数：{count}',
        'species_breakdown': '\n📊 種の内訳：',
        'species_count': '   • {species}：{count}羽',
        'session_id': '   🆔 セッションID：{id}',
        'filename_format': '\n💡 ファイル名形式：{format}',
        'next_steps': '\n💡 次のステップ：',
        'next_step_review': '   1. 種サブディレクトリ内の抽出画像を確認：{path}',
        'next_step_verify': '   2. 自動分類を手動で確認（種モデル使用時）',
        'next_step_manual_sort': '   2. 各種のサブディレクトリを作成し、画像を正しいフォルダに移動',
        'next_step_organize': '   3. organize_dataset.pyを使用してトレーニング/検証分割を作成',
        'next_step_train': '   4. 新しいデータで改善されたモデルをトレーニング！',
        'processing_video': '📹 ビデオ処理中 {idx}/{total}：{name}',
        'error_processing': '\n❌ {name}の処理中にエラーが発生しました：{error}',
        'continuing': '   次のビデオに進みます...',
        'all_videos_processed': '✅ すべてのビデオを処理しました！\n   📁 出力ディレクトリ：{path}',
        
        # File processing (NEW)
        'files_found_header': '📁 {total}個のファイルが見つかりました:',
        'files_videos_count': '   🎬 {count}個の動画',
        'files_images_count': '   🖼️  {count}個の画像',
        'files_and_more': '   ... 他{count}個',
        'processing_videos_header': '🎬 {count}個の動画ファイルを処理中',
        'processing_video_item': '📹 動画を処理中 {idx}/{total}: {name}',
        'processing_images_header': '🖼️  {count}個の画像ファイルを処理中',
        'processing_image_item': '📸 画像を処理中 {idx}/{total}: {name}',
        'convert_mode_header': '🔄 変換モード: 既存の鳥画像を処理中',
        'convert_images_found': '🖼️  {count}個の画像が変換対象として見つかりました',
        'convert_source_dir': '📁 ソース: {path}',
        'convert_target_dir': '📁 ターゲット: {path}',
        'convert_target_directory': '📁 ターゲットディレクトリ: {path}',
        'convert_total_processed': '🖼️  処理済み合計: {count}',
        'convert_quality_report': '📊 品質レポート',
        
        # 分類（バッチ推論）
        'classify_header': '鳥画像一括分類',
        'classify_model_not_found': '❌ モデルが見つかりません：{path}',
        'classify_loading_model': '🤖 モデルを読み込み中：{path}',
        'classify_model_loaded': '   ✅ {device}に{species}種のモデルをロード',
        'classify_detected_species': '🐦 検出された種：{species}',
        'classify_input_not_found': '❌ 入力ディレクトリが見つかりません：{path}',
        'classify_found_images': '📸 分類する画像が{count}枚見つかりました',
        'classify_no_images': 'ℹ️  {path}に画像が見つかりません',
        'classify_processing_header': '\n🔄 {total}枚の画像を処理中...',
        'classify_progress': '画像を分類中',
        'classify_image_error': '   ⚠️  {path}の処理中にエラー：{error}',
        'classify_exporting_csv': '\n💾 結果をCSVにエクスポート中：{path}',
        'classify_csv_saved': '   ✅ CSVレポート保存：{path}（{count}枚の画像）',
        'classify_sorting_header': '\n📁 種別に画像を振り分け中...',
        'classify_copying': 'コピー中',
        'classify_moving': '移動中',
        'classify_dry_run_mode': '（ドライラン）',
        'classify_sort_progress': '画像を振り分け中',
        'classify_file_error': '   ⚠️  {path}の処理中にエラー：{error}',
        'classify_sorting_complete': '   ✅ 画像を振り分けました：{path}',
        'classify_deleting_source': '\n🗑️  ソースディレクトリを削除中：{path}',
        'classify_source_deleted': '   ✅ ソースディレクトリを削除しました',
        'classify_delete_error': '   ⚠️  ソース削除中にエラー：{error}',
        'classify_delete_warning': '⚠️  警告：処理後にソースディレクトリが完全に削除されます！',
        'classify_delete_confirm': '続行しますか？ [y/N]: ',
        'classify_cancelled': '❌ ユーザーによって操作がキャンセルされました',
        'classify_statistics_header': '分類統計',
        'classify_total_classified': '📊 分類済み合計：{count}',
        'classify_species_distribution': '\n🐦 種の分布：',
        'classify_sorted_statistics': '\n📁 振り分けられたファイル：',
        'classify_dry_run_complete': '✅ ドライラン完了！ファイルは変更されませんでした。',
        'classify_complete': '✅ 分類完了！',
        'classify_invalid_top_k': '❌ 無効なtop-k値：{k}。1から5の間で指定してください。',
        'classify_invalid_confidence': '❌ 無効な信頼度閾値：{conf}。0.0から1.0の間で指定してください。',
        
        # Evaluation
        'evaluate_header': 'モデル評価・解析',
        'evaluate_model_not_found': '❌ モデルが見つかりません：{path}',
        'evaluate_loading_model': '🤖 モデルを読み込み中：{path}',
        'evaluate_model_loaded': '   ✅ {device}に{species}種のモデルをロード',
        'evaluate_test_dir_not_found': '❌ テストディレクトリが見つかりません：{path}',
        'evaluate_no_test_images': 'ℹ️  {path}にテスト画像が見つかりません',
        'evaluate_found_images': '📸 {species}種にわたる{count}枚のテスト画像を発見',
        'evaluate_species_list': '種',
        'evaluate_species_mismatch': '⚠️  警告：モデルとテストの種が一致しません！',
        'evaluate_model_species': 'モデルの種',
        'evaluate_test_species': 'テストの種',
        'evaluate_species_progress': '種',
        'evaluate_processing': '🔄 モデルを評価中...',
        'evaluate_image_error': '   ⚠️  {path}の処理中にエラー：{error}',
        'evaluate_confusion_matrix_header': '混同行列',
        'evaluate_metrics_header': '種別メトリクス',
        'evaluate_overall_accuracy': '📊 総合精度：{accuracy:.2f}%',
        'evaluate_correct': '正解',
        'evaluate_misclassified': '誤分類',
        'evaluate_no_misclassifications': 'ℹ️  誤分類は見つかりませんでした！',
        'evaluate_misclassifications_saved': '   ✅ 誤分類を保存：{path}（{count}枚の画像）',
        'evaluate_json_saved': '   ✅ メトリクスをJSONにエクスポート：{path}',
        'evaluate_complete': '✅ 評価完了！',
        
        # Organization
        'organizing_dataset': '📊 データセットを整理中：{path}',
        'output_dir': '📁 出力ディレクトリ：{path}',
        'train_ratio': '📈 トレーニング/検証比率：{ratio:.0%}/{val:.0%}',
        'found_species': '🐦 {count}種を発見：',
        'species_images': '   • {species}：{count}枚の画像',
        'creating_splits': '🔄 トレーニング/検証分割を作成中...',
        'split_created': '   ✅ {species}：{train}トレーニング / {val}検証',
        'organization_complete': '\n✅ データセット整理完了！',
        'dataset_summary': '\n📊 データセット概要：',
        'total_images': '   📷 総画像数：{count}',
        'training_images': '   🏋️  トレーニング：{count}枚',
        'validation_images': '   ✅ 検証：{count}枚',
        'scanning_directory': '🔍 ディレクトリをスキャン中：{path}',
        'species_found': '   {species}：{count}枚の画像を発見',
        'no_images_found': '   ⚠️  画像が見つかりません！',
        'enforcing_max_images': '\n🔢 クラスごとに最大{max}枚の画像を適用中...',
        'delete_error': '   ⚠️  {filename}の削除エラー：{error}',
        'images_deleted': '   ✂️  {species}：{deleted}枚削除（{before} → {after}）',
        'total_deleted': '\n📊 削除された画像の合計：{count}',
        'affected_species': '   影響を受けた種：{species}',
        'class_balance_check': '\n⚖️  クラスバランスチェック：',
        'balance_minimum': '   最小：{count}枚',
        'balance_maximum': '   最大：{count}枚',
        'balance_average': '   平均：{avg:.1f}枚',
        'balance_difference': '   差：{percent:.1f}%',
        'balance_error': '\n❌ エラー：クラス不均衡が大きすぎます！',
        'balance_max_tolerance': '   最大許容差：{percent}%',
        'balance_current_diff': '   現在の差：{percent:.1f}%',
        'balance_affected_classes': '\n   影響を受けたクラス：',
        'balance_class_item': '   • {species:15s}：{count:4d}枚（平均から{diff:+.1f}%）',
        'balance_recommendation': '\n💡 推奨事項：',
        'balance_rec_collect': '   - 過小評価された種のためにより多くの画像を収集',
        'balance_rec_limit': '   - または --max-images-per-class {limit} を使用して{tolerance}%に制限',
        'balance_warning': '\n⚠️  警告：クラスバランスが改善の余地あり',
        'balance_warning_diff': '   差：{percent:.1f}%（許容差：{tolerance}%）',
        'balance_warning_classes': '   影響を受けたクラス：',
        'balance_warning_item': '   • {species:15s}：{count:4d}枚（最大より{diff:.1f}%少ない）',
        'balance_good': '   ✅ クラスバランスは良好です！（< {tolerance}%）',
        
        # Training
        'training_model': '🎓 データセットでモデルをトレーニング中：{path}',
        'model_output': '📁 出力ディレクトリ：{path}',
        'loading_dataset': '📂 データセットを読み込んでいます：{path}',
        'detected_species': '🐦 {count}種を検出：{species}',
        'train_images': '   📊 トレーニング画像：{count}',
        'val_images': '   📊 検証画像：{count}',
        'loading_model': '🤖 モデルを読み込んでいます：{model}',
        'model_params': '   ℹ️  モデルパラメータ：{params:,}',
        'training_config': '⚙️  トレーニング設定：',
        'config_epochs': '   📈 エポック数：{epochs}',
        'config_batch': '   📦 バッチサイズ：{batch}',
        'config_learning_rate': '   📊 学習率：{lr}',
        'config_optimizer': '   🔧 オプティマイザー：{optimizer}',
        'config_scheduler': '   📉 LRスケジューラー：{scheduler}',
        'starting_training': '🚀 トレーニング開始...',
        'training_interrupted': '\n\n⚠️  トレーニングが中断されました！',
        'saving_checkpoint': '💾 チェックポイントを保存中...',
        'checkpoint_saved': '✅ チェックポイント保存完了：{path}',
        'training_complete': '\n✅ トレーニング完了！',
        'final_model_saved': '💾 最終モデル保存完了：{path}',
        'training_summary': '\n📊 トレーニング概要：',
        'best_accuracy': '   🏆 最高精度：{acc:.2%}',
        'final_loss': '   📉 最終損失：{loss:.4f}',
        
        # Testing
        'testing_model': '🧪 モデルをテスト中：{path}',
        'loading_test_model': '🤖 モデルとプロセッサーを読み込んでいます...',
        'testing_validation': '🧪 検証セットでモデルをテスト中...',
        'testing_image': '🖼️  単一画像をテスト中：{path}',
        'image_not_found': '❌ 画像が見つかりません：{path}',
        'predicted_species': '   🐦 予測：{species}（{conf:.1%}信頼度）',
        'top_predictions': '\n📊 上位5つの予測：',
        'prediction_item': '   {rank}. {species}：{conf:.1%}',
        'testing_species': '🐦 {species}をテスト中...',
        'test_result': '   🐦 予測：{predicted}（{conf:.1%}信頼度）',
        'test_summary': '\n📊 テスト結果：',
        'overall_accuracy': '   🎯 全体精度：{acc:.2%}',
        'correct_predictions': '   ✅ 正解：{correct}/{total}',
        'species_accuracy': '\n📈 種ごとの精度：',
        'species_acc_item': '   • {species}：{acc:.1%}（{correct}/{total}）',
        
        # CLI
        'cli_extracting_from': '🎥 鳥を抽出中：{path}',
        'cli_output_folder': '📁 出力フォルダ：{path}',
        'cli_output_directory': '📁 出力ディレクトリ：{path}',
        'cli_species': '🐦 種：{species}',
        'cli_using_classifier': '🤖 種分類器を使用：{path}',
        'cli_processing_video': '\n📹 処理中：{path}',
        'cli_organizing_dataset': '📊 データセット整理中：{path}',
        'cli_training_model': '🎓 データセットでモデルをトレーニング中：{path}',
        
        # Logging
        'log_file': '📝 ログファイル：{path}',
        'log_permission_denied': '⚠️  警告：/var/log/vogel-kamera-linux/への書き込み権限がありません',
        'log_permission_hint': 'sudoで実行するか、権限を変更してください：',
        
        # Training
        'train_loading_model': '🤖 ベースモデルを読み込み中：{model}',
        'train_header': '鳥種認識トレーニング',
        'train_ctrl_c_hint': '（Ctrl+Cできれいに終了）',
        'train_detecting_species': '\n🔍 ディレクトリ構造から鳥種を検出中...',
        'train_output_dir': '\n📁 出力ディレクトリ：{path}',
        'train_species': '🐦 鳥の種：{species}',
        'train_num_classes': '🔢 クラス数：{count}',
        'train_loading_dataset': '\n📂 データセットを読み込み中...',
        'train_dataset_size': '   トレーニング：{train}枚の画像',
        'train_val_size': '   検証：{val}枚の画像',
        'train_dataset_labels': '\n📋 データセットラベル：{labels}',
        'train_detected_species': '📋 検出された種：{species}',
        'train_species_mismatch_warning': '\n⚠️  警告：種リストがデータセットと一致しません！',
        'train_species_mismatch_details': '   データセット：{dataset}\n   検出：{detected}',
        'train_using_dataset_labels': '\n✅ データセットラベルマッピングを使用：{labels}',
        'train_applying_transforms': '\n🔄 変換を適用中...',
        'train_augmentation_strength': '   🎨 拡張強度：{strength}',
        'train_image_size': '   📐 画像サイズ：{size}x{size}px',
        'train_starting': '\n🚀 トレーニング開始...',
        'train_batch_size': '📦 バッチサイズ：{size}',
        'train_learning_rate': '📈 学習率：{rate}',
        'train_epochs': '🔄 エポック：{epochs}',
        'train_weight_decay': '⚖️  重み減衰：{decay}',
        'train_warmup_ratio': '🔥 ウォームアップ比：{ratio}',
        'train_scheduler': '📊 LRスケジューラー：{scheduler}',
        'train_early_stopping': '⏹️  早期停止：{patience}エポックの忍耐',
        'train_gradient_accumulation': '🔁 勾配累積：{steps}ステップ',
        'train_mixed_precision': '⚡ 混合精度：{precision}',
        'train_saving_model': '\n💾 最終モデルを保存中：{path}',
        'train_complete': '\n✅ トレーニング完了！',
        'train_model_saved': '📁 モデル保存先：{path}',
        'train_interrupted': '\n\n⚠️  トレーニング中断（Ctrl+C検出）',
        'train_waiting_clean_exit': '現在のステップのクリーンな終了を待っています...',
        'train_force_exit_hint': '（Ctrl+Cを再度押すと即座に終了）',
        'train_force_exit': '\n⚠️  即座の終了を強制！',
        'train_error': '\n❌ トレーニングエラー：{error}',
        
        # Testing
        'test_loading_model': '🤖 モデルを読み込み中：{path}',
        'test_classifying_image': '🖼️  画像を分類中：{path}',
        'test_results': '\n結果：',
        'test_on_validation': '\n🧪 検証セットでテスト中：{path}',
        'test_no_images_found': '⚠️  {species}の画像が見つかりません',
        'test_overall_accuracy': '📊 全体精度：{correct}/{total} = {accuracy:.1f}%',
        'test_usage': '使用方法：',
        'test_usage_single': '  単一画像をテスト：',
        'test_usage_single_cmd': '    python test_model.py <model_path> <image_path>',
        'test_usage_validation': '  検証セットでテスト：',
        'test_usage_validation_cmd': '    python test_model.py <model_path> --data-dir <data_dir>',
        'test_error_no_input': '❌ 画像パスまたは--data-dirを指定してください',
        
        # Deduplication
        'dedup_header': 'データセット重複削除',
        'dedup_directory': 'ディレクトリ：{path}',
        'dedup_threshold': '類似度閾値：{threshold}（ハミング距離0-64）',
        'dedup_method': 'ハッシュ方法：{method}',
        'dedup_mode': 'モード：{mode}',
        'dedup_recursive': '再帰的：{recursive}',
        'dedup_scanning': '{count}枚の画像をスキャン中...',
        'dedup_progress': 'ハッシュ計算：{current}/{total}',
        'dedup_hashed': '{count}個のハッシュを計算',
        'dedup_no_duplicates': '重複が見つかりませんでした！データセットはクリーンです。',
        'dedup_found_groups': '{count}個の重複グループを発見',
        'dedup_found_total': '合計重複：{count}',
        'dedup_report_header': '重複グループ：',
        'dedup_hint_delete': '重複を削除するには、次を実行：',
        'dedup_move_to': '重複を移動先：{path}',
        'dedup_deleted': '{count}枚の重複画像を正常に削除',
        'dedup_moved': '{count}枚の重複画像を正常に移動',
        'dedup_skipped_duplicate': '   ⏭️  重複をスキップ：{filename}に類似（距離：{distance}）',
        'dedup_stats': '\n📊 重複削除統計：',
        'dedup_stats_checked': '   チェック済み：{count}枚の画像',
        'dedup_stats_skipped': '   スキップ：{count}枚の重複（{percent:.1f}%）',
        'dedup_loading_existing': '   🔄 重複削除のため既存画像を読み込み中...',
        'dedup_loaded_existing': '   ✅ {count}枚の既存画像をハッシュキャッシュに読み込みました',
        
        # Quality Check
        'quality_check_header': '品質チェック - データセット画像品質分析',
        'quality_check_directory': 'ディレクトリ：{directory}',
        'quality_blur_threshold': 'ぼかし閾値：{threshold}（ラプラシアン分散）',
        'quality_min_resolution': '最小解像度：{resolution}px',
        'quality_min_filesize': '最小ファイルサイズ：{size}バイト',
        'quality_brightness_check_enabled': '明るさチェック：有効',
        'quality_mode': 'モード：{mode}',
        'quality_scanning': '{count}枚の画像をスキャン中...',
        'quality_progress': 'チェック済み：{current}/{total}',
        'quality_results': '品質チェック結果',
        'quality_total_issues': '品質問題のある画像：{count}',
        'quality_no_issues': '品質問題は見つかりませんでした！すべての画像は良好です。',
        'quality_issues_breakdown': 'タイプ別問題',
        'quality_detailed_report': '詳細レポート',
        'quality_path': 'パス',
        'quality_blur_score': 'ぼかしスコア',
        'quality_resolution': '解像度',
        'quality_filesize': 'ファイルサイズ',
        'quality_deleting': '低品質画像を削除中...',
        'quality_deleted_file': '削除：{file}',
        'quality_delete_error': '{file}の削除エラー：{error}',
        'quality_moving': '低品質画像を移動先：{directory}',
        'quality_moved_file': '移動：{file}',
        'quality_move_error': '{file}の移動エラー：{error}',
        'quality_summary': '概要',
        'quality_deleted_count': '削除：{count}枚の画像',
        'quality_moved_count': '移動：{count}枚の画像',
        'quality_filesize_too_small': 'ファイルが小さすぎます：{size}バイト（最小：{min_size}）',
        'quality_resolution_too_small': '解像度が小さすぎます：{width}x{height}（最小：{min_res}px）',
        'quality_image_blurry': '画像がぼやけています：スコア{score:.1f}（閾値：{threshold}）',
        'quality_image_too_dark': '画像が暗すぎます：明るさ{brightness:.1f}',
        'quality_image_too_bright': '画像が明るすぎます：明るさ{brightness:.1f}（露出過多）',
        'quality_cannot_read_opencv': 'OpenCVで画像を読み取れません',
        'quality_cannot_open_image': '画像を開けません：{error}',
        'quality_file_error': 'ファイルエラー：{error}',
        
        # General
        'error': 'エラー',
        'warning': '警告',
    }
}

# Current language (default: English)
_current_lang = 'en'


def detect_language():
    """Detect system language from environment variables."""
    lang = os.environ.get('LANG', '')
    
    if lang.startswith('de'):
        return 'de'
    elif lang.startswith('ja'):
        return 'ja'
    else:
        return 'en'


def set_language(lang):
    """Set the current language."""
    global _current_lang
    if lang in TRANSLATIONS:
        _current_lang = lang
    else:
        _current_lang = 'en'


def get_text(key, **kwargs):
    """
    Get translated text for the given key.
    
    Args:
        key: Translation key
        **kwargs: Format parameters for the translation string
        
    Returns:
        Formatted translation string
    """
    translation = TRANSLATIONS.get(_current_lang, TRANSLATIONS['en']).get(key, key)
    
    if kwargs:
        try:
            return translation.format(**kwargs)
        except KeyError:
            return translation
    
    return translation


# Alias for shorter usage
_ = get_text


# Auto-detect language on module import
_current_lang = detect_language()
