|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Prep a growth-conditions deep-research sweep over CommunityMech records. |
| 3 | +
|
| 4 | +Companion to the `add-growth-conditions` skill. This script does the *deterministic* |
| 5 | +part of the whole-KB sweep so the (LLM) extraction agents get a ready source bundle |
| 6 | +instead of each re-fetching: |
| 7 | +
|
| 8 | + 1. Enumerate records that lack a `growth_media` (and `cultivation_setup`) block. |
| 9 | + 2. For each, pick the **primary reference** — the PMID/DOI cited most often in the |
| 10 | + record's evidence items. |
| 11 | + 3. Fetch the Europe PMC abstract and run the legal full-text **access ladder** |
| 12 | + (Europe PMC OA -> Unpaywall -> CORE; else an author-request draft) via |
| 13 | + `fulltext_access.py`. |
| 14 | + 4. Write one staging bundle per record under `reports/growth_conditions_sweep/` |
| 15 | + (abstract + access verdict + full-text URL to fetch Methods from, or the |
| 16 | + author-request draft) and an `INDEX.md` with per-record access status + counts. |
| 17 | +
|
| 18 | +It never edits kb/ — extraction and YAML writes are the agent's job, so a curator |
| 19 | +can review this prep before any record changes. Access status buckets each record as |
| 20 | +OA_FULLTEXT (Methods reachable), ABSTRACT_ONLY (paywalled; abstract-level only), or |
| 21 | +NO_REFERENCE (no citable PMID/DOI found). |
| 22 | +
|
| 23 | +Usage: |
| 24 | + python scripts/growth_conditions_sweep.py --list |
| 25 | + python scripts/growth_conditions_sweep.py --prep # all missing records |
| 26 | + python scripts/growth_conditions_sweep.py --prep --limit 5 # first 5 (test batch) |
| 27 | + python scripts/growth_conditions_sweep.py --prep FILE [FILE ...] # explicit records |
| 28 | +""" |
| 29 | + |
| 30 | +from __future__ import annotations |
| 31 | + |
| 32 | +import argparse |
| 33 | +import re |
| 34 | +import sys |
| 35 | +from collections import Counter |
| 36 | +from pathlib import Path |
| 37 | + |
| 38 | +# fulltext_access.py lives beside this script; its dir is on sys.path when run directly. |
| 39 | +from fulltext_access import ( |
| 40 | + author_request_draft, |
| 41 | + crossref_meta, |
| 42 | + epmc_core, |
| 43 | + try_core, |
| 44 | + try_europepmc, |
| 45 | + try_unpaywall, |
| 46 | +) |
| 47 | + |
| 48 | +REPO = Path(__file__).resolve().parent.parent |
| 49 | +COMMUNITIES = REPO / "kb" / "communities" |
| 50 | +OUT_DIR = REPO / "reports" / "growth_conditions_sweep" |
| 51 | + |
| 52 | +REF_RE = re.compile(r"^\s*-?\s*reference:\s*(\S+)", re.MULTILINE) |
| 53 | +HAS_BLOCK_RE = re.compile(r"^(growth_media|cultivation_setup):", re.MULTILINE) |
| 54 | + |
| 55 | + |
| 56 | +def lacks_conditions(text: str) -> bool: |
| 57 | + """True if the record has neither a growth_media nor cultivation_setup block.""" |
| 58 | + return not HAS_BLOCK_RE.search(text) |
| 59 | + |
| 60 | + |
| 61 | +def candidates(explicit: list[Path] | None) -> list[Path]: |
| 62 | + files = explicit or sorted(COMMUNITIES.glob("*.yaml")) |
| 63 | + return [f for f in files if lacks_conditions(f.read_text())] |
| 64 | + |
| 65 | + |
| 66 | +def primary_reference(text: str) -> tuple[str | None, list[tuple[str, int]]]: |
| 67 | + """Most-cited reference in the record, plus the frequency-ranked full list.""" |
| 68 | + refs = [r.strip().strip("\"'") for r in REF_RE.findall(text)] |
| 69 | + if not refs: |
| 70 | + return None, [] |
| 71 | + ranked = Counter(refs).most_common() |
| 72 | + return ranked[0][0], ranked |
| 73 | + |
| 74 | + |
| 75 | +def split_ref(ref: str) -> tuple[str | None, str | None]: |
| 76 | + """Split a 'PMID:123' / 'doi:10.x' reference into (pmid, doi).""" |
| 77 | + low = ref.lower() |
| 78 | + if low.startswith("pmid:"): |
| 79 | + return ref.split(":", 1)[1].strip(), None |
| 80 | + if low.startswith("doi:"): |
| 81 | + return None, ref.split(":", 1)[1].strip() |
| 82 | + if ref.startswith("10."): # bare DOI |
| 83 | + return None, ref |
| 84 | + return None, None |
| 85 | + |
| 86 | + |
| 87 | +def access_ladder(rec: dict, doi: str | None, title: str | None) -> tuple[str, str | None]: |
| 88 | + """Return (method, url) for the first legal full-text hit, or ('none', None).""" |
| 89 | + for method, fn in ( |
| 90 | + ("europepmc_oa", lambda: try_europepmc(rec)), |
| 91 | + ("unpaywall", lambda: try_unpaywall(doi)), |
| 92 | + ("core", lambda: try_core(doi, title)), |
| 93 | + ): |
| 94 | + url = fn() |
| 95 | + if url: |
| 96 | + return method, url |
| 97 | + return "none", None |
| 98 | + |
| 99 | + |
| 100 | +def strip_html(s: str) -> str: |
| 101 | + return re.sub(r"<[^>]+>", "", s or "").strip() |
| 102 | + |
| 103 | + |
| 104 | +def prep_record(path: Path) -> dict: |
| 105 | + """Fetch sources for one record and write its staging bundle. Returns a summary row.""" |
| 106 | + text = path.read_text() |
| 107 | + ref, ranked = primary_reference(text) |
| 108 | + row = {"record": path.stem, "ref": ref or "—", "status": "", "method": "", "url": ""} |
| 109 | + |
| 110 | + if not ref: |
| 111 | + row["status"] = "NO_REFERENCE" |
| 112 | + _write_bundle(path.stem, ref, {}, ranked, "none", None, None) |
| 113 | + return row |
| 114 | + |
| 115 | + pmid, doi = split_ref(ref) |
| 116 | + rec = epmc_core(pmid, doi) |
| 117 | + doi = doi or rec.get("doi") |
| 118 | + if not rec.get("title") and doi: # DOI-only / not in EPMC -> CrossRef metadata |
| 119 | + rec = {**crossref_meta(doi), **rec} |
| 120 | + title = strip_html(rec.get("title", "")) |
| 121 | + method, url = access_ladder(rec, doi, title) |
| 122 | + |
| 123 | + row["method"] = method |
| 124 | + row["url"] = url or "" |
| 125 | + row["status"] = "OA_FULLTEXT" if url else "ABSTRACT_ONLY" |
| 126 | + _write_bundle(path.stem, ref, rec, ranked, method, url, doi) |
| 127 | + return row |
| 128 | + |
| 129 | + |
| 130 | +def _write_bundle( |
| 131 | + stem: str, |
| 132 | + ref: str | None, |
| 133 | + rec: dict, |
| 134 | + ranked: list[tuple[str, int]], |
| 135 | + method: str, |
| 136 | + url: str | None, |
| 137 | + doi: str | None, |
| 138 | +) -> None: |
| 139 | + OUT_DIR.mkdir(parents=True, exist_ok=True) |
| 140 | + title = strip_html(rec.get("title", "")) |
| 141 | + abstract = strip_html(rec.get("abstractText", "")) |
| 142 | + lines = [ |
| 143 | + f"# Growth-conditions prep — {stem}", |
| 144 | + "", |
| 145 | + f"- **Primary reference:** `{ref or 'none found'}`", |
| 146 | + f"- **Title:** {title or '(unresolved)'}", |
| 147 | + f"- **All cited refs (freq):** {', '.join(f'{r}×{n}' for r, n in ranked) or '—'}", |
| 148 | + ] |
| 149 | + if url: |
| 150 | + lines += [ |
| 151 | + f"- **Full-text access:** `{method}` — OA full text available", |
| 152 | + f"- **Methods URL (fetch this):** {url}", |
| 153 | + " - Europe PMC XML: fetch with `curl --compressed <url>` and read the Methods.", |
| 154 | + ] |
| 155 | + else: |
| 156 | + lines += [ |
| 157 | + "- **Full-text access:** `NO_LEGAL_OA` — abstract-level conditions only.", |
| 158 | + " - Use only conditions stated in the abstract below; do **not** invent any.", |
| 159 | + ] |
| 160 | + lines += ["", "## Abstract", "", abstract or "_(no abstract retrieved)_", ""] |
| 161 | + if not url and (rec.get("title") or ref): |
| 162 | + lines += [ |
| 163 | + "## Author-request draft (for closed-access follow-up)", |
| 164 | + "", |
| 165 | + "```", |
| 166 | + author_request_draft(rec, doi), |
| 167 | + "```", |
| 168 | + "", |
| 169 | + ] |
| 170 | + (OUT_DIR / f"{stem}.md").write_text("\n".join(lines)) |
| 171 | + |
| 172 | + |
| 173 | +def write_index(rows: list[dict]) -> Path: |
| 174 | + OUT_DIR.mkdir(parents=True, exist_ok=True) |
| 175 | + counts = Counter(r["status"] for r in rows) |
| 176 | + lines = [ |
| 177 | + "# Growth-conditions sweep — prep index", |
| 178 | + "", |
| 179 | + f"- Records prepped: **{len(rows)}**", |
| 180 | + f"- OA full text (Methods reachable): **{counts.get('OA_FULLTEXT', 0)}**", |
| 181 | + f"- Abstract-only (paywalled): **{counts.get('ABSTRACT_ONLY', 0)}**", |
| 182 | + f"- No citable reference: **{counts.get('NO_REFERENCE', 0)}**", |
| 183 | + "", |
| 184 | + "| Record | Primary ref | Access | Method | Methods URL |", |
| 185 | + "|---|---|---|---|---|", |
| 186 | + ] |
| 187 | + for r in sorted(rows, key=lambda x: (x["status"], x["record"])): |
| 188 | + url = f"[link]({r['url']})" if r["url"] else "—" |
| 189 | + lines.append( |
| 190 | + f"| {r['record']} | `{r['ref']}` | {r['status']} | {r['method'] or '—'} | {url} |" |
| 191 | + ) |
| 192 | + lines += ["", "Per-record source bundles are in this directory (`<Record>.md`)."] |
| 193 | + path = OUT_DIR / "INDEX.md" |
| 194 | + path.write_text("\n".join(lines)) |
| 195 | + return path |
| 196 | + |
| 197 | + |
| 198 | +def main(argv: list[str] | None = None) -> int: |
| 199 | + p = argparse.ArgumentParser( |
| 200 | + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter |
| 201 | + ) |
| 202 | + mode = p.add_mutually_exclusive_group(required=True) |
| 203 | + mode.add_argument("--list", action="store_true", help="List candidate records and exit.") |
| 204 | + mode.add_argument("--prep", action="store_true", help="Fetch sources + write staging bundles.") |
| 205 | + p.add_argument( |
| 206 | + "files", nargs="*", type=Path, help="Explicit record paths (default: all missing)." |
| 207 | + ) |
| 208 | + p.add_argument("--limit", type=int, default=0, help="Cap the number of records processed.") |
| 209 | + args = p.parse_args(argv) |
| 210 | + |
| 211 | + cand = candidates(args.files or None) |
| 212 | + if args.limit: |
| 213 | + cand = cand[: args.limit] |
| 214 | + |
| 215 | + if args.list: |
| 216 | + for f in cand: |
| 217 | + print(f.name) |
| 218 | + print(f"\n{len(cand)} record(s) lack growth_media/cultivation_setup", file=sys.stderr) |
| 219 | + return 0 |
| 220 | + |
| 221 | + rows = [] |
| 222 | + for i, f in enumerate(cand, 1): |
| 223 | + print(f"[sweep] ({i}/{len(cand)}) {f.stem}", file=sys.stderr) |
| 224 | + rows.append(prep_record(f)) |
| 225 | + idx = write_index(rows) |
| 226 | + print(f"[sweep] wrote {len(rows)} bundles + {idx.relative_to(REPO)}", file=sys.stderr) |
| 227 | + return 0 |
| 228 | + |
| 229 | + |
| 230 | +if __name__ == "__main__": |
| 231 | + raise SystemExit(main()) |
0 commit comments