From 264d606cff0c0ab2a40f983fb6acf05d39e24b40 Mon Sep 17 00:00:00 2001 From: James Stevenson Date: Tue, 17 Sep 2024 16:25:57 -0400 Subject: [PATCH] feat: add initial drugs@fda API wrapper --- .gitignore | 153 +++++++++ .pre-commit-config.yaml | 18 + LICENSE | 21 ++ README.md | 54 +++ pyproject.toml | 147 ++++++++ src/regbot/__init__.py | 10 + src/regbot/fetch/__init__.py | 1 + src/regbot/fetch/drugsfda.py | 449 +++++++++++++++++++++++++ tests/conftest.py | 11 + tests/fixtures/fetch_anda_falmina.json | 105 ++++++ tests/fixtures/fetch_nda_xadago.json | 203 +++++++++++ tests/test_fetch_drugsfda.py | 37 ++ 12 files changed, 1209 insertions(+) create mode 100644 .gitignore create mode 100644 .pre-commit-config.yaml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 pyproject.toml create mode 100644 src/regbot/__init__.py create mode 100644 src/regbot/fetch/__init__.py create mode 100644 src/regbot/fetch/drugsfda.py create mode 100644 tests/conftest.py create mode 100644 tests/fixtures/fetch_anda_falmina.json create mode 100644 tests/fixtures/fetch_nda_xadago.json create mode 100644 tests/test_fetch_drugsfda.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0a8e4ab --- /dev/null +++ b/.gitignore @@ -0,0 +1,153 @@ +# Ignore xlsx temp file +\~* + +# Ignore system files +.DS_Store + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ +docs/build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# allow pytest override with pytest.ini +pytest.ini + +# IDE materials +.idea/ +.vim/ +*.swp diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..0ea2558 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,18 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 # pre-commit-hooks version + hooks: + - id: check-added-large-files + - id: detect-private-key + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-merge-conflict + - id: detect-aws-credentials + args: [ --allow-missing-credentials ] + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.5.0 # ruff version + hooks: + - id: ruff-format + - id: ruff + args: [ --fix, --exit-non-zero-on-fix ] +minimum_pre_commit_version: 3.7.1 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f63841a --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Wagner Laboratory at the Institute for Genomic Medicine + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d17a69c --- /dev/null +++ b/README.md @@ -0,0 +1,54 @@ +# regbot + +[![image](https://img.shields.io/pypi/v/regbot.svg)](https://pypi.python.org/pypi/regbot) +[![image](https://img.shields.io/pypi/l/regbot.svg)](https://pypi.python.org/pypi/regbot) +[![image](https://img.shields.io/pypi/pyversions/regbot.svg)](https://pypi.python.org/pypi/regbot) +[![Actions status](https://github.com/genomicmedlab/regbot/actions/workflows/checks.yaml/badge.svg)](https://github.com/genomicmedlab/regbot/actions/checks.yaml) + + +Fetch regulatory approval data for drug terms + + + + +--- + +## Installation + +Install from [PyPI](https://pypi.org/project/regbot/): + +```shell +python3 -m pip install regbot +``` + +--- + +## Development + +Clone the repo and create a virtual environment: + +```shell +git clone https://github.com/genomicmedlab/regbot +cd regbot +python3 -m virtualenv venv +source venv/bin/activate +``` + +Install development dependencies and `pre-commit`: + +```shell +python3 -m pip install -e '.[dev,tests]' +pre-commit install +``` + +Check style with `ruff`: + +```shell +python3 -m ruff format . && python3 -m ruff check --fix . +``` + +Run tests with `pytest`: + +```shell +pytest +``` diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..a1040a4 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,147 @@ +[project] +name = "regbot" +authors = [ + {name = "Wagner Lab"}, +] +readme = "README.md" +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Science/Research", + "Intended Audience :: Developers", + "Topic :: Scientific/Engineering :: Bio-Informatics", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", +] +requires-python = ">=3.10" +description = "Fetch regulatory approval data for drug terms" +license = {file = "LICENSE"} +dependencies = ["requests"] +dynamic = ["version"] + +[project.optional-dependencies] +tests = ["pytest", "pytest-cov", "requests-mock"] +dev = ["pre-commit>=3.7.1", "ruff==0.5.0"] + + +[project.urls] +Homepage = "https://github.com/genomicmedlab/regbot" +Documentation = "https://github.com/genomicmedlab/regbot" +Changelog = "https://github.com/genomicmedlab/regbot/releases" +Source = "https://github.com/genomicmedlab/regbot" +"Bug Tracker" = "https://github.com/genomicmedlab/regbot/issues" + +[project.scripts] + +[build-system] +requires = ["setuptools>=64", "setuptools_scm>=8"] +build-backend = "setuptools.build_meta" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.setuptools_scm] + +[tool.pytest.ini_options] +addopts = "--cov=src --cov-report term-missing" +testpaths = ["tests"] + +[tool.coverage.run] +branch = true + +[tool.ruff] +src = ["src"] + + +[tool.ruff.lint] +select = [ + "F", # https://docs.astral.sh/ruff/rules/#pyflakes-f + "E", "W", # https://docs.astral.sh/ruff/rules/#pycodestyle-e-w + "I", # https://docs.astral.sh/ruff/rules/#isort-i + "N", # https://docs.astral.sh/ruff/rules/#pep8-naming-n + "D", # https://docs.astral.sh/ruff/rules/#pydocstyle-d + "UP", # https://docs.astral.sh/ruff/rules/#pyupgrade-up + "ANN", # https://docs.astral.sh/ruff/rules/#flake8-annotations-ann + "ASYNC", # https://docs.astral.sh/ruff/rules/#flake8-async-async + "S", # https://docs.astral.sh/ruff/rules/#flake8-bandit-s + "B", # https://docs.astral.sh/ruff/rules/#flake8-bugbear-b + "A", # https://docs.astral.sh/ruff/rules/#flake8-builtins-a + "C4", # https://docs.astral.sh/ruff/rules/#flake8-comprehensions-c4 + "DTZ", # https://docs.astral.sh/ruff/rules/#flake8-datetimez-dtz + "T10", # https://docs.astral.sh/ruff/rules/#flake8-datetimez-dtz + "EM", # https://docs.astral.sh/ruff/rules/#flake8-errmsg-em + "LOG", # https://docs.astral.sh/ruff/rules/#flake8-logging-log + "G", # https://docs.astral.sh/ruff/rules/#flake8-logging-format-g + "INP", # https://docs.astral.sh/ruff/rules/#flake8-no-pep420-inp + "PIE", # https://docs.astral.sh/ruff/rules/#flake8-pie-pie + "T20", # https://docs.astral.sh/ruff/rules/#flake8-print-t20 + "PT", # https://docs.astral.sh/ruff/rules/#flake8-pytest-style-pt + "Q", # https://docs.astral.sh/ruff/rules/#flake8-quotes-q + "RSE", # https://docs.astral.sh/ruff/rules/#flake8-raise-rse + "RET", # https://docs.astral.sh/ruff/rules/#flake8-return-ret + "SLF", # https://docs.astral.sh/ruff/rules/#flake8-self-slf + "SIM", # https://docs.astral.sh/ruff/rules/#flake8-simplify-sim + "ARG", # https://docs.astral.sh/ruff/rules/#flake8-unused-arguments-arg + "PTH", # https://docs.astral.sh/ruff/rules/#flake8-use-pathlib-pth + "PGH", # https://docs.astral.sh/ruff/rules/#pygrep-hooks-pgh + "PERF", # https://docs.astral.sh/ruff/rules/#perflint-perf + "FURB", # https://docs.astral.sh/ruff/rules/#refurb-furb + "RUF", # https://docs.astral.sh/ruff/rules/#ruff-specific-rules-ruf +] +fixable = [ + "I", + "F401", + "D", + "UP", + "ANN", + "B", + "C4", + "LOG", + "G", + "PIE", + "PT", + "RSE", + "SIM", + "PERF", + "FURB", + "RUF" +] +# ANN003 - missing-type-kwargs +# ANN101 - missing-type-self +# ANN102 - missing-type-cls +# D203 - one-blank-line-before-class +# D205 - blank-line-after-summary +# D206 - indent-with-spaces* +# D213 - multi-line-summary-second-line +# D300 - triple-single-quotes* +# D400 - ends-in-period +# D415 - ends-in-punctuation +# E111 - indentation-with-invalid-multiple* +# E114 - indentation-with-invalid-multiple-comment* +# E117 - over-indented* +# E501 - line-too-long* +# W191 - tab-indentation* +# S321 - suspicious-ftp-lib-usage +# *ignored for compatibility with formatter +ignore = [ + "ANN003", "ANN101", "ANN102", + "D203", "D205", "D206", "D213", "D300", "D400", "D415", + "E111", "E114", "E117", "E501", + "W191", + "S321", +] + +[tool.ruff.lint.per-file-ignores] +# ANN001 - missing-type-function-argument +# ANN2 - missing-return-type +# ANN102 - missing-type-cls +# S101 - assert +# B011 - assert-false +# INP001 - implicit-namespace-package +# D103 - missing-docstring-public-function +"tests/*" = ["ANN001", "ANN2", "ANN102", "S101", "B011", "INP001", "D103"] + +[tool.ruff.format] +docstring-code-format = true diff --git a/src/regbot/__init__.py b/src/regbot/__init__.py new file mode 100644 index 0000000..d75bf8a --- /dev/null +++ b/src/regbot/__init__.py @@ -0,0 +1,10 @@ +"""Fetch regulatory approval data for drug terms""" + +from importlib.metadata import PackageNotFoundError, version + +try: + __version__ = version("regbot") +except PackageNotFoundError: + __version__ = "unknown" +finally: + del version, PackageNotFoundError diff --git a/src/regbot/fetch/__init__.py b/src/regbot/fetch/__init__.py new file mode 100644 index 0000000..c263ea1 --- /dev/null +++ b/src/regbot/fetch/__init__.py @@ -0,0 +1 @@ +"""Fetch data from regulatory agency APIs.""" diff --git a/src/regbot/fetch/drugsfda.py b/src/regbot/fetch/drugsfda.py new file mode 100644 index 0000000..9b87b31 --- /dev/null +++ b/src/regbot/fetch/drugsfda.py @@ -0,0 +1,449 @@ +"""Provide utilities for interacting with Drugs@FDA API endpoint.""" + +import datetime +import logging +from collections import namedtuple +from enum import Enum + +import requests +from requests.exceptions import RequestException + +_logger = logging.getLogger(__name__) + + +Result = namedtuple( + "Result", + ("submissions", "application_number", "sponsor_name", "openfda", "products"), +) +Product = namedtuple( + "Product", + ( + "product_number", + "reference_drug", + "brand_name", + "active_ingredients", + "reference_standard", + "dosage_form", + "route", + "marketing_status", + "te_code", + ), +) +ActiveIngredient = namedtuple("ActiveIngredient", ("name", "strength")) +ApplicationDoc = namedtuple("ApplicationDoc", ("id", "url", "date", "type")) +Submission = namedtuple( + "Submission", + ( + "submission_type", + "submission_number", + "submission_status", + "submission_status_date", + "review_priority", + "submission_class_code", + "submission_class_code_description", + "application_docs", + ), +) +OpenFda = namedtuple( + "OpenFda", + ( + "application_number", + "brand_name", + "generic_name", + "manufacturer_name", + "product_ndc", + "product_type", + "route", + "substance_name", + "rxcui", + "spl_id", + "spl_set_id", + "package_ndc", + "nui", + "pharm_class_epc", + "pharm_class_cs", + "pharm_class_moa", + "unii", + ), +) + + +class ApplicationDocType(str, Enum): + """Provide values for application document type.""" + + LABEL = "label" + LETTER = "letter" + REVIEW = "review" + + +class ProductMarketingStatus(str, Enum): + """'Marketing status indicates how a drug product is sold in the United States. Drug + products in Drugs@FDA are identified as: + + * Prescription + * Over-the-counter + * Discontinued + * None - drug products that have been tentatively approved' + + https://www.fda.gov/drugs/drug-approvals-and-databases/drugsfda-glossary-terms#marketing_status + """ + + PRESCRIPTION = "prescription" + OTC = "over_the_counter" + DISCONTINUED = "discontinued" + NONE = "none" + + @classmethod + def _missing_(cls, value): # noqa: ANN001 ANN206 + try: + if value.lower() == "over-the-counter": + return cls.OTC + msg = f"'{value}' is not a valid {cls.__name__}" + raise ValueError(msg) + except AttributeError as _: + msg = f"'{value}' is not a valid {cls.__name__}" + raise ValueError(msg) from None + + +class ProductRoute(str, Enum): + """Provide values for product routes.""" + + ORAL = "oral" + + +class ProductDosageForm(str, Enum): + """'A dosage form is the physical form in which a drug is produced and dispensed, + such as a tablet, a capsule, or an injectable.' + + https://www.fda.gov/drugs/drug-approvals-and-databases/drugsfda-glossary-terms#form + """ + + TABLET = "tablet" + CAPSULE = "capsule" + + +class ProductTherapeuticEquivalencyCode(str, Enum): + """See eg https://www.fda.gov/drugs/development-approval-process-drugs/orange-book-preface#TEC""" + + AA = "aa" + AB = "ab" + BC = "bc" + + +class OpenFdaProductType(str, Enum): + """Define product type.""" + + HUMAN_PRESCRIPTION_DRUG = "human_prescription_drug" + + @classmethod + def _missing_(cls, value): # noqa: ANN001 ANN206 + try: + if value.lower() == "human prescription drug": + return cls.HUMAN_PRESCRIPTION_DRUG + msg = f"'{value}' is not a valid {cls.__name__}" + raise ValueError(msg) + except AttributeError as _: + msg = f"'{value}' is not a valid {cls.__name__}" + raise ValueError(msg) from None + + +class SubmissionType(str, Enum): + """Provide values for FDA submission type.""" + + ORIG = "orig" + SUPPL = "suppl" + + +class SubmissionStatus(str, Enum): + """Provide values for FDA submission status.""" + + AP = "ap" + + +class SubmissionReviewPriority(str, Enum): + """Provide values for FDA submission review priority rating.""" + + STANDARD = "standard" + PRIORITY = "priority" + UNKNOWN = "unknown" + N_A = "n_a" + REQUIRE_901 = "require 901" + + @classmethod + def _missing_(cls, value): # noqa: ANN001 ANN206 + try: + val_lower = value.lower() + if val_lower == "n/a": + return cls.N_A + if val_lower == "901 required": + return cls.REQUIRE_901 + msg = f"'{value}' is not a valid {cls.__name__}" + raise ValueError(msg) + except AttributeError as _: + msg = f"'{value}' is not a valid {cls.__name__}" + raise ValueError(msg) from None + + +class SubmissionClassCode(str, Enum): + """Provide values for class code for FDA submission.""" + + UNKNOWN = "unknown" + EFFICACY = "efficacy" + MANUF_CMC = "manuf_cmc" # TODO context + LABELING = "labeling" + TYPE_1 = "type_1" + TYPE_2 = "type_2" + TYPE_3 = "type_3" + TYPE_4 = "type_4" + + @classmethod + def _missing_(cls, value): # noqa: ANN001 ANN206 + try: + val_lower = value.lower() + if val_lower == "manuf (cmc)": + return cls.MANUF_CMC + if val_lower == "type 1": + return cls.TYPE_1 + if val_lower == "type 2": + return cls.TYPE_2 + if val_lower == "type 3": + return cls.TYPE_3 + if val_lower == "type 4": + return cls.TYPE_4 + msg = f"'{value}' is not a valid {cls.__name__}" + raise ValueError(msg) + except AttributeError as _: + msg = f"'{value}' is not a valid {cls.__name__}" + raise ValueError(msg) from None + + +def _make_truthy(status: str | None) -> bool | str | None: + if status is None: + return None + lower_status = status.lower() + if lower_status == "no": + return False + if lower_status == "yes": + return True + _logger.error("Encountered unknown value for converting to bool: %s", status) + return status + + +def _enumify(value: str | None, CandidateEnum: type[Enum]) -> Enum | str | None: # noqa: N803 + if value is None: + return None + try: + return CandidateEnum(value.lower()) + except ValueError: + _logger.error( + "Unable to enumify value '%s' into enum '%s'", value, CandidateEnum + ) + return value + + +def _intify(value: str) -> int | None: + try: + return int(value) + except ValueError: + _logger.error("Cannot convert value '%s' to int", value) + return None + + +def _make_datetime(value: str) -> datetime.datetime | None: + try: + return datetime.datetime.strptime(value, "%Y%m%d").replace( + tzinfo=datetime.timezone.utc + ) + except ValueError: + _logger.error("Unable to convert value '%s' to datetime", value) + return None + + +def _get_product(data: dict, normalize: bool) -> Product: + reference_drug = ( + _make_truthy(data["reference_drug"]) if normalize else data["reference_drug"] + ) + reference_standard = ( + _make_truthy(data["reference_standard"]) + if normalize + else data["reference_standard"] + ) + dosage_form = ( + _enumify(data["dosage_form"], ProductDosageForm) + if normalize + else data["dosage_form"] + ) + route = ( + _enumify(data["route"], ProductRoute) + if normalize and "route" in data + else data.get("route") + ) + marketing_status = ( + _enumify(data["marketing_status"], ProductMarketingStatus) + if normalize + else data["marketing_status"] + ) + te_code = ( + _enumify(data["te_code"], ProductTherapeuticEquivalencyCode) + if normalize and "te_code" in data + else data.get("te_code") + ) + return Product( + product_number=data["product_number"], + reference_drug=reference_drug, + brand_name=data["brand_name"], + active_ingredients=[ + ActiveIngredient(**ai) for ai in data["active_ingredients"] + ], + reference_standard=reference_standard, + dosage_form=dosage_form, + route=route, + marketing_status=marketing_status, + te_code=te_code, + ) + + +def _get_application_docs(data: list[dict], normalize: bool) -> list[ApplicationDoc]: + return [ + ApplicationDoc( + id=doc["id"], + url=doc["url"], + date=_make_datetime(doc["date"]) if normalize else doc["date"], + type=_enumify(doc["type"], ApplicationDocType) + if normalize + else doc["type"], + ) + for doc in data + ] + + +def _get_submission(data: dict, normalize: bool) -> Submission: + submission_type = ( + _enumify(data["submission_type"], SubmissionType) + if normalize + else data["submission_type"] + ) + submission_number = ( + _intify(data["submission_number"]) if normalize else data["submission_number"] + ) + submission_status = ( + _enumify(data["submission_status"], SubmissionStatus) + if normalize + else data["submission_status"] + ) + submission_status_date = ( + _make_datetime(data["submission_status_date"]) + if normalize + else data["submission_status_date"] + ) + review_priority = ( + _enumify(data.get("review_priority"), SubmissionReviewPriority) + if normalize + else data.get("review_priority") + ) + submission_class_code = ( + _enumify(data.get("submission_class_code"), SubmissionClassCode) + if normalize + else data.get("submission_class_code") + ) + application_docs = ( + _get_application_docs(data["application_docs"], normalize) + if "application_docs" in data + else None + ) + + return Submission( + submission_type=submission_type, + submission_number=submission_number, + submission_status=submission_status, + submission_status_date=submission_status_date, + review_priority=review_priority, + submission_class_code=submission_class_code, + submission_class_code_description=data.get("submission_class_code_description"), + application_docs=application_docs, + ) + + +def _get_openfda(data: dict, normalize: bool) -> OpenFda: + product_type = [ + _enumify(pt, OpenFdaProductType) if normalize else pt + for pt in data["product_type"] + ] + if "route" in data: + route = [ + _enumify(rt, ProductRoute) if normalize else rt for rt in data["route"] + ] + else: + route = None + return OpenFda( + application_number=data["application_number"], + brand_name=data["brand_name"], + generic_name=data["generic_name"], + manufacturer_name=data["manufacturer_name"], + product_ndc=data["product_ndc"], + product_type=product_type, + route=route, + substance_name=data.get("substance_name"), + rxcui=data["rxcui"], + spl_id=data["spl_id"], + spl_set_id=data["spl_set_id"], + package_ndc=data["package_ndc"], + nui=data.get("nui"), + pharm_class_epc=data.get("pharm_class_epc"), + pharm_class_cs=data.get("pharm_class_cs"), + pharm_class_moa=data.get("pharm_class_moa"), + unii=data.get("unii"), + ) + + +def _get_result(data: dict, normalize: bool) -> Result: + return Result( + submissions=[_get_submission(s, normalize) for s in data["submissions"]], + application_number=data["application_number"], + sponsor_name=data["sponsor_name"], + openfda=_get_openfda(data["openfda"], normalize), + products=[_get_product(p, normalize) for p in data["products"]], + ) + + +def get_drugsfda_results(url: str, normalize: bool = False) -> list[Result] | None: + """Get Drugs@FDA data given an API query URL. + + :param url: URL to request + :param normalize: if ``True``, try to normalize values to controlled enumerations + and appropriate Python datatypes + :return: list of Drugs@FDA ``Result``s if successful + :raise RequestException: if HTTP response status != 200 + """ + with requests.get(url, timeout=30) as r: + try: + r.raise_for_status() + except RequestException as e: + raise e + data = r.json() + return [_get_result(r, normalize) for r in data["results"]] + + +def get_anda_results(anda: str, normalize: bool = False) -> list[Result] | None: + """Get Drugs@FDA data for an ANDA ID. + + :param anda: ANDA code (should be a six-digit number formatted as a string) + :param normalize: if ``True``, try to normalize values to controlled enumerations + and appropriate Python datatypes + :return: list of Drugs@FDA ``Result``s if successful + """ + """TODO""" + url = f"https://api.fda.gov/drug/drugsfda.json?search=openfda.application_number:ANDA{anda}" + return get_drugsfda_results(url, normalize) + + +def get_nda_results(nda: str, normalize: bool = False) -> list[Result] | None: + """Get Drugs@FDA data for an NDA ID. + + :param nda: NDA code (should be a six-digit number formatted as a string) + :param normalize: if ``True``, try to normalize values to controlled enumerations + and appropriate Python datatypes + :return: list of Drugs@FDA ``Result``s if successful + """ + url = f"https://api.fda.gov/drug/drugsfda.json?search=openfda.application_number:NDA{nda}" + return get_drugsfda_results(url, normalize) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..036f19e --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,11 @@ +"""Provide basic test configuration and fixture root.""" + +from pathlib import Path + +import pytest + + +@pytest.fixture(scope="session") +def fixtures_dir(): + """Provide path to fixtures directory.""" + return Path(__file__).resolve().parent / "fixtures" diff --git a/tests/fixtures/fetch_anda_falmina.json b/tests/fixtures/fetch_anda_falmina.json new file mode 100644 index 0000000..aefa7d1 --- /dev/null +++ b/tests/fixtures/fetch_anda_falmina.json @@ -0,0 +1,105 @@ +{ + "meta": { + "disclaimer": "Do not rely on openFDA to make decisions regarding medical care. While we make every effort to ensure that data is accurate, you should assume all results are unvalidated. We may limit or otherwise restrict your access to the API in line with our Terms of Service.", + "terms": "https://open.fda.gov/terms/", + "license": "https://open.fda.gov/license/", + "last_updated": "2024-09-10", + "results": { + "skip": 0, + "limit": 1, + "total": 1 + } + }, + "results": [ + { + "submissions": [ + { + "submission_type": "ORIG", + "submission_number": "1", + "submission_status": "AP", + "submission_status_date": "20120328" + }, + { + "submission_type": "SUPPL", + "submission_number": "2", + "submission_status": "AP", + "submission_status_date": "20170809", + "review_priority": "STANDARD", + "submission_class_code": "LABELING", + "submission_class_code_description": "Labeling" + }, + { + "submission_type": "SUPPL", + "submission_number": "7", + "submission_status": "AP", + "submission_status_date": "20220429", + "review_priority": "STANDARD", + "submission_class_code": "LABELING", + "submission_class_code_description": "Labeling" + } + ], + "application_number": "ANDA090721", + "sponsor_name": "NOVAST LABS LTD", + "openfda": { + "application_number": [ + "ANDA090721" + ], + "brand_name": [ + "FALMINA" + ], + "generic_name": [ + "LEVONORGESTREL AND ETHINYL ESTRADIOL" + ], + "manufacturer_name": [ + "Northstar Rx LLC" + ], + "product_ndc": [ + "16714-359" + ], + "product_type": [ + "HUMAN PRESCRIPTION DRUG" + ], + "rxcui": [ + "242297", + "748797", + "748868", + "1304988" + ], + "spl_id": [ + "b65ade06-5fdd-465b-9123-54e898caa35d" + ], + "spl_set_id": [ + "cf6f069e-4b78-4adb-b5be-100b9d85aab7" + ], + "package_ndc": [ + "16714-359-01", + "16714-359-02", + "16714-359-03", + "16714-359-04" + ] + }, + "products": [ + { + "product_number": "001", + "reference_drug": "No", + "brand_name": "FALMINA", + "active_ingredients": [ + { + "name": "ETHINYL ESTRADIOL", + "strength": "0.02MG" + }, + { + "name": "LEVONORGESTREL", + "strength": "0.1MG" + } + ], + "reference_standard": "No", + "dosage_form": "TABLET", + "route": "ORAL-28", + "marketing_status": "Prescription", + "te_code": "AB1" + } + ] + } + ] +} diff --git a/tests/fixtures/fetch_nda_xadago.json b/tests/fixtures/fetch_nda_xadago.json new file mode 100644 index 0000000..2159943 --- /dev/null +++ b/tests/fixtures/fetch_nda_xadago.json @@ -0,0 +1,203 @@ +{ + "meta": { + "disclaimer": "Do not rely on openFDA to make decisions regarding medical care. While we make every effort to ensure that data is accurate, you should assume all results are unvalidated. We may limit or otherwise restrict your access to the API in line with our Terms of Service.", + "terms": "https://open.fda.gov/terms/", + "license": "https://open.fda.gov/license/", + "last_updated": "2024-09-10", + "results": { + "skip": 0, + "limit": 1, + "total": 1 + } + }, + "results": [ + { + "submissions": [ + { + "submission_type": "SUPPL", + "submission_number": "5", + "submission_status": "AP", + "submission_status_date": "20191125", + "review_priority": "STANDARD", + "submission_class_code": "LABELING", + "submission_class_code_description": "Labeling", + "application_docs": [ + { + "id": "61081", + "url": "http://www.accessdata.fda.gov/drugsatfda_docs/appletter/2019/207145Orig1s005ltr.pdf", + "date": "20191127", + "type": "Letter" + }, + { + "id": "61100", + "url": "http://www.accessdata.fda.gov/drugsatfda_docs/label/2019/207145s005lbl.pdf", + "date": "20191129", + "type": "Label" + } + ] + }, + { + "submission_type": "SUPPL", + "submission_number": "1", + "submission_status": "AP", + "submission_status_date": "20170616", + "review_priority": "STANDARD", + "submission_class_code": "LABELING", + "submission_class_code_description": "Labeling", + "application_docs": [ + { + "id": "48756", + "url": "http://www.accessdata.fda.gov/drugsatfda_docs/label/2017/207145s001lbl.pdf", + "date": "20170619", + "type": "Label" + }, + { + "id": "48775", + "url": "http://www.accessdata.fda.gov/drugsatfda_docs/appletter/2017/207145Orig1s001ltr.pdf", + "date": "20170620", + "type": "Letter" + } + ] + }, + { + "submission_type": "SUPPL", + "submission_number": "6", + "submission_status": "AP", + "submission_status_date": "20210806", + "review_priority": "STANDARD", + "submission_class_code": "LABELING", + "submission_class_code_description": "Labeling", + "application_docs": [ + { + "id": "68316", + "url": "http://www.accessdata.fda.gov/drugsatfda_docs/label/2021/207145s006lbl.pdf", + "date": "20210809", + "type": "Label" + }, + { + "id": "68325", + "url": "http://www.accessdata.fda.gov/drugsatfda_docs/appletter/2021/207145Orig1s006ltr.pdf", + "date": "20210810", + "type": "Letter" + } + ] + }, + { + "submission_type": "ORIG", + "submission_number": "1", + "submission_status": "AP", + "submission_status_date": "20170321", + "review_priority": "STANDARD", + "submission_class_code": "TYPE 1", + "submission_class_code_description": "Type 1 - New Molecular Entity", + "application_docs": [ + { + "id": "47630", + "url": "http://www.accessdata.fda.gov/drugsatfda_docs/label/2017/207145lbl.pdf", + "date": "20170322", + "type": "Label" + }, + { + "id": "47730", + "url": "http://www.accessdata.fda.gov/drugsatfda_docs/appletter/2017/207145Orig1s000ltr.pdf", + "date": "20170328", + "type": "Letter" + }, + { + "id": "48180", + "url": "http://www.accessdata.fda.gov/drugsatfda_docs/nda/2017/207145Orig1s000TOC.cfm", + "date": "20170501", + "type": "Review" + } + ] + } + ], + "application_number": "NDA207145", + "sponsor_name": "MDD US", + "openfda": { + "application_number": [ + "NDA207145" + ], + "brand_name": [ + "XADAGO" + ], + "generic_name": [ + "SAFINAMIDE MESYLATE" + ], + "manufacturer_name": [ + "MDD US Operations LLC, a subsidiary of Supernus Pharmaceuticals, Inc." + ], + "product_ndc": [ + "27505-110", + "27505-111" + ], + "product_type": [ + "HUMAN PRESCRIPTION DRUG" + ], + "route": [ + "ORAL" + ], + "substance_name": [ + "SAFINAMIDE MESYLATE" + ], + "rxcui": [ + "1922466", + "1922472", + "1922474", + "1922476" + ], + "spl_id": [ + "0cf4e97f-18de-5426-e063-6294a90ac4b0" + ], + "spl_set_id": [ + "c4d65f28-983f-42b4-bb23-023ae0fe81b2" + ], + "package_ndc": [ + "27505-110-30", + "27505-110-90", + "27505-110-14", + "27505-111-30", + "27505-111-90", + "27505-111-14" + ], + "unii": [ + "YS90V3DTX0" + ] + }, + "products": [ + { + "product_number": "001", + "reference_drug": "Yes", + "brand_name": "XADAGO", + "active_ingredients": [ + { + "name": "SAFINAMIDE MESYLATE", + "strength": "EQ 50MG BASE" + } + ], + "reference_standard": "No", + "dosage_form": "TABLET", + "route": "ORAL", + "marketing_status": "Prescription", + "te_code": "AB" + }, + { + "product_number": "002", + "reference_drug": "Yes", + "brand_name": "XADAGO", + "active_ingredients": [ + { + "name": "SAFINAMIDE MESYLATE", + "strength": "EQ 100MG BASE" + } + ], + "reference_standard": "Yes", + "dosage_form": "TABLET", + "route": "ORAL", + "marketing_status": "Prescription", + "te_code": "AB" + } + ] + } + ] +} diff --git a/tests/test_fetch_drugsfda.py b/tests/test_fetch_drugsfda.py new file mode 100644 index 0000000..a7349ab --- /dev/null +++ b/tests/test_fetch_drugsfda.py @@ -0,0 +1,37 @@ +"""Test regbot.fetch.drugsfda""" + +from pathlib import Path + +import requests_mock + +from regbot.fetch.drugsfda import get_anda_results, get_nda_results + + +def test_get_anda_results(fixtures_dir: Path): + with ( + requests_mock.Mocker() as m, + (fixtures_dir / "fetch_anda_falmina.json").open() as json_response, + ): + m.get( + "https://api.fda.gov/drug/drugsfda.json?search=openfda.application_number:ANDA090721", + text=json_response.read(), + ) + + results = get_anda_results("090721", True) + assert results + assert len(results) > 0 + + +def test_get_nda_results(fixtures_dir: Path): + with ( + requests_mock.Mocker() as m, + (fixtures_dir / "fetch_nda_xadago.json").open() as json_response, + ): + m.get( + "https://api.fda.gov/drug/drugsfda.json?search=openfda.application_number:NDA207145", + text=json_response.read(), + ) + + results = get_nda_results("207145", True) + assert results + assert len(results) > 0