U
    9%e=                     @   sP  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k
r   e
sd dlZY nX 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__ _/var/www/html/Darija-Ai-API/env/lib/python3.8/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kr*tdn| _ jd j dgd}|	  jd< W 5 Q R X 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              	      sP   j j| |d}j|}jj|dd W 5 Q R X  fdd jD }|S )zcached parquet file loader)r?   recordfastparquet)enginec                    s   i | ]}| | j qS r   )r!   .0cdfr   r   
<dictcomp>   s      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   rf   r   joinreadr6   loadsrX   r5   rd   out_root
cat_threshr   rj   )	r   rk   rf   rq   
cache_sizeZcategorical_thresholdrh   metrj   r   r   r   r   e   s     


zLazyReferenceMapper.__init__c                 K   s8   i | d}| d|dgt|  t||f|S )NrY   rX   rU   rV   )pipern   r6   r7   r8   rM   )rX   rk   rf   kwargsrt   r   r   r   create   s    
 zLazyReferenceMapper.createTc                 C   sF   | j dkr*dd | jD }dd |D | _ | j }|rBd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>   s     z/LazyReferenceMapper.listdir.<locals>.<listcomp>c                 S   s   h | ]}|r| d s|qS ).
startswithrz   r   r   r   	<setcomp>   s      
 z.LazyReferenceMapper.listdir.<locals>.<setcomp>c                 S   s   g | ]}t j|qS r   )osr'   basename)r_   r'   r   r   r   r|      s     )rl   r5   )r   r   rl   Zlistingr   r   r   r:      s    
zLazyReferenceMapper.listdir c                    s4   s  }tdgdd jD  dd jD  }|dk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krt
|t
|	 S |}
dd t|	|
D }|| S )zShortcut file listingsrV   c                 S   s   g | ]}d |kr|qS rU   r   r_   namer   r   r   r|      s      z*LazyReferenceMapper.ls.<locals>.<listcomp>c                 S   s   g | ]}d |kr|qS r   r   r   r   r   r   r|      s      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k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>       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|      s      c                    s    g | ]}|   d r|qS r   r~   r   r   r   r   r|      s      c              	      s<   g | ]4}|d t | jk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:   setr5   r9   updatesortedry   r<   FileNotFoundError_keys_in_fieldr    r=   rD   )r   r'   detaildirnamesZothersZdirinfoZfileinfopartsr?   rE   ZrecsZrecinfor   r'   r   r   ls   sN    


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




zLazyReferenceMapper.lsc              
      sf  || j kr| j | S || jkr2t| j|  S d|ksD| |rLt||d\}}| |\}}}| j 	||fi 	|d}|dkrtn|r|S z.| |\}}|dkrW dS | 
|| W n" tttfk
r   t|Y nX dddd	g} fd
d|D }	|	d }
|
dk	r"|
S |	d dkr8td|	dd ddgkrZ|	dd S |	dd S )zfGet the reference for one key

        Returns bytes, one-element list or three-element list.
        rU   FNr   r   r'   offsetr   rawc                    s$   g | ]}| kr |  nd qS r   r   r^   ri   rir   r   r|      s     z5LazyReferenceMapper._load_one_key.<locals>.<listcomp>rG   zThis reference has been deletedrF      )r9   r5   r6   r7   r8   _is_metaKeyErrorry   _key_to_recordr$   rj   
ValueError	TypeErrorr   )r   r   r?   Zsub_keyr[   _maybe
chunk_sizerg   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|     s     z6LazyReferenceMapper._key_to_record.<locals>.<listcomp>r}   )ry   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 k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   	<genexpr>!  s     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   '  s     N)rj   iterrD   r!   r<   )r   r?   r[   ri   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|krf|  |sf|d\}}| |\}}}| j||fi }|||< t|| jkr| || n,|| j|< t	t
|tr| n|| j|< d S NrU   )r   ry   r   r9   r,   r<   rX   writer6   rp   r%   bytesdecoder5   )	r   r   valuer?   r   r[   rJ   r   subdictr   r   r   __setitem__?  s    
zLazyReferenceMapper.__setitem__c                 C   s   |  dpd| kS )N.zz/.zr~   r   r   r   r   r   N  s    zLazyReferenceMapper._is_metac                 C   s   || j kr| j |= n|| jkr(| j|= npd|kr| |s|d\}}| |\}}}| j ||fi }d ||< t|| jkr| || n
d | j |< d S r   )	r9   r5   r   ry   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|
|||d
dd}|j |j p.d | jkrL|d d|d< ddd}ddg}| jj|pn| 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dtypeZint64rF   r   )r'   r   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   rq   fullrX   nanZzerosr   r%   r    r<   rb   Z	_proc_rawZ	DataFramer'   countZnuniquerr   Zastyperf   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|k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   ru   rU   N)r    r9   r%   r&   r   r6   rp   r   r5   rX   r7   r8   rf   rv   rn   rq   rj   cache_clear)r   r   r   thingr?   r[   krt   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k
r&   Y dS X 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     s     z5LazyReferenceMapper._keys_in_field.<locals>.<genexpr>rU   r}   c                 S   s   g | ]}t |qS r   )r+   r^   r   r   r   r|     s     z6LazyReferenceMapper._keys_in_field.<locals>.<listcomp>)r;   r<   	itertoolsr   rn   )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   staticmethodrx   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   sF   

       
*



