metaseed-ena 0.78.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,70 @@
1
+ # Python
2
+ __pycache__/
3
+
4
+ # Generated version file (hatch-vcs)
5
+ src/metaseed/_version.py
6
+ *.py[cod]
7
+ *$py.class
8
+ *.so
9
+ .Python
10
+ build/
11
+ develop-eggs/
12
+ dist/
13
+ downloads/
14
+ eggs/
15
+ .eggs/
16
+ lib/
17
+ lib64/
18
+ parts/
19
+ sdist/
20
+ var/
21
+ wheels/
22
+ *.egg-info/
23
+ .installed.cfg
24
+ *.egg
25
+
26
+ # Virtual environments
27
+ .venv/
28
+ venv/
29
+ ENV/
30
+
31
+ # UV
32
+ .uv/
33
+ # uv.lock is committed for reproducible dev/CI builds and Dependabot scanning.
34
+
35
+ # Testing
36
+ .pytest_cache/
37
+ .coverage
38
+ htmlcov/
39
+ .tox/
40
+ .nox/
41
+
42
+ # IDE
43
+ .idea/
44
+ .vscode/
45
+ *.swp
46
+ *.swo
47
+ *~
48
+
49
+ # Jupyter
50
+ .ipynb_checkpoints/
51
+
52
+ # Documentation
53
+ site/
54
+
55
+ # OS
56
+ .DS_Store
57
+ Thumbs.db
58
+
59
+ # Environment
60
+ .env
61
+ .env.local
62
+ *.local
63
+
64
+ # Logs
65
+ *.log
66
+
67
+ # Type checking
68
+ .mypy_cache/
69
+ .pytype/
70
+ docs/REVIEW.md
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.5
2
+ Name: metaseed-ena
3
+ Version: 0.78.0
4
+ Summary: The European Nucleotide Archive: import public metadata for an accession, export SRA submission XML, and the ena profile, for metaseed
5
+ Project-URL: Homepage, https://sorenwacker.github.io/metaseed/
6
+ Project-URL: Repository, https://github.com/sorenwacker/metaseed
7
+ Author: Sören Wacker
8
+ License: MIT
9
+ Keywords: ena,fair-data,metadata
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering
14
+ Requires-Python: >=3.11
15
+ Requires-Dist: httpx<1,>=0.27
16
+ Requires-Dist: metaseed==0.78.0
17
+ Description-Content-Type: text/markdown
18
+
19
+ # metaseed-ena
20
+
21
+ The ENA adapter for [metaseed](https://pypi.org/project/metaseed/): import public metadata for an accession, export SRA submission XML, and the ena profile. Install it through metaseed's extra:
22
+
23
+ ```bash
24
+ pip install 'metaseed[ena]'
25
+ ```
26
+
27
+ It is imported as `metaseed.ena`, requires `metaseed` at its own version, and is described in [Integration Adapters](https://sorenwacker.github.io/metaseed/architecture/integration-adapters/) and [ADR 007](https://sorenwacker.github.io/metaseed/architecture/decisions/007-profiles-and-adapters-are-plugins/).
@@ -0,0 +1,9 @@
1
+ # metaseed-ena
2
+
3
+ The ENA adapter for [metaseed](https://pypi.org/project/metaseed/): import public metadata for an accession, export SRA submission XML, and the ena profile. Install it through metaseed's extra:
4
+
5
+ ```bash
6
+ pip install 'metaseed[ena]'
7
+ ```
8
+
9
+ It is imported as `metaseed.ena`, requires `metaseed` at its own version, and is described in [Integration Adapters](https://sorenwacker.github.io/metaseed/architecture/integration-adapters/) and [ADR 007](https://sorenwacker.github.io/metaseed/architecture/decisions/007-profiles-and-adapters-are-plugins/).
@@ -0,0 +1,24 @@
1
+ """Pin a plugin's metaseed dependencies to its own version at build time (ADR 007).
2
+
3
+ Every distribution under ``packages/`` carries this same file; a test keeps
4
+ the copies identical.
5
+ """
6
+
7
+ from hatchling.metadata.plugin.interface import MetadataHookInterface
8
+
9
+
10
+ class PinToRelease(MetadataHookInterface):
11
+ """Set the dependencies from ``[tool.hatch.metadata.hooks.custom]``.
12
+
13
+ ``pinned`` names the distributions required at exactly the version this
14
+ build carries (``metaseed`` when omitted); ``dependencies`` lists the others,
15
+ each bounded below its next major version.
16
+ """
17
+
18
+ def update(self, metadata: dict) -> None:
19
+ """Write ``dependencies`` from the version hatch-vcs derived from the tag."""
20
+ version = metadata["version"]
21
+ pinned = self.config.get("pinned", ["metaseed"])
22
+ metadata["dependencies"] = [f"{name}=={version}" for name in pinned] + list(
23
+ self.config.get("dependencies", [])
24
+ )
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "metaseed-ena"
3
+ # The version comes from the repository's v* tag, shared with metaseed; the
4
+ # dependencies are written by hatch_build.py, which pins metaseed to that same
5
+ # version (ADR 007).
6
+ dynamic = ["version", "dependencies"]
7
+ description = "The European Nucleotide Archive: import public metadata for an accession, export SRA submission XML, and the ena profile, for metaseed"
8
+ readme = "README.md"
9
+ requires-python = ">=3.11"
10
+ license = { text = "MIT" }
11
+ authors = [{ name = "Sören Wacker" }]
12
+ keywords = ["metadata", "fair-data", "ena"]
13
+ classifiers = [
14
+ "Intended Audience :: Science/Research",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Scientific/Engineering",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://sorenwacker.github.io/metaseed/"
22
+ Repository = "https://github.com/sorenwacker/metaseed"
23
+
24
+ [project.entry-points."metaseed.plugins"]
25
+ ena = "metaseed.ena.plugin:PLUGIN"
26
+
27
+ [build-system]
28
+ requires = ["hatchling", "hatch-vcs"]
29
+ build-backend = "hatchling.build"
30
+
31
+ [tool.hatch.version]
32
+ source = "vcs"
33
+
34
+ [tool.hatch.version.raw-options]
35
+ root = "../.."
36
+ local_scheme = "no-local-version"
37
+
38
+ [tool.hatch.metadata.hooks.custom]
39
+ dependencies = ["httpx>=0.27,<1"]
40
+
41
+ # The package keeps its import path, metaseed.ena: this distribution installs
42
+ # metaseed/ena/ and no metaseed/__init__.py of its own.
43
+ [tool.hatch.build.targets.wheel]
44
+ only-include = ["src/metaseed/ena"]
45
+ sources = ["src"]
46
+
47
+ [tool.hatch.build.targets.sdist]
48
+ only-include = ["src/metaseed/ena", "README.md", "pyproject.toml", "hatch_build.py"]
49
+
50
+ [tool.uv.sources]
51
+ metaseed = { workspace = true }
@@ -0,0 +1,97 @@
1
+ """ENA (European Nucleotide Archive) importer.
2
+
3
+ Fetches public metadata for an ENA accession and maps it into a validated
4
+ ``ena``-profile dataset. Raw sequence files are referenced, never downloaded.
5
+
6
+ >>> from metaseed.ena import import_accession
7
+ >>> client = import_accession("PRJEB10000") # needs metaseed[ena]
8
+ >>> client.validate()
9
+
10
+ ``build_dataset`` (the pure mapper) is importable without the ``metaseed[ena]``
11
+ extra; ``import_accession`` needs ``httpx``.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+ import re
18
+ from typing import TYPE_CHECKING
19
+
20
+ from metaseed.dcat.publication import origin_url
21
+ from metaseed.ena.export import to_ena_xml
22
+ from metaseed.ena.mapper import build_dataset
23
+ from metaseed.facade.profiles import make_package_callable
24
+ from metaseed.provenance import INSDC_POLICY, creators_from, imported_now
25
+
26
+ if TYPE_CHECKING:
27
+ from metaseed.api.client import MetaseedClient
28
+ from metaseed.ena.client import EnaClient
29
+
30
+ __all__ = ["build_dataset", "import_accession", "to_ena_xml"]
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ #: A primary (PRJEB...) or secondary (ERP...) study accession: the only kind the
35
+ #: Portal's ``study`` and ``analysis`` results accept.
36
+ STUDY_ACCESSION = re.compile(r"^(PRJ[A-Z]{2}[0-9]+|[EDSR]RP[0-9]{6,})$")
37
+
38
+
39
+ def import_accession(
40
+ accession: str,
41
+ *,
42
+ version: str = "1.0",
43
+ client: EnaClient | None = None,
44
+ ) -> MetaseedClient:
45
+ """Import an ENA accession into an ``ena``-profile dataset.
46
+
47
+ Args:
48
+ accession: An ENA accession resolvable to runs (study, sample,
49
+ experiment, or run).
50
+ version: ``ena`` profile version.
51
+ client: Optional pre-configured :class:`~metaseed.ena.client.EnaClient`.
52
+
53
+ Returns:
54
+ A :class:`~metaseed.api.client.MetaseedClient` holding the imported
55
+ Study and its Samples, Experiments, Runs, Analyses and File references.
56
+ Call :meth:`~metaseed.api.client.MetaseedClient.validate` to report
57
+ gaps.
58
+ """
59
+ from metaseed.ena.client import EnaClient
60
+
61
+ client = client or EnaClient()
62
+ # Three requests per import, one per Portal result, whatever the study
63
+ # holds. The study and analysis results accept only a study accession,
64
+ # so a run, sample or experiment accession is resolved to its study
65
+ # through the runs first. The Portal answers an empty result with an
66
+ # empty list; the counts are logged so an absence is visibly an answer
67
+ # rather than a query not made.
68
+ runs = client.read_run(accession)
69
+ study_accession = runs[0].get("study_accession") if runs else None
70
+ if study_accession is None and STUDY_ACCESSION.match(accession):
71
+ study_accession = accession
72
+ study = client.study(study_accession) if study_accession else []
73
+ analyses = client.analysis(study_accession) if study_accession else []
74
+ logger.info(
75
+ "%s: %d study records, %d runs, %d analyses",
76
+ accession,
77
+ len(study),
78
+ len(runs),
79
+ len(analyses),
80
+ )
81
+ dataset = build_dataset(runs, study=study, analyses=analyses, version=version)
82
+ # ENA records name no license; the INSDC policy covers every one of them.
83
+ dataset.origin = imported_now(
84
+ "ENA",
85
+ accession,
86
+ record_url=origin_url("ena", accession),
87
+ stated_license=None,
88
+ repository_terms=INSDC_POLICY,
89
+ # ENA records name an organisation, not people.
90
+ creators=creators_from([(row.get("center_name") or "", "") for row in study]),
91
+ )
92
+ return dataset
93
+
94
+
95
+ # ``metaseed.ena`` is also the ``ena()`` facade shortcut; importing this
96
+ # package rebinds that name, so the package itself calls the shortcut.
97
+ make_package_callable(__name__)
@@ -0,0 +1,112 @@
1
+ """HTTP client for the ENA Portal API.
2
+
3
+ Fetches the metadata the Portal ``filereport`` endpoint publishes for an
4
+ accession, one request per result — ``study``, ``read_run`` and ``analysis`` —
5
+ asking for every column ENA publishes (``fields=all``). Requires ``httpx`` (the
6
+ ``metaseed[ena]`` extra). An ``httpx.Client`` can be injected for hermetic
7
+ testing.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import TYPE_CHECKING, Any
13
+
14
+ try:
15
+ import httpx
16
+ except (
17
+ ModuleNotFoundError
18
+ ) as exc: # pragma: no cover - exercised only without the extra
19
+ raise ModuleNotFoundError(
20
+ "ENA import requires httpx. Install with: pip install 'metaseed[ena]'"
21
+ ) from exc
22
+
23
+ from metaseed._http import request_json
24
+
25
+ if TYPE_CHECKING:
26
+ from collections.abc import Mapping
27
+
28
+ PORTAL_FILEREPORT = "https://www.ebi.ac.uk/ena/portal/api/filereport"
29
+ USER_AGENT = "metaseed (+https://github.com/sorenwacker/metaseed)"
30
+
31
+
32
+ class EnaClient:
33
+ """Minimal client for the ENA Portal ``filereport`` endpoint."""
34
+
35
+ def __init__(
36
+ self,
37
+ *,
38
+ base_url: str = PORTAL_FILEREPORT,
39
+ timeout: float = 30.0,
40
+ http_client: httpx.Client | None = None,
41
+ ) -> None:
42
+ """Initialize the client.
43
+
44
+ Args:
45
+ base_url: ENA Portal filereport endpoint.
46
+ timeout: Per-request timeout in seconds.
47
+ http_client: Optional pre-configured ``httpx.Client`` (e.g. with a
48
+ mock transport for tests). When omitted, a request is issued
49
+ directly via ``httpx``.
50
+ """
51
+ self._base_url = base_url
52
+ self._timeout = timeout
53
+ self._client = http_client
54
+
55
+ def _rows(self, accession: str, result: str) -> list[dict[str, Any]]:
56
+ """One ``filereport`` request for ``result``, with every column.
57
+
58
+ Asks for ``fields=all``, so each row carries every column ENA publishes
59
+ for that result rather than a chosen subset. A column the ``ena``
60
+ profile does not declare a field for still reaches the dataset, as an
61
+ attribute.
62
+ """
63
+ params: Mapping[str, str] = {
64
+ "accession": accession,
65
+ "result": result,
66
+ "fields": "all", # every column ENA publishes for the result
67
+ "format": "json",
68
+ "limit": "0", # no row cap
69
+ }
70
+ headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
71
+ data = request_json(
72
+ self._base_url,
73
+ params=params,
74
+ headers=headers,
75
+ timeout=self._timeout,
76
+ http_client=self._client,
77
+ )
78
+ return data if isinstance(data, list) else []
79
+
80
+ def read_run(self, accession: str) -> list[dict[str, Any]]:
81
+ """Return ENA ``read_run`` rows for an accession: one per run.
82
+
83
+ Args:
84
+ accession: Any ENA accession resolvable to runs (study, sample,
85
+ experiment, or run).
86
+
87
+ Returns:
88
+ One dict per run (empty if the accession resolves to no runs).
89
+ """
90
+ return self._rows(accession, "read_run")
91
+
92
+ def study(self, accession: str) -> list[dict[str, Any]]:
93
+ """Return the ENA ``study`` row for an accession.
94
+
95
+ The study record carries the columns that exist under no other result
96
+ (``study_description``, ``study_name``, ``keywords``, ...).
97
+
98
+ Returns:
99
+ One dict per study the accession resolves to (normally one).
100
+ """
101
+ return self._rows(accession, "study")
102
+
103
+ def analysis(self, accession: str) -> list[dict[str, Any]]:
104
+ """Return ENA ``analysis`` rows for an accession: one per analysis.
105
+
106
+ Assemblies, variant calls and annotations are a different Portal
107
+ result from the runs they derive from.
108
+
109
+ Returns:
110
+ One dict per analysis (empty when the study has none).
111
+ """
112
+ return self._rows(accession, "analysis")
@@ -0,0 +1,110 @@
1
+ """Check stored ENA Webin credentials against the live service.
2
+
3
+ Submitting to ENA needs a Webin account, and the one question worth answering
4
+ before a submission is attempted is whether the credentials work at all. One
5
+ request answers it: the Webin authentication endpoint returns a token for a
6
+ valid account and ``401`` for anything else.
7
+
8
+ The check runs against ENA's **test** service. The account is the same one
9
+ production uses, so a token from the test service proves the credentials, and
10
+ checking there means confirming a password never touches the live archive.
11
+ Submission chooses its service separately and deliberately.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import socket
17
+ from typing import TYPE_CHECKING
18
+
19
+ try:
20
+ import httpx
21
+ except (
22
+ ModuleNotFoundError
23
+ ) as exc: # pragma: no cover - exercised only without the extra
24
+ raise ModuleNotFoundError(
25
+ "ENA submission requires httpx. Install with: pip install 'metaseed[ena]'"
26
+ ) from exc
27
+
28
+ from metaseed.connection import PROBE_TIMEOUT, ConnectionCheck
29
+ from metaseed.ena.client import USER_AGENT
30
+
31
+ if TYPE_CHECKING:
32
+ from collections.abc import Mapping
33
+
34
+ #: ENA's test service. Deliberately the default for a credential check.
35
+ WEBIN_TEST_AUTH_URL = "https://wwwdev.ebi.ac.uk/ena/submit/webin/auth/token"
36
+ #: The live service. Only a submission the user confirms should reach this.
37
+ WEBIN_AUTH_URL = "https://www.ebi.ac.uk/ena/submit/webin/auth/token"
38
+
39
+
40
+ def _describe_failure(exc: Exception) -> str:
41
+ """Name the cause of a failed Webin request."""
42
+ host = "ENA's Webin service"
43
+ if isinstance(exc, socket.gaierror) or "name resolution" in str(exc).lower():
44
+ return f"Cannot resolve {host}. Check this machine's network and DNS."
45
+ if isinstance(exc, httpx.ConnectError | httpx.ConnectTimeout):
46
+ return f"Nothing answered at {host}. Check this machine can reach the internet."
47
+ if isinstance(exc, httpx.TimeoutException):
48
+ return f"{host} did not answer within {PROBE_TIMEOUT:g} seconds."
49
+ if isinstance(exc, httpx.HTTPStatusError):
50
+ code = exc.response.status_code
51
+ if code in (401, 403):
52
+ return (
53
+ "ENA rejected the Webin credentials. Check the username is the "
54
+ "Webin-NNNNN account and the password was copied whole."
55
+ )
56
+ if code >= 500:
57
+ return (
58
+ f"{host} is not answering right now (HTTP {code}). Try again "
59
+ "once it is back; the credentials were not judged."
60
+ )
61
+ return f"{host} refused the request (HTTP {code})."
62
+ return f"Could not reach {host}: {exc}"
63
+
64
+
65
+ def check_connection(
66
+ config: Mapping[str, str], *, http_client: httpx.Client | None = None
67
+ ) -> ConnectionCheck:
68
+ """Whether the stored Webin credentials authenticate.
69
+
70
+ Args:
71
+ config: The adapter's stored settings, holding ``webin_username`` and
72
+ ``webin_password``.
73
+ http_client: An ``httpx.Client`` to use instead of a new one, for
74
+ hermetic testing.
75
+
76
+ Returns:
77
+ A :class:`ConnectionCheck`. ``projects`` is always empty: ENA has no
78
+ equivalent of a project to choose between, so the Plugins page offers
79
+ no choice for this adapter.
80
+ """
81
+ username = str(config.get("webin_username") or "").strip()
82
+ password = str(config.get("webin_password") or "")
83
+ if not username or not password:
84
+ return ConnectionCheck(
85
+ ok=False,
86
+ message="Enter the Webin username (Webin-NNNNN) and password.",
87
+ )
88
+
89
+ payload = {"authRealms": ["ENA"], "username": username, "password": password}
90
+ headers = {"User-Agent": USER_AGENT, "Content-Type": "application/json"}
91
+ try:
92
+ if http_client is not None:
93
+ response = http_client.post(
94
+ WEBIN_TEST_AUTH_URL, json=payload, headers=headers
95
+ )
96
+ else:
97
+ with httpx.Client(timeout=PROBE_TIMEOUT) as client:
98
+ response = client.post(
99
+ WEBIN_TEST_AUTH_URL, json=payload, headers=headers
100
+ )
101
+ response.raise_for_status()
102
+ except Exception as exc:
103
+ # Every failure becomes a sentence: a settings page must report why it
104
+ # could not check, not raise into the request.
105
+ return ConnectionCheck(ok=False, message=_describe_failure(exc))
106
+
107
+ return ConnectionCheck(
108
+ ok=True,
109
+ message=f"ENA accepted {username} on the test service.",
110
+ )