
    e                        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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mZ ddlZddlmZ ddlmZ dd	lmZmZ dd
lmZmZ ddlmZ ddlmZmZ ddl m!Z!m"Z"m#Z# d"dZ$ G d dej%                  Z& G d dej'                  Z( G d dej'                  Z) G d de(          Z* G d de)          Z+ G d de(          Z, G d de)          Z- G d dej%                  Z.d Z/ G d  d!e.          Z0dS )#a  
Module defining input/output interfaces to HoloViews.

There are two components for input/output:

Exporters: Process (composite) HoloViews objects one at a time. For
           instance, an exporter may render a HoloViews object as a
           svg or perhaps pickle it.

Archives: A collection of HoloViews objects that are first collected
          then processed together. For instance, collecting HoloViews
          objects for a report then generating a PDF or collecting
          HoloViews objects to dump to HDF5.
    N)defaultdict)sha256)BytesIO)
bothmethod   )LabelledData)CollatorElement)	NdMappingUniformNdMapping)Store)LayoutOverlay)group_sanitizerlabel_sanitizerunique_iteratorc                 N    |g d}|D ]\  }}|                      ||          } | S )zH
    String sanitizer to avoid problematic characters in filenames.
    N)):_)/r   )\r   )replace)namereplacementsoldnews       1lib/python3.11/site-packages/holoviews/core/io.py	sanitizerr   '   sB     <<< % %C||C$$K    c                   0    e Zd ZdZed             ZddZdS )	Referencea  
    A Reference allows access to an object to be deferred until it is
    needed in the appropriate context. References are used by
    Collector to capture the state of an object at collection time.

    One particularly important property of references is that they
    should be pickleable. This means that you can pickle Collectors so
    that you can unpickle them in different environments and still
    collect from the required object.

    A Reference only needs to have a resolved_type property and a
    resolve method. The constructor will take some specification of
    where to find the target object (may be the object itself).
    c                     t           )z
        Returns the type of the object resolved by this references. If
        multiple types are possible, the return is a tuple of types.
        NotImplementedErrorselfs    r   resolved_typezReference.resolved_typeB   s
     "!r   Nc                     t           )z
        Return the referenced object. Optionally, a container may be
        passed in from which the object is to be resolved.
        r#   )r&   	containers     r   resolvezReference.resolveK   s
    
 "!r   N)__name__
