
    0-Ph                    (   d Z ddlmZ g dZddlZddlZddlZddlZddlZddl	m
Z
 ddlZddlZ	 ddlmZmZ ddlmZ ddlmZ n"# e$ rZ ed	ej         d
          edZ[ww xY wddlmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& e
r:ddl'm(Z(m)Z)m*Z*m+Z+m,Z, ddl	m-Z-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddlm9Z9m:Z:  G d de          Z; G d de;          Z< G d de;          Z=dddddAd'Z>dBd.Z?dCd1Z@dDd5ZAdEd7ZBdFd:ZCdGd=ZDdHd@ZEdS )Iz%Zarr 3 TIFF and file sequence stores.    )annotations)	ZarrStoreZarrTiffStoreZarrFileSequenceStoreN)TYPE_CHECKING)ByteRequestStore)NDBuffer)RegularChunkGridzzarr z < 3 is not supported   )	CHUNKMODECOMPRESSION	FileCacheFileSequenceNullContext	TiffFrameTiffPageTiffPageSeriesTiledSequencecreate_outputenumargimreadjpeg_decode_colorspaceproduct)AsyncIteratorCallableIterableIteratorSequence)AnyTextIO)	DTypeLikeNDArray)BufferBufferPrototype)	BytesLike)BasicSelection)	ByteOrder
OutputTypec                       e Zd ZU dZded<   ded<   ded<   ded	<   d
d
ddd3 fdZd4dZd5dZed6d            Z	d7d#Z
d7d$Zed6d%            Zd8d&Zed6d'            Zd9d*Zed6d+            Zd:d-Zd;d/Zd;d0Zed6d1            Zd<d2Z xZS )=r   a  Zarr 3 store base class.

    Parameters:
        fillvalue:
            Value to use for missing chunks of Zarr store.
            The default is 0.
        chunkmode:
            Specifies how to chunk data.
        read_only:
            Passed to zarr `Store` constructor.

    References:
        1. https://zarr.readthedocs.io/en/stable/api/zarr/abc/store/
        3. https://zarr.readthedocs.io/en/stable/spec/v2.html
        3. https://forum.image.sc/t/multiscale-arrays-v0-1/37930

    bool
_read_onlydict[str, Any]_storezint | float
_fillvalueint
_chunkmodeNT	fillvalue	chunkmode	read_onlyr3   int | float | Noner4   CHUNKMODE | int | str | Noner5   returnNonec                  t                                          |           i | _        |dn|| _        |t	          d          | _        d S t          t          |          | _        d S )N)r5   r   )super__init__r.   r/   r   r1   r   )selfr3   r4   r5   	__class__s       M/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/tifffile/zarr.pyr<   zZarrStore.__init__r   sc     	9---(0!!i'llDOOO%i;;DOOO    otherobjectc                    t          |t          |                     o/| j        |j        k    o| j        |j        k    o| j        |j        k    S )zReturn if objects are equal.)
isinstancetyper.   r/   r1   )r=   rA   s     r?   __eq__zZarrStore.__eq__   sS     ud4jj)) 4u|+45#334 5#33		
r@   	prototyper%   
key_ranges(Iterable[tuple[str, ByteRequest | None]]list[Buffer | None]c                4    K    fd|D              d{V S )z5Return possibly partial values from given key_ranges.c                T   K   g | ]"\  }}                     ||           d {V #S N)get).0key
byte_rangerG   r=   s      r?   
<listcomp>z0ZarrStore.get_partial_values.<locals>.<listcomp>   sS       
 
 
Z ((3	:66666666
 
 
r@   N )r=   rG   rH   s   `` r?   get_partial_valueszZarrStore.get_partial_values   sV      
 
 
 
 
#-
 
 
 
 
 
 
 
 
 	
r@   c                    | j          S )zStore supports writes.)r,   r=   s    r?   supports_writeszZarrStore.supports_writes   s     ?""r@   rP   strvaluer$   c                   t           )Store (key, value) pair.)NotImplementedErrorr=   rP   rY   s      r?   _setzZarrStore._set   s    !!r@   c                6   K   |                      ||           dS )r[   N)r^   r]   s      r?   setzZarrStore.set   s       		#ur@   c                    dS )zStore supports deletes.FrS   rV   s    r?   supports_deleteszZarrStore.supports_deletes   	     ur@   c                $   K   t          d          )zRemove key from store.z"ZarrStore does not support deletesPermissionErrorr=   rP   s     r?   deletezZarrStore.delete   s      BCCCr@   c                    dS )zStore support partial writes.FrS   rV   s    r?   supports_partial_writesz!ZarrStore.supports_partial_writes   rc   r@   key_start_values$Iterable[tuple[str, int, BytesLike]]c                $   K   t          d          )z2Store values at key, starting at byte range_start.z)ZarrStore does not support partial writesre   )r=   rk   s     r?   set_partial_valueszZarrStore.set_partial_values   s       IJJJr@   c                    dS )zStore supports listing.TrS   rV   s    r?   supports_listingzZarrStore.supports_listing   s	     tr@   AsyncIterator[str]c               (   K   | j         D ]}|W V  dS )zReturn all keys in store.Nr.   rg   s     r?   listzZarrStore.list   s.      ; 	 	CIIIII	 	r@   prefixc               l   K   t          | j                  D ]}|                    |          r|W V  dS )zxReturn all keys in store that begin with prefix.

        Keys are returned relative to the root of the store.

        N)rt   r.   
