a
    
d>                     @   sN  d dl Z d dl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	m
Z
 d dlZzd dlZW n ey   e
s~d dlZY n0 ddlmZ ddlmZ ddlmZmZmZ ddlmZmZmZ ed	ZG d
d deZdd Z dd Z!dd Z"G dd dej#j$Z%G dd dej#j&Z'dd Z(G dd dej#j)Z*G dd deZ+dS )    N)	lru_cache)TYPE_CHECKING   )AsyncFileSystem)_DEFAULT_CALLBACK)
filesystemopensplit_protocol)
isfilelikemerge_offset_rangesother_pathszfsspec.referencec                       s$   e Zd Z fddZdd Z  ZS )ReferenceNotReachablec                    s   t  j|  || _|| _d S N)super__init__	referencetarget)selfr   r   args	__class__ i/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/fsspec/implementations/reference.pyr      s    zReferenceNotReachable.__init__c                 C   s   d| j  d| j S )NzReference "z" failed to fetch target )r   r   r   r   r   r   __str__!   s    zReferenceNotReachable.__str__)__name__
__module____qualname__r   r   __classcell__r   r   r   r   r      s   r   c                 C   s   t |  d S Nr   )listvalues)dr   r   r   _first%   s    r#   c                 C   s<   | | }t|ttfr8|d r0t|d d S |d S d S r   )get
isinstancer    tupler	   )path
referencesrefr   r   r   _prot_in_references)   s    
r*   c                 C   sH   t | trt| || giS i }| D ] }t||}||g | q"|S r   )r%   strr*   
setdefaultappend)pathsr(   outr'   protocolr   r   r   _protocol_groups/   s    

r1   c                   @   s   e Zd Zdd ZdS )RefsValuesViewc                 c   s   | j j D ]}t| V  q| j j E d H  | j  D ]@}| j |}t	|dkrl| j |d  V  q>| j 
|E d H  q>d S )Nr   /0)_mapping	zmetadatar!   jsondumpsencode_itemslistdir_get_chunk_sizeslen_generate_all_records)r   valfieldchunk_sizesr   r   r   __iter__:   s    zRefsValuesView.__iter__Nr   r   r   rA   r   r   r   r   r2   9   s   r2   c                   @   s   e Zd Zdd ZdS )RefsItemsViewc                 C   s   t | j | j S r   )zipr4   keysr!   r   r   r   r   rA   G   s    zRefsItemsView.__iter__NrB   r   r   r   r   rC   F   s   rC   c                 C   sH   d}d}t | d d d |d d d D ]\}}||| 7 }||9 }q&|S )Nr      )rD   )idxsizesr>   Zmultisr   r   r   ravel_multi_indexK   s    &
rL   c                   @   s   e Zd ZdZedd Zedd Zd9d	d
Zedd Z	d:ddZ
d;ddZdd Zeddd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zed$d%d& Zd'd( Zed)d* Zd+d, Zd<d-d.Zd=d/d0Zd1d2 Zd3d4 Zd5d6 Zd7d8 ZdS )>LazyReferenceMapperzVInterface to read parquet store as if it were a standard kerchunk
    references dict.c                 C   s   dd l }|S r   )numpy)r   npr   r   r   rO   Y   s    zLazyReferenceMapper.npc                 C   s   dd l }|S r   )pandas)r   pdr   r   r   rQ   _   s    zLazyReferenceMapper.pdN   
   c           	         s   | _ i  _i  _d _|du r*tdn| _ jd j dgd}|	  jd< W d   n1 sn0    Y  t
 jd }|d  _|d  _ j d  _|p j  _| _t|d	 fd
d}| _dS )a  
        Parameters
        ----------
        root : str
            Root of parquet store
        fs : fsspec.AbstractFileSystem
            fsspec filesystem object, default is local filesystem.
        cache_size : int
            Maximum size of LRU cache, where cache_size*record_size denotes
            the total number of references that can be loaded in memory at once.
        Nfile/