__module____qualname____doc__propertyr'   r*    r   r   r!   r!   2   sM          " " X"" " " " " "r   r!   c                       e Zd ZdZg dZ ej        d          Z ej        d d          Ze	d             Z
ed	             Zed
             ZddZedd            ZdS )Exportera  
    An Exporter is a parameterized function that accepts a HoloViews
    object and converts it to a new some new format. This mechanism is
    designed to be very general so here are a few examples:

    Pickling:   Native Python, supported by HoloViews.
    Rendering:  Any plotting backend may be used (default uses matplotlib)
    Storage:    Saving to a database (e.g. SQL), HDF5 etc.
    )zimage/svg+xmlz	text/htmlz	text/jsonaz  
      Function that generates the metadata key from the HoloViews
      object being saved. The metadata key is a single
      high-dimensional key of values associated with dimension labels.

      The returned dictionary must have string keys and simple
      literals that may be conveniently used for dictionary-style
      indexing. Returns an empty dictionary by default.docc                 $    dt          |           iS )Nrepr)r7   xs    r   <lambda>zExporter.<lambda>k   s    tAww/? r   av  
      Function that generates additional metadata information from the
      HoloViews object being saved.

      Unlike metadata keys, the information returned may be unsuitable
      for use as a key index and may include entries such as the
      object's repr. Regardless, the info metadata should still only
      contain items that will be quick to load and inspect. defaultr5   c                 X    |\  }}|d         | j         v r|                    d          S |S )z
        Classmethod that applies conditional encoding based on
        mime-type. Given an entry as returned by __call__ return the
        data in the appropriate encoding.
        	mime_typeutf-8)utf8_mime_typesencode)clsentrydatainfos       r   rA   zExporter.encodeu   s7     t 333;;w'''Kr   c                 z    t          j        |          }|                    | j                  s| d| j         S |S )z-Add the file extension if not already present.)osfspathendswithfile_extself_or_clsfilenames     r   	_filenamezExporter._filename   sH     9X&&  !566 	77!5777Or   c                 N    d |D             }|rt          |fi  ||          n|S )zz
        Returns a merged metadata info dictionary from the supplied
        function and additional dictionaries
        c                 H    i | ]}|                                 D ]\  }}||	 S r1   )items).0dkvs       r   
<dictcomp>z,Exporter._merge_metadata.<locals>.<dictcomp>   s3    <<<!!''))<<!A!A<<<<r   )dict)rM   objfndictsmergeds        r   _merge_metadatazExporter._merge_metadata   s?     =<u<<<*,8tF&&bbgg&&&&8r   Nc                      t          d          )a  
        Given a HoloViews object return the raw exported data and
        corresponding metadata as the tuple (data, metadata). The
        metadata should include:

        'file-ext' : The file extension if applicable (else empty string)
        'mime_type': The mime-type of the data.

        The fmt argument may be used with exporters that support multiple
        output formats. If not supplied, the exporter is to pick an
        appropriate format automatically.
        zExporter not implemented.r#   )r&   rY   fmts      r   __call__zExporter.__call__   s     ""=>>>r   c                 0    |i }|i }t          d          )a  
        Similar to the call method except saves exporter data to disk
        into a file with specified basename. For exporters that
        support multiple formats, the fmt argument may also be
        supplied (which typically corresponds to the file-extension).

        The supplied metadata key and info dictionaries will be used
        to update the output of the relevant key and info functions
        which is then saved (if supported).
        Nz%Exporter save method not implemented.r#   )rM   rY   basenamer_   keyrE   kwargss          r   savezExporter.save   s'     <D;C!"IJJJr   r+   )NNN)r,   r-   r.   r/   r@   paramCallablekey_fninfo_fnclassmethodrA   r   rO   r]   r`   re   r1   r   r   r3   r3   T   s          BAAOU^ !; < < <F en%?%? F@ A A AG 
 
 [
   Z 9 9 Z9? ? ? ?  K K K ZK K Kr   r3   c                   r    e Zd ZdZd Zedd            Zed             Zed             Zed             Z	dS )	Importeraw  
    An Importer is a parameterized function that accepts some data in
    some format and returns a HoloViews object. This mechanism is
    designed to be very general so here are a few examples:

    Unpickling: Native Python, supported by HoloViews.
    Servers:    Loading data over a network connection.
    Storage:    Loading from a database (e.g. SQL), HDF5 etc.
    c                      t          d          )z
        Given raw data in the appropriate format return the
        corresponding HoloViews object. Acts as the inverse of
        Exporter when supplied the data portion of an Exporter's
        output.
        zImporter not implemented.r#   r&   rD   s     r   r`   zImporter.__call__   s     ""=>>>r   Nc                      t          d          )z|
        Given some source (e.g. a filename, a network connection etc),
        return the loaded HoloViews object.
        z%Importer load method not implemented.r#   )rM   srcentriess      r   loadzImporter.load   s     ""IJJJr   c                      | j         di |S Nr1   )rr   )rM   rd   s     r   loaderzImporter.loader   s    {))&)))r   c                      t          d          )zL
        Returns the 'info' portion of the metadata (if available).
        z%Importer info method not implemented.r#   rM   rp   s     r   rE   zImporter.info       
 ""IJJJr   c                      t          d          )z:
        Returns the metadata key (if available).
        z%Importer keys method not implemented.r#   rw   s     r   rc   zImporter.key   rx   r   r+   )
r,   r-   r.   r/   r`   r   rr   ru   rE   rc   r1   r   r   rl   rl      s         ? ? ? K K K ZK * * Z* K K ZK K K ZK K Kr   rl   c                       e Zd ZdZ ej        ej        d          Z ej	        ddd          Z
 ej	        dd	
          Zd Zedd            ZdS )
Serializerz9A generic exporter that supports any arbitrary serializera4  
       The serializer function, set to Store.dumps by default. The
       serializer should take an object and output a serialization as
       a string or byte stream.

       Any suitable serializer may be used. For instance, pickle.dumps
       may be used although this will not save customized options.r;   zapplication/python-pickleTzE
       The mime-type associated with the serializer (if applicable).)
allow_Noner5   pklz`
       The file extension associated with the corresponding file
       format (if applicable).r4   c                 N    |                      |          }|| j        | j        dfS )Nfile-extr>   )
serializerrK   r>   )r&   rY   rd   rD   s       r   r`   zSerializer.__call__   s*    s##$-T^LLLLr   Nc                    |i }|i } | |fi |\  }}|                      || j        |          }|                      || j        ||          } | ||dfi |\  }}	|                     |          }t	          |d          5 }
|
                    |           |
                    |           d d d            d S # 1 swxY w Y   d S )NrE   rc   ab)r]   rh   ri   rO   openwrite)rM   rY   rN   rE   rc   rd   rD   	base_infometadatar   fs              r   re   zSerializer.save  s/   ;C<D%+c44V44i))#{/A3GG**30CT9UU!k$c":":EEfEE!((22(D!! 	QGGHGGDMMM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   +B::B>B>NN)r,   r-   r.   r/   rf   rg   r   dumpsr   Stringr>   rK   r`   r   re   r1   r   r   r{   r{      s        ??u~ek 8F G G GJ el64 NH I I II u|E (" # # #H
M M M    Z  r   r{   c                       e Zd ZdZ ej        ej        d          Zd Z	e
d             Ze
d             Ze
d             ZdS )	Deserializerz=A generic importer that supports any arbitrary de-serializer.a  
       The deserializer function, set to Store.load by default. The
       deserializer should take a file-like object that can be read
       from until the first object has been deserialized. If the file
       has not been exhausted, the deserializer should be able to
       continue parsing and loading objects.

       Any suitable deserializer may be used. For instance,
       pickle.load may be used although this will not load customized
       options.r;   c                 F    |                      t          |                    S r+   )deserializerr   rn   s     r   r`   zDeserializer.__call__!  s      ///r   c                     t          |d          5 }|                     |          }	 |                     |          }n# t          $ r Y nw xY wd d d            n# 1 swxY w Y   |S )Nrb)r   r   	Exception)rM   rN   r   rD   s       r   rr   zDeserializer.load$  s    (D!! 	Q++A..D"//22   		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 s1   A>A
AA
AAA!Ac                     t          |d          5 }|                     |          }d d d            n# 1 swxY w Y   t          |t                    r|ni }|                    di           S )Nr   rc   r   r   
isinstancerX   getrM   rN   r   r   s       r   rc   zDeserializer.key.  s    (D!! 	3Q"//22H	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3)(D99A88r||E2&&&   377c                     t          |d          5 }|                     |          }d d d            n# 1 swxY w Y   t          |t                    r|ni }|                    di           S )Nr   rE   r   r   s       r   rE   zDeserializer.info5  s    (D!! 	3Q"//22H	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3)(D99A88r||FB'''r   N)r,   r-   r.   r/   rf   rg   r   rr   r   r`   r   rc   rE   r1   r   r   r   r     s        CC
 	9 	 	 	L0 0 0   Z ' ' Z' ( ( Z( ( (r   r   c                       e Zd ZdZ ej        dd          Z ej        dd          ZdZ	dZ
dd
Zedd            Zd	S )Picklera  
    The recommended pickler for serializing HoloViews object to a .hvz
    file (a simple zip archive of pickle files). In addition to the
    functionality offered by Store.dump and Store.load, this file
    format offers three additional features:

    1. Optional (zip) compression.
    2. Ability to save and load components of a Layout independently.
    3. Support for metadata per saved component.

    The output file with the .hvz file extension is simply a zip
    archive containing pickled HoloViews objects.
       z
        The pickling protocol where 0 is ASCII, 1 supports old Python
        versions and 2 is efficient for new style classes.r;   Tz.
        Whether compression is enabled or notzapplication/ziphvzNc                     |i }|i }t                      } | j        ||f||d| |                    d           |                                d| j        dfS )N)rc   rE   r   r   r   )r   re   seekreadr>   )r&   rY   rc   rE   rd   buffs         r   r`   zPickler.__call__X  sn    <D;Cyy	#t:4::6:::		!yy{{DNKKKKr   c           	      4   |i }|i }d| j         d}|                     || j        |          }|                     || j        ||          }| j        rt
          j        nt
          j        }t          |t          t          j        f          r|                     |          n|}t          j        |d|          5 }t          |t                    rt          |t                    skd |j                                        D             }	t%          |j                                                  }