startswith)r=   ru   rP   s      r?   list_prefixzZarrStore.list_prefix   sK       $$ 	 	C~~f%% 					 	r@   c                  K                        d          dk    rd | j        D             }nfd| j        D             }|D ]}|W V  dS )zReturn all keys and prefixes with prefix.

        Keys and prefixes do not contain the character "/" after the given
        prefix.

        / c                D    h | ]}|                     d           d         S rz   r   )split)rO   ks     r?   	<setcomp>z%ZarrStore.list_dir.<locals>.<setcomp>   s&    @@@q1773<<?@@@r@   c                    h | ]Q}|                     d z             r7|k     |                    d z                                 d           d         RS r}   )rw   removeprefixr~   )rO   rP   ru   s     r?   r   z%ZarrStore.list_dir.<locals>.<setcomp>   si       >>&3,// 586MM   #..44S99!<4AMMr@   N)rstripr.   )r=   ru   keys_uniquerP   s    `  r?   list_dirzZarrStore.list_dir   s       s##R<<@@DK@@@KK   ;  K
  	 	CIIIII	 	r@   c                     d| j         d         v S )z$Return if ZarrStore is multi-scales.s   multiscales.zattrsrs   rV   s    r?   is_multiscaleszZarrStore.is_multiscales   s     Y!777r@   c                    | j         j         S rM   )r>   __name__rV   s    r?   __repr__zZarrStore.__repr__   s    .)++r@   )r3   r6   r4   r7   r5   r+   r8   r9   )rA   rB   r8   r+   )rG   r%   rH   rI   r8   rJ   )r8   r+   rP   rX   rY   r$   r8   r9   )rP   rX   r8   r9   )rk   rl   r8   r9   )r8   rq   )ru   rX   r8   rq   )r8   rX   )r   
__module____qualname____doc____annotations__r<   rF   rT   propertyrW   r^   r`   rb   rh   rj   rn   rp   rt   rx   r   r   r   __classcell__r>   s   @r?   r   r   Z   s         $ OOO )-26< < < < < < < <"
 
 
 


 

 

 

 # # # X#" " " "       XD D D D    XK K K K    X   
      & 8 8 8 X8, , , , , , , ,r@   r   c                       e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<   ded<   ded<   dddddddddddddO fd'ZdP fd(Zdddddddd)d*d+	dQd<Z	 dRdSdDZdTdEZ	dUdHZ
dVdJZdWdNZ xZS )Xr   a+  Zarr 3 store interface to image array in TiffPage or TiffPageSeries.

    ZarrTiffStore is using a TiffFile instance for reading and decoding chunks.
    Therefore, ZarrTiffStore instances cannot be pickled.

    For writing, image data must be stored in uncompressed, unpredicted,
    and unpacked form. Sparse strips and tiles are not written.

    Parameters:
        arg:
            TIFF page or series to wrap as Zarr store.
        level:
            Pyramidal level to wrap. The default is 0.
        chunkmode:
            Use strips or tiles (0) or whole page data (2) as chunks.
            The default is 0.
        fillvalue:
            Value to use for missing chunks. The default is 0.
        zattrs:
            Additional attributes to store in `.zattrs`.
        multiscales:
            Create a multiscales compatible Zarr group store.
            By default, create a Zarr array store for pages and non-pyramidal
            series.
        lock:
            Reentrant lock to synchronize seeks and reads from file.
            By default, the lock of the parent's file handle is used.
        squeeze:
            Remove length-1 dimensions from shape of TiffPageSeries.
        maxworkers:
            If `chunkmode=0`, asynchronously run chunk decode function
            in separate thread if greater than 1.
            If `chunkmode=2`, maximum number of threads to concurrently decode
            strips or tiles.
            If *None* or *0*, use up to :py:attr:`_TIFF.MAXWORKERS` or
            asyncio assigned threads.
        buffersize:
            Approximate number of bytes to read from file in one pass
            if `chunkmode=2`. The default is :py:attr:`_TIFF.BUFFERSIZE`.
        read_only:
            Passed to zarr `Store` constructor.
        _openfiles:
            Internal API.

    zlist[TiffPageSeries]_datar   
_filecachez-Callable[[NDArray[Any]], NDArray[Any]] | None
_transformr0   _maxworkers
int | None_buffersizebool | None_squeezer+   _multiscalesN)levelr4   r3   zattrsmultiscaleslocksqueeze
maxworkers
buffersizer5   
_openfilesarg%TiffPage | TiffFrame | TiffPageSeriesr   r4   r7   r3   r6   r   dict[str, Any] | Noner   r   $threading.RLock | NullContext | Noner   r   r   r5   r   kwargsr    r8   r9   c              	   |t          d          | _        nt          t           |          | _        | j        dvrt          | j        d          |d nt	          |          | _        |
| _        t          |t                    r;|j	        | _
        |j        | _        ||sd| j
                 g| _
        |j        }nt          |g          g| _
        d | _        d}|	s*| j
        d         j        j        }	|	dk     r| j        dk    rd}	|	| _        | j
        d         j        j        j        j        }| |                                 p
| j        dk    }t+                                          || j        |           ||                    d           |j        }t3          ||	          | _        |i nt7          |          }|st9          | j
                  dk    rd| _        d
|v r|                    d
          }n-t?          | j
        d                              |                    }tC          ddi          | j"        d<   tC          dd|d tG          t9          | j
                            D             i dgi|          | j"        d<   | j
        d         $                    |          }tK          | j
                  D ]\  }|j        }|j&         |$                    |          }|j'        }||j(        x| _)        }| j        r|j*        }n|j+        }tC          d
fdtY          |||          D             i          | j"         d<   tC          d|t[          |||j.                  t_          |          d ta          ||          dd d          | j"         d<   | j1        ste          |           | _1        d S d| _        | j
        d         }|j        }|j&         |$                    |          }|j'        }||j(        x| _)        }| j        r|j*        }n|j+        }d
|vr%t?          |                     |                    |d
<   tC          |          | j"        d<   tC          d|t[          |||j.                  t_          |          d ta          ||          dd d          | j"        d<   | j1        ste          |           | _1        d S d S )Nr   >   r      z not implementedUnnamed   r   r2   T)sizer   _ARRAY_DIMENSIONSzarr_formatr   .zgroupr   z0.1c                0    g | ]}d t          |          iS )pathrX   rO   is     r?   rR   z*ZarrTiffStore.__init__.<locals>.<listcomp>|  s3     ) ) )$% "(Q 0) ) )r@   )versionnamedatasetsmetadatar   c                4    g | ]\  }}}||k    r|  n|S rS   rS   )rO   axr   jr   s       r?   rR   z*ZarrTiffStore.__init__.<locals>.<listcomp>  sC     . . . (Aq 01Avv^E^^^2. . .r@   z/.zattrsCr   shapechunksdtype
compressor
fill_valueorderfiltersz/.zarrayF.zarray)3r   r1   r   r\   r+   r   r   rD   r   levelsr   	transformr   r   keyframer   r   parent_parent
filehandlewritabler;   r<   set_lockr   r   r   dictlenr   poprt   get_axes_json_dumpsr.   range	get_shape	enumeratedecoder   nodatar/   r   r   zip_chunksshaped
_dtype_str_json_valuer,   _is_writable)r=   r   r   r4   r3   r   r   r   r   r   r   r5   r   r   r   fharray_dimensionsshape0seriesr   r   r   r   r>   s     `                    r?   r<   zZarrTiffStore.__init__+  se   $ 'llDOO%i;;DO?&((%&L&L&LMMM 'T']]%c>** 	DJ!mDO&{& "j/0
8DD(#//0DJ"DOD 	A/:JA~~$/Q"6"6
%Z]#*2=KKMM)AT_-AI4?i 	 	
 	
 	
 <KK7D#$???~4<<  \	=#dj//A-- $D"f,,#)::.A#B#B  #'