.zmetadatarbrecord_sizemetadataz/{field}/refs.{record}.parq)maxsizec                    sd   j j| |d}j| }jj|dd W d   n1 sB0    Y   fdd jD }|S )zcached parquet file loader)r?   recordfastparquet)engineNc                    s   i | ]}| | j qS r   )r!   .0cdfr   r   
<dictcomp>       zCLazyReferenceMapper.__init__.<locals>.open_refs.<locals>.<dictcomp>)urlformatfsr   rQ   Zread_parquetcolumns)r?   r[   r'   frefsr   ra   r   	open_refs   s
    .z/LazyReferenceMapper.__init__.<locals>.open_refs)rootr@   r9   dirsfsspecr   rg   r   joinreadr6   loadsrX   r5   re   out_root
cat_threshr   rk   )	r   rl   rg   rr   
cache_sizeZcategorical_thresholdri   metrk   r   r   r   r   e   s     ,


zLazyReferenceMapper.__init__c                 K   s<   i | d}| d|dgt|  t||fi |S )NrY   rX   rU   rV   )pipero   r6   r7   r8   rM   )rX   rl   rg   kwargsru   r   r   r   create   s    
 zLazyReferenceMapper.createTc                 C   sN   | j du r2dd | jD }ttdd |D | _ | j }|rJdd |D }|S )zList top-level directoriesNc                 S   s   g | ]}| d dd qS )rU   rF   r   )splitr_   pr   r   r   
<listcomp>   rd   z/LazyReferenceMapper.listdir.<locals>.<listcomp>c                 s   s    | ]}|r| d s|V  qdS ).N
startswithr{   r   r   r   	<genexpr>   rd   z.LazyReferenceMapper.listdir.<locals>.<genexpr>c                 S   s   g | ]}t j|qS r   )osr'   basename)r_   r'   r   r   r   r}      rd   )rm   r5   setsorted)r   r   rm   listingr   r   r   r:      s    
zLazyReferenceMapper.listdir c                    s4   s  }tdgdd jD  dd jD  }|du rP|| t|S dd |D }fdd|D }t|| dd	 d
S  dd}t|dkrtd|d }t fddjD  fddjD  }fdd|D }	|}	|du rt
|t
|	 S |}
dd t|	|
D }|| S )zShortcut file listingsrV   c                 S   s   g | ]}d |vr|qS rU   r   r_   namer   r   r   r}      rd   z*LazyReferenceMapper.ls.<locals>.<listcomp>c                 S   s   g | ]}d |vr|qS r   r   r   r   r   r   r}      rd   Fc                 S   s   g | ]}|d ddqS )	directoryr   r   typesizer   r   r   r   r   r}      s   c              	      s<   g | ]4}|d t | jv r(t j| n j| dqS rT   r   r<   r5   r6   r7   r9   r   r   r   r   r}      s   
c                 S   s   | d S )Nr   r   )rK   r   r   r   <lambda>   rd   z(LazyReferenceMapper.ls.<locals>.<lambda>keyrU   rF   z(Cannot list within directories right nowr   c                    s    g | ]}|   d r|qS r   r   r   r'   r   r   r}      rd   c                    s    g | ]}|   d r|qS r   r   r   r   r   r   r}      rd   c              	      s<   g | ]4}|d t | jv r(t j| n j| dqS r   r   r   r   r   r   r}      s   
c                 S   s(   g | ] \}}|d  r|d|d dqS )r   rT   rG   r   r   )r_   r   Zrecr   r   r   r}      s   )r:   r   r5   r9   updater   rz   r<   FileNotFoundError_keys_in_fieldr    r=   rD   )r   r'   detaildirnamesothersZdirinfoZfileinfopartsr?   rE   ZrecsZrecinfor   r'   r   r   ls   sN    