t)          |	          dk    r|	n|	d         dz   g}	n@d	                    t-          |j        d
          t1          |j        d
                    g}	|g}
t5          |
|	          D ]4\  }}|                    |t9          j        || j                             5|                    dt?          j        ||d                     d d d            d S # 1 swxY w Y   d S )Nr   r   w)compressionc                 8    g | ]}d                      |          S rG   )join)rS   rU   s     r   
<listcomp>z Pickler.save.<locals>.<listcomp>q  s"    @@@1388A;;@@@r   r   r   (L)z{}.{}F)protocolr   r   ) r>   r]   rh   ri   compresszipfile
ZIP_STOREDZIP_DEFLATEDr   strrH   PathLikerO   ZipFiler   r   rD   keyslistvalueslenformatr   groupr   labelzipwritestrr   r   r   pickle)rM   rY   rN   rc   rE   rd   r   r   r   rq   
components	componentrC   s                r   re   zPickler.saveb  s_   <D;C!&K4IJJ	))#{/A3GG**30CT9UU,7,@Zg((gFZ6@CQSQ\K]6^6^l;((222dl_XsDDD 	?#v&& #z#w/G/G #@@@@@!#(//"3"344
%(\\A%5%5''GAJu<L;M">>/#)U*K*K&5ci&G&GI I J!U
$'
G$<$< R R 	5

5 ;y;;OPPPR R R RJJz|D$<$<==? ? ?	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	?s   :EHHHr   )r,   r-   r.   r/   rf   Integerr   Booleanr   r>   rK   r`   r   re   r1   r   r   r   r   >  s          u}Q -> ? ? ?H u}T 01 2 2 2H "IHL L L L ? ? ? Z? ? ?r   r   c                       e Zd ZdZddZedd            Zed             Zed             Zed             Z	ed             Z
edd
            ZdS )	Unpicklera  
    The inverse of Pickler used to load the .hvz file format which is
    simply a zip archive of pickle objects.

    Unlike a regular pickle file, info and key metadata as well as
    individual components of a Layout may be loaded without needing to
    load the entire file into memory.

    The components that may be individually loaded may be found using
    the entries method.
    Nc                 N    t          |          }|                     ||          S )N)rq   )r   rr   )r&   rD   rq   r   s       r   r`   zUnpickler.__call__  s#    t}}yywy///r   c           	         g d}}|r|n|                      |          }t          j        |d          5 }|D ]z}||                                vrt	          d| d          |                    t          j        |                    |                               |	                    d          }{	 d d d            n# 1 swxY w Y   t          |          dk    r
