| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
import argparse |
| 5 |
import subprocess |
| 6 |
import sys |
| 7 |
from collections import defaultdict |
| 8 |
|
| 9 |
from common import Dict |
| 10 |
|
| 11 |
|
| 12 |
def parse_args(): |
| 13 |
parser = argparse.ArgumentParser( |
| 14 |
description="Generate ST phrase entries from regional phrase keys." |
| 15 |
) |
| 16 |
parser.add_argument("--input", action="append", required=True) |
| 17 |
parser.add_argument("--append-to") |
| 18 |
parser.add_argument("--output", required=True) |
| 19 |
backend = parser.add_mutually_exclusive_group(required=True) |
| 20 |
backend.add_argument("--opencc") |
| 21 |
backend.add_argument("--node-binding") |
| 22 |
parser.add_argument("--config", required=True) |
| 23 |
parser.add_argument("--dict-dir", required=True) |
| 24 |
return parser.parse_args() |
| 25 |
|
| 26 |
|
| 27 |
def clean_path_arg(path): |
| 28 |
return path.replace('"', "") |
| 29 |
|
| 30 |
|
| 31 |
def convert_keys(opencc, config, dict_dir, keys): |
| 32 |
result = subprocess.run( |
| 33 |
[ |
| 34 |
opencc, |
| 35 |
"-c", |
| 36 |
config, |
| 37 |
"--path", |
| 38 |
dict_dir, |
| 39 |
"--include-tofu-risk-dictionaries", |
| 40 |
], |
| 41 |
input="\n".join(keys) + "\n", |
| 42 |
encoding="utf-8", |
| 43 |
stdout=subprocess.PIPE, |
| 44 |
stderr=subprocess.PIPE, |
| 45 |
check=False, |
| 46 |
) |
| 47 |
if result.returncode != 0: |
| 48 |
print(result.stderr, file=sys.stderr, end="") |
| 49 |
return None |
| 50 |
|
| 51 |
converted = result.stdout.splitlines() |
| 52 |
if len(converted) != len(keys): |
| 53 |
print( |
| 54 |
"Converted key count mismatch: " |
| 55 |
f"expected {len(keys)}, got {len(converted)}", |
| 56 |
file=sys.stderr, |
| 57 |
) |
| 58 |
return None |
| 59 |
return converted |
| 60 |
|
| 61 |
|
| 62 |
def convert_keys_node(node_binding, config, dict_dir, keys): |
| 63 |
script = r""" |
| 64 |
const fs = require('fs'); |
| 65 |
const path = require('path'); |
| 66 |
const binding = require(process.argv[1]); |
| 67 |
const config = fs.readFileSync(process.argv[2], 'utf8'); |
| 68 |
let dictDir = process.argv[3].replace(/"/g, ''); |
| 69 |
if (!dictDir.endsWith(path.sep)) { |
| 70 |
dictDir += path.sep; |
| 71 |
} |
| 72 |
const converter = new binding.Opencc(config, dictDir); |
| 73 |
let input = ''; |
| 74 |
process.stdin.setEncoding('utf8'); |
| 75 |
process.stdin.on('data', chunk => { input += chunk; }); |
| 76 |
process.stdin.on('end', () => { |
| 77 |
const lines = input.endsWith('\n') ? input.slice(0, -1).split('\n') : input.split('\n'); |
| 78 |
for (const line of lines) { |
| 79 |
process.stdout.write(converter.convertSync(line) + '\n'); |
| 80 |
} |
| 81 |
}); |
| 82 |
""" |
| 83 |
result = subprocess.run( |
| 84 |
["node", "-e", script, node_binding, config, dict_dir], |
| 85 |
input="\n".join(keys) + "\n", |
| 86 |
encoding="utf-8", |
| 87 |
stdout=subprocess.PIPE, |
| 88 |
stderr=subprocess.PIPE, |
| 89 |
check=False, |
| 90 |
) |
| 91 |
if result.returncode != 0: |
| 92 |
print(result.stderr, file=sys.stderr, end="") |
| 93 |
return None |
| 94 |
|
| 95 |
converted = result.stdout.splitlines() |
| 96 |
if len(converted) != len(keys): |
| 97 |
print( |
| 98 |
"Converted key count mismatch: " |
| 99 |
f"expected {len(keys)}, got {len(converted)}", |
| 100 |
file=sys.stderr, |
| 101 |
) |
| 102 |
return None |
| 103 |
return converted |
| 104 |
|
| 105 |
|
| 106 |
def main(): |
| 107 |
args = parse_args() |
| 108 |
if args.opencc: |
| 109 |
args.opencc = clean_path_arg(args.opencc) |
| 110 |
if args.node_binding: |
| 111 |
args.node_binding = clean_path_arg(args.node_binding) |
| 112 |
args.config = clean_path_arg(args.config) |
| 113 |
args.dict_dir = clean_path_arg(args.dict_dir) |
| 114 |
input_names = [input_path.rsplit("/", 1)[-1] for input_path in args.input] |
| 115 |
output_name = args.output.rsplit("/", 1)[-1] |
| 116 |
|
| 117 |
collisions = defaultdict(list) |
| 118 |
for input_path in args.input: |
| 119 |
entries = list(Dict().iter(input_path)) |
| 120 |
keys = [entry["key"] for entry in entries] |
| 121 |
if args.opencc: |
| 122 |
converted_keys = convert_keys(args.opencc, args.config, args.dict_dir, keys) |
| 123 |
else: |
| 124 |
converted_keys = convert_keys_node( |
| 125 |
args.node_binding, args.config, args.dict_dir, keys |
| 126 |
) |
| 127 |
if converted_keys is None: |
| 128 |
return 1 |
| 129 |
|
| 130 |
for converted_key, original_key in zip(converted_keys, keys): |
| 131 |
|
| 132 |
|
| 133 |
if len(converted_key) < 3: |
| 134 |
continue |
| 135 |
collisions[converted_key].append(original_key) |
| 136 |
|
| 137 |
conflicts = { |
| 138 |
key: values for key, values in collisions.items() if len(set(values)) > 1 |
| 139 |
} |
| 140 |
if conflicts: |
| 141 |
print("Conflicting regional phrase simplified projections:", file=sys.stderr) |
| 142 |
for key in sorted(conflicts): |
| 143 |
print(f" {key}: {' '.join(conflicts[key])}", file=sys.stderr) |
| 144 |
return 1 |
| 145 |
|
| 146 |
generated = [ |
| 147 |
{"key": key, "values": [values[0]]} |
| 148 |
for key, values in collisions.items() |
| 149 |
] |
| 150 |
if args.append_to: |
| 151 |
base_entries = list(Dict().iter(args.append_to)) |
| 152 |
seen_keys = {entry["key"] for entry in base_entries} |
| 153 |
generated = base_entries + [ |
| 154 |
entry for entry in generated if entry["key"] not in seen_keys |
| 155 |
] |
| 156 |
generated.sort(key=lambda entry: entry["key"]) |
| 157 |
|
| 158 |
with open(args.output, "w", encoding="utf-8", newline="\n") as stream: |
| 159 |
stream.write("# Open Chinese Convert (OpenCC) Dictionary\n") |
| 160 |
stream.write(f"# File: {output_name}\n") |
| 161 |
stream.write("# Format: key\tvalue(s) (values separated by spaces)\n") |
| 162 |
stream.write("# License: Apache-2.0 (see LICENSE)\n") |
| 163 |
stream.write( |
| 164 |
"# Source: generated from " + ", ".join(input_names) + |
| 165 |
" keys via t2s.json\n" |
| 166 |
) |
| 167 |
if args.append_to: |
| 168 |
append_to_name = args.append_to.rsplit("/", 1)[-1] |
| 169 |
stream.write(f"# Also includes entries from {append_to_name}\n") |
| 170 |
stream.write("# Used in configs: s2t.json, s2hk.json, s2tw.json\n") |
| 171 |
else: |
| 172 |
stream.write("# Used in configs: s2hkp.json, s2twp.json\n") |
| 173 |
stream.write("#\n") |
| 174 |
stream.write("# This generated ST phrase dictionary preserves Simplified-input spans\n") |
| 175 |
stream.write("# before applying regional phrase vocabulary.\n") |
| 176 |
stream.write("\n") |
| 177 |
for entry in generated: |
| 178 |
stream.write(Dict.get_line(entry)) |
| 179 |
|
| 180 |
return 0 |
| 181 |
|
| 182 |
|
| 183 |
if __name__ == "__main__": |
| 184 |
sys.exit(main()) |