zLazyReferenceMapper.lsc              
      s`  || j v r| j | S || jv r2t| j|  S d|vsD| |rLt||d\}}| |\}}}| j 	||fi 	|d}|du rtn|r|S z.| |\}}|dkrW dS | 
|| W n  tttfy   t|Y n0 g d} fdd|D }	|	d	 }
|
dur|
S |	d du r2td
|	dd ddgkrT|	dd S |	dd S )zfGet the reference for one key

        Returns bytes, one-element list or three-element list.
        rU   FNr   rd   r'   offsetr   rawc                    s$   g | ]}| v r |  nd qS r   r   r^   rj   rir   r   r}      rd   z5LazyReferenceMapper._load_one_key.<locals>.<listcomp>rG   zThis reference has been deletedrF      )r9   r5   r6   r7   r8   _is_metaKeyErrorrz   _key_to_recordr$   rk   
ValueError	TypeErrorr   )r   r   r?   Zsub_keyr[   _maybe
chunk_sizerh   Z	selectionr   r   r   r   _load_one_key   s<    



z!LazyReferenceMapper._load_one_keyi   c           	      C   sh   | d\}}| |}t|dkr(dS dd | dD }t||}|| j }|| j }||t|fS )z3Details needed to construct a reference for one keyrU   r   )r   r   r   c                 S   s   g | ]}t |qS r   )intr^   r   r   r   r}     rd   z6LazyReferenceMapper._key_to_record.<locals>.<listcomp>r~   )rz   r;   r<   rL   rX   )	r   r   r?   chunkr@   Z	chunk_idxZchunk_numberr[   r   r   r   r   r     s    



z"LazyReferenceMapper._key_to_recordc                 C   sJ   || j vr@| j| d }dd t|d |d D }|| j |< | j | S )z6The number of chunks along each axis for a given fieldz/.zarrayc                 S   s   g | ]\}}t || qS r   )mathceil)r_   rK   r`   r   r   r   r}     s   z8LazyReferenceMapper._get_chunk_sizes.<locals>.<listcomp>shapechunks)r@   r5   rD   )r   r?   ZzarrayZ
size_ratior   r   r   r;     s    

z$LazyReferenceMapper._get_chunk_sizesc                 C   s\   |  ||}tt| }t|dkr6dd |D S t|dkrJ|d S dd |D S dS )z8The references for a given parquet file of a given fieldr   c                 s   s   | ]}t |V  qd S r   r    r_   tr   r   r   r   !  rd   z7LazyReferenceMapper._generate_record.<locals>.<genexpr>rF   r   c                 s   s.   | ]&}|d  st |dd  n|d  V  qdS )r   Nr   r   r   r   r   r   '  rd   N)rk   iterrD   r!   r<   )r   r?   r[   rj   itr   r   r   _generate_record  s    z$LazyReferenceMapper._generate_recordc                 c   sP   d}|  |D ]}||9 }qt|| j }t|D ]}| ||E dH  q4dS )zJLoad all the references within a field by iterating over the parquet filesrF   N)r;   r   r   rX   ranger   )r   r?   Znrecchr[   r   r   r   r=   )  s    
z)LazyReferenceMapper._generate_all_recordsc                 C   s   t | S r   )r2   r   r   r   r   r!   2  s    zLazyReferenceMapper.valuesc                 C   s   t | S r   )rC   r   r   r   r   items5  s    zLazyReferenceMapper.itemsc                 C   s   t | S r   )idr   r   r   r   __hash__8  s    zLazyReferenceMapper.__hash__   c                 C   s
   |  |S r   )r   )r   r   r   r   r   __getitem__;  s    zLazyReferenceMapper.__getitem__c           	      C   s   d|v rf|  |sf|d\}}| |\}}}| j||fi }|||< t|| jkr| || n,|| j|< t	t
|tr| n|| j|< d S NrU   )r   rz   r   r9   r,   r<   rX   writer6   rq   r%   bytesdecoder5   )	r   r   valuer?   r   r[   rJ   r   subdictr   r   r   __setitem__?  s    
zLazyReferenceMapper.__setitem__c                 C   s   |  dpd| v S )N.zz/.zr   r   r   r   r   r   N  s    zLazyReferenceMapper._is_metac                 C   s   || j v r| j |= n|| jv r(| j|= npd|v r| |s|d\}}| |\}}}| j ||fi }d ||< t|| jkr| || n
d | j |< d S r   )	r9   r5   r   rz   r   r,   r<   rX   r   )r   r   r?   r   r[   r   r   r   r   r   __delitem__R  s    



zLazyReferenceMapper.__delitem__c              
   C   s  dd l }dd l}dd l}| j||f }|p.| j d| d| d}	|j| j|jdd}