|s|d         S t          |          S )NFrEntry z not availabler   r   r   )rq   r   r   namelistr   appendr   loadsr   rJ   r   r   )rM   rN   rq   r   single_layoutr   rC   s          r   rr   zUnpickler.load  s7   $&M
$G''+*=*=h*G*G_Xs++ 	6q  6 6

,,#$BU$B$B$BCCC!!%+affUmm"<"<=== %u 5 5	6	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 z??aa= *%%%s   A>B>>CCc                 6   t          j        |d          5 }d|                                vrt          d          t	          j        |                    d                    }||vrt          d| d          ||         cd d d            S # 1 swxY w Y   d S )Nr   r   zNo metadata availabler   z is missing from the metadata)r   r   r   r   r   r   r   KeyError)rM   rN   r   r   r   s        r   _load_metadatazUnpickler._load_metadata  s    _Xs++ 	"q-- 7888|AFF:$6$677H8##KKKKLLLD>	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	"s   A+BBBc                 .    |                      |d          S )Nrc   r   rL   s     r   rc   zUnpickler.key  s    ))(E:::r   c                 .    |                      |d          S )NrE   r   rL   s     r   rE   zUnpickler.info  s    ))(F;;;r   c                     t          j        |d          5 }d |                                D             cd d d            S # 1 swxY w Y   d S )Nr   c                     g | ]
}|d k    |S )r   r1   rS   els     r   r   z%Unpickler.entries.<locals>.<listcomp>  s"    BBB2z1A1AB1A1A1Ar   )r   r   r   )rM   rN   r   s      r   rq   zUnpickler.entries  s    _Xs++ 	CqBBBBB	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	Cs   AAATc                     |g }t          |t          t          f           }t          |t                    rt          |          }|j        }n|j        }t          |t                    r|j        ng }g }|r,d |                                D             } fd|D             }t          |                    dd                    }	t          |          |	z
  }
|	t          |          z  }t          |t          |
          z   ddg j        ||z   	          t          fd
          }|j                                        D ]\  }}t          |t                    r|d         n|}|r                     |          ni |D ];}||                    |                   }||         k    rt%          d|z            <t          fd|
D                       }|r|n||z   }t          |t                    rt'          |          dk    r|\  }                     |          D ]}||gf||         |<   t+          |                                          S )a  
        Given a list or NdMapping type containing file paths return a
        Layout of Collators, which can be called to load a given set
        of files using the current Importer.

        If supplied as a list each file is expected to disambiguate
        itself with contained metadata. If an NdMapping type is
        supplied additional key dimensions may be supplied as long as
        they do not clash with the file metadata. Any key dimension
        may be dropped by name by supplying a drop argument.
        Nc                 L    g | ]!}t          |t                    r|d          n|"S r   )r   tuple)rS   fnames     r   r   z%Unpickler.collect.<locals>.<listcomp>  s?     3 3 3 #-UE":":EeAhh 3 3 3r   c                 h    h | ].}                     |                                          D ]}|/S r1   )rc   r   )rS   r   kdimrM   s      r   	<setcomp>z$Unpickler.collect.<locals>.<setcomp>  s^     E E E5&1ooe&<&<&A&A&C&CE E"  E E E Er   rc   T)r   rN   rq   )kdimsvdimsvalue_transformdropc                      t          di  S )Nr+   )r	   )rd   s   r   r:   z#Unpickler.collect.<locals>.<lambda>  s    (*B*B6*B*B r   r   z5Metadata supplies inconsistent value for dimension %sc              3   D   K   | ]}                     |d           V  d S r+   )r   )rS   rT   mdatas     r   	<genexpr>z$Unpickler.collect.<locals>.<genexpr>  s1      @@1d++@@@@@@r   r   )r   r   r
   r	   r   r   r   set
dimensionsrX   sortedru   r   rD   rR   r   rc   get_dimension_indexr   r   rq   r   )rM   filesr   r   aslist
file_kdims
drop_extra
mdata_dimsfnames	file_dims
added_dimsoverlap_dimslayout_datarc   r   odimkvalmkeyrC   rd   r   s   `                  @@r   collectzUnpickler.collect  s    <D	7';<<<eW%% 	%UOOEJJJ#-eX#>#>FUZZB

 	E3 3#(<<>>3 3 3FE E E EF E E EJ((d(;;<<	__y0
 3z??2J
););;'3&1&8%,. . . ""B"B"B"BCC***,, 	; 	;JC *5% 8 8CE!HHeE.6>KOOE***BE$ D D544T::;5;&&" $<>B$C D D D ' @@@@Z@@@@@D 0$$cDjC%'' !CJJ!OO $,,U33 ; ;+05'*:E"3'';k''))***r   r+   )NT)r,   r-   r.   r/   r`   r   rr   r   rc   rE   rq   r   r1   r   r   r   r     s        
 
