Datasets:
Download geoalign/tools/build_confusion.py from WorldInsightLab/china-admin-divisions: direct link, hf CLI and curl.
- Browser
- Download file 3.46 kB
-
https://huggingface.co/datasets/WorldInsightLab/china-admin-divisions/resolve/main/geoalign/tools/build_confusion.py
- Command line
-
hf download hf://datasets/WorldInsightLab/china-admin-divisions/geoalign/tools/build_confusion.py
-
curl -L -o build_confusion.py https://huggingface.co/datasets/WorldInsightLab/china-admin-divisions/resolve/main/geoalign/tools/build_confusion.py
3.46 kB
| """错别字规则用的字表。写到 geoalign/data/confusion.json。 | |
| 用法:python tools/build_confusion.py <数据集 data 目录里的 years.csv> <字体文件 NotoSansCJK-Regular.ttc> | |
| 只在建表时用 Pillow、numpy、pypinyin;工具库运行时不用它们。 | |
| 两种“像”: | |
| 1. 同音:不计声调的拼音有相同的(多音字算所有读音)。字的范围:GBK 里的全部汉字 + 官方名称里的字。 | |
| 2. 形近:用 Noto Sans CJK SC 把字画成 56×56 的图,模糊 1.5 像素,算余弦相似度。 | |
| 每个官方名称里的字,取最像的 5 个字,相似度至少 0.80。 | |
| 参数(5 个、0.80、模糊 1.5)是先定的,没有按测试题调。 | |
| """ | |
| import csv, json, os, sys | |
| import numpy as np | |
| from PIL import Image, ImageDraw, ImageFont, ImageFilter | |
| from pypinyin import pinyin, Style | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| PKG = os.path.join(os.path.dirname(HERE), "geoalign") | |
| YEARS, FONT = sys.argv[1], sys.argv[2] | |
| TOPK, MINSIM, BLUR, SZ = 5, 0.80, 1.5, 56 | |
| name_chars = set() | |
| for r in csv.DictReader(open(YEARS, encoding="utf-8")): | |
| name_chars |= {ch for ch in r["name"] if "一" <= ch <= "鿿" or "㐀" <= ch <= "䶿"} | |
| pool = set(name_chars) | |
| for hi in range(0x81, 0xFF): | |
| for lo in range(0x40, 0xFF): | |
| try: | |
| ch = bytes([hi, lo]).decode("gbk") | |
| except UnicodeDecodeError: | |
| continue | |
| if "一" <= ch <= "鿿": | |
| pool.add(ch) | |
| pool = sorted(pool) | |
| print("name chars", len(name_chars), "pool", len(pool)) | |
| # 拼音 | |
| py = {} | |
| for ch in pool: | |
| ps = {p.rstrip("0123456789") for p in pinyin(ch, style=Style.NORMAL, heteronym=True)[0]} | |
| ps = {p for p in ps if p.isalpha() and p.isascii()} | |
| if ps: | |
| py[ch] = sorted(ps) | |
| py_main = {} | |
| for ch in pool: | |
| p = pinyin(ch, style=Style.NORMAL, heteronym=False)[0][0] | |
| if p.isalpha() and p.isascii(): | |
| py_main[ch] = p | |
| # 字形 | |
| # Noto Sans CJK 的 ttc 里第几个是简体中文 | |
| idx = next(i for i in range(10) if "SC" in ImageFont.truetype(FONT, 12, index=i).getname()[0]) | |
| F = ImageFont.truetype(FONT, 48, index=idx) | |
| def vec(ch): | |
| im = Image.new("L", (SZ, SZ), 0) | |
| ImageDraw.Draw(im).text((4, -6), ch, font=F, fill=255) | |
| im = im.filter(ImageFilter.GaussianBlur(BLUR)) | |
| return np.asarray(im, dtype=np.float32).ravel() | |
| tofu = vec("\U000F0000") # 字体里没有的字画出来的样子 | |
| V = np.stack([vec(ch) for ch in pool]) | |
| has = ~np.all(np.isclose(V, tofu[None, :]), axis=1) & (V.sum(1) > 0) | |
| V /= np.linalg.norm(V, axis=1, keepdims=True) + 1e-6 | |
| print("chars without glyph", int((~has).sum())) | |
| P = {ch: i for i, ch in enumerate(pool)} | |
| shape = {} | |
| nc = sorted(name_chars) | |
| for k in range(0, len(nc), 500): | |
| chunk = [c for c in nc[k:k + 500]] | |
| ids = [P[c] for c in chunk] | |
| S = V[ids] @ V.T | |
| S[:, ~has] = -1 | |
| for row, c in zip(S, chunk): | |
| if not has[P[c]]: | |
| continue | |
| row[P[c]] = -1 | |
| top = np.argsort(-row)[:TOPK] | |
| nb = [pool[j] for j in top if row[j] >= MINSIM] | |
| if nb: | |
| shape[c] = nb | |
| json.dump(dict(params=dict(topk=TOPK, minsim=MINSIM, blur=BLUR, size=SZ, font="Noto Sans CJK SC"), pinyin=py, pinyin_main=py_main, shape=shape), | |
| open(os.path.join(PKG, "data", "confusion.json"), "w", encoding="utf-8"), ensure_ascii=False) | |
| print("pinyin", len(py), "shape", len(shape)) | |
| for c in "埇浉硚瀍亳汨谯楞侯淞颍丘州德惠凤藏梁新芦": | |
| print(c, shape.get(c), py.get(c)) | |