SPB Git

Repository Public License

localize.py 10.4 KB 248 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : ORIX Camera10# File             : Scripts/localize.py11# Description      : Refreshes App/Resources/Localizable.xcstrings from the12#                    compiler's extracted strings (*.stringsdata of the last13#                    Debug simulator build), merges the French (Canada)14#                    translations of Scripts/translations-fr.json, writes15#                    one/other plural variants in English and French, and16#                    checks that every key is translated with matching format17#                    specifiers. usage: Scripts/localize.py [--no-sync] (exit18#                    code 1 when a key has no French translation or a check19#                    fails)20# Module           : Scripts21# Repository       : https://git.spboucher.ai/orix-camera22# Project Website  : https://www.orixlab.dev23# Created          : 2026-11-2124# Last Modified    : 2026-11-2125#26# =============================================================================27# AUTHOR & PROFESSIONAL AFFILIATION28# =============================================================================29#30# Author           : Simon-Pierre Boucher31# Position         : Professor of Finance32# Institution      : Université du Québec en Outaouais (UQO)33# Department       : Département des sciences administratives34# Organization     : SP Boucher35#36# Website          : https://spboucher.ai37# Git              : https://git.spboucher.ai38#39# =============================================================================40# OFFICIAL CONTACT DIRECTORY41# =============================================================================42#43# General          : info@spboucher.ai44# Professional     : contact@spboucher.ai45# Direct           : simon@spboucher.ai46# Research         : research@spboucher.ai47# Development      : dev@spboucher.ai48# Support          : support@spboucher.ai49# Security/Admin   : admin@spboucher.ai50# Notifications    : notifications@spboucher.ai51#52# Preferred Contact: support@spboucher.ai53#54# =============================================================================55# COPYRIGHT & INTELLECTUAL PROPERTY56# =============================================================================57#58# Copyright (c) 202659# Simon-Pierre Boucher60#61# All rights reserved where applicable.62#63# This file is governed by the applicable project license,64# copyright notices, institutional agreements and relevant law.65#66# Unless expressly authorized by the applicable license or67# rights holder, copying, redistribution, sublicensing,68# publication and commercial exploitation are not permitted.69#70# Existing third-party rights and notices remain unaffected.71#72# =============================================================================73# CONFIDENTIALITY & SECURITY74# =============================================================================75#76# Classification   : Public77# Distribution     : Public repository; use is governed by the project license78# Security Contact : admin@spboucher.ai79#80# Access to this source does not independently grant permission81# to redistribute or disclose confidential materials.82#83# Do not embed credentials, private keys, access tokens,84# certificates or confidential personal information.85#86# =============================================================================87# LICENSE & MAINTENANCE88# =============================================================================89#90# License          : Proprietary, all rights reserved (see license file)91# License File     : LICENSE92# Maintainer       : Simon-Pierre Boucher93# Technical Contact: dev@spboucher.ai94#95# =============================================================================96# END OF SP BOUCHER SOURCE HEADER97# =============================================================================9899import glob100import json101import os102import re103import subprocess104import sys105106ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))107CATALOG = os.path.join(ROOT, "App", "Resources", "Localizable.xcstrings")108TRANSLATIONS = os.path.join(ROOT, "Scripts", "translations-fr.json")109STRINGSDATA = os.path.join(ROOT, "build", "DerivedData", "Build", "Intermediates.noindex", "ORIXCamera.build",110                           "Debug-iphonesimulator", "ORIXCamera.build")111FRENCH = "fr-CA"112NBSP = " "113114# Count strings whose noun inflects: key -> (English one, French one, French other or None to use the translation table).115# The key itself is the English "other" form. In French, "one" also covers zero.116PLURALS = json.load(open(os.path.join(ROOT, "Scripts", "plurals-fr.json"), encoding="utf-8")) if os.path.exists(os.path.join(ROOT, "Scripts", "plurals-fr.json")) else {}117# Strings that reach the interface through a variable (text produced by the imaging package, names of looks, presets and118# white-balance presets): the compiler cannot extract them, so they are added to the catalog here.119MANUAL_KEYS = json.load(open(os.path.join(ROOT, "Scripts", "manual-keys.json"), encoding="utf-8"))120# Keys that are not text to translate.121UNTRANSLATABLE = {""}122123SPECIFIER = re.compile(r"%(?:(\d+)\$)?(lld|ld|d|@|lf|f|s|u|llu)")124PLACEHOLDER = re.compile(r"\$\{[A-Za-z_]+\}|\{(?:title|date|time|pages)\}")125126127def typography(text):128    """French spacing: no-break space before : ; ? ! and inside « »."""129    text = re.sub(r"[  ]([:;?!])", NBSP + r"\1", text)130    text = re.sub(r"«[  ]", "«" + NBSP, text)131    text = re.sub(r"[  ]»", NBSP + "»", text)132    return text133134135def specifiers(text):136    """Format arguments as a sorted list of (position, type); implicit positions are numbered in order."""137    found, implicit = [], 0138    for match in SPECIFIER.finditer(text):139        if match.group(1):140            position = int(match.group(1))141        else:142            implicit += 1143            position = implicit144        found.append((position, match.group(2)))145    return sorted(found)146147148def positional(text):149    """Rewrites implicit specifiers as positional ones (needed as soon as a string has several arguments)."""150    counter = [0]151152    def replace(match):153        if match.group(1):154            return match.group(0)155        counter[0] += 1156        return "%%%d$%s" % (counter[0], match.group(2))157158    return SPECIFIER.sub(replace, text) if len(SPECIFIER.findall(text)) > 1 else text159160161def unit(value):162    return {"stringUnit": {"state": "translated", "value": value}}163164165def plural(one, other):166    return {"variations": {"plural": {"one": unit(one), "other": unit(other)}}}167168169def sync():170    files = sorted(glob.glob(os.path.join(STRINGSDATA, "**", "*.stringsdata"), recursive=True))171    if not files:172        print("warning: no .stringsdata under build/DerivedData (build the app first: Scripts/build.sh debug); catalog not refreshed")173        return False174    if not os.path.exists(CATALOG):175        with open(CATALOG, "w") as handle:176            json.dump({"sourceLanguage": "en", "strings": {}, "version": "1.0"}, handle)177    subprocess.run(["xcrun", "xcstringstool", "sync", CATALOG, "--stringsdata"] + files, check=True)178    return True179180181def main():182    if "--no-sync" not in sys.argv:183        sync()184    if not os.path.exists(CATALOG):185        sys.exit("error: %s does not exist and could not be created" % CATALOG)186    catalog = json.load(open(CATALOG, encoding="utf-8"))187    table = json.load(open(TRANSLATIONS, encoding="utf-8"))["translations"]188    strings = catalog["strings"]189    for key in MANUAL_KEYS:190        strings.setdefault(key, {})["extractionState"] = "manual"191    problems, untranslated, plurals, translated = [], [], 0, 0192193    for key in sorted(strings):194        entry = strings[key]195        if entry.get("extractionState") == "stale":196            continue197        localizations = entry.setdefault("localizations", {})198        if key in UNTRANSLATABLE:199            entry["shouldTranslate"] = False200            entry.pop("localizations", None)201            continue202        if key not in table:203            untranslated.append(key)204            continue205        french = typography(table[key])206        if PLACEHOLDER.findall(key) != [] and sorted(PLACEHOLDER.findall(key)) != sorted(PLACEHOLDER.findall(french)):207            problems.append("placeholders differ: %r -> %r" % (key, french))208        if specifiers(key) != specifiers(french):209            problems.append("format specifiers differ: %r -> %r" % (key, french))210        if key in PLURALS:211            english_one, french_one = PLURALS[key][:2]212            french_one = typography(french_one)213            english_other = positional(key)214            # A singular form may drop the number ("Every page"); otherwise it must take the same arguments.215            for label, value in (("en one", english_one), ("fr one", french_one)):216                if specifiers(value) not in ([], specifiers(key)):217                    problems.append("plural %s has different specifiers: %r" % (label, value))218            localizations["en"] = plural(english_one, english_other)219            localizations[FRENCH] = plural(french_one, positional(french))220            plurals += 1221        else:222            localizations.pop("en", None)223            localizations[FRENCH] = unit(french)224        translated += 1225226    stale = sorted(k for k, v in strings.items() if v.get("extractionState") == "stale")227    orphans = sorted(k for k in table if k not in strings or strings[k].get("extractionState") == "stale")228    with open(CATALOG, "w", encoding="utf-8") as handle:229        json.dump(catalog, handle, ensure_ascii=False, indent=2, sort_keys=True, separators=(",", " : "))230        handle.write("\n")231232    print("%d keys in the catalog, %d translated to %s (%d with one/other plural variants), %d not translatable"233          % (len(strings) - len(stale), translated, FRENCH, plurals, len([k for k in strings if k in UNTRANSLATABLE])))234    if stale:235        print("stale keys (no longer in the code, safe to delete from the catalog): %s" % stale)236    if orphans:237        print("translations without a key in the catalog (remove from translations-fr.json): %s" % orphans)238    for key in untranslated:239        print("UNTRANSLATED: %r" % key)240    for problem in problems:241        print("PROBLEM: %s" % problem)242    if untranslated or problems:243        sys.exit(1)244245246if __name__ == "__main__":247    main()248
Files main
Menu

Theme