feat: 找字体改为流式接口 + 内存对象评分,全库搜索内存降至 ~270MB

- /api/glyph-match 改为 NDJSON 流式:start/font/glyph/fontDone/done 事件,
  前端逐字体渲染预览与分数,消除整包等待
- 评分直接消费裁剪管线内存 ttf 对象(按字形 unicode 重建子集 cmap),
  免去序列化再解析;源界明朝/装甲明朝等 re-parse 失败字体首次可评分
- glyph_bitmap 对快路径字形(_origBuf 原始字节引用)按需调用 vendor
  parseGlyf 解码坐标,修复内存对象方案下「借」字镂空回归
- 所有裁剪调用点接入 withMemoryGate 内存闸门(cgroup 探测并发控制)
- HTTP 服务支持流式响应(LLRT 下经 _stream 附加属性传递),
  客户端断连 EPIPE/Controller closed 全链路容错,不再打死进程
- 单字体处理失败 try-catch 隔离,不中断整个搜索流
- app.ts 端口支持 PORT 环境变量覆盖,便于并行测试实例
This commit is contained in:
崮生(子虚) 2026-11-01 19:47:26 +08:00
parent e1579eb3cf
commit 5d6d71c447
13 changed files with 571 additions and 447 deletions

View File

@ -217,7 +217,7 @@ async function main() {
await ensureDirectories();
const server = new SimpleHttpServer({ port: 8087 });
const server = new SimpleHttpServer({ port: Number(process.env.PORT) || 8087 });
server.use(
logMiddleware,
corsMiddleware,

View File

@ -218,16 +218,27 @@ export const writeFont = (
return new Uint8Array(result);
};
/** subset 结果:内存 ttf 对象(含完整字形轮廓,OTF 路径为 null)+ 按需序列化函数 */
export interface SubsetResult {
/** optimize 后的子集 ttf 对象,可直接用于字形光栅化,免去序列化再解析 */
ttf: Record<string, unknown> | null;
/** 序列化为指定格式二进制(可多次调用输出不同格式) */
write: (outType: FontEditor.FontType) => Uint8Array;
}
/**
* 完整的字体裁剪流程(当前生产实现)
* 解析 -> subset -> 优化 -> 序列化
* 解析 -> subset -> 优化 -> GPOS/GSUB 重写
* 优化293: 移除 async,函数体内无 await,消除不必要的 Promise 包装和微任务调度
*
* 部分字体(如源界明朝)序列化后的 glyf 表无法被 fonteditor 严格再解析,
* 但内存对象与浏览器解析均正常;直接消费内存 ttf 对象可避免该闭环问题。
*/
export const fontSubset = (
export const fontSubsetToObject = (
fontBuffer: ArrayBuffer,
subString: string,
option: { sourceType: FontEditor.FontType; outType: FontEditor.FontType },
): Uint8Array => {
): SubsetResult => {
/** 自适应锚定注入:仅小子集(<32 个唯一码点)需要 blue zone 校准。大子集
* 自身字符已提供足够的 blue zone 统计样本(千字文段 SSIM 本就 1.0),注入
* 32 锚定字反而推高体积与浏览器加载耗时。阈值实测:<32 全部敏感用例达标,
@ -247,10 +258,9 @@ export const fontSubset = (
const fontU8 = new Uint8Array(fontBuffer);
const otfBytes = subsetOTF(fontU8, codePoints, true, option.outType);
if (otfBytes !== null) {
if (option.outType === "woff2") {
return encodeTTFToWOFF2(otfBytes);
}
return otfBytes;
const bytes = option.outType === "woff2" ? encodeTTFToWOFF2(otfBytes) : otfBytes;
/** OTF(CFF)路径直接透传字节,无 fonteditor 内存 ttf 对象 */
return { ttf: null, write: () => bytes };
}
/** subsetOTF 不支持(非 CID CFF 等)降级到原 fonteditor 路径 */
}
@ -329,5 +339,17 @@ export const fontSubset = (
const optimized = optimizeFont(font);
/** GPOS/GSUB 表子集化:按子集字形重映射布局表 glyphId,恢复标点压缩与连字/上下文替换 */
rewriteLayoutTablesForSubset(optimized, subsetGids);
return writeFont(optimized, option.outType);
return {
ttf: (optimized as unknown as { get: () => Record<string, unknown> }).get(),
write: (outType: FontEditor.FontType) => writeFont(optimized, outType),
};
};
/** 向后兼容包装:直接序列化为目标格式 */
export const fontSubset = (
fontBuffer: ArrayBuffer,
subString: string,
option: { sourceType: FontEditor.FontType; outType: FontEditor.FontType },
): Uint8Array => {
return fontSubsetToObject(fontBuffer, subString, option).write(option.outType);
};

View File

@ -1,53 +1,21 @@
/**
* 服务端字形位图光栅化 + IoU 比对 —— 截图找字体的服务端比对核心
* 服务端字形位图光栅化与相似度计算。
*
* 不依赖任何 canvas / DOM:直接取 fonteditor 解析出的 glyf 二次贝塞尔轮廓,
* 扁平化为多边形后扫描线填充(奇偶规则),再紧致归一化到 64x64 二值网格。
* 归一化算法与前端 segmenter 完全一致(留 12% 边距、等比缩放、居中、
* 像素中心采样),保证两侧特征空间相同,位图可直接 IoU 比对。
*
* 缓存两层:字体对象(解析一次)+ 字形位图(字体×字符),进程内常驻。
* 输入必须是现有裁剪管线生成的小字体,只处理当前请求需要的少量字形。
* 不保存完整字体对象或跨请求字形缓存,避免全库识别耗尽服务进程内存。
*/
import { Font } from "../../vendor/fonteditor-core/lib/ttf/font";
import transformGlyfContours from "../../vendor/fonteditor-core/lib/ttf/util/transformGlyfContours";
import { parseGlyf } from "../../vendor/fonteditor-core/lib/ttf/table/glyf/parse";
/** 归一化网格边长(与前端 segmenter.GRID 一致) */
const GRID = 64;
/** 归一化留边比例(与前端一致:12%) */
const MARGIN_RATIO = 0.12;
/** 字体对象缓存:字体名 → 解析后的 ttfObject(含 glyf/cmap) */
const fontObjectCache = new Map<string, ReturnType<ReturnType<typeof Font.create>["get"]>>();
/** 字形位图缓存:字体名 → 码点 → 64x64 位图(01 串);值为 null 表示该字体缺此字 */
const glyphBitmapCache = new Map<string, Map<number, Uint8Array | null>>();
/**
* 按魔数探测字体类型(woff2 'wOF2' / woff 'wOFF' / otf 'OTTO' / 其余按 ttf)
*/
function detectType(buf: ArrayBuffer): "ttf" | "otf" | "woff" | "woff2" {
const b = new Uint8Array(buf, 0, 4);
if (b[0] === 0x77 && b[1] === 0x4f && b[2] === 0x46 && b[3] === 0x32) return "woff2";
if (b[0] === 0x77 && b[1] === 0x4f) return "woff";
if (b[0] === 0x4f && b[1] === 0x54 && b[2] === 0x54 && b[3] === 0x4f) return "otf";
return "ttf";
}
/**
* 解析字体(带进程内缓存)
* 传入读取字体文件的函数,避免本模块直接依赖 shared/interface 的 IO 层
*/
export function loadFontObject(
fontName: string,
readBuffer: (name: string) => Promise<ArrayBuffer | null>,
): Promise<ReturnType<ReturnType<typeof Font.create>["get"]> | null> {
const hit = fontObjectCache.get(fontName);
if (hit) return Promise.resolve(hit);
return readBuffer(fontName).then((buf) => {
if (!buf) return null;
const ttf = Font.create(buf, { type: detectType(buf) }).get();
fontObjectCache.set(fontName, ttf);
return ttf;
});
/** 当前裁剪字体对象;只保留调用方这一次比对所需的生命周期 */
export interface SubsetTtfObject {
cmap?: Record<number, number>;
glyf?: any[];
}
/** 二维点(已扁平化的多边形顶点,y 已翻转) */
@ -70,6 +38,32 @@ function readGlyphContours(ttf: any, glyf: any): RawContour[] {
if (glyf.compound) return transformGlyfContours(glyf, ttf);
if (Array.isArray(glyf.contours) && Array.isArray(glyf.contours[0])) return glyf.contours;
/**
* 裁剪快路径字形(优化310)只携带原始字节引用(_origBuf),坐标未解码。
* 此处按需调用 vendor 的 parseGlyf 解出 _xArr/_flags 并写回字形对象,
* 后续读取(同字体多字比对)即可直接命中紧凑坐标分支。
* 快路径保证 compound 及其 component 走完整 parse,故此处必为 simple 字形。
*/
if (glyf._xArr == null && glyf._origBuf != null && glyf._origOff != null) {
/** _origBuf 为完整原始 ArrayBuffer(快路径直接引用 view.buffer),_origOff 是相对该 buffer 的绝对偏移 */
const origBuf = glyf._origBuf as ArrayBuffer | Uint8Array;
const buffer = origBuf instanceof ArrayBuffer ? origBuf : origBuf.buffer;
const view = new DataView(buffer);
const baseOff = origBuf instanceof ArrayBuffer ? 0 : origBuf.byteOffset;
const reader = {
offset: glyf._origOff - baseOff,
view,
seek(offset: number) {
this.offset = offset;
},
};
const parsed = parseGlyf(reader as never, { readOptions: { hinting: false } }, glyf._origOff - baseOff) as any;
glyf._xArr = parsed._xArr;
glyf._yArr = parsed._yArr;
glyf._flags = parsed._flags;
glyf.endPtsOfContours = parsed.endPtsOfContours;
}
const xArr = glyf._xArr;
const yArr = glyf._yArr;
const flags = glyf._flags;
@ -242,47 +236,27 @@ function normalizePolys(polys: Pt[][]): Pt[][] {
}
/**
* 取字体的指定码点字形归一化位图(带缓存;缺字返回 null)
* 判断裁剪字体是否确实包含目标字符,避免把缺字注入的 .notdef 当作有效笔画参与评分。
*/
export function hasGlyph(ttf: SubsetTtfObject, codePoint: number): boolean {
return ttf.cmap?.[codePoint] !== undefined;
}
/** 取当前裁剪字体的指定码点归一化位图;缺字返回 null */
export function getGlyphBitmap(
ttf: ReturnType<ReturnType<typeof Font.create>["get"]>,
fontName: string,
ttf: SubsetTtfObject,
codePoint: number,
): Uint8Array | null {
let byFont = glyphBitmapCache.get(fontName);
if (!byFont) {
byFont = new Map();
glyphBitmapCache.set(fontName, byFont);
}
if (byFont.has(codePoint)) return byFont.get(codePoint)!;
let bitmap: Uint8Array | null = null;
try {
/** cmap 的 key 是码点的十进制值;无 cmap 时按 glyf.unicode 兜底扫描 */
let gid = ttf.cmap?.[codePoint as unknown as number] as number | undefined;
if (gid === undefined && ttf.glyf) {
for (let i = 0; i < ttf.glyf.length; i++) {
const u = ttf.glyf[i]!.unicode;
if (u === codePoint || (Array.isArray(u) && u.includes(codePoint))) {
gid = i;
break;
}
}
}
const glyf = typeof gid === "number" ? ttf.glyf?.[gid] : undefined;
const contours = readGlyphContours(ttf, glyf);
if (contours.length > 0) {
const polys = contours.map(flattenContour).filter((p) => p.length >= 3);
const normalized = normalizePolys(polys);
bitmap = normalized.length > 0 ? scanlineFill(normalized) : null;
/** 全空位图视为缺字 */
if (bitmap && !bitmap.some((v) => v)) bitmap = null;
}
} catch {
bitmap = null;
}
byFont.set(codePoint, bitmap);
return bitmap;
if (!hasGlyph(ttf, codePoint)) return null;
const gid = ttf.cmap![codePoint]!;
const glyf = ttf.glyf?.[gid];
const contours = readGlyphContours(ttf, glyf);
if (contours.length === 0) return null;
const polys = contours.map(flattenContour).filter((p) => p.length >= 3);
const normalized = normalizePolys(polys);
const bitmap = normalized.length > 0 ? scanlineFill(normalized) : null;
/** 全空位图视为缺字 */
return bitmap?.some((v) => v) ? bitmap : null;
}
/**

View File

@ -0,0 +1,37 @@
import type { FontEditor } from "../../vendor/fonteditor-core/lib/ttf/font";
import { fontSubsetToObject, type SubsetResult } from "./font";
import { stat } from "../interface";
import { readFontBuffer } from "../shared";
/**
* 根据源字体大小预留裁剪任务内存。
* 轮廓解析、布局表重写和序列化会同时持有源文件及多份临时结构,不能只按源文件大小限流。
*/
export async function estimateSubsetMemory(fontPath: string): Promise<number> {
const { size } = await stat(fontPath);
return Math.max(64 * 1024 * 1024, size * 4);
}
/**
* 字体裁剪的唯一文件入口。
* HTTP 裁剪接口和截图找字体都调用这里,不额外缓存完整字体对象。
* 返回的 ttf 为内存子集对象(可直接光栅化评分,免去序列化再解析);
* OTF(CFF)输入时 ttf 为 null。
*/
export async function subsetFontFile(
fontPath: string,
text: string,
outType: FontEditor.FontType,
): Promise<SubsetResult & { bytes: Uint8Array; readMs: number; subsetMs: number }> {
const sourceType = fontPath.split(".").pop() as FontEditor.FontType;
const readStarted = Date.now();
const fontBuffer = await readFontBuffer(fontPath);
const subsetStarted = Date.now();
const result = fontSubsetToObject(fontBuffer, text, { sourceType, outType });
return {
...result,
bytes: result.write(outType),
readMs: subsetStarted - readStarted,
subsetMs: Date.now() - subsetStarted,
};
}

View File

@ -2,6 +2,7 @@ import { extractFontMeta, META_VERSION, type FontUserConfig } from "../font_util
import { parseUrl, jsonResponse, findFontPath, readFontBuffer } from "../shared";
import { readFile, writeFile, stat } from "../interface";
import { withMemoryGate } from "../subset_queue";
import { estimateSubsetMemory } from "../font_util/subset_file";
import { subsetQueueTimeoutSeconds } from "../config";
/**
@ -113,13 +114,14 @@ export async function handleFontMeta(req: Request, _res: Response) {
/** 3. 首次请求 —— 解析 cmap + name 表计算元数据(CPU/内存密集,复用子集化并发闸门) */
if (!meta) {
/** 排队超时,返回 503 让客户端重试 */
const memoryBytes = await estimateSubsetMemory(fontPath);
const result = await withMemoryGate(
async () => {
const fontBuffer = await readFontBuffer(fontPath);
return extractFontMeta(fontBuffer);
},
subsetQueueTimeoutSeconds * 1000,
fontPath,
memoryBytes,
);
if (result === null) {

View File

@ -1,41 +1,35 @@
/**
* POST /api/glyph-match —— 截图找字体:一次请求对全库字体做字形相似度比对
* POST /api/glyph-match —— 逐字体裁剪、逐字评分,并以 NDJSON 流式返回。
*
* 请求体:{ glyphs: [{ char: string, bitmap: string }] }
* bitmap 为 4096 字符的 01 串(64x64 归一化二值位图,前端 segmenter 产线)
* 响应:{ results: [{ font, score, missing, glyphs: [{ char, score, bitmap, queryIndex }] }] }
* 按平均分降序;bitmap 为该字体渲染的归一化位图(01 串,前端画预览小图)
* queryIndex 对应该字在请求 glyphs 中的位置,候选字体缺字时仍能保持预览对应关系
*
* 性能:字形位图按 字体×字符 进程内缓存(首次请求某字时惰性光栅化),
* 之后每次比对只计算归一化位图相似度。
* 每个候选字体只经过一次现有裁剪管线;同一份 woff2 同时供前端预览。
* 不缓存完整字体对象,也不为了生成预览再发起第二轮全库裁剪。
*/
import { jsonResponse, findFontPath, readFontBuffer } from "../shared";
import { Font } from "../../vendor/fonteditor-core/lib/ttf/font";
import { jsonResponse, findFontPath } from "../shared";
import { readdir } from "../interface";
import { fontDirs } from "../config";
import { loadFontObject, getGlyphBitmap, glyphSimilarity } from "../font_util/glyph_bitmap";
import { fontDirs, subsetQueueTimeoutSeconds } from "../config";
import { getGlyphBitmap, glyphSimilarity, hasGlyph, type SubsetTtfObject } from "../font_util/glyph_bitmap";
import { estimateSubsetMemory, subsetFontFile } from "../font_util/subset_file";
import { withMemoryGate } from "../subset_queue";
/** 单个查询字形 */
interface QueryGlyph {
char: string;
bitmap: string;
}
/** 响应中的单字形结果 */
interface GlyphResult {
interface ParsedQueryGlyph {
char: string;
score: number;
bitmap: string;
bitmap: Uint8Array;
queryIndex: number;
}
/** 响应中的单字体结果 */
interface FontResult {
font: string;
score: number;
missing: boolean;
glyphs: GlyphResult[];
}
/** 流式响应事件 */
type GlyphMatchEvent =
| { type: "start"; total: number }
| { type: "font"; font: string; subset: string }
| { type: "glyph"; font: string; glyph: { char: string; score: number; queryIndex: number } | null; missing: boolean }
| { type: "fontDone"; font: string }
| { type: "done" };
/** 01 串 → Uint8Array;非法输入返回 null */
function parseBitmap(s: unknown): Uint8Array | null {
@ -49,13 +43,6 @@ function parseBitmap(s: unknown): Uint8Array | null {
return out;
}
/** Uint8Array 位图 → 01 串 */
function encodeBitmap(b: Uint8Array): string {
let s = "";
for (let i = 0; i < b.length; i++) s += b[i] ? "1" : "0";
return s;
}
/** 遍历字体目录收集候选字体文件名(含临时上传) */
async function listCandidateFonts(): Promise<string[]> {
const names: string[] = [];
@ -72,6 +59,99 @@ async function listCandidateFonts(): Promise<string[]> {
return names;
}
/** 小字体转 base64,随流交给浏览器渲染,无需再次请求裁剪接口 */
function bytesToBase64(bytes: Uint8Array): string {
let binary = "";
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
}
return btoa(binary);
}
/** 解析裁剪产物;OTF(CFF)等无内存 ttf 对象的路径不参与字形评分 */
function readSubsetObject(bytes: Uint8Array): SubsetTtfObject {
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
return Font.create(buffer, { type: "ttf", hinting: false }).get();
}
/**
* 裁剪管线的内存 ttf 对象中 glyf 已是子集但 cmap 仍是原始 gid 映射,
* 按字形自带的 unicode 标注重建 codepoint→新 gid 映射。
* 返回浅拷贝视图(glyf 共享引用),不修改原对象以免影响序列化。
*/
function buildSubsetCmapView(ttf: Record<string, unknown>): SubsetTtfObject {
const glyf = ttf.glyf as Array<{ unicode?: number | number[] }>;
const cmap: Record<number, number> = {};
for (const [index, glyph] of glyf.entries()) {
if (!glyph.unicode) continue;
for (const cp of Array.isArray(glyph.unicode) ? glyph.unicode : [glyph.unicode]) {
if (!(cp in cmap)) cmap[cp] = index;
}
}
return { ...ttf, cmap } as unknown as SubsetTtfObject;
}
/** 依次产出事件;每次只保留下一个候选字体的数据,浏览器背压会自然暂停后续裁剪 */
async function* streamMatches(
fonts: string[],
queryGlyphs: ParsedQueryGlyph[],
): AsyncGenerator<GlyphMatchEvent> {
yield { type: "start", total: fonts.length };
const text = queryGlyphs.map((glyph) => glyph.char).join("");
for (const font of fonts) {
try {
const fontPath = await findFontPath(font);
if (!fontPath) {
yield { type: "fontDone", font };
continue;
}
const memoryBytes = await estimateSubsetMemory(fontPath);
const subset = await withMemoryGate(
() => subsetFontFile(fontPath, text, "ttf"),
subsetQueueTimeoutSeconds * 1000,
memoryBytes,
);
if (!subset) throw new Error(`字体裁剪排队超时:${font}`);
/** 优先用裁剪管线返回的内存 ttf 对象(重建子集 cmap),免去序列化再解析(部分字体 re-parse 会失败) */
const ttf = subset.ttf ? buildSubsetCmapView(subset.ttf) : readSubsetObject(subset.bytes);
let started = false;
let hasMatch = false;
for (const query of queryGlyphs) {
const codePoint = query.char.codePointAt(0)!;
if (!hasGlyph(ttf, codePoint)) {
if (started) yield { type: "glyph", font, glyph: null, missing: true };
continue;
}
if (!started) {
started = true;
yield { type: "font", font, subset: bytesToBase64(subset.bytes) };
}
const candidate = getGlyphBitmap(ttf, codePoint);
if (!candidate) {
yield { type: "glyph", font, glyph: null, missing: true };
continue;
}
hasMatch = true;
yield {
type: "glyph",
font,
glyph: { char: query.char, score: glyphSimilarity(query.bitmap, candidate), queryIndex: query.queryIndex },
missing: false,
};
}
/** 全部缺字的候选不展示,但仍计入完成进度 */
if (started && !hasMatch) yield { type: "glyph", font, glyph: null, missing: true };
} catch (err) {
/** 单个字体裁剪/解析失败不拖垮整个搜索流,记录后继续下一个 */
console.error(`[glyph-match] ${font} 处理失败:`, err instanceof Error ? err.message : err);
}
yield { type: "fontDone", font };
}
yield { type: "done" };
}
export async function handleGlyphMatch(req: Request, _res: Response) {
let body: { glyphs?: QueryGlyph[] };
try {
@ -85,55 +165,43 @@ export async function handleGlyphMatch(req: Request, _res: Response) {
return { req, res: jsonResponse({ error: "invalid json" }, 400) };
}
const queryGlyphs = (body.glyphs ?? [])
.map((g, queryIndex) => ({
char: typeof g?.char === "string" ? g.char : "",
bitmap: parseBitmap(g?.bitmap),
.map((glyph, queryIndex) => ({
char: typeof glyph?.char === "string" ? glyph.char : "",
bitmap: parseBitmap(glyph?.bitmap),
queryIndex,
}))
.filter((g): g is { char: string; bitmap: Uint8Array; queryIndex: number } =>
g.char.length > 0 && g.bitmap !== null,
);
.filter((glyph): glyph is ParsedQueryGlyph => glyph.char.length > 0 && glyph.bitmap !== null);
if (queryGlyphs.length === 0) {
return { req, res: jsonResponse({ error: "glyphs required (char + 64x64 bitmap)" }, 400) };
}
const fonts = await listCandidateFonts();
const results: FontResult[] = [];
for (const font of fonts) {
const fontPath = await findFontPath(font);
if (!fontPath) continue;
const ttf = await loadFontObject(font, async (name) => {
const p = await findFontPath(name);
if (!p) return null;
return readFontBuffer(p);
});
if (!ttf) continue;
const glyphResults: GlyphResult[] = [];
let missing = false;
let scoreSum = 0;
for (const q of queryGlyphs) {
const cp = q.char.codePointAt(0)!;
const candidate = getGlyphBitmap(ttf, font, cp);
if (!candidate) {
missing = true;
continue;
const encoder = new TextEncoder();
const events = streamMatches(fonts, queryGlyphs);
const stream = new ReadableStream<Uint8Array>({
async pull(controller) {
const { done, value } = await events.next();
if (done) {
controller.close();
return;
}
const score = glyphSimilarity(q.bitmap, candidate);
scoreSum += score;
glyphResults.push({ char: q.char, score, bitmap: encodeBitmap(candidate), queryIndex: q.queryIndex });
}
if (glyphResults.length === 0) continue;
results.push({
font,
score: scoreSum / glyphResults.length,
missing,
glyphs: glyphResults,
});
}
results.sort((a, b) => b.score - a.score);
return { req, res: jsonResponse({ results }) };
controller.enqueue(encoder.encode(`${JSON.stringify(value)}\n`));
},
async cancel() {
await events.return(undefined);
},
});
/** LLRT 的 Response 不支持 ReadableStream body(body 会变 undefined),流挂在附加属性上由 HTTP 层写出 */
const res = new Response(null, {
status: 200,
headers: {
"Content-Type": "application/x-ndjson; charset=utf-8",
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
"Connection": "close",
},
});
(res as Response & { _stream?: ReadableStream<Uint8Array> })._stream = stream;
return { req, res };
}

View File

@ -1,8 +1,7 @@
import { fontSubset } from "../font_util/font";
import type { FontEditor } from "../../vendor/fonteditor-core/lib/ttf/font";
import { parseUrl, stats, subsetCache, findFontPath, readFontBuffer, markStatsDirty } from "../shared";
import { parseUrl, stats, subsetCache, findFontPath, markStatsDirty } from "../shared";
import { markFontUsed } from "../temp_cleaner";
import { withMemoryGate } from "../subset_queue";
import { estimateSubsetMemory, subsetFontFile } from "../font_util/subset_file";
import { subsetQueueTimeoutSeconds } from "../config";
/**
@ -94,34 +93,13 @@ export async function handleFontSubset(req: Request, res: Response) {
};
}
const fontType = fontPath.split(".").pop() as FontEditor.FontType;
let oldFontBuffer: ArrayBuffer;
try {
oldFontBuffer = await readFontBuffer(fontPath);
} catch {
return {
req,
res: new Response(`Font read error: ${font}`, {
status: 500,
headers: { "Content-Type": "text/plain; charset=utf-8" },
}),
};
}
/** readFontBuffer 结束时间戳(磁盘 IO / buffer 缓存命中) */
const t2 = Date.now();
/**
* 实际子集化(CPU/内存密集)—— 通过内存水位闸门控制
*
* 缓存未命中的请求才进入闸门;RSS 超 softLimit 时排队等待,
* 前面请求完成 + GC 释放内存后 RSS 回落才执行。避免 OOM 崩溃。
*/
const subsetResult = await withMemoryGate(async () => {
return fontSubset(oldFontBuffer, text, {
outType: outType,
sourceType: fontType,
});
}, subsetQueueTimeoutSeconds * 1000, fontPath);
const memoryBytes = await estimateSubsetMemory(fontPath);
/** 完整字体读取和裁剪都位于共享内存闸门内;缓存命中不占用重任务槽位 */
const subsetResult = await withMemoryGate(
() => subsetFontFile(fontPath, text, outType),
subsetQueueTimeoutSeconds * 1000,
memoryBytes,
);
/** 排队超时,返回 503 让客户端重试 */
if (subsetResult === null) {
@ -137,8 +115,7 @@ export async function handleFontSubset(req: Request, res: Response) {
};
}
const newFont = subsetResult;
/** fontSubset 结束时间戳(实际裁剪,亚毫秒级应在此体现) */
const newFont = subsetResult.bytes;
const t3 = Date.now();
/** 写入裁剪结果缓存 */
@ -156,8 +133,8 @@ export async function handleFontSubset(req: Request, res: Response) {
"X-Cache": "MISS",
/** 分阶段耗时(毫秒),供排查服务端处理时间分布 */
"X-Timing-Find": `${t1 - t0}`,
"X-Timing-Read": `${t2 - t1}`,
"X-Timing-Subset": `${t3 - t2}`,
"X-Timing-Read": `${subsetResult.readMs}`,
"X-Timing-Subset": `${subsetResult.subsetMs}`,
"X-Timing-Total": `${t3 - t0}`,
},
}),

View File

@ -183,16 +183,16 @@ async function connectionHandle(
});
const resHeaertText = `HTTP/1.1 ${res.status} OK\r\n${headerText.join("\r\n")}\r\n\r\n`;
await resWriter.write(encoder.encode(resHeaertText));
if (res.body) {
/** node 运行时 */
/** LLRT 的 Response 不支持流 body,流式路由通过附加属性传递 */
const stream = (res as Response & { _stream?: ReadableStream<Uint8Array> })._stream ?? res.body;
if (stream) {
/** 流式响应:pipeTo 自行管理 writer 生命周期,结束后负责关闭流 */
resWriter.releaseLock();
await res.body?.pipeTo(connection.writable);
await stream.pipeTo(connection.writable, { preventClose: false });
} else {
/** llrt 运行时 */
const buffer = new Uint8Array(await (await res.blob()).arrayBuffer());
await resWriter.write(buffer);
}
if (!resWriter.closed) {
await resWriter.close();
}
connection.close();
@ -285,8 +285,12 @@ function createStreamAfterTarget(
controller.enqueue(value);
}
} catch (err) {
/** body stream 被消费方 cancel 时预期会抛错 */
console.log("[createStreamAfterTarget] body stream closed:", err);
/** body stream 被消费方 cancel(客户端断连)时预期会抛错,controller 可能已关闭 */
try {
controller.error(err instanceof Error ? err : new Error(String(err)));
} catch {
/** controller 已结束,忽略 */
}
}
})();
},

View File

@ -15,10 +15,20 @@ export function createTcpServer(
controller.enqueue(new Uint8Array(chunk));
});
socket.on("error", (err) => {
controller.error(err);
/** error 后 close 事件仍会触发,这里只终止读取侧 */
try {
controller.error(err);
} catch {
/** controller 已结束(如 cancel 先到),忽略 */
}
});
socket.on("close", () => {
controller.close();
/** 客户端断连时 controller 可能已被 error/cancel 关闭,重复 close 会抛未捕获异常打死进程 */
try {
controller.close();
} catch {
/** 已关闭,忽略 */
}
});
},
cancel() {
@ -32,8 +42,17 @@ export function createTcpServer(
return new Promise<void>((resolve, reject) => {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
socket.write(buffer, (err) => {
if (err) reject(err);
else resolve();
if (err) {
/** EPIPE:客户端已断开,销毁连接而非让异常向上冒泡打死进程 */
if ((err as NodeJS.ErrnoException).code === "EPIPE") {
socket.destroy();
resolve();
} else {
reject(err);
}
} else {
resolve();
}
});
});
},

View File

@ -1,135 +1,121 @@
/**
* 字体子集化并发队列(带字体分组调度)
*
* LLRT 运行时内存受限(~900M),字体裁剪是内存密集操作。
* 通过固定并发数限制同时执行的子集化任务,防止 OOM 崩溃。
*
* 分组优化:排队中的请求按字体(groupKey)分组,同字体的请求优先连续处理,
* 使字体 buffer / 解析对象在缓存窗口内被下一个请求复用,降低内存峰值。
*/
import { freemem, totalmem } from "os";
import { readFile } from "./interface";
/** 等待队列项:resolver + groupKey(用于同字体分组连续唤醒) */
interface QueueItem {
resolve: () => void;
/** 分组键(通常为 fontPath),同组优先连续处理以复用字体缓存 */
groupKey: string;
/** 内存快照:同时考虑宿主机空闲内存和容器 cgroup 剩余额度 */
interface MemorySnapshot {
limit: number;
free: number;
reserve: number;
}
/** 等待队列:release 按分组优先级唤醒 */
const waitQueue: QueueItem[] = [];
/** 当前正在执行的子集化数量 */
const MIB = 1024 * 1024;
const decoder = new TextDecoder();
let activeCount = 0;
/** 最大并发数(由 initConcurrency 设置) */
let waitingCount = 0;
let reservedBytes = 0;
let maxConcurrency = 4;
/** 最近一次执行的 groupKey——同组请求优先连续唤醒 */
let lastGroupKey = "";
/** 读取一个内核数值文件;memory.max 在未限制时为 max,会返回 NaN 并被忽略 */
async function readMemoryNumber(path: string): Promise<number> {
return Number(decoder.decode(await readFile(path)).trim());
}
/** 优先读取 cgroup v2,再兼容 v1;非容器环境没有这些文件 */
async function readCgroupMemory(): Promise<{ limit: number; used: number } | null> {
const candidates = [
["/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory.current"],
["/sys/fs/cgroup/memory/memory.limit_in_bytes", "/sys/fs/cgroup/memory/memory.usage_in_bytes"],
] as const;
for (const [limitPath, usedPath] of candidates) {
try {
const [limit, used] = await Promise.all([readMemoryNumber(limitPath), readMemoryNumber(usedPath)]);
if (Number.isFinite(limit) && limit > 0 && Number.isFinite(used) && used >= 0) {
return { limit, used };
}
} catch {
/** 当前运行环境没有这一版 cgroup 接口,继续探测下一版 */
}
}
return null;
}
/** 每次准入都读取当前值,不缓存内存水位 */
async function readMemorySnapshot(): Promise<MemorySnapshot> {
const hostLimit = totalmem();
const hostFree = freemem();
const cgroup = await readCgroupMemory();
const limit = cgroup ? Math.min(hostLimit, cgroup.limit) : hostLimit;
const cgroupFree = cgroup ? Math.max(0, cgroup.limit - cgroup.used) : hostLimit;
const free = Math.max(0, Math.min(hostFree, cgroupFree));
/** 给运行时和静态请求保留内存,绝不把水位用满 */
const reserve = Math.max(32 * MIB, Math.min(128 * MIB, limit * 0.1));
return { limit, free, reserve };
}
/** 小内存机器最多同时执行两个重任务;大内存机器仍受配置上限约束 */
function concurrencyLimit(memory: MemorySnapshot): number {
return memory.limit <= 2 * 1024 * MIB ? Math.min(maxConcurrency, 2) : maxConcurrency;
}
function delay(milliseconds: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
/**
* 通过并发队列执行子集化任务
* 所有字体重任务共用的内存闸门。
*
* - active < maxConcurrency → 立即执行
* - active ≥ maxConcurrency → 排队等待,前面的完成后唤醒(同 groupKey 优先)
* - 队列超时 → 返回 null(调用方返回 503,客户端可重试)
*
* 分组优化:同 groupKey(同一字体)的排队请求优先连续唤醒,
* 使字体 buffer / 解析对象在缓存窗口内被下一个请求复用,降低内存峰值。
*
* @param task 实际的异步任务
* @param queueTimeoutMs 排队超时(毫秒)
* @param groupKey 分组键(通常为 fontPath),同组连续处理以复用缓存
* @returns 任务结果,或 null 表示排队超时
* 在读取完整字体之前按源文件预估内存;并发槽位和实际可用内存任一不足都排队。
* 没有任务运行时允许启动一个大任务,避免小内存机器因预估值偏大而永久饥饿。
* 任务超时返回 null,由调用方按现有接口语义返回 503 或流式错误。
*/
export async function withMemoryGate<T>(
task: () => Promise<T>,
queueTimeoutMs: number,
groupKey = "",
estimatedBytes = 64 * MIB,
): Promise<T | null> {
/** 并发已满,进入排队 */
if (activeCount >= maxConcurrency) {
const acquired = await waitForSlot(queueTimeoutMs, groupKey);
if (!acquired) return null;
}
lastGroupKey = groupKey;
activeCount++;
try {
return await task();
} finally {
activeCount--;
release();
const deadline = Date.now() + queueTimeoutMs;
let queued = false;
while (true) {
const memory = await readMemorySnapshot();
const hasSlot = activeCount < concurrencyLimit(memory);
const available = memory.free - memory.reserve - reservedBytes;
const hasMemory = activeCount === 0 ? available > 0 : available >= estimatedBytes;
if (hasSlot && hasMemory) {
if (queued) waitingCount--;
activeCount++;
reservedBytes += estimatedBytes;
try {
return await task();
} finally {
activeCount--;
reservedBytes -= estimatedBytes;
}
}
if (!queued) {
queued = true;
waitingCount++;
}
const remaining = deadline - Date.now();
if (remaining <= 0) {
waitingCount--;
return null;
}
await delay(Math.min(50, remaining));
}
}
/**
* 排队等待并发槽位
*
* 加入队列,等待前面的请求完成后唤醒(同 groupKey 优先)。
* 超时则从队列移除自己,返回 false。
*/
function waitForSlot(timeoutMs: number, groupKey: string): Promise<boolean> {
return new Promise((resolve) => {
const item: QueueItem = {
resolve: () => resolve(true),
groupKey,
};
const timer = setTimeout(() => {
const idx = waitQueue.indexOf(item);
if (idx !== -1) waitQueue.splice(idx, 1);
resolve(false);
}, timeoutMs);
item.resolve = () => {
clearTimeout(timer);
resolve(true);
};
waitQueue.push(item);
});
}
/**
* 从队列中取出下一个该唤醒的项
*
* 策略:优先选与 lastGroupKey 相同的项(同字体连续处理,复用缓存);
* 没有同组项则取队首(FIFO 公平)。
*/
function pickNext(): QueueItem | undefined {
if (waitQueue.length === 0) return undefined;
if (lastGroupKey) {
const idx = waitQueue.findIndex((item) => item.groupKey === lastGroupKey);
if (idx !== -1) return waitQueue.splice(idx, 1)[0];
}
return waitQueue.shift();
}
/**
* 释放一个并发槽位,唤醒下一个等待者(同 groupKey 优先)
*/
function release(): void {
if (waitQueue.length === 0) return;
if (activeCount < maxConcurrency) {
pickNext()?.resolve();
}
}
/**
* 初始化并发参数(由 config 设置)
*
* 必须在第一次 withMemoryGate 调用前执行。
* @param concurrency 最大并发数
*/
/** 初始化最大并发数;实际并发还会随每次任务的内存水位进一步降低 */
export function initMemoryGate(concurrency?: number): void {
if (concurrency && concurrency > 0) {
maxConcurrency = concurrency;
}
console.log(`[subset-queue] maxConcurrency=${maxConcurrency}`);
if (concurrency && concurrency > 0) maxConcurrency = concurrency;
console.log(`[subset-queue] maxConcurrency=${maxConcurrency}, memoryAware=true`);
}
/** 获取当前队列状态(用于 stats / 日志) */
export function getQueueStats() {
return {
active: activeCount,
waiting: waitQueue.length,
waiting: waitingCount,
reservedBytes,
maxConcurrency,
};
}

View File

@ -2,21 +2,25 @@
* 截图找字体 —— 服务端比对自测(无需浏览器,直接测核心算法)
*
* 自测方法(self-consistent 验证):
* 1. 用 getGlyphBitmap 渲染「思源黑体」的目标字,得到 64x64 归一化位图
* 2. 把这些位图当作「用户截图切分后的查询输入」
* 3. 跑全库 glyphSimilarity 比对,思源黑体必须排第一(自渲自比,满分 1.0)
* 1. 走共享裁剪入口 subsetFontFile 裁出「思源黑体」的目标字小字体
* 2. getGlyphBitmap 渲染出 64x64 归一化位图,当作「用户截图切分后的查询输入」
* 3. 全库每个字体同样只裁一次,跑 glyphSimilarity 比对,
* 思源黑体必须排第一(自渲自比,满分 1.0)
*
* 这一步验证的是服务端光栅化 + 比对的核心链路正确性。
* 前端二值化/切分用另一组注入测试覆盖。
* 与线上 /api/glyph-match 走同一裁剪管线,无完整字体对象缓存。
*/
import "../backend/server/node";
import { loadFontObject, getGlyphBitmap, glyphSimilarity } from "../backend/font_util/glyph_bitmap";
import { findFontPath, readFontBuffer } from "../backend/shared";
import { Font } from "../vendor/fonteditor-core/lib/ttf/font";
import { getGlyphBitmap, glyphSimilarity, hasGlyph, type SubsetTtfObject } from "../backend/font_util/glyph_bitmap";
import { findFontPath } from "../backend/shared";
import { readdir } from "../backend/interface";
import { fontDirs } from "../backend/config";
import { subsetFontFile } from "../backend/font_util/subset_file";
const TARGET_FONT = "思源黑体.ttf";
const TEXT = "天地玄黄";
/** 覆盖「借」的内部封闭留白回归 */
const HOLLOW_TEXT = "借";
/** 统计不与位图边缘连通的白色像素,用于验证字形内部镂空仍然存在 */
function countEnclosedWhitePixels(bitmap: Uint8Array): number {
@ -47,18 +51,36 @@ function countEnclosedWhitePixels(bitmap: Uint8Array): number {
return enclosedTotal;
}
/**
* 裁剪并返回内存子集 ttf 对象(与 glyph_match.ts 相同口径)。
* 内存对象中 glyf 已是子集但 cmap 仍是原始 gid,按字形 unicode 重建映射。
*/
async function loadSubsetObject(fontName: string, text: string): Promise<SubsetTtfObject | null> {
const fontPath = await findFontPath(fontName);
if (!fontPath) return null;
const subset = await subsetFontFile(fontPath, text, "ttf");
const ttf = subset.ttf;
if (!ttf) return null;
const glyf = ttf.glyf as Array<{ unicode?: number | number[] }>;
const cmap: Record<number, number> = {};
for (const [index, glyph] of glyf.entries()) {
if (!glyph.unicode) continue;
for (const cp of Array.isArray(glyph.unicode) ? glyph.unicode : [glyph.unicode]) {
if (!(cp in cmap)) cmap[cp] = index;
}
}
return { ...ttf, cmap } as unknown as SubsetTtfObject;
}
async function main() {
console.log("=== 服务端字形比对自测 ===");
/** 1. 渲染目标字体的查询位图(模拟截图切分输入) */
const ttf = await loadFontObject(TARGET_FONT, async (name) => {
const p = await findFontPath(name);
return p ? readFontBuffer(p) : null;
});
/** 1. 裁剪目标字体并渲染查询位图(模拟截图切分输入) */
const ttf = await loadSubsetObject(TARGET_FONT, TEXT + HOLLOW_TEXT);
if (!ttf) throw new Error(`无法加载目标字体 ${TARGET_FONT}`);
/** 「借」的「日」有两个封闭留白,不能因轮廓填充错误变成实心 */
const jieBitmap = getGlyphBitmap(ttf, TARGET_FONT, "借".codePointAt(0)!);
const jieBitmap = getGlyphBitmap(ttf, "借".codePointAt(0)!);
const enclosed = jieBitmap ? countEnclosedWhitePixels(jieBitmap) : 0;
console.log(` 借: 封闭留白像素=${enclosed}`);
if (enclosed < 8) throw new Error(`${TARGET_FONT} 的「借」内部留白丢失`);
@ -66,7 +88,8 @@ async function main() {
const queryBitmaps: Uint8Array[] = [];
for (const ch of TEXT) {
const cp = ch.codePointAt(0)!;
const bm = getGlyphBitmap(ttf, TARGET_FONT, cp);
if (!hasGlyph(ttf, cp)) throw new Error(`${TARGET_FONT} 缺 ${ch}`);
const bm = getGlyphBitmap(ttf, cp);
if (!bm) throw new Error(`${TARGET_FONT} 渲染 ${ch} 失败(返回空位图)`);
const ink = bm.reduce((a, b) => a + b, 0);
console.log(` ${ch} (U+${cp.toString(16)}): 位图墨点数=${ink}`);
@ -75,7 +98,7 @@ async function main() {
}
console.log(`✓ 目标字体 ${TARGET_FONT} 的「${TEXT}」渲染成功\n`);
/** 2. 遍历全库字体,用同样的字做 glyphSimilarity 比对 */
/** 2. 遍历全库字体,每个只裁一次,用同样的字做 glyphSimilarity 比对 */
const fontNames: string[] = [];
for (const dir of fontDirs) {
try {
@ -88,24 +111,33 @@ async function main() {
const results: Array<{ font: string; score: number; perChar: number[] }> = [];
for (const font of fontNames) {
const f = await loadFontObject(font, async (name) => {
const p = await findFontPath(name);
return p ? readFontBuffer(p) : null;
});
if (!f) continue;
/** 单个字体裁剪/解析失败不中断全库比对(如缺字导致空 glyf 的小字体) */
const f = await loadSubsetObject(font, TEXT).catch(() => null);
if (!f) {
console.log(` ${font}: 解析失败,跳过`);
continue;
}
const perChar: number[] = [];
let sum = 0;
let missing = false;
for (let i = 0; i < TEXT.length; i++) {
const cp = TEXT.codePointAt(i)!;
const cand = getGlyphBitmap(f, font, cp);
if (!cand) {
let index = 0;
for (const ch of TEXT) {
const cp = ch.codePointAt(0)!;
if (!hasGlyph(f, cp)) {
missing = true;
index++;
continue;
}
const s = glyphSimilarity(queryBitmaps[i]!, cand);
const cand = getGlyphBitmap(f, cp);
if (!cand) {
missing = true;
index++;
continue;
}
const s = glyphSimilarity(queryBitmaps[index]!, cand);
perChar.push(s);
sum += s;
index++;
}
results.push({ font, score: perChar.length ? sum / perChar.length : 0, perChar });
if (missing) console.log(` ${font}: 缺字`);

View File

@ -1,14 +1,10 @@
/**
* 候选字体比对引擎 —— 渲染侧
*
* 对每个候选字体:经后端 subset API 拿到只含目标字符的最小 woff2(服务端有缓存,
* 同字符组合只裁一次)→ FontFace 加载 → canvas 渲染每个字 → 与截图切出的字形
* 归一化后逐一 SSIM,取平均分。
*
* 竞态安全:每个字体用独立 family 名(`ff-match-<序号>-<随机>`),
* 比对完立即 delete() 释放,不污染全局字体空间。
* 服务端在 /api/glyph-match 流式比对时逐字体裁剪一次,并把 woff2 随事件下发;
* 本模块用该 woff2 加载 FontFace → canvas 渲染每个字 → 生成归一化预览。
* 不再发起第二轮裁剪请求。
*/
import { calculateSSIM } from "./ssim";
import {
imageToMask,
maskToNormalizedRGBA,
@ -18,32 +14,6 @@ import {
type Mask,
} from "./segmenter";
/** 单个候选字形的比对结果 */
export interface GlyphMatch {
/** 识别用的字符 */
char: string;
/** 截图字形归一化预览(DataURL) */
queryPreview: string;
/** 候选字体渲染字形归一化预览(DataURL) */
candidatePreview: string;
/** 该字的 SSIM 得分 0~1 */
score: number;
}
/** 单个字体的比对结果 */
export interface FontMatchResult {
/** 字体文件名(后端 font 名) */
font: string;
/** 所有字形平均 SSIM 得分 */
score: number;
/** 逐字明细 */
glyphs: GlyphMatch[];
/** 该字体缺字(subset 后渲染不出目标字符) */
missing: boolean;
/** 比对耗时 ms */
elapsed: number;
}
/**
* 渲染缓冲 canvas 尺寸 —— 远大于归一化网格,保证小笔画细节在降采样前已充分光栅化
*/
@ -113,27 +83,36 @@ function tightCrop(mask: Mask): Mask {
return { data: crop, w: cw, h: ch };
}
/** base64 → Uint8Array(流事件中的 woff2 载荷) */
export function base64ToBytes(b64: string): Uint8Array {
const bin = atob(b64);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return bytes;
}
/**
* 加载候选字体子集 —— 走后端 subset API(GET /api?font=&text=&outType=woff2)
* 只请求目标字符,传输量极小且命中服务端 subset 缓存
* 用 woff2 字节加载临时 FontFace(独立 family,用完即删)
* 字节来自流式接口的同一份裁剪结果,不再发第二轮裁剪请求
*/
async function loadSubsetFontFace(font: string, text: string): Promise<FontFace> {
const url = `/api?font=${encodeURIComponent(font)}&text=${encodeURIComponent(text)}&outType=woff2`;
const res = await fetch(url);
if (!res.ok) throw new Error(`subset failed: ${font} HTTP ${res.status}`);
const buf = await res.arrayBuffer();
const family = `ff-match-${font.replace(/[^a-z0-9]/gi, "")}-${Math.random().toString(36).slice(2, 8)}`;
async function loadFontFaceFromBytes(bytes: Uint8Array): Promise<FontFace> {
/** 拷贝出独立 ArrayBuffer,避免复用底层缓冲破后续读取 */
const buf = bytes.slice().buffer as ArrayBuffer;
const family = `ff-match-${Math.random().toString(36).slice(2, 10)}`;
const face = new FontFace(family, buf);
await face.load();
document.fonts.add(face);
(face as FontFace & { _family?: string })._family = family;
return face;
}
/** 一次裁剪指定字体所需字符,并用浏览器生成各字符的归一化预览 */
export async function renderSubsetGlyphPreviews(font: string, chars: string[]): Promise<Map<string, string>> {
const face = await loadSubsetFontFace(font, [...new Set(chars)].join(""));
/**
* 用流事件携带的 woff2 生成各字符的归一化预览
* 每个字体只裁剪一次,预览复用同一份裁剪结果
*/
export async function renderSubsetGlyphPreviews(woff2: Uint8Array, chars: string[]): Promise<Map<string, string>> {
const previews = new Map<string, string>();
if (!chars.length) return previews;
const face = await loadFontFaceFromBytes(woff2);
try {
for (const char of new Set(chars)) {
const rawMask = renderCharMask(char, face.family, 96);
@ -147,49 +126,6 @@ export async function renderSubsetGlyphPreviews(font: string, chars: string[]):
return previews;
}
/**
* 对单个候选字体执行比对
*
* @param font 字体文件名
* @param text 用户确认的选区文字(与 queryMasks 一一对应)
* @param queryMasks 截图切分出的归一化 RGBA 字形序列
*/
export async function matchFont(
font: string,
text: string,
queryMasks: Uint8Array[],
previews: string[],
): Promise<FontMatchResult> {
const t0 = performance.now();
const glyphs: GlyphMatch[] = [];
let missing = false;
let face: FontFace | null = null;
try {
face = await loadSubsetFontFace(font, text);
const family = (face as FontFace & { _family?: string })._family!;
for (let i = 0; i < text.length; i++) {
const char = text[i]!;
const rawMask = renderCharMask(char, family, 96);
if (!rawMask) {
missing = true;
continue;
}
const candidateRGBA = maskToNormalizedRGBA(tightCrop(rawMask));
const score = calculateSSIM(queryMasks[i]!, candidateRGBA, 64, 64);
glyphs.push({
char,
queryPreview: previews[i]!,
candidatePreview: rgbaToDataURL(candidateRGBA),
score,
});
}
const score = glyphs.length ? glyphs.reduce((s, g) => s + g.score, 0) / glyphs.length : 0;
return { font, score, glyphs, missing, elapsed: performance.now() - t0 };
} finally {
if (face) document.fonts.delete(face);
}
}
/** 截图 ImageData → 归一化 RGBA 序列 + 预览
* 管线:自适应二值化 → 去噪 → 倾角校正 → 切分 → 归一化
* 已知字数时按方块字等分切分(字间粘连也能切开);未知时用投影切分

View File

@ -10,14 +10,14 @@
*/
import { ref, computed, useTemplateRef } from "vue";
import { usePageSeo } from "../useSeo";
import { prepareQueryGlyphs, renderSubsetGlyphPreviews } from "../font-finder/matcher";
import { prepareQueryGlyphs, renderSubsetGlyphPreviews, base64ToBytes } from "../font-finder/matcher";
/** 服务端返回的单字体结果(与 backend/routes/glyph_match.ts 对齐) */
/** 服务端逐字返回的单字体结果(与 backend/routes/glyph_match.ts 的 NDJSON 事件对齐) */
interface ServerFontResult {
font: string;
score: number;
missing: boolean;
glyphs: Array<{ char: string; score: number; bitmap: string; queryIndex: number }>;
glyphs: Array<{ char: string; score: number; queryIndex: number }>;
}
/** 归一化 RGBA(0/255 灰度)→ 4096 字符 01 串(笔画=1) */
@ -212,7 +212,7 @@ function onGlyphInput() {
results.value = [];
}
/** 裁剪接口生成的字体预览缓存(同字体同字只渲染一次) */
/** 裁剪接口生成的字体预览缓存(同字体同字只渲染一次,来自流事件的 woff2) */
const glyphPreviewCache = new Map<string, string>();
function serverGlyphPreview(font: string, char: string): string {
return glyphPreviewCache.get(font + "|" + char) ?? "";
@ -224,13 +224,35 @@ function queryPreview(queryIndex: number): string {
return sourceIndex === undefined ? "" : (glyphPreviews.value[sourceIndex] ?? "");
}
/** 开始识别:一次请求,只提交已填写字符的图块 */
/** 收到 font 事件后异步渲染预览:直接消费流携带的 woff2,不再二次请求裁剪接口 */
function renderPreviewsFromEvent(font: string, subsetB64: string) {
const woff2 = base64ToBytes(subsetB64);
const chars = filledGlyphIndices.value.map((i) => glyphChars.value[i]!);
void renderSubsetGlyphPreviews(woff2, chars).then((previews) => {
for (const [char, preview] of previews) {
glyphPreviewCache.set(font + "|" + char, preview);
}
});
}
/** 新的单字分数到达后重算平均分并按分数降序重排,让最像的字体始终在顶部 */
function resortResults() {
for (const r of results.value) {
r.score = r.glyphs.length
? r.glyphs.reduce((s, g) => s + g.score, 0) / r.glyphs.length
: 0;
}
results.value = [...results.value].sort((a, b) => b.score - a.score);
}
/** 开始识别:NDJSON 流式请求,识别一个字即可看到一个字的结果 */
async function startMatch() {
if (!canMatch.value) return;
matching.value = true;
errorMsg.value = "";
results.value = [];
doneCount.value = 0;
totalCount.value = 0;
const t0 = performance.now();
try {
const res = await fetch("/api/glyph-match", {
@ -243,20 +265,65 @@ async function startMatch() {
})),
}),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = (await res.json()) as { results?: ServerFontResult[]; error?: string };
if (data.error) throw new Error(data.error);
const matchedResults = data.results ?? [];
/** 每个字体只裁剪一次,同次裁剪包含该结果需要展示的全部字符 */
await Promise.all(matchedResults.map(async (result) => {
const previews = await renderSubsetGlyphPreviews(result.font, result.glyphs.map((g) => g.char));
for (const [char, preview] of previews) {
glyphPreviewCache.set(result.font + "|" + char, preview);
if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
const byFont = new Map<string, ServerFontResult>();
/** 处理单个 NDJSON 事件,增量更新 UI */
const handleEvent = (event: any) => {
switch (event.type) {
case "start": {
totalCount.value = event.total;
break;
}
case "font": {
const item: ServerFontResult = { font: event.font, score: 0, missing: false, glyphs: [] };
byFont.set(event.font, item);
results.value.push(item);
renderPreviewsFromEvent(event.font, event.subset);
break;
}
case "glyph": {
const item = byFont.get(event.font);
if (!item) break;
if (event.glyph) {
item.glyphs.push(event.glyph);
} else if (event.missing) {
item.missing = true;
}
resortResults();
break;
}
case "fontDone": {
doneCount.value++;
break;
}
case "done": {
break;
}
}
}));
results.value = matchedResults;
totalCount.value = results.value.length;
doneCount.value = results.value.length;
};
/** 增量按行解析:逐字节累积到换行符即分发事件 */
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let newlineIndex: number;
while ((newlineIndex = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, newlineIndex).trim();
buffer = buffer.slice(newlineIndex + 1);
if (line) handleEvent(JSON.parse(line));
}
}
const tail = decoder.decode();
if (tail.trim()) buffer += tail;
for (const line of buffer.split("\n")) {
if (line.trim()) handleEvent(JSON.parse(line.trim()));
}
elapsedMs.value = Math.round(performance.now() - t0);
} catch (err) {
errorMsg.value = `识别失败:${err instanceof Error ? err.message : String(err)}`;
@ -363,7 +430,7 @@ const scoreColor = (s: number) => (s > 0.9 ? "#16a34a" : s > 0.8 ? "#d97706" : "
<!-- 识别中进度 -->
<div v-if="matching" style="margin-top: 14px; padding: 12px 16px; border: 1px solid #91caff; background: #e6f4ff; border-radius: 8px; font-size: 14px; color: #0958d9; display: flex; align-items: center; gap: 10px">
<span style="display: inline-block; width: 16px; height: 16px; border: 2px solid #1677ff; border-top-color: transparent; border-radius: 50%; animation: ff-spin 0.8s linear infinite"></span>
正在与站内字体库比对,请稍候…
{{ totalCount ? `正在比对 ${doneCount}/${totalCount} 个字体,已出 ${results.length} 个结果…` : "正在与站内字体库比对,请稍候…" }}
</div>
</div>