U
    ?hx                     @   s   d 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	m
Z
 ddlmZ ddlmZmZmZmZ dd	lmZ dd
lmZ eZdd ZG dd deZG dd deZdS )a  

.. note::
    imageio is under construction, some details with regard to the
    Reader and Writer classes may change.

These are the main classes of imageio. They expose an interface for
advanced users and plugin developers. A brief overview:

  * imageio.FormatManager - for keeping track of registered formats.
  * imageio.Format - representation of a file format reader/writer
  * imageio.Format.Reader - object used during the reading of a file.
  * imageio.Format.Writer - object used during saving a file.
  * imageio.Request - used to store the filename and other info.

Plugins need to implement a Format class and register
a format object using ``imageio.formats.add_format()``.

    N)Path   )Arrayasarray)	ImageMode   )known_pluginsknown_extensionsPluginConfigFileExtension)_original_order)imopenc                 C   s   d}t | j tkr&t | j }nN| tkr0nD|  tkrF|  }n.d|   tkrdd|   }ntd|  d|dk	rdd t| D D ]}t| jr|}  qqt|  S )zTOld Plugin resolution logic.

    Remove once we remove the old format manager.
    N.zNo format known by name `z`.c                 S   s   g | ]}|j D ]}|qqS  )priority).0Zfile_extensionxr   r   E/var/www/html/venv/lib/python3.8/site-packages/imageio/core/format.py
<listcomp>H   s    z_get_config.<locals>.<listcomp>)r   suffixlowerr	   r   
IndexError	is_legacy)pluginZextension_nameZplugin_namer   r   r   _get_config4   s$    


r   c                   @   s   e Zd ZdZd%ddZdd Zdd Zed	d
 Zedd Z	edd Z
edd Zedd Zdd Zdd Zdd Zdd Zdd Zdd ZG dd  d eZG d!d" d"eZG d#d$ d$eZdS )&Formatu+  Represents an implementation to read/write a particular file format

    A format instance is responsible for 1) providing information about
    a format; 2) determining whether a certain file can be read/written
    with this format; 3) providing a reader/writer class.

    Generally, imageio will select the right format and use that to
    read/write an image. A format can also be explicitly chosen in all
    read/write functions. Use ``print(format)``, or ``help(format_name)``
    to see its documentation.

    To implement a specific format, one should create a subclass of
    Format and the Format.Reader and Format.Writer classes. See
    :class:`imageio.plugins` for details.

    Parameters
    ----------
    name : str
        A short name of this format. Users can select a format using its name.
    description : str
        A one-line description of the format.
    extensions : str | list | None
        List of filename extensions that this format supports. If a
        string is passed it should be space or comma separated. The
        extensions are used in the documentation and to allow users to
        select a format by file extension. It is not used to determine
        what format to use for reading/saving a file.
    modes : str
        A string containing the modes that this format can handle ('iIvV'),
        “i” for an image, “I” for multiple images, “v” for a volume,
        “V” for multiple volumes.
        This attribute is used in the documentation and to select the
        formats when reading/saving a file.
    Nc                 C   s   |  | _|| _|dkrg }nt|tr:|ddd}t|ttfr^tdd |D | _	nt
d|pld| _t| jtst
d| jD ]}|d	krt
d
qdS )u  Initialize the Plugin.

        Parameters
        ----------
        name : str
            A short name of this format. Users can select a format using its name.
        description : str
            A one-line description of the format.
        extensions : str | list | None
            List of filename extensions that this format supports. If a
            string is passed it should be space or comma separated. The
            extensions are used in the documentation and to allow users to
            select a format by file extension. It is not used to determine
            what format to use for reading/saving a file.
        modes : str
            A string containing the modes that this format can handle ('iIvV'),
            “i” for an image, “I” for multiple images, “v” for a volume,
            “V” for multiple volumes.
            This attribute is used in the documentation and to select the
            formats when reading/saving a file.
        N, c                 S   s"   g | ]}|rd | d   qS )r   )stripr   )r   er   r   r   r      s      z#Format.__init__.<locals>.<listcomp>z#Invalid value for extensions given. zInvalid value for modes given.ziIvV?zInvalid value for mode given.)upper_name_description