1(>(>w(G(G#H#H %0-1C%D%DDK	"%0 "',$() )).s4:)?)?) ) ) )+
 
$ & &DK	"& Z],,W55F!*4:!6!6 "A "Av!?((11$2:/ADOi? -%^FF%_F2=+ . . . .,/ 0%- -. . .	3 	3u.../ 3>'(!&")&%"I"I!+E!2!2&*&1)U&C&C!$#'	 	3 3u.../  A*6x*@*@&@DOE"A "AH !&DZ]FHOO$$W--ELE .6o=) )!!"&00.26??73K3K.L.L*+%0%8%8DK	"%0#$"%feX_EE'.."&"-i"?"? #	 	& &DK	" ? =&28&<&<"<= =r@   c                z    t                                                       | j                                         dS )zClose store.N)r;   closer   clear)r=   r>   s    r?   r   zZarrTiffStore.close  s.    r@   FT)		groupnametemplatenamecompressorsr   _shape_axes_index_append_closeurl
str | Nonejsonfilestr | os.PathLike[Any] | TextIOr   r   r   *dict[COMPRESSION | int, str | None] | Noner   r   Sequence[int] | Noner   Sequence[str] | Noner   r   r   c      	           i ddddddddddd	d
ddddddddddddddddddddddddddddd |i n|}| j         D ]\}d!}|j        }|j        d"v r|j        j        r
d#||j        <   |j        |vrt          |j        d$|z             |j        dk    rt          |j        d$|z             |j        d%vrt          |j        d$|z             |j        d&vr5|j        d'vr,||j                 d#k    rt          d(|j         d$|z             | j	        s(|j
        s!|j        |j        z  rt          d)|z             | j	        r!|j        st          | j	        d$|z             |j        *t          |j                  dk    rt          d*|z             ^|d+}n|r|d,         d-k    r|d-z  }|                    d.d-          }|d+}n|r|d,         d-k    r|d-z  }t$          j        d/k    rd0nd1}| j         d2         j        j        j        |k    s7| j         d2         j        j         | j         d2         j        j        j        dk    rd}|g nt-          |          }|g nt-          |          }t          |          t          |          k    rt          d3          |	d+}nUt          |          t          |	          k    rt          d4          |	r$d5                    d6 |	D                       }|d5z  }i }|dk    r|
rt          d7          |d8}d|d9<   i |d:<   g |d;<   i }| j         d2         j        r_d2}| j         d2         j        D ]I}||j        |j        j        j        j        }||v r'| | }d<| d=||<   ||z   |d:         |<   |dz  }Jn;| j         d2         j        j        j        j        }| }d<| d=||<   ||z   |d:         |<   i x|d><   }n|}|
sI|r&t7          d?d@i                                          |dA<   | j                                        D ]\  }}dB|v r9|r7t?          j         |          }dC|v r||dC         z   |dC<   t7          |          }ndD|v rd-|v r(tC          |"                    d-          d2                   nd2}| j         |         j        }t?          j         |          }|r-||dE         z   |dE<   dgt          |          z  |dF         z   |dF<   ||j                 }|dk    r|j        }|d}n+d2dl#}|$                    |                                          }|j%        }|d}n+d2dl#}|$                    |                                          }tM          |j'        |j(        |j)        |j*                  \  } }!||||j        | |!dG|dH<   n|dk    r|j+        dIk    r	|dJdK|dH<   n|d#k    r|j        dLk    rytC          |j,        -                    dMd                    }"tC          |j,        -                    dNd@                    }#tC          |j,        -                    dOd@                    }$n|j        dPk    rd}"d@}#d@}$nd}"d@}#d@}$||j.        |"|#|$dQ|dH<   n	|dR|i|dH<   |||dS         dd         z   |dS<   |j/        dk    r]|j/        dTv rdU}%ndV}%|j/        dWk    rd}&n|j/        dXv rd@}&ndI}&|j(        dk    r|j+        dk    rdY}'nd,}'|%|'|&|dF         |dS         dZg|d[<   t7          |          }|                                |||z   <   ta          |d\          r|}(ntc          |d]d^_          }(|dk    rI|(2                    t?          j3        |d`          4                    dad          d2         daz              db})n8|
rdc})n3|(2                    t?          j3        |d`          ddY                    dc})| j                                        D ]\  }}dD|v rt?          j         |          }|dE         }*|dF         }+d-|v r|"                    d-          d2         d-z   nd+},tk          |*|+          D ]}-|,|-z   }| 6                    |          \  }}}.}/}0|r| j	        r|/|j7        d2         }/|j8        }0|/rO|0rM|j        j        j        }|dk    r	||         }n| | }|(2                    dd|) de| | df| dg|/ dh|0 di           |dk    r|(2                    dj           n|r|(2                    dk           ta          |d\          s|(9                                 dS dS )la  Write fsspec ReferenceFileSystem as JSON to file.

        Parameters:
            jsonfile:
                Name or open file handle of output JSON file.
            url:
                Remote location of TIFF file(s) without file name(s).
            groupname:
                Zarr group name.
            templatename:
                Version 1 URL template name. The default is 'u'.
            compressors:
                Mapping of :py:class:`COMPRESSION` codes to Numcodecs codec
                names.
            version:
                Version of fsspec file to write. The default is 0.
            _shape:
                Shape of file sequence (experimental).
            _axes:
                Axes of file sequence (experimental).
            _index
                Index of file in sequence (experimental).
            _append:
                If *True*, only write index keys and values (experimental).
            _close:
                If *True*, no more appends (experimental).

        Raises:
            ValueError:
                ZarrTiffStore cannot be represented as ReferenceFileSystem
                due to features that are not supported by Zarr, Numcodecs,
                or Imagecodecs:

                - compressors, such as CCITT
                - filters, such as bitorder reversal, packed integers
                - dtypes, such as float24, complex integers
                - JPEGTables in multi-page series
                - incomplete chunks, such as `imagelength % rowsperstrip != 0`

                Files containing incomplete tiles may fail at runtime.

        Notes:
            Parameters `_shape`,  `_axes`, `_index`, `_append`, and `_close`
            are an experimental API for joining the ReferenceFileSystems of
            multiple files of a TiffSequence.

        References:
            - `fsspec ReferenceFileSystem format
              <https://github.com/fsspec/kerchunk>`_

        r   N   zlibi  im  lzmai]     imagecodecs_lzw   imagecodecs_jpegiRX  imagecodecs_jpegxri  imagecodecs_packbitsi  imagecodecs_jpeg2ki  i    i  iG  imagecodecs_lercL  iu  imagecodecs_pngimagecodecs_jetrawimagecodecs_zstdimagecodecs_webpimagecodecs_jpegxl)iv  i  iP  iQ  iR  iB  z0 not supported by the fsspec ReferenceFileSystem>         imagecodecs_eerz is   r   r   r         r          @      >   r   r  r  zBitsPerSample zincomplete chunks arez"JPEGTables in multi-page files arer{   rz   \big<>r   zlen(_shape) != len(_axes)zlen(_shape) != len(_index).c              3  4   K   | ]}t          |          V  d S rM   r   r   s     r?   	<genexpr>z-ZarrTiffStore.write_fsspec.<locals>.<genexpr>|  s(      44SVV444444r@   zcannot append to version 1ur   	templatesgen{{}}refsr   r   r   r   r   r   r   r   )idtablesheaderbitspersamplecolorspace_jpegcolorspace_datar      T)r#  hasalphar  i  i  i  r  )r#  r   rlebitshorzbitsvertbitsr#  r   >   M  r   r  imagecodecs_deltaimagecodecs_floatpredr   >   N  r  )r#  axisdistr   r   r   writewutf-8encodingindent}"   ,
