Use Gemini multimodal long context to directly "read and understand" any PDF, routing by document type to the corresponding structured template for outputChinese Markdown.
The 4 document types (academic paper / product manual / whitepaper / book) share the same SDK invocation + Markdown style fingerprint + error-handling contract,
and each follows its own independent template (assets/template-{paper,manual,whitepaper,book}.md + shared _base.md)。
the agent can directly call this skill's script to process a single document, or follow references/api-quickstart.md to call the SDK itself within the session.
Dependencies: Python ≥ 3.7,
google-genai(pip install -U google-genai), environment variableGEMINI_API_KEY(created in Google AI Studio ). For detailed dependencies and failure troubleshooting, see "Prerequisites" at the end.
When to use / not use
Use
- The user provides alocal PDF, and wants structured Chinese summary output by document type (paper / manual / whitepaper / book)
- The user wants tobatch-processmultiple PDFs, each following the same type
- The PDF contains a large amount of charts / formulas / layout information, and plain-text extraction (pdftotext / PyPDF2) would lose information
- The user wants to use Gemini to read the PDF directly, rather than OCR first
- The output ultimately needs to land in
yzr-llm-wiki-management'sraw/<type>/<slug>/for subsequent ingest - The user is unsure of the PDF type—
--auto-detectlet the script auto-detect (PDF metadata + first-page text + Gemini viewing pages 1-3 of the first page for verification)
Do not use
- The PDF is not a PDF (webpage, Markdown, plain text)—convert to PDF first or use another skill
- Needword-for-word translation / full-text reproduction(this skill is "summarization", not translation)
- Needto compare multiple PDFs—this skill handles one at a time; for multiple, call it multiple times and then manually combine
- Only want to extract key sentences, extractive summarization—this skill is generative structured summarization
- The user is unwilling or unable to provide
GEMINI_API_KEY --typeis missing and--auto-detectwas not passed—the script will error and prompt the agent to ask the user to confirm the type (see §Workflow §A)
Input / Output
Input
| Field | Required | Description |
|---|---|---|
| PDF path | ✓ | Local .pdf file, absolute or relative path both acceptable |
| Document type | ✓ | --type <paper|manual|whitepaper|book> choose one of the two; if unsure use --auto-detect(script auto-determines) |
GEMINI_API_KEY |
✓ | Environment variable |
| Model ID | ✗ | Default gemini-3.1-pro-preview(no need to pass --model ; as of 2026-07-06 all skills uniformly default to pro-preview, with stable long-context attention + mermaid architecture diagrams fully preserved);only when there is a clear reasonshould it be overridden; see the "Model selection" subsection below for details |
| Focus | ✗ | --focus "重点关注实验部分" and the like, will be appended to the prompt |
| Output path | ✗ | --output <path> Two forms (2026-07-07 pitfall-fixing report §2.1):(1) Ends with .md ending → treated asfile path, mkdir the parent directory then write directly (applicable: paper full / manual / whitepaper / book / paper quick + --no-figures / by-chapter after passing --output <dir> when you want to precisely specify the filename, etc.);(2) Does not end with .md ending → treated asdirectory(paper quick writes summary.md + figures/by default when images are included, wiki-root usage writes <wiki-root>/raw/papers/<slug>.full.md, by-chapter writes 00-index.md + N 个 <NN>-<L1-slug>.md); if not passed, stdout (images are not exported, PDF image references in Markdown are automatically cleaned up into plain text).Counterexample (pitfall): for paper full, passing --output /path/to/<slug>.full.md —— fixednow lands directly on that file, no longer producing <output>.md/raw/papers/<slug>.full.md 4-level nesting |
| Template / mode | ✗ | paper quick default;--full enables paper full or book mode;--by-chapter splits into N .md files by chapter (mutually exclusive with --full ) |
| Chapter splitting method (by-chapter companion) | ✗ | --granularity {L1|auto}(default L1, since 2026-07-06): L1 makes N independent API calls by the PDF's native L1 chapters + L2 subsections are merged into L1 (comes with File API caching, saving N-1 uploads); auto makes a single call (only applicable to short PDFs ≤ 50 pages; >50 pages goes through pre-flight rejection and recommends L1) |
| Page range (auto by-chapter companion) | ✗ | --pages 1-50: first use PyMuPDF to slice the page range, then hand it to Gemini; combined with --by-chapter --granularity auto it can split ultra-long PDFs.In L1 mode, passing --pages will report an error(L1 automatically slices pages by chapter) |
| Extract images | ✗ | Only effective for paper quick:--no-figures turns off image export (manual / whitepaper / book do not enable images by default) |
| Render scale | ✗ | --figure-dpi 2.0(default 2.0;144 DPI = 72 × 2.0 converted value, not an independent threshold; when changing --figure-dpi this table does not need to be synchronized), only effective when paper quick image export is enabled |
| Image format | ✗ | --figure-format {png,webp,jpeg}, default png; for webp/jpeg you can use --figure-quality compression |
| Compression quality | ✗ | --figure-quality 1-100, default 85; only effective for webp/jpeg |
| Pixel limit | ✗ | --max-width N, after rendering scale proportionally to ≤ N px width; None means no limit |
| Size limit | ✗ | --max-size-kb N, automatically degrades when exceeding N KB (quality → format → scale); None means no limit |
| Thumbnail | ✗ | --thumbnail additionally generates a thumbnail;--thumbnail-width(default 400px) controls the width |
| Stage 2 visual grounding | ✗ | --refine-figures / --no-refine-figures(default True), only effective for paper quick |
| Stage 2 render scale | ✗ | --refine-dpi 2.0, only effective when paper quick enables refine |
| Stage 2 model | ✗ | --refine-model <id>(added 2026-07-06), only effective for paper quick + --refine-figures ; default None → follows --model go. See the §Model Selection section for details |
| Force overwrite | ✗ | --force-full, only paper --full mode takes effect; when the raw-side artifact already exists, overwrite is rejected by default |
Model Selection
Default = do not pass
--model. Script defaultgemini-3.1-pro-previewis the unified default across all skills (2026-07-06 decision):
- 3.5-flash under
--by-chaptersingle call + JSON structured output hits theFULL_MAX_OUTPUT_TOKENSlimit and is measured as unusable- pro-preview has more stable long-context attention and fully preserves mermaid architecture diagrams (flash silently drops mermaid blocks under structured output)
- The 4 document types (paper / manual / whitepaper / book) uniformly use pro-preview, no longer special-cased by mode
Don't know what to choose / no special reason → just use the default。
Decision Flow:
1. 跑 gemini_pdf_summary.py(不传 --model,用默认 pro-preview)
2. 输出不满意?
├─ 否 → 用默认就好
└─ 是 → 先调 prompt(--focus 或改 template-*.md),再考虑换模型
3. 真要换模型 → 从下方"当前推荐"里按场景选;不要凭印象写 model 字符串
Current recommendation (based on gemini-api-docs-mcp measured results + local by-chapter measured results, 2026-07):
| Model | Status | Positioning | When to explicitly override (vs default) |
|---|---|---|---|
gemini-3.1-pro-preview(Default, unified across all skills) |
Preview | Strongest complex reasoning + stable long context | In most scenarios just don't pass --model is sufficient |
gemini-3.5-flash |
Stable | Best overall quality/cost | Batch passing / simple summaries / large context but low requirements (known risk: under structured output it drops mermaid blocks, and --by-chapter single call easily hits the FULL_MAX_OUTPUT_TOKENS limit) |
gemini-3.1-flash-lite |
Stable | Cheapest, lightweight | Massive low-cost passing / summarization / content exploration |
Primary model unavailable → error out, no end-to-end degradation(reinforced 2026-06-30, agent blind spot patched 2026-07-01): In the table above,anymodel encountering 503 / 429 / 5xx, after the script does 3 retriesdirectly throws an errorto the upper layer— never silently switch to lite/pro or another cheap model.And upon receiving this error, the agent must not switch models and rerun on its own (the "use
--model <id>to switch models" in the script error is an instruction for the user, not for the agent), it must faithfully present the error + three-step suggestion to the user, and the user decides. Switching models must be explicitly specified with--model <id>, see §Core Principles #8 for the complete policy(including the error message format and three-step suggestion).
Stage 2 can be configured with an independent model(added 2026-07-06 with
--refine-model, only effective for paper quick +--refine-figures): Stage 2 is single-page PNG + structured JSON bbox/caption output, a simple task, not long-context reasoning, so in theoryflash-liteis sufficient. The model configuration can be split:# 主总结 pro-preview(保复杂推理 + 长文稳)+ Stage 2 flash-lite(保结构化输出 + 降 503 概率 + 便宜) python3 gemini_pdf_summary.py --pdf paper.pdf --type paper \ --model gemini-3.1-pro-preview --refine-model gemini-3.1-flash-liteBy default
--refine-modelis None → Stage 2 follows--model, keeping the old behavior unchanged. After splitting, if bbox precision degrades (crop spans to caption / multiple boxes with irrelevant content), fall back to not passing--refine-modeland let Stage 2 follow the primary model.
Avoid using:
- ==
gemini-2.5-flash==: deprecated, officially recommended replacementgemini-3.5-flash(has a shutdown date) gemini-2.5-pro: deprecated, replacementgemini-3.1-pro-previewgemini-2.5-flash-lite: deprecated, replacementgemini-3.1-flash-lite- Any
*-preview-09-2025/*-preview-12-2025and other old preview snapshots—expired, officially deprecated
The deprecated series will be shut down over time. The shutdown dates in this table are based on
mcp__gemini-api-docs-mcp__search_documentation/get_current_modelactual measurements; before use, agents / users shouldcheck once firstto confirm it has not changed.Do nothardcode the shutdown dates / deprecated list by month; this section is reviewed once a year/quarter.
Output
Route to the corresponding template by document type,unify section order, naming, and character count targetsas declared in each template header (single source of truth):
- paper quick(default): opening 3-column table → team item →
## 3 句话总结→ background and motivation → method design → representative experimental results → business insights & value → limitations and future work- For evaluation / benchmark papers, automatically replace "method design + representative experimental results" with "evaluation design + evaluation findings"
- paper full(
--full): expand subsection by subsection in the original PDF section order (including Definition / Theorem / Algorithm labels + formulas$...$+ row-level table transcription + numeric precision to 3 significant figures); do not extract original figures - manual: expand subsection by subsection following the PDF's native table of contents structure (full-style full-text-level transcription, including command lists / parameter tables / error codes; troubleshooting + FAQ + changelog highlights at the end of sections are preserved as-is);do not extract original figures
- whitepaper: expand subsection by subsection following the PDF's native table of contents structure (full-style full-text-level transcription, including industry data tables / comparison tables / customer cases; Conclusion + Key Takeaways + Recommendations at the end of sections are preserved as-is);do not extract original figures
- book(full only): fully transcribe in the PDF's native
Chapter/Section/Appendix/Indexorder;do not extract original figures - by-chapter(
--by-chapter, common to all 4 document types,default L1 mode, from 2026-07-06): N independent API calls per PDF native L1 chapter + L2 subsections merged into L1. The output layout is<output>/00-index.md(N_L1 rows of TOC) +<output>/01-<L1-slug>.md(including ## L1.title + ### L2 subsections) + ... L1 mode comes with File API caching(PDF > 20MB uses File API upload once + NPart.from_uri()references, saving N-1 upload tokens). Fine granularity such as L2/L3 can naturally be obtained through Gemini splitting within a single L1; the oldautomode (single API call, Gemini decides granularity itself) is retained for short PDFs ≤ 50 pages + users accustomed to the old behavior,50 pages goes through pre-flight interception and recommends L1. For the detailed contract see
references/full-mode-contract.md§by-chapter
Character count targets:
SSOT exception note: this table shares the same source as the
assets/template-paper.mdheader—the template header is the target shown to Gemini, this table is a mirror for agents to quickly look up, and both places must be changed in sync. The SSOT is in the template header (script_load_prompt_for_typeextracts this field); this table is the mirror within SKILL.md. manual / whitepaper / book are full style, with no character count upper limit—not within the scope of the SSOT exception.
- paper quick ≤ 2500
- paper full / manual / whitepaper / book: no character count upper limit; when the token budget is tight,prioritize tightening wording, cutting specific examples,forbiddenMerge entire sections, delete subsections, skip formulas / theorems / algorithm steps (paper full) / commands / parameters / error codes (manual) / industry data / customer cases (whitepaper) / Chapter content (book)
Figure handling strategy(SSOT in assets/_base.md §Figure handling conventions):
| Type / Mode | Figure handling | Reason |
|---|---|---|
| paper quick | Extract original PDF figures → figures/*.png(on by default) |
Forpeopleto read as a quick summary, must include figures |
| paper full | Do not extract figures; draw mermaid / tables / ASCII within markdown | Agent Q&A foundation; only ~50% of agents can consume PNG |
| manual / whitepaper | Same as paper full | Output is mainly for LLM consumption, entering llm-wiki for secondary ingest |
| book | Same as paper full | Long-form transcription, agent performs chapter-by-chapter Q&A afterward |
Nonexistent sections may be omitted;Default Chinese(titles, narration, connectives), but terminology, model names, product names, library names, etc. when necessary keep in English directly(see core principles #4 and #9 below).
Conciseness first(only applies to paper quick; full style follows full-text level): Every paragraph and every bullet should be cut wherever possible—if something can be explained in 1 sentence, do not split it into 3; omit any setup / repetition / concept definitions that can be omitted; the criterion is: "if deleting this paragraph would make the reader misunderstand / miss key information" is the only case that "must be kept"; otherwise cut everything. Density of the summary > length of the summary.
Execution principles / boundaries
Core principles
- Feed the original PDF directly to Gemini; do not extract text first
- Use
Part.from_bytes(data=<bytes>, mime_type="application/pdf")to go multimodal - Do not use pdftotext / PyPDF2 / pdfplumber or similar to extract plain text first (this loses figures, formulas, and layout)
- Use
- Structured summary, not paraphrase
- Route by document type to the corresponding template'smainline order and namingoutput; for character count targets see the header of each template (single source, do not hard-code values in the body)
- Nonexistent sections may be omitted(e.g., omit "representative experimental results" when a purely theoretical paper has no experimental data)
- Key data / values must be retained; avoid speaking in generalities
- Faithful to the original; do not invent
- If the document does not say it, mark "not specified in the original"
- When citing conclusions, indicate the source (e.g., "see Section 4.2 Experiments")
- Not forced to be all Chinese: keep English where it should be kept
- The main output language is still Chinese, but the following five categorieskeep in English directly, do not force translation:
- Academic proper nouns / method names: Transformer, RLHF, LoRA, Mixture-of-Experts, Beam Search
- Model / product / tool names: Gemini, GPT-4, Claude, PyTorch, vLLM, Hugging Face
- Library / API / file names:
transformers、pip、requirements.txt、<config>field names - Algorithm / protocol / standard names: Top-p, TCP, gRPC, REST, IEEE 802.11ax
- Metrics / abbreviations / proper terms: BLEU, ROUGE, ACL, GPU, FLOPS, perplexity
- Decision criteria: when translation instead introduces ambiguity, loses semantics, or the English is already the standard usage in the field, keep it unconditionally. Mixed Chinese-English is the norm (e.g. "训练使用 LoRA(低秩适配)")
- In lists / tables, if an item itself is an English term, keep the entire item in English
- The main output language is still Chinese, but the following five categorieskeep in English directly, do not force translation:
- Figure handling comes in two sets(see detailed rules in
assets/_base.md§Figure handling conventions)- paper quick: extract original PDF figures (on by default) →
figures/figure-pX-fN.png; caption is written into the markdown image's alt field (); bbox is written in the PDF reference string for precise cropping by the script - Other 3 types (manual / whitepaper / book + paper full): do not extract original figures,
concepts are drawn directly in markdown using
```mermaidblocks (architecture / flowcharts) / markdown tables (data visualization figures) / one line of text (decorative figures omitted)
- paper quick: extract original PDF figures (on by default) →
- GitHub-style paper related work / high-frequency citations: only output by paper quick, as a "business insights & value" subsection
- When the paper has an introduction / related work sectiononly thenoutput; omit the entire section when there is no related work
- Sort in descending order by "importance to this paper",3-5 items; omit the "citation count" column
- Prioritize inclusion: baselines directly compared in experiments > foundational work / recent SOTA / direct predecessors of this paper's method
- Citation details follow the PDF reference list; when uncertain, fill in only author + year (do not fabricate)
- paper quick open-source implementations: as a "business insights & value" subsection (applicable rules see
template-paper.mdquick mode) - Model selection: see the defaults and "when to explicitly override" guide in §Model selection subsection
(script
DEFAULT_MODELconstant, seescripts/gemini_pdf_summary.py). The actually available models are subject to the current Gemini documentation (verify usinggemini-api-docs-mcpofget_current_model). Why not relist model names here: the model selection table is the SSOT, listed in the §Model selection subsection- Result quality > system availability · no automatic fallback(2026-06-21 decision, 2026-06-30 hardening): when the default model encounters high-concurrency / rate-limit errors such as 503 UNAVAILABLE / 429 RESOURCE_EXHAUSTED / 5xx, uniformly go through 3 retries (2s/4s backoff; 4xx permanent errors are not retried and are thrown directly) — if still failing, the scriptthrows an error directlyto the upper layer,neversilently degrading to a cheaper model
- No end-to-end degradation · the agent must not switch models on its own(2026-07-01 hardening): the script throws
RuntimeError(includingmodel=+status=+ three-step suggestions) means the task fails,the agent must noton its own add--model gemini-3.1-flash-liteand other cheap models to rerun
- Markdown style conventions (repository unified baseline)——see the detailed 10-section rules in
references/markdown-style.md. SKILL.md mentions only the 3 key points:- bullet marker always use
*(do not use-or+) - Place mermaid blocks outside bullets (block-level), do not nest them inside bullet sub-items
- Math / ranges / formulas: MathJax is disabled:
$...$/$$...$$outline-wiki does not render—— switch to plain text / Unicode ([1, 2^64)/2⁶⁴/≥≤×→≈); book template's full-text-level transcription output may keep$...$inline formulas (agent Q&A scenarios can consume LaTeX)
- bullet marker always use
Boundaries
- Only process local PDFs; anything that is not a PDF must first be converted to PDF
- No full-text translation; no multi-document comparison
- One PDF at a time
- A single PDF's size is constrained by the File API hard limit (for the value and how to handle oversized files, see §Preconditions)
--typeand--auto-detectare mutually exclusive; exactly one must be passed; if neither is passed → the script errors out and prompts the agent to ask the user- manual / whitepaper / book only support the full style: the script automatically enables the
--fullstyle prompt loading (no need for the user to pass--full; for the full mode contract seereferences/full-mode-contract.md) - manual / whitepaper / book + paper full do not extract original images: automatically enables
--no-figures(script INFO notice) - paper quick mode image handling: follows gemini-paper-summary's three-layer localization (Stage 2 visual localization + caption locator + bbox hint); if all fail, delete the entire image + strip the corresponding sentence
- paper quick mode image reference identification: the line text must be in the form
Figure N[.:]+ description to count as a caption; height sanity check 250pt threshold; seereferences/figure-extraction.md
Workflow / Steps
A. agent calls within the session (recommended flow)
⚠️ Before calling the script: PDF topic confirmation (2026-07-07 pitfall report §1.2 hardening)
If the user-provided PDF metadata isincomplete(only a filename/abbreviation, such as
ART-ICDE'13.pdf), the agent must, before calling the script,at minimum usepdftotext -f 1 -l 2or the Read tool to extract the PDF's first two pages to confirm the paper topic, avoiding guessing about the PDF content (pitfall case: the user passedART-ICDE'13.pdf, the agent directly guessed it as "ART: A Feature Selection Method for an lcde Classification Rule Induction Algorithm"——rough sets + ant colony + feature selection; the actual PDF is "The Adaptive Radix Tree: ARTful Indexing for Main-Memory Databases", both are ICDE 2013 + both contain "ART" but are completely different papers).Judgment criterion: a 3-letter abbreviation has N meanings across different fields (Adaptive Radix Tree / Average Run Time / Ant-based Rule Tuning, etc.), so never guess from the filename/first few words of the title.
Step 1 — Three-way clarification of type + split method + output path(Critical: the script strictly requires it):
1. 用户说"总结这个 PDF" / agent 拿到本地 .pdf 文件
2. 如果用户已说明类型("这是产品手册"/"这是白皮书"/"这是论文"/"这是书") → 直接传 --type
3. 如果用户没说 / agent 无法确定 → 反问用户:
"这份 PDF 属于哪种类型?
- paper - 学术论文
- manual - 产品手册 / datasheet / 用户手册
- whitepaper - 行业 / 技术 / vendor 白皮书
- book - 书籍 / 长篇技术文档
或者让我用 --auto-detect 自动识别"
4. 用户回答后传 --type <answer>
Step 1b — Split method clarification(Critical: only takes effect in --by-chapter mode):
1. 跑 --by-chapter 前,agent 必须反问拆法(**禁止 agent 拍板粒度**——粒度差异
直接决定产物文件数 + 后续 ingest 路径):
"希望按什么粒度拆?
- L1 (默认): 按 PDF 原生 L1 章 N 次独立调用 + L2 子节合并进 L1。
产物少、撞 token 限概率近 0、自带 File API 缓存。
例:98 页白皮书 14 个 L1 章 → 14 个 .md
- auto: 单次 API 调用,Gemini 自决粒度。仅适用 ≤ 50 页短 PDF。
例:98 页白皮书 1 次调用 → 35%+ 章节截断(不推荐长 PDF)"
2. 用户回答后传 --granularity <L1|auto>(默认 L1,不传走 L1)
3. **不**反问场景:用户已说"按章节拆"未指定粒度 → agent 仍需反问要 L1 还是 auto
("按章节"是模糊诉求;体验教训:98 页白皮书直接拆出 118 个细粒度 .md,
后续合并丢数据)
Step 2 — Output path + slug clarification(Critical: avoid writing to the wrong location + slug overreach):
1. 如果用户已说明输出位置("落到 raw/manuals/foo/")→ 直接传 --output
2. 如果用户没说 → 反问用户:
"输出到哪个路径?建议:
- 落到 llm-wiki 的 raw 端:<wiki-root>/raw/<type>/<slug>/
- 落到临时目录:~/tmp/<slug>/
- 打印到 stdout(仅纯文字速读用,不导出图)"
3. 用户回答后传 --output <answer>
4. **slug 反问(必做,2026-07-07 踩坑报告 §1.1 加固)**:slug 是 raw 仓里这份产物的
**唯一持久标识**——决定后续 `ingest_diff.py` 找不找得到、跨页交叉引用怎么写、
按作者检索能不能命中。**agent 不得替用户拍板**,给 3-4 个候选让用户选:
"slug 用哪个?它是产物在 wiki 仓里的唯一持久标识,直接影响后续 ingest:
- <slug-from-pdf-filename> # 默认推断(如 ART-ICDE'13.pdf → art-icde-13)
- <author-year 形式,如 art-icde13>
- <短标题形式,如 art-radix-tree>
- 其它,我来告诉你"
收到用户回答后:
- 传 --slug <answer>(避免被脚本 slugify 改写,如 baz13 → baz-13)
- 或传 --output <dir>/<slug>.full.md(--output 以 .md 结尾时 slug 自动取自该路径 stem)
Why the agent must ask:
- The 4 document types correspond to different output layouts (
raw/papers//raw/manuals//raw/whitepapers//raw/books/)——if the agent makes the decision for the user, it easily lands in the wrong directory, and the subsequentyzr-llm-wiki-management'singest_diff.pycannot find the output, so the run is wasted.- The slug needs the user's decision even more than the path does: if the path is wrong, just change
mvand it's fine; if the slug is wrong, thewiki/sources/<slug>.mdwritten by subsequent ingest + all cross-references will be mismatched, and you'll have to manually rename + fix the reference chain.The Agent must not go ahead using a slug inferred from the PDF filename(pitfall case: the user uploadedART-ICDE'13.pdf, the agent directly concatenatedart-feature-selection-icde13, but the actual PDF was a completely different paper; the user ultimately choseart-icde13)。
Step 3 — Call the script:
1. 确认 PDF 存在且可读
2. 确认 GEMINI_API_KEY 已设置;未设置则提示用户去 aistudio.google.com/apikey 申请
3. 确认 google-genai 已安装:python3 -c "import google.genai" 或 pip install -U google-genai
4. 调用 scripts/gemini_pdf_summary.py:
paper full(--output 两种合法形态,踩坑报告 §2.1 已修复,二选一即可):
形态 1:--output 是 .md 文件路径 → 直接落该文件(mkdir 父目录)
python3 yzr-gemini-pdf-summary/scripts/gemini_pdf_summary.py \
--pdf <path> \
--type paper \
--full \
--output /path/to/<wiki-root>/raw/papers/<slug>/<slug>.full.md \
--force-full
形态 2:--output 是 wiki 仓根(目录) → 产物落 <wiki-root>/raw/papers/<slug>.full.md
python3 yzr-gemini-pdf-summary/scripts/gemini_pdf_summary.py \
--pdf <path> \
--type paper \
--full \
--output /path/to/<wiki-root>/ # 注意:无 .md 后缀,目录路径
--force-full
(修复前踩坑案例: --output 以 .md 结尾 + 路径是文件时,早期脚本会建
<output>.md/raw/papers/<slug>.full.md 嵌套;现已直接落该 .md 文件。)
paper quick 默认带图 + Stage 2 视觉定位(--refine-figures 默认开),保证图质量;
--no-figures 关闭图导出:
python3 yzr-gemini-pdf-summary/scripts/gemini_pdf_summary.py \
--pdf <path> \
--type paper \
--output <output-dir> # paper quick 默认是目录(写 summary.md + figures/)
# --no-figures 时 --output 可传 .md 文件路径
by-chapter 模式(默认 L1, 2026-07-06 起):
python3 yzr-gemini-pdf-summary/scripts/gemini_pdf_summary.py \
--pdf <path> \
--type <type> \
--by-chapter \
--granularity L1 # 默认;可省略;长 PDF 首选
# --granularity auto # 单次调用,仅 ≤ 50 页短 PDF
--output <output-dir> # by-chapter --output 总是目录,写 00-index.md + 各 L1 .md
# L1 模式产物:<output>/00-index.md + N_L1 个 <NN>-<L1-slug>.md
5. 把生成的 Markdown 总结(含图)呈现给用户
6. 标注所用模型与 PDF 文件名
7. 失败处理(重要):若第 4 步脚本抛 RuntimeError(503/429/5xx 重试耗尽),
agent 不得自行加 --model 换便宜模型重跑——把错误原文 + 三步建议如实
呈现给用户并停下,换不换模型由用户决定(见 §核心原则 #8 端到端不降级)
8. by-chapter 失败处理:L1 模式下若个别 L1 章失败,脚本写 FAILED-<slug>.md
占位 + 继续后续 L1(不中断);00-index.md 标 ⚠FAILED 指向失败项;agent 可
单独用 --pages <失败页范围> --granularity auto 重跑失败段。
You can also call the SDK directly in the session (for API details see references/api-quickstart.md)。
Safety guidelines for post-hoc cleanup after artifacts are written to disk (hardened per the 2026-07-07 pitfall report §1.3)
The script's raw-compatible layout (
wiki-root/raw/papers/<slug>.full.md, etc.) may leave unexpected nesting / empty wrapper directories in the following situations;the agent must follow these when manually cleaning up:
- Do not use
rm -rf——mv src dst/whendstis an already-existing directory, as it will move things in-place, and the immediately followingrm -rf dstwill delete the just-moved contents along with it.Only usermdirto delete empty directories level by level。- Before each step,
lsverify: before deleting, firstls -la <dir>to see what's inside; if it's not empty, don't delete.- Confirm it's empty before deleting:
test -d "$d" && [ -z "$(ls -A "$d")" ](double-layer check to avoid deleting a non-empty directory).Safe cleanup template (move nested artifacts to the correct location):
SRC=<嵌套路径>/raw/papers/<slug>.full.md DST_DIR=<期望目录> mv "$SRC" "$DST_DIR/<slug>.full.md" # mv 目标写死文件名,不要传目录 rmdir "$DST_DIR/raw/papers" 2>/dev/null # 仅删空目录 rmdir "$DST_DIR/raw" 2>/dev/null # 最后 ls -la "$DST_DIR" 确认只有期望的文件
- (after the 2026-07-07 fix) when paper full,
--outputending with.mdalreadywrites that file directly, and will no longer produce<output>.md/raw/papers/<slug>.full.mdnesting — the safety guidelines in this section are only for defense; the new script does not require manual cleanup.
B. auto-detect (when the type is uncertain)
python3 yzr-gemini-pdf-summary/scripts/gemini_pdf_summary.py \
--pdf unknown.pdf \
--auto-detect \
--output raw/manuals/foo/ # 类型识别后产物仍落用户指定目录
auto-detect flow(see references/auto-detect.md):
- Read PDF metadata (Title / Subject / Keywords / Producer) + first-page text
- Local heuristic scoring (KEYWORD_HINTS table) → return directly if high confidence; otherwise proceed to 3
- Render pages 1-3 of the first pages to Gemini for multimodal recognition → return paper / manual / whitepaper / book
On failure (insufficient heuristics + Gemini verification exception): report an error + 4 candidate types + suggest the user explicitly pass --type。
C. 4 output templates (the chapter skeleton SSOT is in assets/template-*.md)
For the complete templates and figure reference conventions see assets/template-{paper,manual,whitepaper,book}.md。
Any template change only requires modifying the corresponding template-<type>.md; SKILL.md does not copy it again to avoid scattering.
The chapter skeleton blocks for the 4 document types and 5 reference examples have been delegated to
references/output-skeletons-and-examples.md
— this section only points out the "consumer" difference for each type (humans reading vs LLMs reading); for the detailed skeletons and examples, just read that file.
D. Handoff with yzr-llm-wiki-management
This skill only produces local files— manual / whitepaper / book never extract original figures throughout; paper full / book are self-contained; paper quick includes figures by default (PNG). Uploading to outline-wiki is not managed by this skill。
End-to-end workflow (PDF → wiki accumulation):
1. 本 skill:跑 gemini_pdf_summary.py --type <type> --output <dir>
产出 <dir>/summary.md(paper quick 同时含 figures/*.png)
2. 把产物复制到 <wiki-root>/raw/<type>/<slug>/(保持 llm-wiki 仓布局)
3. yzr-llm-wiki-management:跑 ingest_diff.py 发现 raw 新增
→ 生成 wiki/sources/<slug>.md(含 frontmatter type: source + sources 字段指向 raw 路径)
→ 同步 entity / concept 页(如有)
→ 更新 index.md + log.md
Anti-patterns(Don'tdo this):
- Writing the PDF summary directly into an outline-wiki document instead ofnotGo through wiki ingest — loses the source page frontmatter and cross-references
- Place the artifact in a directory that does not match
--type(e.g.--type manualbut it lands inraw/papers/) — ingest_diff cannot find it (Note:raw/papers/is used in this line only as a counterexample and does not represent the layout standard; for the 4 layout types see §Workflow §A Step 2 follow-up prompts) - Assume this skill willautomaticallypush to outline-wiki —it will not, this skill only goes as far as local
E. Troubleshooting
| Symptom | Cause | Resolution |
|---|---|---|
ModuleNotFoundError: google.genai |
SDK not installed | pip install --user --break-system-packages google-genai |
import fitz fails / pymupdf missing |
pymupdf not installed | pip install --user --break-system-packages pymupdf |
DefaultCredentialsError / api_key not set |
Missing GEMINI_API_KEY |
export GEMINI_API_KEY=... or .env + direnv |
400 INVALID_ARGUMENT + mime type errors |
PDF corrupted / encrypted / not a PDF header | Use file <pdf> to verify; decrypt or re-download |
413 REQUEST_TOO_LARGE |
PDF over 50 MB | Upload via File API (see references/api-quickstart.md §Oversized PDF) |
必须传 --type 或 --auto-detect 二者之一 |
Call missing type | agent asks the user to confirm the type (see §Workflow §A) |
--auto-detect cannot be determined by either |
Both heuristics + Gemini have insufficient confidence | Explicitly pass --type <paper|manual|whitepaper|book> |
book 类型仅支持 full 模式 |
Attempting --type book without --full |
Add --full, or switch to the paper type |
manual / whitepaper / book 仅支持 full 风格 |
Attempting --type manual etc. then passing --no-figures to disable mermaid |
Disable --no-figures; manual / whitepaper / book are full style and do not accept a "compressed summary" mode |
| Model 404 | Model name misspelled or deprecated | Use gemini-api-docs-mcp 's get_current_model to check currently available models |
Ran successfully with a deprecated model (gemini-2.5-*) but it is about to shut down |
The model still works but is deprecated | Migrate to gemini-3.1-pro-preview(default) or gemini-3.5-flash / gemini-3.1-flash-lite |
| Output character count far exceeds the target declared in the prompt | Gemini does not strictly follow the prompt's character count constraint | First adjust the prompt (specific values in assets/template-*.md)/ --focus; post-process trimming |
| Output empty / truncated | Hit the output token limit | paper quick → adjust the prompt character target (SSOT see assets/template-paper.md)/ --focus; full / book truncated at the end → mostly the model did not faithfully transcribe, switch models and rerun or split the book;--by-chapter last chapter truncated → already the pro-preview default, use --pages to split into segments and rerun the last segment (see references/full-mode-contract.md §by-chapter) |
--by-chapter and --full are mutually exclusive |
Passed both --by-chapter --full |
Choose one:--full goes through paper full single artifact (.full.md);--by-chapter goes through N API calls splitting into N .md files by L1 chapter (default L1) |
--by-chapter --granularity auto + PDF > 50 pages + no --pages |
A single API call hits the FULL_MAX_OUTPUT_TOKENS limit → last chapter truncated (measured 35%+) |
Switch to --granularity L1(default): N independent calls by native PDF L1 chapter, probability of hitting the limit per chapter ≤ 50 pages is near 0 |
--by-chapter --granularity L1 + --pages |
L1 mode splits pages automatically by chapter,--pages incompatible |
Delete --pages; L1 mode automatically splits by native PDF L1 chapter boundaries. To split by custom page ranges → switch to --granularity auto |
| L1 mode missing pymupdf | --granularity L1 requires PyMuPDF to read TOC + split pages |
pip install --user --break-system-packages pymupdf; or change to --granularity auto to use a single call (no pymupdf needed) |
| L1 mode PDF has no TOC | PDF has no embedded bookmarks / outline | Script automatically falls back to --granularity auto(stderr WARN message); if strict L1 splitting is needed → add bookmarks when regenerating the PDF |
| L1 mode: a certain L1 chapter failed | The API call for that L1 page range threw an error (API rate limiting / PDF corruption, etc.) | Script writes FAILED-<slug>.md placeholder + continues with subsequent L1; agent can separately --pages <失败页范围> --granularity auto rerun |
| L1 mode File API upload failed | When PDF > 20MB, L1 mode relies on File API caching | Script directly throws an error (does not silently fall back to inline — inline cannot be reused across calls); handling: 1) Retry 2) --granularity auto use a single call 3) Shrink the PDF |
In by-chapter output, < 100B empty file appears |
Chapter abandoned by the model (truncation / missing content) | Script automatically cleans up + stderr WARN number (00-index.md still contains the original reference; manually delete or rerun if necessary) |
503 UNAVAILABLE / 429 RESOURCE_EXHAUSTED Still fails after 3 retries |
Primary model temporarily unavailable / rate limited | No end-to-end degradation—— script directly throws an error (including model name + status + three-step suggestion);upon receiving this error, the agent must not switch models and rerun on its own, must truthfully report to the user, and let the user decide whether to --model explicitly retry |
In the generated md,  reference appears |
non-paper type or paper full mode output | Automatic handling: script strip_pdf_figure_refs cleans up at the end of main; if it appears, it means the prompt was missed in the change |
Reference examples
5 end-to-end examples (single paper / product manual / whitepaper / book / auto-detect) have been moved down to
references/output-skeletons-and-examples.md §Reference examples
——each example includes "user's original words → agent's follow-up question → final bash call + output description".
Companion references
- 4 template skeletons + reference examples:
references/output-skeletons-and-examples.md—— the lower layer of SKILL.md §C / §Reference examples (chapter skeleton blocks + 5 end-to-end examples) - Shared basic conventions:
assets/_base.md—— API calls / style baseline / character count discipline / chart handling rules shared by the 4 template types - paper quick + full template:
assets/template-paper.md - manual template:
assets/template-manual.md - whitepaper template:
assets/template-whitepaper.md - book template:
assets/template-book.md - API quick start:
references/api-quickstart.md—— examples for calling the SDK directly + File API approach for very large PDFs - auto-detect implementation details:
references/auto-detect.md—— heuristic keyword table + Gemini verification process + failure fallback - paper quick image export:
references/figure-extraction.md—— Stage 1/2 + caption locator + bbox sanity check - Stage 2 / image size / thumbnail parameters:
references/figure-processing.md——--refine-figures/--figure-dpi/--thumbnailand other detailed specifications - 4-type template comparison quick reference:
references/templates.md— dimension comparison table / template change rules / checklist for adding new types - paper full contract:
references/full-mode-contract.md——--fullmode's output constraints / integrity validation / token budget
Prerequisites
1. Python ≥ 3.7
2. pip install -U google-genai
3. pip install --user --break-system-packages pymupdf # paper quick 图导出 / auto-detect 需要
4. export GEMINI_API_KEY="你的 key" # 在 https://aistudio.google.com/apikey 创建