isinstancestrreplacesplittuplelist_extensions
ValueError_modes)selfnamedescription
extensionsmodesmr   r   r   __init__x   s"    



zFormat.__init__c                 C   s   d| j | jf S )Nz<Format %s - %s>)r.   r/   r-   r   r   r   __repr__   s    zFormat.__repr__c                 C   s   | j S N)docr4   r   r   r   __str__   s    zFormat.__str__c                 C   s   d| j | j| j f S )zCThe documentation for this format (name + description + docstring).z%s - %s

    %s
)r.   r/   __doc__r   r4   r   r   r   r7      s
    z
Format.docc                 C   s   | j S )zThe name of this format.)r"   r4   r   r   r   r.      s    zFormat.namec                 C   s   | j S )z#A short description of this format.)r#   r4   r   r   r   r/      s    zFormat.descriptionc                 C   s   | j S )zpA list of file extensions supported by this plugin.
        These are all lowercase with a leading dot.
        )r*   r4   r   r   r   r0      s    zFormat.extensionsc                 C   s   | j S )z:A string specifying the modes that this format can handle.)r,   r4   r   r   r   r1      s    zFormat.modesc                 C   sN   |j d dkr|j d nd}|| jkrBtd| j d|j j d| | |S )zget_reader(request)

        Return a reader object that can be used to read data and info
        from the given file. Users are encouraged to use
        imageio.get_reader() instead.
        r   iIvVr    Format z cannot read in  mode)moder1   RuntimeErrorr.   
image_modeReaderr-   requestZselect_moder   r   r   
get_reader   s    
zFormat.get_readerc                 C   sN   |j d dkr|j d nd}|| jkrBtd| j d|j j d| | |S )zget_writer(request)

        Return a writer object that can be used to write data and info
        to the given file. Users are encouraged to use
        imageio.get_writer() instead.
        r   r:   r    r;   z cannot write in r<   )r=   r1   r>   r.   r?   WriterrA   r   r   r   
get_writer   s    
zFormat.get_writerc                 C   s
   |  |S )zacan_read(request)

        Get whether this format can read data from the specified uri.
        )	_can_readr-   rB   r   r   r   can_read   s    zFormat.can_readc                 C   s
   |  |S )zacan_write(request)

        Get whether this format can write data to the speciefed uri.
        )
_can_writerG   r   r   r   	can_write   s    zFormat.can_writec                 C   s   dS )aN  Check if Plugin can read from ImageResource.

        This method is called when the format manager is searching for a format
        to read a certain image. Return True if this format can do it.

        The format manager is aware of the extensions and the modes that each
        format can handle. It will first ask all formats that *seem* to be able
        to read it whether they can. If none can, it will ask the remaining
        formats if they can: the extension might be missing, and this allows
        formats to provide functionality for certain extensions, while giving
        preference to other plugins.

        If a format says it can, it should live up to it. The format would
        ideally check the request.firstbytes and look for a header of some kind.

        Parameters
        ----------
        request : Request
            A request that can be used to access the ImageResource and obtain
            metadata about it.

        Returns
        -------
        can_read : bool
            True if the plugin can read from the ImageResource, False otherwise.

        Nr   rG   r   r   r   rF      s    zFormat._can_readc                 C   s   dS )al  Check if Plugin can write to ImageResource.

        Parameters
        ----------
        request : Request
            A request that can be used to access the ImageResource and obtain
            metadata about it.

        Returns
        -------
        can_read : bool
            True if the plugin can write to the ImageResource, False otherwise.

        Nr   rG   r   r   r   rI     s    zFormat._can_writec                   @   sv   e Zd ZdZdd Zedd Zedd Zdd	 Zd