|j| jdd}|j| jdd}|j| j|jdd}d}d}|	 D ]d\}}t
|tr|d7 }|d |
|< t|dkr|d ||< |d	 ||< q|d7 }|j|||< q|jt|
|||d
dd}|j |j p0d | jkrN|d d|d< tddd}ddg}| jj|pr| j d| dd |j|	d|pt| jdd ddd||d |  | j||f d S )Nr   rU   z/refs.z.parqO)Zdtypeint64rF   r   r   F)copyr'   categoryr   utf8)r   r'   r   Texist_okr\   storage_optionsZzstd)r]   r   compressionindexstatsobject_encoding	has_nulls)Zkerchunk.dfrN   rP   r9   rr   fullrX   nanzerosr   r%   r    r<   rb   Z	_proc_rawZ	DataFramedictr'   countZnuniquers   Zastyperg   ZmkdirsZ
to_parquetgetattrclearpop)r   r?   r[   base_urlr   ZkerchunkrO   rQ   	partitionfnr.   offsetsrI   ZrawsZnrawnpathjdatarb   r   r   r   r   r   r   c  s^    
	""zLazyReferenceMapper.writec                 C   s   t | jD ](}t|tr
|\}}| j||||d q
t | jD ],}|dkr>d|v r>t| j|| j|< q>| j| j	d}t
| | jd< | jd|p| jdg| jd  | j  dS )zOutput any modified or deleted keys

        Parameters
        ----------
        base_url: str
            Location of the output
        )r   r   rV   r   rv   rU   N)r    r9   r%   r&   r   r6   rq   r   r5   rX   r7   r8   rg   rw   ro   rr   rk   cache_clear)r   r   r   thingr?   r[   kru   r   r   r   flush  s&    	
zLazyReferenceMapper.flushc                 C   sd   d}|   D ]6}|dr$|d7 }q| |}| j|}||7 }q|t| j7 }|t| j7 }|S )Nr   r~   rF   )r:   r   r;   rO   productr<   r5   r9   )r   r   r?   r@   Znchunksr   r   r   __len__  s    



zLazyReferenceMapper.__len__c                 c   sR   t | j}|| j |D ]}t|tr|V  q|  D ]}| |E d H  q8d S r   )r   r5   r   r9   r%   r+   r:   r   )r   Zmetasbitr?   r   r   r   rA     s    

zLazyReferenceMapper.__iter__c                 C   s*   z|  | W dS  ty$   Y dS 0 d S )NTF)r   r   )r   itemr   r   r   __contains__  s
    
z LazyReferenceMapper.__contains__c                 c   sd   |  |}t|dkr$|d V  dS tjdd |D  }|D ]"}|d ddd	 |D  V  q<dS )
z|List key names in given field

        Produces strings like "field/x.y" appropriate from the chunking of the array
        r   r3   Nc                 s   s   | ]}t |V  qd S r   )r   )r_   rJ   r   r   r   r     rd   z5LazyReferenceMapper._keys_in_field.<locals>.<genexpr>rU   r~   c                 S   s   g | ]}t |qS r   )r+   r^   r   r   r   r}     rd   z6LazyReferenceMapper._keys_in_field.<locals>.<listcomp>)r;   r<   	itertoolsr   ro   )r   r?   r@   Zindsindr   r   r   r     s    

z"LazyReferenceMapper._keys_in_field)NNrR   rS   )T)r   T)NN)NN)r   r   r   __doc__propertyrO   rQ   r   staticmethodry   r:   r   r   r   r   r;   r   r=   r!   r   r   r   r   r   r   r   r   r   rA   r   r   r   r   r   r   rM   T   s@   

 
*



<)

	


:
!rM   c                       s  e Zd ZdZdZdC fdd		ZdDd
dZdEddZdFddZdd Z	dd Z
efddZdGddZdHddZdIddZdd ZdJd d!Zd"d# Zd$d% Zd&d' ZdKd)d*ZdLd+d,Zd-d. Zd/d0 Zd1d2 ZdMd3d4ZdN fd5d6	Zd7d8 Zd9d: Zd;d< Zd=d> Zd?d@ Z dAdB Z!  Z"S )OReferenceFileSystema  View byte ranges of some other file as a file system
    Initial version: single file system target, which must support
    async, and must allow start and end args in _cat_file. Later versions
    may allow multiple arbitrary URLs for the targets.
    This FileSystem is read-only. It is designed to be used with async
    targets (for now). This FileSystem only allows whole-file access, no
    ``open``. We do not get original file details from the target FS.
    Configuration is by passing a dict of references at init, or a URL to
    a JSON file containing the same; this dict
    can also contain concrete data for some set of paths.
    Reference dict format:
    {path0: bytes_data, path1: (target_url, offset, size)}
    https://github.com/fsspec/kerchunk/blob/main/README.md
    r   NT    @BrR   c                    s  t  jf i | || _|	| _|
