trapi-predict-kit

๐Ÿงฐ A package to help create and deploy Translator Reasoner APIs (TRAPI) from any prediction model exposed as a regular python function.

https://github.com/maastrichtu-ids/trapi-predict-kit

Science Score: 62.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • โœ“
    CITATION.cff file
    Found CITATION.cff file
  • โœ“
    codemeta.json file
    Found codemeta.json file
  • โœ“
    .zenodo.json file
    Found .zenodo.json file
  • โ—‹
    DOI references
  • โœ“
    Academic publication links
    Links to: science.org
  • โ—‹
    Academic email domains
  • โœ“
    Institutional organization owner
    Organization maastrichtu-ids has institutional domain (www.maastrichtuniversity.nl)
  • โ—‹
    JOSS paper metadata
  • โ—‹
    Scientific vocabulary similarity
    Low similarity (15.3%) to scientific vocabulary

Keywords

openapi prediction-model translator-api trapi
Last synced: 6 months ago · JSON representation ·

Repository

๐Ÿงฐ A package to help create and deploy Translator Reasoner APIs (TRAPI) from any prediction model exposed as a regular python function.

Basic Info
Statistics
  • Stars: 1
  • Watchers: 3
  • Forks: 2
  • Open Issues: 4
  • Releases: 8
Topics
openapi prediction-model translator-api trapi
Created over 2 years ago · Last pushed 11 months ago
Metadata Files
Readme License Citation

README.md

# ๐Ÿงฐ TRAPI Predict Kit [![PyPI - Version](https://img.shields.io/pypi/v/trapi-predict-kit.svg?logo=pypi&label=PyPI&logoColor=silver)](https://pypi.org/project/trapi-predict-kit/) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/trapi-predict-kit.svg?logo=python&label=Python&logoColor=silver)](https://pypi.org/project/trapi-predict-kit/) [![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) [![code style - black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) [![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)

A package to help create and deploy Translator Reasoner APIs (TRAPI) from any prediction model exposed as a regular python function.

The TRAPI Predict Kit helps data scientists build, and publish prediction models in a FAIR and reproducible manner. It provides helpers for various steps of the process:

  • A template to help user quickly bootstrap a new prediction project with the recommended structure (MaastrichtU-IDS/cookiecutter-trapi-predict-kit)
  • Helper function to easily save a generated model, its metadata, and the data used to generate it. It uses tools such as dvc to store large model outside of the git repository.
  • Deploy API endpoints for retrieving predictions, which comply with the NCATS Biomedical Data Translator standards (Translator Reasoner API and BioLink model), using a decorator @trapi_predict to simply annotate the function that produces predicted associations for a given input entity

Predictions 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.

Checkout the documentation website at maastrichtu-ids.github.io/trapi-predict-kit for more details.

๐Ÿ“ฆ๏ธ Installation

This package requires Python >=3.7, simply install it with:

shell pip install trapi-predict-kit

To also include uvicorn/gunicorn for deployment:

bash pip install trapi-predict-kit[web]

๐Ÿช„ Usage

๐Ÿช Start a new prediction project

A template to help user quickly bootstrap a new prediction project with the recommended structure (MaastrichtU-IDS/cookiecutter-openpredict-api)

You can use our cookiecutter template 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

bash pip install cookiecutter cookiecutter https://github.com/MaastrichtU-IDS/cookiecutter-openpredict-api

๐Ÿ”ฎ Define the prediction endpoint(s)

The 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).

The 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:

```python from trapipredictkit import trapi_predict, PredictInput, PredictOutput

@trapipredict( path='/predict', name="Get predicted targets for a given entity", description="Return the predicted targets for a given entity: drug (DrugBank ID) or disease (OMIM ID), with confidence scores.", edges=[ { 'subject': 'biolink:Drug', 'predicate': 'biolink:treats', 'inverse': 'biolink:treatedby', 'object': 'biolink:Disease', }, ], nodes={ "biolink:Disease": { "idprefixes": [ "OMIM" ] }, "biolink:Drug": { "idprefixes": [ "DRUGBANK" ] } } ) def getpredictions(request: PredictInput) -> PredictOutput: predictions = [] # Add the code the load the model and get predictions here # Available props: request.subjects, request.objects, request.options for subj in request.subjects: predictions.append({ "subject": subj, "object": "OMIM:246300", "score": 0.12345, "objectlabel": "Leipirudin", "objecttype": "biolink:Drug", }) for obj in request.objects: predictions.append({ "subject": "DRUGBANK:DB00001", "object": obj, "score": 0.12345, "objectlabel": "Leipirudin", "object_type": "biolink:Drug", }) return {"hits": predictions, "count": len(predictions)} ```