d Z	dd Z
dd Zedd ZdddZdd Zdd ZdS )zFormat._BaseReaderWriterzBase class for the Reader and Writer class to implement common
        functionality. It implements a similar approach for opening/closing
        and context management as Python's file objects.
        c                 C   s0   d| _ d| _|| _|| _| jf | jj  d S )NF)_BaseReaderWriter__closed_BaseReaderWriter_last_index_format_request_openrB   kwargscopy)r-   formatrB   r   r   r   r3   2  s
    z!Format._BaseReaderWriter.__init__c                 C   s   | j S )zgThe :class:`.Format` object corresponding to the current
            read/write operation.
            )rN   r4   r   r   r   rS   :  s    zFormat._BaseReaderWriter.formatc                 C   s   | j S )zhThe :class:`.Request` object corresponding to the
            current read/write operation.
            )rO   r4   r   r   r   rB   A  s    z Format._BaseReaderWriter.requestc                 C   s   |    | S r6   )_checkClosedr4   r   r   r   	__enter__H  s    z"Format._BaseReaderWriter.__enter__c                 C   s   |d kr|    d S r6   )close)r-   typevalue	tracebackr   r   r   __exit__L  s    z!Format._BaseReaderWriter.__exit__c                 C   s&   z|    W n tk
r    Y nX d S r6   )rV   	Exceptionr4   r   r   r   __del__Q  s    z Format._BaseReaderWriter.__del__c                 C   s&   | j r
dS d| _ |   | j  dS )znFlush and close the reader/writer.
            This method has no effect if it is already closed.
            NT)rL   _closerB   finishr4   r   r   r   rV   W  s
    zFormat._BaseReaderWriter.closec                 C   s   | j S )z$Whether the reader/writer is closed.)rL   r4   r   r   r   closedb  s    zFormat._BaseReaderWriter.closedNc                 C   s&   | j r"| jj}|pd| }t|dS )z8Internal: raise an ValueError if reader/writer is closedzI/O operation on closed %s.N)r_   	__class____name__r>   )r-   msgwhatr   r   r   rT   g  s    z%Format._BaseReaderWriter._checkClosedc                 K   s
   t  dS )aA  _open(**kwargs)

            Plugins should probably implement this.

            It is called when reader/writer is created. Here the
            plugin can do its initialization. The given keyword arguments
            are those that were given by the user at imageio.read() or
            imageio.write().
            NNotImplementedErrorr-   rQ   r   r   r   rP   p  s    
zFormat._BaseReaderWriter._openc                 C   s
   t  dS )z_close()

            Plugins should probably implement this.

            It is called when the reader/writer is closed. Here the plugin
            can do a cleanup, flush, etc.

            Nrd   r4   r   r   r   r]   |  s    	zFormat._BaseReaderWriter._close)N)ra   
__module____qualname__r9   r3   propertyrS   rB   rU   rZ   r\   rV   r_   rT   rP   r]   r   r   r   r   _BaseReaderWriter,  s   



	rj   c                   @   sj   e Zd ZdZdd Zdd Zdd Zdd	 ZdddZdd Z	dd Z
dd Zdd Zdd Zdd Zd
S )zFormat.Readerah  
        The purpose of a reader object is to read data from an image
        resource, and should be obtained by calling :func:`.get_reader`.

        A reader can be used as an iterator to read multiple images,
        and (if the format permits) only reads data from the file when
        new data is requested (i.e. streaming). A reader can also be
        used as a context manager so that it is automatically closed.

        Plugins implement Reader's for different formats. Though rare,
        plugins may provide additional functionality (beyond what is
        provided by the base reader class).
        c                 C   s   |   S )a  get_length()

            Get the number of images in the file. (Note: you can also
            use ``len(reader_object)``.)

            The result can be:
                * 0 for files that only have meta data
                * 1 for singleton images (e.g. in PNG, JPEG, etc.)
                * N for image series
                * inf for streams (series of unknown length)
            )_get_lengthr4   r   r   r   
get_length  s    zFormat.Reader.get_lengthc                 K   sL   |    || _z| j|f|\}}W n tk
r@   t|Y nX t||S )aw  get_data(index, **kwargs)

            Read image data from the file, using the image index. The
            returned image has a 'meta' attribute with the meta data.
            Raises IndexError if the index is out of range.

            Some formats may support additional keyword arguments. These are
            listed in the documentation of those formats.
            )rT   rM   	_get_dataStopIterationr   r   )r-   indexrQ   immetar   r   r   get_data  s    
