OpenIslet

scripts/extract_ring1_corpus.py

Step 5B (v0.3 Deep Quantitative & Canonical Graph Upgrade):

script Release v0.8.0 gen-eb955f8266035aba 296 KB · 22 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/extract_ring1_corpus.py · SHA-256: eee6ac565ed0fb16…

    sval = str(int(val)) if isinstance(val, float) and val.is_integer() else str(val)
    if _has_bounded_num(sval) or _has_bounded_num(str(val)):
        return True
    if field_name in ("treatment_n", "control_n") and isinstance(val, (int, float)) and int(val) >= 2:
        if len(re.findall(r">\d+", q_clean)) == int(val) and "observation periods" in q_clean.lower():
            return True
    if isinstance(val, float):
        for fmt in (f"{val:.1f}", f"{val:.2f}", f"{val:.3f}", f"{val:g}"):
            if abs(val - float(fmt)) <= 1e-6 and _has_bounded_num(fmt):
                return True
    return False


_PROVENANCE_SPAN_RE = re.compile(
    r"^(abstract|title|fulltext_data_sections\.(results_paragraphs|figure_legends|methods_paragraphs)\[(\d+)\](\.caption)?)\[(\d+):(\d+)\]\|norm=(exact|whitespace_normalized)$"
)
_PROVENANCE_BIB_FURNITURE_RE = re.compile(
    r"(?:\bDOI\b|10\.\d{4,9}/\S+"
    r"|\b(?:NEJM|N\.?\s*Engl\.?\s*J\.?\s*Med\.?|Correspondence|Letter)\b.{0,40}\b(?:19|20)\d{2}\b"
    r"|\b(?:19|20)\d{2}\b.{0,40}\b(?:NEJM|N\.?\s*Engl\.?\s*J\.?\s*Med\.?|Correspondence|Letter)\b"
    r"|\b\d{1,4}\(\d{1,3}\):\s*\d+\s*[-\u2013\u2014]\s*\d+\b)",
    flags=re.IGNORECASE,
)
_PROVENANCE_BIB_TOKEN_STRIP_RE = re.compile(
    r"(?:10\.\d{4,9}/[^\s,;)\]]+"
    r"|\b(?:doi|pmid|pmcid|nejm|n\.?\s*engl\.?\s*j\.?\s*med\.?|correspondence|letter|commentary|editorial|vol(?:ume)?|issue|no|pp?|et\s+al)\b"
    r"|\b(?:19|20)\d{2}\b"
    r"|\b\d{1,5}(?:\(\d{1,4}\))?(?::\s*\d+(?:[-\u2013\u2014]\d+)?)?\b"
    r"|[\s\(\)\[\]\{\}:;,.\-\u2013\u2014/]+)",
    flags=re.IGNORECASE,
)


def _norm_provenance_text(text: str | None) -> str:
    return re.sub(r"\s+", " ", (text or "").strip()).rstrip(".?!:;").lower()


def _is_title_or_bib_echo_quote(quote: str, title: str) -> bool:
    nq = _norm_provenance_text(quote)
    nti = _norm_provenance_text(title)
    if not nq or not nti:
        return False
    if nq == nti:
        return True
    if nq.startswith(nti):
        rem = nq[len(nti):].strip()
        if not rem:
            return True
        if _PROVENANCE_BIB_TOKEN_STRIP_RE.sub("", rem) == "":
            return True
        if re.fullmatch(r"[\(\[].*[\)\]]", rem) and _PROVENANCE_BIB_FURNITURE_RE.search(rem):
            return True
    return False


