hypoagent-gbm / scripts /fetch_kb.py
eduzrh's picture
HypoAgent-Bio: code, frozen KB, full results, paper and reproducibility cache (part 5)
7ba3101 verified
Raw History Blame Contribute Delete
11.8 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Build a frozen, reproducible knowledge snapshot for HypoAgent-Bio.
Sources
-------
1. PubMed E-utilities: literature abstracts for GBM / temozolomide resistance.
2. UniProt REST: structured protein cards for candidate molecules.
The script writes:
data/kb/documents.jsonl one PubMed abstract per line
data/kb/entities.json structured protein / lncRNA cards
data/kb/manifest.json queries, counts, timestamps, source URLs
The snapshot is committed to the repository so that retrieval, experiments and
the paper can be reproduced without network access.
"""
from __future__ import annotations
import json
import re
import sys
import time
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
KB_DIR = ROOT / "data" / "kb"
EUTILS = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
UNIPROT = "https://rest.uniprot.org/uniprotkb"
# Each theme has 2 complementary queries; retmax is kept small on purpose so
# that the frozen corpus stays reviewable (roughly 100 abstracts).
QUERIES: dict[str, list[str]] = {
"mgmt": [
"glioblastoma temozolomide resistance MGMT promoter methylation",
"MGMT DNA repair temozolomide glioblastoma therapy response",
],
"dna_damage": [
"glioblastoma temozolomide DNA damage response apoptosis",
"temozolomide resistance DNA mismatch repair base excision repair glioma",
],
"tme": [
"glioblastoma tumor microenvironment immunosuppression temozolomide resistance",
"glioblastoma associated macrophage microglia temozolomide treatment",
],
"singlecell": [
"glioblastoma single-cell RNA sequencing heterogeneity temozolomide resistance",
"glioma stem cell drug tolerance single cell transcriptomics",
],
"candidate": [
"ELFN2 glioma glioblastoma",
"LRRC4 glioma glioblastoma",
"TMBIM6 glioma glioblastoma",
"SRRM1 glioma glioblastoma",
"LINC00470 glioma glioblastoma",
"PPP1CA glioma glioblastoma protein phosphatase 1",
],
"combination": [
"glioblastoma temozolomide combination therapy synthetic lethality",
"glioblastoma temozolomide sensitizer blood-brain barrier",
],
"biomarker": [
"glioblastoma temozolomide resistance biomarker prediction",
"glioblastoma molecular subtype temozolomide response",
],
"plm": [
"protein language model drug target discovery cancer",
"deep learning protein function prediction glioma",
],
}
ENTITY_GENES = ["ELFN2", "PPP1CA", "SRRM1", "TMBIM6", "LRRC4"]
ENTITY_ALIASES = {
"ELFN2": ["ELFN2", "protein phosphatase 1 regulatory subunit 29"],
"PPP1CA": ["PPP1CA", "PP1", "PP1-alpha", "protein phosphatase 1"],
"SRRM1": ["SRRM1", "SRm160", "serine/arginine repetitive matrix protein 1"],
"TMBIM6": ["TMBIM6", "BI-1", "Bax inhibitor 1"],
"LRRC4": ["LRRC4", "LRRC4A", "leucine-rich repeat-containing protein 4"],
"LINC00470": ["LINC00470", "long intergenic non-protein coding RNA 470"],
}
HEADERS = {"User-Agent": "HypoAgent-Bio/1.0 (academic reproducibility snapshot)"}
def http_get(url: str, tries: int = 4, timeout: int = 45) -> bytes:
last = None
for attempt in range(tries):
try:
req = urllib.request.Request(url, headers=HEADERS)
with urllib.request.urlopen(req, timeout=timeout) as fh:
return fh.read()
except Exception as exc: # noqa: BLE001 - retry any transport error
last = exc
time.sleep(1.5 * (attempt + 1))
raise RuntimeError(f"GET failed after {tries} tries: {url}") from last
def esearch(term: str, retmax: int = 12) -> list[str]:
qs = urllib.parse.urlencode(
{"db": "pubmed", "term": term, "retmax": retmax, "retmode": "json", "sort": "relevance"}
)
payload = json.loads(http_get(f"{EUTILS}/esearch.fcgi?{qs}"))
return payload.get("esearchresult", {}).get("idlist", [])
def efetch(pmids: list[str]) -> list[dict]:
if not pmids:
return []
qs = urllib.parse.urlencode({"db": "pubmed", "id": ",".join(pmids), "retmode": "xml"})
xml_bytes = http_get(f"{EUTILS}/efetch.fcgi?{qs}")
root = ET.fromstring(xml_bytes)
docs = []
for art in root.findall(".//PubmedArticle"):
pmid = art.findtext(".//PMID") or ""
title = "".join(art.find(".//ArticleTitle").itertext()) if art.find(".//ArticleTitle") is not None else ""
abstract_parts = []
for node in art.findall(".//Abstract/AbstractText"):
label = node.attrib.get("Label")
text = "".join(node.itertext()).strip()
if text:
abstract_parts.append(f"{label}: {text}" if label else text)
abstract = " ".join(abstract_parts).strip()
journal = art.findtext(".//Journal/Title") or ""
year = art.findtext(".//JournalIssue/PubDate/Year") or ""
if not year:
medline = art.findtext(".//JournalIssue/PubDate/MedlineDate") or ""
year = medline[:4] if medline else ""
authors = []
for a in art.findall(".//AuthorList/Author"):
last = a.findtext("LastName") or ""
initials = a.findtext("Initials") or ""
if last:
authors.append(f"{last} {initials}".strip())
doi = ""
for aid in art.findall(".//ArticleId"):
if aid.attrib.get("IdType") == "doi":
doi = (aid.text or "").strip()
break
if len(abstract) >= 180 and title:
docs.append(
{
"doc_id": f"PMID:{pmid}",
"source": "PubMed",
"pmid": pmid,
"doi": doi,
"title": title.strip(),
"abstract": abstract,
"journal": journal,
"year": year,
"authors": authors[:8],
"url": f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/",
}
)
return docs
def fetch_uniprot(gene: str) -> dict | None:
q = urllib.parse.quote(f"gene_exact:{gene} AND organism_id:9606 AND reviewed:true")
fields = "accession,protein_name,gene_names,cc_function,cc_subcellular_location,cc_disease"
url = f"{UNIPROT}/search?query={q}&fields={fields}&format=json&size=5"
data = json.loads(http_get(url))
results = data.get("results", [])
if not results:
return None
rec = results[0]
functions = []
locations = []
diseases = []
for comment in rec.get("comments", []):
ctype = comment.get("commentType")
texts = [t.get("value", "") for t in comment.get("texts", []) if t.get("value")]
if ctype == "FUNCTION":
functions.extend(texts)
elif ctype == "SUBCELLULAR LOCATION":
locations.extend(texts)
elif ctype == "DISEASE":
diseases.extend(texts)
return {
"uniprot": rec.get("primaryAccession", ""),
"protein_name": (
rec.get("proteinDescription", {}).get("recommendedName", {}).get("fullName", {}).get("value", "")
),
"function": " ".join(functions)[:1200],
"location": " ".join(locations)[:400],
"disease": " ".join(diseases)[:400],
}
def build_entities(documents: list[dict]) -> list[dict]:
entities = []
for gene in ENTITY_GENES:
card = fetch_uniprot(gene)
time.sleep(0.35)
if not card:
continue
aliases = ENTITY_ALIASES.get(gene, [gene])
evidence_ids = []
for doc in documents:
haystack = f"{doc['title']} {doc['abstract']}".lower()
if any(alias.lower() in haystack for alias in aliases):
evidence_ids.append(doc["doc_id"])
entities.append(
{
"entity_id": f"GENE:{gene}",
"gene": gene,
"name": card["protein_name"],
"type": "protein",
"aliases": aliases,
"uniprot": card["uniprot"],
"function": card["function"],
"location": card["location"],
"disease": card["disease"],
"evidence_ids": evidence_ids,
"source_url": f"https://www.uniprot.org/uniprotkb/{card['uniprot']}/entry",
}
)
# LINC00470 is a lncRNA and has no UniProt protein entry; keep a literature-only card.
aliases = ENTITY_ALIASES["LINC00470"]
evidence_ids = [
d["doc_id"]
for d in documents
if any(a.lower() in f"{d['title']} {d['abstract']}".lower() for a in aliases)
]
entities.append(
{
"entity_id": "GENE:LINC00470",
"gene": "LINC00470",
"name": "long intergenic non-protein coding RNA 470",
"type": "lncRNA",
"aliases": aliases,
"uniprot": "",
"function": "Long non-coding RNA; no UniProt protein entry. Function must be grounded in the retrieved literature evidence.",
"location": "nucleus / cytoplasm (context dependent, see evidence)",
"disease": "glioma / glioblastoma (see evidence)",
"evidence_ids": evidence_ids,
"source_url": "https://www.ncbi.nlm.nih.gov/gene/?term=LINC00470",
}
)
return entities
def main() -> None:
KB_DIR.mkdir(parents=True, exist_ok=True)
all_docs: dict[str, dict] = {}
manifest_queries = []
for theme, queries in QUERIES.items():
for query in queries:
pmids = esearch(query)
docs = efetch(pmids)
added = 0
for doc in docs:
if doc["doc_id"] in all_docs:
themes = set(all_docs[doc["doc_id"]].get("themes", []))
themes.add(theme)
all_docs[doc["doc_id"]]["themes"] = sorted(themes)
else:
doc["themes"] = [theme]
all_docs[doc["doc_id"]] = doc
added += 1
manifest_queries.append(
{"theme": theme, "query": query, "pmids": pmids, "new_documents": added}
)
print(f"[{theme}] {query[:60]}... -> {len(pmids)} hits, {added} new", flush=True)
time.sleep(0.4)
documents = sorted(all_docs.values(), key=lambda d: (d["year"], d["doc_id"]), reverse=True)
with (KB_DIR / "documents.jsonl").open("w", encoding="utf-8") as fh:
for doc in documents:
fh.write(json.dumps(doc, ensure_ascii=False) + "\n")
print(f"Fetching {len(ENTITY_GENES)} UniProt cards + LINC00470 ...", flush=True)
entities = build_entities(documents)
(KB_DIR / "entities.json").write_text(
json.dumps(entities, ensure_ascii=False, indent=2), encoding="utf-8"
)
manifest = {
"created_at_utc": datetime.now(timezone.utc).isoformat(),
"n_documents": len(documents),
"n_entities": len(entities),
"themes": {t: sum(1 for d in documents if t in d["themes"]) for t in QUERIES},
"queries": manifest_queries,
"sources": {
"literature": "NCBI PubMed E-utilities",
"proteins": "UniProtKB REST",
},
"license_note": "PubMed abstracts are used for non-commercial research; cite original PMIDs.",
}
(KB_DIR / "manifest.json").write_text(
json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8"
)
print(f"Done: {len(documents)} documents, {len(entities)} entity cards -> {KB_DIR}")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(130)