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