| _i | _i | _i | _|| _|| _	t
|trtf i |p^|p^i d|i}tjj|fi |\}}||rtj|dfi |&}td| t|}W d   n1 s0    Y  | ||	 ntd| t|||d| _n| ||	 t
|trNdd | D | _d| jvrJtd	| jd< dS |durt
|jtrp|jd
 n|j}|| j|< |du r| j D ]X}t|r| }tj|\}}|r|| jvrt|fi |pi }|| j|< q|du rv| j D ]r}t|r| }t
|t r|d
 rtj|d
 \}}|| jvrt|fi |p\i }|| j|<  qvq|r|| jvrt|fi |pi }|| j|< |ptd	| jd< dS )a  
        Parameters
        ----------
        fo : dict or str
            The set of references to use for this instance, with a structure as above.
            If str referencing a JSON file, will use fsspec.open, in conjunction
            with target_options and target_protocol to open and parse JSON at this
            location. If a directory, then assume references are a set of parquet
            files to be loaded lazily.
        target : str
            For any references having target_url as None, this is the default file
            target to use
        ref_storage_args : dict
            If references is a str, use these kwargs for loading the JSON file.
            Deprecated: use target_options instead.
        target_protocol : str
            Used for loading the reference file, if it is a path. If None, protocol
            will be derived from the given path
        target_options : dict
            Extra FS options for loading the reference file ``fo``, if given as a path
        remote_protocol : str
            The protocol of the filesystem on which the references will be evaluated
            (unless fs is provided). If not given, will be derived from the first
            URL that has a protocol in the templates or in the references, in that
            order.
        remote_options : dict
            kwargs to go with remote_protocol
        fs : AbstractFileSystem | dict(str, (AbstractFileSystem | dict))
            Directly provide a file system(s):
                - a single filesystem instance
                - a dict of protocol:filesystem, where each value is either a filesystem
                  instance, or a dict of kwargs that can be used to create in
                  instance for the given protocol

            If this is given, remote_options and remote_protocol are ignored.
        template_overrides : dict
            Swap out any templates in the references file with these - useful for
            testing.
        simple_templates: bool
            Whether templates can be processed with simple replace (True) or if
            jinja  is needed (False, much slower). All reference sets produced by
            ``kerchunk`` are simple in this sense, but the spec allows for complex.
        max_gap, max_block: int
            For merging multiple concurrent requests to the same remote file.
            Neighboring byte ranges will only be merged when their
            inter-range gap is <= ``max_gap``. Default is 64KB. Set to 0
            to only merge when it requires no extra bytes. Pass a negative
            number to disable merging, appropriate for local target files.
            Neighboring byte ranges will only be merged when the size of
            the aggregated range is <= ``max_block``. Default is 256MB.
        cache_size : int
            Maximum size of LRU cache, where cache_size*record_size denotes
            the total number of references that can be loaded in memory at once.
            Only used for lazily loaded references.
        kwargs : passed to parent class
        r0   rW   zRead reference from URL %sNz$Open lazy reference dict from URL %s)rg   rt   c                 S   s>   i | ]6\}}|t |tr6tj|d dd fi |n|qS ):rF   r   )r%   r   rn   r   rz   )r_   r   optsr   r   r   rc   g  s
    z0ReferenceFileSystem.__init__.<locals>.<dictcomp>rT   r   )!r   r   r   template_overridessimple_templates	templatesfssZ	_dircachemax_gap	max_blockr%   r+   r   rn   coreZ	url_to_fsisfiler   loggerinfor6   load_process_referencesrM   r(   r   r   r0   r&   r!   callabler	   r    )r   for   Zref_storage_argsZtarget_protocolZtarget_optionsZremote_protocolZremote_optionsrg   r   r   r   r   rt   rx   ZdicZref_fsZfo2ri   textr)   r0   r   r   r   r   r     sz    I

(









zReferenceFileSystem.__init__c              
   C   st  |  |}td|  z| j| }W n tyB   t|Y n0 t|trV| }t|t	rtd| d |
