SPB Git

Repository Public License

localize.py 6.5 KB 144 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : ORIX Monitor10# File             : Scripts/localize.py11# Description      : Rebuilds App/Resources/Localizable.xcstrings: keys12#                    extracted by the compiler, run-time keys (L("…") and core13#                    strings), French-Canadian values from14#                    Scripts/translations-fr-CA.json. Run after a build.15#                    `--missing` lists untranslated keys.16# Module           : Scripts17# Repository       : https://git.spboucher.ai/orix-monitor18# Created          : 2026-11-2119# Last Modified    : 2026-11-2120#21# =============================================================================22# AUTHOR & PROFESSIONAL AFFILIATION23# =============================================================================24#25# Author           : Simon-Pierre Boucher26# Position         : Professor of Finance27# Institution      : Université du Québec en Outaouais (UQO)28# Department       : Département des sciences administratives29# Organization     : SP Boucher30#31# Website          : https://spboucher.ai32# Git              : https://git.spboucher.ai33#34# =============================================================================35# OFFICIAL CONTACT DIRECTORY36# =============================================================================37#38# General          : info@spboucher.ai39# Professional     : contact@spboucher.ai40# Direct           : simon@spboucher.ai41# Research         : research@spboucher.ai42# Development      : dev@spboucher.ai43# Support          : support@spboucher.ai44# Security/Admin   : admin@spboucher.ai45# Notifications    : notifications@spboucher.ai46#47# Preferred Contact: support@spboucher.ai48#49# =============================================================================50# COPYRIGHT & INTELLECTUAL PROPERTY51# =============================================================================52#53# Copyright (c) 202654# Simon-Pierre Boucher55#56# All rights reserved where applicable.57#58# This file is governed by the applicable project license,59# copyright notices, institutional agreements and relevant law.60#61# Unless expressly authorized by the applicable license or62# rights holder, copying, redistribution, sublicensing,63# publication and commercial exploitation are not permitted.64#65# Existing third-party rights and notices remain unaffected.66#67# =============================================================================68# CONFIDENTIALITY & SECURITY69# =============================================================================70#71# Classification   : Public72# Distribution     : Public repository; use is governed by the project license73# Security Contact : admin@spboucher.ai74#75# Access to this source does not independently grant permission76# to redistribute or disclose confidential materials.77#78# Do not embed credentials, private keys, access tokens,79# certificates or confidential personal information.80#81# =============================================================================82# LICENSE & MAINTENANCE83# =============================================================================84#85# License          : Proprietary, all rights reserved (see license file)86# License File     : LICENSE87# Maintainer       : Simon-Pierre Boucher88# Technical Contact: dev@spboucher.ai89#90# =============================================================================91# END OF SP BOUCHER SOURCE HEADER92# =============================================================================9394import glob, json, re, subprocess, sys, os9596ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))97CATALOG = os.path.join(ROOT, "App/Resources/Localizable.xcstrings")98TRANSLATIONS = os.path.join(ROOT, "Scripts/translations-fr-CA.json")99100def swift_unescape(text):101    return text.replace('\\"', '"').replace("\\n", "\n").replace("\\\\", "\\")102103def runtime_keys():104    keys = set()105    pattern = re.compile(r'\bL\("((?:[^"\\]|\\.)*)"\)')106    files = glob.glob(os.path.join(ROOT, "App/Sources/**/*.swift"), recursive=True)107    files += glob.glob(os.path.join(ROOT, "Packages/ORIXMonitorCore/Sources/ORIXMonitorCore/Reporting/*.swift"))108    for path in files:109        keys.update(swift_unescape(m) for m in pattern.findall(open(path, encoding="utf-8").read()))110    probe = subprocess.run(["swift", "run", "--package-path", os.path.join(ROOT, "Packages/ORIXMonitorCore"), "orix-probe", "--strings"],111                           capture_output=True, text=True, check=True)112    keys.update(json.loads(probe.stdout[probe.stdout.index("["):]))113    keys.update(["Overview", "Performance", "Compact", "Good", "Fair", "Poor", "Check Battery"])114    return keys115116def main():117    data = glob.glob(os.path.join(ROOT, "build/dd/Build/Intermediates.noindex/ORIXMonitor.build/**/*.stringsdata"), recursive=True)118    if not data:119        sys.exit("No .stringsdata found: build the app first (Scripts/xb.sh).")120    json.dump({"sourceLanguage": "en", "strings": {}, "version": "1.0"}, open(CATALOG, "w"))121    subprocess.run(["xcrun", "xcstringstool", "sync", CATALOG, "--stringsdata", *data], check=True)122    catalog = json.load(open(CATALOG, encoding="utf-8"))123    for key in runtime_keys():124        catalog["strings"].setdefault(key, {})125    french = json.load(open(TRANSLATIONS, encoding="utf-8")) if os.path.exists(TRANSLATIONS) else {}126    missing = []127    for key, entry in catalog["strings"].items():128        if not re.search(r"[A-Za-z]{2}", key):129            entry["shouldTranslate"] = False130            continue131        if key in french:132            entry["localizations"] = {"fr-CA": {"stringUnit": {"state": "translated", "value": french[key]}}}133        else:134            missing.append(key)135    json.dump(catalog, open(CATALOG, "w", encoding="utf-8"), ensure_ascii=False, indent=2, sort_keys=True)136    unused = sorted(set(french) - set(catalog["strings"]))137    print(f"{len(catalog['strings'])} keys, {len(catalog['strings']) - len(missing)} with French, {len(missing)} missing, {len(unused)} unused translations")138    if "--missing" in sys.argv:139        json.dump(sorted(missing), open(os.path.join(ROOT, "build/missing-fr.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=0)140    if "--unused" in sys.argv:141        print("\n".join(unused))142143main()144
Files main
Menu

Theme