0 0 0 0 & & & Z& " " Z" ; ; Z; < < Z< C C ZC 3+ 3+ 3+ Z3+ 3+ 3+r   r   c                   B    e Zd ZdZ ej        g d          Zd Zd ZdS )Archivead  
    An Archive is a means to collect and store a collection of
    HoloViews objects in any number of different ways. Examples of
    possible archives:

    * Generating tar or zip files (compressed or uncompressed).
    * Collating a report or document (e.g. PDF, HTML, LaTex).
    * Storing a collection of HoloViews objects to a database or HDF5.
    zi
        The exporter functions used to convert HoloViews objects into the
        appropriate format(s).r;   c                     t           )z8
        Add a HoloViews object to the archive.
        r#   )r&   rY   argsrd   s       r   addzArchive.add   
     "!r   c                     t           )z1
        Finalize and close the archive.
        r#   )r&   r   rd   s      r   exportzArchive.export  r   r   N)	r,   r-   r.   r/   rf   List	exportersr   r   r1   r   r   r   r     s]          uz" +" % % %I" " "" " " " "r   r   c                     t          | t                    rJ|                     d           }d t          j        |          D             }d                    |          }nt          |           }|S )a}  
    Simple name_generator designed for HoloViews objects.

    Objects are labeled with {group}-{label} for each nested
    object, based on a depth-first search.  Adjacent objects with
    identical representations yield only a single copy of the
    representation, to avoid long names for the common case of
    a container whose element(s) share the same group and label.
    c                 8    | j         | j        r
d| j        z   ndz   S )N- )r   r   r8   s    r   r:   z'simple_name_generator.<locals>.<lambda>  s"     w17*J#--K r   c                     g | ]
}|d          S r   r1   )rS   ls     r   r   z)simple_name_generator.<locals>.<listcomp>  s    888!888r   ,)r   r   traverse	itertoolsgroupbyr   r7   )rY   labelsobj_strs      r   simple_name_generatorr    sx     #|$$  M M N N88i/77888((6""s))Nr   c                       e Zd ZdZ ej        egd          Z ej        dd          Z	 ej
        ed          Z ej        dd	          Z ej        d
d          Z ej        dd          Z ej        dddgd          Z ej        dd          Z ej        dd          Z ej        dd          Z ej        ddd          Z ej        dd          Zh dZdhZed             Z fd Zd! Zd" Zd9d$Z d:d%Z!d:d&Z"d' Z#d( Z$d) Z%d* Z&d;d+Z'd<d/Z(d0 Z)d=d1Z*d2 Z+d3 Z,d4 Z-d>d6Z.d7 Z/d8 Z0 xZ1S )?FileArchivez|
    A file archive stores files on disk, either unpacked in a
    directory or in an archive format (e.g. a zip file).
    zi
        The exporter functions used to convert HoloViews objects into
        the appropriate format(s).r;   z{name}_{range}z
        A string formatter for the output file based on the
        supplied HoloViews objects dimension names and values.
        Valid fields are the {name}, {range} and {unit} of the
        dimensions.r4   z
        Callable that given an object returns a string suitable for
        inclusion in file and directory names. This is what generates
        the value used in the {obj} field of the filename
        formatter.z{dimensions},{obj}a  
        A string formatter for output filename based on the HoloViews
        object that is being rendered to disk.

        The available fields are the {type}, {group}, {label}, {obj}
        of the holoviews object added to the archive as well as
        {timestamp}, {obj} and {SHA}. The {timestamp} is the export
        timestamp using timestamp_format, {obj} is the object
        representation as returned by object_formatter and {SHA} is
        the SHA of the {obj} value used to compress it into a shorter
        string.z%Y_%m_%d-%H_%M_%Szl
        The timestamp format that will be substituted for the
        {timestamp} field in the export name.rG   zr
        The root directory in which the output directory is
        located. May be an absolute or relative path.r   tarz
        The archive format to use if there are multiple files and pack
        is set to True. Supported formats include 'zip' and 'tar'.)r<   objectsr5   FaX  
        Whether or not to pack to contents into the specified archive
        format. If pack is False, the contents will be output to a
        directory.

        Note that if there is only a single file in the archive, no
        packing will occur and no directory is created. Instead, the
        file is treated as a single-file archive.{timestamp}a  
        The name assigned to the overall export. If an archive file is
        used, this is the correspond filename (e.g. of the exporter zip
        file). Alternatively, if unpack=False, this is the name of the
        output directory. Lastly, for archives of a single file, this
        is the basename of the output file.

        The {timestamp} field is available to include the timestamp at
        the time of export in the chosen timestamp format.z
       Whether the export name should be made unique with a numeric
       suffix. If set to False, any existing export of the same name
       will be removed and replaced.d   )r   Nz
       Maximum length to enforce on generated filenames.  100 is the
       practical maximum for zip and tar file generation, but you may
       wish to use a lower value to avoid long filenames.)r<   boundsr5   TzA
       Flushed the contents of the archive after export.
       >   SHArY   typer   r   	timestampr   r  c                    |g S 	 t          t          j                                        |                    }d t          t	          |           d         D             S # t
          $ r}t          d|          |d}~ww xY w)z3Returns the format fields otherwise raise exceptionNc                     h | ]}||S r+   r1   rS   r   s     r   r   z+FileArchive.parse_fields.<locals>.<setcomp>}  s    EEE!q}A}}}r   r   zCould not parse formatter )r   string	Formatterparser   r   SyntaxError)rB   	formatterr  es       r   parse_fieldszFileArchive.parse_fieldsw  s     Ri	Q)++11)<<==EEEtCK003EEEE 	Q 	Q 	QH9HHIIqP	Qs   AA 
