Parcourir la source

Refactor i18n tools for improved readability and consistency

- Updated string formatting to use double quotes consistently across files.
- Reformatted multi-line dictionaries and sets for better readability.
- Simplified regex patterns and improved whitespace handling in string processing functions.
- Enhanced file handling by removing unnecessary encoding specifications.
- Cleaned up comments and added spacing for better code organization.
- Removed trailing whitespace and unnecessary blank lines for cleaner diffs.
Manuel il y a 7 mois
Parent
commit
fab5568b71

+ 1 - 1
routes/admin/acls.py

@@ -1,6 +1,7 @@
 """Admin ACL management routes."""
 
 from flask import flash, redirect, render_template, request, url_for
+from flask_babel import gettext as _
 
 from services.auth.auth_service import admin_required
 from services.squid.acls_service import (
@@ -14,7 +15,6 @@ from services.squid.acls_service import (
 )
 
 from .helpers import flash_and_redirect, get_config_manager, get_int_form_field
-from flask_babel import gettext as _
 
 
 def register_routes(bp):

+ 10 - 4
routes/admin/backup.py

@@ -1,11 +1,11 @@
 """Admin backup API routes."""
 
 from flask import jsonify, request, send_file
+from flask_babel import gettext as _
 from loguru import logger
 
 from services.auth.auth_service import admin_required
 from services.database import backup_service
-from flask_babel import gettext as _
 
 
 def register_routes(bp):
@@ -27,7 +27,9 @@ def register_routes(bp):
             ), 400
 
         if cfg.get("frequency") not in backup_service.FREQUENCY_CHOICES:
-            return jsonify({"status": "error", "message": _("Frecuencia inválida")}), 400
+            return jsonify(
+                {"status": "error", "message": _("Frecuencia inválida")}
+            ), 400
 
         if "enabled" in cfg:
             cfg["enabled"] = bool(cfg["enabled"])
@@ -52,14 +54,18 @@ def register_routes(bp):
             return jsonify({"status": "success", "backups": backups})
         except Exception:
             logger.exception("Error listing backups")
-            return jsonify({"status": "error", "message": _("Error leyendo salvas")}), 500
+            return jsonify(
+                {"status": "error", "message": _("Error leyendo salvas")}
+            ), 500
 
     @bp.route("/backup/download/<filename>")
     @admin_required
     def backup_download(filename):
         path = backup_service.get_backup_file_path(filename)
         if path is None:
-            return jsonify({"status": "error", "message": _("Archivo no encontrado")}), 404
+            return jsonify(
+                {"status": "error", "message": _("Archivo no encontrado")}
+            ), 404
         return send_file(path, as_attachment=True, download_name=filename)
 
     @bp.route("/backup/delete/<filename>", methods=["DELETE"])

+ 13 - 4
routes/admin/blacklist.py

@@ -1,6 +1,7 @@
 """Admin blacklist management routes."""
 
 from flask import flash, redirect, render_template, request, url_for
+from flask_babel import gettext as _
 from loguru import logger
 
 from database.database import get_session
@@ -23,7 +24,6 @@ from services.security.blocklist_enforcement import (
     get_enforced_blocklist_urls,
 )
 