drt|dd  }|d d fS t|dkrtd| d|  |d }|| }}n|\}}}	td| d	| d
| d|	  ||	 }
|d ur*|dkr || }n|
| }n|}|d urV|dkrL|| }n|
| }n|
}|d u rj| j}|||fS )Nzcat: zReference: z, type bytes   base64:   rF   z, whole file => r   z => z	, offset z, size )_strip_protocolr   debugr(   r   r   r%   r+   r8   r   r   base64	b64decoder<   r   )r   r'   startendpartre   Zstart1Zend1start0r   end0r   r   r   _cat_common  sB    





"








zReferenceFileSystem._cat_commonc              
      s   | j |||d\}}}t|tr,||| S t|\}}	z | j| j|||dI d H  W n0 ty }
 zt|||
W Y d }
~
n
d }
~
0 0 d S N)r  r  )r  r%   r   r	   r   	_cat_file	Exceptionr   r   r'   r  r  rx   Zpart_or_urlr  r  r0   r   er   r   r   r    s    
 zReferenceFileSystem._cat_filec              
   K   s   | j |||d\}}}t|tr,||| S t|\}}	z| j| j|||dW S  ty }
 zt|||
W Y d }
~
n
d }
~
0 0 d S r  )r  r%   r   r	   r   cat_filer  r   r  r   r   r   r    s    
zReferenceFileSystem.cat_filec                 K   s   || j |< dS )z2Temporarily add binary data or reference as a fileNr(   )r   r'   r   r   r   r   r   	pipe_file  s    zReferenceFileSystem.pipe_filec                    s`   |  |rtj|ddS | |I d H }t|d}|| W d    n1 sR0    Y  d S NTr   wb)isdirr   makedirsr  r   r   )r   rpathlpathrx   r   ri   r   r   r   	_get_file  s
    
zReferenceFileSystem._get_filec                 K   s   |  |rtj|ddS | j|fi |}|t| t|rL|| n4t|d}|| W d    n1 sv0    Y  |	t| d S r  )
r  r   r  r  Zset_sizer<   r
   r   r   Zabsolute_update)r   r  r   callbackrx   r   ri   r   r   r   get_file  s    
(zReferenceFileSystem.get_fileFc           
         s   |r  d  j||d}tjddd}t||}|rR  fdd|D }n
 |}t||D ] \}}	||v rf||	||  qfd S )Nr   )	recursiverT   T)Z
auto_mkdirc                    s   g | ]}  |s|qS r   )r  )r_   rr   r   r   r}     rd   z+ReferenceFileSystem.get.<locals>.<listcomp>)r   Zexpand_pathrn   r   r   catrD   r  )
r   r  r   r$  rx   rg   targetsr   remotelocalr   r   r   r$     s    


zReferenceFileSystem.getraisec           #      K   s  t |tr|rtt |tr6|s2tdd |D r6tt|| j}i }| D ]\}}| j| }	g g g   }
}}|D ]v}z2| 	|\}}}|

| |
| |
| W qv ty } z&|dkrƂ |dkr|||< W Y d }~qvd }~0 0 qvg }g }g }g }t }t|
|||D ]`\}}}}t |tr4|||< n<|d u r|| |
| |
| |
| |
| qt|
|||D ]J\}}}}|d ur||vr|
| |
| |
| |
| qtt|t|t|d| j| jd\}}}|	|||}t|
|||D ]\}}}}||v r.qt||||D ]\}}}}||kr|d u sf|d u rt |tr||||< n||| ||< nR||kr<||kr<||kr<t |tr|||< n||| || pd  ||< q<qqN|  D ]b\}} t | tr|| jv r|| }!t|| j| }"|!|"_|dkrD|"n|dkr|"||< qt|dkrt |trd|vrt|S |S )	Nc                 s   s   | ]}d |v V  qdS )*Nr   r{   r   r   r   r     rd   z*ReferenceFileSystem.cat.<locals>.<genexpr>r*  ZomitT)sortr   r   rF   r+  )r%   r+   NotImplementedErrorr    anyr1   r(   r   r   r  r-   r   r   rD   r   addr   r   r   Z
cat_rangesr  r   r   	__cause__r<   r#   )#r   r'   r$  Zon_errorrx   Z
proto_dictr/   protor.   rg   urlsZstartsZendsr|   urK   r  errZurls2Zstarts2Zends2Zpaths2Zwhole_filesZ	new_pathsZ
new_startsZnew_endsZ	bytes_outrO   nsnebr   vexZnew_exr   r   r   r&    s     


 











(

$zReferenceFileSystem.catc                 C   sJ   | dd }|d u r | | n&|dkr8| j||d ntd| d S )NversionrF   )r   z Unknown reference spec version: )r$   _process_references0_process_references1r   )r   r(   r   versr   r   r   r  U  s    z'ReferenceFileSystem._process_referencesc                 C   s
   || _ dS )z&Make reference dict for Spec Version 0Nr  )r   r(   r   r   r   r;  `  s    z(ReferenceFileSystem._process_references0c                    s2  j rjrdd l i _|di  td fdd}|di  D ]\}}t|t	r|