def validate_record_quote_and_locator_provenance(
    doc: dict[str, Any], dossier: dict[str, Any] | None = None
) -> None:
    """
    Local (zero-network) IIP-0040 provenance guard enforcing Rules R1 and R2:
      - Null quote / null source_span pairing: verbatim_evidence_quote is None and
        source_span is None is permitted STRICTLY when
        source_text_type == 'Citation_Only_No_Abstract_Indexed' and abstract_indexed is False;
        mismatched null/non-null pairs or null quotes on empirical records are rejected.
      - R1: Any abstract[a:b] source_span is rejected whenever
        source_text_type == 'Citation_Only_No_Abstract_Indexed',
        study_metadata.abstract_indexed is False, or the loaded dossier lacks stored abstract text.
      - R2 (a): Any non-null, non-redacted verbatim_evidence_quote that equals the record title or
        equals title + bibliographic/DOI/journal/correspondence/letter furniture is rejected.
      - R2 (b, conjunctive): A span with offsets [0:len(quote)] does NOT fire on legitimate
        abstract-opening quotes; it is rejected only conjunctively when ALSO either (i) the stored
        quote carries bibliographic furniture (DOI, NEJM/Correspondence/Letter+year, vol(issue):pages)
        or (ii) it fails to resolve against the declared stored dossier source text.
    """
    meta = doc.get("study_metadata") or {}
    pmid = str(meta.get("pmid") or "")
    title = str(meta.get("title") or "")
    src_type = str(meta.get("source_text_type") or "")
    abstract_indexed = meta.get("abstract_indexed")
    is_citation_only = (
        src_type == "Citation_Only_No_Abstract_Indexed" and abstract_indexed is False
    )

    loaded_dossier = dossier
    if loaded_dossier is None and pmid:
        dp = DOSSIER_DIR / f"{pmid}.json"
        if dp.exists():
            loaded_dossier = json.loads(dp.read_text(encoding="utf-8"))

    for eff in doc.get("atomic_effects", []):
        eid = str(eff.get("effect_id") or "<unknown_effect>")
        q = eff.get("verbatim_evidence_quote")
        span = eff.get("source_span")

        if (q is None) != (span is None):
            raise ValueError(
                f"{eid}: R1/R2 violation — verbatim_evidence_quote and source_span must either both be null "
                "(strictly on Citation_Only_No_Abstract_Indexed with abstract_indexed=False) or both be non-null"
            )
        if q is None and span is None:
            if not is_citation_only:
                raise ValueError(
                    f"{eid}: R1 violation — null verbatim_evidence_quote/source_span is permitted strictly when "
                    "source_text_type=='Citation_Only_No_Abstract_Indexed' and abstract_indexed is False"
                )
            continue

        if not isinstance(q, str) or not q.strip():
            raise ValueError(f"{eid}: non-citation-only record requires a nonempty verbatim_evidence_quote string")
        if not isinstance(span, str) or not span.strip():
            raise ValueError(f"{eid}: non-citation-only record requires a nonempty source_span string")

        m_sp = _PROVENANCE_SPAN_RE.match(span)
        if not m_sp:
            raise ValueError(f"{eid}: invalid source_span format {span!r}")
        sec_path, sec_kind, sec_idx, _, s_idx, e_idx, norm_mode = m_sp.groups()
        s_i, e_i = int(s_idx), int(e_idx)

        source_dossier = loaded_dossier
        q_pmid = str(eff.get("quote_source_dossier_pmid") or pmid)
        if q_pmid != pmid and pmid in PEER_REVIEWED_TO_PREPRINT_MAP and q_pmid == PEER_REVIEWED_TO_PREPRINT_MAP[pmid]:
            pre_dp = DOSSIER_DIR / f"{q_pmid}.json"
            if pre_dp.exists():
                source_dossier = json.loads(pre_dp.read_text(encoding="utf-8"))

        # Rule R1: reject abstract[...] locator on citation-only or empty/unindexed-abstract records
        if sec_path == "abstract":
            dossier_missing_abstract = (
                source_dossier is not None
                and (
                    source_dossier.get("abstract_indexed") is False
                    or not (source_dossier.get("abstract") or "").strip()
                )
            )
            if (
                src_type == "Citation_Only_No_Abstract_Indexed"
                or abstract_indexed is False
                or dossier_missing_abstract
            ):
                raise ValueError(
                    f"{eid}: R1 violation — abstract[...] source_span {span!r} is forbidden on "
                    "citation-only or unindexed-abstract record"
                )

        is_redacted = q.startswith("[REDACTED_NON_OA_EXCERPT:") or q.startswith("[REDACTED_CONSERVATIVE_EXCERPT:")
        if not is_redacted:
            # Rule R2(a): reject title echo or title + bibliographic/DOI/journal/letter furniture
            if _is_title_or_bib_echo_quote(q, title):
                raise ValueError(
                    f"{eid}: R2 violation — verbatim_evidence_quote echoes study title or bibliographic citation label"
                )

            # Rule R2(b, conjunctive): [0:len(q)] span checked conjunctively against bib furniture or resolution failure
            if s_i == 0 and e_i == len(q):
                has_bib_furniture = bool(_PROVENANCE_BIB_FURNITURE_RE.search(q))
                resolution_failed = False
                if source_dossier is not None:
                    source_ft = _get_effective_fulltext_sections(q_pmid, source_dossier)
                    if sec_path == "abstract":
                        sec_txt = source_dossier.get("abstract") or ""
                    elif sec_path == "title":
                        sec_txt = source_dossier.get("title") or ""
                    elif sec_kind == "results_paragraphs":
                        sections = source_ft.get("results_paragraphs", [])
                        sec_txt = sections[int(sec_idx)] if isinstance(sections, list) and int(sec_idx) < len(sections) else ""
                    elif sec_kind == "figure_legends":
                        sections = source_ft.get("figure_legends", [])
                        sec_txt = (
                            sections[int(sec_idx)].get("caption") or ""
                            if isinstance(sections, list) and int(sec_idx) < len(sections) and isinstance(sections[int(sec_idx)], dict)
                            else ""
                        )
                    else:
                        sections = source_ft.get("methods_paragraphs", [])
                        sec_txt = sections[int(sec_idx)] if isinstance(sections, list) and int(sec_idx) < len(sections) else ""
                    if not isinstance(sec_txt, str) or not (0 <= s_i < e_i <= len(sec_txt)):
                        resolution_failed = True
                    else:
                        sliced = sec_txt[s_i:e_i]
                        if norm_mode == "exact":
                            resolution_failed = sliced != q
                        else:
                            resolution_failed = re.sub(r"\s+", " ", sliced).strip() != re.sub(r"\s+", " ", q).strip()
                if has_bib_furniture or resolution_failed:
                    raise ValueError(
                        f"{eid}: R2 violation — coextensive [0:{e_i}] span carries bibliographic furniture "
                        "or fails to resolve against stored dossier source text"
                    )


