{"id":23370042,"url":"https://github.com/maastrichtu-ids/trapi-predict-kit","last_synced_at":"2026-03-10T10:32:11.227Z","repository":{"id":178587944,"uuid":"662091518","full_name":"MaastrichtU-IDS/trapi-predict-kit","owner":"MaastrichtU-IDS","description":"🧰 A package to help create and deploy Translator Reasoner APIs (TRAPI) from any prediction model exposed as a regular python function.","archived":false,"fork":false,"pushed_at":"2025-03-13T15:05:27.000Z","size":925,"stargazers_count":1,"open_issues_count":4,"forks_count":2,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-09-04T18:56:22.578Z","etag":null,"topics":["openapi","prediction-model","translator-api","trapi"],"latest_commit_sha":null,"homepage":"https://maastrichtu-ids.github.io/trapi-predict-kit","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MaastrichtU-IDS.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":"CITATION.cff","codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-07-04T10:36:00.000Z","updated_at":"2025-03-13T15:05:31.000Z","dependencies_parsed_at":"2024-01-25T11:17:45.904Z","dependency_job_id":"9f27e00d-b1c5-4ef7-9408-8ae145c4896a","html_url":"https://github.com/MaastrichtU-IDS/trapi-predict-kit","commit_stats":null,"previous_names":["maastrichtu-ids/trapi-predict-kit"],"tags_count":8,"template":false,"template_full_name":null,"purl":"pkg:github/MaastrichtU-IDS/trapi-predict-kit","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MaastrichtU-IDS%2Ftrapi-predict-kit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MaastrichtU-IDS%2Ftrapi-predict-kit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MaastrichtU-IDS%2Ftrapi-predict-kit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MaastrichtU-IDS%2Ftrapi-predict-kit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MaastrichtU-IDS","download_url":"https://codeload.github.com/MaastrichtU-IDS/trapi-predict-kit/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MaastrichtU-IDS%2Ftrapi-predict-kit/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30330576,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-10T05:25:20.737Z","status":"ssl_error","status_checked_at":"2026-03-10T05:25:17.430Z","response_time":106,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["openapi","prediction-model","translator-api","trapi"],"created_at":"2024-12-21T15:33:03.027Z","updated_at":"2026-03-10T10:32:11.203Z","avatar_url":"https://github.com/MaastrichtU-IDS.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n\n# 🧰 TRAPI Predict Kit\n\n[![PyPI - Version](https://img.shields.io/pypi/v/trapi-predict-kit.svg?logo=pypi\u0026label=PyPI\u0026logoColor=silver)](https://pypi.org/project/trapi-predict-kit/)\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/trapi-predict-kit.svg?logo=python\u0026label=Python\u0026logoColor=silver)](https://pypi.org/project/trapi-predict-kit/)\n[![license](https://img.shields.io/pypi/l/trapi-predict-kit.svg?color=%2334D058)](https://github.com/MaastrichtU-IDS/trapi-predict-kit/blob/main/LICENSE.txt)\n[![code style - black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n\n[![Test package](https://github.com/MaastrichtU-IDS/trapi-predict-kit/actions/workflows/test.yml/badge.svg)](https://github.com/MaastrichtU-IDS/trapi-predict-kit/actions/workflows/test.yml)\n\n\u003c/div\u003e\n\nA package to help create and deploy Translator Reasoner APIs (TRAPI) from any prediction model exposed as a regular python function.\n\nThe **TRAPI Predict Kit** helps data scientists build, and **publish prediction models** in a [FAIR](https://www.go-fair.org/fair-principles/) and reproducible manner. It provides helpers for various steps of the process:\n\n* A template to help user quickly bootstrap a new prediction project with the recommended structure ([MaastrichtU-IDS/cookiecutter-trapi-predict-kit](https://github.com/MaastrichtU-IDS/cookiecutter-trapi-predict-kit/))\n* Helper function to easily save a generated model, its metadata, and the data used to generate it. It uses tools such as [`dvc`](https://dvc.org/) to store large model outside of the git repository.\n* Deploy API endpoints for retrieving predictions, which comply with the NCATS Biomedical Data Translator standards ([Translator Reasoner API](https://github.com/NCATSTranslator/ReasonerAPI) and [BioLink model](https://github.com/biolink/biolink-model)), using a decorator `@trapi_predict` to simply annotate the function that produces predicted associations for a given input entity\n\nPredictions are usually generated from machine learning models (e.g. predict disease treated by drug), but it can adapt to generic python function, as long as the input params and return object follow the expected structure.\n\nCheckout the documentation website at **[maastrichtu-ids.github.io/trapi-predict-kit](https://maastrichtu-ids.github.io/trapi-predict-kit)** for more details.\n\n## 📦️ Installation\n\nThis package requires Python \u003e=3.7, simply install it with:\n\n```shell\npip install trapi-predict-kit\n```\n\nTo also include uvicorn/gunicorn for deployment:\n\n```bash\npip install trapi-predict-kit[web]\n```\n\n## 🪄 Usage\n\n### 🍪 Start a new prediction project\n\nA template to help user quickly bootstrap a new prediction project with the recommended structure ([MaastrichtU-IDS/cookiecutter-openpredict-api](https://github.com/MaastrichtU-IDS/cookiecutter-openpredict-api/))\n\nYou can use [**our cookiecutter template**](https://github.com/MaastrichtU-IDS/cookiecutter-openpredict-api/) to quickly bootstrap a repository with everything ready to start developing your prediction models, to then easily publish, and integrate them in the Translator ecosystem\n\n```bash\npip install cookiecutter\ncookiecutter https://github.com/MaastrichtU-IDS/cookiecutter-openpredict-api\n```\n\n### 🔮 Define the prediction endpoint(s)\n\nThe `trapi_predict_kit` package provides a decorator `@trapi_predict` to annotate your functions that generate predictions. Predictions generated from functions decorated with `@trapi_predict` can easily be imported in the Translator OpenPredict API, exposed as an API endpoint to get predictions from the web, and queried through the  Translator Reasoner API (TRAPI).\n\nThe annotated predict functions are expected to take 2 input  arguments: the input ID (string) and options for the prediction (dictionary). And it should return a dictionary with a list of predicted associated entities hits. Here is an example:\n\n ```python\nfrom trapi_predict_kit import trapi_predict, PredictInput, PredictOutput\n\n@trapi_predict(\n    path='/predict',\n    name=\"Get predicted targets for a given entity\",\n    description=\"Return the predicted targets for a given entity: drug (DrugBank ID) or disease (OMIM ID), with confidence scores.\",\n    edges=[\n        {\n            'subject': 'biolink:Drug',\n            'predicate': 'biolink:treats',\n            'inverse': 'biolink:treated_by',\n            'object': 'biolink:Disease',\n        },\n    ],\n    nodes={\n        \"biolink:Disease\": {\n            \"id_prefixes\": [\n                \"OMIM\"\n            ]\n        },\n        \"biolink:Drug\": {\n            \"id_prefixes\": [\n                \"DRUGBANK\"\n            ]\n        }\n    }\n)\ndef get_predictions(request: PredictInput) -\u003e PredictOutput:\n    predictions = []\n    # Add the code the load the model and get predictions here\n    # Available props: request.subjects, request.objects, request.options\n    for subj in request.subjects:\n        predictions.append({\n            \"subject\": subj,\n            \"object\": \"OMIM:246300\",\n            \"score\": 0.12345,\n            \"object_label\": \"Leipirudin\",\n            \"object_type\": \"biolink:Drug\",\n        })\n    for obj in request.objects:\n        predictions.append({\n            \"subject\": \"DRUGBANK:DB00001\",\n            \"object\": obj,\n            \"score\": 0.12345,\n            \"object_label\": \"Leipirudin\",\n            \"object_type\": \"biolink:Drug\",\n        })\n    return {\"hits\": predictions, \"count\": len(predictions)}\n ```\n\n### Define the TRAPI object\n\nYou will need to instantiate a `TRAPI` class to deploy a Translator Reasoner API serving a list of prediction functions that have been decorated with `@trapi_predict`. For example:\n\n```python\nimport logging\n\nfrom trapi_predict_kit.config import settings\nfrom trapi_predict_kit import TRAPI\n# TODO: change to your module name\nfrom my_model.predict import get_predictions\n\nlog_level = logging.INFO\nlogging.basicConfig(level=log_level)\n\nopenapi_info = {\n    \"contact\": {\n        \"name\": \"Firstname Lastname\",\n        \"email\": \"email@example.com\",\n        # \"x-id\": \"https://orcid.org/0000-0000-0000-0000\",\n        \"x-role\": \"responsible developer\",\n    },\n    \"license\": {\n        \"name\": \"MIT license\",\n        \"url\": \"https://opensource.org/licenses/MIT\",\n    },\n    \"termsOfService\": 'https://github.com/your-org-or-username/my-model/blob/main/LICENSE.txt',\n\n    \"x-translator\": {\n        \"component\": 'KP',\n        # TODO: update the Translator team to yours\n        \"team\": [ \"Clinical Data Provider\" ],\n        \"biolink-version\": settings.BIOLINK_VERSION,\n        \"infores\": 'infores:openpredict',\n        \"externalDocs\": {\n            \"description\": \"The values for component and team are restricted according to this external JSON schema. See schema and examples at url\",\n            \"url\": \"https://github.com/NCATSTranslator/translator_extensions/blob/production/x-translator/\",\n        },\n    },\n    \"x-trapi\": {\n        \"version\": settings.TRAPI_VERSION,\n        \"asyncquery\": False,\n        \"operations\": [\n            \"lookup\",\n        ],\n        \"externalDocs\": {\n            \"description\": \"The values for version are restricted according to the regex in this external JSON schema. See schema and examples at url\",\n            \"url\": \"https://github.com/NCATSTranslator/translator_extensions/blob/production/x-trapi/\",\n        },\n    }\n}\n\napp = TRAPI(\n    predict_endpoints=[ get_predictions ],\n    info=openapi_info,\n    title='OpenPredict TRAPI',\n    version='1.0.0',\n    openapi_version='3.0.1',\n    description=\"\"\"Machine learning models to produce predictions that can be integrated to Translator Reasoner APIs.\n\\n\\nService supported by the [NCATS Translator project](https://ncats.nih.gov/translator/about)\"\"\",\n    itrb_url_prefix=\"openpredict\",\n    dev_server_url=\"https://openpredict.semanticscience.org\",\n)\n```\n\n### Deploy the API\n\nRun the webserver with the path to the api file:\n\n```bash\nuvicorn src.my_model.api:app --port 8808 --reload\n```\n\n### 💾 Save a generated model\n\nHelper function to easily save a generated model, its metadata, and the data used to generate it. It uses tools such as [`dvc`](https://dvc.org/) to store large model outside of the git repository.\n\n```python\nfrom trapi_predict_kit import save\n\nhyper_params = {\n    'penalty': 'l2',\n    'dual': False,\n    'tol': 0.0001,\n    'C': 1.0,\n    'random_state': 100\n}\n\nsaved_model = save(\n    model=clf,\n    path=\"models/my_model\",\n    sample_data=sample_data,\n    hyper_params=hyper_params,\n    scores=scores,\n)\n```\n\n## 🧑‍💻 Development setup\n\nThe final section of the README is for if you want to run the package in development, and get involved by making a code contribution.\n\n### 📥️ Clone\n\nClone the repository:\n\n```bash\ngit clone https://github.com/MaastrichtU-IDS/trapi-predict-kit\ncd trapi-predict-kit\n```\n\n### 🐣 Install dependencies\n\nInstall [Hatch](https://hatch.pypa.io), this will automatically handle virtual environments and make sure all dependencies are installed when you run a script in the project:\n\n```bash\npip install --upgrade hatch\n```\n\nInstall the dependencies in a local virtual environment:\n\n```bash\nhatch -v env create\n```\n\nTo test it locally with python 3.7 use mamba or conda:\n\n```bash\nmamba create -n py37 python=3.7\n```\n\n### 🧑‍💻 Develop\n\nRun the API for development defined in `tests/dev.py`:\n\n```bash\nhatch run api\n```\n\n### ☑️ Run tests\n\nMake sure the existing tests still work by running ``pytest``. Note that any pull requests to the fairworkflows repository on github will automatically trigger running of the test suite;\n\n```bash\nhatch run test\n```\n\nTo display all logs when debugging:\n\n```bash\nhatch run test -s\n```\n\n### 🧹 Code formatting\n\nThe code will be automatically formatted when you commit your changes using `pre-commit`. But you can also run the script to format the code yourself:\n\n```\nhatch run fmt\n```\n\n### 📖 Update docs\n\nServe docs locally with `mkdocs`:\n\n```bash\nhatch run docs\n```\n\nThe documentation website is automatically updated by a GitHub action workflow.\n\n### ♻️ Reset the environment\n\nIn case you are facing issues with dependencies not updating properly you can easily reset the virtual environment with:\n\n```bash\nhatch env prune\n```\n\n### 🏷️ New release process\n\nThe deployment of new releases is done automatically by a GitHub Action workflow when a new release is created on GitHub. To release a new version:\n\n1. Make sure the `PYPI_TOKEN` secret has been defined in the GitHub repository (in Settings \u003e Secrets \u003e Actions). You can get an API token from PyPI at [pypi.org/manage/account](https://pypi.org/manage/account).\n2. Increment the `version` number in the `pyproject.toml` file in the root folder of the repository.\n\n    ```bash\n    hatch version fix\n    ```\n\n3. Create a new release on GitHub, which will automatically trigger the publish workflow, and publish the new release to PyPI.\n\nYou can also manually trigger the workflow from the Actions tab in your GitHub repository webpage.\n\nOr use `hatch`:\n\n```bash\nhatch build\nhatch publish -u \"__token__\"\n```\n\nAnd create the release with `gh`:\n\n```bash\ngh release create\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaastrichtu-ids%2Ftrapi-predict-kit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmaastrichtu-ids%2Ftrapi-predict-kit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaastrichtu-ids%2Ftrapi-predict-kit/lists"}