<)

	


:
!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 | _|| _|| _	t
|trtf |pV|pVi d|i}tjj|f|\}}||rtj|df|}td| t|}W 5 Q R X | ||	 qtd| t|||d| _n| ||	 t
|tr(dd | D | _d| jkr$td	| jd< dS |dk	rZt
|jtrJ|jd
 n|j}|| j|< |dkr| j D ]T}t|r| }tj|\}}|rn|| jkrnt|f|pi }|| j|< qn|dkrH| j D ]n}t|r| }t
|t r|d
 rtj|d
 \}}|| jkrt|f|p0i }|| j|<  qHq|rv|| jkrvt|f|phi }|| 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 %sz$Open lazy reference dict from URL %s)rf   rs   c                 S   s:   i | ]2\}}|t |tr2tj|d dd f|n|qS ):rF   r   )r%   dictrm   r   ry   )r_   r   optsr   r   r   rc   g  s
   z0ReferenceFileSystem.__init__.<locals>.<dictcomp>NrT   r   )!r   r   r   template_overridessimple_templates	templatesfssZ	_dircachemax_gap	max_blockr%   r+   r   rm   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_optionsrf   r   r   r   r   rs   rw   ZdicZref_fsZfo2rh   textr)   r0   r   r   r   r   r     sz    I












zReferenceFileSystem.__init__c              
   C   sv  |  |}td|  z| j| }W n tk
rD   t|Y nX t|trX| }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 k	r,|dkr"|| }n|
| }n|}|d k	rX|dkrN|| }n|
| }n|
}|d krl| 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partrd   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 n. tk
r }
 zt|||
W 5 d }
~
X Y nX d S N)r	  r
  )r  r%   r   r	   r   	_cat_file	Exceptionr   r   r'   r	  r
  rw   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k
r~ }
 zt|||
W 5 d }
~
X Y nX 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              	      sL   |  |rtj|ddS | |I d H }t|d}|| W 5 Q R X d S NTr   wb)isdirr   makedirsr  r   r   )r   rpathlpathrw   r   rh   r   r   r   	_get_file  s
    
zReferenceFileSystem._get_filec              	   K   sz   |  |rtj|ddS | j|f|}|t| t|rH|| n t|d}|| W 5 Q R X |	t| d S r  )
r  r   r  r  Zset_sizer<   r
   r   r   Zabsolute_update)r   r  r  callbackrw   r   rh   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 ] \}}	||krf||	||  qfd S )Nr   )	recursiverT   T)Z
auto_mkdirc                    s   g | ]}  |s|qS r   )r  )r_   rr   r   r   r|     s     
 z+ReferenceFileSystem.get.<locals>.<listcomp>)r   Zexpand_pathrm   r   r   catrD   r  )
r   r  r  r   rw   rf   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 ]t}z2| 	|\}}}|

| |
| |
| W qv tk
r } z|dkrȂ |dkr|||< W 5 d }~X Y qvX qvg }g }g }g }t }t|
|||D ]`\}}}}t |tr2|||< n<|d kr|| |
| |
| |
| |
| qt|
|||D ]J\}}}}|d k	r||kr|
| |
| |
| |
| qtt|t|t|d| j| jd\}}}|	|||}t|
|||D ]\}}}}||kr,qt||||D ]\}}}}||kr|d ksd|d krt |trz|||< n||| ||< nR||kr:||kr:||kr:t |tr|||< n||| || pd  ||< q:qqN|  D ]b\}} t | tr|| jkr|| }!t|| j| }"|!|"_|dkrB|"n|dkr|"||< qt|dkrt |trd|krt|S |S )	Nc                 s   s   | ]}d |kV  qdS )*Nr   rz   r   r   r   r     s     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_errorrw   Z
proto_dictr/   protor.   rf   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 k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   r7  `  s    z(ReferenceFileSystem._process_references0c                    s.  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	|kr؈j r|d	d
ddjf 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 jS r   )Templaterenderr   )r/  jinja2r   r   r   _render_jinjaj  s    z?ReferenceFileSystem._process_references1.<locals>._render_jinjari   zbase64:r  {{{z}}}rF   r   gen)r   r   r=  r(   _process_templatesr$   r   r   r%   r+   r   r  r  replacere   r<   r   _process_gen)r   r(   r   r>  r   r4  r/  r   r<  r   r8  d  s4    

 ,z(ReferenceFileSystem._process_references1c                    sd   i | _ | jd k	r|| j | D ]:\}}d|krTdd l |f fdd	| j |< q$|| j |< q$d S )Nr?  r   c                    s     | jf |S r   )r:  r;  )temprw   r=  r   r   r     s   z8ReferenceFileSystem._process_templates.<locals>.<lambda>)r   r   r   r   r=  )r   tmpr   r4  r   rG  r   rC    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 || j}||d jf || j}d	|krd