"": ["z", z, ]
 }
}
}):r   r   compressionr   is_eer
ValueError	fillordersampleformatr&  r1   is_tiledimagelengthrowsperstripis_final
jpegtablesr   pagesreplacesys	byteorderr   itemsizert   joinis_multifiler   r   r   r   r.   itemsjsonloadsr0   r~   base64	b64encode
jpegheaderr   photometricplanarconfigextrasamplesis_jfifsamplesperpixeltagsvalueofr   	predictorhasattropenr5  dumpsrsplit_ndindex
_parse_keydataoffsetsnbytesr   )1r=   r   r   r   r   r   r   r   r   r   r   r   r   errormsgr   rR  indexr"  r  r   pagefnamerP   refzarrrY   r   codec_idrN  r$  rY  r[  r%  r'  r(  r+  r,  r-  	filter_idr4  r3  r   r;  r   r   levelstr
chunkindex_offset	bytecounts1                                                    r?   write_fsspeczZarrTiffStore.write_fsspec  s   F
t
v
 6
 6	

 6
  
 !
 '
 )
 '
 '
 '
 %
 '
 %
  %!
" $#
$ ('%%''/
 
 
0 !(rrk1
6 j /	 /	FIHH$(===O* > 5FH01#;66 H$8!?!?!?(!JKKK!Q&& H$6!=!=!=!HIII$L88 H$9!@!@!@8!KLLL&  (    459JJJ @X%;@@@8K   OE )E (8+@@E
 !!88!CDDD Gx'8 G DO!:!:!:X!EFFF".3v|3D3Dq3H3H 88C   ;CC 	SW^^3JCkk$$$II 	9R=C//I-0]e-C-Ccc	JqM")3y@@z!}%+3z!}%+499I ~4<<mev;;#e**$$8999>EE[[CKK''9::: 	HH44V44444ESLE!a<< ? !=>>>#"DO "DDKIz!}) 5 JqM/ 	 	D|t}'<  M0;@E	)) ).1..C'7c'7'7'7Ie$-05[D%c*FAA	 
1.5@E%'#3##3#3#3	% ),u[!#&%''DL77G u	: N%0-1C%D%D%K%K%M%M	""k//11 p: p:
U### Ju--E*e33!E*=$>> 12 (..EE#%%69SjjC		#q 1222aE#z%09H Ju--E N)/%.)@g+,#F*;eHo*Mh*8+?@H#555%-%8
%-%)FF)MMM%+%5%5j%A%A%H%H%J%JF%-%8
%-%)FF)MMM%+%5%5j%A%A%H%H%J%JF 3$0$1$1$,	 ++ #+&,&,-5-C/>/>/ /l++ !$666$499 #+(,/ /l++ "%666#/588&)(-*?*?q*I*I&J&JG'*8=+@+@+J+J'K'KH'*8=+@+@+J+J'K'KHH%1U::&'G'(H'(HH&'G'(H'(H"*%-_'.(0(0/ /l++ "-/3X.>l+ ,)2U7^ABB5G)Gg)A-- $-1BBB(;II(?I#-22#$DD%/>AA#$DD#$D$1Q66 ( 81 < <#%DD#%D '0(,(,).x).w ,i( (..E+0<<>>	C(( 8W%% 	7BBhg666Ba<<HHTZQ///66tQ??BTIJJJFF 	FFHHTZQ///4555F +++-- 	 	JCC
5))gx8;s

CIIcNN1-33"*5&"9"9  J"Z/C;???3;O;O8HdAvy 4 4FN!%!1!!4$,O	 	) 	 ( : ?"a<<$-e$4EE'*OEOOEB& B B9 Bc B B!&B B+1B B5>B B B   a<<HHY 	HHUOOOx)) 	HHJJJJJ	 	r@   rP   rX   rG   r%   rQ   ByteRequest | NoneBuffer | Nonec                  K   |t          d|d          || j        v r%|j                            | j        |                   S |dk    s*|dd         dk    s|dd         dk    s|dd         d	k    rdS |                     |          \  }}}}}||d
k    s|d
k    rdS |j        j        }	| j        r||J t          |j        d
||f|f          }| j	        
                    |	           |                    | j	        j        | j        | j                  }
