Skip to content

知らない分野を、原文にたどりつくまで芋づる式に掘る Claude Code のスキル

Python

fetch: PMC は Europe PMC の全文 XML から取り、JATS を行ごとの .md にする

服部真弓73188fab3f40
diff --git a/skills/imozuru/SKILL.md b/skills/imozuru/SKILL.md
index 782f919..c0968a7 100644
--- a/skills/imozuru/SKILL.md
+++ b/skills/imozuru/SKILL.md
@@ -225,7 +225,7 @@ map.md を下の書式で作り、**問い**と、答えるのに要る**主張*
スクリプトは Python 3.10 以上の標準ライブラリだけで動く。外部コマンドは、あれば使う(無いときの動きは各行に書いた)。
-- `scripts/fetch.py <sources_dir> <name> <url>` — ダウンロードして本物か確かめる。PDF は .pdf と .txt(`pdftotext -layout`・poppler か Xpdf)、HTML は .md、YouTube は字幕を `[分:秒] 文` の .md(`yt-dlp`・動画は保存しない)。文字の層が無い PDF は `pdftoppm` と `tesseract` で OCR する。言語は tesseract の言語データに `jpn`・`jpn_vert` があれば英語に足し、環境変数 `IMOZURU_OCR_LANG` があればそれを使う。読み取りの確信度が低いとき(言語データが合わず意味のない字の列になったとき)と、読めなかったページがあるときは OCR の結果を使わず、理由を添えて `FAIL` する。要るコマンドが無いときは、無いコマンドの名前を書いて `FAIL` する。HTML は [ax](https://github.com/yusukebe/ax) があれば ax で、無ければ標準ライブラリで本文を文字にする(見出しや表の形は ax のほうが残る)。取得はいつも fetch.py 自身が宛先を確かめながら行い、ax には取ってきた HTML を渡して変換だけさせる。HTML のページは、名乗りを変えてもう一度頼み、PDF 本体が返ればそちらを残す(HAL はブラウザの名乗りに閲覧用の HTML を返す)。取ってきたものは作業用のフォルダで検査し、通ったものだけを sources_dir へ移す。404・ログインの要求・短すぎる本文は `FAIL`(同じ名前の原文がすでにあれば、そのまま残る)。短さの下限は PDF が 3,000字、HTML が 1,000字で、和文の字が3割を超える PDF は HTML と同じ 1,000字で判定する。X は本文が取れないので取りに行かず `FAIL`=URL と、検索役が拾った抜粋を(未確認)で map.md に残す
+- `scripts/fetch.py <sources_dir> <name> <url>` — ダウンロードして本物か確かめる。PDF は .pdf と .txt(`pdftotext -layout`・poppler か Xpdf)、HTML は .md、YouTube は字幕を `[分:秒] 文` の .md(`yt-dlp`・動画は保存しない)。文字の層が無い PDF は `pdftoppm` と `tesseract` で OCR する。言語は tesseract の言語データに `jpn`・`jpn_vert` があれば英語に足し、環境変数 `IMOZURU_OCR_LANG` があればそれを使う。読み取りの確信度が低いとき(言語データが合わず意味のない字の列になったとき)と、読めなかったページがあるときは OCR の結果を使わず、理由を添えて `FAIL` する。要るコマンドが無いときは、無いコマンドの名前を書いて `FAIL` する。HTML は [ax](https://github.com/yusukebe/ax) があれば ax で、無ければ標準ライブラリで本文を文字にする(見出しや表の形は ax のほうが残る)。取得はいつも fetch.py 自身が宛先を確かめながら行い、ax には取ってきた HTML を渡して変換だけさせる。HTML のページは、名乗りを変えてもう一度頼み、PDF 本体が返ればそちらを残す(HAL はブラウザの名乗りに閲覧用の HTML を返す)。取ってきたものは作業用のフォルダで検査し、通ったものだけを sources_dir へ移す。PMC(pmc.ncbi.nlm.nih.gov)の記事ページは captcha で取れないので、同じ本文を Europe PMC の全文 XML から取り、見出し・段落・図表の説明・文献を1つずつ1行にした .md にする(題名と書誌は頭の数行。Europe PMC に全文が無ければ `FAIL`)。404・ログインの要求・ボット確認のページ・短すぎる本文は `FAIL`(同じ名前の原文がすでにあれば、そのまま残る)。短さの下限は PDF が 3,000字、HTML が 1,000字で、和文の字が3割を超える PDF は HTML と同じ 1,000字で判定する。X は本文が取れないので取りに行かず `FAIL`=URL と、検索役が拾った抜粋を(未確認)で map.md に残す
- 動画の場所は行番号の代わりに時刻で指す(`sources/x.md [12:34]`)
- `scripts/report.py <topic_dir> [--check]` — extracts.json の抜き書きを原文と照合し、合えば report.html にする。`--check` は照合だけ
- `scripts/watch.py add|list|check` — 見張り。RSS / Atom を引いて前回からの新着を出す。検索を使わないので費用はかからず結果も揺れない。DOCTYPE・ENTITY を含むフィードは安全のため読まない。フィードの場所にタブや改行が入っていたら足さない
diff --git a/skills/imozuru/scripts/fetch.py b/skills/imozuru/scripts/fetch.py
index 4dfb893..9c20ae5 100755
--- a/skills/imozuru/scripts/fetch.py
+++ b/skills/imozuru/scripts/fetch.py
@@ -7,7 +7,8 @@
論文だけでなく個人の発信も落とす。YouTube は字幕を `[分:秒] 文` の形で
.md にする(場所を時刻で指せるように)。X はログインの壁で本文が取れないので、
-取りに行かずに FAIL を返す。
+取りに行かずに FAIL を返す。PMC の記事ページは captcha で取れないので、
+同じ本文を Europe PMC の全文 XML から取り、見出し・段落ごとの行の .md にする。
使い方:
fetch.py <sources_dir> <name> <url>
@@ -28,6 +29,7 @@ import sys
import tempfile
import urllib.parse
import urllib.request
+import xml.etree.ElementTree as ET
from html.parser import HTMLParser
from pathlib import Path
@@ -673,6 +675,145 @@ def youtube_to_md(url: str, out: Path) -> str:
return body
+PMC_PATHS = {"pmc.ncbi.nlm.nih.gov": r"/articles/(PMC\d+)", "www.ncbi.nlm.nih.gov": r"/pmc/articles/(PMC\d+)",
+ "europepmc.org": r"/article/PMC/(PMC\d+)"}
+
+
+def pmc_id(url: str) -> str | None:
+ """PMC の記事の URL なら PMCID を返す。arxiv_id と同じく、URL のどこかではなくホスト名とパスで見る。"""
+ p = urllib.parse.urlsplit(url)
+ pattern = PMC_PATHS.get((p.hostname or "").lower().rstrip("."))
+ m = re.match(pattern, p.path, re.I) if pattern else None
+ return m.group(1).upper() if m else None
+
+
+EUROPE_PMC_XML = "https://www.ebi.ac.uk/europepmc/webservices/rest/{}/fullTextXML"
+_XLINK_HREF = "{http://www.w3.org/1999/xlink}href"
+# 段落の中の飾りや参照。前後に空白を足すと「Smith et al. ( 2020 )」のように崩れるので、そのままつなぐ
+_JATS_INLINE = {"italic", "bold", "sup", "sub", "sc", "underline", "monospace", "roman", "strike",
+ "overline", "xref", "ext-link", "uri", "named-content", "styled-content",
+ "inline-formula", "abbrev"}
+# 本文の文字ではないもの(図の差し替え用の説明や ID)
+_JATS_SKIP = {"alt-text", "object-id", "graphic", "inline-graphic", "media"}
+# 見出しを持つ入れ物。title が無ければ下の既定の見出しを使う(無いものは見出しなしで中へ)
+_JATS_SECTIONS = {"sec": "", "abstract": "Abstract", "trans-abstract": "Abstract", "ack": "Acknowledgements",
+ "app": "Appendix", "ref-list": "References", "glossary": "Glossary", "boxed-text": ""}
+
+
+def _local(tag) -> str:
+ return tag.rsplit("}", 1)[-1] if isinstance(tag, str) else ""
+
+
+def _jats_raw(el) -> str:
+ parts = [el.text or ""]
+ for child in el:
+ tag = _local(child.tag)
+ if tag in _JATS_SKIP:
+ inner = ""
+ elif tag == "alternatives":
+ # 同じ式が TeX・MathML・画像で並ぶ。読める TeX を1つだけ残す
+ kids = list(child)
+ pick = next((k for k in kids if _local(k.tag) == "tex-math"), kids[0] if kids else None)
+ inner = _jats_raw(pick) if pick is not None else ""
+ else:
+ inner = _jats_raw(child).strip()
+ href = child.get(_XLINK_HREF)
+ if tag in ("ext-link", "uri") and href and href != inner:
+ inner = f"[{inner}]({href})" # HTML と同じく、後ろへたどれるようにリンクを残す
+ parts.append(inner if tag in _JATS_INLINE else f" {inner} ")
+ parts.append(child.tail or "")
+ return "".join(parts)
+
+
+def _jats_flat(el) -> str:
+ """要素の文字を1行にする。文献の <surname>Smith</surname><given-names>J</given-names> も語の間を空ける。"""
+ if el is None:
+ return ""
+ text = " ".join(_jats_raw(el).split())
+ return re.sub(r"([(\[])\s+", r"\1", re.sub(r"\s+([,.;:)\]])", r"\1", text))
+
+
+def _jats_blocks(el, level: int, out: list[str]) -> None:
+ """本文の入れ物をたどり、見出しは1行、段落・図表の説明・文献は1つずつ1行にする。"""
+ for child in el:
+ tag = _local(child.tag)
+ if tag in ("title", "label") or tag in _JATS_SKIP:
+ continue # 見出しは親が書く
+ if tag in _JATS_SECTIONS:
+ title = _jats_flat(child.find("title")) or _JATS_SECTIONS[tag]
+ label = _jats_flat(child.find("label"))
+ if title:
+ out += ["", "#" * min(level, 6) + " " + " ".join(filter(None, [label, title])), ""]
+ _jats_blocks(child, level + 1 if title else level, out)
+ elif tag in ("p", "disp-formula", "disp-quote", "def-item", "fn", "statement"):
+ line = _jats_flat(child)
+ if line:
+ out.append(line)
+ elif tag in ("list",):
+ out += ["- " + _jats_flat(item) for item in child if _local(item.tag) == "list-item"]
+ elif tag in ("fig", "table-wrap", "supplementary-material"):
+ label = _jats_flat(child.find("label")) or {"fig": "図", "table-wrap": "表"}.get(tag, "補足")
+ caption = _jats_flat(child.find("caption"))
+ out.append(f"[{label}] {caption}".rstrip())
+ for row in child.iter():
+ if _local(row.tag) == "tr":
+ out.append(" | ".join(_jats_flat(cell) for cell in row))
+ for foot in child.findall("table-wrap-foot"):
+ _jats_blocks(foot, level, out)
+ elif tag == "ref":
+ label = _jats_flat(child.find("label"))
+ cites = [c for c in child if _local(c.tag) != "label"]
+ text = " ".join(_jats_flat(c) for c in cites)
+ doi = next((p.text for p in child.iter() if _local(p.tag) == "pub-id"
+ and p.get("pub-id-type") == "doi" and p.text), None)
+ if doi and f"doi.org/{doi.strip()}" not in text:
+ text += f" https://doi.org/{doi.strip()}"
+ out.append(" ".join(filter(None, [f"[{label}]" if label else "", text])))
+ else:
+ _jats_blocks(child, level, out) # body・back・fn-group・notes などはそのまま中へ
+
+
+def jats_to_md(xml: bytes, url: str, xml_url: str) -> str:
+ """Europe PMC の全文 XML(JATS)を、見出し・段落ごとの行にした markdown にする。要約はしない。
+
+ XML をそのまま文字にすると、雑誌名・ID・著者が区切りなく1行目につながって読めなかった
+ (2026-10-19 の試しで Dully 2021 など)。題名と書誌は頭の数行にまとめ、本文は行番号で指せる形にする。
+ """
+ # JATS は DOCTYPE を必ず持つので watch.py のように DOCTYPE ごとは断れない。外部の DTD は expat が
+ # 取りに行かないので害は無い。膨らむ実体(billion laughs)だけは中で宣言されるので、それを断る
+ if b"<!ENTITY" in xml:
+ raise ValueError("XML が ENTITY を宣言している")
+ root = ET.fromstring(xml)
+ meta = root.find("front/article-meta")
+ if meta is None:
+ meta = ET.Element("article-meta")
+ journal = _jats_flat(root.find("front/journal-meta/journal-title-group/journal-title"))
+ year = next((y.text for y in meta.iter("year") if y.text), "")
+ ids = {a.get("pub-id-type"): (a.text or "").strip() for a in meta.findall("article-id")}
+ authors = []
+ for contrib in meta.iter("contrib"):
+ if contrib.get("contrib-type") != "author":
+ continue
+ name = contrib.find("name")
+ authors.append(" ".join(filter(None, [_jats_flat(name.find("given-names")),
+ _jats_flat(name.find("surname"))]))
+ if name is not None else _jats_flat(contrib.find("collab")))
+ out = [f"# {_jats_flat(meta.find('title-group/article-title')) or url}", "", url,
+ f"本文: Europe PMC の全文 XML({xml_url})",
+ " / ".join(filter(None, [journal, year, ids.get("doi") and f"https://doi.org/{ids['doi']}",
+ ids.get("pmcid")])),
+ "著者: " + ", ".join(a for a in authors if a)]
+ keywords = [_jats_flat(k) for k in meta.iter("kwd")]
+ if keywords:
+ out.append("キーワード: " + ", ".join(keywords))
+ # 要旨は article-meta の中にあるので、見出しつきの節として本文・巻末と同じ流れに乗せる
+ parts = ET.Element("article")
+ parts.extend([*meta.findall("abstract"), *meta.findall("trans-abstract"),
+ *(n for n in (root.find("body"), root.find("back")) if n is not None)])
+ _jats_blocks(parts, 2, out)
+ return re.sub(r"\n{3,}", "\n\n", "\n".join(out)).strip() + "\n"
+
+
def clean(s: str) -> str:
"""端末に出す文字列から、制御文字(色やクリップボードを操る ESC の並び)と改行の仲間を空白にする。
@@ -745,6 +886,21 @@ def fetch_source(sources: Path, name: str, url: str, destination: Path) -> int:
print(f"OK\t{name}\t{kept}\t{len(body)}\t{first_line(body)}")
return 0
+ pmc = pmc_id(url)
+ if pmc:
+ # PMC の記事ページは urllib には captcha を返す(2026-10-19)。同じ本文を Europe PMC が
+ # 公開の API で全文 XML として配っているので、そちらを正規の別ルートとして取る
+ xml_url = EUROPE_PMC_XML.format(pmc)
+ try:
+ text = jats_to_md(download(xml_url)[0], url, xml_url)
+ except Exception as e: # 全文が無い(OA でない)と 404 などが返る。XML が壊れていても同じく取れない
+ print(f"FAIL\t{name}\tEurope PMC に全文 XML が無い({type(e).__name__}: {clean(str(e))})。"
+ "PMC は captcha なので、ブラウザで開いてもらう候補")
+ return 1
+ kept = saved = sources / f"{name}.md"
+ kept.write_text(text, encoding="utf-8")
+ return verify_and_save(name, text, saved, kept, destination)
+
try:
body, ctype = download(url)
except Exception as e: # HTTP エラーも接続失敗も、呼び手にとっては同じ「取れない」
@@ -826,6 +982,12 @@ def fetch_source(sources: Path, name: str, url: str, destination: Path) -> int:
else:
trial.unlink(missing_ok=True)
+ return verify_and_save(name, text, saved, kept, destination, ocr_note)
+
+
+def verify_and_save(name: str, text: str, saved: Path, kept: Path, destination: Path,
+ ocr_note: str = "") -> int:
+ """短すぎる本文と壁を FAIL にし、通ったものだけを保存先に移して OK を出す。"""
# PDF は英語の論文を基準に高い下限。和文の PDF だけは HTML と同じ下限にする
floor = MIN_TEXT_CHARS if saved.suffix == ".pdf" and not mostly_cjk(text) else MIN_HTML_CHARS
head = text[:4000].lower()
diff --git a/tests/test_fetch.py b/tests/test_fetch.py
index 7ebfa9d..1e8343f 100644
--- a/tests/test_fetch.py
+++ b/tests/test_fetch.py
@@ -231,6 +231,85 @@ class FetchPreservationTests(unittest.TestCase):
self.assertIn(f"OK\tpaper\t{target}\t", self.stdout.getvalue())
self.assertFalse(any(p.is_dir() for p in self.sources.iterdir()))
+ def test_bot_check_page_is_a_wall(self):
+ # HAL(hal.science)の Anubis が返した 1,297 字のページ。壁の文に掛かることを確かめる
+ self.seed(".md")
+ before = self.snapshot()
+ body = (b"<html><head><title>Making sure you&#39;re not a bot!</title></head><body>"
+ b"<h1>Making sure you're not a bot!</h1><p>Loading...</p><p>You are seeing this because "
+ b"the administrator of this website has set up Anubis to protect the server.</p>"
+ + b"<p>Anubis is a compromise. Anubis uses a Proof-of-Work scheme.</p>" * 20
+ + b"</body></html>")
+ with patch.object(fetch, "download", return_value=(body, "text/html")):
+ self.assertEqual(self.run_fetch("https://hal.science/hal-01577896"), 1)
+ self.assertIn("FAIL\tpaper\t壁に当たった(you're not a bot)", self.stdout.getvalue())
+ self.assert_preserved(before)
+
+ JATS = """<?xml version="1.0"?>
+<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.4//EN" "JATS.dtd">
+<article xmlns:xlink="http://www.w3.org/1999/xlink"><front>
+<journal-meta><journal-title-group><journal-title>Mol Ecol</journal-title></journal-title-group></journal-meta>
+<article-meta><article-id pub-id-type="pmcid">PMC1234567</article-id>
+<article-id pub-id-type="doi">10.1111/mec.1</article-id>
+<title-group><article-title>Environmental <italic>DNA</italic> for biomonitoring</article-title></title-group>
+<contrib-group><contrib contrib-type="author"><name><surname>Pawlowski</surname><given-names>Jan</given-names></name></contrib></contrib-group>
+<pub-date><year>2021</year></pub-date>
+<abstract><p>Short abstract text.</p></abstract></article-meta></front>
+<body><sec><title>Introduction</title><p>First paragraph (<xref ref-type="bibr" rid="r1">Smith, 2020</xref>).</p>
+<p>Second paragraph with a <ext-link xlink:href="https://example.org/data">dataset</ext-link>.</p>
+<sec><title>Sub section</title><p>Nested paragraph.</p></sec></sec>
+<sec><title>Results</title><p>{filler}</p>
+<fig><label>Figure 1</label><caption><p>Caption of the figure.</p></caption><graphic xlink:href="f1.jpg"/></fig></sec></body>
+<back><ref-list><title>References</title><ref><label>1</label><element-citation><person-group>
+<name><surname>Smith</surname><given-names>J</given-names></name></person-group>
+<article-title>A paper</article-title><source>Nature</source><year>2020</year>
+<pub-id pub-id-type="doi">10.1038/x</pub-id></element-citation></ref></ref-list></back></article>
+""".replace("{filler}", "Results text. " * 100)
+
+ def test_pmc_url_is_fetched_from_europe_pmc_as_lines(self):
+ self.seed(".md")
+ with patch.object(fetch, "download", return_value=(self.JATS.encode(), "application/xml")) as dl:
+ self.assertEqual(self.run_fetch("https://pmc.ncbi.nlm.nih.gov/articles/PMC1234567/"), 0)
+ self.assertEqual(dl.call_args.args[0],
+ "https://www.ebi.ac.uk/europepmc/webservices/rest/PMC1234567/fullTextXML")
+ lines = (self.sources / "paper.md").read_text(encoding="utf-8").splitlines()
+ # 1行目は題名だけ。雑誌名や ID がつながらない
+ self.assertEqual(lines[0], "# Environmental DNA for biomonitoring")
+ self.assertIn("Mol Ecol / 2021 / https://doi.org/10.1111/mec.1 / PMC1234567", lines)
+ self.assertIn("著者: Jan Pawlowski", lines)
+ for line in ("## Abstract", "Short abstract text.", "## Introduction",
+ "First paragraph (Smith, 2020).",
+ "Second paragraph with a [dataset](https://example.org/data).",
+ "### Sub section", "Nested paragraph.", "## Results",
+ "[Figure 1] Caption of the figure.", "## References",
+ "[1] Smith J A paper Nature 2020 10.1038/x https://doi.org/10.1038/x"):
+ self.assertIn(line, lines)
+ self.assertLess(lines.index("## Introduction"), lines.index("### Sub section"))
+ self.assertIn("OK\tpaper\t", self.stdout.getvalue())
+
+ def test_pmc_without_europe_pmc_full_text_fails_and_preserves(self):
+ self.seed(".md")
+ before = self.snapshot()
+ error = fetch.urllib.error.HTTPError("https://www.ebi.ac.uk/", 404, "Not Found", {}, None)
+ with patch.object(fetch, "download", side_effect=error):
+ self.assertEqual(self.run_fetch("https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7654321/"), 1)
+ self.assertIn("FAIL\tpaper\tEurope PMC に全文 XML が無い", self.stdout.getvalue())
+ self.assert_preserved(before)
+
+ def test_pmc_is_recognized_by_host_not_anywhere_in_url(self):
+ self.assertEqual(fetch.pmc_id("https://pmc.ncbi.nlm.nih.gov/articles/PMC1234567/"), "PMC1234567")
+ self.assertEqual(fetch.pmc_id("https://www.ncbi.nlm.nih.gov/pmc/articles/pmc1234567"), "PMC1234567")
+ self.assertEqual(fetch.pmc_id("https://europepmc.org/article/PMC/PMC1234567"), "PMC1234567")
+ # 他人のページの URL に書き込まれた PMCID の本文を、そのページの原文として保存しない
+ self.assertIsNone(fetch.pmc_id("https://evil.example/?next=pmc.ncbi.nlm.nih.gov/articles/PMC1234567/"))
+ self.assertIsNone(fetch.pmc_id("https://pmc.ncbi.nlm.nih.gov.evil.example/articles/PMC1234567/"))
+
+ def test_jats_with_entity_declaration_is_refused(self):
+ xml = b'<?xml version="1.0"?><!DOCTYPE a [<!ENTITY x "xx">]><article>&x;</article>'
+ with patch.object(fetch, "download", return_value=(xml, "application/xml")):
+ self.assertEqual(self.run_fetch("https://pmc.ncbi.nlm.nih.gov/articles/PMC1234567/"), 1)
+ self.assertIn("ENTITY", self.stdout.getvalue())
+
def test_failed_first_fetch_leaves_no_partial_source(self):
with patch.object(fetch, "download", return_value=(b"Short response", "text/plain")):
self.assertEqual(self.run_fetch(), 1)