mark_i18n.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. #!/usr/bin/env python3
  2. """
  3. Automated i18n string marker for SquidStats templates and Python files.
  4. Wraps Spanish user-facing text with {{ _("...") }} in templates
  5. and _("...") in Python files.
  6. """
  7. import os
  8. import re
  9. import sys
  10. PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
  11. TEMPLATES_DIR = os.path.join(PROJECT_ROOT, "templates")
  12. def process_template_file(filepath):
  13. """Process a single Jinja2 template file and wrap Spanish text."""
  14. with open(filepath, encoding="utf-8") as f:
  15. content = f.read()
  16. original = content
  17. # ─── Pattern: plain text inside HTML tags (not already wrapped) ───
  18. # Match: >Spanish text< but NOT >{{ ... }}< or >{% ... %}<
  19. # This regex finds text content between > and < that contains Spanish chars
  20. def wrap_text_node(m):
  21. prefix = m.group(1) # the >
  22. text = m.group(2)
  23. suffix = m.group(3) # the <
  24. stripped = text.strip()
  25. if not stripped:
  26. return m.group(0)
  27. # Skip if already wrapped
  28. if "{{" in stripped or "{%" in stripped:
  29. return m.group(0)
  30. # Skip if it's just numbers, punctuation, or variable refs
  31. if re.match(r'^[\d\s\.\,\;\:\-\+\*/=<>!@#$%^&()\[\]{}|\\/"\'`~]+$', stripped):
  32. return m.group(0)
  33. # Skip very short strings (1-2 chars) that are likely formatting
  34. if len(stripped) <= 1:
  35. return m.group(0)
  36. # Skip if it looks like a CSS class, URL, or code
  37. if stripped.startswith(("http", "www.", "/", "#", ".", "fas ", "fab ", "far ")):
  38. return m.group(0)
  39. # Must contain at least one letter
  40. if not re.search(r"[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]", stripped):
  41. return m.group(0)
  42. # Preserve whitespace around the text
  43. leading_ws = text[: len(text) - len(text.lstrip())]
  44. trailing_ws = text[len(text.rstrip()) :]
  45. # Escape any quotes in the text
  46. escaped = stripped.replace('"', '\\"')
  47. return f'{prefix}{leading_ws}{{{{ _("{escaped}") }}}}{trailing_ws}{suffix}'
  48. # Process text between HTML tags
  49. content = re.sub(
  50. r"(>)((?:(?!<|{{|{%).)+?)(<)", wrap_text_node, content, flags=re.DOTALL
  51. )
  52. # ─── Pattern: HTML attributes with Spanish text ───
  53. # Common attributes: placeholder, title, data-tooltip, aria-label, alt
  54. attrs_to_translate = [
  55. "placeholder",
  56. "title",
  57. "data-tooltip",
  58. "aria-label",
  59. "alt",
  60. "data-confirm",
  61. "data-message",
  62. "data-title",
  63. ]
  64. for attr in attrs_to_translate:
  65. def wrap_attr(m):
  66. value = m.group(3)
  67. if "{{" in value or "{%" in value:
  68. return m.group(0)
  69. if not re.search(r"[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]", value):
  70. return m.group(0)
  71. if value.startswith(("http", "www.", "/", "#", ".", "fas ", "url_for")):
  72. return m.group(0)
  73. if len(value.strip()) <= 1:
  74. return m.group(0)
  75. escaped = value.replace('"', '\\"').replace("'", "\\'")
  76. return f'{m.group(1)}"{{% raw %}}{{{{ _("{escaped}") }}}}{{% endraw %}}"'
  77. # Match attr="value" where value contains text
  78. pattern = rf'({attr}=)(["\'])((?:(?!\2).)*?)\2'
  79. # Simpler approach - just use {{ _() }} in attribute values
  80. def wrap_attr_simple(m):
  81. attr_name = m.group(1)
  82. value = m.group(3)
  83. if "{{" in value or "{%" in value or "_(" in value:
  84. return m.group(0)
  85. if not re.search(r"[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]", value):
  86. return m.group(0)
  87. if value.startswith(("http", "www.", "/", "#", ".", "fas ", "url_for")):
  88. return m.group(0)
  89. stripped = value.strip()
  90. if len(stripped) <= 1:
  91. return m.group(0)
  92. escaped = stripped.replace('"', '\\"')
  93. # Use {{ _() }} with the attribute
  94. return f'{attr_name}"{{{{ _("{escaped}") }}}}"'
  95. content = re.sub(pattern, wrap_attr_simple, content)
  96. if content != original:
  97. with open(filepath, "w", encoding="utf-8") as f:
  98. f.write(content)
  99. return True
  100. return False
  101. def process_python_file(filepath):
  102. """Process a Python file and wrap user-facing strings with _()."""
  103. with open(filepath, encoding="utf-8") as f:
  104. content = f.read()
  105. original = content
  106. # Add import if _() is going to be used and not already imported
  107. needs_import = False
  108. # Pattern: "message": "Spanish text" in dict returns
  109. def wrap_message_value(m):
  110. nonlocal needs_import
  111. key = m.group(1)
  112. value = m.group(3)
  113. if "_(" in value or 'f"' in value or "f'" in value:
  114. return m.group(0)
  115. if not re.search(r"[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]", value):
  116. return m.group(0)
  117. if value.startswith(("http", "/", ".")):
  118. return m.group(0)
  119. needs_import = True
  120. escaped = value.replace('"', '\\"')
  121. return f'"{key}": _("{escaped}")'
  122. # Wrap "message": "text" patterns
  123. content = re.sub(
  124. r'"(message|status_message|error)":\s*(["\'])((?:(?!\2).)*?)\2',
  125. wrap_message_value,
  126. content,
  127. )
  128. # Pattern: flash("Spanish text", ...)
  129. def wrap_flash(m):
  130. nonlocal needs_import
  131. prefix = m.group(1)
  132. value = m.group(2)
  133. suffix = m.group(3)
  134. if "_(" in value:
  135. return m.group(0)
  136. needs_import = True
  137. escaped = value.replace('"', '\\"')
  138. return f'{prefix}_("{escaped}"){suffix}'
  139. content = re.sub(r'(flash\()"([^"]+)"(\s*[,)])', wrap_flash, content)
  140. if content != original:
  141. # Add import if needed
  142. if needs_import and "from flask_babel import" not in content:
  143. # Find the best place to add import
  144. if "from flask import" in content:
  145. content = content.replace(
  146. "from flask import",
  147. "from flask_babel import gettext as _\nfrom flask import",
  148. 1,
  149. )
  150. else:
  151. content = "from flask_babel import gettext as _\n" + content
  152. with open(filepath, "w", encoding="utf-8") as f:
  153. f.write(content)
  154. return True
  155. return False
  156. def main():
  157. print("=" * 60)
  158. print("SquidStats i18n String Marker")
  159. print("=" * 60)
  160. mode = sys.argv[1] if len(sys.argv) > 1 else "all"
  161. if mode in ("all", "templates"):
  162. print("\n📄 Processing templates...")
  163. template_count = 0
  164. for root, _dirs, files in os.walk(TEMPLATES_DIR):
  165. for f in sorted(files):
  166. if f.endswith(".html"):
  167. filepath = os.path.join(root, f)
  168. relpath = os.path.relpath(filepath, PROJECT_ROOT)
  169. if process_template_file(filepath):
  170. print(f" ✓ {relpath}")
  171. template_count += 1
  172. else:
  173. print(f" - {relpath} (no changes)")
  174. print(f"\n Templates modified: {template_count}")
  175. if mode in ("all", "python"):
  176. print("\n🐍 Processing Python files...")
  177. python_dirs = ["routes", "services"]
  178. py_count = 0
  179. for pdir in python_dirs:
  180. full_dir = os.path.join(PROJECT_ROOT, pdir)
  181. for root, _dirs, files in os.walk(full_dir):
  182. for f in sorted(files):
  183. if f.endswith(".py"):
  184. filepath = os.path.join(root, f)
  185. relpath = os.path.relpath(filepath, PROJECT_ROOT)
  186. if process_python_file(filepath):
  187. print(f" ✓ {relpath}")
  188. py_count += 1
  189. else:
  190. print(f" - {relpath} (no changes)")
  191. print(f"\n Python files modified: {py_count}")
  192. print("\n✅ Done! Next steps:")
  193. print(" 1. Review changes manually")
  194. print(" 2. Run: pybabel extract -F babel.cfg -o translations/messages.pot .")
  195. print(" 3. Run: pybabel init -i translations/messages.pot -d translations -l en")
  196. print(" 4. Edit translations/en/LC_MESSAGES/messages.po")
  197. print(" 5. Run: pybabel compile -d translations")
  198. if __name__ == "__main__":
  199. main()