drt|dd  j|< |j|< qRjr|d }d	|v r܈j r|d	d
ddjf i j}n||}t|dkr|gn||d |d gj|< qR|j|< qRj|dg  d S )Nr   r   i  c                    s     | jf i jS r   )Templaterenderr   )r3  jinja2r   r   r   _render_jinjaj  s    z?ReferenceFileSystem._process_references1.<locals>._render_jinjarj   zbase64:r  {{{z}}}rF   r   gen)r   r   rA  r(   _process_templatesr$   r   r   r%   r+   r   r  r  replacerf   r<   r   _process_gen)r   r(   r   rB  r   r8  r3  r   r@  r   r<  d  s2    

,z(ReferenceFileSystem._process_references1c                    sd   i | _ | jd ur|| j | D ]:\}}d|v rTdd l |f fdd	| j |< q$|| j |< q$d S )NrC  r   c                    s     | jf i |S r   )r>  r?  )temprx   rA  r   r   r     s   z8ReferenceFileSystem._process_templates.<locals>.<lambda>)r   r   r   r   rA  )r   tmpr   r8  r   rK  r   rG    s    
z&ReferenceFileSystem._process_templatesc                    s&  i }|D ]}dd |d   D   fddtj   D }|D ]}dd l}||d jf i || j}||d jf i || j}d	|v rd
|v rt||d	 jf i || j}	t||d
 jf i || j}
||	|
g||< qDd	|v d
|v A rt	dqD|g||< qDq|S )Nc              
   S   s@   i | ]8\}}|t |tr|nt|d d|d |ddqS )r  r   stopsteprF   )r%   r    r   r$   )r_   r   r8  r   r   r   rc     s
   z4ReferenceFileSystem._process_gen.<locals>.<dictcomp>Z
dimensionsc                 3   s    | ]}t t  |V  qd S r   )r   rD   rE   )r_   r!   Z	dimensionr   r   r     s   z3ReferenceFileSystem._process_gen.<locals>.<genexpr>r   r   re   r   lengthz^Both 'offset' and 'length' are required for a reference generator entry if either is provided.)
r   r   r   r!   rA  r>  r?  r   r   r   )r   Zgensr/   rF  ZproductsprrA  r   re   r   rP  r   rO  r   rI    s4    


  z ReferenceFileSystem._process_genc           	      C   s   dg i| _ | j }|D ]\}}t|ttfr8t|}nt|dkrJd }n
|\}}}d|v rl|ddd nd}|}|r|| j vrg | j |< | j d|v r|ddd ndg 	|ddd | 
|}qt| j | 	|d|d qd S )Nr   rF   rU   r   r   r   rT   )dircacher(   r   r%   r   r+   r<   rsplitr,   r-   _parent)	r   r   r'   r  r   r   r  parZpar0r   r   r   _dircache_from_items  s&    





z(ReferenceFileSystem._dircache_from_itemsrW   c                 K   s   |  |}t|S r   )r  ioBytesIO)r   r'   mode
block_sizeZcache_optionsrx   r   r   r   r   _open  s    
zReferenceFileSystem._openc                 K   s   |  |}t| jtrJz| j||W S  ty8   Y n0 td| d| jsX|   | 	|}|d u rrt||rz|S dd |D S )N'z' is not a known keyc                 S   s   g | ]}|d  qS r   r   r_   or   r   r   r}     rd   z*ReferenceFileSystem.ls.<locals>.<listcomp>)
r	  r%   r(   rM   r   r   r   rR  rV  _ls_from_cache)r   r'   r   rx   r/   r   r   r   r     s    

