omnitax 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,29 @@
1
+ /scratch/
2
+ /ref/
3
+
4
+ # Python
5
+ __pycache__/
6
+ *.py[cod]
7
+ *.egg-info/
8
+ build/
9
+ dist/
10
+ .venv/
11
+ .venv*/
12
+ .pytest_cache/
13
+ .coverage
14
+ htmlcov/
15
+
16
+ # Local taxonomy files
17
+ *.part
18
+ *.sqlite
19
+ *.sqlite3
20
+ *.sqlite-*
21
+
22
+ # Editors / OS
23
+ .playwright-mcp/
24
+ .DS_Store
25
+ *.swp
26
+
27
+ # Zensical: the built site and its build cache (it drops its own `.gitignore` with `*` inside).
28
+ /site/
29
+ /.cache/
@@ -0,0 +1,69 @@
1
+ # Changelog
2
+
3
+ All notable changes to `omnitax` are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
+ [semantic versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2026-11-27
10
+
11
+ First release. omnitax began as the NCBI taxonomy code of [sylphd](https://github.com/Abrinca/sylphd) and is now a library for several taxonomies. It is written with LLM coding agents, reviewed by a human, and largely untested in practice; APIs may change before 1.0. Linux only.
12
+
13
+ ### Taxonomies and loaders
14
+
15
+ - Loaders (`omnitax.load`, `omnitax build SPEC`) for NCBI, GTDB releases 80 to 232, SILVA, Greengenes2, Open Tree, custom tables, and taxdump files (gtdb-taxdump, ictv-taxdump, TaxonKit output). SILVA, Greengenes2 and Open Tree load real files but have had little more checking.
16
+ - NCBI versions are dates: `ncbi:2026-11-26` is the current dump, `ncbi:YYYY-MM-DD` is built from NCBI's monthly archive (from 2018-12-01); any other date is an error that names the nearest ones.
17
+ - Links attach keys to nodes: `ncbi+assemblies` (NCBI's assembly summaries, with their attributes), `ncbi+gtdb:232` (GTDB's genomes with NCBI taxids), a taxdump's `taxid.map`. Genomes are stored under their full accession; `gca_gcf=True` joins `GCA_` and `GCF_`.
18
+ - GTDB `+representatives` keeps only the species-representative genomes.
19
+
20
+ ### Python API
21
+
22
+ - `Taxonomy` and `Taxon` over any taxonomy: lineages with rank slots, `at`, `closest(formal=)`, `lca`, `consensus`, `lineage_string()`, `lookup`, `many`, `of_rank`, `subset`, `prune`, `with_links`, `stats`, `write`, `save`, `names`, `provenance`.
23
+ - `search` is autocomplete: `match="exact"|"prefix"|"substring"|"fuzzy"`, word starts, abbreviated binomials (`e. coli`), `rank=`, `classes=`, `within=`, `details=True`.
24
+ - `omnitax.open`, `omnitax.taxonomies`, `omnitax.connect` (a file, a Unix socket or a URL; `headers=`, `prefix=`, `retries=`). `omnitax.LayoutError` for a file of another layout.
25
+ - A taxonomy that is loaded, subset or edited lives in a temporary SQLite file (`$OMNITAX_TMPDIR`; NCBI is about 1.2 GB, mind a RAM-disk `/tmp`); `close()` removes it.
26
+ - `omnitax.annotate`: append taxa (id, name, rank, lineage, a rank) to the rows of a table.
27
+
28
+ ### Translation and its defaults
29
+
30
+ - `Taxonomy.translate` maps a node to another taxonomy through shared keys (genomes, sequence accessions, or the ids of the other taxonomy) by a weighted vote. `weight="leaf"` (default) or `"genome"`, `cap=`, `via=`, `sources=`, `details=True` (a `Placement` with support, total, abstained and the votes).
31
+ - `consensus` and every conversion that was not measured (NCBI → GTDB, GTDB release → release): threshold 0.9, plain voting, no ranks ladder, nothing excluded.
32
+ - GTDB → NCBI, the one measured conversion (GTDB 232 → NCBI 2026-11, bacteria and archaea): threshold 0.9, `min_informative=0.2` (abstention of placeholder votes), `ranks=GTDB_RANKS`, the target's uninformative nodes excluded. Turn off with `min_informative=False`, `ranks=()`, `exclude=()` (command line: `--min-informative off`, `--ranks none`, `--exclude none`). `Taxonomy.defaults_for(other)` shows what applies.
33
+ - `top=` is multitax's rule (no abstention). The benchmarks and their results are in `benchmarks/`.
34
+
35
+ ### Files and the SQLite layout
36
+
37
+ - One SQLite file holds any number of taxonomies (`kind:version`), each with a word index and, by default, a trigram index. The layout number is a CRC of the DDL (comments and white space left out); a file of another layout is refused with `LayoutError`.
38
+ - Files are in WAL mode: readers and the one writer do not wait for each other. A new file is written under `FILE.PID.RANDOM.part`, synced and then given its name, so a failed build leaves nothing. Writing a taxonomy is one transaction.
39
+ - Nested-interval numbering (`lft`, `rgt`) makes subtree queries one range scan. Foreign keys are declared.
40
+
41
+ ### Server and client
42
+
43
+ - `omnitax serve` serves every taxonomy of a file on a Unix socket, TCP, or both (extra `omnitax[server]`); `omnitax.server.taxonomy_routes(catalog)` mounts the routes into a Starlette app. No authentication and no rate limit: a reverse proxy does those.
44
+ - `RemoteStore` gives the same answers as a file (a conformance test checks it). Endpoints are batched; large answers are NDJSON streams. The wire format is positional and carries an integer `api_version` that the client compares for equality.
45
+
46
+ ### Command line
47
+
48
+ - `build`, `list`, `lookup`, `lineage`, `search`, `translate`, `link`, `annotate`, `export-taxdump`, `serve`. Query commands take `--db FILE`, `--url`, `--socket`, or the matching environment variables; `--header` and `--path-prefix` for servers behind a proxy.
49
+ - `build` refuses two specs of one taxonomy before downloading, and warns when it replaces a taxonomy that had links.
50
+
51
+ ### Overlays
52
+
53
+ - `build --overlay DIR` and `Taxonomy.apply(overlay, nodes=, links=, remove=, uninformative=)` add, change and remove nodes and links from `nodes.tsv`, `links.tsv`, `remove.tsv`. They are declarative, so they apply again to every newer release, and everything is checked, with file and line, before anything is written.
54
+
55
+ ### Taxdumps
56
+
57
+ - `Taxonomy.write_taxdump` and `omnitax export-taxdump` write `nodes.dmp`, `names.dmp`, `merged.dmp`, `delnodes.dmp` and `taxid.map` for Kraken2, KMCP, ganon and TaxonKit. NCBI's ids stay; other ids follow TaxonKit's `create-taxdump` recipe (optional extra `omnitax[taxdump]`: `xxhash`).
58
+
59
+ ### Provenance and downloads
60
+
61
+ - Every source file of a build is recorded with its URL or path, size and sha256, and the omnitax version is recorded. Downloads resume and are checked against the checksum NCBI and GTDB publish; a mismatch fails the build. `omnitax list --json` shows it.
62
+
63
+ ### Known limits
64
+
65
+ - Only GTDB 232 → NCBI translation is measured; no SILVA, Greengenes2 or Open Tree pair can be translated (no links for them). An NCBI → GTDB answer can come out high (see the translation guide).
66
+ - Not supported: native ICTV, GBIF, Catalogue of Life, UNITE, PR2, LTP, RDP, BOLD; export other than taxdump and tables.
67
+ - An edit (overlay, `subset`, `prune`) is a rebuild into a new file (NCBI about 80 s). A file of another layout must be rebuilt; there is no migration.
68
+ - Readers leave `-wal` and `-shm` files beside the file. `--source-url gtdb-links=` is not supported (use `--file gtdb-links=`). NCBI archive dates are checked only when downloading.
69
+ - Linux only; the file must be on a local disk.
omnitax-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thomas Roder, Abrinca Genomics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
omnitax-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.5
2
+ Name: omnitax
3
+ Version: 0.1.0
4
+ Summary: Biological taxonomies (NCBI, GTDB and a few more) as Python objects, in one SQLite file or behind a small server, with a benchmarked way to translate between NCBI and GTDB.
5
+ Project-URL: Homepage, https://abrinca.github.io/omnitax/
6
+ Project-URL: Documentation, https://abrinca.github.io/omnitax/
7
+ Project-URL: Repository, https://github.com/Abrinca/omnitax
8
+ Author: Thomas Roder, Abrinca Genomics
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: bioinformatics,lineage,ncbi,taxid,taxonomy
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.12
22
+ Requires-Dist: httpx
23
+ Provides-Extra: server
24
+ Requires-Dist: anyio; extra == 'server'
25
+ Requires-Dist: starlette; extra == 'server'
26
+ Requires-Dist: uvicorn; extra == 'server'
27
+ Provides-Extra: taxdump
28
+ Requires-Dist: xxhash; extra == 'taxdump'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # omnitax
32
+
33
+ Biological taxonomies (NCBI, GTDB and a few more) as Python objects, in one SQLite file or behind a small server, with a benchmarked way to translate between NCBI and GTDB.
34
+
35
+ > **Please read first.** omnitax was written with LLM coding agents and reviewed by a human. It is largely untested in practice: it has one real user so far ([sylphd](https://github.com/Abrinca/sylphd)). APIs may change before 1.0. It runs on Linux only for now. Check results on your own data before you rely on them.
36
+
37
+ ## Goals
38
+
39
+ 1. **Many taxonomies, handled the same way**: download, parse, one set of Python objects, conversion, export to standard formats. "All taxonomies" is not the aim; the common ones for microbiome work, and a pattern to add more, is.
40
+ 2. **One API, several backends**: a SQLite file, or a server on a Unix socket or HTTP, with the same answers.
41
+ 3. **Benchmarked translation between taxonomies**, with the method and results published. NCBI ↔ GTDB first.
42
+ 4. **Taxonomies you can change**: your own taxa as a small set of files that is applied again to every new release.
43
+ 5. **Reproducibility**: dated, checksummed snapshots of several taxonomies and versions in one file.
44
+
45
+ ## What works today
46
+
47
+ - Loaders for NCBI (current, or any monthly archive since 2018-12), GTDB 80 to 232, SILVA, Greengenes2, Open Tree, custom tables, and taxdump files (gtdb-taxdump, ictv-taxdump, TaxonKit output). SILVA, Greengenes2 and Open Tree load the real files but have had little more checking than that.
48
+ - Lineages, ranks, LCA, consensus, exact and fuzzy name search, subsets and edits, export as a taxdump or a table.
49
+ - Translation between NCBI and GTDB through shared genome accessions. Only GTDB 232 → NCBI has been measured; see [Translation](https://abrinca.github.io/omnitax/guides/translation/).
50
+ - Your own taxa as an overlay, a few files applied to each rebuild.
51
+ - A server, a client, and a command line (`build`, `list`, `lookup`, `lineage`, `search`, `translate`, `link`, `annotate`, `export-taxdump`, `serve`).
52
+
53
+ ## What does not work yet
54
+
55
+ SILVA, Greengenes2 and Open Tree cannot be translated to anything (no loader makes links for them). Not supported: native ICTV, GBIF, Catalogue of Life, UNITE, PR2, LTP, RDP, BOLD. Export is a taxdump or a table; there is no Newick or QIIME-style output. Linux only: Windows and macOS are not supported. See the [roadmap](https://github.com/Abrinca/omnitax/blob/main/ROADMAP.md).
56
+
57
+ ## Install
58
+
59
+ ```bash
60
+ uv add omnitax # the library (needs only httpx); or: pip install omnitax
61
+ uv tool install 'omnitax[server]' # the command line, with `omnitax serve`
62
+ ```
63
+
64
+ Python 3.12 or newer.
65
+
66
+ ## Use
67
+
68
+ ```bash
69
+ omnitax build -o taxonomies.sqlite ncbi+gtdb:232 gtdb:232 # downloads about 500 MB, takes minutes
70
+ omnitax lookup --db taxonomies.sqlite -t ncbi 562 "Homo sapiens"
71
+ omnitax translate --db taxonomies.sqlite -t gtdb:232 --to ncbi "s__Escherichia coli"
72
+ ```
73
+
74
+ ```python
75
+ import omnitax
76
+
77
+ ncbi = omnitax.open("taxonomies.sqlite", "ncbi")
78
+ ncbi["562"].lineage_string() # d__Bacteria;p__Pseudomonadota;...;s__Escherichia coli
79
+ ncbi.consensus({"562": 6, "564": 4}, threshold=0.5, exclude=ncbi.uninformative)
80
+ tiny = ncbi.subset(["561"], descendants=True) # a new taxonomy, in a temporary file
81
+ ```
82
+
83
+ Documentation: <https://abrinca.github.io/omnitax/>
84
+
85
+ ## Credits
86
+
87
+ - [sylphd](https://github.com/Abrinca/sylphd): omnitax began as its NCBI taxonomy code.
88
+ - [multitax](https://github.com/pirovc/multitax) (MIT): the source URLs and file formats, and the inspiration.
89
+ - [get-tax-info](https://github.com/MrTomRod/get-tax-info): an earlier tool that loads NCBI's taxdump into SQLite.
90
+ - [TaxonKit](https://github.com/shenwei356/taxonkit) (MIT): the recipe for taxids of taxonomies that have none.
91
+ - [gtdb-taxdump](https://github.com/shenwei356/gtdb-taxdump): the published taxdumps that omnitax's output is checked against.
92
+
93
+ How omnitax differs from these and from related tools is on [its own page](https://abrinca.github.io/omnitax/project/comparison/).
94
+
95
+ ## Licence
96
+
97
+ MIT.
@@ -0,0 +1,67 @@
1
+ # omnitax
2
+
3
+ Biological taxonomies (NCBI, GTDB and a few more) as Python objects, in one SQLite file or behind a small server, with a benchmarked way to translate between NCBI and GTDB.
4
+
5
+ > **Please read first.** omnitax was written with LLM coding agents and reviewed by a human. It is largely untested in practice: it has one real user so far ([sylphd](https://github.com/Abrinca/sylphd)). APIs may change before 1.0. It runs on Linux only for now. Check results on your own data before you rely on them.
6
+
7
+ ## Goals
8
+
9
+ 1. **Many taxonomies, handled the same way**: download, parse, one set of Python objects, conversion, export to standard formats. "All taxonomies" is not the aim; the common ones for microbiome work, and a pattern to add more, is.
10
+ 2. **One API, several backends**: a SQLite file, or a server on a Unix socket or HTTP, with the same answers.
11
+ 3. **Benchmarked translation between taxonomies**, with the method and results published. NCBI ↔ GTDB first.
12
+ 4. **Taxonomies you can change**: your own taxa as a small set of files that is applied again to every new release.
13
+ 5. **Reproducibility**: dated, checksummed snapshots of several taxonomies and versions in one file.
14
+
15
+ ## What works today
16
+
17
+ - Loaders for NCBI (current, or any monthly archive since 2018-12), GTDB 80 to 232, SILVA, Greengenes2, Open Tree, custom tables, and taxdump files (gtdb-taxdump, ictv-taxdump, TaxonKit output). SILVA, Greengenes2 and Open Tree load the real files but have had little more checking than that.
18
+ - Lineages, ranks, LCA, consensus, exact and fuzzy name search, subsets and edits, export as a taxdump or a table.
19
+ - Translation between NCBI and GTDB through shared genome accessions. Only GTDB 232 → NCBI has been measured; see [Translation](https://abrinca.github.io/omnitax/guides/translation/).
20
+ - Your own taxa as an overlay, a few files applied to each rebuild.
21
+ - A server, a client, and a command line (`build`, `list`, `lookup`, `lineage`, `search`, `translate`, `link`, `annotate`, `export-taxdump`, `serve`).
22
+
23
+ ## What does not work yet
24
+
25
+ SILVA, Greengenes2 and Open Tree cannot be translated to anything (no loader makes links for them). Not supported: native ICTV, GBIF, Catalogue of Life, UNITE, PR2, LTP, RDP, BOLD. Export is a taxdump or a table; there is no Newick or QIIME-style output. Linux only: Windows and macOS are not supported. See the [roadmap](https://github.com/Abrinca/omnitax/blob/main/ROADMAP.md).
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ uv add omnitax # the library (needs only httpx); or: pip install omnitax
31
+ uv tool install 'omnitax[server]' # the command line, with `omnitax serve`
32
+ ```
33
+
34
+ Python 3.12 or newer.
35
+
36
+ ## Use
37
+
38
+ ```bash
39
+ omnitax build -o taxonomies.sqlite ncbi+gtdb:232 gtdb:232 # downloads about 500 MB, takes minutes
40
+ omnitax lookup --db taxonomies.sqlite -t ncbi 562 "Homo sapiens"
41
+ omnitax translate --db taxonomies.sqlite -t gtdb:232 --to ncbi "s__Escherichia coli"
42
+ ```
43
+
44
+ ```python
45
+ import omnitax
46
+
47
+ ncbi = omnitax.open("taxonomies.sqlite", "ncbi")
48
+ ncbi["562"].lineage_string() # d__Bacteria;p__Pseudomonadota;...;s__Escherichia coli
49
+ ncbi.consensus({"562": 6, "564": 4}, threshold=0.5, exclude=ncbi.uninformative)
50
+ tiny = ncbi.subset(["561"], descendants=True) # a new taxonomy, in a temporary file
51
+ ```
52
+
53
+ Documentation: <https://abrinca.github.io/omnitax/>
54
+
55
+ ## Credits
56
+
57
+ - [sylphd](https://github.com/Abrinca/sylphd): omnitax began as its NCBI taxonomy code.
58
+ - [multitax](https://github.com/pirovc/multitax) (MIT): the source URLs and file formats, and the inspiration.
59
+ - [get-tax-info](https://github.com/MrTomRod/get-tax-info): an earlier tool that loads NCBI's taxdump into SQLite.
60
+ - [TaxonKit](https://github.com/shenwei356/taxonkit) (MIT): the recipe for taxids of taxonomies that have none.
61
+ - [gtdb-taxdump](https://github.com/shenwei356/gtdb-taxdump): the published taxdumps that omnitax's output is checked against.
62
+
63
+ How omnitax differs from these and from related tools is on [its own page](https://abrinca.github.io/omnitax/project/comparison/).
64
+
65
+ ## Licence
66
+
67
+ MIT.
@@ -0,0 +1,89 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "omnitax"
7
+ dynamic = ["version"]
8
+ description = "Biological taxonomies (NCBI, GTDB and a few more) as Python objects, in one SQLite file or behind a small server, with a benchmarked way to translate between NCBI and GTDB."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ { name = "Thomas Roder" },
15
+ { name = "Abrinca Genomics" },
16
+ ]
17
+ keywords = ["bioinformatics", "taxonomy", "ncbi", "taxid", "lineage"]
18
+ classifiers = [
19
+ "Development Status :: 3 - Alpha",
20
+ "Intended Audience :: Science/Research",
21
+ "Operating System :: POSIX :: Linux",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
27
+ "Typing :: Typed",
28
+ ]
29
+ # The base install is light on purpose: importing omnitax needs only the standard library;
30
+ # httpx is loaded when a server is used or a source is downloaded.
31
+ dependencies = [
32
+ "httpx",
33
+ ]
34
+
35
+ [project.optional-dependencies]
36
+ # `omnitax serve` and omnitax.server (mount /taxonomy/* into your own Starlette app).
37
+ server = [
38
+ "starlette",
39
+ "uvicorn",
40
+ "anyio",
41
+ ]
42
+ # Faster ids when writing a taxdump of a taxonomy whose ids are not numbers (omnitax.taxdump has a pure-Python xxHash64 without it).
43
+ taxdump = [
44
+ "xxhash",
45
+ ]
46
+
47
+ [project.urls]
48
+ Homepage = "https://abrinca.github.io/omnitax/"
49
+ Documentation = "https://abrinca.github.io/omnitax/"
50
+ Repository = "https://github.com/Abrinca/omnitax"
51
+
52
+ [project.scripts]
53
+ omnitax = "omnitax.cli:main"
54
+
55
+ [dependency-groups]
56
+ dev = [
57
+ "pytest",
58
+ "omnitax[server,taxdump]",
59
+ ]
60
+
61
+ [tool.hatch.version]
62
+ path = "src/omnitax/__init__.py"
63
+
64
+ [tool.hatch.build.targets.wheel]
65
+ packages = ["src/omnitax"]
66
+
67
+ [tool.hatch.build.targets.sdist]
68
+ # A sdist is the package: list it instead of pruning afterwards, so `uv build` never
69
+ # walks scratch/ or ref/. pyproject.toml is always included by hatchling.
70
+ only-include = ["src/omnitax", "README.md", "LICENSE", "CHANGELOG.md"]
71
+
72
+ [tool.pytest.ini_options]
73
+ testpaths = ["tests"]
74
+ addopts = "-ra -m 'not network'"
75
+ markers = ["network: downloads the real sources (opt in with -m network)"]
76
+ filterwarnings = [
77
+ "ignore:Using `httpx` with `starlette.testclient` is deprecated",
78
+ ]
79
+
80
+ [tool.ruff]
81
+ line-length = 180
82
+ target-version = "py312"
83
+
84
+ [tool.ruff.lint]
85
+ select = ["E", "F", "W", "B", "UP", "I", "RUF", "C90", "SIM"]
86
+ ignore = ["E501", "RUF001", "RUF002", "RUF012", "B905"] # long lines: the code is written wide on purpose
87
+
88
+ [tool.ruff.lint.mccabe]
89
+ max-complexity = 14
@@ -0,0 +1,26 @@
1
+ """omnitax: biological taxonomies (NCBI, GTDB, SILVA, Greengenes, Open Tree, custom) as Python
2
+ objects, parsed into a SQLite file, read from one or from a server.
3
+
4
+ ::
5
+
6
+ import omnitax
7
+
8
+ tax = omnitax.load("gtdb", "232") # parse into a temporary SQLite file
9
+ tax = omnitax.open("taxonomy.sqlite", "ncbi") # a file (see `omnitax build`)
10
+ tax = omnitax.connect(url="https://...", taxonomy="ncbi") # a server
11
+ tax["562"].lineage()
12
+ tax.consensus({"562": 6, "564": 4})
13
+
14
+ Importing this package needs only the standard library; ``httpx`` is imported when something is
15
+ downloaded or a server is used, ``starlette`` only by :mod:`omnitax.server`.
16
+ """
17
+
18
+ __version__ = "0.1.0" # first: modules imported below read it
19
+
20
+ from . import loaders
21
+ from .api import connect, open, taxonomies
22
+ from .core import GTDB_RANKS, Taxon, Taxonomy
23
+ from .loaders import load
24
+ from .sqlite import LayoutError
25
+
26
+ __all__ = ["GTDB_RANKS", "LayoutError", "Taxon", "Taxonomy", "__version__", "connect", "load", "loaders", "open", "taxonomies"]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,163 @@
1
+ """Downloading a source file: a resumable ``httpx`` transfer.
2
+
3
+ Only what ``omnitax build`` needs. The transfer goes to ``<destination>.part``, resumes with
4
+ HTTP ``Range`` and ``If-Range`` (the ``ETag`` or ``Last-Modified`` is kept in ``<destination>.part.validator``), is tried again a few times
5
+ after connection errors and ``5xx``, and is renamed once the size matches the ``Content-Length`` of the server.
6
+ ``httpx`` is imported here, so a machine that only reads a taxonomy file never loads it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import sys
13
+ import time
14
+ from collections.abc import Callable
15
+ from pathlib import Path
16
+ from typing import Any, NamedTuple
17
+
18
+ import httpx
19
+
20
+ #: Chunk size for streaming transfers.
21
+ CHUNK_SIZE = 1024 * 1024
22
+ #: Tries after the first one for a connection error or a 5xx answer, and the wait before the first (it doubles).
23
+ RETRIES = 3
24
+ RETRY_DELAY = 1.0
25
+
26
+ ProgressCallback = Callable[[str, int, int | None], None]
27
+
28
+
29
+ class DownloadError(RuntimeError):
30
+ """A transfer failed or produced the wrong file size."""
31
+
32
+
33
+ def _range_start(response: httpx.Response) -> int | None:
34
+ """Where a ``206`` response starts: ``Content-Range: bytes 100-999/1000`` is 100."""
35
+ try:
36
+ return int(response.headers["Content-Range"].split(None, 1)[1].split("-", 1)[0])
37
+ except (KeyError, IndexError, ValueError):
38
+ return None
39
+
40
+
41
+ class Download(NamedTuple):
42
+ """A file downloaded: where it is, its ``size`` and its checksums, computed as it arrived."""
43
+
44
+ path: Path
45
+ size: int
46
+ sha256: str
47
+ md5: str
48
+
49
+
50
+ def _hashed(path: Path | None = None) -> tuple[int, Any, Any]:
51
+ """``(size, sha256, md5)`` hashers that have read ``path`` (none: fresh ones)."""
52
+ sha, md5, size = hashlib.sha256(), hashlib.md5(usedforsecurity=False), 0
53
+ if path:
54
+ with open(path, "rb") as handle:
55
+ while chunk := handle.read(CHUNK_SIZE):
56
+ sha.update(chunk)
57
+ md5.update(chunk)
58
+ size += len(chunk)
59
+ return size, sha, md5
60
+
61
+
62
+ def hash_file(path: Path) -> tuple[int, str, str]:
63
+ """``(size, sha256, md5)`` of a file that was not downloaded (a cached or a local one): one pass over it."""
64
+ size, sha, md5 = _hashed(path)
65
+ return size, sha.hexdigest(), md5.hexdigest()
66
+
67
+
68
+ def _validator(response: httpx.Response) -> str:
69
+ """What tells that a resumed transfer is of the same file: the strong ``ETag``, else ``Last-Modified`` (empty: neither)."""
70
+ tag = response.headers.get("ETag", "")
71
+ return tag if tag and not tag.startswith("W/") else response.headers.get("Last-Modified", "")
72
+
73
+
74
+ def _attempt(client: httpx.Client, url: str, partial: Path, progress: ProgressCallback | None) -> tuple[int, Any, Any, int | None]:
75
+ """One transfer into ``partial``, resuming what is there when the server confirms it is still the same file (``If-Range`` with the validator kept
76
+ next to it; without one the partial file is dropped). ``(size, sha256, md5, expected size)``."""
77
+ sidecar = partial.with_name(partial.name + ".validator")
78
+ offset = partial.stat().st_size if partial.exists() else 0
79
+ validator = sidecar.read_text().strip() if sidecar.exists() else ""
80
+ if offset and not validator: # cannot be told from a part of another file
81
+ partial.unlink()
82
+ offset = 0
83
+ # identity: the bytes are saved as served (a .gz stays a .gz) and their number is the Content-Length
84
+ headers = {"Accept-Encoding": "identity", **({"Range": f"bytes={offset}-", "If-Range": validator} if offset else {})}
85
+ with client.stream("GET", url, headers=headers) as response:
86
+ resumed = bool(offset) and response.status_code == 206
87
+ if response.status_code == 416 or (resumed and _range_start(response) != offset):
88
+ partial.unlink(missing_ok=True)
89
+ sidecar.unlink(missing_ok=True)
90
+ return _attempt(client, url, partial, progress) # from the start
91
+ response.raise_for_status()
92
+ if not resumed: # a new file (or the server says the old one changed: 200 to a ranged request)
93
+ if validator_now := _validator(response):
94
+ sidecar.write_text(validator_now)
95
+ else:
96
+ sidecar.unlink(missing_ok=True)
97
+ done, sha, md5 = _hashed(partial if resumed else None) # a resumed file is read once, for what is there already
98
+ length = response.headers.get("Content-Length")
99
+ total = done + int(length) if length and length.isdigit() else None
100
+ with open(partial, "ab" if resumed else "wb") as handle:
101
+ for chunk in response.iter_raw(CHUNK_SIZE):
102
+ handle.write(chunk)
103
+ sha.update(chunk)
104
+ md5.update(chunk)
105
+ done += len(chunk)
106
+ if progress is not None:
107
+ progress(partial.name.removesuffix(".part"), done, total)
108
+ return done, sha, md5, total
109
+
110
+
111
+ def download(url: str, destination: Path, progress: ProgressCallback | None = None) -> Download:
112
+ """Download ``url`` into ``destination`` through ``destination.part``. An interrupted transfer is resumed (read once, to be hashed) if the
113
+ server says the file is the same (``If-Range``), else it starts over; connection errors and ``5xx`` answers are tried again ``RETRIES``
114
+ times, resuming. The bytes are those the server holds (no ``Content-Encoding`` is undone). The checksums are those of the whole file."""
115
+ partial = destination.with_name(destination.name + ".part")
116
+ partial.parent.mkdir(parents=True, exist_ok=True)
117
+ try:
118
+ with httpx.Client(timeout=httpx.Timeout(None, connect=30.0), follow_redirects=True) as client:
119
+ for attempt in range(RETRIES + 1):
120
+ try:
121
+ done, sha, md5, total = _attempt(client, url, partial, progress)
122
+ break
123
+ except (httpx.NetworkError, httpx.TimeoutException, httpx.RemoteProtocolError, httpx.HTTPStatusError) as error:
124
+ if attempt == RETRIES or (isinstance(error, httpx.HTTPStatusError) and error.response.status_code < 500):
125
+ raise
126
+ time.sleep(RETRY_DELAY * 2**attempt)
127
+ except (httpx.HTTPError, OSError) as error:
128
+ raise DownloadError(f"could not download {url}: {error}") from error
129
+ if total is not None and done != total:
130
+ partial.unlink(missing_ok=True)
131
+ partial.with_name(partial.name + ".validator").unlink(missing_ok=True)
132
+ raise DownloadError(f"could not download {url}: expected {total} bytes, got {done}")
133
+ partial.replace(destination)
134
+ partial.with_name(partial.name + ".validator").unlink(missing_ok=True)
135
+ return Download(destination, done, sha.hexdigest(), md5.hexdigest())
136
+
137
+
138
+ class ProgressPrinter:
139
+ """Callable progress reporter: rewrites one line per whole percent."""
140
+
141
+ def __init__(self, stream: object = None) -> None:
142
+ self.stream = stream if stream is not None else sys.stderr
143
+ self._last: dict[str, int] = {}
144
+
145
+ def __call__(self, name: str, done: int, total: int | None) -> None:
146
+ if total:
147
+ percent = int(done * 100 / total)
148
+ if percent == self._last.get(name) and done < total:
149
+ return
150
+ self._last[name] = percent
151
+ print(
152
+ f"\r{name}: {percent:3d}% ({done / 1e6:.1f}/{total / 1e6:.1f} MB)",
153
+ end="\n" if done >= total else "",
154
+ file=self.stream,
155
+ flush=True,
156
+ )
157
+ else:
158
+ print(
159
+ f"\r{name}: {done / 1e6:.1f} MB",
160
+ end="",
161
+ file=self.stream,
162
+ flush=True,
163
+ )