Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 6 additions & 27 deletions scripts/translations/babel_update.sh
Original file line number Diff line number Diff line change
Expand Up @@ -108,33 +108,12 @@ do
fi
done

# A few UI labels ("% calculation" etc.) parse as accidentally-valid
# %-format directives (a space flag plus a conversion character), so
# babel auto-flags them python-format on every write and msgfmt then
# fatals on their translations. The app never %-formats them; strip the
# flag AFTER the update pass (babel re-adds it during the update, so
# UI text with a literal percent sign ("% of total", "% calculation", ...)
# parses as accidentally-valid %-format directives (a space flag plus a
# conversion character), so babel auto-flags it python-format on every write
# and msgfmt then fatals on its translations. The app never %-formats it;
# strip the flag AFTER the update pass (babel re-adds it during the update, so
# this must run last). Line-targeted so canonical wrapping is untouched.
python3 - <<'PYEOF'
import glob

TARGETS = {'msgid "% calculation"\n', 'msgid "% of parent"\n', 'msgid "% of total"\n'}
paths = ["superset/translations/messages.pot"] + sorted(
glob.glob("superset/translations/*/LC_MESSAGES/messages.po")
)
for path in paths:
lines = open(path, encoding="utf-8").readlines()
changed = False
for i, line in enumerate(lines):
if line in TARGETS and i > 0 and lines[i - 1].startswith("#,"):
tokens = [t.strip() for t in lines[i - 1][2:].split(",")]
if "python-format" in tokens:
tokens = [t for t in tokens if t != "python-format"]
if "no-python-format" not in tokens:
tokens.append("no-python-format")
lines[i - 1] = "#, " + ", ".join(tokens) + "\n"
changed = True
if changed:
open(path, "w", encoding="utf-8").writelines(lines)
PYEOF
python scripts/translations/literal_percent.py || exit 1

