Upload 3 files
Browse files- src/LICENSE +21 -0
- src/render_single_chars.py +215 -0
- src/requirements.txt +2 -0
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/render_single_chars.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""
|
| 4 |
+
render_single_chars.py — render a list of Chinese characters into a
|
| 5 |
+
"one image per character" evaluation image set.
|
| 6 |
+
|
| 7 |
+
Core features
|
| 8 |
+
1. Multi-font-plane routing: look up the cmap of each font in order and
|
| 9 |
+
use the first font that covers the character;
|
| 10 |
+
2. Adaptive scaling: shrink the font size when the glyph overflows the
|
| 11 |
+
canvas, keeping it centered (anchor=mm);
|
| 12 |
+
3. Blank-glyph guard: count ink pixels after rendering; blank/tofu images
|
| 13 |
+
automatically retry with the next font;
|
| 14 |
+
4. Annotation output: each batch writes annotations.csv (filename,
|
| 15 |
+
character, codepoint, font used).
|
| 16 |
+
|
| 17 |
+
Typical usage
|
| 18 |
+
# render each input txt into a same-named subdirectory under --out
|
| 19 |
+
python render_single_chars.py token2.txt token3.txt token4.txt \
|
| 20 |
+
--out ./images --font fontA.ttf fontB.ttf
|
| 21 |
+
|
| 22 |
+
# render everything into one directory (distinguished by --prefix)
|
| 23 |
+
python render_single_chars.py chars.txt --out ./images --flat \
|
| 24 |
+
--font fontA.ttf --prefix 2token
|
| 25 |
+
|
| 26 |
+
Dependencies: pip install Pillow fonttools
|
| 27 |
+
"""
|
| 28 |
+
from __future__ import annotations
|
| 29 |
+
|
| 30 |
+
import argparse
|
| 31 |
+
import csv
|
| 32 |
+
import sys
|
| 33 |
+
import time
|
| 34 |
+
from collections import Counter
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
|
| 37 |
+
if hasattr(sys.stdout, "reconfigure"): # Windows consoles default to GBK
|
| 38 |
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 39 |
+
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
| 40 |
+
|
| 41 |
+
from fontTools.ttLib import TTFont, TTLibFileIsCollectionError
|
| 42 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# --------------------------------------------------------------------------- #
|
| 46 |
+
# Font management
|
| 47 |
+
# --------------------------------------------------------------------------- #
|
| 48 |
+
class FontRouter:
|
| 49 |
+
"""Route a single character across multiple font files (multi-plane fonts).
|
| 50 |
+
.ttc collections are supported: every face in a collection is routed
|
| 51 |
+
separately, in file order."""
|
| 52 |
+
|
| 53 |
+
def __init__(self, font_paths: list[str]):
|
| 54 |
+
if not font_paths:
|
| 55 |
+
raise ValueError("at least one font file is required (--font)")
|
| 56 |
+
self.paths: list[Path] = [] # per-face path (may repeat for .ttc)
|
| 57 |
+
self.faces: list[int] = [] # face number within the file
|
| 58 |
+
self.labels: list[str] = [] # human-readable name for annotations.csv
|
| 59 |
+
for p in map(Path, font_paths):
|
| 60 |
+
if not p.is_file():
|
| 61 |
+
raise FileNotFoundError(f"font not found: {p}")
|
| 62 |
+
first = None
|
| 63 |
+
try:
|
| 64 |
+
first = TTFont(str(p), lazy=True)
|
| 65 |
+
faces = [first]
|
| 66 |
+
except TTLibFileIsCollectionError:
|
| 67 |
+
first = TTFont(str(p), lazy=True, fontNumber=0)
|
| 68 |
+
faces = [TTFont(str(p), lazy=True, fontNumber=i)
|
| 69 |
+
for i in range(first.reader.numFonts)]
|
| 70 |
+
for i, f in enumerate(faces):
|
| 71 |
+
self.paths.append(p)
|
| 72 |
+
self.faces.append(i)
|
| 73 |
+
self.labels.append(p.name if len(faces) == 1 else f"{p.name}#{i}")
|
| 74 |
+
if first is not None:
|
| 75 |
+
first.close()
|
| 76 |
+
self.cmaps = []
|
| 77 |
+
for p, face in zip(self.paths, self.faces):
|
| 78 |
+
try:
|
| 79 |
+
f = TTFont(str(p), lazy=True, fontNumber=face)
|
| 80 |
+
self.cmaps.append(f.getBestCmap() or {})
|
| 81 |
+
f.close()
|
| 82 |
+
except Exception as e:
|
| 83 |
+
print(f"[warn] cannot read cmap of {p.name}#{face}: {e}",
|
| 84 |
+
file=sys.stderr)
|
| 85 |
+
self.cmaps.append({})
|
| 86 |
+
self._cache: dict[tuple[int, int], ImageFont.FreeTypeFont] = {}
|
| 87 |
+
|
| 88 |
+
def font_index(self, ch: str) -> int | None:
|
| 89 |
+
"""Return the index of the first font covering the character."""
|
| 90 |
+
cp = ord(ch)
|
| 91 |
+
for i, cm in enumerate(self.cmaps):
|
| 92 |
+
if cp in cm:
|
| 93 |
+
return i
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
def _font(self, idx: int, px: int) -> ImageFont.FreeTypeFont:
|
| 97 |
+
key = (idx, px)
|
| 98 |
+
if key not in self._cache:
|
| 99 |
+
self._cache[key] = ImageFont.truetype(str(self.paths[idx]), px,
|
| 100 |
+
index=self.faces[idx])
|
| 101 |
+
return self._cache[key]
|
| 102 |
+
|
| 103 |
+
def render(self, ch: str, canvas: int, font_px: int,
|
| 104 |
+
bg: int = 255, fg: int = 0, min_ink: int = 40):
|
| 105 |
+
"""Render one character; return (PIL.Image, font index) or (None, None)."""
|
| 106 |
+
order = [i for i in range(len(self.paths)) if ord(ch) in self.cmaps[i]]
|
| 107 |
+
for idx in order:
|
| 108 |
+
try:
|
| 109 |
+
px = font_px
|
| 110 |
+
probe = ImageDraw.Draw(Image.new("L", (8, 8)))
|
| 111 |
+
# Adaptive scaling: shrink the font size when it overflows
|
| 112 |
+
while px > 20:
|
| 113 |
+
font = self._font(idx, px)
|
| 114 |
+
b = probe.textbbox((canvas // 2, canvas // 2), ch,
|
| 115 |
+
font=font, anchor="mm")
|
| 116 |
+
if b[0] >= 0 and b[1] >= 0 and b[2] <= canvas and b[3] <= canvas:
|
| 117 |
+
break
|
| 118 |
+
px -= 6
|
| 119 |
+
img = Image.new("L", (canvas, canvas), bg)
|
| 120 |
+
ImageDraw.Draw(img).text((canvas // 2, canvas // 2), ch,
|
| 121 |
+
font=self._font(idx, px), fill=fg, anchor="mm")
|
| 122 |
+
ink = sum(img.histogram()[:200]) # pixels < 200 (blank/tofu guard)
|
| 123 |
+
if ink >= min_ink:
|
| 124 |
+
return img, idx
|
| 125 |
+
except Exception as e: # one failed char must not abort the batch
|
| 126 |
+
print(f"[warn] render {ch!r} with {self.paths[idx].name}: {e}",
|
| 127 |
+
file=sys.stderr)
|
| 128 |
+
return None, None
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# --------------------------------------------------------------------------- #
|
| 132 |
+
# Main flow
|
| 133 |
+
# --------------------------------------------------------------------------- #
|
| 134 |
+
def read_chars(path: Path) -> list[str]:
|
| 135 |
+
"""Read a txt input: every non-whitespace character on every line is a
|
| 136 |
+
character to render. utf-8-sig tolerates a BOM (the BOM is not treated
|
| 137 |
+
as a character)."""
|
| 138 |
+
chars: list[str] = []
|
| 139 |
+
for line in path.read_text(encoding="utf-8-sig").splitlines():
|
| 140 |
+
chars.extend(c for c in line if not c.isspace())
|
| 141 |
+
chars = [c for c in chars if c != "\ufeff"]
|
| 142 |
+
# dedup, preserving order
|
| 143 |
+
seen: set[str] = set()
|
| 144 |
+
return [c for c in chars if not (c in seen or seen.add(c))]
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def render_batch(chars: list[str], out_dir: Path, router: FontRouter,
|
| 148 |
+
prefix: str, canvas: int, font_px: int, min_ink: int) -> tuple[list[dict], list[str]]:
|
| 149 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 150 |
+
rows, failed = [], []
|
| 151 |
+
for i, ch in enumerate(chars, 1):
|
| 152 |
+
img, idx = router.render(ch, canvas, font_px, min_ink=min_ink)
|
| 153 |
+
if img is None:
|
| 154 |
+
failed.append(ch)
|
| 155 |
+
continue
|
| 156 |
+
fname = f"{prefix}_{i:04d}_{ch}.png"
|
| 157 |
+
img.save(out_dir / fname)
|
| 158 |
+
rows.append({
|
| 159 |
+
"filename": fname, "char": ch, "codepoint": f"U+{ord(ch):04X}",
|
| 160 |
+
"font": router.labels[idx] if idx is not None else "",
|
| 161 |
+
})
|
| 162 |
+
return rows, failed
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def main() -> int:
|
| 166 |
+
ap = argparse.ArgumentParser(
|
| 167 |
+
description="Render a list of Chinese characters into a "
|
| 168 |
+
"one-image-per-character evaluation set",
|
| 169 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
| 170 |
+
ap.add_argument("inputs", nargs="+", type=Path,
|
| 171 |
+
help="input txt files (chars per line, whitespace ignored, "
|
| 172 |
+
"auto-dedup preserving order)")
|
| 173 |
+
ap.add_argument("--out", type=Path, default=Path("images"), help="output root")
|
| 174 |
+
ap.add_argument("--font", nargs="+", required=True,
|
| 175 |
+
help="font file(s), priority = order given (e.g., plane-split stacks)")
|
| 176 |
+
ap.add_argument("--size", type=int, default=128, help="canvas size (px)")
|
| 177 |
+
ap.add_argument("--font-px", type=int, default=100, help="initial font size (auto-shrinks)")
|
| 178 |
+
ap.add_argument("--min-ink", type=int, default=40, help="blank-detection threshold (dark pixels)")
|
| 179 |
+
ap.add_argument("--flat", action="store_true",
|
| 180 |
+
help="render into --out without per-input subdirectories")
|
| 181 |
+
ap.add_argument("--prefix", default="char", help="filename prefix in --flat mode")
|
| 182 |
+
args = ap.parse_args()
|
| 183 |
+
|
| 184 |
+
router = FontRouter(args.font)
|
| 185 |
+
all_rows: list[dict] = []
|
| 186 |
+
t0 = time.time()
|
| 187 |
+
|
| 188 |
+
for src in args.inputs:
|
| 189 |
+
if not src.is_file():
|
| 190 |
+
print(f"[error] input not found: {src}", file=sys.stderr)
|
| 191 |
+
return 1
|
| 192 |
+
chars = read_chars(src)
|
| 193 |
+
prefix = args.prefix if args.flat else src.stem
|
| 194 |
+
out_dir = args.out if args.flat else args.out / src.stem
|
| 195 |
+
|
| 196 |
+
rows, failed = render_batch(chars, out_dir, router, prefix,
|
| 197 |
+
args.size, args.font_px, args.min_ink)
|
| 198 |
+
all_rows.extend({**r, "group": prefix} for r in rows)
|
| 199 |
+
cov = Counter(r["font"] for r in rows)
|
| 200 |
+
print(f"[{src.name}] chars={len(chars)} rendered={len(rows)} "
|
| 201 |
+
f"failed={len(failed)}{''.join(failed[:10])} fonts={dict(cov)}")
|
| 202 |
+
|
| 203 |
+
ann = args.out / "annotations.csv"
|
| 204 |
+
ann.parent.mkdir(parents=True, exist_ok=True)
|
| 205 |
+
with open(ann, "w", encoding="utf-8-sig", newline="") as f:
|
| 206 |
+
w = csv.DictWriter(f, fieldnames=["group", "filename", "char",
|
| 207 |
+
"codepoint", "font"])
|
| 208 |
+
w.writeheader()
|
| 209 |
+
w.writerows(all_rows)
|
| 210 |
+
print(f"total={len(all_rows)} annotations={ann} time={time.time()-t0:.1f}s")
|
| 211 |
+
return 0
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
if __name__ == "__main__":
|
| 215 |
+
sys.exit(main())
|
src/requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Pillow>=10.0
|
| 2 |
+
fonttools>=4.40
|