Define the TRAPI object

You 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:

```python import logging

from trapipredictkit.config import settings from trapipredictkit import TRAPI

TODO: change to your module name

from mymodel.predict import getpredictions

loglevel = logging.INFO logging.basicConfig(level=loglevel)

openapi_info = { "contact": { "name": "Firstname Lastname", "email": "email@example.com", # "x-id": "https://orcid.org/0000-0000-0000-0000", "x-role": "responsible developer", }, "license": { "name": "MIT license", "url": "https://opensource.org/licenses/MIT", }, "termsOfService": 'https://github.com/your-org-or-username/my-model/blob/main/LICENSE.txt',

"x-translator": {
    "component": 'KP',
    # TODO: update the Translator team to yours
    "team": [ "Clinical Data Provider" ],
    "biolink-version": settings.BIOLINK_VERSION,
    "infores": 'infores:openpredict',
    "externalDocs": {
        "description": "The values for component and team are restricted according to this external JSON schema. See schema and examples at url",
        "url": "https://github.com/NCATSTranslator/translator_extensions/blob/production/x-translator/",
    },
},
"x-trapi": {
    "version": settings.TRAPI_VERSION,
    "asyncquery": False,
    "operations": [
        "lookup",
    ],
    "externalDocs": {
        "description": "The values for version are restricted according to the regex in this external JSON schema. See schema and examples at url",
        "url": "https://github.com/NCATSTranslator/translator_extensions/blob/production/x-trapi/",
    },
}

}

app = TRAPI( predictendpoints=[ getpredictions ], info=openapiinfo, title='OpenPredict TRAPI', version='1.0.0', openapiversion='3.0.1', description="""Machine learning models to produce predictions that can be integrated to Translator Reasoner APIs. \n\nService supported by the NCATS Translator project""", itrburlprefix="openpredict", devserverurl="https://openpredict.semanticscience.org", ) ```

Deploy the API

Run the webserver with the path to the api file:

bash uvicorn src.my_model.api:app --port 8808 --reload

๐Ÿ’พ Save a generated model

Helper function to easily save a generated model, its metadata, and the data used to generate it. It uses tools such as dvc to store large model outside of the git repository.

```python from trapipredictkit import save

hyperparams = { 'penalty': 'l2', 'dual': False, 'tol': 0.0001, 'C': 1.0, 'randomstate': 100 }

savedmodel = save( model=clf, path="models/mymodel", sampledata=sampledata, hyperparams=hyperparams, scores=scores, ) ```

๐Ÿง‘โ€๐Ÿ’ป Development setup

The final section of the README is for if you want to run the package in development, and get involved by making a code contribution.

๐Ÿ“ฅ๏ธ Clone

Clone the repository:

bash git clone https://github.com/MaastrichtU-IDS/trapi-predict-kit cd trapi-predict-kit

๐Ÿฃ Install dependencies

Install Hatch, this will automatically handle virtual environments and make sure all dependencies are installed when you run a script in the project:

bash pip install --upgrade hatch

Install the dependencies in a local virtual environment:

bash hatch -v env create

To test it locally with python 3.7 use mamba or conda:

bash mamba create -n py37 python=3.7

๐Ÿง‘โ€๐Ÿ’ป Develop

Run the API for development defined in tests/dev.py:

bash hatch run api

โ˜‘๏ธ Run tests

Make 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;

bash hatch run test

To display all logs when debugging:

bash hatch run test -s

๐Ÿงน Code formatting

The 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:

hatch run fmt

๐Ÿ“– Update docs

Serve docs locally with mkdocs:

bash hatch run docs

The documentation website is automatically updated by a GitHub action workflow.

โ™ป๏ธ Reset the environment

In case you are facing issues with dependencies not updating properly you can easily reset the virtual environment with:

bash hatch env prune

๐Ÿท๏ธ New release process