|krt||d	 jf || j}	t||d
 jf || j}
||	|
g||< qDd	|kd
|k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   r4  r   r   r   rc     s
   z4ReferenceFileSystem._process_gen.<locals>.<dictcomp>
dimensionsc                 3   s    | ]}t t  |V  qd S r   )r   rD   rE   )r_   r!   	dimensionr   r   r     s   z3ReferenceFileSystem._process_gen.<locals>.<genexpr>r   r   rd   r   lengthz^Both 'offset' and 'length' are required for a reference generator entry if either is provided.)
r   r   r   r!   r=  r:  r;  r   r   r   )r   Zgensr/   rB  Zproductsprr=  r   rd   r   rN  r   rL  r   rE    s4    


z ReferenceFileSystem._process_genc           	      C   s   dg i| _ | j }|D ]\}}t|ttfr8t|}nt|dkrJd }n
|\}}}d|krl|ddd nd}|}|r|| j krg | j |< | j d|k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_optionsrw   r   r   r   r   _open  s    
zReferenceFileSystem._openc                 K   s   |  |}t| jtrLz| j||W S  tk
r:   Y nX td| d| jsZ|   | 	|}|d krtt||r||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|     s     z*ReferenceFileSystem.ls.<locals>.<listcomp>)
r  r%   r(   rM   r   r   r   rP  rT  _ls_from_cache)r   r'   r   rw   r/   r   r   r   r     s    

zReferenceFileSystem.lsc                 K   s   |  |p| |S r   )r  r   r   r'   rw   r   r   r   exists  s    zReferenceFileSystem.existsc                    sH   | j r | j kS t| jtr, | jdk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     s     z,ReferenceFileSystem.isdir.<locals>.<genexpr>)rP  r%   r(   rM   r:   r*  r   r'   r   r   r   r    s
    
zReferenceFileSystem.isdirc                 C   s
   || j kS r   r  ra  r   r   r   r     s    zReferenceFileSystem.isfilec                    s   | j ||f|S r   )r   )r   r'   r   rw   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     s     
 z+ReferenceFileSystem.find.<locals>.<genexpr>c                    s   i | ]}|  |d  qS )r   )r^  re  r   r   r   rc     s      z,ReferenceFileSystem.find.<locals>.<dictcomp>)r   findr  r   r(   rP  rT  )r   r'   rc  rd  r   rw   r!  r   r   r   rf    s&      

zReferenceFileSystem.findc                    s   | j  }|d k	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 k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|     s      z,ReferenceFileSystem.info.<locals>.<listcomp>r   r   r   )
r(   r$   r%   r+   r   r<   r   r	   r   r   )r   r'   rw   r/   Zout0Zprotr   r   r   r   r     s    "zReferenceFileSystem.infoc                    s
   |  |S r   )r   r_  r   r   r   _info  s    zReferenceFileSystem._infoc                    s   | j |d  | j  d S r   )r(   r   rP  r   r_  r   r   r   _rm_file  s
     zReferenceFileSystem._rm_filec                    s   || j |< | j  d S r   )r(   rP  r   )r   r'   r   r   r   r   
_pipe_file!  s    
zReferenceFileSystem._pipe_filec              	      s2   t |d}| | j|< W 5 Q R X | j  d S )NrW   )r   ro   r(   rP  r   )r   r  r  rh   r   r   r   	_put_file&  s    zReferenceFileSystem._put_filec              	   K   s   i }| j  D ]Z\}}t|tr`z|d||< W qh tk
r\   dt|  ||< Y qhX q|||< qtj	|df| }|
td|d  W 5 Q R X dS )z+Write modified references into new locationasciir  r  rF   )r6  ri   N)r(   r   r%   r   r   UnicodeDecodeErrorr  	b64encoderm   r   r   r6   r7   r8   )r   rd   r   r/   r   r4  rh   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   r7  r8  rC  rE  rT  rY  r   r`  r  r   rb  rf  r   rg  rh  ri  rj  rn  r   r   r   r   r   r     sV                
*





\

#



r   ),r  collectionsrU  r   loggingr   r   	functoolsr   typingr   Zfsspec.corerm   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>   


	   