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

64 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-02-17 16:08 +0000

1import os 

2from functools import cached_property 

3from pathlib import Path 

4from typing import Any, Optional, Union 

5 

6import platformdirs 

7from genericache import DiskCache 

8from genericache.digest import UrlDigest 

9from pydantic import Field, field_validator 

10from pydantic_settings import BaseSettings, SettingsConfigDict 

11from typing_extensions import Annotated 

12 

13from .root_url import RootHttpUrl 

14 

15 

16class Settings( 

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

18): 

19 """environment variables for bioimageio.spec""" 

20 

21 model_config = SettingsConfigDict( 

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

23 ) 

24 

25 allow_pickle: bool = False 

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

27 

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

29 """bioimageio cache location""" 

30 

31 def __setattr__(self, name: str, value: Any): 

32 super().__setattr__(name, value) 

33 # 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 

34 if ( 

35 name == "cache_path" 

36 and "disk_cache" in self.__dict__ 

37 and self.disk_cache.dir_path != value 

38 ): 

39 del self.disk_cache 

40 

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

42 @classmethod 

43 def _expand_user(cls, value: Path): 

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

45 

46 CI: Annotated[Union[bool, str], Field(alias="CI")] = False 

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

48 

49 collection_http_pattern: str = ( 

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

51 ) 

52 """A pattern to map bioimageio IDs to bioimageio.yaml URLs. 

53 Notes: 

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

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

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

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

58 """ 

59 

60 github_username: Optional[str] = None 

61 """GitHub username for API requests""" 

62 

63 github_token: Optional[str] = None 

64 """GitHub token for API requests""" 

65 

66 http_timeout: float = 10.0 

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

68 

69 huggingface_http_pattern: str = ( 

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

71 ) 

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

73 Notes: 

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

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

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

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

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

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

80 """ 

81 

82 hypha_upload: str = ( 

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

84 ) 

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

86 

87 hypha_upload_token: Optional[str] = None 

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

89 

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

91 

92 How to obtain a token: 

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

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

95 """ 

96 

97 id_map: str = ( 

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

99 ) 

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

101 

102 id_map_draft: str = ( 

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

104 ) 

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

106 

107 log_warnings: bool = True 

108 """Log validation warnings to console.""" 

109 

110 perform_io_checks: bool = True 

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

112 e.g. downloading a remote files. 

113 

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

115 

116 resolve_draft: bool = True 

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

118 <resource id>/draft. 

119 

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

121 may not have been reviewed yet. 

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

123 and disallow loading draft versions.""" 

124 

125 user_agent: Optional[str] = None 

126 """user agent for http requests""" 

127 

128 @cached_property 

129 def disk_cache(self): 

130 cache = DiskCache[RootHttpUrl].create( 

131 url_type=RootHttpUrl, 

132 cache_dir=self.cache_path, 

133 url_hasher=UrlDigest.from_str, 

134 ) 

135 return cache 

136 

137 @property 

138 def github_auth(self): 

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

140 return None 

141 else: 

142 return (self.github_username, self.github_token) 

143 

144 

145settings = Settings() 

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