Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / wordmaker / generate_dictionary_assets.py

generate_dictionary_assets.py320 lines · 10.4 KiBRaw
1#!/usr/bin/env python3
2"""Offline generator: dictionary.csv -> words.dawg + definitions.br
3
4Replaces the 16.4 MB dictionary.csv asset (176k rows: Word,Count,POS,Definition)
5with two compact assets:
6
7 words.dawg A minimized DAWG (deterministic acyclic word graph) encoding the
8 set of valid words. Used for membership tests (contains()).
9 definitions.br A brotli-compressed, tab/newline delimited store mapping each
10 word to its list of definitions. Decoded lazily at runtime with
11 org.brotli.dec.BrotliInputStream for getDefinition().
12
13The word set and definitions are parsed with the EXACT same logic the old
14Dictionary.kt used, so runtime behaviour is preserved:
15
16 for each line:
17 parts = line.split(",", limit=4)
18 if len(parts) < 4: skip
19 word = parts[0].lower()
20 definition = parts[3].strip('"')
21 defs[word].append(definition)
22
23The DAWG is built over the UTF-8 BYTES of each word (one edge per byte), so any
24word the old naive CSV parse produced -- including non-ASCII garbage -- is
25representable. contains() in Kotlin traverses the query word's UTF-8 bytes.
26
27words.dawg binary format (big-endian, java.io.DataInputStream friendly):
28 magic : 4 bytes = b"WDG1"
29 edgeCount : int32
30 rootOffset : int32 (edge index where the root node's edges begin)
31 repeat edgeCount:
32 edge : int32 packed:
33 bits 24..31 (8) byte value (one UTF-8 byte of the word)
34 bit 23 (1) lastEdgeOfNode
35 bit 22 (1) targetIsFinal (a word ends at the target node)
36 bits 0..21 (22) targetOffset (edge index of target node, 0 = leaf)
37
38Edge index 0 is a reserved sentinel (an "empty node"); leaf nodes point there so
39a scan of an empty node terminates immediately without matching.
40
41definitions.br: brotli stream of UTF-8 text. One record per word:
42 word \t def1 \t def2 \t ... \n
43Tabs/newlines inside words or definitions are replaced with spaces (none exist in
44the source data; the guard keeps the format unambiguous).
45"""
46
47import struct
48import subprocess
49import sys
50import tempfile
51from pathlib import Path
52
53MAGIC = b"WDG1"
54OFFSET_BITS = 22
55MAX_OFFSET = (1 << OFFSET_BITS) - 1
56FINAL_BIT = 1 << 22
57LAST_BIT = 1 << 23
58
59
60class DawgNode:
61 __slots__ = ("id", "final", "edges")
62 _next_id = 0
63
64 def __init__(self):
65 self.id = DawgNode._next_id
66 DawgNode._next_id += 1
67 self.final = False
68 self.edges = {} # int byte -> DawgNode
69
70 def key(self):
71 # Children are already minimized (bottom-up), so their ids are stable.
72 return (self.final, tuple(sorted((b, n.id) for b, n in self.edges.items())))
73
74
75class Dawg:
76 """Incremental minimal-DAWG construction (Daciuk et al.). Insert in sorted order."""
77
78 def __init__(self):
79 self.previous = b""
80 self.root = DawgNode()
81 self.unchecked = [] # list of (parent, char, child)
82 self.minimized = {} # key -> node
83
84 def insert(self, word):
85 # word is a bytes object; edges are keyed by int byte values.
86 if word < self.previous:
87 raise ValueError(f"words must be inserted in sorted order: {word!r} < {self.previous!r}")
88 common = 0
89 for a, b in zip(word, self.previous):
90 if a != b:
91 break
92 common += 1
93 self._minimize(common)
94 node = self.root if not self.unchecked else self.unchecked[-1][2]
95 for byte in word[common:]:
96 nxt = DawgNode()
97 node.edges[byte] = nxt
98 self.unchecked.append((node, byte, nxt))
99 node = nxt
100 node.final = True
101 self.previous = word
102
103 def finish(self):
104 self._minimize(0)
105
106 def _minimize(self, down_to):
107 for i in range(len(self.unchecked) - 1, down_to - 1, -1):
108 parent, letter, child = self.unchecked[i]
109 k = child.key()
110 existing = self.minimized.get(k)
111 if existing is not None:
112 parent.edges[letter] = existing
113 else:
114 self.minimized[k] = child
115 self.unchecked.pop()
116
117
118def parse_csv(csv_path: Path):
119 """Reproduce old Dictionary.kt parsing exactly. Returns dict[word] -> [defs]."""
120 defs = {}
121 order = []
122 with csv_path.open("r", encoding="utf-8", errors="replace", newline="") as f:
123 # BufferedReader.lines() splits on \n / \r / \r\n; Python universal newlines match.
124 first = True
125 for raw in f:
126 if first:
127 first = False
128 # header row "Word,Count,POS,Definition" -> parts[0]="word" would be
129 # inserted by the old code too, but header word "word" split has 4 parts
130 # ("Word","Count","POS","Definition") so the OLD code DID include it.
131 # Preserve that behaviour: do not skip the header.
132 pass
133 line = raw.rstrip("\n").rstrip("\r")
134 parts = line.split(",", 3)
135 if len(parts) < 4:
136 continue
137 w = parts[0].lower()
138 definition = parts[3].strip('"')
139 if w not in defs:
140 defs[w] = []
141 order.append(w)
142 defs[w].append(definition)
143 return defs, order
144
145
146def build_dawg(words):
147 dawg = Dawg()
148 encoded = sorted(w.encode("utf-8") for w in words if w != "")
149 for wb in encoded:
150 dawg.insert(wb)
151 dawg.finish()
152 return dawg
153
154
155def serialize_dawg(dawg: Dawg) -> bytes:
156 # Collect reachable nodes from root.
157 reachable = []
158 seen = set()
159 stack = [dawg.root]
160 while stack:
161 n = stack.pop()
162 if id(n) in seen:
163 continue
164 seen.add(id(n))
165 reachable.append(n)
166 for c in sorted(n.edges):
167 stack.append(n.edges[c])
168
169 non_leaf = [n for n in reachable if n.edges]
170 # Deterministic order by node id.
171 non_leaf.sort(key=lambda n: n.id)
172
173 # Assign edge offsets. Index 0 is the reserved sentinel (empty node).
174 offset_of = {}
175 idx = 1
176 for n in non_leaf:
177 offset_of[id(n)] = idx
178 idx += len(n.edges)
179 edge_count = idx
180
181 if edge_count > MAX_OFFSET:
182 raise ValueError(f"edge count {edge_count} exceeds {OFFSET_BITS}-bit offset range")
183
184 edges = [0] * edge_count # index 0 = sentinel: char 0, lastBit set, target 0
185 edges[0] = (0 << 24) | LAST_BIT | 0
186
187 for n in non_leaf:
188 base = offset_of[id(n)]
189 keys = sorted(n.edges)
190 for i, code in enumerate(keys):
191 target = n.edges[code]
192 if not (0 <= code <= 0xFF):
193 raise ValueError(f"byte {code} out of range")
194 packed = code << 24
195 if i == len(keys) - 1:
196 packed |= LAST_BIT
197 if target.final:
198 packed |= FINAL_BIT
199 packed |= offset_of.get(id(target), 0) # leaf -> 0
200 edges[base + i] = packed & 0xFFFFFFFF
201
202 root_offset = offset_of[id(dawg.root)]
203 out = bytearray()
204 out += MAGIC
205 out += struct.pack(">i", edge_count)
206 out += struct.pack(">i", root_offset)
207 for e in edges:
208 out += struct.pack(">I", e)
209 return bytes(out)
210
211
212def build_definitions_blob(defs, order):
213 lines = []
214 sanitized = 0
215 for w in order:
216 parts = [w]
217 for d in defs[w]:
218 if "\t" in d or "\n" in d or "\r" in d:
219 d = d.replace("\t", " ").replace("\r", " ").replace("\n", " ")
220 sanitized += 1
221 parts.append(d)
222 clean_w = w.replace("\t", " ").replace("\r", " ").replace("\n", " ")
223 parts[0] = clean_w
224 lines.append("\t".join(parts))
225 if sanitized:
226 print(f" note: sanitized {sanitized} definition(s) containing tab/newline")
227 return ("\n".join(lines)).encode("utf-8")
228
229
230def brotli_compress(data: bytes, out_path: Path):
231 with tempfile.NamedTemporaryFile(delete=False) as tmp:
232 tmp.write(data)
233 tmp_path = Path(tmp.name)
234 try:
235 subprocess.run(
236 ["brotli", "-q", "11", "-f", "-o", str(out_path), str(tmp_path)],
237 check=True,
238 )
239 finally:
240 tmp_path.unlink(missing_ok=True)
241
242
243def main():
244 root = Path(__file__).resolve().parents[2]
245 assets = root / "games/wordmaker/src/main/assets"
246 csv_path = assets / "dictionary.csv"
247 dawg_path = assets / "words.dawg"
248 defs_path = assets / "definitions.br"
249
250 if not csv_path.exists():
251 sys.exit(f"missing {csv_path}")
252
253 print(f"Parsing {csv_path} ...")
254 defs, order = parse_csv(csv_path)
255 print(f" {len(order)} unique words, {sum(len(v) for v in defs.values())} definitions")
256
257 print("Building DAWG ...")
258 dawg = build_dawg(defs.keys())
259 dawg_bytes = serialize_dawg(dawg)
260 dawg_path.write_bytes(dawg_bytes)
261 print(f" wrote {dawg_path} ({len(dawg_bytes):,} bytes)")
262
263 print("Building brotli definitions store ...")
264 blob = build_definitions_blob(defs, order)
265 brotli_compress(blob, defs_path)
266 print(f" wrote {defs_path} ({defs_path.stat().st_size:,} bytes, "
267 f"from {len(blob):,} bytes uncompressed)")
268
269 # Round-trip sanity: verify every word is found by re-reading the DAWG.
270 verify_dawg(dawg_bytes, defs.keys())
271 print("DAWG self-check passed.")
272
273
274def verify_dawg(data: bytes, words):
275 magic = data[:4]
276 assert magic == MAGIC, magic
277 edge_count = struct.unpack_from(">i", data, 4)[0]
278 root_offset = struct.unpack_from(">i", data, 8)[0]
279 edges = struct.unpack_from(f">{edge_count}I", data, 12)
280
281 def contains(word):
282 wb = word.encode("utf-8")
283 node = root_offset
284 n = len(wb)
285 for j, code in enumerate(wb):
286 i = node
287 found = -1
288 while True:
289 e = edges[i]
290 ec = (e >> 24) & 0xFF
291 if ec == code:
292 found = i
293 break
294 if e & LAST_BIT:
295 break
296 i += 1
297 if found < 0:
298 return False
299 e = edges[found]
300 if j == n - 1:
301 return bool(e & FINAL_BIT)
302 node = e & MAX_OFFSET
303 return False
304
305 checked = 0
306 for w in words:
307 if w == "":
308 continue
309 if not contains(w):
310 raise AssertionError(f"word not found in DAWG round-trip: {w!r}")
311 checked += 1
312 # Negative check: a couple of non-words.
313 for bad in ("zzzzzq", "qwxzptv"):
314 if contains(bad):
315 raise AssertionError(f"false positive in DAWG: {bad!r}")
316 print(f" verified {checked} words")
317
318
319if __name__ == "__main__":
320 main()