| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
import argparse |
| 20 |
import difflib |
| 21 |
from collections import Counter |
| 22 |
from itertools import combinations |
| 23 |
from pathlib import Path |
| 24 |
import sys |
| 25 |
from typing import Iterable |
| 26 |
|
| 27 |
|
| 28 |
def workspace_root() -> Path: |
| 29 |
return Path(__file__).resolve().parents[2] |
| 30 |
|
| 31 |
|
| 32 |
def output_dir() -> Path: |
| 33 |
return workspace_root() / "test/golden/output" |
| 34 |
|
| 35 |
|
| 36 |
def parse_output_name(path: Path) -> tuple[str, str]: |
| 37 |
stem = path.stem |
| 38 |
input_name, _, config = stem.rpartition(".") |
| 39 |
if not input_name or not config: |
| 40 |
raise ValueError(f"Unexpected output file name: {path.name}") |
| 41 |
return input_name, config |
| 42 |
|
| 43 |
|
| 44 |
def load_outputs() -> dict[str, dict[str, list[str]]]: |
| 45 |
grouped: dict[str, dict[str, list[str]]] = {} |
| 46 |
for path in sorted(output_dir().glob("*.txt")): |
| 47 |
input_name, config = parse_output_name(path) |
| 48 |
grouped.setdefault(input_name, {})[config] = path.read_text( |
| 49 |
encoding="utf-8" |
| 50 |
).splitlines() |
| 51 |
return grouped |
| 52 |
|
| 53 |
|
| 54 |
def choose_input(all_outputs: dict[str, dict[str, list[str]]], input_name: str | None) -> str: |
| 55 |
if input_name is not None: |
| 56 |
if input_name not in all_outputs: |
| 57 |
raise SystemExit(f"Unknown input: {input_name}") |
| 58 |
return input_name |
| 59 |
|
| 60 |
names = sorted(all_outputs) |
| 61 |
if len(names) != 1: |
| 62 |
joined = ", ".join(names) |
| 63 |
raise SystemExit(f"Multiple inputs found; pass --input. Available: {joined}") |
| 64 |
return names[0] |
| 65 |
|
| 66 |
|
| 67 |
def diff_lines(left: list[str], right: list[str]) -> list[int]: |
| 68 |
limit = min(len(left), len(right)) |
| 69 |
differing = [i + 1 for i in range(limit) if left[i] != right[i]] |
| 70 |
if len(left) != len(right): |
| 71 |
differing.extend(range(limit + 1, max(len(left), len(right)) + 1)) |
| 72 |
return differing |
| 73 |
|
| 74 |
|
| 75 |
def use_color(mode: str) -> bool: |
| 76 |
if mode == "always": |
| 77 |
return True |
| 78 |
if mode == "never": |
| 79 |
return False |
| 80 |
return sys.stdout.isatty() and "NO_COLOR" not in os_environ() |
| 81 |
|
| 82 |
|
| 83 |
def os_environ() -> dict[str, str]: |
| 84 |
import os |
| 85 |
|
| 86 |
return os.environ |
| 87 |
|
| 88 |
|
| 89 |
def colorize(text: str, enabled: bool, role: str = "minor") -> str: |
| 90 |
if not enabled or not text: |
| 91 |
return text |
| 92 |
colors = { |
| 93 |
"major": "\033[1;34m", |
| 94 |
"minor": "\033[1;31m", |
| 95 |
} |
| 96 |
return f"{colors.get(role, colors['minor'])}{text}\033[0m" |
| 97 |
|
| 98 |
|
| 99 |
def common_prefix(strings: list[str]) -> str: |
| 100 |
if not strings: |
| 101 |
return "" |
| 102 |
prefix = strings[0] |
| 103 |
for text in strings[1:]: |
| 104 |
limit = min(len(prefix), len(text)) |
| 105 |
index = 0 |
| 106 |
while index < limit and prefix[index] == text[index]: |
| 107 |
index += 1 |
| 108 |
prefix = prefix[:index] |
| 109 |
if not prefix: |
| 110 |
break |
| 111 |
return prefix |
| 112 |
|
| 113 |
|
| 114 |
def common_suffix(strings: list[str], prefix_len: int) -> str: |
| 115 |
if not strings: |
| 116 |
return "" |
| 117 |
suffix = strings[0][prefix_len:] |
| 118 |
for text in strings[1:]: |
| 119 |
candidate = text[prefix_len:] |
| 120 |
limit = min(len(suffix), len(candidate)) |
| 121 |
index = 0 |
| 122 |
while index < limit and suffix[-(index + 1)] == candidate[-(index + 1)]: |
| 123 |
index += 1 |
| 124 |
suffix = suffix[len(suffix) - index :] if index else "" |
| 125 |
if not suffix: |
| 126 |
break |
| 127 |
return suffix |
| 128 |
|
| 129 |
|
| 130 |
def highlight_spans( |
| 131 |
text: str, spans: list[tuple[int, int, str]], enabled: bool |
| 132 |
) -> str: |
| 133 |
if not enabled or not spans: |
| 134 |
return text |
| 135 |
|
| 136 |
merged: list[tuple[int, int, str]] = [] |
| 137 |
for start, end, role in sorted(spans): |
| 138 |
if start >= end: |
| 139 |
continue |
| 140 |
if not merged or start > merged[-1][1] or role != merged[-1][2]: |
| 141 |
merged.append((start, end, role)) |
| 142 |
else: |
| 143 |
merged[-1] = (merged[-1][0], max(merged[-1][1], end), role) |
| 144 |
|
| 145 |
parts: list[str] = [] |
| 146 |
cursor = 0 |
| 147 |
for start, end, role in merged: |
| 148 |
parts.append(text[cursor:start]) |
| 149 |
parts.append(colorize(text[start:end], enabled, role)) |
| 150 |
cursor = end |
| 151 |
parts.append(text[cursor:]) |
| 152 |
return "".join(parts) |
| 153 |
|
| 154 |
|
| 155 |
def map_reference_span( |
| 156 |
opcodes: list[tuple[str, int, int, int, int]], start: int, end: int |
| 157 |
) -> tuple[int, int]: |
| 158 |
mapped_start: int | None = None |
| 159 |
mapped_end: int | None = None |
| 160 |
|
| 161 |
for tag, i1, i2, j1, j2 in opcodes: |
| 162 |
if end <= i1: |
| 163 |
break |
| 164 |
if start >= i2: |
| 165 |
continue |
| 166 |
overlap_start = max(start, i1) |
| 167 |
overlap_end = min(end, i2) |
| 168 |
if overlap_start >= overlap_end: |
| 169 |
continue |
| 170 |
|
| 171 |
if tag == "equal": |
| 172 |
candidate_start = j1 + (overlap_start - i1) |
| 173 |
candidate_end = j1 + (overlap_end - i1) |
| 174 |
elif tag == "replace": |
| 175 |
candidate_start = j1 |
| 176 |
candidate_end = j2 |
| 177 |
elif tag == "delete": |
| 178 |
candidate_start = j1 |
| 179 |
candidate_end = j1 |
| 180 |
else: |
| 181 |
continue |
| 182 |
|
| 183 |
if mapped_start is None: |
| 184 |
mapped_start = candidate_start |
| 185 |
mapped_end = candidate_end |
| 186 |
|
| 187 |
if mapped_start is None or mapped_end is None: |
| 188 |
for tag, i1, i2, j1, j2 in opcodes: |
| 189 |
if tag == "insert" and i1 == start: |
| 190 |
return j1, j2 |
| 191 |
return 0, 0 |
| 192 |
|
| 193 |
return mapped_start, mapped_end |
| 194 |
|
| 195 |
|
| 196 |
def highlight_matrix_values( |
| 197 |
configs: list[str], |
| 198 |
values: dict[str, str], |
| 199 |
enabled: bool, |
| 200 |
reference_name: str | None = None, |
| 201 |
) -> dict[str, str]: |
| 202 |
unique_values = list(dict.fromkeys(values.values())) |
| 203 |
if len(unique_values) <= 1: |
| 204 |
return values |
| 205 |
|
| 206 |
if reference_name is None: |
| 207 |
counts = Counter(values.values()) |
| 208 |
reference_text = max(unique_values, key=lambda value: (counts[value], -len(value))) |
| 209 |
reference_name = next( |
| 210 |
config for config in configs if values[config] == reference_text |
| 211 |
) |
| 212 |
else: |
| 213 |
reference_text = values[reference_name] |
| 214 |
|
| 215 |
config_opcodes: dict[str, list[tuple[str, int, int, int, int]]] = {} |
| 216 |
reference_spans: list[tuple[int, int]] = [] |
| 217 |
for config in configs: |
| 218 |
if config == reference_name: |
| 219 |
continue |
| 220 |
opcodes = difflib.SequenceMatcher(a=reference_text, b=values[config]).get_opcodes() |
| 221 |
config_opcodes[config] = opcodes |
| 222 |
for tag, i1, i2, j1, j2 in opcodes: |
| 223 |
if tag == "equal": |
| 224 |
continue |
| 225 |
if tag == "insert": |
| 226 |
reference_spans.append((i1, i1)) |
| 227 |
else: |
| 228 |
reference_spans.append((i1, i2)) |
| 229 |
|
| 230 |
merged_reference_spans: list[tuple[int, int]] = [] |
| 231 |
for start, end in sorted(reference_spans): |
| 232 |
if not merged_reference_spans or start > merged_reference_spans[-1][1]: |
| 233 |
merged_reference_spans.append((start, end)) |
| 234 |
else: |
| 235 |
merged_reference_spans[-1] = ( |
| 236 |
merged_reference_spans[-1][0], |
| 237 |
max(merged_reference_spans[-1][1], end), |
| 238 |
) |
| 239 |
|
| 240 |
spans: dict[str, list[tuple[int, int, str]]] = {config: [] for config in configs} |
| 241 |
for start, end in merged_reference_spans: |
| 242 |
reference_segment = reference_text[start:end] |
| 243 |
spans[reference_name].append((start, end, "major")) |
| 244 |
for config in configs: |
| 245 |
if config == reference_name: |
| 246 |
continue |
| 247 |
mapped_start, mapped_end = map_reference_span( |
| 248 |
config_opcodes[config], start, end |
| 249 |
) |
| 250 |
segment = values[config][mapped_start:mapped_end] |
| 251 |
role = "major" if segment == reference_segment else "minor" |
| 252 |
spans[config].append((mapped_start, mapped_end, role)) |
| 253 |
|
| 254 |
highlighted: dict[str, str] = {} |
| 255 |
for config in configs: |
| 256 |
highlighted[config] = highlight_spans(values[config], spans[config], enabled) |
| 257 |
return highlighted |
| 258 |
|
| 259 |
|
| 260 |
def highlight_pair(left: str, right: str, enabled: bool) -> tuple[str, str]: |
| 261 |
if not enabled or left == right: |
| 262 |
return left, right |
| 263 |
|
| 264 |
left_role = "major" |
| 265 |
right_role = "minor" |
| 266 |
left_parts: list[str] = [] |
| 267 |
right_parts: list[str] = [] |
| 268 |
matcher = difflib.SequenceMatcher(a=left, b=right) |
| 269 |
for tag, i1, i2, j1, j2 in matcher.get_opcodes(): |
| 270 |
left_chunk = left[i1:i2] |
| 271 |
right_chunk = right[j1:j2] |
| 272 |
if tag == "equal": |
| 273 |
left_parts.append(left_chunk) |
| 274 |
right_parts.append(right_chunk) |
| 275 |
continue |
| 276 |
left_parts.append(colorize(left_chunk, True, left_role)) |
| 277 |
right_parts.append(colorize(right_chunk, True, right_role)) |
| 278 |
return "".join(left_parts), "".join(right_parts) |
| 279 |
|
| 280 |
|
| 281 |
def print_summary(outputs: dict[str, list[str]]) -> None: |
| 282 |
configs = sorted(outputs) |
| 283 |
width = max(len(config) for config in configs) |
| 284 |
for left_name, right_name in combinations(configs, 2): |
| 285 |
differing = diff_lines(outputs[left_name], outputs[right_name]) |
| 286 |
first = differing[0] if differing else "-" |
| 287 |
print( |
| 288 |
f"{left_name:<{width}} vs {right_name:<{width}} " |
| 289 |
f"diff_lines={len(differing):<3} first={first}" |
| 290 |
) |
| 291 |
|
| 292 |
|
| 293 |
def print_matrix( |
| 294 |
outputs: dict[str, list[str]], |
| 295 |
only_diffs: bool, |
| 296 |
line_numbers: Iterable[int] | None, |
| 297 |
color: bool, |
| 298 |
reference_name: str | None, |
| 299 |
) -> None: |
| 300 |
configs = sorted(outputs) |
| 301 |
if reference_name is not None and reference_name not in outputs: |
| 302 |
raise SystemExit(f"Unknown config: {reference_name}") |
| 303 |
width = max(len(config) for config in configs) |
| 304 |
total_lines = max(len(lines) for lines in outputs.values()) |
| 305 |
selected = set(line_numbers or []) |
| 306 |
|
| 307 |
for line_number in range(1, total_lines + 1): |
| 308 |
values = { |
| 309 |
outputs[config][line_number - 1] if line_number - 1 < len(outputs[config]) else "" |
| 310 |
for config in configs |
| 311 |
} |
| 312 |
if selected and line_number not in selected: |
| 313 |
continue |
| 314 |
if only_diffs and len(values) <= 1: |
| 315 |
continue |
| 316 |
|
| 317 |
print(f"LINE {line_number}") |
| 318 |
rendered = highlight_matrix_values( |
| 319 |
configs, |
| 320 |
{ |
| 321 |
config: ( |
| 322 |
outputs[config][line_number - 1] |
| 323 |
if line_number - 1 < len(outputs[config]) |
| 324 |
else "" |
| 325 |
) |
| 326 |
for config in configs |
| 327 |
}, |
| 328 |
color, |
| 329 |
reference_name=reference_name, |
| 330 |
) |
| 331 |
for config in configs: |
| 332 |
print(f"{config:<{width}} {rendered[config]}") |
| 333 |
print() |
| 334 |
|
| 335 |
|
| 336 |
def print_pair( |
| 337 |
outputs: dict[str, list[str]], left_name: str, right_name: str, color: bool |
| 338 |
) -> None: |
| 339 |
if left_name not in outputs or right_name not in outputs: |
| 340 |
missing = [name for name in (left_name, right_name) if name not in outputs] |
| 341 |
raise SystemExit(f"Unknown config: {', '.join(missing)}") |
| 342 |
|
| 343 |
left = outputs[left_name] |
| 344 |
right = outputs[right_name] |
| 345 |
width = max(len(left_name), len(right_name)) |
| 346 |
|
| 347 |
for line_number in diff_lines(left, right): |
| 348 |
left_value = left[line_number - 1] if line_number - 1 < len(left) else "" |
| 349 |
right_value = right[line_number - 1] if line_number - 1 < len(right) else "" |
| 350 |
left_value, right_value = highlight_pair(left_value, right_value, color) |
| 351 |
print(f"LINE {line_number}") |
| 352 |
print(f"{left_name:<{width}} {left_value}") |
| 353 |
print(f"{right_name:<{width}} {right_value}") |
| 354 |
print() |
| 355 |
|
| 356 |
|
| 357 |
def parse_args() -> argparse.Namespace: |
| 358 |
parser = argparse.ArgumentParser( |
| 359 |
description="Inspect differences between OpenCC golden outputs." |
| 360 |
) |
| 361 |
parser.add_argument("--input", help="Input stem, for example us_constitution_zhs") |
| 362 |
parser.add_argument( |
| 363 |
"--color", |
| 364 |
choices=["auto", "always", "never"], |
| 365 |
default="auto", |
| 366 |
help="Whether to use ANSI colors in diff output", |
| 367 |
) |
| 368 |
|
| 369 |
subparsers = parser.add_subparsers(dest="command", required=True) |
| 370 |
|
| 371 |
subparsers.add_parser("summary", help="Show pairwise diff-line counts") |
| 372 |
|
| 373 |
matrix_parser = subparsers.add_parser( |
| 374 |
"matrix", help="Show all configs side by side for differing lines" |
| 375 |
) |
| 376 |
matrix_parser.add_argument( |
| 377 |
"--all-lines", |
| 378 |
action="store_true", |
| 379 |
help="Show every line instead of only differing lines", |
| 380 |
) |
| 381 |
matrix_parser.add_argument( |
| 382 |
"--line", |
| 383 |
dest="lines", |
| 384 |
action="append", |
| 385 |
type=int, |
| 386 |
help="Show a specific line number; repeatable", |
| 387 |
) |
| 388 |
matrix_parser.add_argument( |
| 389 |
"--against", |
| 390 |
dest="reference_name", |
| 391 |
help="Highlight each config against this reference config", |
| 392 |
) |
| 393 |
|
| 394 |
pair_parser = subparsers.add_parser( |
| 395 |
"pair", help="Show differing lines for two configs" |
| 396 |
) |
| 397 |
pair_parser.add_argument("left") |
| 398 |
pair_parser.add_argument("right") |
| 399 |
|
| 400 |
return parser.parse_args() |
| 401 |
|
| 402 |
|
| 403 |
def main() -> None: |
| 404 |
args = parse_args() |
| 405 |
color = use_color(args.color) |
| 406 |
all_outputs = load_outputs() |
| 407 |
input_name = choose_input(all_outputs, args.input) |
| 408 |
outputs = all_outputs[input_name] |
| 409 |
|
| 410 |
if args.command == "summary": |
| 411 |
print_summary(outputs) |
| 412 |
return |
| 413 |
|
| 414 |
if args.command == "matrix": |
| 415 |
print_matrix( |
| 416 |
outputs, |
| 417 |
only_diffs=not args.all_lines, |
| 418 |
line_numbers=args.lines, |
| 419 |
color=color, |
| 420 |
reference_name=args.reference_name, |
| 421 |
) |
| 422 |
return |
| 423 |
|
| 424 |
if args.command == "pair": |
| 425 |
print_pair(outputs, args.left, args.right, color) |
| 426 |
return |
| 427 |
|
| 428 |
raise SystemExit(f"Unknown command: {args.command}") |
| 429 |
|
| 430 |
|
| 431 |
if __name__ == "__main__": |
| 432 |
main() |