jcode/skills/svg-translate/svg_text.py

82 lines
3.4 KiB
Python

#!/usr/bin/env python3
"""svg_text.py - extract / apply translatable text of an SVG file.
python svg_text.py extract in.svg strings.json
python svg_text.py apply in.svg strings.json out.svg [--lang de] [--drop-textlength]
Needs lxml (pip install lxml)."""
import json, re, sys
from lxml import etree
TEXT_TAGS = {"text", "tspan", "textPath", "title", "desc", "flowRoot", "flowPara", "flowSpan", "a"}
ATTRS = ["aria-label"] # translatable attributes
SKIP_RX = re.compile(r"^[\W\d_]*$") # only digits/punctuation/symbols -> keep as is
def local(el):
return etree.QName(el).localname if isinstance(el.tag, str) else None
def units(root):
"""Yield (kind, element, current_string, context) in document order.
kind: 'text' (el.text), 'tail' (el.tail inside a text element), 'attr:<name>'."""
for el in root.iter():
name = local(el)
if name is None:
continue
for a in ATTRS:
if el.get(a):
yield f"attr:{a}", el, el.get(a), el.get(a)
if name not in TEXT_TAGS:
continue
in_text = name != "a" or any(local(p) in ("text", "tspan") for p in el.iterancestors())
if not in_text and name == "a":
continue
top = next((p for p in [*el.iterancestors()][::-1] if local(p) in ("text", "flowRoot")), el)
ctx = " ".join("".join(top.itertext()).split()) # whole sentence, for translation context
if el.text and el.text.strip():
yield "text", el, el.text, ctx
for child in el:
if child.tail and child.tail.strip():
yield "tail", child, child.tail, ctx
def extract(src, dst):
root = etree.parse(src).getroot()
out = []
for i, (kind, el, s, ctx) in enumerate(units(root)):
if SKIP_RX.match(s):
continue
out.append({"id": i, "text": s, "context": ctx, "where": f"{kind} of <{local(el)}>"})
json.dump(out, open(dst, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print(f"{len(out)} translatable strings -> {dst}")
if not out:
print("WARNING: no text found - the text may be converted to paths (cannot be translated).")
def apply(src, jsn, dst, lang=None, drop_tl=False):
tree = etree.parse(src); root = tree.getroot()
tr = {int(d["id"]): d["translation"] for d in json.load(open(jsn, encoding="utf-8"))
if d.get("translation") is not None}
n = 0
for i, (kind, el, s, ctx) in enumerate(units(root)):
if i not in tr:
continue
new = tr[i]
lead = s[:len(s) - len(s.lstrip())]; trail = s[len(s.rstrip()):] # keep surrounding whitespace
new = lead + new.strip() + trail
if kind == "text": el.text = new
elif kind == "tail": el.tail = new
else: el.set(kind[5:], new)
n += 1
if drop_tl:
for el in root.iter():
if isinstance(el.tag, str):
el.attrib.pop("textLength", None); el.attrib.pop("lengthAdjust", None)
if lang:
root.set("{http://www.w3.org/XML/1998/namespace}lang", lang)
tree.write(dst, xml_declaration=True, encoding="utf-8")
print(f"{n} strings applied -> {dst}")
if __name__ == "__main__":
a = sys.argv[1:]
if len(a) == 3 and a[0] == "extract": extract(a[1], a[2])
elif len(a) >= 4 and a[0] == "apply":
lang = a[a.index("--lang") + 1] if "--lang" in a else None
apply(a[1], a[2], a[3], lang, "--drop-textlength" in a)
else: print(__doc__); sys.exit(1)