mark_python_i18n.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. #!/usr/bin/env python3
  2. """Mark user-facing strings in Python files with _() for Flask-Babel."""
  3. import os
  4. import re
  5. import sys
  6. PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  7. # Directories to process
  8. DIRS = ["routes", "services"]
  9. # Keys whose string values should be translated in dict literals
  10. TRANSLATABLE_KEYS = {
  11. "message",
  12. "error",
  13. "msg",
  14. "error_message",
  15. "user_message",
  16. }
  17. IMPORT_LINE = "from flask_babel import gettext as _"
  18. def should_skip_file(filepath):
  19. """Skip certain files."""
  20. basename = os.path.basename(filepath)
  21. if basename == "__init__.py":
  22. return True
  23. if basename == "i18n_routes.py":
  24. return True
  25. return False
  26. def has_gettext_import(content):
  27. """Check if file already imports gettext as _."""
  28. return bool(re.search(r"from flask_babel import.*gettext", content))
  29. def add_import(content):
  30. """Add flask_babel import to file."""
  31. if has_gettext_import(content):
  32. return content
  33. lines = content.split("\n")
  34. insert_idx = 0
  35. for i, line in enumerate(lines):
  36. stripped = line.strip()
  37. if stripped.startswith("from ") or stripped.startswith("import "):
  38. insert_idx = i + 1
  39. lines.insert(insert_idx, IMPORT_LINE)
  40. return "\n".join(lines)
  41. def is_translatable(text):
  42. """Check if a string value should be translated."""
  43. if not text or len(text.strip()) <= 1:
  44. return False
  45. if text.lower() in ("true", "false", "none", "null", "ok"):
  46. return False
  47. # Must have a letter
  48. if not re.search(r"[a-zA-ZáéíóúñÁÉÍÓÚÑüÜ]", text):
  49. return False
  50. # Skip URLs, paths
  51. if re.match(r"^(https?://|/|\.)", text):
  52. return False
  53. return True
  54. def wrap_flash_strings(content):
  55. """Wrap literal string arguments in flash() calls."""
  56. # flash("...", ...) → flash(_("..."), ...)
  57. # Don't match f-strings or already wrapped
  58. def replace_flash_dq(m):
  59. pre = m.group(1)
  60. text = m.group(2)
  61. post = m.group(3)
  62. if not is_translatable(text):
  63. return m.group(0)
  64. return f'{pre}_("{text}"){post}'
  65. # Double-quoted: flash("text", ...) or flash("text")
  66. content = re.sub(
  67. r'(flash\()"((?:[^"\\]|\\.)+)"(\s*[,\)])', replace_flash_dq, content
  68. )
  69. def replace_flash_sq(m):
  70. pre = m.group(1)
  71. text = m.group(2)
  72. post = m.group(3)
  73. if not is_translatable(text):
  74. return m.group(0)
  75. escaped = text.replace('"', '\\"')
  76. return f'{pre}_("{escaped}"){post}'
  77. # Single-quoted: flash('text', ...)
  78. content = re.sub(
  79. r"(flash\()'((?:[^'\\]|\\.)+)'(\s*[,\)])", replace_flash_sq, content
  80. )
  81. return content
  82. def wrap_dict_strings(content):
  83. """Wrap string values for translatable dict keys."""
  84. for key in TRANSLATABLE_KEYS:
  85. # "key": "value" → "key": _("value")
  86. pattern = rf'("{key}":\s*)"((?:[^"\\]|\\.)+)"'
  87. def make_replacer():
  88. def replacer(m):
  89. prefix = m.group(1)
  90. value = m.group(2)
  91. if not is_translatable(value):
  92. return m.group(0)
  93. return f'{prefix}_("{value}")'
  94. return replacer
  95. content = re.sub(pattern, make_replacer(), content)
  96. # 'key': 'value' patterns
  97. pattern_sq = rf"('{key}':\s*)'((?:[^'\\]|\\.)+)'"
  98. def make_replacer_sq():
  99. def replacer_sq(m):
  100. prefix = m.group(1)
  101. value = m.group(2)
  102. if not is_translatable(value):
  103. return m.group(0)
  104. escaped = value.replace('"', '\\"')
  105. return f'{prefix}_("{escaped}")'
  106. return replacer_sq
  107. content = re.sub(pattern_sq, make_replacer_sq(), content)
  108. return content
  109. def wrap_return_dict_strings(content):
  110. """Wrap string values in return {"error": "..."} patterns."""
  111. # Handles return {"error": "text"} and return {"error": "text", ...}
  112. for key in ["error", "success", "message"]:
  113. pattern = rf'(\{{\s*"{key}":\s*)"((?:[^"\\]|\\.)+)"'
  114. def make_replacer(k=key):
  115. def replacer(m):
  116. prefix = m.group(1)
  117. value = m.group(2)
  118. if not is_translatable(value):
  119. return m.group(0)
  120. return f'{prefix}_("{value}")'
  121. return replacer
  122. content = re.sub(pattern, make_replacer(), content)
  123. return content
  124. def process_file(filepath):
  125. """Process a single Python file."""
  126. with open(filepath, encoding="utf-8") as f:
  127. content = f.read()
  128. # Skip if already has _() calls throughout (likely already processed)
  129. original = content
  130. content = wrap_flash_strings(content)
  131. content = wrap_dict_strings(content)
  132. content = wrap_return_dict_strings(content)
  133. if content != original:
  134. content = add_import(content)
  135. with open(filepath, "w", encoding="utf-8") as f:
  136. f.write(content)
  137. return True
  138. return False
  139. def main():
  140. print("=" * 60)
  141. print("SquidStats Python i18n Marker")
  142. print("=" * 60)
  143. target = sys.argv[1] if len(sys.argv) > 1 else None
  144. if target:
  145. filepath = os.path.join(PROJECT_ROOT, target)
  146. if not os.path.exists(filepath):
  147. filepath = target
  148. if os.path.exists(filepath):
  149. if process_file(filepath):
  150. print(f"✓ Modified: {target}")
  151. else:
  152. print(f"- No changes: {target}")
  153. else:
  154. print(f"File not found: {filepath}")
  155. return
  156. count = 0
  157. for dir_name in DIRS:
  158. dir_path = os.path.join(PROJECT_ROOT, dir_name)
  159. for root, _dirs, files in os.walk(dir_path):
  160. for f in sorted(files):
  161. if not f.endswith(".py"):
  162. continue
  163. filepath = os.path.join(root, f)
  164. if should_skip_file(filepath):
  165. continue
  166. relpath = os.path.relpath(filepath, PROJECT_ROOT)
  167. if process_file(filepath):
  168. print(f" ✓ {relpath}")
  169. count += 1
  170. else:
  171. print(f" - {relpath} (no changes)")
  172. print(f"\nModified {count} Python files")
  173. if __name__ == "__main__":
  174. main()