zFormat.Reader.get_datac                 K   s   | j | jd f|S )zget_next_data(**kwargs)

            Read the next image from the series.

            Some formats may support additional keyword arguments. These are
            listed in the documentation of those formats.
            r   )rr   rM   rf   r   r   r   get_next_data  s    zFormat.Reader.get_next_datac                 K   s*   |    |  }tt|d d|| _dS )zset_image_index(index)

            Set the internal pointer such that the next call to
            get_next_data() returns the image specified by the index
            r   rK   N)rT   rl   minmaxrM   )r-   ro   rQ   nr   r   r   set_image_index  s    zFormat.Reader.set_image_indexNc                 C   s0   |    | |}t|ts,td|jj |S )aV  get_meta_data(index=None)

            Read meta data from the file. using the image index. If the
            index is omitted or None, return the file's (global) meta data.

            Note that ``get_data`` also provides the meta data for the returned
            image as an attribute of that image.

            The meta data is a dict, which shape depends on the format.
            E.g. for JPEG, the dict maps group names to subdicts and each
            group is a dict with name-value pairs. The groups represent
            the different metadata formats (EXIF, XMP, etc.).
            z Meta data must be a dict, not %r)rT   _get_meta_datar$   dictr+   r`   ra   )r-   ro   rq   r   r   r   get_meta_data  s    


zFormat.Reader.get_meta_datac                 c   s   |    |  }d}||k rz| |\}}W n< tk
rD   Y dS  tk
rj   |tdkrdY dS  Y nX t||V  |d7 }qdS )ziter_data()

            Iterate over all images in the series. (Note: you can also
            iterate over the reader object.)

            r   Ninfr   )rT   rl   rm   rn   r   floatr   )r-   rv   irp   rq   r   r   r   	iter_data  s    zFormat.Reader.iter_datac                 C   s   |   S r6   )r~   r4   r   r   r   __iter__  s    zFormat.Reader.__iter__c                 C   s   |   }|tdkrtj}|S )Nr{   )rl   r|   sysmaxsize)r-   rv   r   r   r   __len__  s    zFormat.Reader.__len__c                 C   s
   t  dS )z_get_length()

            Plugins must implement this.

            The returned scalar specifies the number of images in the series.
            See Reader.get_length for more information.
            Nrd   r4   r   r   r   rk     s    zFormat.Reader._get_lengthc                 C   s
   t  dS )z_get_data()

            Plugins must implement this, but may raise an IndexError in
            case the plugin does not support random access.

            It should return the image and meta data: (ndarray, dict).
            Nrd   r-   ro   r   r   r   rm     s    zFormat.Reader._get_datac                 C   s
   t  dS )z_get_meta_data(index)

            Plugins must implement this.

            It should return the meta data as a dict, corresponding to the
            given index, or to the file's (global) meta data if index is
            None.
            Nrd   r   r   r   r   rx     s    	zFormat.Reader._get_meta_data)N)ra   rg   rh   r9   rl   rr   rs   rw   rz   r~   r   r   rk   rm   rx   r   r   r   r   r@     s   




r@   c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )zFormat.Writera2  
        The purpose of a writer object is to write data to an image
        resource, and should be obtained by calling :func:`.get_writer`.

        A writer will (if the format permits) write data to the file
        as soon as new data is provided (i.e. streaming). A writer can
        also be used as a context manager so that it is automatically
        closed.

        Plugins implement Writer's for different formats. Though rare,
        plugins may provide additional functionality (beyond what is
        provided by the base writer class).
        Nc                 C   s~   |    t|tjstdi }t|drBt|jtrB||j |dkrLnt|ts`tdn
|| t	|}| 
||S )zappend_data(im, meta={})

            Append an image (and meta data) to the file. The final meta
            data that is used consists of the meta data on the given
            image (if applicable), updated with the given meta data.
            z)append_data requires ndarray as first argrq   NMeta must be a dict.)rT   r$   npZndarrayr+   hasattrrq   ry   updater   _append_data)r-   rp   rq   Z
total_metar   r   r   append_data5  s    


zFormat.Writer.append_datac                 C   s*   |    t|tstdn
| |S dS )a  set_meta_data(meta)

            Sets the file's (global) meta data. The meta data is a dict which
            shape depends on the format. E.g. for JPEG the dict maps
            group names to subdicts, and each group is a dict with
            name-value pairs. The groups represents the different
            metadata formats (EXIF, XMP, etc.).

            Note that some meta formats may not be supported for
            writing, and individual fields may be ignored without
            warning if they are invalid.
            r   N)rT   r$   ry   r+   _set_meta_datar-   rq   r   r   r   set_meta_dataP  s    

