ai-chatbot/services/smart-edit/prepare_fonts.py

24 lines
1.4 KiB
Python

"""Prewarm the audited font catalogue. Downloads and outputs are checksum verified."""
import concurrent.futures,hashlib,json,os,tempfile,urllib.request
from pathlib import Path
from font import prepare
root=Path(os.environ.get('SMART_EDIT_FONT_CACHE_DIR','.cache/smart-edit-fonts')).resolve();root.mkdir(parents=True,exist_ok=True)
catalog=json.loads(Path('lib/video-canvas/smart-edit/font-catalog.json').read_text())
def digest(file):return hashlib.sha256(file.read_bytes()).hexdigest()
def install(font):
output=root/font['file']
if output.is_file() and digest(output)==font['preparedSha256']:return
with tempfile.TemporaryDirectory(dir=root) as work:
raw=Path(work)/'source';prepared=Path(work)/'prepared.ttf'
with urllib.request.urlopen(font['url'],timeout=90) as response:
data=response.read(40*1024*1024+1)
if len(data)>40*1024*1024:raise ValueError('字体超过大小上限')
raw.write_bytes(data)
if digest(raw)!=font['sha256']:raise ValueError('原始字体校验失败: '+font['name'])
prepare(str(raw),str(prepared),font['family'])
if digest(prepared)!=font['preparedSha256']:raise ValueError('字体处理版本不匹配: '+font['name'])
prepared.replace(output)
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
list(pool.map(install,catalog))
print(json.dumps({'fonts':len(catalog)+5,'catalogueFonts':len(catalog),'cache':str(root)},ensure_ascii=False))