The 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:

  1. Make sure the PYPI_TOKEN secret has been defined in the GitHub repository (in Settings > Secrets > Actions). You can get an API token from PyPI at pypi.org/manage/account.
  2. Increment the version number in the pyproject.toml file in the root folder of the repository.

    bash hatch version fix

  3. Create a new release on GitHub, which will automatically trigger the publish workflow, and publish the new release to PyPI.

You can also manually trigger the workflow from the Actions tab in your GitHub repository webpage.

Or use hatch:

bash hatch build hatch publish -u "__token__"

And create the release with gh:

bash gh release create

Owner

  • Name: Maastricht University IDS
  • Login: MaastrichtU-IDS
  • Kind: organization
  • Email: info-ids@maastrichtuniversity.nl
  • Location: Maastricht, Netherlands

Institute of Data Science at Maastricht University

Citation (CITATION.cff)

cff-version: 1.2.0
message: "If you use this software, please cite it as below."
authors:
  - orcid: https://orcid.org/0000-0002-1501-1082
    email: vincent.emonet@gmail.com
    given-names: Vincent Emonet
    # affiliation: Institute of Data Science, Maastricht University
title: "TRAPI Predict Kit"
repository-code: https://github.com/MaastrichtU-IDS/trapi-predict-kit
date-released: 2023-07-04
url: https://pypi.org/project/trapi-predict-kit
# doi: 10.48550/arXiv.2206.13787

GitHub Events

Total
  • Issues event: 3
  • Delete event: 1
  • Member event: 1
  • Push event: 8
  • Pull request event: 8
  • Create event: 1
Last Year
  • Issues event: 3
  • Delete event: 1
  • Member event: 1
  • Push event: 8
  • Pull request event: 8
  • Create event: 1

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 5
  • Total pull requests: 10
  • Average time to close issues: about 18 hours
  • Average time to close pull requests: 8 days
  • Total issue authors: 2
  • Total pull request authors: 3
  • Average comments per issue: 1.4
  • Average comments per pull request: 0.2
  • Merged pull requests: 6
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 3
  • Pull requests: 8
  • Average time to close issues: N/A
  • Average time to close pull requests: 10 days
  • Issue authors: 1
  • Pull request authors: 1
  • Average comments per issue: 0.0
  • Average comments per pull request: 0.0
  • Merged pull requests: 4
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • anas-elghafari (3)
  • micheldumontier (2)
Pull Request Authors
  • anas-elghafari (8)
  • CaseyTa (3)
  • renayang2023 (2)
Top Labels
Issue Labels
bug (1)
Pull Request Labels

Packages

  • Total packages: 1
  • Total downloads:
    • pypi 22 last-month
  • Total dependent packages: 0
  • Total dependent repositories: 1
  • Total versions: 7
  • Total maintainers: 1
pypi.org: trapi-predict-kit

A package to help create and deploy Translator Reasoner APIs (TRAPI) from any prediction model exposed as a regular python function.

  • Homepage: https://github.com/MaastrichtU-IDS/trapi-predict-kit
  • Documentation: https://github.com/MaastrichtU-IDS/trapi-predict-kit
  • License: MIT License Copyright (c) 2023-present Vincent Emonet <vincent.emonet@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  • Latest release: 0.2.3
    published about 2 years ago
  • Versions: 7
  • Dependent Packages: 0
  • Dependent Repositories: 1
  • Downloads: 22 Last month
Rankings
Dependent packages count: 10.1%
Downloads: 15.5%
Dependent repos count: 21.6%
Average: 23.2%
Forks count: 29.8%
Stargazers count: 38.8%
Maintainers (1)
Last synced: 6 months ago

Dependencies

.github/workflows/publish.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
  • pypa/gh-action-pypi-publish release/v1 composite
.github/workflows/test.yml actions
  • actions/checkout v3 composite
  • actions/configure-pages v3 composite
  • actions/deploy-pages v2 composite
  • actions/setup-python v4 composite
  • actions/upload-pages-artifact v2 composite
  • github/codeql-action/analyze v2 composite
  • github/codeql-action/autobuild v2 composite
  • github/codeql-action/init v2 composite
pyproject.toml pypi
  • SPARQLWrapper >=2.0.0,<3.0.0
  • fastapi >=0.68.1
  • mlem *
  • pydantic >=1.9
  • rdflib >=6.1.1
  • reasoner-pydantic >=3.0.1
  • requests >=2.23.0