| j	                            |	           | j        |                     |
          }
|                    |
                    d                              d                    S ||J | j	                            |	||          }ddi}|j        
|j        |d<   |j        
|j        |d<   |J |j         | j        dk    r t/          j        |j        ||fi | d{V }n |j        ||fi |}|d
         }
~|
J | j        |                     |
          }
| j        r|j        }n|j        }|
j        t9          |          k    r&t;          |
j         dt9          |                     |                    |
                    d                              d                    S )!Return value associated with key.Nbyte_range= not supported	zarr.json
.zmetadatar   r   r   )rm  r   rj  databytecounts)r   r   r   r  B	_fullsizeTrN  r[  r   z != )r\   r.   buffer
from_bytesri  r   r   r1   r   r   re  asarrayr   r   r   r   r   reshapeviewreadrN  r[  r   asyncio	to_threadr   r   r   r   RuntimeError)r=   rP   rG   rQ   r   rn  rt  rv  rw  r   chunkchunk_bytes
decodeargsdecodedr   s                  r?   rN   zZarrTiffStore.getG  sn      !%&F&F&F&FGGG$+#..t{3/?@@@ ;344yL((233x9$$233x9$$ 48<8L8L5$
FI<6Q;;)q..4[#? 	! !,,, K%!'	$-<   O  $$$LL_)++ !  E
 O!!"%%%*..##b!!&&s++   !i&;&;&;o**2vyAA&14%8
?&'+J|$*'/':J|$%%%a#-j <F       GG &hok:LLLLG
   ?&OOE**E? 	%^FF_F:((%*CC'&//CCDDDMM"""3''
 
 	
r@   c                   K   || j         v rdS t          |t                    sJ 	 |                     |          \  }}}}}n# t          t
          f$ r Y dS w xY w| j        r|dS |duo|duo|duo|dk    o|dk    S )Return if key exists in store.TFNr   )r.   rD   rX   ri  KeyError
IndexErrorr1   )r=   rP   ru  rn  rv  rw  s         r?   existszZarrTiffStore.exists  s       $+4#s#####	,0OOC,@,@)AtQ		*% 	 	 	55	? 	v~4 d"% 
 A	
