feat(api): 新增素材检索 API 服务(图标/海报检索 + SVG 直链 + Key 鉴权 + 中文语义检索)
This commit is contained in:
@@ -0,0 +1,571 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 画个标 · 素材 API 索引构建
|
||||
*
|
||||
* 读取 ../js/data 下的图标/海报源文件,产出两类文件到 api/data/:
|
||||
* {kind}/{source}.jsonl 每行一个素材的完整 JSON(按字节偏移随机读取)
|
||||
* {kind}/{source}.idx.json 检索索引(name/categoryCn/type + 字节偏移)
|
||||
*
|
||||
* 设计要点:
|
||||
* - 不依赖任何第三方库,Node 原生即可跑
|
||||
* - 索引常驻内存,素材正文按需 seek 读取,避免把 99MB 源文件整体加载
|
||||
* - 源文件是严格 JSON 对象字面量(window['HGB_Source_x'] = {...};),可直接 JSON.parse
|
||||
*
|
||||
* 用法:
|
||||
* node build-index.js # 默认读取上一级的 js/data
|
||||
* DRAWLOGO_ROOT=/opt/drawlogo node build-index.js
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const API_ROOT = __dirname;
|
||||
const SITE_ROOT = process.env.DRAWLOGO_ROOT || path.resolve(API_ROOT, '..');
|
||||
const SITE_DATA = path.join(SITE_ROOT, 'js', 'data');
|
||||
const OUT = path.join(API_ROOT, 'data');
|
||||
const OUT_ICONS = path.join(OUT, 'icons');
|
||||
const OUT_POSTERS = path.join(OUT, 'posters');
|
||||
|
||||
/** 不允许商用的协议特征(与项目规则一致:排除 BY-SA/BY-NC/BY-ND/GPL) */
|
||||
const NON_COMMERCIAL_RE = /BY-NC|BY-SA|BY-ND|\bGPL\b|NonCommercial|非商业|禁止商用/i;
|
||||
|
||||
/**
|
||||
* 中文语义别名表:中文关键词 → 英文词根
|
||||
* 解决的问题:图标 name 是英文、categoryCn 是「教育学习」这类宽分类,
|
||||
* 用户搜「学校/医院/餐厅」时匹配不到。构建期为每个图标预计算中文别名。
|
||||
*/
|
||||
const CN_ALIAS = {
|
||||
'学校': ['school', 'graduation', 'student', 'book', 'academic', 'backpack'],
|
||||
'教育': ['education', 'school', 'graduation', 'book', 'study', 'learn', 'academic', 'pencil'],
|
||||
'医院': ['hospital', 'medical', 'health', 'doctor', 'nurse', 'stethoscope', 'pill', 'ambulance'],
|
||||
'医疗': ['medical', 'health', 'hospital', 'doctor', 'pill', 'stethoscope', 'first-aid'],
|
||||
'餐厅': ['restaurant', 'food', 'dining', 'chef', 'fork', 'knife', 'meal', 'cook', 'utensil'],
|
||||
'餐饮': ['restaurant', 'food', 'chef', 'fork', 'meal', 'cook', 'coffee', 'cup'],
|
||||
'咖啡': ['coffee', 'cup', 'cafe', 'mug', 'tea'],
|
||||
'银行': ['bank', 'wallet', 'credit', 'card', 'money', 'payment', 'currency', 'coin'],
|
||||
'支付': ['payment', 'credit', 'card', 'wallet', 'qr', 'money', 'cash'],
|
||||
'金融': ['finance', 'money', 'bank', 'chart', 'stock', 'coin', 'currency', 'wallet'],
|
||||
'科技': ['tech', 'chip', 'cpu', 'circuit', 'robot', 'code', 'terminal', 'server', 'brain'],
|
||||
'互联网': ['internet', 'web', 'cloud', 'network', 'wifi', 'globe', 'link'],
|
||||
'物流': ['truck', 'shipping', 'delivery', 'package', 'box', 'warehouse', 'cargo', 'container'],
|
||||
'运输': ['truck', 'shipping', 'delivery', 'package', 'cargo', 'bus', 'train'],
|
||||
'房产': ['home', 'house', 'building', 'apartment', 'estate', 'door'],
|
||||
'建筑': ['building', 'architecture', 'construction', 'home', 'house', 'crane'],
|
||||
'法律': ['law', 'legal', 'gavel', 'justice', 'scale', 'court', 'contract'],
|
||||
'旅游': ['travel', 'plane', 'map', 'luggage', 'hotel', 'compass', 'globe', 'beach'],
|
||||
'酒店': ['hotel', 'bed', 'building', 'key', 'door'],
|
||||
'制造': ['factory', 'industry', 'gear', 'machine', 'cog', 'wrench', 'production'],
|
||||
'工业': ['factory', 'industry', 'gear', 'machine', 'cog', 'wrench'],
|
||||
'农业': ['agriculture', 'farm', 'plant', 'leaf', 'seed', 'tractor', 'wheat'],
|
||||
'能源': ['energy', 'battery', 'power', 'solar', 'electric', 'zap', 'fuel', 'plug'],
|
||||
'零售': ['shop', 'store', 'cart', 'bag', 'shopping', 'basket', 'market'],
|
||||
'电商': ['shop', 'cart', 'shopping', 'store', 'bag', 'package'],
|
||||
'娱乐': ['music', 'play', 'game', 'movie', 'film', 'video', 'headphone', 'party'],
|
||||
'媒体': ['media', 'video', 'camera', 'music', 'film', 'play', 'mic'],
|
||||
'体育': ['sport', 'ball', 'fitness', 'run', 'gym', 'bike', 'swim', 'trophy'],
|
||||
'安防': ['security', 'shield', 'lock', 'camera', 'alarm', 'guard', 'safe'],
|
||||
'通信': ['phone', 'message', 'mail', 'signal', 'wifi', 'antenna', 'chat'],
|
||||
'汽车': ['car', 'auto', 'vehicle', 'truck', 'wheel', 'road', 'engine'],
|
||||
'航空': ['plane', 'flight', 'airplane', 'rocket', 'jet'],
|
||||
'政务': ['government', 'building', 'document', 'law', 'badge', 'flag', 'landmark'],
|
||||
'宠物': ['pet', 'dog', 'cat', 'paw', 'animal', 'bone'],
|
||||
'美容': ['beauty', 'scissors', 'cosmetic', 'sparkle', 'flower', 'lipstick'],
|
||||
'服装': ['shirt', 'clothes', 'fashion', 'dress', 'tag', 'hanger'],
|
||||
'食品': ['food', 'apple', 'coffee', 'restaurant', 'meal', 'bottle', 'bread'],
|
||||
'工具': ['tool', 'wrench', 'hammer', 'settings', 'gear', 'screwdriver'],
|
||||
'安全': ['shield', 'lock', 'key', 'security', 'safe', 'protect'],
|
||||
'云': ['cloud', 'server', 'upload', 'download', 'storage'],
|
||||
'数据': ['data', 'chart', 'database', 'analytics', 'graph', 'bar', 'table'],
|
||||
'人工智能': ['ai', 'robot', 'brain', 'chip', 'sparkles', 'neural'],
|
||||
'设计': ['design', 'pen', 'brush', 'palette', 'layout', 'ruler', 'vector'],
|
||||
'音乐': ['music', 'note', 'headphone', 'speaker', 'audio', 'mic'],
|
||||
'摄影': ['camera', 'photo', 'image', 'aperture', 'lens'],
|
||||
'游戏': ['game', 'joystick', 'controller', 'dice', 'trophy', 'arcade'],
|
||||
'地图': ['map', 'location', 'pin', 'navigation', 'compass', 'route'],
|
||||
'时间': ['clock', 'time', 'calendar', 'watch', 'timer', 'alarm'],
|
||||
'天气': ['weather', 'sun', 'cloud', 'rain', 'snow', 'wind', 'thermometer'],
|
||||
'环保': ['leaf', 'recycle', 'nature', 'tree', 'eco', 'plant', 'globe'],
|
||||
'公益': ['heart', 'hand', 'donate', 'help', 'charity', 'volunteer'],
|
||||
'社交': ['user', 'users', 'message', 'chat', 'share', 'heart', 'comment'],
|
||||
'办公': ['briefcase', 'file', 'folder', 'desk', 'paperclip', 'printer'],
|
||||
'购物': ['cart', 'bag', 'shopping', 'store', 'tag', 'credit'],
|
||||
'地图定位': ['map-pin', 'location', 'navigation', 'gps'],
|
||||
'视频': ['video', 'play', 'film', 'camera', 'youtube', 'movie'],
|
||||
'搜索': ['search', 'magnify', 'find', 'zoom'],
|
||||
'设置': ['settings', 'gear', 'cog', 'sliders', 'wrench'],
|
||||
'用户': ['user', 'users', 'person', 'account', 'profile', 'avatar'],
|
||||
'下载': ['download', 'arrow-down', 'save', 'import'],
|
||||
'上传': ['upload', 'arrow-up', 'cloud', 'export'],
|
||||
'通知': ['bell', 'notification', 'alert', 'message'],
|
||||
'邮件': ['mail', 'email', 'envelope', 'inbox', 'send'],
|
||||
'电话': ['phone', 'call', 'telephone', 'headset'],
|
||||
'日历': ['calendar', 'date', 'schedule', 'event'],
|
||||
'锁': ['lock', 'unlock', 'key', 'shield', 'password'],
|
||||
'星星': ['star', 'sparkle', 'favorite', 'rating'],
|
||||
'心': ['heart', 'love', 'favorite', 'like'],
|
||||
'箭头': ['arrow', 'chevron', 'direction', 'right', 'left', 'up', 'down'],
|
||||
'文件': ['file', 'document', 'folder', 'page', 'paper'],
|
||||
'图表': ['chart', 'graph', 'bar', 'pie', 'trend', 'analytics'],
|
||||
'机器人': ['robot', 'bot', 'ai', 'android'],
|
||||
'礼物': ['gift', 'present', 'box', 'ribbon'],
|
||||
'旗帜': ['flag', 'banner', 'country'],
|
||||
'地球': ['globe', 'earth', 'world', 'planet', 'international'],
|
||||
'闪电': ['zap', 'lightning', 'flash', 'bolt', 'power'],
|
||||
'火焰': ['fire', 'flame', 'hot', 'burn'],
|
||||
'水滴': ['droplet', 'water', 'drop', 'rain'],
|
||||
'叶子': ['leaf', 'plant', 'nature', 'eco', 'green'],
|
||||
'太阳': ['sun', 'sunny', 'light', 'day'],
|
||||
'月亮': ['moon', 'night', 'dark', 'sleep'],
|
||||
'相机': ['camera', 'photo', 'lens', 'picture'],
|
||||
'打印机': ['printer', 'print', 'paper'],
|
||||
'键盘': ['keyboard', 'typing', 'input'],
|
||||
'鼠标': ['mouse', 'click', 'pointer', 'cursor'],
|
||||
'电脑': ['computer', 'laptop', 'desktop', 'monitor', 'pc'],
|
||||
'手机': ['phone', 'mobile', 'smartphone', 'device'],
|
||||
'平板': ['tablet', 'ipad', 'device'],
|
||||
'服务器': ['server', 'database', 'rack', 'cloud', 'host'],
|
||||
'数据库': ['database', 'db', 'storage', 'server', 'data'],
|
||||
'网络': ['network', 'wifi', 'signal', 'internet', 'router', 'globe'],
|
||||
'蓝牙': ['bluetooth', 'wireless', 'connect'],
|
||||
'电池': ['battery', 'power', 'charge', 'energy'],
|
||||
'插座': ['plug', 'socket', 'power', 'electric'],
|
||||
'灯泡': ['bulb', 'idea', 'light', 'lamp'],
|
||||
'齿轮': ['gear', 'cog', 'settings', 'machine', 'engine'],
|
||||
'锤子': ['hammer', 'tool', 'build', 'repair'],
|
||||
'扳手': ['wrench', 'tool', 'repair', 'settings'],
|
||||
'螺丝刀': ['screwdriver', 'tool', 'repair'],
|
||||
'刷子': ['brush', 'paint', 'design', 'clean'],
|
||||
'画笔': ['brush', 'pen', 'paint', 'design', 'draw'],
|
||||
'调色板': ['palette', 'color', 'design', 'paint'],
|
||||
'尺子': ['ruler', 'measure', 'design', 'size'],
|
||||
'剪刀': ['scissors', 'cut', 'tool', 'barber'],
|
||||
'针': ['needle', 'pin', 'sew', 'medical'],
|
||||
'药': ['pill', 'medicine', 'drug', 'health', 'pharmacy'],
|
||||
'注射器': ['syringe', 'vaccine', 'medical', 'injection'],
|
||||
'听诊器': ['stethoscope', 'doctor', 'medical', 'health'],
|
||||
'救护车': ['ambulance', 'emergency', 'medical', 'hospital'],
|
||||
'消防': ['fire', 'extinguisher', 'emergency', 'alarm'],
|
||||
'警察': ['police', 'badge', 'security', 'law'],
|
||||
'法庭': ['court', 'gavel', 'law', 'justice', 'judge'],
|
||||
'合同': ['contract', 'document', 'agreement', 'sign', 'file'],
|
||||
'印章': ['stamp', 'seal', 'approve', 'official'],
|
||||
'发票': ['invoice', 'receipt', 'bill', 'document', 'money'],
|
||||
'钱包': ['wallet', 'money', 'payment', 'finance', 'card'],
|
||||
'硬币': ['coin', 'money', 'currency', 'cash', 'finance'],
|
||||
'信用卡': ['credit-card', 'payment', 'bank', 'money', 'card'],
|
||||
'二维码': ['qr', 'code', 'scan', 'payment'],
|
||||
'条形码': ['barcode', 'scan', 'code', 'product'],
|
||||
'包裹': ['package', 'box', 'delivery', 'shipping', 'parcel'],
|
||||
'卡车': ['truck', 'delivery', 'shipping', 'transport', 'logistics'],
|
||||
'飞机': ['plane', 'flight', 'travel', 'airport', 'airplane'],
|
||||
'火车': ['train', 'railway', 'transport', 'travel'],
|
||||
'公交': ['bus', 'transport', 'public', 'travel'],
|
||||
'自行车': ['bike', 'bicycle', 'cycle', 'transport', 'sport'],
|
||||
'船': ['ship', 'boat', 'sail', 'sea', 'transport'],
|
||||
'路': ['road', 'route', 'street', 'map', 'navigation'],
|
||||
'地图标记': ['map-pin', 'location', 'marker', 'gps', 'place'],
|
||||
'导航': ['navigation', 'compass', 'route', 'direction', 'gps'],
|
||||
'指南针': ['compass', 'navigation', 'direction', 'explore'],
|
||||
'行李箱': ['luggage', 'suitcase', 'travel', 'bag'],
|
||||
'护照': ['passport', 'travel', 'document', 'id'],
|
||||
'签证': ['visa', 'passport', 'travel', 'document'],
|
||||
'床': ['bed', 'hotel', 'sleep', 'room', 'furniture'],
|
||||
'房子': ['house', 'home', 'building', 'property', 'real-estate'],
|
||||
'公寓': ['apartment', 'building', 'home', 'property'],
|
||||
'工厂': ['factory', 'industry', 'manufacture', 'plant', 'production'],
|
||||
'仓库': ['warehouse', 'storage', 'logistics', 'inventory'],
|
||||
'小麦': ['wheat', 'grain', 'agriculture', 'farm', 'food'],
|
||||
'拖拉机': ['tractor', 'farm', 'agriculture', 'vehicle'],
|
||||
'种植': ['plant', 'seed', 'grow', 'agriculture', 'farm'],
|
||||
'太阳能': ['solar', 'sun', 'energy', 'panel', 'renewable'],
|
||||
'风力': ['wind', 'turbine', 'energy', 'renewable'],
|
||||
'核能': ['nuclear', 'atom', 'energy', 'power'],
|
||||
'回收': ['recycle', 'eco', 'environment', 'green', 'sustainability'],
|
||||
'树': ['tree', 'nature', 'forest', 'eco', 'plant'],
|
||||
'花': ['flower', 'nature', 'beauty', 'plant', 'bloom'],
|
||||
'动物': ['animal', 'pet', 'wildlife', 'dog', 'cat'],
|
||||
'狗': ['dog', 'pet', 'animal', 'paw'],
|
||||
'猫': ['cat', 'pet', 'animal', 'kitten'],
|
||||
'咖啡杯': ['coffee', 'cup', 'mug', 'cafe', 'drink'],
|
||||
'面包': ['bread', 'food', 'bakery', 'bake'],
|
||||
'蛋糕': ['cake', 'dessert', 'birthday', 'food'],
|
||||
'披萨': ['pizza', 'food', 'restaurant', 'slice'],
|
||||
'汉堡': ['burger', 'food', 'fastfood', 'restaurant'],
|
||||
'饮料': ['drink', 'beverage', 'cup', 'bottle', 'water'],
|
||||
'酒': ['wine', 'beer', 'drink', 'bar', 'alcohol'],
|
||||
'购物车': ['cart', 'shopping', 'store', 'ecommerce', 'buy'],
|
||||
'商店': ['shop', 'store', 'market', 'retail', 'building'],
|
||||
'标签': ['tag', 'label', 'price', 'sale'],
|
||||
'折扣': ['discount', 'sale', 'tag', 'percent', 'price'],
|
||||
'支付成功': ['check', 'success', 'payment', 'done', 'circle-check'],
|
||||
'图表分析': ['chart', 'analytics', 'data', 'report', 'trend', 'graph'],
|
||||
'报表': ['report', 'document', 'chart', 'data', 'file'],
|
||||
'演示': ['presentation', 'screen', 'slides', 'projector', 'chart'],
|
||||
'会议': ['meeting', 'users', 'video', 'calendar', 'presentation'],
|
||||
'团队': ['team', 'users', 'group', 'people', 'collaboration'],
|
||||
'招聘': ['recruit', 'user', 'briefcase', 'hiring', 'person'],
|
||||
'简历': ['resume', 'document', 'briefcase', 'profile', 'cv'],
|
||||
'培训': ['training', 'education', 'learn', 'presentation', 'book'],
|
||||
'证书': ['certificate', 'award', 'badge', 'achievement', 'diploma'],
|
||||
'奖杯': ['trophy', 'award', 'win', 'prize', 'achievement'],
|
||||
'排名': ['ranking', 'trophy', 'chart', 'leaderboard', 'medal'],
|
||||
'目标': ['target', 'goal', 'aim', 'focus', 'bullseye'],
|
||||
'火箭': ['rocket', 'launch', 'startup', 'space', 'growth'],
|
||||
'灯泡创意': ['bulb', 'idea', 'innovation', 'light', 'creative'],
|
||||
'大脑': ['brain', 'ai', 'mind', 'thinking', 'intelligence'],
|
||||
'芯片': ['chip', 'cpu', 'processor', 'hardware', 'tech'],
|
||||
'电路': ['circuit', 'electronics', 'chip', 'board'],
|
||||
'代码': ['code', 'terminal', 'programming', 'developer', 'brackets'],
|
||||
'终端': ['terminal', 'console', 'command', 'shell', 'code'],
|
||||
'bug': ['bug', 'debug', 'error', 'issue', 'insect'],
|
||||
'测试': ['test', 'check', 'verify', 'flask', 'experiment'],
|
||||
'部署': ['deploy', 'rocket', 'server', 'upload', 'cloud'],
|
||||
'备份': ['backup', 'save', 'cloud', 'archive', 'storage'],
|
||||
'恢复': ['restore', 'refresh', 'rotate', 'backup'],
|
||||
'删除': ['trash', 'delete', 'remove', 'bin', 'garbage'],
|
||||
'编辑': ['edit', 'pencil', 'pen', 'write', 'modify'],
|
||||
'保存': ['save', 'disk', 'download', 'check'],
|
||||
'分享': ['share', 'send', 'social', 'link'],
|
||||
'链接': ['link', 'chain', 'url', 'connect'],
|
||||
'二维码扫描': ['qr', 'scan', 'code', 'camera'],
|
||||
'指纹': ['fingerprint', 'security', 'identity', 'biometric'],
|
||||
'人脸': ['face', 'user', 'avatar', 'profile', 'scan'],
|
||||
'盾牌': ['shield', 'security', 'protect', 'safe', 'defense'],
|
||||
'钥匙': ['key', 'lock', 'security', 'access', 'password'],
|
||||
'警报': ['alert', 'warning', 'alarm', 'danger', 'exclamation'],
|
||||
'禁止': ['ban', 'block', 'forbidden', 'stop', 'prohibited'],
|
||||
'检查': ['check', 'tick', 'done', 'success', 'verify'],
|
||||
'关闭': ['close', 'x', 'cancel', 'exit'],
|
||||
'菜单': ['menu', 'hamburger', 'list', 'bars'],
|
||||
'更多': ['more', 'dots', 'ellipsis', 'options'],
|
||||
'刷新': ['refresh', 'reload', 'rotate', 'sync', 'update'],
|
||||
'同步': ['sync', 'refresh', 'rotate', 'update', 'cloud'],
|
||||
'筛选': ['filter', 'funnel', 'sort', 'sliders'],
|
||||
'排序': ['sort', 'arrow', 'list', 'order'],
|
||||
'折叠': ['chevron', 'arrow', 'collapse', 'expand', 'down'],
|
||||
'展开': ['chevron', 'arrow', 'expand', 'down', 'up'],
|
||||
'全屏': ['fullscreen', 'expand', 'maximize', 'screen'],
|
||||
'静音': ['mute', 'volume', 'speaker', 'sound', 'off'],
|
||||
'音量': ['volume', 'speaker', 'sound', 'audio'],
|
||||
'播放': ['play', 'media', 'video', 'music', 'start'],
|
||||
'暂停': ['pause', 'media', 'stop', 'break'],
|
||||
'录音': ['record', 'mic', 'audio', 'voice'],
|
||||
'麦克风': ['mic', 'microphone', 'audio', 'record', 'voice'],
|
||||
'耳机': ['headphone', 'audio', 'music', 'listen'],
|
||||
'喇叭': ['speaker', 'volume', 'sound', 'audio', 'megaphone'],
|
||||
'广播': ['broadcast', 'signal', 'radio', 'live', 'antenna'],
|
||||
'卫星': ['satellite', 'space', 'signal', 'orbit'],
|
||||
'天线': ['antenna', 'signal', 'network', 'wireless'],
|
||||
'无线': ['wireless', 'wifi', 'signal', 'network'],
|
||||
'定位': ['location', 'pin', 'gps', 'map', 'place'],
|
||||
'地震': ['earthquake', 'activity', 'wave', 'pulse', 'seismic'],
|
||||
'温度': ['temperature', 'thermometer', 'weather', 'heat'],
|
||||
'湿度': ['humidity', 'water', 'weather', 'droplet'],
|
||||
'空气质量': ['air', 'wind', 'weather', 'quality'],
|
||||
'时钟': ['clock', 'time', 'watch', 'timer'],
|
||||
'日历事件': ['calendar', 'event', 'date', 'schedule'],
|
||||
'提醒': ['bell', 'reminder', 'notification', 'alarm'],
|
||||
'待办': ['todo', 'check', 'list', 'task', 'checkbox'],
|
||||
'清单': ['list', 'checklist', 'todo', 'tasks'],
|
||||
'看板': ['board', 'kanban', 'columns', 'layout', 'dashboard'],
|
||||
'仪表盘': ['dashboard', 'gauge', 'chart', 'speed', 'analytics'],
|
||||
'大屏': ['dashboard', 'monitor', 'screen', 'chart', 'display'],
|
||||
'报表导出': ['export', 'download', 'file', 'sheet', 'csv']
|
||||
};
|
||||
|
||||
function ensureDir(p) {
|
||||
fs.mkdirSync(p, { recursive: true });
|
||||
}
|
||||
|
||||
/* ---------- 中文别名匹配(词边界,避免 car→card 之类误命中) ---------- */
|
||||
const ROOT_RANK = new Map(); // 单词词根 -> [[中文词, 位次], ...]
|
||||
const MULTI_ROOTS = []; // 含连字符的词根(如 real-estate)
|
||||
|
||||
for (const [cn, roots] of Object.entries(CN_ALIAS)) {
|
||||
roots.forEach((r, rank) => {
|
||||
const k = r.toLowerCase();
|
||||
if (k.includes('-')) {
|
||||
MULTI_ROOTS.push([k, cn, rank]);
|
||||
} else {
|
||||
if (!ROOT_RANK.has(k)) ROOT_RANK.set(k, []);
|
||||
ROOT_RANK.get(k).push([cn, rank]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 为图标名计算中文别名(按 -/_ 分词后精确匹配,多词词根用包含匹配)
|
||||
* @returns {Array<{cn:string, rank:number}>} rank = 词根在该中文词表中的位次(越小越相关)
|
||||
*/
|
||||
function aliasesFor(name) {
|
||||
const tokens = String(name || '').toLowerCase().split(/[-_\s]+/);
|
||||
const best = new Map(); // cn -> 最小 rank
|
||||
|
||||
const add = (cn, rank) => {
|
||||
const prev = best.get(cn);
|
||||
if (prev === undefined || rank < prev) best.set(cn, rank);
|
||||
};
|
||||
|
||||
for (const t of tokens) {
|
||||
const list = ROOT_RANK.get(t);
|
||||
if (list) for (const [cn, rank] of list) add(cn, rank);
|
||||
}
|
||||
if (MULTI_ROOTS.length) {
|
||||
const lower = String(name || '').toLowerCase();
|
||||
for (const [root, cn, rank] of MULTI_ROOTS) {
|
||||
if (lower.includes(root)) add(cn, rank);
|
||||
}
|
||||
}
|
||||
return [...best.entries()].map(([cn, rank]) => ({ cn, rank }));
|
||||
}
|
||||
|
||||
function readJSON(file) {
|
||||
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 `window['HGB_Source_x'] = {...};` 形式的源文件
|
||||
* 注意:不能用 eval/vm,大文件(99MB)会撑爆内存;这里直接截取 JSON 文本。
|
||||
*/
|
||||
function parseSourceFile(file) {
|
||||
const text = fs.readFileSync(file, 'utf8');
|
||||
const m = text.match(/window\[['"][^'"]+['"]\]\s*=\s*/);
|
||||
if (!m) throw new Error('无法识别赋值格式: ' + file);
|
||||
let json = text.slice(m.index + m[0].length).trim();
|
||||
if (json.endsWith(';')) json = json.slice(0, -1);
|
||||
return JSON.parse(json);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一个源的素材数组写成 jsonl + idx.json
|
||||
* @returns {{count:number, bytes:number}}
|
||||
*/
|
||||
function buildIndex(items, outBase) {
|
||||
const jsonlPath = outBase + '.jsonl';
|
||||
const fd = fs.openSync(jsonlPath, 'w');
|
||||
|
||||
const names = [];
|
||||
const catIdx = [];
|
||||
const typeIdx = [];
|
||||
const aliasIdx = [];
|
||||
const aliasRank = [];
|
||||
const offsets = [];
|
||||
const cats = [];
|
||||
const types = [];
|
||||
const aliases = [];
|
||||
const catMap = new Map();
|
||||
const typeMap = new Map();
|
||||
const aliasMap = new Map();
|
||||
|
||||
let offset = 0;
|
||||
for (const it of items) {
|
||||
const line = JSON.stringify(it) + '\n';
|
||||
const buf = Buffer.from(line, 'utf8');
|
||||
fs.writeSync(fd, buf);
|
||||
|
||||
names.push(String(it.name || it.id || '').toLowerCase());
|
||||
const cat = String(it.categoryCn || '');
|
||||
if (!catMap.has(cat)) { catMap.set(cat, cats.length); cats.push(cat); }
|
||||
catIdx.push(catMap.get(cat));
|
||||
const ty = String(it.type || '');
|
||||
if (!typeMap.has(ty)) { typeMap.set(ty, types.length); types.push(ty); }
|
||||
typeIdx.push(typeMap.get(ty));
|
||||
|
||||
// 中文语义别名(词边界匹配,rank 越小越相关)
|
||||
const list = aliasesFor(it.name || it.id);
|
||||
const codes = [];
|
||||
const ranks = [];
|
||||
for (const { cn, rank } of list) {
|
||||
if (!aliasMap.has(cn)) { aliasMap.set(cn, aliases.length); aliases.push(cn); }
|
||||
codes.push(aliasMap.get(cn));
|
||||
ranks.push(rank);
|
||||
}
|
||||
aliasIdx.push(codes);
|
||||
aliasRank.push(ranks);
|
||||
|
||||
offsets.push(offset, buf.length);
|
||||
offset += buf.length;
|
||||
}
|
||||
fs.closeSync(fd);
|
||||
|
||||
const idx = {
|
||||
count: items.length,
|
||||
n: names,
|
||||
c: catIdx,
|
||||
t: typeIdx,
|
||||
k: aliasIdx,
|
||||
r: aliasRank,
|
||||
kws: aliases,
|
||||
cats,
|
||||
types,
|
||||
o: offsets
|
||||
};
|
||||
fs.writeFileSync(outBase + '.idx.json', JSON.stringify(idx));
|
||||
return { count: items.length, bytes: offset };
|
||||
}
|
||||
|
||||
/** 进度输出(构建 224 个源时便于观察) */
|
||||
let done = 0;
|
||||
function tick(label, count, bytes) {
|
||||
done++;
|
||||
if (done % 20 === 0 || count > 20000) {
|
||||
process.stdout.write(` [${String(done).padStart(3)}] ${label} → ${count} 条 / ${(bytes / 1048576).toFixed(1)} MB\n`);
|
||||
}
|
||||
}
|
||||
|
||||
function buildIcons() {
|
||||
console.log('\n[1/3] 图标库');
|
||||
const manifest = readJSON(path.join(SITE_DATA, 'manifest', 'icons.json'));
|
||||
const sources = [];
|
||||
|
||||
for (const s of manifest.sources) {
|
||||
const file = path.join(SITE_DATA, s.file || ('sources/' + s.id + '.js'));
|
||||
if (!fs.existsSync(file)) {
|
||||
console.warn(' 跳过(文件缺失): ' + s.id);
|
||||
continue;
|
||||
}
|
||||
let data;
|
||||
try {
|
||||
data = parseSourceFile(file);
|
||||
} catch (e) {
|
||||
console.warn(' 跳过(解析失败): ' + s.id + ' — ' + e.message);
|
||||
continue;
|
||||
}
|
||||
const items = Array.isArray(data.icons) ? data.icons : [];
|
||||
if (!items.length) continue;
|
||||
|
||||
const r = buildIndex(items, path.join(OUT_ICONS, s.id));
|
||||
const commercial = !NON_COMMERCIAL_RE.test(String(s.license || ''));
|
||||
sources.push({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
nameCn: s.nameCn,
|
||||
desc: s.desc,
|
||||
style: s.style,
|
||||
type: s.type,
|
||||
license: s.license,
|
||||
licenseNote: s.licenseNote,
|
||||
commercial,
|
||||
home: s.home,
|
||||
github: s.github,
|
||||
npm: s.npm,
|
||||
count: r.count,
|
||||
index: 'icons/' + s.id + '.idx.json',
|
||||
data: 'icons/' + s.id + '.jsonl',
|
||||
workspaces: s.workspaces || []
|
||||
});
|
||||
tick(s.id, r.count, r.bytes);
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'icons',
|
||||
total: sources.reduce((a, b) => a + b.count, 0),
|
||||
sources
|
||||
};
|
||||
}
|
||||
|
||||
function buildPosters() {
|
||||
console.log('\n[2/3] 海报素材库');
|
||||
const manifest = readJSON(path.join(SITE_DATA, 'manifest', 'posters.json'));
|
||||
const sources = [];
|
||||
|
||||
for (const s of manifest.sources) {
|
||||
const file = path.join(SITE_DATA, s.file || ('posters/' + s.id + '.js'));
|
||||
if (!fs.existsSync(file)) {
|
||||
console.warn(' 跳过(文件缺失): ' + s.id);
|
||||
continue;
|
||||
}
|
||||
let data;
|
||||
try {
|
||||
data = parseSourceFile(file);
|
||||
} catch (e) {
|
||||
console.warn(' 跳过(解析失败): ' + s.id + ' — ' + e.message);
|
||||
continue;
|
||||
}
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
if (!items.length) continue;
|
||||
|
||||
const r = buildIndex(items, path.join(OUT_POSTERS, s.id));
|
||||
const commercial = !NON_COMMERCIAL_RE.test(String(s.license || ''));
|
||||
sources.push({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
nameCn: s.nameCn,
|
||||
desc: s.desc,
|
||||
type: s.type,
|
||||
license: s.license,
|
||||
licenseNote: s.licenseNote,
|
||||
commercial,
|
||||
home: s.home,
|
||||
github: s.github,
|
||||
count: r.count,
|
||||
index: 'posters/' + s.id + '.idx.json',
|
||||
data: 'posters/' + s.id + '.jsonl',
|
||||
workspaces: s.workspaces || ['poster']
|
||||
});
|
||||
tick(s.id, r.count, r.bytes);
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'posters',
|
||||
total: sources.reduce((a, b) => a + b.count, 0),
|
||||
sources
|
||||
};
|
||||
}
|
||||
|
||||
function buildSkills() {
|
||||
console.log('\n[3/3] 技能库(元数据)');
|
||||
const manifest = readJSON(path.join(SITE_DATA, 'manifest', 'skills.json'));
|
||||
const out = {
|
||||
kind: 'skills',
|
||||
shared: { total: (manifest.shared && manifest.shared.total) || 0, skills: (manifest.shared && manifest.shared.skills) || [] },
|
||||
poster: { total: (manifest.poster && manifest.poster.total) || 0, skills: (manifest.poster && manifest.poster.skills) || [] },
|
||||
sticker: { total: (manifest.sticker && manifest.sticker.total) || 0, skills: (manifest.sticker && manifest.sticker.skills) || [] }
|
||||
};
|
||||
fs.writeFileSync(path.join(OUT, 'skills.json'), JSON.stringify(out));
|
||||
console.log(` 共享 ${out.shared.total} / 海报 ${out.poster.total} / 表情 ${out.sticker.total}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const t0 = Date.now();
|
||||
ensureDir(OUT);
|
||||
ensureDir(OUT_ICONS);
|
||||
ensureDir(OUT_POSTERS);
|
||||
|
||||
console.log('画个标素材 API · 索引构建');
|
||||
console.log(' 源目录: ' + SITE_DATA);
|
||||
console.log(' 输出至: ' + OUT);
|
||||
|
||||
const icons = buildIcons();
|
||||
const posters = buildPosters();
|
||||
const skills = buildSkills();
|
||||
|
||||
const catalog = {
|
||||
builtAt: new Date().toISOString(),
|
||||
icons: { total: icons.total, sources: icons.sources },
|
||||
posters: { total: posters.total, sources: posters.sources },
|
||||
skills: { shared: skills.shared.total, poster: skills.poster.total, sticker: skills.sticker.total }
|
||||
};
|
||||
fs.writeFileSync(path.join(OUT, 'sources.json'), JSON.stringify(catalog));
|
||||
|
||||
const size = dirSize(OUT);
|
||||
console.log('\n完成:');
|
||||
console.log(` 图标 ${icons.total} 个 / ${icons.sources.length} 源`);
|
||||
console.log(` 海报 ${posters.total} 个 / ${posters.sources.length} 源`);
|
||||
console.log(` 技能 ${skills.shared.total + skills.poster.total + skills.sticker.total} 个`);
|
||||
console.log(` 索引总体积 ${(size / 1048576).toFixed(1)} MB,耗时 ${((Date.now() - t0) / 1000).toFixed(1)}s`);
|
||||
}
|
||||
|
||||
function dirSize(dir) {
|
||||
let total = 0;
|
||||
for (const name of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, name.name);
|
||||
if (name.isDirectory()) total += dirSize(p);
|
||||
else total += fs.statSync(p).size;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
main();
|
||||
Reference in New Issue
Block a user