B)A<<Bc                 p     t                      j        di | i | _        |                                  d S rt   )super__init___files_validate_formatters)r&   params	__class__s     r   r$  zFileArchive.__init__  s?    ""6"""!!#####r   c                 8   |sdS |                     d t          g          }|                     d           }g }t          |j        ||z              t	          |          }g }|D ]}|                    |j                  \  }}|                    |          |                    |          }}||k    r|                    |          }	n| d| }	|j        |	|j        d}
|	                     | j
        j        di |
           d                    |          S )Nr  c                     | j         S r+   )r   r8   s    r   r:   z,FileArchive._dim_formatter.<locals>.<lambda>  s    !' r   c                     | j         S r+   )cdimsr8   s    r   r:   z,FileArchive._dim_formatter.<locals>.<lambda>  s    qw r   r  )r   rangeunitr   r1   )r  r   mapextendr   r-  r   pprint_valuer.  r   dimension_formatterr   r   )r&   rY   key_dimsconstant_dimsdimsdim_stringsdimlowerupperr-  
formatterss              r   _dim_formatterzFileArchive._dim_formatter  sD   22<< 1 14D3EFF%6%677DKM1222t$$ 
	N 
	NC99SX..LE5,,U33,,U33 E~~((// **5**"%(U"%(, ,J>t7>LLLLMMMMxx$$$r   c                 `   |                      | j                                      | j                  s7t	          dd                    t          | j                                       |                      | j                                      | j                  s7t	          dd                    t          | j                                       	 t          j
        | j        t          t          j                                         d S # t          $ r}t	          d          |d }~ww xY w)NzValid filename fields are: r  zValid export fields are: zTimestamp format invalid)r!  filename_formatterissubsetffieldsr   r   r   export_nameefieldstimestrftimetimestamp_formatr   	localtime)r&   r   s     r   r&  z FileArchive._validate_formatters  s     !899BB4<PP 	ZZ#((6$,CWCW:X:XZZ[[[""4#344==dlKK 	ZXAUAU8V8VXXYYY	?M$/t~7G7G1H1HIIIII 	? 	? 	?677Q>	?s   8D 
D-D((D-Nc                 4   |i }||gddgk    rt          d          |8|                     |                              dh          st          d          ||gddgk    rt          d          |rd|vrt          d          |                                  g }|B| j        D ]9} ||          }||\  }}	t          |fi |	}|                    ||f           :n|                    ||f           |D ]\  }}|                     ||||           dS )	at  
        If a filename is supplied, it will be used. Otherwise, a
        filename will be generated from the supplied object. Note that
        if the explicit filename uses the {timestamp} field, it will
        be formatted upon export.

        The data to be archived is either supplied explicitly as
        'data' or automatically rendered from the object.
        NzREither filename or a HoloViews object is needed to create an entry in the archive.r  zHOnly the {timestamp} formatter may be used unless an object is supplied.zUEither an object or explicit data must be supplied to create an entry in the archive.r>   zRThe mime-type must be supplied in the info dictionary when supplying data directlyrN   )r   r!  r>  r&  r   rX   r   _add_content)
r&   rY   rN   rD   rE   rd   rq   exporterrenderednew_infos
             r   r   zFileArchive.add  s    <Dc?tTl** H I I I[!2!28!<!<!E!E{m!T!T[fggg4[T4L(( J K K K 	<k-- ; < < < 	!!###< N - -#8C==#X#+ xD--H--d|,,,,- NND$<(((# 	B 	BLT4c4AAAA	B 	Br   c                 X    |                      |||          \  }}||f| j        ||f<   d S )NrG  )_compute_filenamer%  )r&   rY   rD   rE   rN   
unique_keyexts          r   rH  zFileArchive._add_content  s<     223x2PPS*.Z%&&&r   c                    |t                      }|dn|                     |          }|                     |          }|r|nd}|                    |                    d                     t          t          |dd                    }t          t          |dd                    }d||||j        j        t          |          |	                                d	}	| 
                    | j        t          |fi |	          }|                     |          }|                    d
d          }
|                     ||
| j                                        d          \  }}
||
fS )NNoner  r?   r   zno-labelr   zno-groupr  )r  r   r   r   r  rY   r  r   T)force)r   object_formatterr;  updaterA   r   getattrr(  r,   	hexdigest_formatr=  rX   _normalize_namer   _unique_namer%  r   )r&   rY   rE   rN   hashfnr  r   r   r   format_valuesrO  rN  s               r   rM  zFileArchive._compute_filename  sq   XXF #ff1F1Fs1K1KG,,S11J'19rJMM'..11222gc7J??@@Egc7J??@@E*7+5(-(-(+(>(1'(:(:(.(8(8(:(:< <M ||D$;$($?$?$?$?A AH ''11hhz2&& --h.2k.>.>.@.@ . N NSC  r   c                    d                     |                     |d|                    }t          j        t          j                             ||          d          5 }|D ]Q\  \  }}}|                     ||          }	|                    | d|	 t          	                    |                     R	 d d d            d S # 1 swxY w Y   d S )NrG   r   r   r   )
r   rY  r   r   rH   path_truncate_namer   r3   rA   )
r&   r@  r   rootarchnamezipfrb   rO  rC   rN   s
             r   _zip_archivezFileArchive._zip_archive  s!   88D--k5$GGHH_RW\\$993?? 	R4*/ R R&3..x==99x99(//%:P:PQQQQR	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	Rs   ACCCc                 
   d                     |                     |d|                    }t          j        t          j                             ||          d          5 }|D ]\  \  }}}|                     ||          }	t          j        | d|	           }
t          	                    |          }t          |          |
_        |                    |
t          |                     	 d d d            d S # 1 swxY w Y   d S )NrG   r  r   r   )r   rY  tarfileTarFilerH   r]  r^  TarInfor3   rA   r   sizeaddfiler   )r&   r@  r   r_  r`  tarfrb   rO  rC   rN   tarinfofiledatas               r   _tar_archivezFileArchive._tar_archive  s4   88D--k5$GGHH_RW\\$993?? 	94*/ 9 9&3..x==!/[*E*E8*E*EFF#??511"8}}Wgh&7&788889	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9s   BC88C<?C<c                    |d         \  \  }}}| d| }|                      |||          \  }}|                     |                     |          |          }	t          j                            ||	          }
t          |
d          5 }|                    t          	                    |                     d d d            d S # 1 swxY w Y   d S )Nr   r   )rO  wb)
rY  r^  rX  rH   r]  r   r   r   r3   rA   )r&   r@  r   r_  rb   rO  rC   
full_fnameunique_namerN   fpathr   s               r   _single_file_archivez FileArchive._single_file_archive  s   #(8 (C%#00h00
!..z3EEc&&t';';K'H'Hc&RRT8,,% 	,!GGHOOE**+++	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	,s   
.CC	C	c                 6   t           j                            ||                     |d|          d                   }t           j                            |          rt          j        |           t          j        |           |D ]\  \  }}}|                     ||          }t           j                            ||          }	t          |	d          5 }
|

                    t                              |                     d d d            n# 1 swxY w Y   d S )Nr  r   rn  )rH   r]  r   rY  isdirshutilrmtreemakedirsr^  r   r   r3   rA   )r&   r@  r   r_  
output_dirrb   rO  rC   rN   rq  r   s              r   _directory_archivezFileArchive._directory_archive  s2   W\\$(9(9+b$(O(OPQ(RSS
7==$$ 	&M*%%%
J&+ 	0 	0"OXsU**8S99HGLLX66EeT"" 0a..///0 0 0 0 0 0 0 0 0 0 0 0 0 0 0	0 	0s   .DD	D	c                 `   |rdn| j          }|r||fS |dn|}t          |t                    rGd t          j        t          j                            |                    D             }d |D             }|d}}||f|v r |dz   t          |          z   }|dz  }||f|v  t          |          |fS )av  
        Find a unique basename for a new file/key where existing is
        either a list of (basename, ext) pairs or an absolute path to
        a directory.

        By default, uniqueness is enforced depending on the state of
        the unique_name parameter (for export names). If force is
        True, this parameter is ignored and uniqueness is guaranteed.
        FNr  c                 L    g | ]!}t           j                            |          "S r1   )rH   r]  splitextr   s     r   r   z,FileArchive._unique_name.<locals>.<listcomp>'  s>     F F F W%%b)) F F Fr   c                 4    g | ]\  }}||s|n	|d d         fS )r   Nr1   )rS   nexs      r   r   z,FileArchive._unique_name.<locals>.<listcomp>)  s2    KKK'1bb4BBbf5KKKr   r   r  )rp  r   r   rH   listdirr]  abspathr   )	r&   rb   rO  existingrR  skipsplitnew_namecounters	            r   rY  zFileArchive._unique_name  s     9uu(8$8'3'KbbSh$$ 	LF F!z"'//(*C*CDDF F FEKKUKKKH$a'o))|CLL0HqLG o)) (##S))r   r  
   ...c                     || j         n|}|t          |          z
  }t          |          |k    r0|d ||t          |          z   z
           }|| d          }||z   |z   }|r| d| n|}	|	S )NrG   )max_filenamer   )
r&   rb   rO  tailr   maxlenmax_lenstartendrN   s
             r   r^  zFileArchive._truncate_name1  s    &,n""&S/x==7""8gtc$ii'7889ED566"Ct|c)H*-;h&&&&&8r   c                     t          j        dd|          }t          j        dd|          }|                    dd          S )Nz-+r  z^[-,_]r   r   )resubr   )r&   rb   s     r   rX  zFileArchive._normalize_name=  s>    S**H--S)))r   c                     i | t          t          j                              n|}t          j         j        |          }t          |                                j                  } fd j        	                                D             }t          j                             j                  }t                     dk    r j        s                     |||           npt          |          dk    r                     |||           nE j        dk    r                     |||           n" j        dk    r                     |||            j        r	i  _        dS dS )z8
        Export the archive, directory or file.
        N)r  c                 P    g | ]"\  \  }}}                     |          |f|f#S r1   )rW  )rS   baserO  valrE   r&   s       r   r   z&FileArchive.export.<locals>.<listcomp>N  sO     @ @ @'ktS3 <<d++S137 @ @ @r   r   r   r  )r   rB  rE  rC  rD  rX   rW  r@  r%  rR   rH   r]  r  r_  r   packry  rr  archive_formatrb  rl  flush_archive)r&   r  rE   tvaltstampr@  r   r_  s   ` `     r   r   zFileArchive.exportC  s    <D*3*;uT^%%&&&t4d;;DF+++ll4#3T::@ @ @ @ @+/;+<+<+>+>@ @ @wty))t99q===##K====ZZ1__%%k5$???? E))k5$7777 E))k5$777 	DKKK	 	r   c                 b      fd|                                 D             } j        di |S )Nc                 J    i | ]\  }}|                               v || S r1   )r!  )rS   rU   rV   r  r&   s      r   rW   z'FileArchive._format.<locals>.<dictcomp>^  sA     : : :CAaD--i8888 a888r   r1   )rR   r   )r&   r  rE   filtereds   ``  r   rW  zFileArchive._format]  sQ    : : : : :4::<< : : :y++(+++r   c                 *    t          | j                  S )z6The number of files currently specified in the archive)r   r%  r%   s    r   __len__zFileArchive.__len__b  s    4;r   c                 4    | j                                         S r+   )rf   pprintr%   s    r   __repr__zFileArchive.__repr__f  s    z  """r   F   c                     g }t           j                  dk    rt          d j        j                    dS  fd j        D             }t          d |D                       }t          | j                                                  D ]N\  }}|d                             dd          }|	                    |
                    |           d	|            Ot          d
                    |                     dS )z6Print the current (unexported) contents of the archiver   zEmpty Nc                 *    g | ]} j         |d iS )r  )r^  )rS   rU   r  r&   s     r   r   z(FileArchive.contents.<locals>.<listcomp>p  s,    NNNQ%$%q888NNNr   c                 ,    g | ]}t          |          S r1   )r   r  s     r   r   z(FileArchive.contents.<locals>.<listcomp>q  s    ...!s1vv...r   r   r>   zno mime typez : 
)r   r%  printr(  r,   maxr   r   r   r   ljustr   )r&   r  linesr   r  r   rV   r>   s   ``      r   contentszFileArchive.contentsi  s   t{q  44>244555FNNNNN$+NNN..v...//&$+"4"4"6"677 	A 	AFD!n==ILLDJJw//??I??@@@@diir   c                 H    d | j                                         D             S )z:Return a list of filename entries currently in the archivec                 *    g | ]\  }}|r| d | n|S r   r1   )rS   r   rO  s      r   r   z'FileArchive.listing.<locals>.<listcomp>y  s/    MMMw#*1sMMMr   )r%  r   r%   s    r   listingzFileArchive.listingw  s$    MM$+:J:J:L:LMMMMr   c                 8    | j                                          dS )zClears the file archiveN)r%  clearr%   s    r   r  zFileArchive.clear{  s    r   )NNNNr+   )F)r  r  r  Nr   )r  )2r,   r-   r.   r/   rf   r   r   r   r   r2  rg   r  rS  r=  rD  r_  ObjectSelectorr  r   r  r@  rp  r   r  r  r?  rA  rj   r!  r$  r;  r&  r   rH  rM  rb  rl  rr  ry  rY  r^  rX  r   rW  r  r  r  r  r  __classcell__)r(  s   @r   r  r  $  se        
 uz7) 2& ' ' 'I '%,'7 >    &u~.C J    &&: 
