mark_templates_i18n.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #!/usr/bin/env python3
  2. """
  3. Targeted i18n marker for SquidStats Jinja2 templates.
  4. Wraps visible text content with {{ _("...") }}.
  5. Conservative approach - only marks clear text nodes.
  6. """
  7. import os
  8. import re
  9. import sys
  10. PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  11. TEMPLATES_DIR = os.path.join(PROJECT_ROOT, "templates")
  12. # Attributes that contain user-visible text
  13. TRANSLATABLE_ATTRS = {
  14. "placeholder",
  15. "title",
  16. "data-tooltip",
  17. "aria-label",
  18. "alt",
  19. "data-confirm",
  20. "data-confirm-title",
  21. "data-confirm-text",
  22. }
  23. # Strings to skip (technical, not user-facing)
  24. SKIP_PATTERNS = {
  25. "true",
  26. "false",
  27. "none",
  28. "null",
  29. "utf-8",
  30. "UTF-8",
  31. "POST",
  32. "GET",
  33. "PUT",
  34. "DELETE",
  35. "PATCH",
  36. "text/html",
  37. "application/json",
  38. "multipart/form-data",
  39. "hidden",
  40. "submit",
  41. "button",
  42. "text",
  43. "password",
  44. "email",
  45. "number",
  46. "checkbox",
  47. "display: none",
  48. "visibility: hidden",
  49. }
  50. def is_translatable_text(text):
  51. """Check if a text string should be translated."""
  52. stripped = text.strip()
  53. if not stripped or len(stripped) <= 1:
  54. return False
  55. # Already has Jinja2 syntax
  56. if "{{" in stripped or "{%" in stripped or "_(" in stripped:
  57. return False
  58. # Skip technical strings
  59. if stripped.lower() in SKIP_PATTERNS:
  60. return False
  61. # Must contain a letter (not just numbers/symbols)
  62. if not re.search(r"[a-zA-ZáéíóúñÁÉÍÓÚÑüÜàèìòùÀÈÌÒÙ]", stripped):
  63. return False
  64. # Skip URLs, paths, CSS classes, etc.
  65. if re.match(
  66. r"^(https?://|www\.|/|#|\.|fas |fab |far |fal |fad |fa-|bi-|text-|bg-|btn-|col-|row-|d-|p-|m-|w-|h-|flex-|grid-|items-|justify-)",
  67. stripped,
  68. ):
  69. return False
  70. # Skip if it looks like a Jinja variable or filter
  71. if re.match(r"^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)*$", stripped):
  72. return False
  73. # Skip JS code snippets
  74. if any(
  75. kw in stripped
  76. for kw in [
  77. "function(",
  78. "var ",
  79. "const ",
  80. "let ",
  81. "=>",
  82. "return ",
  83. "console.",
  84. "document.",
  85. "window.",
  86. "addEventListener",
  87. ]
  88. ):
  89. return False
  90. return True
  91. def wrap_text(text):
  92. """Wrap a text string with {{ _("...") }}."""
  93. stripped = text.strip()
  94. # Normalize multi-line whitespace to single line
  95. stripped = " ".join(stripped.split())
  96. leading = text[: len(text) - len(text.lstrip())]
  97. trailing = text[len(text.rstrip()) :]
  98. # Escape double quotes
  99. escaped = stripped.replace('"', '\\"')
  100. return f'{leading}{{{{ _("{escaped}") }}}}{trailing}'
  101. def process_text_between_tags(content):
  102. """Process text nodes between HTML tags."""
  103. result = []
  104. pos = 0
  105. while pos < len(content):
  106. # Find next tag or Jinja block
  107. tag_match = re.search(
  108. r"(<[^>]+>|{{.*?}}|{%.*?%}|{#.*?#})", content[pos:], re.DOTALL
  109. )
  110. if not tag_match:
  111. # Rest is text
  112. remaining = content[pos:]
  113. if is_translatable_text(remaining):
  114. result.append(wrap_text(remaining))
  115. else:
  116. result.append(remaining)
  117. break
  118. # Text before the tag
  119. text_before = content[pos : pos + tag_match.start()]
  120. if text_before and is_translatable_text(text_before):
  121. result.append(wrap_text(text_before))
  122. else:
  123. result.append(text_before)
  124. # The tag/block itself
  125. tag = tag_match.group(0)
  126. # Check if it's a script or style tag - skip content
  127. script_match = re.match(r"<(script|style)[\s>]", tag, re.IGNORECASE)
  128. if script_match:
  129. tag_name = script_match.group(1).lower()
  130. close_pattern = f"</{tag_name}>"
  131. close_pos = content.find(close_pattern, pos + tag_match.end())
  132. if close_pos >= 0:
  133. # Include everything from tag to closing tag
  134. result.append(
  135. content[pos + tag_match.start() : close_pos + len(close_pattern)]
  136. )
  137. pos = close_pos + len(close_pattern)
  138. continue
  139. # Process translatable attributes in the tag
  140. if tag.startswith("<"):
  141. tag = process_tag_attributes(tag)
  142. result.append(tag)
  143. pos = pos + tag_match.end()
  144. return "".join(result)
  145. def process_tag_attributes(tag):
  146. """Process translatable attributes in an HTML tag."""
  147. for attr in TRANSLATABLE_ATTRS:
  148. # Match attr="value" or attr='value'
  149. pattern = rf'({attr}=")([^"]*?)(")'
  150. def replace_attr(m):
  151. prefix = m.group(1)
  152. value = m.group(2)
  153. suffix = m.group(3)
  154. if is_translatable_text(value):
  155. escaped = value.strip().replace('"', '\\"')
  156. return f'{prefix}{{{{ _("{escaped}") }}}}{suffix}'
  157. return m.group(0)
  158. tag = re.sub(pattern, replace_attr, tag)
  159. # Single quotes version
  160. pattern_sq = rf"({attr}=')([^']*?)(')"
  161. def replace_attr_sq(m, attr=attr):
  162. value = m.group(2)
  163. if is_translatable_text(value):
  164. escaped = value.strip().replace("'", "\\'")
  165. return f"""{attr}="{{ _("{escaped}") }}" """
  166. return m.group(0)
  167. tag = re.sub(pattern_sq, replace_attr_sq, tag)
  168. return tag
  169. def process_template(filepath):
  170. """Process a single template file."""
  171. with open(filepath, encoding="utf-8") as f:
  172. content = f.read()
  173. original = content
  174. new_content = process_text_between_tags(content)
  175. if new_content != original:
  176. with open(filepath, "w", encoding="utf-8") as f:
  177. f.write(new_content)
  178. return True
  179. return False
  180. def process_line(line):
  181. """Process a single line of template content."""
  182. # Don't process Jinja2 comments
  183. if "{#" in line:
  184. return line
  185. # Don't process lines that are just whitespace
  186. if not line.strip():
  187. return line
  188. # Process text content between tags on this line
  189. # Pattern: find segments of text that are between > and <
  190. def replace_text_segment(m):
  191. before = m.group(1) # > or start
  192. text = m.group(2) # text content
  193. after = m.group(3) # < or end
  194. if is_translatable_text(text):
  195. return before + wrap_text(text) + after
  196. return m.group(0)
  197. # Find text between > and < (tag content)
  198. result = re.sub(r"(>)([^<>{%{}]+?)(<)", replace_text_segment, line)
  199. # Process translatable attributes
  200. for attr in TRANSLATABLE_ATTRS:
  201. pattern = rf'({attr}=")([^"{{}}]*?)(")'
  202. def attr_replacer(m):
  203. prefix = m.group(1)
  204. value = m.group(2)
  205. suffix = m.group(3)
  206. if is_translatable_text(value):
  207. escaped = value.strip().replace('"', '\\"')
  208. return f'{prefix}{{{{ _("{escaped}") }}}}{suffix}'
  209. return m.group(0)
  210. result = re.sub(pattern, attr_replacer, result)
  211. return result
  212. def main():
  213. print("=" * 60)
  214. print("SquidStats Template i18n Marker")
  215. print("=" * 60)
  216. dry_run = "--dry-run" in sys.argv
  217. target = (
  218. sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("--") else None
  219. )
  220. if target:
  221. filepath = os.path.join(PROJECT_ROOT, target)
  222. if not os.path.exists(filepath):
  223. filepath = target
  224. if os.path.exists(filepath):
  225. if dry_run:
  226. with open(filepath) as f:
  227. original = f.read()
  228. process_template(filepath)
  229. with open(filepath) as f:
  230. modified = f.read()
  231. if original != modified:
  232. print(f"Would modify: {target}")
  233. # Restore
  234. with open(filepath, "w") as f:
  235. f.write(original)
  236. else:
  237. print(f"No changes: {target}")
  238. else:
  239. if process_template(filepath):
  240. print(f"✓ Modified: {target}")
  241. else:
  242. print(f"- No changes: {target}")
  243. else:
  244. print(f"File not found: {filepath}")
  245. return
  246. count = 0
  247. for root, _dirs, files in os.walk(TEMPLATES_DIR):
  248. for f in sorted(files):
  249. if f.endswith(".html"):
  250. filepath = os.path.join(root, f)
  251. relpath = os.path.relpath(filepath, PROJECT_ROOT)
  252. if process_template(filepath):
  253. print(f" ✓ {relpath}")
  254. count += 1
  255. else:
  256. print(f" - {relpath} (no changes)")
  257. print(f"\nModified {count} template files")
  258. if __name__ == "__main__":
  259. main()