cd $CURRENT_DIR
13 changes: 7 additions & 6 deletions scripts/translations/backfill_po.py
Original file line number Diff line number Diff line change
Expand Up @@ -810,11 +810,6 @@ def _process_batches(
return translated_count, failed_count


# Mirrors the post-processing at the end of babel_update.sh: Babel tags these
# msgids python-format because of the bare ``%``, but they are literal labels.
_PERCENT_LABEL_MSGIDS = {"% calculation", "% of parent", "% of total"}


def normalize_catalog(po_path: Path) -> None:
"""Re-serialize a catalog in the canonical form ``babel_update.sh`` writes.

Expand All @@ -827,11 +822,17 @@ def normalize_catalog(po_path: Path) -> None:
"""
from babel.messages.pofile import read_po, write_po

# A sibling script; importable because this file runs as a script.
from literal_percent import is_literal_percent

lang = po_path.parent.parent.name
with open(po_path, "rb") as f:
catalog = read_po(f, locale=lang)
for message in catalog:
if message.id in _PERCENT_LABEL_MSGIDS and "python-format" in message.flags:
# Mirrors the post-processing at the end of babel_update.sh: Babel
# tags msgids like "% of total" python-format, but the ``%`` is literal.
msgids = message.id if isinstance(message.id, (list, tuple)) else [message.id]
if "python-format" in message.flags and is_literal_percent(*msgids):
message.flags.discard("python-format")
message.flags.add("no-python-format")
with open(po_path, "wb") as f:
Expand Down
131 changes: 131 additions & 0 deletions scripts/translations/literal_percent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Drop the python-format flag from messages whose ``%`` is literal text.

Babel flags a message ``python-format`` whenever its msgid contains something
that parses as a %-format directive. UI text such as "% of total" or
"% calculation" parses by accident: ``% o`` and ``% c`` read as a space flag
plus a conversion character. The app never %-formats these strings, and msgfmt
rejects any translation that does not repeat the accidental directive. This
swaps ``python-format`` for ``no-python-format`` on those entries.

Babel re-adds the flag every time it writes a catalog, so ``babel_update.sh``
runs this after its ``pybabel update`` pass, and ``backfill_po.py`` applies
``is_literal_percent`` when it re-serializes a catalog. Only ``#,`` flag lines
are rewritten, so the canonical wrapping of the files is untouched.

Usage:
python scripts/translations/literal_percent.py [PATH ...]
# PATH defaults to messages.pot and every language's messages.po
"""

from __future__ import annotations

import re
import sys
from pathlib import Path

from babel.messages.catalog import PYTHON_FORMAT
from babel.messages.pofile import unescape

TRANSLATIONS_DIR: Path = (
Path(__file__).parent.parent.parent / "superset" / "translations"
)

# A percent sign followed by a space and a word, as in "% of" or "50% off".
# A real space-flag directive ("% d") is never followed by more letters, and
# the second "%" of a "%%" escape is part of a real format string.
_LITERAL_PERCENT = re.compile(r"(?<!%)% (?=[A-Za-z]{2})")


def is_literal_percent(*msgids: str) -> bool:
"""Return True if Babel sees %-format directives only in literal ``% word`` text.

Pass the msgid and, for plural entries, the msgid_plural. A message that
also has a real placeholder (``%(name)s``, ``%s``) keeps its flag.
"""
return any(PYTHON_FORMAT.search(msgid) for msgid in msgids) and not any(
PYTHON_FORMAT.search(_LITERAL_PERCENT.sub(" ", msgid)) for msgid in msgids
)


def _read_field(lines: list[str], i: int, keyword: str) -> tuple[str | None, int]:
"""Read a possibly wrapped ``keyword "..."`` field starting at line ``i``.

Returns the unescaped value (None if line ``i`` is not that field) and the
index of the first line after it.
"""
if i >= len(lines) or not lines[i].startswith(f'{keyword} "'):
return None, i
parts = [lines[i][len(keyword) :].strip()]
i += 1
while i < len(lines) and lines[i].startswith('"'):
parts.append(lines[i].strip())
i += 1
return "".join(unescape(part) for part in parts), i


def fix_flags(path: Path) -> bool:
"""Rewrite the flags of literal-percent entries in ``path``.

Returns True if the file changed.
"""
lines = path.read_text(encoding="utf-8").splitlines(keepends=True)
changed = False
for i, line in enumerate(lines):
if not line.startswith("#,"):
continue
flags = [flag.strip() for flag in line[2:].split(",")]
if "python-format" not in flags:
continue
j = i + 1
while j < len(lines) and lines[j].startswith("#|"):
j += 1
_, j = _read_field(lines, j, "msgctxt")
msgid, j = _read_field(lines, j, "msgid")
if msgid is None:
continue
msgids = [msgid]
plural, j = _read_field(lines, j, "msgid_plural")
if plural is not None:
msgids.append(plural)
if not is_literal_percent(*msgids):
continue
flags = [flag for flag in flags if flag != "python-format"]
if "no-python-format" not in flags:
flags.append("no-python-format")
lines[i] = "#, " + ", ".join(flags) + "\n"
changed = True
if changed:
path.write_text("".join(lines), encoding="utf-8", newline="\n")
return changed


def main(argv: list[str]) -> int:
paths = [Path(arg) for arg in argv[1:]] or [
TRANSLATIONS_DIR / "messages.pot",
*sorted(TRANSLATIONS_DIR.glob("*/LC_MESSAGES/messages.po")),
]
for path in paths:
if fix_flags(path):
print(f"Cleared python-format on literal-percent entries in {path}")
return 0


if __name__ == "__main__":
sys.exit(main(sys.argv))
16 changes: 8 additions & 8 deletions superset/translations/ar/LC_MESSAGES/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -203,22 +203,22 @@ msgid "% calculation"
msgstr "حساب ٪"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of"
msgstr "% من"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of column"
msgstr "% من العمود"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of column total"
msgstr "% من إجمالي العمود"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of grand total"
msgstr "% من الإجمالي الكلي"

Expand All @@ -229,7 +229,7 @@ msgid "% of parent"
msgstr "% من الأصل"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of row total"
msgstr "% من إجمالي الصف"

Expand Down Expand Up @@ -14426,7 +14426,7 @@ msgid "Optional warning about use of this metric"
msgstr "تحذير اختياري حول استخدام هذا المقياس"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Optional. When set together with Low color, Mid color, and High color "
"below, colors diverge from Mid color at this value toward Low color below"
Expand Down Expand Up @@ -24282,7 +24282,7 @@ msgid "Value transform"
msgstr "تحويل القيمة"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Value: type the exact numbers used for coloring below. % of column is "
"unavailable with Server pagination enabled, since each page would compute"
Expand All @@ -24295,7 +24295,7 @@ msgstr ""
"التلقائي أثناء تفعيل ترقيم الصفحات من الخادم."

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Value: type the exact numbers used for coloring below. % of column: type "
"a percentage of the column maximum or sum selected below, so the rule "
Expand Down
16 changes: 8 additions & 8 deletions superset/translations/ca/LC_MESSAGES/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -198,22 +198,22 @@ msgid "% calculation"
msgstr "% càlcul"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of"
msgstr "% de"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of column"
msgstr "% de la columna"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of column total"
msgstr "% del total de la columna"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of grand total"
msgstr "% del total general"

Expand All @@ -222,7 +222,7 @@ msgid "% of parent"
msgstr "%% del pare"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of row total"
msgstr "% del total de la fila"

Expand Down Expand Up @@ -14094,7 +14094,7 @@ msgid "Optional warning about use of this metric"
msgstr "Advertència opcional sobre l'ús d'aquesta mètrica"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Optional. When set together with Low color, Mid color, and High color "
"below, colors diverge from Mid color at this value toward Low color below"
Expand Down Expand Up @@ -23899,7 +23899,7 @@ msgid "Value transform"
msgstr "Transformació del valor"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Value: type the exact numbers used for coloring below. % of column is "
"unavailable with Server pagination enabled, since each page would compute"
Expand All @@ -23913,7 +23913,7 @@ msgstr ""
"dades mentre la paginació del servidor està activada."

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Value: type the exact numbers used for coloring below. % of column: type "
"a percentage of the column maximum or sum selected below, so the rule "
Expand Down
16 changes: 8 additions & 8 deletions superset/translations/cs/LC_MESSAGES/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -190,22 +190,22 @@ msgid "% calculation"
msgstr "Výpočet v %"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of"
msgstr "% z"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of column"
msgstr "% sloupce"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of column total"
msgstr "% součtu sloupce"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of grand total"
msgstr "% celkového součtu"

Expand All @@ -214,7 +214,7 @@ msgid "% of parent"
msgstr "% z nadřazené položky"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of row total"
msgstr "% součtu řádku"

Expand Down Expand Up @@ -13580,7 +13580,7 @@ msgid "Optional warning about use of this metric"
msgstr "Volitelné varování o použití této metriky"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Optional. When set together with Low color, Mid color, and High color "
"below, colors diverge from Mid color at this value toward Low color below"
Expand Down Expand Up @@ -22993,7 +22993,7 @@ msgid "Value transform"
msgstr "Transformace hodnoty"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Value: type the exact numbers used for coloring below. % of column is "
"unavailable with Server pagination enabled, since each page would compute"
Expand All @@ -23007,7 +23007,7 @@ msgstr ""
"serveru automatický rozsah dat."

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Value: type the exact numbers used for coloring below. % of column: type "
"a percentage of the column maximum or sum selected below, so the rule "
Expand Down
Loading
Loading