Debian Codegraph @

scripts/compile_to_inline_config.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 import argparse
4 import datetime
5 import json
6 import re
7 import sys
8 from pathlib import Path
9 from typing import Any, Dict, List
10
11 def get_opencc_version() -> str:
12 try:
13 script_dir = Path(__file__).resolve().parent
14 repo_root = script_dir.parent
15 package_json_path = repo_root / "package.json"
16 if package_json_path.exists():
17 with package_json_path.open("r", encoding="utf-8") as f:
18 data = json.load(f)
19 return data.get("version", "unknown")
20 except Exception:
21 pass
22 return "unknown"
23
24 def parse_jsonc(text: str) -> Any:
25 # remove single line comments
26 text = re.sub(r'//.*', '', text)
27 # remove multi line comments
28 text = re.sub(r'/\*.*?\*/', '', text, flags=re.DOTALL)
29 # remove trailing commas
30 text = re.sub(r',\s*([\]}])', r'\1', text)
31 return json.loads(text)
32
33 def parse_txt_dict(path: Path) -> Dict[str, List[str]]:
34 entries: Dict[str, List[str]] = {}
35 with path.open("r", encoding="utf-8") as f:
36 for line in f:
37 if line.startswith("#") or not line.strip():
38 continue
39 parts = line.rstrip("\r\n").split("\t", 1)
40 if len(parts) < 2:
41 continue
42 key = parts[0]
43 values = parts[1].split(" ")
44 entries[key] = values
45 return entries
46
47 def reverse_dict_entries(entries: Dict[str, List[str]]) -> Dict[str, List[str]]:
48 reversed_entries: Dict[str, List[str]] = {}
49 for key, values in entries.items():
50 for val in values:
51 if val not in reversed_entries:
52 reversed_entries[val] = []
53 reversed_entries[val].append(key)
54 return reversed_entries
55
56 def load_dict(name: str, dict_dir: Path) -> Dict[str, List[str]]:
57 # Check if it is TSCharactersExt
58 if name == "TSCharactersExt":
59 return {} # Ignore as requested
60
61 # Try to load name.txt
62 txt_path = dict_dir / f"{name}.txt"
63 if txt_path.exists():
64 return parse_txt_dict(txt_path)
65
66 # Check if it is a reversed dictionary
67 if name.endswith("Rev"):
68 base_name = name[:-3]
69 base_txt_path = dict_dir / f"{base_name}.txt"
70 if base_txt_path.exists():
71 base_entries = parse_txt_dict(base_txt_path)
72 return reverse_dict_entries(base_entries)
73
74 raise FileNotFoundError(f"Dictionary file not found for: {name} in {dict_dir}")
75
76 def inline_entries_for_file_dict(dict_def: Dict[str, Any], dict_dir: Path) -> Dict[str, str]:
77 file_name = dict_def["file"]
78 base_name = Path(file_name).stem
79 raw_dict = load_dict(base_name, dict_dir)
80 return {k: v[0] for k, v in raw_dict.items()}
81
82 def is_union_mergeable(compiled: Dict[str, Any]) -> bool:
83 """Return True if compiled can be fully flattened into a single inline dict.
84
85 A dict is mergeable if it is inline, or if it is a union group whose every
86 child is recursively mergeable. Short-circuit and other group policies are
87 not mergeable because child order affects which match wins.
88 """
89 if compiled["type"] == "inline":
90 return True
91 if compiled["type"] == "group" and compiled.get("match_policy") == "union":
92 return all(is_union_mergeable(child) for child in compiled["dicts"])
93 return False
94
95
96 def collect_union_entries(compiled: Dict[str, Any], merged: Dict[str, str]) -> None:
97 """Recursively collect entries from a mergeable dict into merged.
98
99 Only call after is_union_mergeable() has confirmed the whole subtree is
100 mergeable. First-occurrence wins for duplicate keys.
101 """
102 if compiled["type"] == "inline":
103 for k, v in compiled["entries"].items():
104 if k not in merged:
105 merged[k] = v
106 else:
107 for child in compiled["dicts"]:
108 collect_union_entries(child, merged)
109
110
111 def compile_dict(dict_def: Dict[str, Any], dict_dir: Path) -> Dict[str, Any]:
112 if dict_def["type"] == "group":
113 compiled_children = [compile_dict(sub_def, dict_dir) for sub_def in dict_def["dicts"]]
114 match_policy = dict_def.get("match_policy", "short_circuit")
115
116 if match_policy == "union":
117 # Union semantics: longest prefix wins regardless of child order.
118 # A flat merged inline dict has the same semantics because LeafMatcher
119 # always returns the longest match; first-occurrence wins for same key.
120 # Nested union groups are also absorbed since union(union(...)) = union(...).
121 if all(is_union_mergeable(child) for child in compiled_children):
122 merged: Dict[str, str] = {}
123 for child in compiled_children:
124 collect_union_entries(child, merged)
125 return {"type": "inline", "entries": sort_dict_keys(merged)}
126
127 result: Dict[str, Any] = {"type": "group"}
128 if "match_policy" in dict_def:
129 result["match_policy"] = dict_def["match_policy"]
130 result["dicts"] = compiled_children
131 return result
132
133 if dict_def["type"] == "inline":
134 entries = dict_def["entries"]
135 else:
136 entries = inline_entries_for_file_dict(dict_def, dict_dir)
137
138 return {
139 "type": "inline",
140 "entries": sort_dict_keys(entries),
141 }
142
143 def sort_dict_keys(d: Dict[str, str]) -> Dict[str, str]:
144 return {k: d[k] for k in sorted(d.keys())}
145
146 def compile_config(config_path: Path, dict_dir: Path) -> Dict[str, Any]:
147 with config_path.open("r", encoding="utf-8") as f:
148 config_content = f.read()
149
150 config_data = parse_jsonc(config_content)
151
152 # Process segmentation dict if present
153 if "segmentation" in config_data and "dict" in config_data["segmentation"]:
154 dict_def = config_data["segmentation"]["dict"]
155 config_data["segmentation"]["dict"] = compile_dict(dict_def, dict_dir)
156
157 # Process conversion chain dicts
158 if "conversion_chain" in config_data:
159 for stage in config_data["conversion_chain"]:
160 if "dict" in stage:
161 dict_def = stage["dict"]
162 stage["dict"] = compile_dict(dict_def, dict_dir)
163
164 return config_data
165
166 def main() -> int:
167 parser = argparse.ArgumentParser(
168 description="Compile OpenCC config and dicts to a single inline JSON config.",
169 epilog="Example:\n"
170 " python3 scripts/compile_to_inline_config.py -c data/config/s2t.json -d data/dictionary -o tmp/s2t_inline.json\n",
171 formatter_class=argparse.RawDescriptionHelpFormatter
172 )
173 parser.add_argument("-c", "--config", required=True, type=Path, help="Path to original OpenCC JSON config")
174 parser.add_argument("-d", "--dict-dir", required=True, type=Path, help="Directory containing .txt source dictionaries")
175 parser.add_argument("-o", "--output", required=True, type=Path, help="Output path for inlined JSON config")
176
177 args = parser.parse_args()
178
179 if not args.config.exists():
180 print(f"Error: Config file not found: {args.config}", file=sys.stderr)
181 return 1
182 if not args.dict_dir.is_dir():
183 print(f"Error: Dictionary directory not found: {args.dict_dir}", file=sys.stderr)
184 return 1
185
186 try:
187 compiled_config = compile_config(args.config, args.dict_dir)
188 args.output.parent.mkdir(parents=True, exist_ok=True)
189
190 version = get_opencc_version()
191 timestamp = datetime.datetime.now().astimezone().strftime('%Y-%m-%d %H:%M:%S %Z')
192 metadata_comments = (
193 "// Generated by OpenCC compile_to_inline_config.py\n"
194 f"// OpenCC Version: {version}\n"
195 f"// Source Config: {args.config.name}\n"
196 f"// Compiled At: {timestamp}\n\n"
197 )
198
199 with args.output.open("w", encoding="utf-8") as f:
200 f.write(metadata_comments)
201 json.dump(compiled_config, f, ensure_ascii=False, indent=2)
202 f.write("\n")
203 print(f"Successfully compiled to {args.output}")
204 return 0
205 except Exception as e:
206 print(f"Error: {e}", file=sys.stderr)
207 return 1
208
209 if __name__ == "__main__":
210 raise SystemExit(main())