-from flask_babel import gettext as _
 from .helpers import (
     flash_and_redirect,
     flash_error_with_details,
@@ -153,12 +153,17 @@ def register_routes(bp):
                 ok, msg = enable_single_blocklist(None, cm)
                 if ok:
                     flash(
-                        _("Lista personalizada guardada y archivo custom de Squid actualizado"),
+                        _(
+                            "Lista personalizada guardada y archivo custom de Squid actualizado"
+                        ),
                         "success",
                     )
                 else:
                     flash(
-                        _("Lista personalizada guardada en DB, pero no se pudo regenerar el archivo de Squid: %(msg)s") % {"msg": msg},
+                        _(
+                            "Lista personalizada guardada en DB, pero no se pudo regenerar el archivo de Squid: %(msg)s"
+                        )
+                        % {"msg": msg},
                         "error",
                     )
             else:
@@ -180,7 +185,11 @@ def register_routes(bp):
         count = delete_blacklist_by_source_url(url)
         disable_single_blocklist(url, cm)
         invalidate_blacklist_cache()
-        flash(_("Lista eliminada: %(url)s (%(count)s dominios)") % {"url": url, "count": count}, "success")
+        flash(
+            _("Lista eliminada: %(url)s (%(count)s dominios)")
+            % {"url": url, "count": count},
+            "success",
+        )
         return redirect(url_for("admin.manage_blacklist"))
 
     @bp.route("/api/blocklist/toggle", methods=["POST"])

+ 1 - 1
routes/admin/http_access.py

@@ -1,6 +1,7 @@
 """Admin http_access rules management routes."""
 
 from flask import flash, redirect, render_template, request, url_for
+from flask_babel import gettext as _
 
 from services.auth.auth_service import admin_required
 from services.squid.http_access_service import (
@@ -17,7 +18,6 @@ from services.squid.http_access_service import (
 )
 
 from .helpers import flash_and_redirect, get_config_manager, get_int_form_field
-from flask_babel import gettext as _
 
 
 def register_routes(bp):

+ 1 - 1
routes/admin/ldap_config.py

@@ -1,11 +1,11 @@
 """Admin LDAP / Active Directory configuration routes."""
 
 from flask import jsonify, render_template, request
+from flask_babel import gettext as _
 from loguru import logger
 
 from services.auth.auth_service import admin_required, api_auth_required
 from services.ldap import ldap_config_service, ldap_service
-from flask_babel import gettext as _
 
 
 def _load_request_config():

+ 1 - 1
routes/admin/squid_config.py

@@ -1,6 +1,7 @@
 """Admin Squid configuration routes (view, edit, env, split)."""
 
 from flask import flash, jsonify, redirect, render_template, request, url_for
+from flask_babel import gettext as _
 from loguru import logger
 
 from services.auth.auth_service import admin_required, api_auth_required
@@ -17,7 +18,6 @@ from services.squid.split_config_service import (
 )
 from services.squid.squid_config_splitter import SquidConfigSplitter
 
-from flask_babel import gettext as _
 from .helpers import (
     flash_error_with_details,
     get_config_manager,

+ 1 - 1
routes/admin/users.py

@@ -1,12 +1,12 @@
 """Admin user management routes."""
 
 from flask import flash, redirect, render_template, request, url_for
+from flask_babel import gettext as _
 
 from services.auth import user_service
 from services.auth.auth_service import AuthService, admin_required
 
 from .helpers import flash_and_redirect
-from flask_babel import gettext as _
 
 
 def register_routes(bp):

+ 26 - 8
routes/admin_routes.py

@@ -13,8 +13,8 @@ from flask import (
     request,
     url_for,
 )
-from loguru import logger
 from flask_babel import gettext as _
+from loguru import logger
 
 from config import Config
 from database.database import get_session
@@ -147,7 +147,10 @@ def edit_config():
                 show_details = False
 
             if show_details:
-                flash(_("Error saving configuration: %(message)s") % {"message": message}, "error")
+                flash(
+                    _("Error saving configuration: %(message)s") % {"message": message},
+                    "error",
+                )
             else:
                 flash(_("Error saving configuration"), "error")
     return render_template(
@@ -344,7 +347,10 @@ def blacklist_import():
             except RuntimeError:
                 show_details = False
             if show_details:
-                flash(_("Error al procesar el archivo: %(error)s") % {"error": str(e)}, "error")
+                flash(
+                    _("Error al procesar el archivo: %(error)s") % {"error": str(e)},
+                    "error",
+                )
             else:
                 flash(_("Error al procesar el archivo"), "error")
             return redirect(url_for("admin.manage_blacklist"))
@@ -378,7 +384,9 @@ def blacklist_import():
         except RuntimeError:
             show_details = False
         if show_details:
-            flash(_("Error al guardar blacklist: %(error)s") % {"error": str(e)}, "error")
+            flash(
+                _("Error al guardar blacklist: %(error)s") % {"error": str(e)}, "error"
+            )
         else:
             flash(_("Error al guardar blacklist"), "error")
 
@@ -411,7 +419,9 @@ def blacklist_save_custom():
         except RuntimeError:
             show_details = False
         if show_details:
-            flash(_("Error al guardar la lista: %(error)s") % {"error": str(e)}, "error")
+            flash(
+                _("Error al guardar la lista: %(error)s") % {"error": str(e)}, "error"
+            )
         else:
             flash(_("Error al guardar la lista"), "error")
 
@@ -735,7 +745,9 @@ def split_config():
         return jsonify(
             {
                 "status": "error",
-                "message": _("Archivo requerido no encontrado. Verifique la configuración del archivo squid.conf."),
+                "message": _(
+                    "Archivo requerido no encontrado. Verifique la configuración del archivo squid.conf."
+                ),
             }
         ), 404
 
@@ -744,7 +756,9 @@ def split_config():
         return jsonify(
             {
                 "status": "error",
-                "message": _("No se tienen permisos suficientes para crear los archivos"),
+                "message": _(
+                    "No se tienen permisos suficientes para crear los archivos"
+                ),
             }
         ), 403
 
@@ -795,7 +809,11 @@ def blacklist_delete_list():
     count = delete_blacklist_by_source_url(url)
     # Also disable enforcement if the list was enforced
     _disable_single_blocklist(url, config_manager)
-    flash(_("Lista eliminada: %(url)s (%(count)s dominios)") % {"url": url, "count": count}, "success")
+    flash(
+        _("Lista eliminada: %(url)s (%(count)s dominios)")
+        % {"url": url, "count": count},
+        "success",
+    )
     return redirect(url_for("admin.manage_blacklist"))
 
 

+ 1 - 1
routes/api_routes.py

@@ -1,4 +1,5 @@
 from flask import Blueprint, current_app, jsonify, request
+from flask_babel import gettext as _
 from loguru import logger
 from werkzeug.exceptions import BadRequest
 
@@ -24,7 +25,6 @@ from services.squid.user_restrictions_service import (
 )
 from services.system.metrics_service import MetricsService
 from services.system.system_service import reload_squid, restart_squid
-from flask_babel import gettext as _
 
 api_bp = Blueprint("api", __name__)
 

+ 7 - 3
routes/auth_routes.py

@@ -15,11 +15,11 @@ from flask import (
     session,
     url_for,
 )
+from flask_babel import gettext as _
 from flask_wtf.csrf import CSRFProtect
 from loguru import logger
 
 from services.auth.auth_service import AuthConfig, AuthService
-from flask_babel import gettext as _
 
 auth_bp = Blueprint("auth", __name__, url_prefix="/auth")
 csrf = CSRFProtect()
@@ -87,7 +87,9 @@ def login():
                 logger.info(
                     f"Successful login for user: {username} from IP: {client_ip} ({remember_status})"
                 )
-                flash(_("¡Bienvenido, %(username)s!") % {"username": username}, "success")
+                flash(
+                    _("¡Bienvenido, %(username)s!") % {"username": username}, "success"
+                )
 
                 # Get redirect URL (stored before login redirect)
                 next_url = session.pop("next_url", None)
@@ -189,7 +191,9 @@ def reset_password():
     if client_ip not in ["127.0.0.1", "::1", "localhost"]:
         logger.warning("Password reset attempt from unauthorized IP")
         return {
-            "error": _("Access denied. This endpoint is only accessible from localhost.")
+            "error": _(
+                "Access denied. This endpoint is only accessible from localhost."
+            )
         }, 403
 
     # Get data from request

+ 9 - 3
routes/i18n_routes.py

@@ -64,8 +64,12 @@ def get_translations():
         "unthrottle_user": _("Restaurar velocidad"),
         "confirm_block": _("¿Estás seguro de que deseas bloquear a este usuario?"),
         "confirm_unblock": _("¿Estás seguro de que deseas desbloquear a este usuario?"),
-        "confirm_throttle": _("¿Estás seguro de que deseas reducir la velocidad de este usuario?"),
-        "confirm_unthrottle": _("¿Estás seguro de que deseas restaurar la velocidad de este usuario?"),
+        "confirm_throttle": _(
+            "¿Estás seguro de que deseas reducir la velocidad de este usuario?"
+        ),
+        "confirm_unthrottle": _(
+            "¿Estás seguro de que deseas restaurar la velocidad de este usuario?"
+        ),
         "operation_success": _("Operación exitosa"),
         "operation_error": _("Error en la operación"),
         "connection_error": _("Error de conexión"),
@@ -131,7 +135,9 @@ def get_translations():
         "creating_backup": _("Creando respaldo..."),
         "backup_created": _("Respaldo creado"),
         "backup_deleted": _("Respaldo eliminado"),
-        "confirm_delete_backup": _("¿Estás seguro de que deseas eliminar este respaldo?"),
+        "confirm_delete_backup": _(
+            "¿Estás seguro de que deseas eliminar este respaldo?"
+        ),
         "restoring_backup": _("Restaurando respaldo..."),
         # System
         "reloading_squid": _("Recargando Squid..."),

+ 1 - 1
routes/logs_routes.py

@@ -1,12 +1,12 @@
 from datetime import datetime
 
 from flask import Blueprint, jsonify, render_template, request
+from flask_babel import gettext as _
 from loguru import logger
 
 from database.database import get_session
 from services.analytics.blacklist_users import find_blacklisted_sites
 from services.analytics.fetch_data_logs import get_users_logs
-from flask_babel import gettext as _
 
 logs_bp = Blueprint("logs", __name__)
 

+ 4 - 2
services/analytics/auditoria_service.py

@@ -2,8 +2,8 @@ from collections import defaultdict
 from datetime import datetime, timedelta
 from typing import Any
 
-from loguru import logger
 from flask_babel import gettext as _
+from loguru import logger
 from sqlalchemy import func, inspect, or_, text
 from sqlalchemy.exc import SQLAlchemyError
 from sqlalchemy.orm import Session
@@ -396,7 +396,9 @@ def get_daily_activity(db: Session, date_str: str, username: str) -> dict[str, A
 
     except SQLAlchemyError as e:
         print(f"Database error in get_daily_activity: {e}")
-        return {"error": _("A database error occurred while calculating daily activity.")}
+        return {
+            "error": _("A database error occurred while calculating daily activity.")
+        }
     except Exception as e:
         print(f"General error in get_daily_activity: {e}")
         return {

+ 1 - 1
services/analytics/blacklist_users.py

@@ -4,6 +4,7 @@ from datetime import datetime
 from typing import Any
 from urllib.parse import urlparse
 
+from flask_babel import gettext as _
 from loguru import logger
 from sqlalchemy import func, inspect, literal, select
 from sqlalchemy.exc import SQLAlchemyError
@@ -11,7 +12,6 @@ from sqlalchemy.orm import Session
 
 from database.database import get_dynamic_models, get_engine
 from database.models.models import BlacklistDomain
-from flask_babel import gettext as _
 
 # ---------------------------------------------------------------------------
 # Module-level TTL cache

+ 1 - 1
services/auth/auth_service.py

@@ -13,11 +13,11 @@ from functools import wraps
 import bcrypt
 import jwt
 from flask import flash, redirect, request, session, url_for
+from flask_babel import gettext as _
 from loguru import logger
 
 from config import Config
 from database.database import AdminUser, get_session
-from flask_babel import gettext as _
 
 
 class AuthConfig:

+ 1 - 1
services/database/backup_service.py

@@ -17,12 +17,12 @@ from datetime import datetime
 from pathlib import Path
 from urllib.parse import urlparse
 
+from flask_babel import gettext as _
 from loguru import logger
 
 from config import Config
 from database.database import get_session
 from database.models.models import BackupConfig
-from flask_babel import gettext as _
 
 # Constants
 

+ 5 - 2
services/database/db_admin_service.py

@@ -1,10 +1,10 @@
 import re
 
+from flask_babel import gettext as _
 from loguru import logger
 from sqlalchemy import MetaData, Table, inspect
 
 from database.database import get_engine
-from flask_babel import gettext as _
 
 
 def delete_table_data(table_name: str):
@@ -13,7 +13,10 @@ def delete_table_data(table_name: str):
     Returns tuple `(response_dict, status_code)` ready to jsonify/return.
     """
     if not table_name:
-        return {"status": "error", "message": _("Nombre de tabla no proporcionado")}, 400
+        return {
+            "status": "error",
+            "message": _("Nombre de tabla no proporcionado"),
+        }, 400
 
     if not re.match(r"^[a-zA-Z0-9_]+$", table_name):
         return {"status": "error", "message": _("Nombre de tabla inválido")}, 400

+ 5 - 2
services/database/db_info_service.py

@@ -1,10 +1,10 @@
+from flask_babel import gettext as _
 from loguru import logger
 from sqlalchemy import text
 
 from config import Config
 from database.database import get_engine, get_session
 from services.database.admin_helpers import get_all_tables_stats
-from flask_babel import gettext as _
 
 
 def get_tables_info():
@@ -194,7 +194,10 @@ def run_integrity_check():
 
     except Exception:
         logger.exception("Error running integrity check")
-        return {"status": "error", "message": _("Error al ejecutar la verificación")}, 500
+        return {
+            "status": "error",
+            "message": _("Error al ejecutar la verificación"),
+        }, 500
 
     finally:
         if session:

+ 5 - 2
services/ldap/ldap_service.py

@@ -2,6 +2,7 @@ from __future__ import annotations
 
 from typing import Any
 
+from flask_babel import gettext as _
 from ldap3 import (
     ALL,
     NTLM,
@@ -14,7 +15,6 @@ from ldap3 import (
 )
 from ldap3.utils.conv import escape_filter_chars
 from loguru import logger
-from flask_babel import gettext as _
 
 # ---------------------------------------------------------------------------
 # Internal helpers
@@ -51,7 +51,10 @@ def test_connection(cfg: dict) -> dict:
     try:
         conn = _connect(cfg)
         conn.unbind()
-        return {"status": "success", "message": _("Conexión exitosa al servidor LDAP/AD.")}
+        return {
+            "status": "success",
+            "message": _("Conexión exitosa al servidor LDAP/AD."),
+        }
     except core.exceptions.LDAPBindError as exc:
         logger.warning(f"LDAP bind falló: {exc}")
         return {"status": "error", "message": f"Error de autenticación: {exc}"}

+ 1 - 1
services/notifications/notifications.py

@@ -7,8 +7,8 @@ from contextlib import contextmanager
 from datetime import datetime, timedelta
 from typing import Any
 
-from loguru import logger
 from flask_babel import gettext as _
+from loguru import logger
 from sqlalchemy import and_, desc, func
 from sqlalchemy.orm import Session
 

+ 5 - 2
services/squid/split_config_service.py

@@ -1,9 +1,9 @@
 import os
 
+from flask_babel import gettext as _
 from loguru import logger
 
 from services.squid.squid_config_splitter import SquidConfigSplitter
-from flask_babel import gettext as _
 
 
 def get_split_view_data():
@@ -39,7 +39,10 @@ def split_config(strict=False):
         }, 200
     except FileNotFoundError as e:
         logger.error("Archivo no encontrado: %s", e)
-        return {"status": "error", "message": _("Archivo requerido no encontrado.")}, 404
+        return {
+            "status": "error",
+            "message": _("Archivo requerido no encontrado."),
+        }, 404
     except PermissionError as e:
         logger.error("Error de permisos: %s", e)
         return {

+ 4 - 2
services/squid/squid_config_splitter.py

@@ -5,8 +5,8 @@ import subprocess  # nosec B404
 from dataclasses import dataclass
 from datetime import datetime
 
-from loguru import logger
 from flask_babel import gettext as _
+from loguru import logger
 
 
 @dataclass(frozen=True)
@@ -620,7 +620,9 @@ class SquidConfigSplitter:
             logger.error(f"Error de permisos al leer archivos: {e}")
             return {
                 "status": "error",
-                "message": _("No se tienen permisos suficientes para leer los archivos"),
+                "message": _(
+                    "No se tienen permisos suficientes para leer los archivos"
+                ),
                 "code": 403,
             }
 

+ 1 - 1
services/squid/ssl_bump_service.py

@@ -1,7 +1,7 @@
 """Service layer for SSL Bump detection."""
 
-from loguru import logger
 from flask_babel import gettext as _
+from loguru import logger
 
 
 def get_ssl_bump_status(config_manager) -> dict:

+ 1 - 1
services/system/system_info.py

@@ -7,8 +7,8 @@ import subprocess  # nosec B404
 import time
 
 import psutil
-from loguru import logger
 from flask_babel import gettext as _
+from loguru import logger
 
 # Variables globales para el cálculo de estadísticas de red
 _last_net_io = None

+ 32 - 31
tools/mark_i18n.py

@@ -15,7 +15,7 @@ TEMPLATES_DIR = os.path.join(PROJECT_ROOT, "templates")
 
 def process_template_file(filepath):
     """Process a single Jinja2 template file and wrap Spanish text."""
-    with open(filepath, "r", encoding="utf-8") as f:
+    with open(filepath, encoding="utf-8") as f:
         content = f.read()
 
     original = content
@@ -49,12 +49,12 @@ def process_template_file(filepath):
             return m.group(0)
 
         # Must contain at least one letter
-        if not re.search(r'[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]', stripped):
+        if not re.search(r"[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]", stripped):
             return m.group(0)
 
         # Preserve whitespace around the text
-        leading_ws = text[:len(text) - len(text.lstrip())]
-        trailing_ws = text[len(text.rstrip()):]
+        leading_ws = text[: len(text) - len(text.lstrip())]
+        trailing_ws = text[len(text.rstrip()) :]
 
         # Escape any quotes in the text
         escaped = stripped.replace('"', '\\"')
@@ -63,26 +63,30 @@ def process_template_file(filepath):
 
     # Process text between HTML tags
     content = re.sub(
-        r'(>)((?:(?!<|{{|{%).)+?)(<)',
-        wrap_text_node,
-        content,
-        flags=re.DOTALL
+        r"(>)((?:(?!<|{{|{%).)+?)(<)", wrap_text_node, content, flags=re.DOTALL
     )
 
     # ─── Pattern: HTML attributes with Spanish text ───
     # Common attributes: placeholder, title, data-tooltip, aria-label, alt
     attrs_to_translate = [
-        'placeholder', 'title', 'data-tooltip', 'aria-label', 'alt',
-        'data-confirm', 'data-message', 'data-title'
+        "placeholder",
+        "title",
+        "data-tooltip",
+        "aria-label",
+        "alt",
+        "data-confirm",
+        "data-message",
+        "data-title",
     ]
 
     for attr in attrs_to_translate:
+
         def wrap_attr(m):
             quote = m.group(2)
             value = m.group(3)
-            if '{{' in value or '{%' in value:
+            if "{{" in value or "{%" in value:
                 return m.group(0)
-            if not re.search(r'[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]', value):
+            if not re.search(r"[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]", value):
                 return m.group(0)
             if value.startswith(("http", "www.", "/", "#", ".", "fas ", "url_for")):
                 return m.group(0)
@@ -93,14 +97,15 @@ def process_template_file(filepath):
 
         # Match attr="value" where value contains text
         pattern = rf'({attr}=)(["\'])((?:(?!\2).)*?)\2'
+
         # Simpler approach - just use {{ _() }} in attribute values
         def wrap_attr_simple(m):
             attr_name = m.group(1)
             quote_char = m.group(2)
             value = m.group(3)
-            if '{{' in value or '{%' in value or '_(' in value:
+            if "{{" in value or "{%" in value or "_(" in value:
                 return m.group(0)
-            if not re.search(r'[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]', value):
+            if not re.search(r"[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]", value):
                 return m.group(0)
             if value.startswith(("http", "www.", "/", "#", ".", "fas ", "url_for")):
                 return m.group(0)
@@ -122,7 +127,7 @@ def process_template_file(filepath):
 
 def process_python_file(filepath):
     """Process a Python file and wrap user-facing strings with _()."""
-    with open(filepath, "r", encoding="utf-8") as f:
+    with open(filepath, encoding="utf-8") as f:
         content = f.read()
 
     original = content
@@ -137,9 +142,9 @@ def process_python_file(filepath):
         quote = m.group(2)
         value = m.group(3)
 
-        if '_(' in value or 'f"' in value or "f'" in value:
+        if "_(" in value or 'f"' in value or "f'" in value:
             return m.group(0)
-        if not re.search(r'[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]', value):
+        if not re.search(r"[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]", value):
             return m.group(0)
         if value.startswith(("http", "/", ".")):
             return m.group(0)
@@ -152,39 +157,35 @@ def process_python_file(filepath):
     content = re.sub(
         r'"(message|status_message|error)":\s*(["\'])((?:(?!\2).)*?)\2',
         wrap_message_value,
-        content
+        content,
     )
 
-    # Pattern: flash("Spanish text", ...) 
+    # Pattern: flash("Spanish text", ...)
     def wrap_flash(m):
         nonlocal needs_import
         prefix = m.group(1)
         value = m.group(2)
         suffix = m.group(3)
-        if '_(' in value:
+        if "_(" in value:
             return m.group(0)
         needs_import = True
         escaped = value.replace('"', '\\"')
         return f'{prefix}_("{escaped}"){suffix}'
 
-    content = re.sub(
-        r'(flash\()"([^"]+)"(\s*[,)])',
-        wrap_flash,
-        content
-    )
+    content = re.sub(r'(flash\()"([^"]+)"(\s*[,)])', wrap_flash, content)
 
     if content != original:
         # Add import if needed
-        if needs_import and 'from flask_babel import' not in content:
+        if needs_import and "from flask_babel import" not in content:
             # Find the best place to add import
-            if 'from flask import' in content:
+            if "from flask import" in content:
                 content = content.replace(
-                    'from flask import',
-                    'from flask_babel import gettext as _\nfrom flask import',
-                    1
+                    "from flask import",
+                    "from flask_babel import gettext as _\nfrom flask import",
+                    1,
                 )
             else:
-                content = 'from flask_babel import gettext as _\n' + content
+                content = "from flask_babel import gettext as _\n" + content
 
         with open(filepath, "w", encoding="utf-8") as f:
             f.write(content)

+ 21 - 18
tools/mark_python_i18n.py

@@ -1,8 +1,8 @@
 #!/usr/bin/env python3
 """Mark user-facing strings in Python files with _() for Flask-Babel."""
 
-import re
 import os
+import re
 import sys
 
 PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -12,7 +12,11 @@ DIRS = ["routes", "services"]
 
 # Keys whose string values should be translated in dict literals
 TRANSLATABLE_KEYS = {
-    "message", "error", "msg", "error_message", "user_message",
+    "message",
+    "error",
+    "msg",
+    "error_message",
+    "user_message",
 }
 
 IMPORT_LINE = "from flask_babel import gettext as _"
@@ -30,7 +34,7 @@ def should_skip_file(filepath):
 
 def has_gettext_import(content):
     """Check if file already imports gettext as _."""
-    return bool(re.search(r'from flask_babel import.*gettext', content))
+    return bool(re.search(r"from flask_babel import.*gettext", content))
 
 
 def add_import(content):
@@ -38,29 +42,29 @@ def add_import(content):
     if has_gettext_import(content):
         return content
 
-    lines = content.split('\n')
+    lines = content.split("\n")
     insert_idx = 0
 
     for i, line in enumerate(lines):
         stripped = line.strip()
-        if stripped.startswith('from ') or stripped.startswith('import '):
+        if stripped.startswith("from ") or stripped.startswith("import "):
             insert_idx = i + 1
 
     lines.insert(insert_idx, IMPORT_LINE)
-    return '\n'.join(lines)
+    return "\n".join(lines)
 
 
 def is_translatable(text):
     """Check if a string value should be translated."""
     if not text or len(text.strip()) <= 1:
         return False
-    if text.lower() in ('true', 'false', 'none', 'null', 'ok'):
+    if text.lower() in ("true", "false", "none", "null", "ok"):
         return False
     # Must have a letter
-    if not re.search(r'[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]', text):
+    if not re.search(r"[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]", text):
         return False
     # Skip URLs, paths
-    if re.match(r'^(https?://|/|\.)', text):
+    if re.match(r"^(https?://|/|\.)", text):
         return False
     return True
 
@@ -80,9 +84,7 @@ def wrap_flash_strings(content):
 
     # Double-quoted: flash("text", ...) or flash("text")
     content = re.sub(
-        r'(flash\()"((?:[^"\\]|\\.)+)"(\s*[,\)])',
-        replace_flash_dq,
-        content
+        r'(flash\()"((?:[^"\\]|\\.)+)"(\s*[,\)])', replace_flash_dq, content
     )
 
     def replace_flash_sq(m):
@@ -96,9 +98,7 @@ def wrap_flash_strings(content):
 
     # Single-quoted: flash('text', ...)
     content = re.sub(
-        r"(flash\()'((?:[^'\\]|\\.)+)'(\s*[,\)])",
-        replace_flash_sq,
-        content
+        r"(flash\()'((?:[^'\\]|\\.)+)'(\s*[,\)])", replace_flash_sq, content
     )
 
     return content
@@ -117,6 +117,7 @@ def wrap_dict_strings(content):
                 if not is_translatable(value):
                     return m.group(0)
                 return f'{prefix}_("{value}")'
+
             return replacer
 
         content = re.sub(pattern, make_replacer(), content)
@@ -132,6 +133,7 @@ def wrap_dict_strings(content):
                     return m.group(0)
                 escaped = value.replace('"', '\\"')
                 return f'{prefix}_("{escaped}")'
+
             return replacer_sq
 
         content = re.sub(pattern_sq, make_replacer_sq(), content)
@@ -152,6 +154,7 @@ def wrap_return_dict_strings(content):
                 if not is_translatable(value):
                     return m.group(0)
                 return f'{prefix}_("{value}")'
+
             return replacer
 
         content = re.sub(pattern, make_replacer(), content)
@@ -161,7 +164,7 @@ def wrap_return_dict_strings(content):
 
 def process_file(filepath):
     """Process a single Python file."""
-    with open(filepath, 'r', encoding='utf-8') as f:
+    with open(filepath, encoding="utf-8") as f:
         content = f.read()
 
     # Skip if already has _() calls throughout (likely already processed)
@@ -173,7 +176,7 @@ def process_file(filepath):
 
     if content != original:
         content = add_import(content)
-        with open(filepath, 'w', encoding='utf-8') as f:
+        with open(filepath, "w", encoding="utf-8") as f:
             f.write(content)
         return True
     return False
@@ -204,7 +207,7 @@ def main():
         dir_path = os.path.join(PROJECT_ROOT, dir_name)
         for root, dirs, files in os.walk(dir_path):
             for f in sorted(files):
-                if not f.endswith('.py'):
+                if not f.endswith(".py"):
                     continue
                 filepath = os.path.join(root, f)
                 if should_skip_file(filepath):

+ 87 - 37
tools/mark_templates_i18n.py

@@ -14,17 +14,42 @@ TEMPLATES_DIR = os.path.join(PROJECT_ROOT, "templates")
 
 # Attributes that contain user-visible text
 TRANSLATABLE_ATTRS = {
-    "placeholder", "title", "data-tooltip", "aria-label", "alt",
-    "data-confirm", "data-confirm-title", "data-confirm-text",
+    "placeholder",
+    "title",
+    "data-tooltip",
+    "aria-label",
+    "alt",
+    "data-confirm",
+    "data-confirm-title",
+    "data-confirm-text",
 }
 
 # Strings to skip (technical, not user-facing)
 SKIP_PATTERNS = {
-    "true", "false", "none", "null", "utf-8", "UTF-8",
-    "POST", "GET", "PUT", "DELETE", "PATCH",
-    "text/html", "application/json", "multipart/form-data",
-    "hidden", "submit", "button", "text", "password", "email", "number", "checkbox",
-    "display: none", "visibility: hidden",
+    "true",
+    "false",
+    "none",
+    "null",
+    "utf-8",
+    "UTF-8",
+    "POST",
+    "GET",
+    "PUT",
+    "DELETE",
+    "PATCH",
+    "text/html",
+    "application/json",
+    "multipart/form-data",
+    "hidden",
+    "submit",
+    "button",
+    "text",
+    "password",
+    "email",
+    "number",
+    "checkbox",
+    "display: none",
+    "visibility: hidden",
 }
 
 
@@ -40,16 +65,33 @@ def is_translatable_text(text):
     if stripped.lower() in SKIP_PATTERNS:
         return False
     # Must contain a letter (not just numbers/symbols)
-    if not re.search(r'[a-zA-ZáéíóúñÁÉÍÓÚÑüÜàèìòùÀÈÌÒÙ]', stripped):
+    if not re.search(r"[a-zA-ZáéíóúñÁÉÍÓÚÑüÜàèìòùÀÈÌÒÙ]", stripped):
         return False
     # Skip URLs, paths, CSS classes, etc.
-    if re.match(r'^(https?://|www\.|/|#|\.|fas |fab |far |fal |fad |fa-|bi-|text-|bg-|btn-|col-|row-|d-|p-|m-|w-|h-|flex-|grid-|items-|justify-)', stripped):
+    if re.match(
+        r"^(https?://|www\.|/|#|\.|fas |fab |far |fal |fad |fa-|bi-|text-|bg-|btn-|col-|row-|d-|p-|m-|w-|h-|flex-|grid-|items-|justify-)",
+        stripped,
+    ):
         return False
     # Skip if it looks like a Jinja variable or filter
-    if re.match(r'^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)*$', stripped):
+    if re.match(r"^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)*$", stripped):
         return False
     # Skip JS code snippets
-    if any(kw in stripped for kw in ["function(", "var ", "const ", "let ", "=>", "return ", "console.", "document.", "window.", "addEventListener"]):
+    if any(
+        kw in stripped
+        for kw in [
+            "function(",
+            "var ",
+            "const ",
+            "let ",
+            "=>",
+            "return ",
+            "console.",
+            "document.",
+            "window.",
+            "addEventListener",
+        ]
+    ):
         return False
     return True
 
@@ -58,9 +100,9 @@ def wrap_text(text):
     """Wrap a text string with {{ _("...") }}."""
     stripped = text.strip()
     # Normalize multi-line whitespace to single line
-    stripped = ' '.join(stripped.split())
-    leading = text[:len(text) - len(text.lstrip())]
-    trailing = text[len(text.rstrip()):]
+    stripped = " ".join(stripped.split())
+    leading = text[: len(text) - len(text.lstrip())]
+    trailing = text[len(text.rstrip()) :]
     # Escape double quotes
     escaped = stripped.replace('"', '\\"')
     return f'{leading}{{{{ _("{escaped}") }}}}{trailing}'
@@ -73,7 +115,9 @@ def process_text_between_tags(content):
 
     while pos < len(content):
         # Find next tag or Jinja block
-        tag_match = re.search(r'(<[^>]+>|{{.*?}}|{%.*?%}|{#.*?#})', content[pos:], re.DOTALL)
+        tag_match = re.search(
+            r"(<[^>]+>|{{.*?}}|{%.*?%}|{#.*?#})", content[pos:], re.DOTALL
+        )
 
         if not tag_match:
             # Rest is text
@@ -85,7 +129,7 @@ def process_text_between_tags(content):
             break
 
         # Text before the tag
-        text_before = content[pos:pos + tag_match.start()]
+        text_before = content[pos : pos + tag_match.start()]
         if text_before and is_translatable_text(text_before):
             result.append(wrap_text(text_before))
         else:
@@ -95,25 +139,27 @@ def process_text_between_tags(content):
         tag = tag_match.group(0)
 
         # Check if it's a script or style tag - skip content
-        script_match = re.match(r'<(script|style)[\s>]', tag, re.IGNORECASE)
+        script_match = re.match(r"<(script|style)[\s>]", tag, re.IGNORECASE)
         if script_match:
             tag_name = script_match.group(1).lower()
-            close_pattern = f'</{tag_name}>'
+            close_pattern = f"</{tag_name}>"
             close_pos = content.find(close_pattern, pos + tag_match.end())
             if close_pos >= 0:
                 # Include everything from tag to closing tag
-                result.append(content[pos + tag_match.start():close_pos + len(close_pattern)])
+                result.append(
+                    content[pos + tag_match.start() : close_pos + len(close_pattern)]
+                )
                 pos = close_pos + len(close_pattern)
                 continue
 
         # Process translatable attributes in the tag
-        if tag.startswith('<'):
+        if tag.startswith("<"):
             tag = process_tag_attributes(tag)
 
         result.append(tag)
         pos = pos + tag_match.end()
 
-    return ''.join(result)
+    return "".join(result)
 
 
 def process_tag_attributes(tag):
@@ -121,6 +167,7 @@ def process_tag_attributes(tag):
     for attr in TRANSLATABLE_ATTRS:
         # Match attr="value" or attr='value'
         pattern = rf'({attr}=")([^"]*?)(")'
+
         def replace_attr(m):
             prefix = m.group(1)
             value = m.group(2)
@@ -129,10 +176,12 @@ def process_tag_attributes(tag):
                 escaped = value.strip().replace('"', '\\"')
                 return f'{prefix}{{{{ _("{escaped}") }}}}{suffix}'
             return m.group(0)
+
         tag = re.sub(pattern, replace_attr, tag)
 
         # Single quotes version
         pattern_sq = rf"({attr}=')([^']*?)(')"
+
         def replace_attr_sq(m):
             prefix = m.group(1)
             value = m.group(2)
@@ -141,6 +190,7 @@ def process_tag_attributes(tag):
                 escaped = value.strip().replace("'", "\\'")
                 return f"""{attr}="{{ _("{escaped}") }}" """
             return m.group(0)
+
         tag = re.sub(pattern_sq, replace_attr_sq, tag)
 
     return tag
@@ -148,14 +198,14 @@ def process_tag_attributes(tag):
 
 def process_template(filepath):
     """Process a single template file."""
-    with open(filepath, 'r', encoding='utf-8') as f:
+    with open(filepath, encoding="utf-8") as f:
         content = f.read()
 
     original = content
     new_content = process_text_between_tags(content)
 
     if new_content != original:
-        with open(filepath, 'w', encoding='utf-8') as f:
+        with open(filepath, "w", encoding="utf-8") as f:
             f.write(new_content)
         return True
     return False
@@ -164,9 +214,9 @@ def process_template(filepath):
 def process_line(line):
     """Process a single line of template content."""
     # Don't process Jinja2 comments
-    if '{#' in line:
+    if "{#" in line:
         return line
-    
+
     # Don't process lines that are just whitespace
     if not line.strip():
         return line
@@ -175,23 +225,20 @@ def process_line(line):
     # Pattern: find segments of text that are between > and <
     def replace_text_segment(m):
         before = m.group(1)  # > or start
-        text = m.group(2)    # text content
-        after = m.group(3)   # < or end
+        text = m.group(2)  # text content
+        after = m.group(3)  # < or end
 
         if is_translatable_text(text):
             return before + wrap_text(text) + after
         return m.group(0)
 
     # Find text between > and < (tag content)
-    result = re.sub(
-        r'(>)([^<>{%{}]+?)(<)',
-        replace_text_segment,
-        line
-    )
+    result = re.sub(r"(>)([^<>{%{}]+?)(<)", replace_text_segment, line)
 
     # Process translatable attributes
     for attr in TRANSLATABLE_ATTRS:
         pattern = rf'({attr}=")([^"{{}}]*?)(")'
+
         def attr_replacer(m):
             prefix = m.group(1)
             value = m.group(2)
@@ -200,6 +247,7 @@ def process_line(line):
                 escaped = value.strip().replace('"', '\\"')
                 return f'{prefix}{{{{ _("{escaped}") }}}}{suffix}'
             return m.group(0)
+
         result = re.sub(pattern, attr_replacer, result)
 
     return result
@@ -211,7 +259,9 @@ def main():
     print("=" * 60)
 
     dry_run = "--dry-run" in sys.argv
-    target = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("--") else None
+    target = (
+        sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("--") else None
+    )
 
     if target:
         filepath = os.path.join(PROJECT_ROOT, target)
@@ -219,15 +269,15 @@ def main():
             filepath = target
         if os.path.exists(filepath):
             if dry_run:
-                with open(filepath, 'r') as f:
+                with open(filepath) as f:
                     original = f.read()
                 process_template(filepath)
-                with open(filepath, 'r') as f:
+                with open(filepath) as f:
                     modified = f.read()
                 if original != modified:
                     print(f"Would modify: {target}")
                     # Restore
-                    with open(filepath, 'w') as f:
+                    with open(filepath, "w") as f:
                         f.write(original)
                 else:
                     print(f"No changes: {target}")
@@ -243,7 +293,7 @@ def main():
     count = 0
     for root, dirs, files in os.walk(TEMPLATES_DIR):
         for f in sorted(files):
-            if f.endswith('.html'):
+            if f.endswith(".html"):
                 filepath = os.path.join(root, f)
                 relpath = os.path.relpath(filepath, PROJECT_ROOT)
                 if process_template(filepath):

+ 7 - 32
tools/translate_po.py

@@ -56,7 +56,6 @@ TRANSLATIONS = {
     "Procesando...": "Processing...",
     "Exportar": "Export",
     "Importar": "Import",
-
     # Auth
     "Iniciar sesión": "Log In",
     "Cerrar sesión": "Log Out",
@@ -66,7 +65,6 @@ TRANSLATIONS = {
     "Recordarme": "Remember me",
     "Olvidé mi contraseña": "Forgot password",
     "Has cerrado sesión correctamente.": "You have logged out successfully.",
-
     # Status
     "Activo": "Active",
     "Inactivo": "Inactive",
@@ -80,7 +78,6 @@ TRANSLATIONS = {
     "Pendiente": "Pending",
     "Completado": "Completed",
     "Fallido": "Failed",
-
     # Table headers & common labels
     "Nombre": "Name",
     "Descripción": "Description",
@@ -110,7 +107,6 @@ TRANSLATIONS = {
     "Fecha de creación": "Creation Date",
     "Acciones": "Actions",
     "ID": "ID",
-
     # Admin sections
     "Gestión de Usuarios": "User Management",
     "Crear Usuario": "Create User",
@@ -134,7 +130,6 @@ TRANSLATIONS = {
     "ACLs": "ACLs",
     "Delay Pools": "Delay Pools",
     "Cuotas": "Quotas",
-
     # Dashboard
     "Panel principal con conexiones activas": "Main panel with active connections",
     "Conexiones Activas": "Active Connections",
@@ -145,7 +140,6 @@ TRANSLATIONS = {
     "Espacio en Disco": "Disk Space",
     "Tiempo de Actividad": "Uptime",
     "Versión de Squid": "Squid Version",
-
     # Blacklist
     "Gestión de Blacklist": "Blacklist Management",
     "Lista Negra": "Blacklist",
@@ -163,7 +157,6 @@ TRANSLATIONS = {
     "Lista importada desde URL correctamente": "List imported from URL successfully",
     "Archivo importado correctamente": "File imported successfully",
     "No se encontraron dominios para importar": "No domains found to import",
-
     # Reports
     "Generar Reporte": "Generate Report",
     "Reporte Diario": "Daily Report",
@@ -175,7 +168,6 @@ TRANSLATIONS = {
     "Rango de Fechas": "Date Range",
     "Sin datos disponibles": "No data available",
     "Sin datos": "No data",
-
     # Logs
     "Registros del Sistema": "System Logs",
     "Ver Logs": "View Logs",
@@ -183,12 +175,10 @@ TRANSLATIONS = {
     "Nivel": "Level",
     "Mensaje": "Message",
     "Componente": "Component",
-
     # Config
     "Variables de entorno guardadas exitosamente": "Environment variables saved successfully",
     "ID de ACL inválido": "Invalid ACL ID",
     "Índice de regla inválido": "Invalid rule index",
-
     # Errors & Success messages
     "Error": "Error",
     "Éxito": "Success",
@@ -219,7 +209,6 @@ TRANSLATIONS = {
     "Error al guardar la lista: %(error)s": "Error saving list: %(error)s",
     "Error al cargar la vista: %(error)s": "Error loading view: %(error)s",
     "Lista eliminada: %(url)s (%(count)s dominios)": "List deleted: %(url)s (%(count)s domains)",
-
     # Squid specific
     "Actualizar paquetes y configuración de Squid": "Update Squid packages and configuration",
     "Actualizar aplicación web SquidStats": "Update SquidStats web application",
@@ -229,18 +218,15 @@ TRANSLATIONS = {
     "Caché": "Cache",
     "Proxy": "Proxy",
     "SquidStats Monitor": "SquidStats Monitor",
-
     # Error page
     "Error - Squid Monitor": "Error - Squid Monitor",
     "Volver al Inicio": "Back to Home",
     "Disculpamos las molestias. Por favor, intenta de nuevo más tarde o contacta al soporte si el problema persiste.": "We apologize for the inconvenience. Please try again later or contact support if the problem persists.",
-
     # Auth page
     "Iniciar Sesión": "Log In",
     "Bienvenido a SquidStats": "Welcome to SquidStats",
     "Ingresa tus credenciales para acceder al sistema": "Enter your credentials to access the system",
     "Recuérdame": "Remember me",
-
     # Notifications
     "Cargando notificaciones...": "Loading notifications...",
     "Ver todas las notificaciones": "View all notifications",
@@ -251,7 +237,6 @@ TRANSLATIONS = {
     "No leído": "Unread",
     "Logo SquidStats": "SquidStats Logo",
     "Toggle menu": "Toggle menu",
-
     # LDAP
     "Configuración LDAP": "LDAP Configuration",
     "Configuración LDAP guardada.": "LDAP configuration saved.",
@@ -262,7 +247,6 @@ TRANSLATIONS = {
     "Parámetro 'q' requerido.": "Parameter 'q' required.",
     "Parámetro 'username' requerido.": "Parameter 'username' required.",
     "Conexión exitosa al servidor LDAP/AD.": "Successfully connected to LDAP/AD server.",
-
     # Backup
     "Motor de BD desconocido": "Unknown database engine",
     "Frecuencia inválida": "Invalid frequency",
@@ -271,26 +255,22 @@ TRANSLATIONS = {
     "Archivo no encontrado": "File not found",
     "Nombre de archivo inválido": "Invalid filename",
     "La salva no existe": "Backup does not exist",
-
     # Database admin
     "Nombre de tabla no proporcionado": "Table name not provided",
     "Nombre de tabla inválido": "Invalid table name",
     "La tabla no existe": "Table does not exist",
     "No se puede eliminar estas tablas críticas": "Cannot delete these critical tables",
-
     # Split config
     "Archivo requerido no encontrado. Verifique la configuración del archivo squid.conf.": "Required file not found. Please check the squid.conf file configuration.",
     "No se tienen permisos suficientes para crear los archivos": "Insufficient permissions to create the files",
     "Error de validación de la configuración": "Configuration validation error",
     "Error interno al dividir la configuración": "Internal error splitting the configuration",
     "Archivo requerido no encontrado.": "Required file not found.",
-
     # Quota
     "Cuota": "Quota",
     "Límite": "Limit",
     "Consumido": "Consumed",
     "Restante": "Remaining",
-
     # System info
     "Información del Sistema": "System Information",
     "Procesador": "Processor",
@@ -299,7 +279,6 @@ TRANSLATIONS = {
     "Red": "Network",
     "Interfaz": "Interface",
     "Dirección": "Address",
-
     # Common phrases
     "Guardar cambios": "Save changes",
     "Guardar Cambios": "Save Changes",
@@ -341,10 +320,8 @@ TRANSLATIONS = {
     "Atención": "Attention",
     "Importante": "Important",
     "Nota": "Note",
-
     # Login specific
     "¡Bienvenido, %(username)s!": "Welcome, %(username)s!",
-
     # Admin specific
     "Gestión de Configuración de Squid": "Squid Configuration Management",
     "Editar Configuración": "Edit Configuration",
@@ -364,7 +341,6 @@ TRANSLATIONS = {
     "Acciones del Servicio": "Service Actions",
     "Recargar Squid": "Reload Squid",
     "Reiniciar Squid": "Restart Squid",
-
     # Form labels
     "Nombre:": "Name:",
     "Tipo:": "Type:",
@@ -375,7 +351,6 @@ TRANSLATIONS = {
     "Requerido": "Required",
     "Opcional": "Optional",
     "Ejemplo:": "Example:",
-
     # Audit
     "Auditoría del Sistema": "System Audit",
     "Evento": "Event",
@@ -385,7 +360,6 @@ TRANSLATIONS = {
     "Antes": "Before",
     "Después": "After",
     "Sin cambios": "No changes",
-
     # Delay Pools
     "Gestión de Delay Pools": "Delay Pool Management",
     "Pool": "Pool",
@@ -393,7 +367,6 @@ TRANSLATIONS = {
     "Velocidad Individual": "Individual Speed",
     "Velocidad Agregada": "Aggregate Speed",
     "Red Asociada": "Associated Network",
-
     # Misc
     "Información general": "General Information",
     "Confirmar": "Confirm",
@@ -430,11 +403,11 @@ def translate_msgid(msgid):
 
 def process_po_file(filepath):
     """Process a .po file and fill in English translations."""
-    with open(filepath, 'r', encoding='utf-8') as f:
+    with open(filepath, encoding="utf-8") as f:
         content = f.read()
 
     # Parse the .po file
-    lines = content.split('\n')
+    lines = content.split("\n")
     result = []
     i = 0
     translated_count = 0
@@ -504,14 +477,16 @@ def process_po_file(filepath):
         result.append(line)
         i += 1
 
-    with open(filepath, 'w', encoding='utf-8') as f:
-        f.write('\n'.join(result))
+    with open(filepath, "w", encoding="utf-8") as f:
+        f.write("\n".join(result))
 
     return translated_count, total_msgids, untranslated
 
 
 def main():
-    po_file = sys.argv[1] if len(sys.argv) > 1 else "translations/en/LC_MESSAGES/messages.po"
+    po_file = (
+        sys.argv[1] if len(sys.argv) > 1 else "translations/en/LC_MESSAGES/messages.po"
+    )
 
     print(f"Processing: {po_file}")
     translated, total, untranslated = process_po_file(po_file)

+ 66 - 98
tools/translate_po_v2.py

@@ -59,7 +59,6 @@ TRANSLATIONS = {
     "Bloquear": "Block",
     "Desbloquear": "Unblock",
     "Seleccionar": "Select",
-
     # ── Auth ──
     "Iniciar sesión": "Log In",
     "Iniciar Sesión": "Log In",
@@ -84,7 +83,6 @@ TRANSLATIONS = {
     "La contraseña debe tener al menos 8 caracteres": "Password must be at least 8 characters",
     "Autenticación": "Authentication",
     "Contraseña Bind": "Bind Password",
-
     # ── Status ──
     "Activo": "Active",
     "Inactivo": "Inactive",
@@ -103,7 +101,6 @@ TRANSLATIONS = {
     "Excedido": "Exceeded",
     "Cargada": "Loaded",
     "No cargada": "Not loaded",
-
     # ── Table headers & labels ──
     "Nombre": "Name",
     "Descripción": "Description",
@@ -150,7 +147,6 @@ TRANSLATIONS = {
     "Tabla": "Table",
     "Frecuencia": "Frequency",
     "Departamento": "Department",
-
     # ── Admin sections ──
     "Gestión de Usuarios": "User Management",
     "Gestionar Usuarios": "Manage Users",
@@ -191,7 +187,6 @@ TRANSLATIONS = {
     "Admin Squid": "Squid Admin",
     "Administrador": "Administrator",
     "Administrador Squid Proxy": "Squid Proxy Administrator",
-
     # ── Dashboard ──
     "Panel principal con conexiones activas": "Main panel with active connections",
     "Conexiones Activas": "Active Connections",
@@ -234,7 +229,6 @@ TRANSLATIONS = {
     "Zona Horaria": "Time Zone",
     "Sistema Operativo": "Operating System",
     "Tipo de Sistema": "System Type",
-
     # ── Blacklist ──
     "Gestión de Blacklist": "Blacklist Management",
     "Blacklist - Gestor de Listas": "Blacklist - List Manager",
@@ -281,7 +275,6 @@ TRANSLATIONS = {
     "Integración Pi-hole": "Pi-hole Integration",
     "Pi-hole Host": "Pi-hole Host",
     "Intentos Bloqueados": "Blocked Attempts",
-
     # ── Reports ──
     "Generar Reporte": "Generate Report",
     "Reporte Diario": "Daily Report",
@@ -311,7 +304,6 @@ TRANSLATIONS = {
     "Últimos 7 días": "Last 7 days",
     "Últimos 30 días": "Last 30 days",
     "24 Horas": "24 Hours",
-
     # ── Logs ──
     "Registros del Sistema": "System Logs",
     "Ver Logs": "View Logs",
@@ -324,7 +316,6 @@ TRANSLATIONS = {
     "Líneas a mostrar:": "Lines to show:",
     "Mostrando últimas": "Showing last",
     "Mostrar:": "Show:",
-
     # ── Config ──
     "Variables de entorno guardadas exitosamente": "Environment variables saved successfully",
     "ID de ACL inválido": "Invalid ACL ID",
@@ -380,7 +371,6 @@ TRANSLATIONS = {
     "Directorio de Salvas": "Backup Directory",
     "Directorio de salida": "Output directory",
     "Dir. Remota": "Remote Dir.",
-
     # ── Errors & Success ──
     "Error": "Error",
     "Éxito": "Success",
@@ -428,7 +418,6 @@ TRANSLATIONS = {
     "Internal error": "Internal error",
     "Error DNS": "DNS Error",
     "Error Parsing": "Parsing Error",
-
     # ── Squid specific ──
     "Actualizar paquetes y configuración de Squid": "Update Squid packages and configuration",
     "Actualizar aplicación web SquidStats": "Update SquidStats web application",
@@ -438,13 +427,11 @@ TRANSLATIONS = {
     "Caché": "Cache",
     "Proxy": "Proxy",
     "SquidStats Monitor": "SquidStats Monitor",
-
     # ── Error page ──
     "Error - Squid Monitor": "Error - Squid Monitor",
     "Volver al Inicio": "Back to Home",
     "Volver al Dashboard Principal": "Back to Main Dashboard",
     "Disculpamos las molestias. Por favor, intenta de nuevo más tarde o contacta al soporte si el problema persiste.": "We apologize for the inconvenience. Please try again later or contact support if the problem persists.",
-
     # ── Notifications ──
     "Cargando notificaciones...": "Loading notifications...",
     "Ver todas las notificaciones": "View all notifications",
@@ -467,7 +454,6 @@ TRANSLATIONS = {
     "Reciente": "Recent",
     "Todos los estados": "All statuses",
     "Todos los tipos": "All types",
-
     # ── LDAP ──
     "Configuración LDAP": "LDAP Configuration",
     "LDAP / Active Directory": "LDAP / Active Directory",
@@ -490,7 +476,6 @@ TRANSLATIONS = {
     "Ver grupos del usuario": "View user groups",
     "Ver grupos": "View groups",
     "Configura la conexión y explora el directorio.": "Configure the connection and explore the directory.",
-
     # ── Backup ──
     "Motor de BD desconocido": "Unknown database engine",
     "Frecuencia inválida": "Invalid frequency",
@@ -517,7 +502,6 @@ TRANSLATIONS = {
     "Diaria — máx. 3 por mes": "Daily — max. 3 per month",
     "Diaria — máx. 3 por semana": "Daily — max. 3 per week",
     "¿Estás seguro de que deseas eliminar este respaldo?": "Are you sure you want to delete this backup?",
-
     # ── Database admin ──
     "Nombre de tabla no proporcionado": "Table name not provided",
     "Nombre de tabla inválido": "Invalid table name",
@@ -556,7 +540,6 @@ TRANSLATIONS = {
     "Esta operación puede tardar varios minutos en bases de datos grandes.": "This operation may take several minutes on large databases.",
     "Información de la Tabla": "Table Information",
     "Monitor de salud, copias de seguridad y gestión de datos": "Health monitoring, backups, and data management",
-
     # ── Split config ──
     "Archivo requerido no encontrado. Verifique la configuración del archivo squid.conf.": "Required file not found. Please check the squid.conf file configuration.",
     "No se tienen permisos suficientes para crear los archivos": "Insufficient permissions to create the files",
@@ -586,7 +569,6 @@ TRANSLATIONS = {
     "¿Tu configuración ya está dividida en módulos?": "Is your configuration already split into modules?",
     "dividir tu configuración": "split your configuration",
     "Si tu squid.conf aún no está dividido, puedes": "If your squid.conf is not split yet, you can",
-
     # ── Quota ──
     "Cuota": "Quota",
     "Cuota (MB)": "Quota (MB)",
@@ -634,7 +616,6 @@ TRANSLATIONS = {
     "Información sobre la política por defecto": "Information about the default policy",
     "Para ver los delay pools debes iniciar sesión.": "You must log in to view delay pools.",
     "Total de velocidad del usuario": "Total user speed",
-
     # ── ACLs ──
     "ACL actualizada": "ACL updated",
     "ACL agregada": "ACL added",
@@ -677,7 +658,6 @@ TRANSLATIONS = {
     "Solo letras, números, guiones y guiones bajos": "Only letters, numbers, hyphens and underscores",
     "Contiene negación (!) - se aplica cuando NO coincide con la ACL": "Contains negation (!) - applies when NOT matching the ACL",
     "antes del nombre de una ACL para negación. Ej:": "before ACL name for negation. E.g.:",
-
     # ── HTTP Access ──
     "HTTP Access": "HTTP Access",
     "Reglas HTTP": "HTTP Rules",
@@ -702,7 +682,7 @@ TRANSLATIONS = {
     "Denegar acceso": "Deny access",
     "La primera regla que coincida se aplica (allow o deny)": "The first matching rule applies (allow or deny)",
     "Las reglas se procesan de arriba hacia abajo": "Rules are processed from top to bottom",
-    "Se recomienda terminar con \\\"deny all\\\" para evitar confusión": "It is recommended to end with \\\"deny all\\\" to avoid confusion",
+    'Se recomienda terminar con \\"deny all\\" para evitar confusión': 'It is recommended to end with \\"deny all\\" to avoid confusion',
     "Se agregará como comentario antes de la regla": "Will be added as a comment before the rule",
     "Importante sobre el orden:": "Important about order:",
     "Mover arriba": "Move up",
@@ -710,7 +690,6 @@ TRANSLATIONS = {
     "⚠️ Sin reglas, el acceso será DENEGADO por defecto": "⚠️ Without rules, access will be DENIED by default",
     "🔒 Política por defecto:": "🔒 Default policy:",
     "http_access deny": "http_access deny",
-
     # ── Delay Pools ──
     "Gestión de Delay Pools": "Delay Pool Management",
     "¿Qué son los Delay Pools?": "What are Delay Pools?",
@@ -775,7 +754,6 @@ TRANSLATIONS = {
     "delay pool": "delay pool",
     "Degradar velocidad (próximamente)": "Throttle speed (coming soon)",
     "Solo notificar (próximamente)": "Notify only (coming soon)",
-
     # ── Users ──
     "Nombre, usuario, email…": "Name, user, email...",
     "Complete el formulario para crear un nuevo usuario administrador.": "Complete the form to create a new administrator user.",
@@ -812,7 +790,6 @@ TRANSLATIONS = {
     "Por Usuario": "By User",
     "Por Grupo": "By Group",
     "Pool #": "Pool #",
-
     # ── Audit ──
     "Auditoría del Sistema": "System Audit",
     "Auditoría -": "Audit -",
@@ -830,7 +807,6 @@ TRANSLATIONS = {
     "Buscar auditoría": "Search audit",
     "Histórico": "History",
     "Los resultados de su auditoría aparecerán aquí.": "Your audit results will appear here.",
-
     # ── Stats ──
     "Actividad Diaria": "Daily Activity",
     "Actividad diaria": "Daily activity",
@@ -894,7 +870,6 @@ TRANSLATIONS = {
     "Top usuarios por actividad": "Top users by activity",
     "Top usuarios por datos": "Top users by data",
     "Top usuarios por solicitudes": "Top users by requests",
-
     # ── Common phrases ──
     "Guardar cambios": "Save changes",
     "Guardar Cambios": "Save Changes",
@@ -959,7 +934,6 @@ TRANSLATIONS = {
     "No se encontraron grupos.": "No groups found.",
     "No se encontraron usuarios.": "No users found.",
     "No se encontraron bloqueos (archivo vacío o no existe).": "No blocks found (file empty or does not exist).",
-
     # ── Misc UI ──
     "¿Deseas actualizar Squid?": "Do you want to update Squid?",
     "¿Deseas actualizar SquidStats?": "Do you want to update SquidStats?",
@@ -1005,7 +979,6 @@ TRANSLATIONS = {
     "Activa en Squid": "Active in Squid",
     "instalado en el servidor.": "installed on the server.",
     "en Squid y se guardará en la base de datos para persistencia.": "in Squid and will be saved in the database for persistence.",
-
     # ── Social media ──
     "Facebook": "Facebook",
     "Instagram": "Instagram",
@@ -1014,7 +987,6 @@ TRANSLATIONS = {
     "YouTube": "YouTube",
     "Pinterest": "Pinterest",
     "Telegram": "Telegram",
-
     # ── Squid config technical ──
     "Kbps": "Kbps",
     "Mbps": "Mbps",
@@ -1052,7 +1024,6 @@ TRANSLATIONS = {
     "No valid domains specified for search.": "No valid domains specified for search.",
     "Error al detectar la configuración SSL Bump": "Error detecting SSL Bump configuration",
     "Error al ejecutar la verificación": "Error running verification",
-
     # ── Examples & placeholders ──
     "192.168.1.2 or example.com": "192.168.1.2 or example.com",
     "CN=admin,DC=empresa,DC=com": "CN=admin,DC=company,DC=com",
@@ -1063,7 +1034,6 @@ TRANSLATIONS = {
     "Ej: 64000/64000 = 512 Kbps": "E.g.: 64000/64000 = 512 Kbps",
     "Ej: Permitir acceso desde la red local": "E.g.: Allow access from local network",
     "Ej: juegos, descargas...": "E.g.: games, downloads...",
-
     # ── Remaining ACL type descriptions ──
     "src (IP origen)": "src (Source IP)",
     "dst (IP destino)": "dst (Destination IP)",
@@ -1113,7 +1083,6 @@ TRANSLATIONS = {
     "note - Anotación transacción": "note - Transaction annotation",
     "any-of - Grupo OR": "any-of - OR Group",
     "all-of - Grupo AND": "all-of - AND Group",
-
     # ── Remaining long Spanish phrases ──
     "Todas las notificaciones aparecerán aquí. ¡Mantente atento a las actualizaciones del sistema!": "All notifications will appear here. Stay tuned for system updates!",
     "Si ya está dividido, verifica que los archivos estén en el directorio correcto o edítalos directamente desde": "If already split, verify files are in the correct directory or edit them directly from",
@@ -1134,14 +1103,13 @@ TRANSLATIONS = {
     "para todos los usuarios que no tengan una cuota individual configurada. La cuota individual siempre tiene prioridad sobre la global.": "for all users without an individual quota configured. Individual quota always has priority over the global one.",
     "Define el comportamiento al superar la cuota. (Por ejemplo: bloquear el acceso o degradar la velocidad).": "Define the behavior when exceeding the quota. (For example: block access or throttle speed).",
     "Aunque no haya ninguna regla guardada, el sistema aplica automáticamente la política de": "Even if no rule is saved, the system automatically applies the policy of",
-    "cuando un usuario supera su cuota. Guarda explícitamente \\\"Bloquear\\\" si quieres que quede registrado.": "when a user exceeds their quota. Explicitly save \\\"Block\\\" if you want it recorded.",
+    'cuando un usuario supera su cuota. Guarda explícitamente \\"Bloquear\\" si quieres que quede registrado.': 'when a user exceeds their quota. Explicitly save \\"Block\\" if you want it recorded.',
     "dominios activos. Para evitar un alto consumo de recursos, la consulta se ha limitado a los primeros": "active domains. To avoid high resource consumption, the query has been limited to the first",
     "dominios. Es posible que algunos accesos bloqueados no aparezcan en este listado.": "domains. Some blocked accesses may not appear in this list.",
     "Se eliminará el bloqueo activo para esta IP y se recargará la configuración de Squid.": "The active block for this IP will be removed and Squid configuration will be reloaded.",
     "existente. Sus conexiones estarán sujetas a los límites de ancho de banda configurados en ese pool.": "existing. Their connections will be subject to the bandwidth limits configured in that pool.",
     "Se eliminará la restricción de velocidad activa para esta IP y se recargará la configuración de Squid.": "The active speed restriction for this IP will be removed and Squid configuration will be reloaded.",
     "Requiere": "Requires",
-
     # ── Technical/pass-through strings ──
     "fa-times-circle": "fa-times-circle",
     "!Safe_ports": "!Safe_ports",
@@ -1159,7 +1127,6 @@ TRANSLATIONS = {
     "all, manager, localhost, to_localhost, to_linklocal, CONNECT": "all, manager, localhost, to_localhost, to_linklocal, CONNECT",
     "List membership": "List membership",
     "example.com\\nexample.org": "example.com\\nexample.org",
-
     # ── HTTP status codes ──
     "200 OK": "200 OK",
     "301 Moved Permanently": "301 Moved Permanently",
@@ -1173,7 +1140,6 @@ TRANSLATIONS = {
     "502 Bad Gateway": "502 Bad Gateway",
     "503 Service Unavailable": "503 Service Unavailable",
     "504 Gateway Timeout": "504 Gateway Timeout",
-
     # ── CSRF/validation ──
     "CSRF token missing.": "CSRF token missing.",
     "CSRF failed.": "CSRF failed.",
@@ -1183,64 +1149,64 @@ TRANSLATIONS = {
 # Patterns for strings that are already in English → copy as-is
 ENGLISH_PATTERNS = [
     # Click/WTForms/Werkzeug validation messages
-    r'^Missing \w+',
-    r'^Invalid \w+',
-    r'^Not a valid',
-    r'^Number must be',
-    r'^Field must be',
-    r'^Choices cannot',
-    r'^File does not',
-    r'^Error: ',
-    r'^Option ',
-    r'^No such ',
-    r'^Try ',
-    r'^Could not',
+    r"^Missing \w+",
+    r"^Invalid \w+",
+    r"^Not a valid",
+    r"^Number must be",
+    r"^Field must be",
+    r"^Choices cannot",
+    r"^File does not",
+    r"^Error: ",
+    r"^Option ",
+    r"^No such ",
+    r"^Try ",
+    r"^Could not",
     r"^Couldn't",
-    r'^Show ',
-    r'^Press any',
-    r'^Repeat for',
-    r'^Usage:',
-    r'^Commands$',
-    r'^Options$',
-    r'^Value must be',
-    r'^This field',
-    r'^DeprecationWarning',
-    r'^Shell completion',
-    r'^Aborted!$',
-    r'^A database error',
-    r'^An unexpected error',
-    r'^No data for',
-    r'^Internal server error$',
-    r'^Invalid JSON body$',
-    r'^Bad request$',
-    r'^Invalid numeric value$',
-    r'^Invalid date format$',
-    r'^Internal error$',
-    r'^Unknown error$',
-    r'^Access denied',
-    r'^Username and',
-    r'^Password must be',
-    r'^Password updated',
-    r'^Failed to update',
-    r'^No file part',
-    r'^Not a valid',
-    r'^\{(name|value|editor|text|param)',
-    r'^\%\(prog\)s',
-    r'^First page$',
-    r'^Last page$',
-    r'^Next page$',
-    r'^Previous page$',
-    r'^Total Bandwidth$',
-    r'^Total Requests$',
-    r'^unknown error$',
-    r'^required$',
-    r'^file$',
-    r'^path$',
-    r'^directory$',
-    r'^(default|env var): ',
-    r'^Argument \{',
-    r'^Choose from',
-    r'^Missing \{',
+    r"^Show ",
+    r"^Press any",
+    r"^Repeat for",
+    r"^Usage:",
+    r"^Commands$",
+    r"^Options$",
+    r"^Value must be",
+    r"^This field",
+    r"^DeprecationWarning",
+    r"^Shell completion",
+    r"^Aborted!$",
+    r"^A database error",
+    r"^An unexpected error",
+    r"^No data for",
+    r"^Internal server error$",
+    r"^Invalid JSON body$",
+    r"^Bad request$",
+    r"^Invalid numeric value$",
+    r"^Invalid date format$",
+    r"^Internal error$",
+    r"^Unknown error$",
+    r"^Access denied",
+    r"^Username and",
+    r"^Password must be",
+    r"^Password updated",
+    r"^Failed to update",
+    r"^No file part",
+    r"^Not a valid",
+    r"^\{(name|value|editor|text|param)",
+    r"^\%\(prog\)s",
+    r"^First page$",
+    r"^Last page$",
+    r"^Next page$",
+    r"^Previous page$",
+    r"^Total Bandwidth$",
+    r"^Total Requests$",
+    r"^unknown error$",
+    r"^required$",
+    r"^file$",
+    r"^path$",
+    r"^directory$",
+    r"^(default|env var): ",
+    r"^Argument \{",
+    r"^Choose from",
+    r"^Missing \{",
     r'^0"',  # HTML fragments that got extracted
 ]
 
@@ -1274,10 +1240,10 @@ def translate_msgid(msgid):
 
 def process_po_file(filepath):
     """Process a .po file and fill in English translations."""
-    with open(filepath, 'r', encoding='utf-8') as f:
+    with open(filepath, encoding="utf-8") as f:
         content = f.read()
 
-    lines = content.split('\n')
+    lines = content.split("\n")
     result = []
     i = 0
     translated_count = 0
@@ -1339,14 +1305,16 @@ def process_po_file(filepath):
         result.append(line)
         i += 1
 
-    with open(filepath, 'w', encoding='utf-8') as f:
-        f.write('\n'.join(result))
+    with open(filepath, "w", encoding="utf-8") as f:
+        f.write("\n".join(result))
 
     return translated_count, total_msgids, untranslated
 
 
 def main():
-    po_file = sys.argv[1] if len(sys.argv) > 1 else "translations/en/LC_MESSAGES/messages.po"
+    po_file = (
+        sys.argv[1] if len(sys.argv) > 1 else "translations/en/LC_MESSAGES/messages.po"
+    )
     print(f"Processing: {po_file}")
     translated, total, untranslated = process_po_file(po_file)
     print(f"Translated: {translated}/{total} strings")