for sp_re in sorted((staging_dir / "data" / "extracted").glob("*.json"), key=lambda p: p.stem): if sp_re.stem.isdigit(): st_re = json.loads(sp_re.read_text(encoding="utf-8")) export_schema_re.validate(st_re) if public_token_errors(st_re, str(st_re["study_metadata"]["pmid"])): raise ValueError("Public study contains an invalid opaque reference") g_re = staging_dir / "data/extracted/cross_study_discovery_graph.json" if g_re.exists() and public_token_errors(json.loads(g_re.read_text(encoding="utf-8"))): raise ValueError("Public graph contains an invalid opaque reference") ceg_re = staging_dir / "data/extracted/context_evidence_graph_v1.json" if ceg_re.exists() and public_token_errors(json.loads(ceg_re.read_text(encoding="utf-8"))): raise ValueError("Public Context-Evidence Graph contains an invalid opaque reference") verify_public_bundle_privacy_guard(staging_dir, source_root=ROOT, require_private_pattern_file=False) if _regular_file_bytes(ROOT, "manifest.json") != manifest_bytes: raise ValueError("Canonical manifest changed during export") for rel in sorted(included - {"manifest.json"}): _verify_pinned_source(ROOT, rel, manifest) except BaseException: if staging_dir.exists(): shutil.rmtree(staging_dir, ignore_errors=True) raise finally: if policy_token is not None: _PUBLIC_POLICY_SNAPSHOT.reset(policy_token) _sys_re.dont_write_bytecode = previous_bytecode backup_dir = None try: require_lease() backup_dir = Path(tempfile.mkdtemp(prefix=f".{final_dest_dir.name}.rollback-", dir=final_dest_dir.parent)) backup_dir.rmdir() if final_dest_dir.exists(): final_dest_dir.rename(backup_dir) require_lease() staging_dir.rename(final_dest_dir) require_lease() except BaseException: owned = publication_lease is None or publication_lease.owns_lock() if owned and backup_dir is not None and backup_dir.exists() and not final_dest_dir.exists(): backup_dir.rename(final_dest_dir) if staging_dir.exists(): shutil.rmtree(staging_dir, ignore_errors=True) raise if backup_dir is not None and backup_dir.exists(): require_lease() shutil.rmtree(backup_dir) return sorted(included) final_dest_dir.parent.mkdir(parents=True, exist_ok=True) require_lease() staging_dir = Path(tempfile.mkdtemp(prefix=f".{final_dest_dir.name}.staging-", dir=final_dest_dir.parent)) policy_token = None import sys previous_bytecode = sys.dont_write_bytecode sys.dont_write_bytecode = True previous_sys_path = list(sys.path) try: (staging_dir / ".openislet_public_bundle").write_text( "openislet_public_bundle_v0.8.0\n", encoding="utf-8" ) work_dir = staging_dir for rel in sorted(included): require_lease() src = ROOT / rel if _has_symlink_component(src, stop_at=ROOT): raise ValueError(f"Symlink not permitted in public bundle export: {src}") dst = work_dir / rel dst.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src, dst) _verify_pinned_source(work_dir, rel, manifest) import types public_helper = types.ModuleType('openislet_export_snapshot_policy') public_helper.__file__ = str(work_dir / 'scripts/public_excerpt_policy.py') exec(compile(_regular_file_bytes(work_dir, 'scripts/public_excerpt_policy.py'), public_helper.__file__, 'exec'), public_helper.__dict__) schema_bytes = _regular_file_bytes(work_dir, 'schemas/extraction_schema_v0.2.json') policy_token = _PUBLIC_POLICY_SNAPSHOT.set({'helper':public_helper, 'schema':schema_bytes}) discovery_path = work_dir / "data/raw/corpus_manifest_all_sources.jsonl" if discovery_path.exists(): discovery_rows = [json.loads(line) for line in discovery_path.read_text(encoding="utf-8").splitlines() if line.strip()] public_rows = [_public_discovery_record(row) for row in discovery_rows] if public_rows != discovery_rows: discovery_path.write_text("".join(json.dumps(row, ensure_ascii=False, allow_nan=False) + "\n" for row in public_rows), encoding="utf-8") # Collect known gene symbols and aliases so redacted non-OA quotes preserve exact gene attribution in rank_islet1_stacks.py import importlib.util as _ilu _rank_spec = _ilu.spec_from_file_location("openislet_rank_helper", work_dir / "scripts" / "rank_islet1_stacks.py") _rank_mod = _ilu.module_from_spec(_rank_spec) _rank_spec.loader.exec_module(_rank_mod) _strict_gene_match = _rank_mod.strict_gene_match def _expand_gene_symbol(raw_g: str) -> list[str]: if not raw_g: return [] if raw_g == "HLA-B_HLA-C_HLA-A24": return ["HLA-B", "HLA-C", "HLA-A"] if raw_g == "IL10_TGFB1_IL2_N88D": return ["IL10", "TGFB1", "IL2"] if raw_g == "JAK1_JAK2": return ["JAK1", "JAK2"] if "_" in raw_g: return [tok for tok in raw_g.split("_") if tok and not re.match(r"^[A-Z]\d+[A-Z]$", tok)] return [raw_g] omics_raw = json.loads(_regular_file_bytes(work_dir, 'data/omics/target_prior_table.json')) omics_targets = omics_raw.get("targets", []) if isinstance(omics_raw, dict) else [] omics_genes = {t["gene_symbol"] for t in omics_targets if isinstance(t, dict) and t.get("gene_symbol")} | set((omics_raw.get("target_priors") or {}).keys()) alias_map = { "ZN-T8": "SLC30A8", "ZNT8": "SLC30A8", "IGRP": "G6PC2", "GAD65": "GAD2", "IA-2": "PTPRN", "PD-L1": "CD274", "PDL1": "CD274", "A20": "TNFAIP3", "PI-9": "SERPINB9", "MDA5": "IFIH1", "CAR": "CXADR", "ICASP9": "CASP9", "IND-CASP9": "CASP9", "IL-10": "IL10", } known_genes = omics_genes | set(alias_map.values()) study_paths = sorted( [p for p in (work_dir / "data" / "extracted").glob("*.json") if p.stem.isdigit()], key=lambda p: p.stem, ) for sp in study_paths: doc = json.loads(sp.read_text(encoding="utf-8")) for arm in doc.get("arms", []): for ed in arm.get("gate2_3_4_genetic_and_epitope_edits", []): for g_atom in _expand_gene_symbol(str(ed.get("gene_symbol_hgnc") or "")): known_genes.add(g_atom) _validate_public_redaction_token("") known_genes &= public_helper.GENES # Identifier slugs must not become an encoded source-prose channel. # The private IDs remain untouched; publish a deterministic bijection. arm_identifier_map = {} for study_path in study_paths: source_study = json.loads(study_path.read_text(encoding="utf-8")) source_pmid = str(source_study["study_metadata"]["pmid"]) for index, arm in enumerate(source_study.get("arms", []), 1): old_id, new_id = arm["arm_id"], f"pmid{source_pmid}_arm{index}" if old_id in arm_identifier_map and arm_identifier_map[old_id] != new_id: raise ValueError("Non-unique study arm identifier cannot be safely exported") arm_identifier_map[old_id] = new_id marker_readout_genes = {"INS", "GCG", "SST", "CHGA", "NKX6-1", "PDX1", "MAFA"} gof_tokens = ( "OVEREXPRESSION", "OVEREXPRESS", "KNOCK-IN", "KNOCKIN", "TRANSGENE", "TRANSGENIC", "ECTOPIC", "LENTIVIRAL", "GAIN-OF-FUNCTION", "GAIN OF FUNCTION", "FORCED EXPRESSION", "CONSTITUTIVE EXPRESSION", "INDUCIBLE EXPRESSION", ) ko_tokens = ( "KNOCKOUT", " KO ", " KO,", " KO.", "-/-", "−/−", "DEFICIENT", "DEFICIENCY", "DELETION", "NULL", "ABLATION", "SILENCING", "SHRNA", "SIRNA", "LOSS-OF-FUNCTION", "LOSS OF FUNCTION", "INHIBITION", "INHIBITOR", "BLOCKADE", ) redacted_studies = [] non_oa_pmids: set[str] = set() seen_pmids: set[str] = set() dossier_source_cache: dict[str, tuple[str, int]] = {} # Shared per-PMID verbatim shingle counter across BOTH study JSONs and cross_study_discovery_graph.json pmid_shingle_used: dict[str, int] = {} for sp in study_paths: doc = _rewrite_exact_arm_references(json.loads(sp.read_text(encoding="utf-8")), arm_identifier_map) meta = doc.get("study_metadata", {}) pmid = str(meta.get("pmid", sp.stem)) if pmid != sp.stem or pmid in seen_pmids or re.fullmatch(r'[1-9][0-9]{0,8}',pmid) is None: raise ValueError('Study filename, PMID and unique article identity must agree') seen_pmids.add(pmid) source_path = (ROOT / "data" / "dossiers") / f"{pmid}.json" imported_source = read_dossier(source_path) if source_path.exists() else None _validate_imported_redaction_tokens(doc, pmid, imported_source) has_verified_open_license = ( pmid in VERIFIED_OPEN_LICENSE_PMIDS and meta.get("license") in ("CC-BY", "CC-BY-4.0", "CC0", "Public_Domain") ) if not has_verified_open_license: non_oa_pmids.add(pmid) dos_path = (ROOT / "data" / "dossiers") / f"{pmid}.json" full_src_text = "" if dos_path.exists(): dos_obj = read_dossier(dos_path) ab_str = dos_obj.get("abstract") or "" ab_len = max(1, len(ab_str)) ft_secs = dos_obj.get("fulltext_data_sections") or {} full_src_text = " ".join( [ str(dos_obj.get("title") or ""), ab_str ] + [ str(v) for v in ft_secs.values() if v ] ) char_budget = min(max_non_oa_chars, max(0, int((max_non_oa_share - 0.01) * ab_len))) else: # Fail closed (budget = 0) when a non-OA study has no local dossier char_budget = 0 dossier_source_cache[pmid] = (full_src_text, char_budget) pmid_shingle_used[pmid] = 0 used_chars = 0 study_genes = { g_atom for arm in doc.get("arms", []) for ed in arm.get("gate2_3_4_genetic_and_epitope_edits", []) for g_atom in _expand_gene_symbol(str(ed.get("gene_symbol_hgnc") or "")) } eff_redaction_meta: dict[str, tuple[str, str]] = {} eff_focal_redaction_meta: dict[str, tuple[str, str]] = {} for eff in doc.get("atomic_effects", []): focal_only = eff.get("focal_factor_X") or "" focal_only_u = focal_only.upper() q_orig = eff.get("verbatim_evidence_quote") or "" fx_orig = focal_only + " " + q_orig fx_orig_u = fx_orig.upper() matched_g = set() for g in known_genes: txt_g = focal_only if (g in marker_readout_genes and g not in study_genes) else fx_orig txt_g_u = focal_only_u if (g in marker_readout_genes and g not in study_genes) else fx_orig_u if g.upper() in txt_g_u and _strict_gene_match(g, txt_g): matched_g.add(g) for al, can in alias_map.items(): txt_a = focal_only if (can in marker_readout_genes and can not in study_genes) else fx_orig txt_a_u = focal_only_u if (can in marker_readout_genes and can not in study_genes) else fx_orig_u if al in txt_a_u and _strict_gene_match(al, txt_a): matched_g.add(can) if not matched_g and len(study_genes) == 1: matched_g = set(study_genes) has_gof = any(tok in focal_only_u or tok in fx_orig_u for tok in gof_tokens) has_ko = any(tok in focal_only_u or tok in fx_orig_u for tok in ko_tokens) pert_tag = "BOTH" if (has_gof and has_ko) else ("GOF_OE" if has_gof else ("KO_LOF" if has_ko else "NONE")) genes_val = ",".join(sorted(matched_g)) if matched_g else "NONE" effect_key = str(eff.get("effect_id") or "") eff_redaction_meta[effect_key] = (genes_val, pert_tag) # Focal metadata must not acquire additional readout genes # from the evidence quote when public wording is redacted. focal_genes = {g for g in known_genes if _strict_gene_match(g, focal_only)} focal_genes.update(can for alias, can in alias_map.items() if can in known_genes and _strict_gene_match(alias, focal_only)) focal_genes_val = ",".join(sorted(focal_genes)) if focal_genes else "NONE" eff_focal_redaction_meta[effect_key] = (focal_genes_val, pert_tag) # Replace verbatim sentence slice in outcome_variable_Y with structured endpoint descriptor out_y = eff.get("outcome_variable_Y") or "" pol_reg = eff.get("endpoint_polarity_registry") or {} pol_cls = pol_reg.get("polarity_class", "higher_is_better") orient_sign = pol_reg.get("orientation_sign", 1) _unit_tok = str(eff.get("measurement_unit") or "qualitative_statement") if not _is_fixed_public_schema_metadata(_unit_tok, "measurement_unit"): _unit_tok = "qualitative_statement" _err_tok = " | erratum_pmid=41887653" if "41887653" in out_y else "" if not full_src_text: eff["outcome_variable_Y"] = ( f"[Endpoint: {eff.get('outcome_domain', 'General')} | polarity={pol_cls} | orientation_sign={orient_sign} | unit={_unit_tok}{_err_tok}]" ) elif out_y.startswith("[Endpoint:"): # Curated structured endpoint summary: verify if it shares any 6-word verbatim shingle with source dossier v_len = _max_verbatim_shingle_chars(out_y, full_src_text) if v_len > 0: