astromandarin's picture
OpenGlyph-OCR-IDS: first release
20fc05e verified
Raw History Blame Contribute Delete
2.4 kB
"""Strict parsing of an Ideographic Description Sequence (IDS), and the literal GlyphWiki name of an IDS glyph
(u2ff0-u961d-u4ee4 for ⿰阝令); such a name does not mean GlyphWiki has the glyph."""
from __future__ import annotations
import re
IDC = {chr(cp): f'u{cp:x}' for cp in range(0x2FF0, 0x3000)}
ARITY = {op: (3 if op in '⿲⿳' else 1 if op in '⿾⿿' else 2) for op in IDC}
def parse_tree(expression):
if not isinstance(expression, str) or not expression:
raise ValueError('IDS 不能为空。')
stack, root, i = [], None, 0
while i < len(expression):
ch = expression[i]
i += 1
if root is not None and not stack:
raise ValueError('IDS 有多余部件;请检查结构符和部件数。')
if ch in IDC:
node = {'op': ch, 'children': []}
elif ch == '{':
end = expression.find('}', i)
if end < 0 or end == i:
raise ValueError('IDS 部件引用需要完整的 {glyph_ref}。')
ref = expression[i:end]
if any(c.isspace() or c in '{}' for c in ref):
raise ValueError('无效 IDS 部件引用。')
node = {'glyph': ref}
i = end + 1
else:
cp = ord(ch)
if ch.isspace() or ch in '{}()[]#' or cp < 0x2000 or 0xD800 <= cp <= 0xDFFF or 0xE0100 <= cp <= 0xE01EF:
raise ValueError('IDS 含不支持的选择符;请用 glyph_lookup 返回的具体字形引用。')
node = {'glyph': ch}
if stack:
stack[-1]['children'].append(node)
else:
root = node
if 'op' in node:
stack.append(node)
while stack and len(stack[-1]['children']) == ARITY[stack[-1]['op']]:
stack.pop()
if stack or root is None:
raise ValueError('IDS 缺少部件;不会用空白或相近字补齐。')
return root
def to_glyph_name(ids):
try:
node = parse_tree(ids)
except ValueError:
return None
parts, pending = [], [node]
while pending:
item = pending.pop()
if 'glyph' in item:
if len(item['glyph']) != 1:
return None
parts.append(f'u{ord(item["glyph"]):x}')
else:
parts.append(IDC[item['op']])
pending.extend(reversed(item['children']))
return '-'.join(parts)