Coverage for src/bioimageio/spec/_internal/_settings.py: 95%
65 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-18 09:17 +0000
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-18 09:17 +0000
1from __future__ import annotations
3import os
4from functools import cached_property
5from pathlib import Path
6from typing import Any
8import platformdirs
9from genericache import DiskCache
10from genericache.digest import UrlDigest
11from pydantic import Field, field_validator
12from pydantic_settings import BaseSettings, SettingsConfigDict
13from typing_extensions import Annotated
15from .root_url import RootHttpUrl
18class Settings(
19 BaseSettings, extra="ignore", allow_inf_nan=False, validate_assignment=True
20):
21 """environment variables for bioimageio.spec"""
23 model_config = SettingsConfigDict(
24 env_prefix="BIOIMAGEIO_", env_file=".env", env_file_encoding="utf-8"
25 )
27 allow_pickle: bool = False
28 """Sets the `allow_pickle` argument for `numpy.load()`"""
30 cache_path: Path = Path(platformdirs.user_cache_dir("bioimageio"))
31 """bioimageio cache location"""
33 def __setattr__(self, name: str, value: Any):
34 super().__setattr__(name, value)
35 # if cache_path is being changed, we need to reset the disk_cache so that it gets re-created with the new path when accessed next time
36 if (
37 name == "cache_path"
38 and "disk_cache" in self.__dict__
39 and self.disk_cache.dir_path != value
40 ):
41 del self.disk_cache
43 @field_validator("cache_path", mode="after")
44 @classmethod
45 def _expand_user(cls, value: Path):
46 return Path(os.path.expanduser(str(value)))
48 CI: Annotated[bool | str, Field(alias="CI")] = False
49 """Wether or not the execution happens in a continuous integration (CI) environment."""
51 collection_http_pattern: str = (
52 "https://hypha.aicell.io/bioimage-io/artifacts/{bioimageio_id}/files/rdf.yaml"
53 )
54 """A pattern to map bioimageio IDs to bioimageio.yaml URLs.
55 Notes:
56 - '{bioimageio_id}' is replaced with user query,
57 e.g. "affable-shark" when calling `load_description("affable-shark")`.
58 - This method takes precedence over resolving via `id_map`.
59 - If this endpoints fails, we fall back to `id_map`.
60 """
62 github_username: str | None = None
63 """GitHub username for API requests"""
65 github_token: str | None = None
66 """GitHub token for API requests"""
68 http_timeout: float = 10.0
69 """Timeout in seconds for http requests."""
71 huggingface_http_pattern: str = (
72 "https://huggingface.co/{repo_id}/resolve/{branch}/package/bioimageio.yaml"
73 )
74 """A pattern to map huggingface repo IDs to bioimageio.yaml URLs.
75 Notes:
76 - Used for loading source strings of the form "huggingface/{user_or_org}/{resource_id}[/{version}]"
77 - example use: `load_description("huggingface/fynnbe/ambitious-sloth/1.3")`
78 - A given version {version} is mapped to a branch name "v{version}", e.g. "v1.3".
79 - If no version is provided the "main" branch is used.
80 - This method takes precedence over resolving via `id_map`.
81 - If this endpoints fails, we fall back to `id_map`.
82 """
84 hypha_upload: str = (
85 "https://hypha.aicell.io/public/services/artifact-manager/create"
86 )
87 """URL to the upload endpoint for bioimageio resources."""
89 hypha_upload_token: str | None = None
90 """Hypha API token to use for uploads.
92 By setting this token you agree to our terms of service at https://bioimage.io/#/toc.
94 How to obtain a token:
95 1. Login to https://bioimage.io
96 2. Generate a new token at https://bioimage.io/#/api?tab=hypha-rpc
97 """
99 id_map: str = (
100 "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/id_map.json"
101 )
102 """URL to bioimageio id_map.json to resolve resource IDs."""
104 id_map_draft: str = (
105 "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/id_map_draft.json"
106 )
107 """URL to bioimageio id_map_draft.json to resolve draft IDs ending with '/draft'."""
109 log_warnings: bool = True
110 """Log validation warnings to console."""
112 perform_io_checks: bool = True
113 """Wether or not to perform validation that requires file io,
114 e.g. downloading a remote files.
116 Existence of any local absolute file paths is still being checked."""
118 resolve_draft: bool = True
119 """Flag to resolve draft resource versions following the pattern
120 <resource id>/draft.
122 Note that anyone may stage a new draft and that such a draft version
123 may not have been reviewed yet.
124 Set this flag to False to avoid this potential security risk
125 and disallow loading draft versions."""
127 user_agent: str | None = None
128 """user agent for http requests"""
130 @cached_property
131 def disk_cache(self):
132 cache = DiskCache[RootHttpUrl].create(
133 url_type=RootHttpUrl,
134 cache_dir=self.cache_path,
135 url_hasher=UrlDigest.from_str,
136 )
137 return cache
139 @property
140 def github_auth(self):
141 if self.github_username is None or self.github_token is None:
142 return None
143 else:
144 return (self.github_username, self.github_token)
147settings = Settings()
148"""parsed environment variables for bioimageio.spec"""