zReferenceFileSystem.lsc                 K   s   |  |p| |S r   )r  r   r   r'   rx   r   r   r   exists  s    zReferenceFileSystem.existsc                    sH   | j r | j v S t| jtr, | jdv S t fdd| jD S d S )Nr   c                 3   s   | ]}|   d V  qdS )rU   Nr   )r_   r   r   r   r   r     rd   z,ReferenceFileSystem.isdir.<locals>.<genexpr>)rR  r%   r(   rM   r:   r.  r   r'   r   r   r   r    s
    
zReferenceFileSystem.isdirc                 C   s
   || j v S r   r  rc  r   r   r   r     s    zReferenceFileSystem.isfilec                    s   | j ||fi |S r   )r   )r   r'   r   rx   r   r   r   _ls  s    zReferenceFileSystem._lsc                    s~   |r t  j f|||d|S  rH  t fddjD }n
tj}|rvjsd  fdd|D S |S d S )N)maxdepthwithdirsr   c                 3   s   | ]}|  r|V  qd S r   r   r_   r   r   r   r   r     rd   z+ReferenceFileSystem.find.<locals>.<genexpr>c                    s   i | ]}|  |d  qS )r   )r`  rg  r   r   r   rc     rd   z,ReferenceFileSystem.find.<locals>.<dictcomp>)r   findr	  r   r(   rR  rV  )r   r'   re  rf  r   rx   r%  r   r   r   rh    s"    

zReferenceFileSystem.findc                    s   | j  }|d ur^t|ttfr2 dt|dS t|dkrN d|d dS  dd dg}n.|  d} fdd|D }|s dd	dS |d	 d
 d u rt| j   d	 \}}| j| 	| j   d	 |d	 d
< |d	 S )NrT   r   rF   r   Tc                    s   g | ]}|d   kr|qS r]  r   r^  r   r   r   r}     rd   z,ReferenceFileSystem.info.<locals>.<listcomp>r   r   r   )
r(   r$   r%   r+   r   r<   r   r	   r   r   )r   r'   rx   r/   Zout0Zprotr   r   r   r   r    s    "zReferenceFileSystem.infoc                    s
   |  |S r   )r  ra  r   r   r   _info  s    zReferenceFileSystem._infoc                    s   | j |d  | j  d S r   )r(   r   rR  r   ra  r   r   r   _rm_file  s    zReferenceFileSystem._rm_filec                    s   || j |< | j  d S r   )r(   rR  r   )r   r'   r   r   r   r   
_pipe_file!  s    
zReferenceFileSystem._pipe_filec                    sF   t |d}| | j|< W d    n1 s.0    Y  | j  d S )NrW   )r   rp   r(   rR  r   )r   r   r  ri   r   r   r   	_put_file&  s    ,zReferenceFileSystem._put_filec              	   K   s   i }| j  D ]X\}}t|tr^z|d||< W qf tyZ   dt|  ||< Y qf0 q|||< qtj	|dfi |*}|
td|d  W d   n1 s0    Y  dS )z+Write modified references into new locationasciir  r  rF   )r:  rj   N)r(   r   r%   r   r   UnicodeDecodeErrorr  	b64encodern   r   r   r6   r7   r8   )r   re   r   r/   r   r8  ri   r   r   r   	save_json,  s    

zReferenceFileSystem.save_json)NNNNNNNNTr   r   rR   )NN)NN)NN)F)Fr*  )N)N)rW   NN)T)T)NFF)#r   r   r   r   r0   r   r  r  r  r  r!  r   r#  r$   r&  r  r;  r<  rG  rI  rV  r[  r   rb  r  r   rd  rh  r  ri  rj  rk  rl  rp  r   r   r   r   r   r     sV                
*





\

#



r   ),r  collectionsrW  r   loggingr   r   	functoolsr   typingr   Zfsspec.corern   Zujsonr6   ImportErrorZasynr   	callbacksr   r   r   r   r	   utilsr
   r   r   	getLoggerr   RuntimeErrorr   r#   r*   r1   abc
ValuesViewr2   	ItemsViewrC   rL   MutableMappingrM   r   r   r   r   r   <module>   s>   


	   