用 sphinx-gallery 生成缩略图?

解读

在国内科研与工程文档中,“一键生成带缩略图的可视化示例库”是展示算法效果、沉淀技术资产的刚需。Sphinx-Gallery 作为 Sphinx 生态的官方扩展,能把 examples/ 目录下的 Python 脚本自动转为 HTML 页面,并为每个脚本提取最后一幅 Matplotlib 图像作为缩略图,最终拼成矩阵式图库。面试官问此题,表面考“如何配置”,实则验证候选人是否理解 Matplotlib 后端切换、Agg 无头渲染、Sphinx 构建钩子、缓存与并行加速 等工程细节,能否在国产 Linux 服务器、麒麟 OS、Jenkins/GitLab CI 等受限环境中稳定出图。

知识点

  1. Sphinx-Gallery 的缩略图机制:默认抓取脚本最后一幅 matplotlib.figure.Figure 实例,通过 matplotlib.image.imsave 生成 _images/sphx_glr_xxx_thumb.png;若脚本无图,则回退到 default_thumb_file 指定占位图。
  2. 无头渲染与后端选择:国产服务器通常无 X11,需在 conf.py 里提前 matplotlib.use('Agg'),防止 tkinter.TclError;同时设置 export DISPLAY= 空值,确保 CI 容器不触发 Qt/WX 依赖。
  3. Gallery 配置键:sphinx_gallery_conf 字典中
    • 'image_scrapers':可自定义为元组 (matplotlib_scraper,),或加入 mayavi_scraper、plotly_scraper 实现多后端混洗;
    • 'thumbnail_size':二元组 (宽, 高),单位像素,国内期刊通常要求 400×280 以上;
    • 'compress_images':设为 ('png', 9),利用 optipng 或 pngquant 压缩,减少 Gitee Pages、腾讯 COS 流量;
    • 'plot_gallery':布尔值,PR 阶段可置 False 仅做语法检查,加速流水线。
  4. 缓存与增量构建:.sphinx_gallery_cache 目录记录 md5,若示例脚本未改动则跳过执行;在 GitLab-CI 中需把该目录加入 cache:key:files,避免每次从零渲染 500+ 图。
  5. 中文与字体陷阱:国产系统缺失 SimHei,需在 conf.py 顶部追加 plt.rcParams['font.family']='DejaVu Sans' 或手动挂载 /usr/share/fonts/truetype 目录,防止缩略图中文乱码。
  6. 扩展钩子:sphinx_gallery_conf['first_notebook_cell'] 可注入 %matplotlib inline 与 sns.set_theme(),保证本地 Jupyter 与线上 Gallery 样式一致;'gallery_dirs' 与 'examples_dirs' 支持相对路径,方便“单仓多子模块”的国企常见布局。

答案

在 doc/conf.py 中完成四步即可稳定生成缩略图:

# 1. 强制无头,必须在 import pyplot 前
import matplotlib
matplotlib.use('Agg')

# 2. 统一中文字体,防止 CI 乱码
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'DejaVu Sans'
plt.rcParams['axes.unicode_minus'] = False

# 3. 配置 sphinx-gallery
sphinx_gallery_conf = {
    'examples_dirs': '../examples',       # 脚本源目录
    'gallery_dirs': 'auto_examples',      # 输出 HTML 目录
    'image_scrapers': ('matplotlib',),    # 只抓 Matplotlib
    'thumbnail_size': (400, 280),         # 国内高清屏适配
    'compress_images': ('png', 9),        # 体积压缩
    'plot_gallery': True,                 # 允许出图
    'filename_pattern': '/plot_.*\.py$',  # 仅渲染 plot_ 前缀脚本,加速
    'within_subsection_order': 'NumberOfCodeLinesSortKey',  # 按代码行数排序,方便评审
    'first_notebook_cell': '%matplotlib inline\nimport seaborn as sns\nsns.set_theme(font_scale=1.2)',
}

# 4. 扩展依赖
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon',
    'sphinx_gallery.gen_gallery',  # 必须置后,确保 Agg 已生效
]

随后在 CI 脚本中安装系统依赖并执行:

sudo apt-get update && sudo apt-get install -y optipng libgl1-mesa-glx
python -m pip install sphinx-gallery matplotlib numpy
make html

构建结束后,build/html/auto_examples/index.html 即呈现矩阵缩略图,每张图下方附带 “源代码” 与 “Jupyter 下载” 按钮,符合国内工程师“先看图、再下代码”的阅读习惯。

拓展思考

  1. 多后端混洗:若项目同时含 Matplotlib、Plotly、PyVista,可自定义 scrapers=[matplotlib_scraper, plotly_scraper],但需保证各自在无头环境能退避到 pio.kaleido.scope.mathjax = None 与 os.environ['PYVISTA_OFF_SCREEN']='true'。
  2. GPU 加速缩略图:对 3D 体渲染示例,可在 conf.py 检测 nvidia-smi 存在时启用 pyvista.GPU_ENABLED=True,并设置 'image_scrapers' 优先级,让显存充足的节点生成高分辨率缩略图,其余节点复用缓存。
  3. 国产操作系统适配:银河麒麟 ARM64 缺少 libxcb,需在 Dockerfile 内 RUN apt-get install -y libxcb-xinerama0-dev libxkbcommon-x11-0 并 export QT_QPA_PLATFORM=offscreen,防止 PyQt 误触发。
  4. 增量评审策略:在 PR 流水线中解析 git diff --name-only,仅对改动的示例脚本设置 'plot_gallery':True,其余目录复用主分支缓存,可把 30 min 的文档构建压缩到 3 min,满足国企内网 GitLab Runner 的 15 min 超时限制。