scripts/extract_ring1_corpus.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/extract_ring1_corpus.py · SHA-256: eee6ac565ed0fb16…
return "Study_Intervention"
def split_contrast_clauses(sent: str, prev_sent: str | None) -> tuple[str, str, str]:
"""
Splits a modifier sentence into (modifier_variable_Z, level_1_clause, level_2_clause)
so both contrasting conditions are explicitly captured.
"""
pivots = [
r",\s*whereas\s+",
r"\s+whereas\s+",
r",\s*while\s+",
r";\s*however,\s*",
r",\s*in\s+contrast\s+to\s+",
r"\s+compared\s+to\s+",
r"\s+compared\s+with\s+",
r"\s+unlike\s+",
r"\s+but\s+not\s+in\s+",
r"\s+but\s+not\s+",
]
for piv in pivots:
parts = re.split(piv, sent, maxsplit=1, flags=re.IGNORECASE)
if len(parts) == 2 and len(parts[0].strip()) >= 15 and len(parts[1].strip()) >= 10:
c1 = parts[0].strip()
c2 = parts[1].strip()
n1, _ = resolve_canonical_node(c1)
n2, _ = resolve_canonical_node(c2)
n1_lbl = n1 or "Condition_1"
n2_lbl = n2 or "Condition_2"
mod_var = f"{n1_lbl} vs. {n2_lbl}" if n1_lbl != n2_lbl else f"Condition contrast ({n1_lbl})"
return mod_var[:120], c1, c2
if prev_sent and re.match(r"^(However|In\s+contrast|Conversely|By\s+contrast|Unlike)\b", sent.strip(), flags=re.IGNORECASE):
n1, _ = resolve_canonical_node(prev_sent)
n2, _ = resolve_canonical_node(sent)
mod_var = f"{n1 or 'Prior_Condition'} vs. {n2 or 'Contrast_Condition'}"
return mod_var[:120], prev_sent.strip(), sent.strip()
n1, _ = resolve_canonical_node(sent)
n1_lbl = n1 or "Experimental_Context"
mid = len(sent) // 2
comma_idx = sent.find(",", mid - 30)
if comma_idx != -1 and 20 < comma_idx < len(sent) - 20:
return f"Regime dependency on {n1_lbl}", sent[:comma_idx].strip(), sent[comma_idx + 1 :].strip()
return f"Regime dependency on {n1_lbl}", sent, f"Reference regime ({n1_lbl})"
def extract_causal_edge_from_sentence(
sent: str, src_label: str, pmid: str, study_edits: list[dict[str, Any]], title: str
) -> dict[str, Any] | None:
"""
Splits a causal sentence around its causal verb and resolves both the upstream subject
and downstream object to Canonical Biological Nodes. Returns None if negated or if
either clause lacks a recognizable biological entity.
"""
m_verb = re.search(
r"\b(upregulat\w+|downregulat\w+|inhibit\w+|activat\w+|induc\w+|suppress\w+|prevent\w+|block\w+|rescu\w+|promot\w+|abolish\w+|abrogat\w+|reduc\w+|increas\w+|enhanc\w+)\b",
sent,
flags=re.IGNORECASE,
)
if not m_verb:
return None
verb = m_verb.group(1).lower()
left_clause = sent[: m_verb.start()].strip()
right_clause = sent[m_verb.end() :].strip()
if len(left_clause) < 4 or len(right_clause) < 6:
return None
# Check for explicit negation in the left window preceding the verb or immediately after
neg_window = left_clause[-45:].lower()
if re.search(
r"\b(did\s+not|does\s+not|do\s+not|was\s+not|were\s+not|not|no|never|neither|failed\s+to|unable\s+to|without|cannot|could\s+not)\b",
neg_window,
):
return None
if any(k in verb for k in ("inhibit", "downregulat", "suppress", "prevent", "block", "abolish", "abrogat", "reduc")):
rel = "Inhibits_or_Downregulates"
elif any(k in verb for k in ("rescu", "stabiliz")):
rel = "Stabilizes_or_Rescues"
else:
rel = "Activates_or_Upregulates"
u_node, u_type = resolve_canonical_node(left_clause, default_type="Gene_or_Protein_Edit")
v_node, v_type = resolve_canonical_node(right_clause, default_type="Cell_Survival_or_Death_Pathway")
if u_node is None or v_node is None:
return None
if u_node == v_node:
return None
return {
"upstream_node": f"{u_node} [{left_clause[-65:]}]",
"upstream_node_type": u_type or "Gene_or_Protein_Edit",
"causal_relation": rel,
"downstream_node": f"{v_node} [{right_clause[:75]}]",
"downstream_node_type": v_type or "Cell_Survival_or_Death_Pathway",
"evidence_source": f"{src_label} (PMID:{pmid}): {sent[:140]}",
}
def _compute_dossier_sha256(pmid: str, dossier: dict[str, Any]) -> str:
dp = DOSSIER_DIR / f"{pmid}.json"
if dp.exists():
raw_bytes = dp.read_bytes()
try:
if json.loads(raw_bytes.decode("utf-8")) == dossier:
return hashlib.sha256(raw_bytes).hexdigest()
except Exception:
pass
return hashlib.sha256(
json.dumps(dossier, sort_keys=True, ensure_ascii=False).encode("utf-8")
).hexdigest()
def _get_effective_fulltext_sections(pmid: str, dossier: dict[str, Any]) -> dict[str, Any]:
ft = dossier.get("fulltext_data_sections") or {}
if pmid in PEER_REVIEWED_TO_PREPRINT_MAP:
pre_pmid = PEER_REVIEWED_TO_PREPRINT_MAP[pmid]
pre_path = DOSSIER_DIR / f"{pre_pmid}.json"
if pre_path.exists():
try:
pre_dos = json.loads(pre_path.read_text(encoding="utf-8"))
pre_ft = pre_dos.get("fulltext_data_sections") or {}
ft_chars = sum(len(p or "") for p in (ft.get("results_paragraphs") or [])) + sum(
len((f or {}).get("caption") or "") for f in (ft.get("figure_legends") or [])
)
pre_chars = sum(len(p or "") for p in (pre_ft.get("results_paragraphs") or [])) + sum(
len((f or {}).get("caption") or "") for f in (pre_ft.get("figure_legends") or [])
)
if (
len(ft.get("results_paragraphs") or []) < len(pre_ft.get("results_paragraphs") or [])
or len(ft.get("figure_legends") or []) < len(pre_ft.get("figure_legends") or [])
or ft_chars < pre_chars
):
return pre_ft
except Exception:
pass
return ft
def _resolve_dossier_character_span(quote: str | None, dossier: dict[str, Any], src_label: str = "") -> str | None:
"""
Resolves a verbatim quote to an exact 0-based character slice inside a single dossier field:
<field_path>[start:end]|norm=(exact|whitespace_normalized)
Returns None when quote is None/empty (citation-only records without indexed abstract)
and raises ValueError instead of fabricating abstract[0:len(q)] when a non-empty quote
cannot be resolved against the stored dossier text.
"""
if quote is None:
return None
q = quote.strip()
if not q:
return None
pmid = str(dossier.get("pmid") or "")
ft = _get_effective_fulltext_sections(pmid, dossier)
all_sections: list[tuple[str, str]] = [
("abstract", dossier.get("abstract") or ""),
("title", dossier.get("title") or ""),
]
for i, rpara in enumerate(ft.get("results_paragraphs", [])):
all_sections.append((f"fulltext_data_sections.results_paragraphs[{i}]", rpara or ""))
for i, fig in enumerate(ft.get("figure_legends", [])):
all_sections.append((f"fulltext_data_sections.figure_legends[{i}].caption", (fig.get("caption") if isinstance(fig, dict) else "") or ""))
for i, mpara in enumerate(ft.get("methods_paragraphs", [])):
all_sections.append((f"fulltext_data_sections.methods_paragraphs[{i}]", mpara or ""))
preferred: list[tuple[str, str]] = []
slbl = (src_label or "").lower()
if slbl == "abstract":
preferred = [s for s in all_sections if s[0] == "abstract"]
elif slbl.startswith("results para"):
m_idx = re.search(r"(\d+)", slbl)
if m_idx:
target_path = f"fulltext_data_sections.results_paragraphs[{int(m_idx.group(1)) - 1}]"
preferred = [s for s in all_sections if s[0] == target_path]
elif "fig" in slbl:
preferred = [s for s in all_sections if "figure_legends" in s[0]]
ordered = preferred + [s for s in all_sections if s not in preferred]
for path, text in ordered:
idx = text.find(q)
if idx != -1:
return f"{path}[{idx}:{idx + len(q)}]|norm=exact"
tokens = [re.escape(tok) for tok in re.split(r"\s+", q) if tok]
if tokens:
pat = re.compile(r"\s+".join(tokens))
for path, text in ordered:
m = pat.search(text)
if m:
return f"{path}[{m.start()}:{m.end()}]|norm=whitespace_normalized"
raise ValueError(f"Unresolved verbatim_evidence_quote in dossier PMID:{pmid}: {q[:80]!r}")
def _infer_endpoint_polarity_registry(text: str) -> dict[str, Any]:
tl = text.lower()
if "pd-l1+ cells/mm2" in tl or "transgene-induction manipulation check" in tl:
return {
"polarity_class": "Qualitative_or_Unoriented_Endpoint",
"orientation_sign": 0,
"matched_lexicon_term": "none_or_mixed",
}
matched_h = [k for k in LEX_H if k in tl]
matched_p = [k for k in LEX_P if k in tl]
if matched_h and not matched_p:
return {
"polarity_class": "Lower_Is_Better_Hazard_Endpoint",
"orientation_sign": -1,
"matched_lexicon_term": matched_h[0],
}
if matched_p and not matched_h:
return {
"polarity_class": "Higher_Is_Better_Protective_Endpoint",
"orientation_sign": 1,
"matched_lexicon_term": matched_p[0],
}
return {
"polarity_class": "Qualitative_or_Unoriented_Endpoint",
"orientation_sign": 0,
"matched_lexicon_term": "none_or_mixed",
}
def _infer_n_unit_from_quote(sl: str, n_val: int | None) -> str:
if n_val is None:
return "unspecified_in_source"
if re.search(r"\b\d[\d,]*\s+(?:responsive\s+)?cells\b|\bcells\s+from\b|\bn\s*=\s*\d[\d,]*\s*(?:responsive\s+)?cells\b", sl):
return "individual_cells_imaged"
if re.search(r"\brhesus\b|\bmacaque\w*\b|\bcynomolgus\b|\bnhp\b|\bmonkey\w*\b|\bbaboon\w*\b", sl):
return "nhp_recipients"
if re.search(r"\bpatient\w*\b|\bparticipant\w*\b|\bsubject\w*\b|\bperson\b", sl):
return "human_participants"
if re.search(r"\bmice\b|\bmouse\b|\brecipient\w*\b|\bgraft\w*\b|\banimal\w*\b", sl):
return "mouse_recipients"
if re.search(r"\bdonor\w*\b", sl):
return "human_islet_donors"
if re.search(r"\bindependent\s+differentiation\w*\b|\bbatch\w*\b|\bdifferentiation\s+experiment\w*\b", sl):
return "independent_differentiations"
if re.search(r"\bislet\w*\b|\bcluster\w*\b|\borganoid\w*\b|\bspheroid\w*\b", sl):
return "islet_or_cluster_replicates"
if re.search(r"\bindependent\s+experiment\w*\b|\breplicate\w*\b|\bco-?culture\w*\b|\bwell\w*\b|\bassay\w*\b", sl):
return "in_vitro_coculture_replicates"
return "unspecified_in_source"
def _extract_comparator_clause(sent: str, study_edits: list[dict[str, Any]], cell_source: str, stage: str, first_author: str, pub_year: Any) -> tuple[str, str]:
"""Extracts the explicit comparator description from a comparative sentence without generic templates."""
comp_desc = ""
for pat in (