怎样用 Python 调用 Google Fonts API,自动替换无授权字体?
解读
在国内商业设计交付中,字体侵权风险高、赔偿金额大,面试官想知道候选人能否:
- 用脚本批量扫描 SVG 文件,定位
<text>或@font-face中声明的字体名; - 判断该字体是否属于“可商用”白名单(Google Fonts 全部开源);
- 通过 Google Fonts Developer API 实时拉取同族或相似字体的 TTF/OTF/WOFF2 链接;
- 把原字体名自动改写成 Google Fonts 提供的 CSS
font-family名称,并嵌入@import或<style>; - 保证脚本在 Windows/macOS/Linux 下都能跑通,且对 Inkscape 的 CLI(
inkscape --export-type=svg --export-plain-svg)无侵入; - 输出可溯源的替换报告,方便法务归档。
知识点
- Google Fonts Developer API v2 配额与认证:生成 API Key,启用「Web Fonts Developer API」,国内需配置代理或镜像源(如
fonts.geekzu.org); - SVG 字体声明方式:
<text style="font-family:'xxx'">、<style>@font-face{font-family:xxx;src:url(...)}</style>、<defs><style>...</style></defs>; - 字体相似度匹配:Google Fonts 返回的
family,category,subsets,variants字段,可用 Pythondifflib.SequenceMatcher或fontTools的 PANOSE 值做粗匹配; - 本地缓存策略:把下载的
.woff2统一放到~/.cache/inkscape_gfonts/目录,避免重复拉取; - Inkscape 命令行:用
--query-id提取文本对象,用--vacuum-defs清理无用样式,保证脚本跑完后文件体积不膨胀; - 版权合规:Google Fonts 全部遵循 OFL 或 Apache 2.0,可商用,但需保留版权抬头;脚本需在报告里附带许可证原文链接,满足国内甲方审计要求;
- 异常处理:国内网络 403/timeout 时自动降级到本地白名单;若 Google Fonts 无对应中文字体,需提示人工复核。
答案
给出一个可直接演示的 Python3 脚本框架,重点突出“自动替换”与“Inkscape 零侵入”。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量扫描当前目录下所有 SVG,把非授权字体自动替换成 Google Fonts 开源字体,
并生成合规报告。依赖:requests、lxml、fonttools。
"""
import os, re, json, shutil, requests, argparse
from pathlib import Path
from lxml import etree
from difflib import SequenceMatcher
API_KEY = os.getenv("GOOGLE_FONTS_KEY") or "YOUR_KEY"
PROXY = {"https": "http://127.0.0.1:7890"} # 国内按需设置
CACHE_DIR = Path.home() / ".cache" / "inkscape_gfonts"
CACHE_DIR.mkdir(parents=True, exist_ok=True)
WHITELIST_LOCAL = {"SimSun", "Microsoft YaHei"} # 本地已知可商用字体示例
GOOGLE_FONTS_LIST_URL = "https://www.googleapis.com/webfonts/v1/webfonts"
CSS_TEMPLATE = '@import url("https://fonts.googleapis.com/css2?family={}:wght@{}&display=swap");'
def fetch_google_fonts():
"""拉取完整字体列表,缓存为 json,减少 API 调用"""
cache_file = CACHE_DIR / "fonts.json"
if cache_file.exists():
return json.loads(cache_file.read_text(encoding="utf-8"))
params = {"key": API_KEY, "sort": "popularity"}
resp = requests.get(GOOGLE_FONTS_LIST_URL, params=params, proxies=PROXY, timeout=15)
resp.raise_for_status()
data = resp.json()["items"]
cache_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
return data
def closest_family(target, gf_list):
"""简单相似度匹配,返回最相近的 Google Fonts 族名"""
target = target.lower().replace(" ", "")
best, score = None, 0
for item in gf_list:
candidate = item["family"].lower().replace(" ", "")
s = SequenceMatcher(None, target, candidate).ratio()
if s > score:
score, best = s, item["family"]
return best if score > 0.4 else None
def patch_svg(svg_path, gf_list):
"""核心函数:扫描并替换字体"""
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(str(svg_path), parser)
root = tree.getroot()
# 1. 收集所有字体名
font_set = set()
for elem in root.xpath("//*[contains(@style,'font-family')]"):
style = elem.get("style", "")
m = re.search(r"font-family:\s*['\"]?([^;'\"]+)['\"]?", style)
if m:
font_set.add(m.group(1).strip())
# 2. 替换
report = []
for old in font_set:
if old in WHITELIST_LOCAL:
continue
new = closest_family(old, gf_list)
if not new:
report.append(f"未找到匹配:{old}")
continue
# 改写 style 字符串
for elem in root.xpath("//*[contains(@style,'font-family')]"):
style = elem.get("style", "")
if old in style:
style = style.replace(f"font-family:{old}", f"font-family:{new}")
elem.set("style", style)
# 插入 @import
head_style = root.xpath("//svg:style", namespaces={"svg": "http://www.w3.org/2000/svg"})
if not head_style:
style_node = etree.Element("style")
style_node.text = CSS_TEMPLATE.format(new.replace(" ", "+"), "400")
root.insert(0, style_node)
else:
head_style[0].text += "\n" + CSS_TEMPLATE.format(new.replace(" ", "+"), "400")
report.append(f"{old} -> {new}")
# 3. 保存
out_path = svg_path.with_name(svg_path.stem + "_gf.svg")
tree.write(str(out_path), pretty_print=True, xml_declaration=True, encoding="utf-8")
return out_path, report
def main():
parser = argparse.ArgumentParser(description="Auto-replace fonts in SVG with Google Fonts.")
parser.add_argument("folder", help="包含 SVG 的文件夹")
args = parser.parse_args()
gf_list = fetch_google_fonts()
summary = []
for svg in Path(args.folder).glob("*.svg"):
out, rep = patch_svg(svg, gf_list)
summary.append({"file": out.name, "replacements": rep})
# 输出报告
report_file = Path(args.folder) / "google_fonts_report.json"
report_file.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
print("完成,报告路径:", report_file)
if __name__ == "__main__":
main()
运行步骤:
- 安装依赖
pip install requests lxml fonttools - 申请 Google Fonts API Key,写入环境变量
export GOOGLE_FONTS_KEY=xxx - 把需要处理的 SVG 放在同一目录,执行
python gfonts_replace.py ./svgs - 目录下会生成
*_gf.svg新文件及google_fonts_report.json,直接拖回 Inkscape 继续编辑即可,无需额外设置。
拓展思考
- 中文字体匹配精度:Google Fonts 中文字体有限,可引入 Adobe 开源「思源黑体/宋体」作为兜底,脚本里再加一层「本地开源字体」映射表;
- 子集化:用
pyftsubset把 Google Fonts 的 WOFF2 按「常用汉字 3500」裁剪,减少 90% 体积,适合嵌入激光切割控制软件; - CI 集成:把脚本封装成 GitHub Action,每次提交 SVG 即自动跑检查,PR 里附带版权报告,设计团队与法务同时可见;
- 反向校验:交付前再用
inkscape --export-text-to-path把文字转路径,彻底杜绝字体泄露风险,但需保留原 SVG 备份以便后期文字修改; - 法律合规:国内法院对「字体侵权」认定以「实质性相似」为准,脚本报告需附带每次替换的相似度分值,证明已尽合理注意义务,降低赔偿概率。