Coverage for src/bioimageio/spec/_internal/_settings.py: 95%

65 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 16:20 +0000

1from __future__ import annotations 

2 

3import os 

4from collections.abc import Sequence 

5from functools import cached_property 

6from pathlib import Path 

7from typing import Annotated, Any 

8 

9import platformdirs 

10from genericache import DiskCache 

11from genericache.digest import UrlDigest 

12from pydantic import Field, field_validator 

13from pydantic_settings import BaseSettings, SettingsConfigDict 

14 

15from .root_url import RootHttpUrl 

16 

17 

18class Settings( 

19 BaseSettings, extra="ignore", allow_inf_nan=False, validate_assignment=True 

20): 

21 """environment variables for bioimageio.spec""" 

22 

23 model_config = SettingsConfigDict( 

24 env_prefix="BIOIMAGEIO_", env_file=".env", env_file_encoding="utf-8" 

25 ) 

26 

27 allow_pickle: bool = False 

28 """Sets the `allow_pickle` argument for `numpy.load()`""" 

29 

30 cache_path: Path = Path(platformdirs.user_cache_dir("bioimageio")) 

31 """bioimageio cache location""" 

32 

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 

42 

43 @field_validator("cache_path", mode="after") 

44 @classmethod 

45 def _expand_user(cls, value: Path): 

46 return Path(os.path.expanduser(str(value))) 

47 

48 CI: Annotated[bool | str, Field(alias="CI")] = False 

49 """Wether or not the execution happens in a continuous integration (CI) environment.""" 

50 

51 collection_http_pattern: str | Sequence[str] = ( 

52 "https://hypha.aicell.io/bioimage-io/artifacts/{bioimageio_id}/files/bioimageio.yaml", 

53 "https://hypha.aicell.io/bioimage-io/artifacts/{bioimageio_id}/files/rdf.yaml", 

54 ) 

55 """A pattern or ordered sequence of patterns to map bioimageio IDs to bioimageio.yaml URLs. 

56 Notes: 

57 - '{bioimageio_id}' is replaced with user query, 

58 e.g. "affable-shark" when calling `load_description("affable-shark")`. 

59 - Multiple patterns are tried in order until one succeeds. 

60 - This method takes precedence over resolving via `id_map`. 

61 - If all endpoints fail, we fall back to `id_map`. 

62 """ 

63 

64 github_username: str | None = None 

65 """GitHub username for API requests""" 

66 

67 github_token: str | None = None 

68 """GitHub token for API requests""" 

69 

70 http_timeout: float = 10.0 

71 """Timeout in seconds for http requests.""" 

72 

73 huggingface_http_pattern: str = ( 

74 "https://huggingface.co/{repo_id}/resolve/{branch}/package/bioimageio.yaml" 

75 ) 

76 """A pattern to map huggingface repo IDs to bioimageio.yaml URLs. 

77 Notes: 

78 - Used for loading source strings of the form "huggingface/{user_or_org}/{resource_id}[/{version}]" 

79 - example use: `load_description("huggingface/fynnbe/ambitious-sloth/1.3")` 

80 - A given version {version} is mapped to a branch name "v{version}", e.g. "v1.3". 

81 - If no version is provided the "main" branch is used. 

82 - This method takes precedence over resolving via `id_map`. 

83 - If this endpoints fails, we fall back to `id_map`. 

84 """ 

85 

86 hypha_upload: str = ( 

87 "https://hypha.aicell.io/public/services/artifact-manager/create" 

88 ) 

89 """URL to the upload endpoint for bioimageio resources.""" 

90 

91 hypha_upload_token: str | None = None 

92 """Hypha API token to use for uploads. 

93 

94 By setting this token you agree to our terms of service at https://bioimage.io/#/toc. 

95 

96 How to obtain a token: 

97 1. Login to https://bioimage.io 

98 2. Generate a new token at https://bioimage.io/#/api?tab=hypha-rpc 

99 """ 

100 

101 id_map: str = ( 

102 "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/id_map.json" 

103 ) 

104 """URL to bioimageio id_map.json to resolve resource IDs.""" 

105 

106 id_map_draft: str = ( 

107 "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/id_map_draft.json" 

108 ) 

109 """URL to bioimageio id_map_draft.json to resolve draft IDs ending with '/draft'.""" 

110 

111 log_warnings: bool = True 

112 """Log validation warnings to console.""" 

113 

114 perform_io_checks: bool = True 

115 """Wether or not to perform validation that requires file io, 

116 e.g. downloading a remote files. 

117 

118 Existence of any local absolute file paths is still being checked.""" 

119 

120 resolve_draft: bool = True 

121 """Flag to resolve draft resource versions following the pattern 

122 <resource id>/draft. 

123 

124 Note that anyone may stage a new draft and that such a draft version 

125 may not have been reviewed yet. 

126 Set this flag to False to avoid this potential security risk 

127 and disallow loading draft versions.""" 

128 

129 user_agent: str | None = None 

130 """user agent for http requests""" 

131 

132 @cached_property 

133 def disk_cache(self): 

134 cache = DiskCache[RootHttpUrl].create( 

135 url_type=RootHttpUrl, 

136 cache_dir=self.cache_path, 

137 url_hasher=UrlDigest.from_str, 

138 ) 

139 return cache 

140 

141 @property 

142 def github_auth(self): 

143 if self.github_username is None or self.github_token is None: 

144 return None 

145 else: 

146 return (self.github_username, self.github_token) 

147 

148 

149settings = Settings() 

150"""parsed environment variables for bioimageio.spec"""