zFormat.Writer.set_meta_datac                 C   s
   t  d S r6   rd   )r-   rp   rq   r   r   r   r   e  s    zFormat.Writer._append_datac                 C   s
   t  d S r6   rd   r   r   r   r   r   i  s    zFormat.Writer._set_meta_data)N)ra   rg   rh   r9   r   r   r   r   r   r   r   r   rD   &  s
   
rD   )NN)ra   rg   rh   r9   r3   r5   r8   ri   r7   r.   r/   r0   r1   rC   rE   rH   rJ   rF   rI   objectrj   r@   rD   r   r   r   r   r   T   s0   #
1





] r   c                   @   sv   e Zd ZdZedd Zdd Zdd Zdd	 Zd
d Z	dd Z
dd ZdddZdd Zdd Zdd Zdd ZdS )FormatManagera  
    The FormatManager is a singleton plugin factory.

    The format manager supports getting a format object using indexing (by
    format name or extension). When used as an iterator, this object
    yields all registered format objects.

    See also :func:`.help`.
    c              
   C   sH   t  }t D ]4}tt  |jr8|jd k	r8|| W 5 Q R X q|S r6   )	r)   r   values
contextlibsuppressImportErrorr   rS   append)r-   Zavailable_formatsconfigr   r   r   _formatsy  s    zFormatManager._formatsc                 C   s   dt | j dS )Nz<imageio.FormatManager with z registered formats>lenr   r4   r   r   r   r5     s    zFormatManager.__repr__c                 C   s   t dd | jD S )Nc                 s   s   | ]}|j V  qd S r6   )rS   r   r   r   r   r   	<genexpr>  s     z)FormatManager.__iter__.<locals>.<genexpr>)iterr   r4   r   r   r   r     s    zFormatManager.__iter__c                 C   s
   t | jS r6   r   r4   r   r   r   r     s    zFormatManager.__len__c                 C   sP   g }| j D ]:}|jd }|jd }|j d| d| d}|| q
d|S )Nr0   r/   z - z []
)r   legacy_argsr.   r   join)r-   ssr   extdescsr   r   r   r8     s    


zFormatManager.__str__c              	   C   s   t jdtdd t|ts"td|dkr2tdt| rfzt|ddd	j	W S  tk
rd   Y nX t
| }z|jW S  tk
r   td
|j d|j dY nX d S )NzjThe usage of `FormatManager` is deprecated and it will be removed in Imageio v3. Use `iio.imopen` instead.r   
stacklevelz;Looking up a format should be done by name or by extension.r    z#No format matches the empty string.rTZlegacy_modezThe `z4` format is not installed. Use `pip install imageio[z]` to install it.)warningswarnDeprecationWarningr$   r%   r+   r   is_filer   rN   r   r!   rS   r   r.   install_name)r-   r.   r   r   r   r   __getitem__  s.    
zFormatManager.__getitem__c                    s"  t jdtdd |D ]4 t ts*tdt fdddD rtdqt|d	k}|r^t	}d
d |D }dd t
 D }|D ]Z}|r|  qt|D ]> dd |jD D ](}| r|j| |jd	| qqqt }t  |D ]  | d}|dk	r|t < qt| dS )ak  sort(name1, name2, name3, ...)

        Sort the formats based on zero or more given names; a format with
        a name that matches one of the given names will take precedence
        over other formats. A match means an equal name, or ending with
        that name (though the former counts higher). Case insensitive.

        Format preference will match the order of the given names: using
        ``sort('TIFF', '-FI', '-PIL')`` would prefer the FreeImage formats
        over the Pillow formats, but prefer TIFF even more. Each time
        this is called, the starting point is the default format order,
        and calling ``sort()`` with no arguments will reset the order.

        Be aware that using the function can affect the behavior of
        other code that makes use of imageio.

        Also see the ``IMAGEIO_FORMAT_ORDER`` environment variable.
        a6  `FormatManager` is deprecated and it will be removed in ImageIO v3. Migrating `FormatManager.sort` depends on your use-case:
	- modify `iio.config.known_plugins` to specify the search order for unrecognized formats.
	- modify `iio.config.known_extensions[<extension>].priority` to control a specific extension.r   r   z)formats.sort() accepts only string names.c                 3   s   | ]}| kV  qd S r6   r   )r   cr.   r   r   r     s     z%FormatManager.sort.<locals>.<genexpr>z.,zHNames given to formats.sort() should not contain dots `.` or commas `,`.r   c                 S   s    g | ]}|d kr|   qS )r    )r   r!   )r   r.   r   r   r   r     s      z&FormatManager.sort.<locals>.<listcomp>c                 S   s   g | ]}|D ]}|qqS r   r   )r   Zext_listr   r   r   r   r     s      c                 S   s   g | ]}|qS r   r   r   r   r   r   r     s     N)r   r   r   r$   r%   	TypeErroranyr+   r   r   r	   r   resetreversedZdefault_priorityendswithr   removeinsertr   rR   clearpopr   )r-   namesZshould_resetZ
