OpenIslet

scripts/generate_release_manifest.py

Generate the Wave-0 / P0-8 Release & Provenance Manifest (`manifest.json`) and

script Release v0.8.0 gen-eb955f8266035aba 148 KB · 11 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/generate_release_manifest.py · SHA-256: 9b8e7a9ff4998368…

                            if used_chars + len(out_y) <= char_budget:
                                used_chars += len(out_y)
                            else:
                                eff["outcome_variable_Y"] = (
                                    f"[Endpoint: {eff.get('outcome_domain', 'General')} | polarity={pol_cls} | orientation_sign={orient_sign} | unit={_unit_tok}{_err_tok}]"
                                )
                    else:
                        eff["outcome_variable_Y"] = (
                            f"[Endpoint: {eff.get('outcome_domain', 'General')} | polarity={pol_cls} | orientation_sign={orient_sign} | unit={_unit_tok}{_err_tok}]"
                        )

                    comp_x0 = eff.get("comparator_X0") or ""
                    if not full_src_text:
                        eff["comparator_X0"] = "Control / comparator condition (see structured arm definitions)"
                    elif _max_verbatim_shingle_chars(comp_x0, full_src_text) > 0:
                        if used_chars + len(comp_x0) <= char_budget:
                            used_chars += len(comp_x0)
                        else:
                            eff["comparator_X0"] = "Control / comparator condition (see structured arm definitions)"

                    q_raw = eff.get("verbatim_evidence_quote")
                    q = q_orig
                    if q_raw is None:
                        # Citation-only records with no indexed abstract intentionally carry null quote;
                        # preserve null rather than fabricating a copyright-redaction hash for "".
                        eff["verbatim_evidence_quote"] = None
                    elif _is_authentic_redaction_marker(q):
                        # A validated opaque pointer already contains no quote;
                        # retain its source digest rather than hashing the token.
                        pass
                    elif used_chars + len(q) <= char_budget and len(q) > 0:
                        used_chars += len(q)
                    else:
                        q_sha = hashlib.sha256(q.encode("utf-8")).hexdigest()
                        span_tok = re.sub(r"[^A-Za-z0-9_.\[\]:|-]", "_", str(eff.get("source_span") or "none"))
                        eff["verbatim_evidence_quote"] = (
                            f"{_redaction_prefix_for_pmid(pmid)} see PMID:{pmid} field=verbatim_evidence_quote genes={genes_val} pert={pert_tag} quote_sha256={q_sha}]"
                        )
                # Enforce article-wide non-OA verbatim cap across all other source-derived text channels
                for arm in doc.get("arms", []):
                    for ed in arm.get("gate2_3_4_genetic_and_epitope_edits", []):
                        smc = ed.get("sub_molecular_coordinate") or {}
                        desc = smc.get("exact_variant_or_swap_description") or ""
                        if desc and not desc.startswith("Experimental perturbation of ") and not _is_authentic_redaction_marker(desc):
                            if used_chars + len(desc) <= char_budget:
                                used_chars += len(desc)
                            else:
                                d_sha = hashlib.sha256(desc.encode("utf-8")).hexdigest()
                                raw_mod = str(ed.get("edit_modality") or "none")
                                mod_tok = raw_mod if raw_mod in public_helper.MODALITIES else "none"
                                g_tok = ",".join(sorted(set(_expand_gene_symbol(str(ed.get("gene_symbol_hgnc") or ""))) & known_genes)) or "NONE"
                                smc["exact_variant_or_swap_description"] = (
                                    f"{_redaction_prefix_for_pmid(pmid)} see PMID:{pmid} field=exact_variant_or_swap_description mod={mod_tok} genes={g_tok} quote_sha256={d_sha}]"
                                )
                for em in doc.get("effect_modifier_interactions", []):
                    for mfield in ("level_1_condition_and_effect", "level_2_condition_and_effect", "mechanistic_explanation"):
                        mval = em.get(mfield) or ""
                        if mval and not _is_authentic_redaction_marker(mval):
                            if used_chars + len(mval) <= char_budget:
                                used_chars += len(mval)
                            else:
                                m_sha = hashlib.sha256(mval.encode("utf-8")).hexdigest()
                                fig_tok = re.sub(r"[^A-Za-z0-9_.\[\]:|-]", "_", str(em.get("source_figure_or_table") or "none"))
                                em[mfield] = (
                                    f"{_redaction_prefix_for_pmid(pmid)} see PMID:{pmid} field={mfield} quote_sha256={m_sha}]"
                                )
                for edge in doc.get("causal_mechanism_edges", []):
                    for nfield in ("upstream_node", "downstream_node"):
                        nval = edge.get(nfield) or ""
                        if "[" in nval and nval.endswith("]"):
                            nval = nval.split("[", 1)[0].strip()
                        if "(" in nval and nval.endswith(")") and (not full_src_text or _max_verbatim_shingle_chars(nval, full_src_text) > 0):
                            nval = nval.split("(", 1)[0].strip()
                        edge[nfield] = nval
                    esrc = edge.get("evidence_source") or ""
                    if esrc and not _is_authentic_redaction_marker(esrc):
                        if used_chars + len(esrc) <= char_budget:
                            used_chars += len(esrc)
                        else:
                            e_sha = hashlib.sha256(esrc.encode("utf-8")).hexdigest()
                            edge["evidence_source"] = f"{_redaction_prefix_for_pmid(pmid)} see PMID:{pmid} field=evidence_source quote_sha256={e_sha}]"
                bridges = doc.get("cross_study_discovery_bridges") or {}
                for rv in bridges.get("residual_failure_and_escape_vectors", []):
                    for rfield in ("residual_loss_or_limitation", "escape_mechanism_identified"):
                        rval = rv.get(rfield) or ""
                        if rval and not _is_authentic_redaction_marker(rval):
                            if used_chars + len(rval) <= char_budget:
                                used_chars += len(rval)
                            else:
                                r_sha = hashlib.sha256(rval.encode("utf-8")).hexdigest()
                                rv[rfield] = f"{_redaction_prefix_for_pmid(pmid)} see PMID:{pmid} field={rfield} quote_sha256={r_sha}]"
                for pf in bridges.get("collateral_and_pleiotropic_findings", []):
                    pval = pf.get("observation") or ""
                    if pval and not _is_authentic_redaction_marker(pval):
                        if used_chars + len(pval) <= char_budget:
                            used_chars += len(pval)
                        else:
                            p_sha = hashlib.sha256(pval.encode("utf-8")).hexdigest()
                            pf["observation"] = f"{_redaction_prefix_for_pmid(pmid)} see PMID:{pmid} field=observation quote_sha256={p_sha}]"
                for rt in bridges.get("regime_thresholds", []):
                    tval = rt.get("verbatim_quote") or ""
                    if tval and not _is_authentic_redaction_marker(tval):
                        if used_chars + len(tval) <= char_budget:
                            used_chars += len(tval)
                        else:
                            t_sha = hashlib.sha256(tval.encode("utf-8")).hexdigest()
                            rt["verbatim_quote"] = f"{_redaction_prefix_for_pmid(pmid)} see PMID:{pmid} field=verbatim_quote quote_sha256={t_sha}]"
                title_str = str((doc.get("study_metadata") or {}).get("title") or "")

                def _enforce_doc_shingle_budget(obj: object, parent_key: str = "", cur_eff_id: str = "", bibliographic: bool = False) -> object:
                    if isinstance(obj, dict):
                        eff_id_here = str(obj.get("effect_id") or cur_eff_id)
                        for k in list(obj.keys()):
                            obj[k] = _enforce_doc_shingle_budget(obj[k], k, eff_id_here,parent_key=='study_metadata')
                        return obj
                    if isinstance(obj, list):
                        for idx in range(len(obj)):
                            obj[idx] = _enforce_doc_shingle_budget(obj[idx], parent_key, cur_eff_id,bibliographic)
                        return obj
                    if isinstance(obj, str):
                        if _is_bounded_public_metadata(obj,parent_key,bibliographic=bibliographic):
                            return obj
                        if not full_src_text and _source_free_effect_identifier(obj, parent_key):
                            return obj
                        if parent_key == "verbatim_evidence_quote" and cur_eff_id in _pre_budgeted_quotes:
                            return obj
                        if _is_authentic_redaction_marker(obj) or _is_fixed_public_schema_metadata(obj, parent_key):
                            return obj
                        f_tok = _public_redaction_field(parent_key or "field")
                        gp_suffix = ""
                        if parent_key in ("focal_factor_X", "verbatim_evidence_quote") and cur_eff_id in eff_redaction_meta:
                            metadata = eff_focal_redaction_meta if parent_key == "focal_factor_X" else eff_redaction_meta
                            g_v, p_v = metadata[cur_eff_id]
                            gp_suffix = f" genes={g_v} pert={p_v}"
                        # Spoofed redaction prefix or missing dossier fails closed immediately
                        if obj.startswith("[REDACTED_NON_OA_EXCERPT:") or obj.startswith("[REDACTED_CONSERVATIVE_EXCERPT:"):
                            s_sha = hashlib.sha256(obj.encode("utf-8")).hexdigest()
                            return f"{_redaction_prefix_for_pmid(pmid)} see PMID:{pmid} field={f_tok}{gp_suffix} quote_sha256={s_sha}]"
                        v_len = _max_verbatim_shingle_chars(obj, full_src_text) if full_src_text else len(obj)
                        if v_len > 0:
                            if pmid_shingle_used[pmid] + v_len <= char_budget:
                                pmid_shingle_used[pmid] += v_len
                            else:
                                s_sha = hashlib.sha256(obj.encode("utf-8")).hexdigest()
                                return f"{_redaction_prefix_for_pmid(pmid)} see PMID:{pmid} field={f_tok}{gp_suffix} quote_sha256={s_sha}]"
                        return obj
                    return obj

                _pre_budgeted_quotes: set[str] = set()
                if not full_src_text:
                    for _e_pre in doc.get("atomic_effects", []):
                        _eid_pre = str(_e_pre.get("effect_id") or "")
                        _vq_pre = _e_pre.get("verbatim_evidence_quote") or ""
                        if isinstance(_vq_pre, str) and _vq_pre and not _is_authentic_redaction_marker(_vq_pre):
                            if _vq_pre.startswith("[REDACTED_NON_OA_EXCERPT:"):
                                _g_v, _p_v = eff_redaction_meta.get(_eid_pre, ("NONE", "NONE"))
                                _s_sha = hashlib.sha256(_vq_pre.encode("utf-8")).hexdigest()
                                _e_pre["verbatim_evidence_quote"] = f"{_redaction_prefix_for_pmid(pmid)} see PMID:{pmid} field=verbatim_evidence_quote genes={_g_v} pert={_p_v} quote_sha256={_s_sha}]"
                            elif pmid_shingle_used[pmid] + len(_vq_pre) <= char_budget:
                                pmid_shingle_used[pmid] += len(_vq_pre)
                                _pre_budgeted_quotes.add(_eid_pre)
                            else:
                                _g_v, _p_v = eff_redaction_meta.get(_eid_pre, ("NONE", "NONE"))
                                _s_sha = hashlib.sha256(_vq_pre.encode("utf-8")).hexdigest()
                                _e_pre["verbatim_evidence_quote"] = f"{_redaction_prefix_for_pmid(pmid)} see PMID:{pmid} field=verbatim_evidence_quote genes={_g_v} pert={_p_v} quote_sha256={_s_sha}]"
                _enforce_doc_shingle_budget(doc)
                sp.write_text(json.dumps(doc, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
            redacted_studies.append(doc)

        # Synchronize exported JSONL aliases and cross_study_discovery_graph.json in work_dir
        dossiers_jsonl = work_dir / "data" / "extracted" / "ring1_study_dossiers_v0.5.jsonl"
        with dossiers_jsonl.open("w", encoding="utf-8") as fh:
            for st in redacted_studies:
                fh.write(json.dumps(st, ensure_ascii=False) + "\n")

        effects_jsonl = work_dir / "data" / "extracted" / "ring1_atomic_effects_v0.5.jsonl"
        with effects_jsonl.open("w", encoding="utf-8") as fh:
            for st in redacted_studies:
                meta = st.get("study_metadata", {})
                pmid = str(meta.get("pmid", ""))
                cit = meta.get("citation_short", "")
                for eff in st.get("atomic_effects", []):
                    fh.write(json.dumps({"pmid": pmid, "citation_short": cit, "source_text_type": meta.get("source_text_type"), "superseded_by_pmid": meta.get("superseded_by_pmid"), **eff}, ensure_ascii=False) + "\n")

        graph_path = work_dir / "data" / "extracted" / "cross_study_discovery_graph.json"
        if graph_path.exists():
            g_obj = _rewrite_exact_arm_references(json.loads(graph_path.read_text(encoding="utf-8")), arm_identifier_map)
            def _extract_pmid(label_or_id: str) -> str:
                m_p = re.search(r"(?:PMID:)?(\d{7,8})", str(label_or_id or ""))
                return m_p.group(1) if m_p else ""

            def _strip_node_quote_suffix(node_str: str, pm: str) -> str:
                s = node_str
                if "[" in s and s.endswith("]"):
                    s = s.split("[", 1)[0].strip()
                if "(" in s and s.endswith(")"):
                    full_src_t, _ = dossier_source_cache.get(pm, ("", 0))
                    if not full_src_t or _max_verbatim_shingle_chars(s, full_src_t) > 0:
                        s = s.split("(", 1)[0].strip()
                return s

            for item in g_obj.get("regime_thresholds", []):
                pm = _extract_pmid(item.get("pmid") or item.get("study", ""))
                if pm in non_oa_pmids and item.get("verbatim_quote") and not _is_authentic_redaction_marker(item["verbatim_quote"]):
                    vq = item["verbatim_quote"]
                    item["verbatim_quote"] = f"{_redaction_prefix_for_pmid(pm)} see PMID:{pm} field=verbatim_quote quote_sha256={hashlib.sha256(vq.encode('utf-8')).hexdigest()}]"
            for item in g_obj.get("residual_failure_and_complementary_lever_pairs", []):
                pm = _extract_pmid(item.get("pmid") or item.get("study", ""))
                if pm in non_oa_pmids:
                    for rf_name in ("verbatim_quote", "residual_loss_or_limitation", "escape_mechanism_identified"):
                        vq = item.get(rf_name) or ""
                        if vq and not _is_authentic_redaction_marker(vq):
                            item[rf_name] = f"{_redaction_prefix_for_pmid(pm)} see PMID:{pm} field={rf_name} quote_sha256={hashlib.sha256(vq.encode('utf-8')).hexdigest()}]"
            for mclass, mod_list in (g_obj.get("effect_modifiers_by_canonical_class") or g_obj.get("effect_modifiers_by_class_Z1_to_Z8") or {}).items():
                for item in mod_list:
                    pm = _extract_pmid(item.get("study", ""))
                    if pm in non_oa_pmids:
                        for mf_name in ("level_1", "level_2", "mechanistic_explanation"):
                            mv = item.get(mf_name) or ""
                            if mv and not _is_authentic_redaction_marker(mv):
                                item[mf_name] = f"{_redaction_prefix_for_pmid(pm)} see PMID:{pm} field={mf_name} quote_sha256={hashlib.sha256(mv.encode('utf-8')).hexdigest()}]"
            for item in g_obj.get("cross_gate_pleiotropic_discoveries", []):
                pm = _extract_pmid(item.get("study", ""))
                if pm in non_oa_pmids:
                    obs = item.get("observation") or ""
                    if obs and not _is_authentic_redaction_marker(obs):
                        item["observation"] = f"{_redaction_prefix_for_pmid(pm)} see PMID:{pm} field=observation quote_sha256={hashlib.sha256(obs.encode('utf-8')).hexdigest()}]"
            bridge_nodes_obj = g_obj.get("shared_cross_study_bridge_nodes", {})
            for node in (bridge_nodes_obj.values() if isinstance(bridge_nodes_obj, dict) else bridge_nodes_obj):
                for lm in node.get("linked_mechanisms_and_bottlenecks", []):
                    pm = _extract_pmid(lm.get("study", ""))
                    if pm in non_oa_pmids:
                        stmt = lm.get("statement") or ""
                        if " -> " in stmt:
                            parts = stmt.split(" -> ", 1)
                            lhs = _strip_node_quote_suffix(parts[0].strip(), pm)
                            rhs = _strip_node_quote_suffix(parts[1].strip(), pm)
                            lm["statement"] = f"{lhs} -> {rhs}"
                        elif stmt and not _is_authentic_redaction_marker(stmt):
                            lm["statement"] = (
                                f"{_redaction_prefix_for_pmid(pm)} see PMID:{pm} field=statement quote_sha256={hashlib.sha256(stmt.encode('utf-8')).hexdigest()}]"
                            )
            for ch in g_obj.get("multi_hop_cross_study_causal_chains", []):
                for h_idx in (1, 2):
                    pm = _extract_pmid(ch.get(f"hop{h_idx}_study", ""))
                    if pm in non_oa_pmids:
                        for nf in ("hop1_from", "hop1_to", "hop2_to"):
                            if nf in ch and isinstance(ch[nf], str):
                                ch[nf] = _strip_node_quote_suffix(ch[nf], pm)
                        ev = ch.get(f"hop{h_idx}_evidence") or ""