|
| 1 | +import argparse |
| 2 | +from .compiler_utils import HEADER |
| 3 | +from ..mandarin.grid import most_plausible_walk |
| 4 | +import sys |
| 5 | +import unittest |
| 6 | + |
| 7 | +errors: list[tuple[int, str]] = [] |
| 8 | +warnings: list[tuple[int, str]] = [] |
| 9 | +epsilon = 0.0001 |
| 10 | + |
| 11 | + |
| 12 | +def set_epsilon(e): |
| 13 | + global epsilon |
| 14 | + epsilon = e |
| 15 | + |
| 16 | + |
| 17 | +def accrue_error(lineno, err): |
| 18 | + errors.append((lineno, err)) |
| 19 | + |
| 20 | + |
| 21 | +def accrue_warning(lineno, warning): |
| 22 | + warnings.append((lineno, warning)) |
| 23 | + |
| 24 | + |
| 25 | +def show_errors_and_warnings(): |
| 26 | + combined = [(lineno, f"error (line {lineno}): {msg}\n") for lineno, msg in errors] |
| 27 | + combined += [ |
| 28 | + (lineno, f"warning (line {lineno}): {msg}\n") for lineno, msg in warnings |
| 29 | + ] |
| 30 | + |
| 31 | + combined = sorted(combined, key=lambda x: x[0]) |
| 32 | + |
| 33 | + for _, msg in combined: |
| 34 | + sys.stderr.write(msg) |
| 35 | + |
| 36 | + |
| 37 | +def segmented_values(nodes): |
| 38 | + return "-".join(n.value for n in nodes) |
| 39 | + |
| 40 | + |
| 41 | +def find_top_unigram_in_lm(lm, reading): |
| 42 | + if reading not in lm: |
| 43 | + return None |
| 44 | + |
| 45 | + unigrams = lm[reading] |
| 46 | + v, s = unigrams[0] |
| 47 | + return (v, float(s)) |
| 48 | + |
| 49 | + |
| 50 | +def find_score_in_lm(lm, reading, value): |
| 51 | + if reading not in lm: |
| 52 | + return None |
| 53 | + |
| 54 | + unigrams = lm[reading] |
| 55 | + for unigram in unigrams: |
| 56 | + if unigram[0] == value: |
| 57 | + return float(unigram[1]) |
| 58 | + |
| 59 | + return None |
| 60 | + |
| 61 | + |
| 62 | +def replace_score_in_lm(lm, reading, value, new_score): |
| 63 | + if reading not in lm: |
| 64 | + raise ValueError(f"reading {reading} not in language model!") |
| 65 | + |
| 66 | + unigrams = lm[reading] |
| 67 | + |
| 68 | + has_replacement = False |
| 69 | + new_unigrams = [] |
| 70 | + for unigram in unigrams: |
| 71 | + uv, us = unigram |
| 72 | + if uv == value: |
| 73 | + if type(us) == str: |
| 74 | + new_unigrams.append((uv, str(new_score))) |
| 75 | + else: |
| 76 | + new_unigrams.append((uv, new_score)) |
| 77 | + has_replacement = True |
| 78 | + else: |
| 79 | + new_unigrams.append((uv, us)) |
| 80 | + |
| 81 | + if not has_replacement: |
| 82 | + raise ValueError("reading:value %s:%s not in LM" % (reading, value)) |
| 83 | + |
| 84 | + unigrams = sorted(new_unigrams, key=lambda x: float(x[1]), reverse=True) |
| 85 | + lm[reading] = unigrams |
| 86 | + return True |
| 87 | + |
| 88 | + |
| 89 | +def promote_over_single_syllables(lineno, lm, value, reading): |
| 90 | + |
| 91 | + readings = reading.split("-") |
| 92 | + |
| 93 | + if len(value) != len(readings): |
| 94 | + return accrue_error(lineno, "number of codepoints don't match readings") |
| 95 | + |
| 96 | + our_score = find_score_in_lm(lm, reading, value) |
| 97 | + if not our_score: |
| 98 | + return accrue_error(lineno, f"reading:value {reading}:{value} not in LM") |
| 99 | + |
| 100 | + # validate data |
| 101 | + unigrams = [find_top_unigram_in_lm(lm, r) for r in readings] |
| 102 | + if not all(unigrams): |
| 103 | + return accrue_error(lineno, "cannot find all single-syllable readings") |
| 104 | + |
| 105 | + their_scores = sum(u[1] for u in unigrams) |
| 106 | + |
| 107 | + if their_scores <= our_score: |
| 108 | + return accrue_error(lineno, "no need to promote") |
| 109 | + |
| 110 | + our_score = their_scores + epsilon |
| 111 | + return replace_score_in_lm(lm, reading, value, our_score) |
| 112 | + |
| 113 | + |
| 114 | +def promote_over_peers(lineno, lm, value, reading): |
| 115 | + our_score = find_score_in_lm(lm, reading, value) |
| 116 | + if not our_score: |
| 117 | + return accrue_error(lineno, f"reading:value {reading}:{value} not in LM") |
| 118 | + |
| 119 | + top_gram = find_top_unigram_in_lm(lm, reading) |
| 120 | + if not top_gram: |
| 121 | + return accrue_error(lineno, f"no unigrams found for reading: {reading}") |
| 122 | + |
| 123 | + top_value, top_score = top_gram |
| 124 | + if top_value == value: |
| 125 | + return accrue_error(lineno, f"value {value} already top among peers") |
| 126 | + |
| 127 | + our_score = float(top_score) + epsilon |
| 128 | + return replace_score_in_lm(lm, reading, value, our_score) |
| 129 | + |
| 130 | + |
| 131 | +def run_assert(lineno, lm, readings, expected, warn_only=False): |
| 132 | + nodes = most_plausible_walk(readings.split("-"), lm) |
| 133 | + result = segmented_values(nodes) |
| 134 | + |
| 135 | + if result != expected: |
| 136 | + if warn_only: |
| 137 | + return accrue_warning(lineno, f"expected: {expected}, actual: {result}") |
| 138 | + else: |
| 139 | + return accrue_error(lineno, f"expected: {expected}, actual: {result}") |
| 140 | + |
| 141 | + |
| 142 | +def postprocess(input, directive, output): |
| 143 | + lm = {} |
| 144 | + |
| 145 | + with open(input) as f: |
| 146 | + lines = f.readlines() |
| 147 | + |
| 148 | + for line in lines[1:]: |
| 149 | + # don't use bare split() since it also splits full-width spaces |
| 150 | + r, v, s = line.strip().split(" ") |
| 151 | + |
| 152 | + if r in lm: |
| 153 | + lm[r].append((v, s)) |
| 154 | + else: |
| 155 | + lm[r] = [(v, s)] |
| 156 | + |
| 157 | + with open(directive) as f: |
| 158 | + lineno = 0 |
| 159 | + |
| 160 | + for line in f: |
| 161 | + lineno += 1 |
| 162 | + |
| 163 | + line = line.strip() |
| 164 | + if not line: |
| 165 | + continue |
| 166 | + if line.startswith("#"): |
| 167 | + continue |
| 168 | + |
| 169 | + elements = line.split() |
| 170 | + if elements[0] == "assert": |
| 171 | + readings = elements[1] |
| 172 | + expected = elements[2] |
| 173 | + run_assert(lineno, lm, readings, expected) |
| 174 | + elif elements[0] == "before": |
| 175 | + readings = elements[1] |
| 176 | + expected = elements[2] |
| 177 | + run_assert(lineno, lm, readings, expected, warn_only=True) |
| 178 | + elif elements[0] == "promote-over-single-syllables": |
| 179 | + value = elements[1] |
| 180 | + reading = elements[2] |
| 181 | + promote_over_single_syllables(lineno, lm, value, reading) |
| 182 | + elif elements[0] == "promote-over-peers": |
| 183 | + value = elements[1] |
| 184 | + reading = elements[2] |
| 185 | + promote_over_peers(lineno, lm, value, reading) |
| 186 | + elif elements[0] == "epsilon": |
| 187 | + set_epsilon(float(elements[1])) |
| 188 | + else: |
| 189 | + accrue_error(lineno, f"unknown command: {elements[0]}") |
| 190 | + |
| 191 | + if errors or warnings: |
| 192 | + show_errors_and_warnings() |
| 193 | + |
| 194 | + if warnings: |
| 195 | + print("%d warning(s) found" % len(warnings)) |
| 196 | + |
| 197 | + if errors: |
| 198 | + print("%d error(s) found" % len(errors)) |
| 199 | + sys.exit(1) |
| 200 | + |
| 201 | + with open(output, "w") as f: |
| 202 | + f.write(HEADER) |
| 203 | + |
| 204 | + for r in sorted(lm.keys(), key=lambda x: x.encode()): |
| 205 | + for v, s in lm[r]: |
| 206 | + f.write("%s %s %s\n" % (r, v, s)) |
| 207 | + |
| 208 | + |
| 209 | +def main(): |
| 210 | + parser = argparse.ArgumentParser(description="postprocess compiled phrase database") |
| 211 | + parser.add_argument("--input", required=True, help="path to source data") |
| 212 | + parser.add_argument("--directive", required=True, help="path to directive file") |
| 213 | + parser.add_argument("--output", required=True, help="path to postprocessed output") |
| 214 | + args = parser.parse_args() |
| 215 | + postprocess(input=args.input, directive=args.directive, output=args.output) |
| 216 | + |
| 217 | + |
| 218 | +if __name__ == "__main__": |
| 219 | + main() |
0 commit comments