def validate_study_semantics(doc: dict[str, Any], dossier: dict[str, Any] | None = None) -> None:
    """
    Cross-field semantic validator (raising ValueError, never assert) enforcing:
      1. Every focal_arm_id and non-null comparator_arm_id exists in doc['arms'] and focal_arm_id != comparator_arm_id.
      2. Every comparator_arm_id is null iff log_response_ratio_or_smd is null; when non-null, focal_arm has is_reference_control=False and comparator_arm has is_reference_control=True.
      3. Every dossier_sha256 matches the SHA-256 digest of the source dossier file (or reconciled preprint dossier for fulltext spans).
      4. Every source_span resolves to the exact quote inside the dossier.
      5. Every endpoint_polarity_registry satisfies the exact bijection between polarity_class and orientation_sign.
      6. Every numeric LRR effect has a valid comparative statistic_type and matches the source operands (treatment_mean / control_mean or fold-change) within 1e-3.
      7. Every non-null numeric field (and arm sample_size_n) is grounded in verbatim_evidence_quote / dossier text.
    """
    if not isinstance(doc, dict):
        raise TypeError("Study must be a dictionary")
    # JSON's default decoder admits NaN/Infinity; comparisons with NaN can
    # otherwise bypass LRR arithmetic and polarity checks below.
    json.dumps(doc, allow_nan=False)
    for key, id_key in (("arms", "arm_id"), ("atomic_effects", "effect_id")):
        rows = doc.get(key, [])
        if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
            raise ValueError(f"{key} must be a list of explicit records")
        identifiers = [row.get(id_key) for row in rows]
        if any(not isinstance(identifier, str) or not identifier for identifier in identifiers) or len(set(identifiers)) != len(identifiers):
            raise ValueError(f"{id_key} values must be nonempty and unique")
    numeric_effect_fields = ("log_response_ratio_or_smd", "point_estimate", "ci_95_lower", "ci_95_upper", "treatment_mean", "control_mean", "treatment_sd_or_sem", "control_sd_or_sem", "treatment_n", "control_n", "p_value", "p_value_bound")
    for effect in doc.get("atomic_effects", []):
        for key in numeric_effect_fields:
            value = effect.get(key)
            if value is not None:
                _finite_numeric_evidence(value, f"{effect.get('effect_id')}: {key}")
    meta_for_dos = doc.get("study_metadata") or {}
    pmid = str(meta_for_dos.get("pmid", ""))
    _is_citation_only_meta = (
        meta_for_dos.get("source_text_type") == "Citation_Only_No_Abstract_Indexed"
        or meta_for_dos.get("abstract_indexed") is False
    )
    if dossier is None:
        dp = DOSSIER_DIR / f"{pmid}.json"
        if dp.exists():
            dossier = json.loads(dp.read_text(encoding="utf-8"))
        else:
            synth_ab = (
                None
                if _is_citation_only_meta
                else " ".join((e.get("verbatim_evidence_quote") or "") for e in doc.get("atomic_effects", []))
            )
            dossier = {"pmid": pmid, "title": meta_for_dos.get("title", ""), "abstract": synth_ab}
    if str(dossier.get("pmid") or "") != pmid:
        raise ValueError(f"Source dossier identity does not match study PMID {pmid}")
    validate_record_quote_and_locator_provenance(doc, dossier=dossier)
    expected_sha = _compute_dossier_sha256(pmid, dossier)
    pre_expected_sha = None
    own_ft = dossier.get("fulltext_data_sections") or {}
    ft = _get_effective_fulltext_sections(pmid, dossier)
    if pmid in PEER_REVIEWED_TO_PREPRINT_MAP and ft is not own_ft and ft != own_ft:
        pre_pmid = PEER_REVIEWED_TO_PREPRINT_MAP[pmid]
        pre_dp = DOSSIER_DIR / f"{pre_pmid}.json"
        if pre_dp.exists():
            pre_dos = json.loads(pre_dp.read_text(encoding="utf-8"))
            pre_expected_sha = _compute_dossier_sha256(pre_pmid, pre_dos)
    arms_by_id = {a["arm_id"]: a for a in doc.get("arms", [])}