AnonymousGAOSA commited on
Commit
eac2ec4
·
verified ·
1 Parent(s): fcb2cfb

Upload 8 files

Browse files
.gitattributes CHANGED
@@ -58,3 +58,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ src/fonts/中华书局宋体00平面_20241226.TTF filter=lfs diff=lfs merge=lfs -text
62
+ src/fonts/中华书局宋体02平面_20241226.TTF filter=lfs diff=lfs merge=lfs -text
63
+ src/fonts/中华书局宋体15平面_20240514.TTF filter=lfs diff=lfs merge=lfs -text
64
+ src/fonts/中华书局字体16平面_20240906.TTF filter=lfs diff=lfs merge=lfs -text
src/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
src/README.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # single-char-renderer
2
+
3
+ 把汉字列表(txt,一行若干字)批量渲染成"一图一字"的评测图片集,专为 CJK 生僻字场景设计。源自古籍 OCR / tokenizer 评测集构建工作流。
4
+
5
+ ## 为什么需要它
6
+
7
+ 构建汉字识别评测集时有两个常见痛点:
8
+
9
+ 1. **生僻字缺字形**——简体常用字体对 CJK 扩展 B/C/D 区(4 字节 UTF-8 字符)覆盖率极低,直接渲染会得到一堆"豆腐块"。本工具支持传入多个字体文件(例如按 Unicode 平面拆分的字库),自动按 cmap 查询路由到第一个有该字形的字体。
10
+ 2. **静默失败**——有些字形即使存在也可能渲染成空白。本工具对每张图做墨水像素统计,低于阈值判为空白/tofu,自动换下一个字体重试,仍失败则记入失败清单,绝不悄悄产出坏图。
11
+
12
+ ## 安装
13
+
14
+ ```bash
15
+ pip install Pillow fonttools
16
+ ```
17
+
18
+ Python ≥ 3.9。
19
+
20
+ ## 用法
21
+
22
+ ```bash
23
+ # 多个 txt → 输出目录下同名子目录(每组一个文件夹)
24
+ # 本包自带 fonts/ 中华书局宋体四平面字库,可直接引用
25
+ python render_single_chars.py token2.txt token3.txt token4.txt ^
26
+ --out ./images ^
27
+ --font fonts/中华书局宋体00平面_20241226.TTF fonts/中华书局宋体02平面_20241226.TTF fonts/中华书局宋体15平面_20240514.TTF fonts/中华书局字体16平面_20240906.TTF
28
+
29
+ # 单个 txt → 平铺一个目录,用前缀区分
30
+ python render_single_chars.py chars.txt --out ./images --flat --prefix 2token ^
31
+ --font myfont.ttf
32
+ ```
33
+
34
+ ## 包内字体说明
35
+
36
+ `fonts/` 内含 **中华书局宋体字库** 四个平面(00/02/15/16),古籍用大字库,CJK 扩展区覆盖率远超系统字体。本工作流实测:34,013 个生僻字仅 00+02 两平面即全覆盖(15/16 备用)。
37
+
38
+ | 文件 | 大小 | cmap 字形数 |
39
+ |---|---|---|
40
+ | 中华书局宋体00平面_20241226.TTF | 22.8 MB | 39,848 |
41
+ | 中华书局宋体02平面_20241226.TTF | 41.1 MB | 61,862 |
42
+ | 中华书局宋体15平面_20240514.TTF | 25.2 MB | 备用平面 |
43
+ | 中华书局字体16平面_20240906.TTF | 8.6 MB | 备用平面 |
44
+
45
+ ⚠️ **版权**:中华书局宋体为商业字库,随包分发仅供内部评测使用,请勿公开再分发字体文件;对外开源时删除 `fonts/` 目录即可(脚本本身 MIT)。
46
+
47
+ ### 参数
48
+
49
+ | 参数 | 默认 | 说明 |
50
+ |------|------|------|
51
+ | `inputs` | (必填) | 输入 txt,每行若干字符,空白忽略,自动去重保序 |
52
+ | `--out` | `images` | 输出根目录 |
53
+ | `--font` | (必填) | 字体文件,可多个,按顺序优先使用 |
54
+ | `--size` | `128` | 画布边长(像素) |
55
+ | `--font-px` | `100` | 初始字号,超出画布自动缩小 |
56
+ | `--min-ink` | `40` | 空白判定阈值(暗像素数) |
57
+ | `--flat` | 关 | 不按输入文件建子目录 |
58
+ | `--prefix` | `char` | `--flat` 模式下的文件名前缀 |
59
+
60
+ ### 输出
61
+
62
+ - `images/<组名>/<prefix>_<序号:04d>_<字>.png` —— 128×128 灰度、白底黑字、单字居中
63
+ - `images/annotations.csv` —— 全部图片的标注(`group, filename, char, codepoint, font`),UTF-8 with BOM,Excel 直接打开不乱码
64
+
65
+ ## 渲染规格(默认值)
66
+
67
+ - 128×128 PNG,8-bit 灰度
68
+ - 背景 255(白)、前景 0(黑)
69
+ - 初始字号 100px,`anchor=mm` 几何居中
70
+ - 字形包围盒超出画布 → 字号 -6 逐级缩小(下限 20px)
71
+ - 墨水像素(灰度 < 200)不足 40 → 判为空白,换字体重试
72
+
73
+ ## 多平面字库建议
74
+
75
+ 按 Unicode 平面拆分的字库(如"00 平面 / 02 平面"系列)传入顺序即优先级:常用字优先用主平面字体,生僻字自动落到扩展平面。工具会在 annotations.csv 里记录每个字实际使用的字体,便于回溯。
76
+
77
+ ## License
78
+
79
+ MIT
src/fonts/中华书局字体16平面_20240906.TTF ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0b46425747a765898c18f2ae891c8a6bee8b612ab9a7439e75ffbd3d9b0264df
3
+ size 9007508
src/fonts/中华书局宋体00平面_20241226.TTF ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3366ef08a85f93c3eb75fff54c3d8be120fd90d2a9ad8e97d84c2261653674a6
3
+ size 23879740
src/fonts/中华书局宋体02平面_20241226.TTF ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb4acaa6277b5c614ca2e86052b57c5d9244fb407e0d2ec3458c4fe48c4fb8a4
3
+ size 43086088
src/fonts/中华书局宋体15平面_20240514.TTF ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8398a8f967ae2858779edfd2f30b1247590eafabd8aa666667bd1ecb768ba087
3
+ size 26387980
src/render_single_chars.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ render_single_chars.py — 把汉字列表渲染成"一图一字"的评测图片集。
5
+
6
+ 核心特性
7
+ 1. 多字体平面自动路由:按顺序在多个字体文件里查 cmap,找到第一个有该字形的字体;
8
+ 2. 自适应缩放:字形超出画布时自动缩小字号,保证完整居中(anchor=mm);
9
+ 3. 空白字形守护:渲染后统计墨水像素,空白/tofu 图自动换下一个字体重试;
10
+ 4. 标注输出:每批渲染生成 annotations.csv(文件名、字符、码点、所用字体)。
11
+
12
+ 典型用法
13
+ # 每个输入 txt 渲染到输出目录下的同名子目录
14
+ python render_single_chars.py token2.txt token3.txt token4.txt \
15
+ --out ./images --font fontA.ttf fontB.ttf
16
+
17
+ # 所有字渲染到同一目录(用文件名前缀区分)
18
+ python render_single_chars.py chars.txt --out ./images --flat \
19
+ --font fontA.ttf --prefix 2token
20
+
21
+ 依赖: pip install Pillow fonttools
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import csv
27
+ import sys
28
+ import time
29
+ from collections import Counter
30
+ from pathlib import Path
31
+
32
+ if hasattr(sys.stdout, "reconfigure"): # Windows 控制台默认 GBK
33
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
34
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
35
+
36
+ from fontTools.ttLib import TTFont
37
+ from PIL import Image, ImageDraw, ImageFont
38
+
39
+
40
+ # --------------------------------------------------------------------------- #
41
+ # 字体管理
42
+ # --------------------------------------------------------------------------- #
43
+ class FontRouter:
44
+ """在多个字体文件(多"平面"字库)之间按顺序路由单个字符。"""
45
+
46
+ def __init__(self, font_paths: list[str]):
47
+ if not font_paths:
48
+ raise ValueError("至少需要一个字体文件 (--font)")
49
+ self.paths = [Path(p) for p in font_paths]
50
+ for p in self.paths:
51
+ if not p.is_file():
52
+ raise FileNotFoundError(f"字体不存在: {p}")
53
+ self.cmaps = [TTFont(str(p), lazy=True).getBestCmap() or {} for p in self.paths]
54
+ self._cache: dict[tuple[int, int], ImageFont.FreeTypeFont] = {}
55
+
56
+ def font_index(self, ch: str) -> int | None:
57
+ """返回第一个覆盖该字符的字体下标。"""
58
+ cp = ord(ch)
59
+ for i, cm in enumerate(self.cmaps):
60
+ if cp in cm:
61
+ return i
62
+ return None
63
+
64
+ def _font(self, idx: int, px: int) -> ImageFont.FreeTypeFont:
65
+ key = (idx, px)
66
+ if key not in self._cache:
67
+ self._cache[key] = ImageFont.truetype(str(self.paths[idx]), px)
68
+ return self._cache[key]
69
+
70
+ def render(self, ch: str, canvas: int, font_px: int,
71
+ bg: int = 255, fg: int = 0, min_ink: int = 40):
72
+ """渲染单个字符;返回 (PIL.Image, 字体下标) 或 (None, None)。"""
73
+ order = [i for i in range(len(self.paths)) if ord(ch) in self.cmaps[i]]
74
+ for idx in order:
75
+ try:
76
+ px = font_px
77
+ probe = ImageDraw.Draw(Image.new("L", (8, 8)))
78
+ # 自适应缩放:超出画布就缩小字号
79
+ while px > 20:
80
+ font = self._font(idx, px)
81
+ b = probe.textbbox((canvas // 2, canvas // 2), ch,
82
+ font=font, anchor="mm")
83
+ if b[0] >= 0 and b[1] >= 0 and b[2] <= canvas and b[3] <= canvas:
84
+ break
85
+ px -= 6
86
+ img = Image.new("L", (canvas, canvas), bg)
87
+ ImageDraw.Draw(img).text((canvas // 2, canvas // 2), ch,
88
+ font=self._font(idx, px), fill=fg, anchor="mm")
89
+ ink = sum(img.histogram()[:200]) # 值<200 的像素数(空白/tofu 守护)
90
+ if ink >= min_ink:
91
+ return img, idx
92
+ except Exception as e: # 单字失败不中断整批
93
+ print(f"[warn] render {ch!r} with {self.paths[idx].name}: {e}",
94
+ file=sys.stderr)
95
+ return None, None
96
+
97
+
98
+ # --------------------------------------------------------------------------- #
99
+ # 主流程
100
+ # --------------------------------------------------------------------------- #
101
+ def read_chars(path: Path) -> list[str]:
102
+ """读入 txt:按行读取,去掉空白,剩余每个字符都是一个待渲染字。
103
+ utf-8-sig 兼容带 BOM 的文件(BOM 不会被当成一个字)。"""
104
+ chars: list[str] = []
105
+ for line in path.read_text(encoding="utf-8-sig").splitlines():
106
+ chars.extend(c for c in line if not c.isspace())
107
+ chars = [c for c in chars if c != "\ufeff"]
108
+ # 去重保序
109
+ seen: set[str] = set()
110
+ return [c for c in chars if not (c in seen or seen.add(c))]
111
+
112
+
113
+ def render_batch(chars: list[str], out_dir: Path, router: FontRouter,
114
+ prefix: str, canvas: int, font_px: int, min_ink: int) -> tuple[list[dict], list[str]]:
115
+ out_dir.mkdir(parents=True, exist_ok=True)
116
+ rows, failed = [], []
117
+ for i, ch in enumerate(chars, 1):
118
+ img, idx = router.render(ch, canvas, font_px, min_ink=min_ink)
119
+ if img is None:
120
+ failed.append(ch)
121
+ continue
122
+ fname = f"{prefix}_{i:04d}_{ch}.png"
123
+ img.save(out_dir / fname)
124
+ rows.append({
125
+ "filename": fname, "char": ch, "codepoint": f"U+{ord(ch):04X}",
126
+ "font": router.paths[idx].name if idx is not None else "",
127
+ })
128
+ return rows, failed
129
+
130
+
131
+ def main() -> int:
132
+ ap = argparse.ArgumentParser(
133
+ description="把汉字列表渲染成一图一字的评测图片集",
134
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter)
135
+ ap.add_argument("inputs", nargs="+", type=Path,
136
+ help="输入 txt 文件(每行若干字符,空白忽略,自动去重保序)")
137
+ ap.add_argument("--out", type=Path, default=Path("images"), help="输出根目录")
138
+ ap.add_argument("--font", nargs="+", required=True,
139
+ help="字体文件,可多个;按顺序优先使用(如多平面字库)")
140
+ ap.add_argument("--size", type=int, default=128, help="画布边长(像素)")
141
+ ap.add_argument("--font-px", type=int, default=100, help="初始字号(超出自动缩小)")
142
+ ap.add_argument("--min-ink", type=int, default=40, help="空白判定阈值(暗像素数)")
143
+ ap.add_argument("--flat", action="store_true",
144
+ help="不按输入文件建子目录,全部渲染到 --out(用 --prefix 区分)")
145
+ ap.add_argument("--prefix", default="char", help="--flat 模式下的文件名前缀")
146
+ args = ap.parse_args()
147
+
148
+ router = FontRouter(args.font)
149
+ all_rows: list[dict] = []
150
+ t0 = time.time()
151
+
152
+ for src in args.inputs:
153
+ if not src.is_file():
154
+ print(f"[error] 输入不存在: {src}", file=sys.stderr)
155
+ return 1
156
+ chars = read_chars(src)
157
+ prefix = args.prefix if args.flat else src.stem
158
+ out_dir = args.out if args.flat else args.out / src.stem
159
+
160
+ rows, failed = render_batch(chars, out_dir, router, prefix,
161
+ args.size, args.font_px, args.min_ink)
162
+ all_rows.extend({**r, "group": prefix} for r in rows)
163
+ cov = Counter(r["font"] for r in rows)
164
+ print(f"[{src.name}] chars={len(chars)} rendered={len(rows)} "
165
+ f"failed={len(failed)}{''.join(failed[:10])} fonts={dict(cov)}")
166
+
167
+ ann = args.out / "annotations.csv"
168
+ ann.parent.mkdir(parents=True, exist_ok=True)
169
+ with open(ann, "w", encoding="utf-8-sig", newline="") as f:
170
+ w = csv.DictWriter(f, fieldnames=["group", "filename", "char",
171
+ "codepoint", "font"])
172
+ w.writeheader()
173
+ w.writerows(all_rows)
174
+ print(f"total={len(all_rows)} annotations={ann} time={time.time()-t0:.1f}s")
175
+ return 0
176
+
177
+
178
+ if __name__ == "__main__":
179
+ sys.exit(main())
src/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Pillow>=10.0
2
+ fonttools>=4.40