Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

4.3 KB
Raw Blame
#!/usr/bin/env python3
import glob, json, os, re, subprocess, sys, tempfile

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LANGS = ["en", "ja", "ko"]
TABLE = os.path.join(ROOT, "Resources/{}.lproj/Localizable.strings")
ZH = os.path.join(ROOT, "Resources/zh-Hans.lproj/Localizable.strings")
DICT = os.path.join(ROOT, "Resources/en.lproj/Localizable.stringsdict")
CJK = re.compile(r"[\u4e00-\u9fff]")
SPEC = re.compile(r"%(?:\d+\$)?[-+ 0#]*\d*(?:\.\d+)?(lld|ld|d|@|f)")


def specs(s):
    return sorted(SPEC.findall(s))


def code_keys():
    out = tempfile.mkdtemp()
    subprocess.run(["swift", "build", "--product", "Cicada", "-Xswiftc", "-emit-localized-strings",
                    "-Xswiftc", "-emit-localized-strings-path", "-Xswiftc", out],
                   cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
    if subprocess.run(["xcrun", "--sdk", "iphonesimulator", "--show-sdk-path"], capture_output=True).returncode == 0:
        subprocess.run([os.path.join(ROOT, "ios/scripts/build.sh")], cwd=ROOT, check=True, stdout=subprocess.DEVNULL,
                       env={**os.environ, "STRINGS_OUT": os.path.join(out, "ios")})
    else:
        print("ios: no iOS SDK (needs Xcode), its strings are not checked")
    keys = {}
    for f in sorted(glob.glob(os.path.join(out, "*.stringsdata")) + glob.glob(os.path.join(out, "ios", "*.stringsdata"))):
        for entries in json.load(open(f))["tables"].values():
            for e in entries:
                if CJK.search(e["key"]):
                    keys.setdefault(e["key"], os.path.basename(f).split(".")[0])
    return keys


PORTS = {"Windows": ["windows/src/**/*.cs"], "Android": ["android/app/src/**/*.kt", "android/core/src/**/*.kt"],
         "Linux": ["linux/cicada/**/*.py"], "iOS broadcast": ["ios/Broadcast/*.swift"]}
PORT_CALL = re.compile(r'\bLF?\("((?:[^"\\]|\\.)*)"')


def port_keys():
    keys = {}
    for port, patterns in PORTS.items():
        for pattern in patterns:
            for f in sorted(glob.glob(os.path.join(ROOT, pattern), recursive=True)):
                for k in PORT_CALL.findall(open(f, encoding="utf-8").read()):
                    k = re.sub(r"\\(.)", lambda m: "\n" if m.group(1) == "n" else m.group(1), k)
                    if CJK.search(k): keys.setdefault(k, set()).add(port)
    return keys


def load(path):
    if not os.path.exists(path):
        return {}
    return json.loads(subprocess.check_output(["plutil", "-convert", "json", "-o", "-", path]))


def esc(s):
    return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")


def write(path, pairs):
    lines, last = [], None
    for k, v, group in pairs:
        if group != last:
            lines.append(f"\n/* {group} */")
            last = group
        lines.append(f'"{esc(k)}" = "{esc(v)}";')
    open(path, "w").write("\n".join(lines).lstrip() + "\n")


def main():
    keys = code_keys()
    ports = port_keys()
    bad = False
    for lang in LANGS:
        path = TABLE.format(lang)
        table = load(path)
        missing = [k for k in keys if k not in table]
        unused = [k for k in table if k not in keys and k not in ports]
        kept = [(k, v, "Only the ports: " + ", ".join(sorted(ports[k]))) for k, v in table.items() if k not in keys and k in ports]
        todo = [k for k, v in table.items() if v == "TODO"]
        mismatch = [k for k, v in table.items() if v != "TODO" and specs(k) != specs(v)]
        for k in missing: print(f"{lang} missing   {keys[k]}: {k}")
        for k in unused: print(f"{lang} unused    {k}")
        for k in todo: print(f"{lang} todo      {k}")
        for k in mismatch: print(f"{lang} specifier {k} -> {table[k]}")
        if "--write" in sys.argv:
            write(path, [(k, table.get(k, "TODO"), g) for k, g in keys.items()] + sorted(kept, key=lambda p: p[2]))
        subprocess.run(["plutil", "-lint", "-s", path], check=True)
        print(f"{lang}: {len(keys)} keys, {len(missing)} missing, {len(unused)} unused, {len(todo)} TODO, {len(mismatch)} bad specifiers")
        bad |= bool(missing or todo or mismatch)
    for k in load(DICT):
        if k not in keys: print(f"unused plural  {k}")
    if "--write" in sys.argv:
        write(ZH, [(k, k, g) for k, g in keys.items()])
    for p in (ZH, DICT):
        subprocess.run(["plutil", "-lint", "-s", p], check=True)
    sys.exit(1 if bad and "--write" not in sys.argv else 0)


main()