s   A AArY   r$   c                  K   | j         rt          d          || j        v s0|dk    s*|dd         dk    s|dd         dk    s|dd         dk    rdS |                     |          \  }}}}}|||d	k    s||d	k    rdS |                                }|t          |          k     r
|d|         }| j                            |j        j	        ||           dS )
r[   zZarrTiffStore is read-onlyr  r  Nr  r  r   r   r   )
r,   rf   r.   ri  to_bytesr   r   r5  r   r   )	r=   rP   rY   r   rn  rt  rv  rw  datas	            r?   r`   zZarrTiffStore.set  s     ? 	@!">??? 4;k!!344yL((233x9$$233x9$$ 48<8L8L5$
FIL~{{ A~~F~~s4yy  

#Ddk4fdCCCCCr@   Ptuple[TiffPage, TiffPage | TiffFrame | None, int | None, int | None, int | None]c               <   | j         r]	 |                    d          \  }}| j        t          |                   }n6# t          t
          f$ r}t          |          |d}~ww xY w| j        d         }|j        }|                     ||          \  }}|j	        |d         }||j
        |j        |d|ddfS ||j        z  |j
        j        z  }		 |	|j        |         z  }	n"# t
          $ r}t          |          |d}~ww xY w| j        r |j        |j
        j        z  }
|j        |||	|
fS n| j        rH| j        j        5  ||         }ddd           n# 1 swxY w Y   ||j        |ddddfS |j        |dddfS | j        j        5  ||         }ddd           n# 1 swxY w Y   ||j        |d|ddfS 	 |j        |         }	n# t
          $ r |j        ||ddfcY S w xY w	 |j        |         }
n"# t
          $ r}t          |          |d}~ww xY w|j        |||	|
fS )ztReturn keyframe, page, index, offset, and bytecount from key.

        Raise KeyError if key is not valid.

        rz   Nr   )r   r~   r   r0   rG  r  r  r   _indices
dataoffsetr   r   rS  rj  r1   r   r   r  )r=   rP   r   r   excr   	pageindexrt  rn  rv  rw  s              r?   ri  zZarrTiffStore._parse_key  s+     	#- YYs^^
sCJJ/
+ - - -smm,- Z]F? $c6 : :	:(!9D|tz1T]5Jz1a77*TZ-@@F-$*:66 - - -smm,- J I
(;;	}dJ	IIJ _ 	=% ) )i() ) ) ) ) ) ) ) ) ) ) ) ) ) )|t}4tQ11=$dD88% ) )i() ) ) ) ) ) ) ) ) ) ) ) ) ) )|t}4z1a77=)*5 = = = }dJ1<<<<=	)+J7II 	) 	) 	)3--S(	)}dJ	AAs{   2< A"AA"C! !
D +C;;D >	EEE	FF"F7G GG"G0 0
H:H

Hr   r   tuple[int, int]c                  |j         }|                    | j                  }	 d |                    d          D             }n"# t          $ r}t          |          |d}~ww xY wt          |          t          |          k    sJ | j        rdt          |j                  z  }n|j	        }d}t          |ddd                   D ]a\  }	}
||
z  }||j        k    rLt          |          |	z
  dz
  }	|d|	         }||	d         }|d|	         }t          ||	d                   } nbt          t          |          t          |j                  k    rt          |          }nt          |          dz
  }	t          |j                  dz
  }	 ||	         |j        |         k    r||         ||	<   |	dz  }	|dz  }n!||	         dk    r|	dz  }	nt          d          |	d	k     s|d	k     rn\t          |          t          |          k    sJ t          |          d	k    r#t          t!          j        ||                    }nd	}t          |          d	k    r#t          t!          j        ||                    }nd	}||fS )
z5Return page and strile indices from Zarr chunk index.c                ,    g | ]}t          |          S rS   r0   r   s     r?   rR   z*ZarrTiffStore._indices.<locals>.<listcomp>  s    666!s1vv666r@   r  Nr   r   r  Tzshape does not match page shaper   )r   r   r   r~   rG  r  r   r1   r   chunkedr   r   rt   r  r   r0   numpyravel_multi_index)r=   rP   r   r   r   indicesr  r  pr   sframes_indicesstrile_indicesframes_chunkedstrile_chunkedr   
frameindexstrileindexs                     r?   r  zZarrTiffStore._indices  s   ?  //	)66syy~~666GG 	) 	) 	)3--S(	)7||s5zz))))? 	'S000GG&GeDDbDk** 
	 
	DAqFAHM!!LL1$q(!(!!(!&rr!%eABBi " ~#hn"5"555!']]NN N##a'AHN##a'A
!!$q(999(/
N1%FAFAA#A&!++FAA&'HIIIq55AEE
 >**gg.>.>>>>>~""'GG JJ J~""'GG KK K;&&s   A 
A"AA")r   r   r   r   r4   r7   r3   r6   r   r   r   r   r   r   r   r   r   r   r   r   r5   r   r   r   r   r    r8   r9   )r8   r9   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r+   r   r+   r8   r9   rM   rP   rX   rG   r%   rQ   ry  r8   rz  rP   rX   r8   r+   r   )rP   rX   r8   r  )rP   rX   r   r   r8   r  )r   r   r   r   r   r<   r   rx  rN   r  r`   ri  r  r   r   s   @r?   r   r      s        , ,\  ==== !26(,(,#'59#!%!%!%!%^= ^= ^= ^= ^= ^= ^= ^=@            !%#'BF"'+&*'+u u u u u uv *.	W
 W
 W
 W
 W
r
 
 
 
(D D D D:8B 8B 8B 8Bt7' 7' 7' 7' 7' 7' 7' 7'r@   r   c            
           e Zd ZU dZded<   	 ded<   ded<   ded	<   d
ed<   ded<   ded<   ded<   dddddddddd	dE fd-ZdFd/Z	 dGdHd5Zdddddd6dd7dIdDZ xZ	S )Jr   a  Zarr 3 store interface to image array in FileSequence.

    Parameters:
        filesequence:
            FileSequence instance to wrap as Zarr store.
            Files in containers are not supported.
        fillvalue:
            Value to use for missing chunks. The default is 0.
        chunkmode:
            Currently only one chunk per file is supported.
        chunkshape:
            Shape of chunk in each file.
            Must match ``FileSequence.imread(file, **imreadargs).shape``.
        chunkdtype:
            Data type of chunk in each file.
            Must match ``FileSequence.imread(file, **imreadargs).dtype``.
        axestiled:
            Axes to be tiled. Map stacked sequence axis to chunk axis.
        zattrs:
            Additional attributes to store in `.zattrs`.
        ioworkers:
            If not 1, asynchronously run `imread` function in separate thread.
            If enabled, internal threading for the `imread` function
            should be disabled.
        read_only:
            Passed to zarr `Store` constructor.
        imreadargs:
            Arguments passed to :py:attr:`FileSequence.imread`.
        **kwargs:
            Arguments passed to :py:attr:`FileSequence.imread`in addition
            to `imreadargs`.

    Notes:
        If `chunkshape` or `chunkdtype` are *None* (default), their values
        are determined by reading the first file with
        ``FileSequence.imread(arg.files[0], **imreadargs)``.

    zCallable[..., NDArray[Any]]r   zdict[tuple[int, ...], str]_lookuptuple[int, ...]r   numpy.dtype[Any]_dtyper   _tiledrX   _commonpathr0   
_ioworkersr-   _kwargsNr   T)	r3   r4   
chunkshape
chunkdtype	axestiledr   	ioworkers
imreadargsr5   filesequencer   r3   r6   r4   r7   r  r   r  DTypeLike | Noner  1dict[int, int] | Sequence[tuple[int, int]] | Noner   r   r  r   r  r5   r+   r   r    r8   r9   c      	           t                                          |||
           | j        dvrt          d| j                  t	          |t
                    st          d          |j        rt          d          |	||	z  }|dn|| _	        || _
        |j        | _        |                                | _        ||- |j        |d         fi |}|j        | _        |j        | _        n/t'          |          | _        t)          j        |          | _        d }t+          |j        | j        |          | _        t/          t1          | j                            |j                  |                    | _        |i nt/          |          }t7          |          | j        d	<   t7          d
| j        j        | j        j        t=          | j                  d t?          || j                  dd d          | j        d<   d S )Nr2   >   r   r   zinvalid chunkmode znot a FileSequencez#cannot open container as Zarr storer   r   )r  r   r   r   r   r   ) r;   r<   r1   rG  rD   r   	TypeError
_containerr\   r  r  r   _imread
commonpathr  r   r   r   r  tupler  r   r  r   r   r  r  r   r.   r   r   r   )r=   r  r3   r4   r  r  r  r   r  r  r5   r   r  r>   s                r?   r<   zZarrFileSequenceStore.__init__x  s     	9	 	 	
 	
 	
 ?&((E$/EEFFF,55 	20111" 	M%&KLLL !j F(0!!i#*'2244!3'L'QBB6BBE ;DL+DKK ,,DL+j11DKE#	
 
 
 ##L$899<HH
 
 ~4<<
 "-V!4!4I!, *+,#DK00"))T[AA	 	"
 "
Ir@   rP   c                   K   || j         v rdS t          |t                    sJ 	 t          d |                    d          D                       }n# t
          $ r Y dS w xY w|| j        v S )r  Tc              3  4   K   | ]}t          |          V  d S rM   r  r   s     r?   r  z/ZarrFileSequenceStore.exists.<locals>.<genexpr>  s(      ;;qCFF;;;;;;r@   r  F)r.   rD   rX   r  r~   	Exceptionr  )r=   rP   r  s      r?   r  zZarrFileSequenceStore.exists  s       $+4#s#####	;;CIIcNN;;;;;GG 	 	 	55	$,&&s   ,A 
