from __future__ import annotations import argparse import json from pathlib import Path import sys from typing import Any sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from patientphex.lexicon import LiteralTrie, build_pattern_ids, calibrate_patterns, predict_documents from patientphex.ontology import HPOOntology def load_jsonl(path: Path) -> list[dict[str, Any]]: return [json.loads(line) for line in path.open(encoding="utf-8") if line.strip()] def main() -> None: parser = argparse.ArgumentParser(description="Build BIO, lexicon, and PhenoTagger deployment candidates.") parser.add_argument("--train-data", type=Path, required=True) parser.add_argument("--predict-data", type=Path, required=True) parser.add_argument("--ontology", type=Path, required=True) parser.add_argument("--bio-output", type=Path, required=True) parser.add_argument("--phenotagger-output", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--lexicon-threshold", type=float, default=0.55) parser.add_argument("--phenotagger-threshold", type=float, default=0.50) args = parser.parse_args() train_documents = load_jsonl(args.train_data) documents = load_jsonl(args.predict_data) document_by_id = {str(document["pmc_id"]): document for document in documents} ontology = HPOOntology.from_obo(args.ontology) bio = json.loads(args.bio_output.read_text(encoding="utf-8")) bio_candidates = { pmc_id: {tuple(map(int, span)) for span in spans} for pmc_id, spans in bio["candidates_at_0_30"].items() } bio_selected = { pmc_id: {tuple(map(int, span)) for span in spans} for pmc_id, spans in bio["best_predictions"].items() } pattern_ids = build_pattern_ids(ontology, train_documents) quality = calibrate_patterns(train_documents, pattern_ids, LiteralTrie(pattern_ids)) lexicon_predictions = predict_documents( documents, pattern_ids, quality, threshold=args.lexicon_threshold ) lexicon_by_id = {str(document["pmc_id"]): document for document in lexicon_predictions} pheno = json.loads(args.phenotagger_output.read_text(encoding="utf-8"))["raw_predictions"] output_documents: dict[str, list[dict[str, Any]]] = {} for pmc_id, document in document_by_id.items(): by_boundary: dict[tuple[int, int], dict[str, Any]] = {} lexicon_entities = { (int(entity["offset"]), int(entity["offset"]) + int(entity["length"])): entity for entity in lexicon_by_id[pmc_id]["entities"] } union = set(bio_candidates.get(pmc_id, set())) | set(lexicon_entities) for start, end in sorted(union): passage = next(( passage for passage in document.get("full_text", []) if int(passage["offset"]) <= start and end <= int(passage["offset"]) + len(passage["text"]) ), None) if passage is None or end <= start: continue local_start = start - int(passage["offset"]) text = passage["text"][local_start:local_start + end - start] lexicon_entity = lexicon_entities.get((start, end)) by_boundary[(start, end)] = { "start": start, "end": end, "text": text, "bio_candidate": (start, end) in bio_candidates.get(pmc_id, set()), "bio_best": (start, end) in bio_selected.get(pmc_id, set()), "lexicon": lexicon_entity is not None, "lexicon_identifier": lexicon_entity["identifier"] if lexicon_entity else None, "lexicon_quality": quality.get(text.lower(), 0.0) if lexicon_entity else 0.0, "phenotagger": False, "phenotagger_score": 0.0, "phenotagger_identifier": None, "gold_boundary": False, } for record in pheno.get(pmc_id, []): if float(record["score"]) < args.phenotagger_threshold: continue start, end = int(record["start"]), int(record["end"]) target = by_boundary.setdefault((start, end), { "start": start, "end": end, "text": record["text"], "bio_candidate": False, "bio_best": False, "lexicon": False, "lexicon_identifier": None, "lexicon_quality": 0.0, "phenotagger": False, "phenotagger_score": 0.0, "phenotagger_identifier": None, "gold_boundary": False, }) target["phenotagger"] = True target["phenotagger_score"] = float(record["score"]) target["phenotagger_identifier"] = record["identifier"] output_documents[pmc_id] = sorted( by_boundary.values(), key=lambda item: (int(item["start"]), int(item["end"])) ) result = { "configuration": { "lexicon_threshold": args.lexicon_threshold, "phenotagger_threshold": args.phenotagger_threshold, }, "documents": output_documents, "candidate_count": sum(map(len, output_documents.values())), } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8") print(json.dumps({"documents": len(output_documents), "candidate_count": result["candidate_count"]})) if __name__ == "__main__": main()