A 
 
 
 $u|$7 >1 2 2 2 5< "9 : : :D *U)%% VF G G GN 5= -5 6 6 6D %,} ;> ? ? ?K  %- 4( ) ) )K
 !5=X D= > > >L
 "EM$ 5   M
 RQQGmGQ Q [Q$ $ $ $ $% % %,? ? ?&B &B &B &BR6 6 6 6
! ! ! !6R R R9 9 9, , ,
0 
0 
0* * * *0	 	 	 	* * *   4, , ,
     # # #       N N N      r   r  r+   )1r/   r	  rH   r   r  ru  r  rd  rB  r   collectionsr   hashlibr   ior   rf   param.parameterizedr   	dimensionr   elementr	   r
   	ndmappingr   r   optionsr   overlayr   r   utilr   r   r   r   Parameterizedr!   ParameterizedFunctionr3   rl   r{   r   r   r   r   r  r  r1   r   r   <module>r     s$        				  				      # # # # # #              * * * * * * # # # # # # & & & & & & & & 2 2 2 2 2 2 2 2       $ $ $ $ $ $ $ $ C C C C C C C C C C   " " " " "# " " "D`K `K `K `K `Ku* `K `K `KH/K /K /K /K /Ku* /K /K /Kf$ $ $ $ $ $ $ $P'( '( '( '( '(8 '( '( '(V?? ?? ?? ?? ??h ?? ?? ??Fl+ l+ l+ l+ l+ l+ l+ l+`" " " " "e! " " ":  ,Y Y Y Y Y' Y Y Y Y Yr   