A! A!rG   r%   rQ   ry  rz  c                  K   |t          d|d          || j        v r%|j                            | j        |                   S |dk    s*|dd         dk    s|dd         dk    s|dd         d	k    rdS t	          d
 |                    d          D                       }| j                            |d          }|dS | j        dk    r$t          j
        | j        |fi | j         d{V }n | j        |fi | j        }|                    |                    d                              d                    S )r|  Nr}  r~  r  r  r  r  r   r   c              3  4   K   | ]}t          |          V  d S rM   r  r   s     r?   r  z,ZarrFileSequenceStore.get.<locals>.<genexpr>  s(      771A777777r@   r  r   r  r  )r\   r.   r  r  r  r~   r  rN   r  r  r  r  r  r  r  )r=   rP   rG   rQ   r  filenamer  s          r?   rN   zZarrFileSequenceStore.get  s      !%&F&F&F&FGGG$+#..t{3/?@@@ ;344yL((233x9$$233x9$$ 477		#77777<##GT224?a!+h *.,       EE !DL::T\::EMM"""3''
 
 	
r@   F)quoter   r   rq  r   r   r   r   r   r   r   r  r   r   r   rq  r   r   r   c                 ddl m}
 | j                                        }|n| j        t
          u rd}nd| j        j        v r| j        j        dk    s	d| j        vrt          d          |	                    d          }t          |t          t          f          r|d         }t          |          r |j                            d	          d         }i d
dddddddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+i|         }nt          d          |d,}n|r|d-         d.k    r|d.z  }|d,}n|r|d-         d.k    r|d.z  }i }|d/k    r4|rt          d0          |d1}d/|d2<   ||i|d3<   g |d4<   i x|d5<   }d6| d7}n|}|r(|s&t          d8d9i                                          |d:<   | j                                        D ]O\  }}d;|v r,t'          j        |          }d<|i||d=<   t          |          }|                                |||z   <   Pt+          |d>          r|}nt-          |d?d@A          }|d/k    rI|                    t'          j        |d/B                              dCd/          d         dCz              dD}n~|rI|                    dE           |                    t'          j        |d/B          d9dF                    dG}n3|                    t'          j        |d/B          ddF                    dG}t5          | j                  }| j                                        D ]\  }}d;|v rt'          j        |          }t9          | j                                        dH I          D ]\  }}||d                             dJd.          }||r |
|          }|d         d.k    r
|d/d         }dK                    dL |D                       }|                    dE| dM| | dN| | dO	           |d/k    r|                    dP           n|	r|                    dQ           t+          |d>          s|                                  dS dS )Rat  Write fsspec ReferenceFileSystem as JSON to file.

        Parameters:
            jsonfile:
                Name or open file handle of output JSON file.
            url:
                Remote location of TIFF file(s) without file name(s).
            quote:
                Quote file names, that is, replace ' ' with '%20'.
                The default is True.
            groupname:
                Zarr group name.
            templatename:
                Version 1 URL template name. The default is 'u'.
            codec_id:
                Name of Numcodecs codec to decode files or chunks.
            version:
                Version of fsspec file to write. The default is 0.
            _append, _close:
                Experimental API.

        References:
            - `fsspec ReferenceFileSystem format
              <https://github.com/fsspec/kerchunk>`_

        r   )r  Ntifffileimagecodecsr   codeczcannot determine codec_idru  apngimagecodecs_apngavifimagecodecs_avifgifimagecodecs_gifheifimagecodecs_heifjpegr   jpeg8jpeg12jpeg2kr  jpeglsimagecodecs_jpeglsjpegxlr	  jpegxrr   ljpegimagecodecs_ljpeglercr  pngr  qoiimagecodecs_qoitiffimagecodecs_tiffwebpr  zfpimagecodecs_zfpr{   r  rz   r   z cannot append to version 1 filesr  r   r  r  r"  r   r!  r   r   r   r   r#  r   r5  r6  r7  r8  r:  r<  r=  r?  r2  r>  c                    | d         S )Nr   rS   )xs    r?   <lambda>z4ZarrFileSequenceStore.write_fsspec.<locals>.<lambda>  s
    ! r@   )rP   r  r  c              3  4   K   | ]}t          |          V  d S rM   r   r   s     r?   r  z5ZarrFileSequenceStore.write_fsspec.<locals>.<genexpr>  s(      '>'>1A'>'>'>'>'>'>r@   r@  rA  z"]rC  rD  )!urllib.parser  r  copyr  r   r   r   rG  r   rD   rt   r  callabler~   r   r   r.   rV  rW  rX  rd  re  r5  rf  rg  r   r  sortedr  rP  rT  r   )r=   r   r   r  r   r   rq  r   r   r   quote_r   r  r"  rp  rP   rY   r   r;  ru   rm  r  indexstrs                          r?   rx  z"ZarrFileSequenceStore.write_fsspec  s   P 	100000""$$\V##!HHdl555%11$,.. !<===JJw''E%$// !a 5,,S11!4** ( *	
 * + , . . . . , * (  (!" *#$ *%& (' ( )HH. 8999;CC 	SW^^3JCII 	9R=C//I!a<< E !CDDD#"DO!-s 3DDK%''DL7++++CCG 	JW 	J!,mQ-?!@!@!G!G!I!IGI+++-- 	6 	6JCC
5))'+X&@&@l##E**',||~~GIO$$ 8W%% 	7BBhg666Ba<<HHTZQ///66tQ??BTIJJJFF 	HHUOOOHHTZQ///"5666FFHHTZQ///4555FT%&&+++-- 	 	JCC
5))'-L&&((nn( ( (  OE8  (088sCCH}}#)6(#3#3{c))#+ABB<"xx'>'>'>'>'>>>HHH/f / /y /( / / /"*/ / /   
 a<<HHY 	HHUOOOx)) 	HHJJJJJ	 	r@   )r  r   r3   r6   r4   r7   r  r   r  r  r  r  r   r   r  r   r  r   r5   r+   r   r    r8   r9   r  rM   r  )r   r   r   r   r  r   r   r   r   r   rq  r   r   r   r   r+   r   r+   r8   r9   )
r   r   r   r   r   r<   r  rN   rx  r   r   s   @r?   r   r   E  sN        % %N ('''8''''OOO )-26+/'+GK(, !,0H
 H
 H
 H
 H
 H
 H
 H
T
' 
' 
' 
'  *.	"
 "
 "
 "
 "
T " $#'#"a a a a a a a a a ar@   r   T)
groupindexr   outstore	selectionr'   r  r   r   r+   r  r)   r8   NDArray[Any]c                 ddl }ddlm}  |j        | dd          }	 t	          ||j                  r|d}||         }n|}|T |||j        t          |j                  	          j        }	t          j
        t          ||	|j                            }