sane_namesZflat_extensions	extensionr   Z	old_orderr   r   r   sort  sF    


zFormatManager.sortFc                 C   s   t jdtdd t|ts$tdn$|sH|j|  krHtd|j dt|j	 |j
j|j
jdd|j|jd	|j|jd
d}|t|j< |jD ]6}t||jgdd|j dd}t|t | qdS )zadd_format(format, overwrite=False)

        Register a format, so that imageio can use it. If a format with the
        same name already exists, an error is raised, unless overwrite is True,
        in which case the current format is replaced.
        z`FormatManager` is deprecated and it will be removed in ImageIO v3.To migrate `FormatManager.add_format` add the plugin directly to `iio.config.known_plugins`.r   r   z/add_format needs argument to be a Format objectzA Format named z8 is already registered, use `overwrite=True` to replace.Tunknownr   )r.   r/   r0   r1   )r.   
class_namemodule_namer   r   r   zUnique Formatz7A format inserted at runtime. It is being read by the `z	` plugin.)r   r   r.   r/   N)r   r   r   r$   r   r+   r.   get_format_namesr
   r!   r`   ra   rg   r/   r   r0   r1   r   r   r	   
setdefaultr)   r   )r-   Z
iio_format	overwriter   r   r   r   r   r   
add_format  s@    




zFormatManager.add_formatc                 C   sV   zt ||jjddjW S  tk
r<   tjdtdd Y dS  tk
rP   Y dS X dS )zsearch_read_format(request)

        Search a format that can read a file according to the given request.
        Returns None if no appropriate format was found. (used internally)
        Tr   zrImageIO now uses a v3 plugin when reading this format. Please migrate to the v3 API (preferred) or use imageio.v2.r   r   N	r   r=   Zio_moderN   AttributeErrorr   r   r   r+   rG   r   r   r   search_read_format5  s    z FormatManager.search_read_formatc                 C   sV   zt ||jjddjW S  tk
r<   tjdtdd Y dS  tk
rP   Y dS X dS )zsearch_write_format(request)

        Search a format that can write a file according to the given request.
        Returns None if no appropriate format was found. (used internally)
        Tr   zrImageIO now uses a v3 plugin when writing this format. Please migrate to the v3 API (preferred) or use imageio.v2.r   r   Nr   rG   r   r   r   search_write_formatL  s    z!FormatManager.search_write_formatc                 C   s    t jdtdd dd | jD S )z(Get the names of all registered formats.z`FormatManager` is deprecated and it will be removed in ImageIO v3.To migrate `FormatManager.get_format_names` use `iio.config.known_plugins.keys()` instead.r   r   c                 S   s   g | ]
}|j qS r   r   )r   fr   r   r   r   m  s     z2FormatManager.get_format_names.<locals>.<listcomp>)r   r   r   r   r4   r   r   r   r   c  s    zFormatManager.get_format_namesc                 C   s   t |  dS )z1Show a nicely formatted list of available formatsN)printr4   r   r   r   showo  s    zFormatManager.showN)F)ra   rg   rh   r9   ri   r   r5   r   r   r8   r   r   r   r   r   r   r   r   r   r   r   r   n  s   

	#H
3r   )r9   r   r   r   numpyr   pathlibr   r    r   r   rB   r   r   r   r	   r
   r   Zconfig.pluginsr   r   Z	MODENAMESr   r   r   r   r   r   r   r   <module>   s$        