Coverage for src/bioimageio/core/_utils/io_zarr.py: 76%

71 statements  

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

1from __future__ import annotations 

2 

3from collections.abc import Mapping, Sequence 

4from typing import Any 

5 

6import zarr 

7from loguru import logger 

8 

9 

10def open_zarr_multiscale_array( 

11 uri: str, 

12) -> tuple[zarr.Array[Any], Any]: 

13 """Open a zarr multiscale array from a URI""" 

14 ms, _uri_to_parent, sub_uri = _recurse_url_to_find_group(uri) 

15 

16 zarr_array_or_group = zarr.open(uri) 

17 if isinstance(zarr_array_or_group, zarr.Group): 

18 keys = list(ms.keys()) 

19 if len(keys) == 1: 19 ↛ 22line 19 didn't jump to line 22 because the condition on line 19 was always true

20 return open_zarr_multiscale_array(f"{uri}/{keys[0]}") 

21 else: 

22 raise ValueError( 

23 f"{uri} does not point to a zarr array, but a group with keys: {keys}." 

24 + " Append '/<key>' to the URI to open a specific array." 

25 ) 

26 

27 return zarr_array_or_group, ms[sub_uri] 

28 

29 

30def _recurse_url_to_find_group(uri: str) -> tuple[Any, str, str]: 

31 """URI may point to an OME-Zarr "multiscales" root or to a specific scale. 

32 Try to find OME-Zarr spec first at URI, then search parent directories. 

33 Returns 

34 - the valid Multiscale 

35 - root URI of the multiscales group 

36 - scale sub-URI""" 

37 uri = uri.rstrip("/") 

38 i = len(uri) 

39 parent_group = None 

40 uri_to_parent = uri 

41 sub_uri = "" 

42 for _ in range(uri.count("/")): 42 ↛ 56line 42 didn't jump to line 56 because the loop on line 42 didn't complete

43 try: 

44 parent_group = zarr.open(uri_to_parent) 

45 if isinstance(parent_group, zarr.Group): 

46 break 

47 except Exception: 

48 # stop looking once we checked a ".zarr" directory 

49 if uri_to_parent.split("/")[-1].endswith(".zarr"): 

50 break 

51 

52 i = uri.rfind("/", 0, i) 

53 uri_to_parent = uri[:i] 

54 sub_uri = uri[i + 1 :] 

55 

56 if isinstance(parent_group, zarr.Group): 56 ↛ 63line 56 didn't jump to line 63 because the condition on line 56 was always true

57 return ( 

58 _ms_from_group(parent_group, sub_uri), 

59 uri_to_parent, 

60 sub_uri, 

61 ) 

62 

63 raise ValueError("No multiscale meta found anywhere along the URI") 

64 

65 

66def _ms_from_group(zarr_group: zarr.Group, must_have_dataset: str | None = None) -> Any: 

67 import clearscale 

68 

69 # 1. Discover the "multiscales" list 

70 try: 

71 ome = zarr_group.attrs["ome"] 

72 assert isinstance(ome, Mapping) 

73 ome_multiscales = ome["multiscales"] 

74 except Exception: 

75 try: 

76 ome_multiscales = zarr_group.attrs["multiscales"] 

77 except Exception: 

78 raise ValueError("No multiscale metadata found in zarr group") 

79 

80 if not isinstance(ome_multiscales, Sequence) or isinstance(ome_multiscales, str): 80 ↛ 81line 80 didn't jump to line 81 because the condition on line 80 was never true

81 raise TypeError( 

82 "Multiscale metadata in this zarr group is not a valid sequence" 

83 ) 

84 

85 # 2. Convert all entries of the "multiscales" list 

86 # (There will practically never be more than one) 

87 valid_multiscales: list[Any] = [] 

88 for ome_ms in ome_multiscales: 

89 try: 

90 assert isinstance(ome_ms, Mapping) 

91 valid_multiscales.append( 

92 clearscale.Multiscale.from_ome_zarr( 

93 ome_ms, shape_source=_get_shape_callable(zarr_group) 

94 ) 

95 ) 

96 except Exception as e: 

97 logger.debug("Encountered invalid multiscale metadata: {}", e) 

98 continue # Invalid multiscale - maybe warn, or just skip 

99 

100 if not valid_multiscales: 100 ↛ 101line 100 didn't jump to line 101 because the condition on line 100 was never true

101 raise ValueError("Multiscale metadata in this zarr group was all invalid") 

102 

103 if must_have_dataset: 

104 selected_ms = next( 

105 (ms for ms in valid_multiscales if must_have_dataset in ms), None 

106 ) 

107 if selected_ms is None: 107 ↛ 108line 107 didn't jump to line 108 because the condition on line 107 was never true

108 raise ValueError( 

109 f"No Multiscale containing a dataset named {must_have_dataset!r} found" 

110 ) 

111 return selected_ms 

112 

113 # 3. Handle the off-chance that there is more than one for some reason. 

114 if len(valid_multiscales) > 1: 114 ↛ 117line 114 didn't jump to line 117 because the condition on line 114 was never true

115 # ilastik bounces back group URLs in this case and forces selection by passing a direct URL to a dataset. 

116 # Many tools just default to valid_multiscales[0] and ignore further multiscale definitions. 

117 raise ValueError( 

118 f"{len(valid_multiscales)} Multiscale definitions found. Selection required." 

119 ) 

120 else: 

121 return valid_multiscales[0] 

122 

123 

124def _get_shape_callable(zarr_group: zarr.Group): 

125 def get_shape(path: str): 

126 zarr_array = zarr_group[path] 

127 assert isinstance(zarr_array, zarr.Array) 

128 return zarr_array.shape 

129 

130 return get_shape