nd}
|                    ||

          }|r|                                  n# |r|                                  w w xY w|S )a  Return selection from Zarr store.

    Parameters:
        store:
            ZarrStore instance to read selection from.
        selection:
            Subset of image to be extracted and returned.
            Refer to the Zarr documentation for valid selections.
        groupindex:
            Index of array if store is Zarr group.
        close:
            Close store before returning.
        out:
            Specifies how image array is returned.
            By default, create a new array.
            If a *numpy.ndarray*, a writable array to which the images
            are copied.
            If *'memmap'*, create a memory-mapped array in a temporary
            file.
            If a *string* or *open file*, the file used to create a
            memory-mapped array.

    r   N)BasicIndexerrr   )moder   0)chunk_shape)r   
chunk_grid)r  )zarrzarr.core.indexingr  re  rD   Groupr   r   r   r
   from_numpy_arrayr   r   get_basic_selectionr   )r  r  r  r   r  r  r  zzarrayr   ndbufferresults               r?   zarr_selectionr    s,   @ KKK////// 		%cq111Aa$$ 	! 
z]FFF? Ll+FFF   	 
  0c5&,77 HH H++I8+DD 	KKMMM  	KKMMMM	Ms   BC	 	C"r   r  r   r"   r3   r6   c               x    ||dk    rt          j        | |          S t          j        | |          }||dd<   |S )zReturn empty chunk.Nr   )r  zerosempty)r   r   r3   r  s       r?   _empty_chunkr    sG     INN{5%(((Ku%%EE!!!HLr@   r  rX   c               l    | j         dk    rd}ndddt          j                 }|| j        dd         z   S )z.Return dtype as string with native byte order.r   |r  r  )r  littleN)rS  rQ  rR  rX   )r   rR  s     r?   r   r     s?    ~		3//>	uy}$$r@   objr    bytesc               Z    t          j        | dddd                              d          S )z*Serialize object to JSON formatted string.r   T),z: )r;  	sort_keysensure_ascii
separatorsascii)rW  rf  encode)r  s    r?   r   r     s7    :   fWoor@   rY   c               .   | | S |j         dk    rt          |           S |j         dv rt          |           S |j         dk    rQt          j        |           rdS t          j        |           rdS t          j        |           rdS t          |           S |j         dk    rwt          j        | |          } t          | j
        |                                j
        j                  t          | j        |                                j        j                  fS | S )	z+Return value which is serializable to JSON.NbuifNaNInfinityz	-Infinityc)kindr+   r0   r  isnanisposinfisneginffloatarrayr   realrE   r   imag)rY   r   s     r?   r   r     s   }zSE{{zT5zzzS;u 	5>%   	:>%   	;U||zSE5))
EJJLL$5$;<<
EJJLL$5$;<<
 	
 Lr@   r   Iterator[str]c             #    K   t          |           t          |          k    sJ t          d t          | |          D                       }t          j        |          D ]#}d                    d |D                       V  $dS )z-Return iterator over all chunk index strings.c              3  :   K   | ]\  }}||z  ||z  rd ndz   V  dS )r   r   NrS   )rO   r   r   s      r?   r  z_ndindex.<locals>.<genexpr>  sM        )-AQq1u#!!!$     r@   r  c              3  4   K   | ]}t          |          V  d S rM   r   )rO   rm  s     r?   r  z_ndindex.<locals>.<genexpr>  s(      77es5zz777777r@   N)r   r  r   r  ndindexrT  )r   r   r  r  s       r?   rh  rh    s       u::V$$$$  14UF1C1C    G =)) 8 8hh77w7777777778 8r@   r   r   c                R    | j         dk    o| j        dk    o| j        dv o| j        dv S )z#Return True if chunks are writable.r   r  r  )rE  rH  rI  r&  )r   s    r?   r   r     sG     	! 	;!#	;!\1	; "&::		r@   r   tuple[int, int, int, int, int]c               F   t          |          }|dk    rdS d|v rd|z  S |d         dk    rdnd}t          |d|z             }t          |           }|d|z   k    r2|d|z   k    r)|d         dk    r|| d         || d         k    r| dz   } |t          |           k     rOt          |           D ]\  }}|dk    r n| |d         } |t          |           k     rt          d	|d
|           t	          dg|t          |           z
  z  t          |           z             S )z(Return chunks with same length as shape.r   rS   r  r   r   r   r  Nzshape=z is shorter than chunks=)r   minr   rG  r  rt   )r   r   r   ndimdr   nr   s           r?   r   r   +  s[    u::DqyyrEzzd{AY!^^AD!a%AFA	QU

QJJ"INN1"##J&!+%% $c&kk (( 	 	GAtaxx #f++FFF6FFGGG!s6{{*+d6ll:;;;r@   )r  r   r  r'   r  r   r   r+   r  r)   r8   r  )r   r  r   r"   r3   r6   r8   r  )r   r  r8   rX   )r  r    r8   r  )rY   r    r   r  r8   r    )r   r  r   r  r8   r0  )r   r   r8   r+   )r   r  r   r  r   r6  r8   r  )Fr   
__future__r   __all__r  rW  osrQ  	threadingtypingr   r  r  zarr.abc.storer   r	   zarr.core.buffer.cpur
   zarr.core.chunk_gridsr   ImportErrorr  rG  __version__r  r   r   r   r   r   r   r   r   r   r   r   r   r   r   collections.abcr   r   r   r   r   r    r!   numpy.typingr"   r#   zarr.core.bufferr$   r%   zarr.core.commonr&   r  r'   r(   r)   r   r   r   r  r  r   r   r   rh  r   r   rS   r@   r?   <module>rJ     s  @ , + " " " " " "
A
A
A   				 



                  O11111111------6666666 O O O
*DT-DDD
E
E3NO                               "  0              #"""""""////////88888888******111111////////L, L, L, L, L, L, L, L,tN' N' N' N' N'I N' N' N'bN N N N NI N N Nl
 "< < < < < <~   % % % %      2	8 	8 	8 	8    <  <  <  <  <  <s   A A$
AA$